Files
buzz/desktop/scripts/prepare-acp-tools-resource.sh
Matt Toohey 64eae442e3 feat(desktop): bundle the ACP bridge tools on Windows
The windows-x86_64 build was the one supported target left out of the
ACP bundling series: no lock entries, no staged resources, and — since
the series made the claude/codex catalog entries platform-unconditional
(empty install commands, "ships with the Buzz desktop app" hint) — a
Windows user without their own claude-agent-acp hit a dead end that
reinstalling could never fix. Everything upstream already exists (both
bridges publish win32-x64 native packages; the release job already runs
under Git Bash; the desktop's resolution/spawn layer is Windows-aware),
so extend the bundle to Windows. The one genuinely Windows-shaped
problem is the runtime shim: the staged bridges are bash wrappers that
Windows cannot execute — and the resolver only looks for <binary>.exe
anyway. Solve it with a tiny compiled launcher instead of .cmd shims,
which would have rippled a two-candidate list (.exe, .cmd) through the
shared resolution code and left an intermediate cmd.exe in the spawn
chain that kill_on_drop cannot reap through.

- New root-workspace crate buzz-acp-node-launcher: reads the sibling
  <binary>.shim.json ({entrypoint, nodeEngine, requiredNodeMajor})
  written by the staging scripts, resolves node from PATH, enforces the
  lock's Node major with the exact wrapper-shim error message and exit
  codes (127 missing / 1 too old), then runs node on the vendored
  entrypoint, proxying stdio and the exit code. On Windows the child
  joins a Job Object with KILL_ON_JOB_CLOSE (mirroring buzz-dev-mcp's
  KillGroup) so terminating the launcher — as buzz-acp's kill_on_drop
  does — takes the node tree with it; on Unix it execs node like the
  bash shim, existing there so workspace clippy/tests pass everywhere.
  Unsafe is confined to the Win32 FFI, cfg-forbidden elsewhere, per the
  buzz-dev-mcp precedent.

- update-acp-tools-lock.mjs gains x86_64-pc-windows-msvc (npmOs win32,
  npmCpu x64, no libc; native executables claude.exe and
  vendor/x86_64-pc-windows-msvc/bin/codex.exe). The committed lock
  grows 8 -> 10 entries via a partial --target run: the two new
  Windows pins match the other targets' versions exactly (0.58.1 /
  1.1.2, sdk 0.3.205, codex 0.144.1-win32-x64) and the existing 8
  entries are preserved byte-identically.

- The staging scripts branch per target family through the shared
  wrapper lib: Unix targets keep the bash wrapper; Windows targets
  stage the launcher as <binary>.exe next to <binary>.shim.json
  (write_windows_node_launcher). The launcher builds via cargo on
  first use (ACP_NODE_LAUNCHER_EXE overrides; target dir resolved via
  cargo metadata, never ./target), a target with no locked tools still
  stages nothing without needing cargo, and dev-cache shims embed
  bin-dir-relative entrypoints because Git Bash absolute paths
  (/c/Users/...) are unresolvable to a native exe. The freshness path
  re-copies the launcher when the built binary changes (cmp-gated: a
  running agent's open .exe is never rewritten), the prune reduces
  <binary>[.exe][.stamp] and <binary>.shim.json to the lock's bare
  binary name, and harness-clis.json drops the .exe suffix from its
  cli keys so the app's bare-name auth probes ("claude", "codex")
  resolve the vendored CLIs on Windows too.

- release.yml's Windows job needs no extra wiring: the staging step
  added with the previous commit now finds lock entries and builds the
  launcher with the job's already-installed MSVC toolchain. The
  windows-rust CI job gains a cargo test step for the launcher so its
  spawn path gates on a real Windows runner.

Per the plan's risk note, codex-on-Windows maturity is a validate-
before-release concern: the lock's per-tool-per-target shape allows
dropping the codex-acp windows entry if a real session shakes out
badly. win32-arm64 packages exist but there is no arm64 Windows
release job; deferred until one exists. Node.js stays a user
prerequisite, surfaced by the existing node-runtime Doctor section.

Verification (macOS host):
- cargo test -p buzz-acp-node-launcher: 9 passed — manifest parsing,
  version parsing, path resolution, plus end-to-end launcher runs
  (arg/stdio/exit-code proxying via real node, missing-manifest,
  missing-entrypoint, and too-old-Node failures with the wrapper-shim
  message). cargo clippy --all-targets -D warnings and
  cargo fmt --all --check: clean.
- Cross-staged the Windows target end-to-end with
  ACP_NODE_LAUNCHER_EXE standing in for the MSVC launcher: both win32
  npm trees install and validate against the lock (integrity + X_OK on
  the vendored claude.exe/codex.exe, confirming the locked vendor
  paths), bin dir stages <binary>.exe + .exe.stamp + .shim.json with
  relative entrypoints, re-run performs zero installs, stray
  .exe/.shim.json artifacts are pruned, and prepare writes
  harness-clis.json with bare "claude"/"codex" keys mapping to the
  vendored .exe paths.
- Empty-target Windows staging (aarch64-pc-windows-msvc) exits 0 with
  the notice, without cargo on PATH.
- Darwin re-stage after the cross-stage: bash wrappers report 0.58.1 /
  1.1.2, manifests back to darwin shape — Unix staging unregressed.
- biome check on update-acp-tools-lock.mjs: clean.

Windows-runner validation (NSIS install, Doctor states, live claude +
codex sessions, auth probes against the vendored CLIs) needs a real
Windows machine and rides the first release train with these entries.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Matt Toohey <contact@matttoohey.com>
2026-07-15 13:52:14 +10:00

206 lines
8.3 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
app_root="$(cd "$script_dir/.." && pwd)"
lock_file="${ACP_TOOLS_LOCK_FILE:-$app_root/acp-tools.lock.json}"
# shellcheck source=lib/acp-node-wrapper.sh
source "$script_dir/lib/acp-node-wrapper.sh"
usage() {
cat <<'USAGE'
Usage: desktop/scripts/prepare-acp-tools-resource.sh [target-triple]
Stages the locked ACP bridge tools into src-tauri/resources/acp so Tauri can
bundle them as application resources: vendored npm package trees under
resources/acp/node and executable wrappers under resources/acp/bin (bash
shims on Unix targets; the compiled buzz-acp-node-launcher plus
<binary>.shim.json manifests on Windows targets). The optional target triple
defaults to the Rust host target.
Note: resources/acp/bin holds a single target at a time, so staging must stay
tied to the build target.
USAGE
}
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
usage
exit 0
fi
target="${1:-}"
ensure_args=()
if [[ -n "$target" ]]; then
ensure_args+=(--target "$target")
else
target="$(rustc -vV | sed -n 's|host: ||p')"
fi
if [[ -z "$target" ]]; then
echo "Could not determine rust host target." >&2
exit 1
fi
cache_bin_dir="$("$script_dir/ensure-acp-tools.sh" ${ensure_args[@]+"${ensure_args[@]}"} --print-bin-dir)"
cache_root="$(dirname "$(dirname "$cache_bin_dir")")"
# Windows targets stage the compiled launcher shim instead of a bash
# wrapper. Resolved lazily at first use so a target with no locked tools
# stays a no-op stage; ensure-acp-tools.sh above already built the launcher
# for any target that has them, so resolution hits a warm target dir.
launcher_exe=""
resource_root="$app_root/src-tauri/resources/acp"
resource_bin_dir="$resource_root/bin"
resource_node_dir="$resource_root/node"
mkdir -p "$resource_bin_dir"
# Keep .gitkeep but refresh any staged tools from the lock.
find "$resource_bin_dir" -type f ! -name ".gitkeep" -delete
rm -rf "$resource_node_dir"
mkdir -p "$resource_node_dir"
# Manifest for the app's Node.js runtime doctor check, staged next to the
# bin dir so the app can resolve it as the bin dir's parent. Removed up
# front so locks with no npm-sourced tools ship no manifest and the doctor
# check stays silent.
node_runtime_manifest="$resource_root/node-runtime.json"
rm -f "$node_runtime_manifest"
node_runtime_entries=()
# Manifest of the native harness CLIs vendored inside the bundled bridges
# (e.g. `claude` inside the claude-agent-sdk native package, `codex` inside
# @openai/codex). The app resolves auth probes against these pinned binaries
# instead of user installs. Kept OUT of resources/acp/bin on purpose: that
# dir is the highest-priority segment of the agent-spawn PATH, and staging
# `claude`/`codex` there would shadow the user's CLIs inside every session.
harness_cli_manifest="$resource_root/harness-clis.json"
rm -f "$harness_cli_manifest"
harness_cli_entries=()
# Ad-hoc signing failure is a warning, not a hard stop: an unsignable Mach-O
# fragment that never executes should not sink the stage, and release builds
# re-sign everything with the real identity anyway. But it must be visible —
# a silently unsigned binary surfaces much later as Gatekeeper killing a
# subprocess mid-session, which is undiagnosable from build output.
codesign_if_darwin() {
local file="$1"
local output
if [[ "$(uname -s)" == "Darwin" ]] && command -v codesign >/dev/null 2>&1; then
if ! output="$(codesign --force --sign - "$file" 2>&1)"; then
echo "Warning: ad-hoc codesign failed for $file — Gatekeeper may kill it at spawn time:" >&2
echo "$output" >&2
fi
fi
}
while IFS=$'\t' read -r id binary package version node_engine native_package native_executable; do
[[ -n "$id" ]] || continue
install_dir="$cache_root/$target/$id/$version/npm"
entrypoint="$install_dir/node_modules/$package/dist/index.js"
if [[ ! -f "$entrypoint" ]]; then
echo "Locked npm ACP tool missing from cache: $package@$version" >&2
exit 1
fi
resource_package_dir="$resource_node_dir/$id"
mkdir -p "$resource_package_dir"
cp -R "$install_dir/." "$resource_package_dir/"
resource_entrypoint="$resource_package_dir/node_modules/$package/dist/index.js"
if [[ ! -f "$resource_entrypoint" ]]; then
echo "Failed to stage npm ACP tool: $package@$version" >&2
exit 1
fi
if acp_target_is_windows "$target"; then
if [[ -z "$launcher_exe" ]]; then
launcher_exe="$(acp_node_launcher_exe "$target")"
fi
write_windows_node_launcher "$resource_bin_dir/$(acp_staged_binary_name "$binary" "$target")" "$launcher_exe" "../node/$id/node_modules/$package/dist/index.js" "$node_engine"
else
write_node_wrapper "$resource_bin_dir/$binary" "../node/$id/node_modules/$package/dist/index.js" "$node_engine"
fi
node_runtime_entries+=("$id"$'\t'"$binary"$'\t'"$node_engine"$'\t'"$(acp_required_node_major "$node_engine")")
# Record the vendored native harness CLI (relative to the acp resource
# root) for the auth-probe manifest. Fail loudly if the lock names one
# that is not in the staged tree — a silent miss would quietly send auth
# probes back to unpinned user installs.
if [[ -n "$native_package" && -n "$native_executable" ]]; then
cli_relpath="node/$id/node_modules/$native_package/$native_executable"
cli_abspath="$resource_root/$cli_relpath"
if [[ ! -f "$cli_abspath" ]]; then
echo "Locked native harness CLI missing from staged tree: $cli_relpath" >&2
exit 1
fi
chmod +x "$cli_abspath"
# The manifest keys CLIs by the bare probe name the app resolves
# ("claude", "codex"), so the Windows vendored executables drop their
# .exe suffix here.
cli_name="$(basename "$native_executable")"
cli_name="${cli_name%.exe}"
harness_cli_entries+=("$id"$'\t'"$cli_name"$'\t'"$cli_relpath")
fi
# Ad-hoc sign every Mach-O in the staged package, not just the main CLIs:
# the codex native package also vendors executables like rg and zsh, and
# unsigned nested Mach-Os are killed by Gatekeeper. Darwin only, so Linux
# staging skips the file(1) scan.
if [[ "$(uname -s)" == "Darwin" ]]; then
while IFS= read -r -d '' candidate; do
if file -b "$candidate" | grep -q "Mach-O"; then
codesign_if_darwin "$candidate"
fi
done < <(find "$resource_package_dir" -type f -print0)
fi
done < <(node - "$lock_file" "$target" <<'NODE'
const fs = require("node:fs");
const [lockFile, target] = process.argv.slice(2);
const data = JSON.parse(fs.readFileSync(lockFile, "utf8"));
for (const entry of data.tools ?? []) {
if (entry.target !== target || typeof entry.binary !== "string") continue;
if (entry.source !== "npm") {
throw new Error(`Unsupported ACP tool source: ${entry.source}`);
}
console.log([
entry.id,
entry.binary,
entry.package,
entry.version,
entry.nodeEngine ?? ">=22",
entry.nativePackage ?? "",
entry.nativeExecutable ?? "",
].join("\t"));
}
NODE
)
# One manifest entry per npm-sourced bridge, each carrying its own required
# Node major, so bridges with different engine ranges surface distinct
# requirements in the doctor check.
if ((${#node_runtime_entries[@]} > 0)); then
node -e '
const fs = require("node:fs");
const [manifestFile, ...entries] = process.argv.slice(1);
const tools = entries.map((line) => {
const [id, binary, nodeEngine, requiredNodeMajor] = line.split("\t");
return { id, binary, nodeEngine, requiredNodeMajor: Number(requiredNodeMajor) };
});
fs.writeFileSync(manifestFile, `${JSON.stringify({ tools }, null, 2)}\n`);
' "$node_runtime_manifest" ${node_runtime_entries[@]+"${node_runtime_entries[@]}"}
echo "Wrote ACP Node runtime manifest: $node_runtime_manifest"
fi
# One manifest entry per vendored native harness CLI, keyed by the bare CLI
# name the app's auth probes use (`claude`, `codex`). Paths are relative to
# the acp resource root (the bin dir's parent).
if ((${#harness_cli_entries[@]} > 0)); then
node -e '
const fs = require("node:fs");
const [manifestFile, ...entries] = process.argv.slice(1);
const clis = entries.map((line) => {
const [id, cli, path] = line.split("\t");
return { id, cli, path };
});
fs.writeFileSync(manifestFile, `${JSON.stringify({ clis }, null, 2)}\n`);
' "$harness_cli_manifest" ${harness_cli_entries[@]+"${harness_cli_entries[@]}"}
echo "Wrote ACP harness CLI manifest: $harness_cli_manifest"
fi
echo "Staged ACP tools resource: $resource_bin_dir"