#!/bin/bash set -e # ───────────────────────────────────────────────────────────────────── # Agentic Control Plane — Universal Installer # # Source: https://github.com/agentic-control-plane/acp-install # License: MIT # Docs: https://agenticcontrolplane.com # Support: https://github.com/agentic-control-plane/acp-install/issues # # What this script will do on your machine: # # 1. Detect which AI clients are installed # Claude Code · Cursor · OpenAI Codex CLI · OpenClaw · GitHub Copilot # # 1b. SHOW YOU THAT LIST and ask which of them to govern, naming the # files each one touches, before writing anything at all. Enter # takes everything found; `n` writes nothing and exits. # # 1c. Safety floor: force-push, destructive SQL handed to a database # client, curl|sh and recursive deletes outside your project wait # for a person, in every harness above. ON for everyone. With a # terminal you are asked "Keep the safety floor on? (Y/n)"; `n` # turns it off (back on any time from the console's Policies page). # Turning the floor off always needs a typed answer: with no # terminal (curl|bash in CI, an agent re-running this) it stays on, # and ACP_FLOOR=off only changes the question to "Turn the safety # floor off for this workspace? (y/N)", read from the terminal. # --all/--only skip the Y/n question. --local prints the floor line # and asks nothing. Only a typed answer is reported (step 7). # # 2. Write ~/.acp/govern.mjs (the hook dispatcher script — shared across clients) # # 3. Register PreToolUse + PostToolUse hooks in each detected client's config: # ~/.claude/settings.json (Claude Code) # ~/.cursor/hooks.json (Cursor) # ~/.codex/hooks.json (Codex CLI) # ~/.copilot/hooks/acp.json (GitHub Copilot — CLI and VS Code agent mode) # # 4. For Codex specifically: # - Enable [features].codex_hooks = true in ~/.codex/config.toml # - Add [mcp_servers.acp] block so `acp_check` / `acp_status` are # available for explicit questions ("am I allowed to X?") # - Write ~/.codex/AGENTS.md section confirming hooks already # govern every tool call (Bash and non-Bash alike) # # 5. Open your browser to authenticate and provision an ACP workspace # # 6. Save the API key to ~/.acp/credentials (chmod 600) # # 7. Tell ACP whether the install finished: one POST to # $API_BASE/install/report with the outcome, the step that failed, # OS/arch, which clients were chosen, the safety floor answer if you # typed one (step 1c; `floor` is absent otherwise), and the exit code — tied to # your workspace if a key is already on this machine. No paths, no # file contents, no command output. Skipped in --local mode; opt # out with ACP_NO_REPORT=1. # # Usage: # curl -sf https://agenticcontrolplane.com/install.sh | bash # # Skip the question (CI, or you already know what you want): # … | bash -s -- --all # … | bash -s -- --only=claude-code,cursor # With no terminal to ask on, the default is everything detected. # # Undo: # acp-uninstall (removes every file listed below) # # Review the source before running: # curl -sf https://agenticcontrolplane.com/install.sh | less # github.com/agentic-control-plane/acp-install (mirror) # # ───────────────────────────────────────────────────────────────────── # Everything below runs inside ONE brace group, closed by the final `}`. # `curl | bash` feeds this script to bash on stdin, and bash executes it as # it reads it. Any child that reads stdin (pipx, pip, hermes, dsh, npm, muse, # claude...) then consumes the unread REST OF THE SCRIPT, and bash resumes # at a random offset: harness canary 2026-10-08 printed the tail of the Muse # fallback text and died with `syntax error near unexpected token fi` (exit 2) # right after Hermes installed. A compound command is parsed in # full before any of it runs, so by the time a child starts there is nothing # left on stdin to steal. A truncated download is now a syntax error with no # side effects, instead of a half-run install. { API_BASE="${ACP_API_BASE:-https://api.agenticcontrolplane.com}" DASHBOARD_BASE="${ACP_DASHBOARD_BASE:-https://cloud.agenticcontrolplane.com}" SITE_BASE="${ACP_SITE_BASE:-https://agenticcontrolplane.com}" CONFIG_DIR="$HOME/.acp" CREDS_FILE="$CONFIG_DIR/credentials" # ── Local mode: no account, no cloud, nothing leaves your machine ────── # Enable with: curl -sf …/install.sh | bash -s -- --local (or ACP_LOCAL=1) LOCAL_MODE=false for _a in "$@"; do case "$_a" in --local|--no-login) LOCAL_MODE=true ;; esac; done [ "${ACP_LOCAL:-}" = "1" ] && LOCAL_MODE=true # ── Update mode: refresh in place, never mint a key ───────────────────── # What `acp-update` runs. Re-fetches govern.mjs, rewrites every launcher and # hook registration and directive block for harnesses already detected on # this machine, then stops before Step 2 (Authenticate) — no device flow, # no prompt, ~/.acp/credentials is left exactly as it was. UPDATE_MODE=false for _a in "$@"; do case "$_a" in --update) UPDATE_MODE=true ;; esac; done # ── Install outcome beacon (step 7 in the header) ───────────────────── # A failed install used to end on the user's machine with no trace on # ours; the first we heard of one was the user finding another channel # (2026-10-22). The EXIT trap below reports a non-zero exit with the step # it died in, and prints where to get help. Best-effort by construction: # 5s cap, stdin closed, every error swallowed — it can never change the # exit code or block the install. ACP_INSTALLER_REV="2026-11-08" ACP_STEP="start" ACP_OUTCOME="" # set before an intentional non-zero exit that is not a failure _ACP_FAIL_AT="" _ACP_REPORTED=false # Safety floor answer (step 1c). The env value is only a request, read once # here; ACP_FLOOR itself is set to on|off by the floor step only when a # person typed an answer, and stays empty otherwise (no tty, --all/--only, # --update), so the beacon then omits the field: the gateway treats absent # as "no change" and keeps the first answer it recorded. _ACP_FLOOR_ENV="${ACP_FLOOR:-}" ACP_FLOOR="" _acp_report() { # $1 = failed|completed, $2 = exit code; echoes "sent" on success [ "$LOCAL_MODE" = true ] && return 0 [ "${ACP_NO_REPORT:-}" = "1" ] && return 0 command -v curl >/dev/null 2>&1 || return 0 _ACP_REPORTED=true local harnesses key auth="" floor_field="" case "$ACP_FLOOR" in on|off) floor_field=",\"floor\":\"$ACP_FLOOR\"" ;; esac harnesses="$(printf '%s' "${TARGETS:-}" | tr 'A-Z' 'a-z' | sed 's/ + /,/g; s/ /-/g')" key="$(head -n 1 "$CREDS_FILE" 2>/dev/null | tr -d '[:space:]')" case "$key" in gsk_*) auth="Authorization: Bearer $key" ;; esac if curl -s -m 5 -o /dev/null -X POST "$API_BASE/install/report" \ -H "Content-Type: application/json" ${auth:+-H "$auth"} \ -d "{\"outcome\":\"$1\",\"exit_code\":$2,\"step\":\"$ACP_STEP\",\"installer\":\"sh\",\"version\":\"$ACP_INSTALLER_REV\",\"os\":\"$(uname -s | tr 'A-Z' 'a-z')\",\"arch\":\"$(uname -m)\",\"harnesses\":\"$harnesses\",\"env\":\"${CI:+ci}\",\"detail\":\"$_ACP_FAIL_AT\"$floor_field}" \ /dev/null 2>&1; then echo sent fi } # Where set -e fired: line number + the failing command's program name # only (never its arguments — they can carry paths or keys). trap '_ACP_FAIL_AT="line $LINENO: $(printf %s "${BASH_COMMAND%% *}" | tr -cd "A-Za-z0-9_./-" | cut -c1-40)"' ERR _acp_on_exit() { local code=$? [ "$_ACP_REPORTED" = true ] && return 0 [ "$code" -eq 0 ] && return 0 local sent outcome="${ACP_OUTCOME:-failed}" # Ctrl-C / kill is the user's choice, not a broken install. case "$code" in 130|143) outcome="aborted" ;; esac sent="$(_acp_report "$outcome" "$code")" [ "$outcome" = aborted ] && return 0 echo "" >&2 # exit 2 = finished without a key; that banner already said so. [ "$code" -ne 2 ] && [ "$outcome" = failed ] && echo " Install did not finish (step: $ACP_STEP, exit $code)." >&2 [ "$sent" = sent ] && [ "$outcome" = failed ] && echo " A report (step and exit code only, no file contents or paths) was sent to ACP so we can look into it." >&2 echo " Get help: support@agenticcontrolplane.com · https://github.com/agentic-control-plane/acp-install/issues" >&2 echo "" >&2 } trap _acp_on_exit EXIT # ── Terminal colors ─────────────────────────────────────────────────── # tput-guarded: green success / red failure / dim secondary, mirroring # the console's ALLOW/DENY language. Degrades to plain text when stdout # is not a TTY or the terminal has no color support. if [ -t 1 ] && command -v tput > /dev/null 2>&1 && [ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]; then C_GREEN="$(tput setaf 2)" C_RED="$(tput setaf 1)" C_DIM="$(tput dim)" C_RESET="$(tput sgr0)" else C_GREEN="" C_RED="" C_DIM="" C_RESET="" fi # ── Pinned downloads (acp-install#29) ───────────────────────────────── # Everything fetched from GitHub and executed later (the govern.mjs hook, the # harness hooks) is pinned to a commit AND verified against a sha256 embedded # here, before it is moved into place. A compromised branch, a repo takeover, # or a TLS-intercepting proxy can no longer turn `main` into persistent code # execution on every tool call. On any mismatch or fetch failure nothing is # installed from the network: govern.mjs falls back to the bundled copy below, # harness hooks print their manual path (the existing fail-open branch). # # BUMPING A PIN (after a plugin release): set the ref to the release commit, # then curl -fsSL https://raw.githubusercontent.com/agentic-control-plane/// | shasum -a 256 # and paste the digest. Hook fixes now reach machines with the installer # release (or `acp-update`, which re-runs this installer), not on every push. ACP_PIN_GOVERN_REPO="claude-code-acp-plugin" # Plugin 0.30.1 (main 8f354ac5): honours ~/.acp/failmode; includes 0.30.0 headless holds. ACP_PIN_GOVERN_REF="8f354ac5345f9d2f48382491895efe566df97690" ACP_PIN_GOVERN_SHA="a896e8e24f337ac41d6fa1104aa29cb3e8d94ae001b72902ad2c87c78ce1a301" ACP_PIN_PI_REF="e27c427621c6a6c4948e95ca87cfd2c97c27c20d" ACP_PIN_PI_INDEX_SHA="cf8c50c0ed57c596f965be1a3f8a958d9a8b9b0dc9f8e1377e4286ca39e127c1" ACP_PIN_PRIME_REF="4043829b9acdaa2d258ca5237166fcc7910bfd14" ACP_PIN_PRIME_INDEX_SHA="d5090db76007e8ebb6f689ed2c7ee55a272fcdb0081617f0deb9c75d8957660d" ACP_PIN_GROK_REF="4710fc511d07346468758db780fafabf09cedede" ACP_PIN_GROK_HOOK_SHA="60b6fbe278066d6e7cdaaea77a353204756b06dd44816e649336e9888896d28c" ACP_PIN_GROK_JSON_SHA="7e5edd4a8615523548ce660d84fde45ef480ac26bda7fca53ecfd0bfcf011b27" ACP_PIN_AGY_REF="3fe9c68caa12ab5d37fcdc6f48ca6304cc0e04c7" ACP_PIN_AGY_HOOK_SHA="ef0e660b41a287f4da41a8770de757c4791dd089546f7ffbd9e85f9373acac8a" ACP_PIN_AGY_JSON_SHA="41b5e3b56e2d4c5f7ff221213dba96df636c5bfebeb085b42db16a23e30008ae" # sha256 of a file on stdout; empty (and nonzero) when no tool is available. _acp_sha256() { if command -v shasum > /dev/null 2>&1; then shasum -a 256 "$1" 2>/dev/null | cut -d' ' -f1 elif command -v sha256sum > /dev/null 2>&1; then sha256sum "$1" 2>/dev/null | cut -d' ' -f1 elif command -v openssl > /dev/null 2>&1; then openssl dgst -sha256 "$1" 2>/dev/null | sed 's/^.*= *//' elif command -v node > /dev/null 2>&1; then node -e 'const c=require("crypto"),f=require("fs");process.stdout.write(c.createHash("sha256").update(f.readFileSync(process.argv[1])).digest("hex"))' "$1" 2>/dev/null else return 1 fi } # _acp_fetch_pinned URL EXPECTED_SHA256 DEST # Download to a private temp file in DEST's own directory, hash THAT file, and # only then rename it over DEST (same filesystem, so the rename is atomic and # the bytes that were hashed are the bytes that land). Returns 0 only on a # verified install. On failure DEST is untouched and ACP_PIN_FAIL says why: # "download" (offline / 404 / no temp file) or "checksum" (bytes differ). ACP_PIN_FAIL="" _acp_fetch_pinned() { _pf_url="$1"; _pf_want="$2"; _pf_dest="$3" ACP_PIN_FAIL="download" _pf_tmp="$(mktemp "$_pf_dest.XXXXXX" 2>/dev/null)" || return 1 if ! curl -fsSL --max-time 20 "$_pf_url" -o "$_pf_tmp" 2>/dev/null || [ ! -s "$_pf_tmp" ]; then rm -f "$_pf_tmp"; return 1 fi _pf_got="$(_acp_sha256 "$_pf_tmp")" if [ -z "$_pf_got" ] || [ "$_pf_got" != "$_pf_want" ]; then ACP_PIN_FAIL="checksum" rm -f "$_pf_tmp"; return 1 fi chmod 644 "$_pf_tmp" 2>/dev/null || true mv -f "$_pf_tmp" "$_pf_dest" || { rm -f "$_pf_tmp"; ACP_PIN_FAIL="download"; return 1; } ACP_PIN_FAIL="" return 0 } # Active version of the ACP plugin from Claude Code's own registry # (~/.claude/plugins/installed_plugins.json; v1 object or v2 array shape). # Empty when not installed or unreadable. `claude plugin list` prints the # same thing, but its output format is not a contract (acp-install#64). _acp_claude_plugin_active_version() { node -e ' const fs = require("fs"), path = require("path"); const p = path.join(process.argv[1], ".claude", "plugins", "installed_plugins.json"); let j; try { j = JSON.parse(fs.readFileSync(p, "utf8")); } catch { process.exit(0); } const e = j && j.plugins && j.plugins["agentic-control-plane@acp"]; const v = Array.isArray(e) ? (e.find((x) => x && x.scope === "user") || e[0] || {}).version : e && e.version; if (typeof v === "string" && /^\d+\.\d+\.\d+/.test(v)) process.stdout.write(v.trim()); ' "$HOME" 2>/dev/null } # Version the LOCAL marketplace clone's manifest says is current — what # `claude plugin marketplace update acp` just fetched. Empty when the clone # is missing or unreadable. _acp_claude_marketplace_version() { node -e ' const fs = require("fs"), path = require("path"); const pd = path.join(process.argv[1], ".claude", "plugins"); let loc = path.join(pd, "marketplaces", "acp"); try { const k = JSON.parse(fs.readFileSync(path.join(pd, "known_marketplaces.json"), "utf8")); if (k && k.acp && typeof k.acp.installLocation === "string" && k.acp.installLocation.trim()) loc = k.acp.installLocation.trim(); } catch {} try { const m = JSON.parse(fs.readFileSync(path.join(loc, ".claude-plugin", "marketplace.json"), "utf8")); const e = (Array.isArray(m.plugins) ? m.plugins : []).find((x) => x && x.name === "agentic-control-plane"); if (e && typeof e.version === "string" && /^\d+\.\d+\.\d+/.test(e.version)) process.stdout.write(e.version.trim()); } catch {} ' "$HOME" 2>/dev/null } # _acp_semver_gt A B — 0 when A is a strictly newer x.y.z than B. Non-numeric # suffixes ("-fallback", "-rc1") are ignored; anything that is not x.y.z # compares as 0.0.0. Pure shell (macOS `sort` has no stable -V). _acp_semver_gt() { _sg_a="$(printf '%s' "$1" | sed -n 's/^\([0-9][0-9]*\)\.\([0-9][0-9]*\)\.\([0-9][0-9]*\).*/\1 \2 \3/p')" _sg_b="$(printf '%s' "$2" | sed -n 's/^\([0-9][0-9]*\)\.\([0-9][0-9]*\)\.\([0-9][0-9]*\).*/\1 \2 \3/p')" set -- ${_sg_a:-0 0 0} ${_sg_b:-0 0 0} [ "$1" -gt "$4" ] && return 0; [ "$1" -lt "$4" ] && return 1 [ "$2" -gt "$5" ] && return 0; [ "$2" -lt "$5" ] && return 1 [ "$3" -gt "$6" ] } # One-line warning when a pinned download was REJECTED (not merely offline). _acp_pin_warn() { [ "$ACP_PIN_FAIL" = "checksum" ] || return 0 echo " ${C_RED}[ACP] WARNING:${C_RESET} $1 did not match its pinned sha256 — NOT installed. $2" >&2 } # ── Detect available clients ────────────────────────────────────────── ACP_STEP="detect" HAS_CLAUDE=false HAS_CURSOR=false HAS_CODEX=false HAS_OPENCLAW=false HAS_OPENCODE=false INSTALLED="" if [ -d "$HOME/.claude" ] || command -v claude > /dev/null 2>&1; then HAS_CLAUDE=true fi if [ -d "$HOME/.cursor" ] || command -v cursor > /dev/null 2>&1; then HAS_CURSOR=true fi if [ -d "$HOME/.codex" ] || command -v codex > /dev/null 2>&1; then HAS_CODEX=true fi if command -v openclaw > /dev/null 2>&1; then HAS_OPENCLAW=true fi # Every remaining harness is detected HERE, before a single byte is written, # because the consent gate below needs the whole list in front of it. Each # one's install block still lives further down next to its own notes; the # gate reaches them by clearing HAS_* for anything the user didn't pick. # Hermes Agent — governed via its native pip plugin. HAS_HERMES=false if command -v hermes > /dev/null 2>&1; then HAS_HERMES=true fi # DeepSeek Harness — native plugin, per profile. HAS_DSH=false DSH_HOME_DIR="${DSH_HOME:-$HOME/.dsh}" if command -v dsh > /dev/null 2>&1 || [ -d "$DSH_HOME_DIR/profiles" ]; then HAS_DSH=true fi # pi (earendil-works) — a global extension file. The ~/.pi/agent dir is the # reliable signal; `command -v pi` alone can match an unrelated binary named # pi, so require the dir when falling back to PATH. HAS_PI=false PI_EXT_DIR="$HOME/.pi/agent/extensions" if [ -d "$HOME/.pi/agent" ] || { command -v pi > /dev/null 2>&1 && [ -d "$HOME/.pi" ]; }; then HAS_PI=true fi # Prime Agent — same shape as pi; require the dir on the PATH fallback. HAS_PRIME=false PRIME_EXT_DIR="$HOME/.prime/agent/extensions" if [ -d "$HOME/.prime/agent" ] || { command -v prime-agent > /dev/null 2>&1 && [ -d "$HOME/.prime" ]; }; then HAS_PRIME=true fi # Muse Code — plugin bundle; require the config dir on the PATH fallback. HAS_MUSE=false if [ -d "$HOME/.config/muse" ] || { command -v muse > /dev/null 2>&1 && [ -x "$HOME/.local/bin/muse" ]; }; then HAS_MUSE=true fi # Grok Build — purpose-built hook in ~/.grok/hooks. HAS_GROK=false if [ -d "$HOME/.grok" ] || command -v grok > /dev/null 2>&1; then HAS_GROK=true fi # Google Antigravity (agy) — one shared registration for CLI, IDE and app. HAS_AGY=false if command -v agy > /dev/null 2>&1 || [ -d "$HOME/.gemini/antigravity-cli" ]; then HAS_AGY=true fi # opencode (sst/opencode) — global config/plugins under ~/.config/opencode. if [ -d "$HOME/.config/opencode" ] || command -v opencode > /dev/null 2>&1; then HAS_OPENCODE=true fi # Qwen Code (QwenLM/qwen-code, Gemini CLI lineage) — hooks are Claude Code's # contract (PreToolUse/PostToolUse, hookSpecificOutput.permissionDecision, # exit 2 = block) read from ~/.qwen/settings.json; timeouts are milliseconds. HAS_QWEN=false if [ -d "$HOME/.qwen" ] || command -v qwen > /dev/null 2>&1; then HAS_QWEN=true fi # GitHub Copilot — the CLI (~/.copilot, `copilot` on PATH) and VS Code's # agent mode (the github.copilot-chat extension) read ONE user-level hook # directory, ~/.copilot/hooks/, in Claude Code's hook contract. Either # presence is enough: the file serves both. HAS_COPILOT=false if [ -d "$HOME/.copilot" ] || command -v copilot > /dev/null 2>&1; then HAS_COPILOT=true fi for _vsx in "$HOME/.vscode/extensions" "$HOME/.vscode-insiders/extensions" "$HOME/.vscode-server/extensions"; do if ls -d "$_vsx"/github.copilot-chat-* > /dev/null 2>&1; then HAS_COPILOT=true; fi done # ── Consent: what we found, and what you actually want governed ──────── ACP_STEP="consent" # # Two people signed up on 2026-09-17, looked at what had just been written # to their machines, and spent the rest of their session taking it back off. # Neither was ever asked. An installer that wires every agent tool on the # box without showing you the list first reads like something you caught # rather than something you chose — so show the list, say plainly what each # entry means, and let people pick. # # Everything detected is the default, because governing one harness and not # another leaves a hole. A default, though, not a fait accompli. HARNESS_SLUG=(); HARNESS_NAME=(); HARNESS_FILES=(); HARNESS_NOTE=() _offer() { # slug detected Label files note if [ "$2" != true ]; then return 0; fi HARNESS_SLUG+=("$1"); HARNESS_NAME+=("$3"); HARNESS_FILES+=("$4"); HARNESS_NOTE+=("$5") } _offer claude-code "$HAS_CLAUDE" "Claude Code" \ "~/.claude/settings.json · ~/.claude/CLAUDE.md" \ "Safety-floor holds appear inline in your session; holds from your own rules are approved from the console or email. Adds a claude-acp launcher that prices model calls." _offer cursor "$HAS_CURSOR" "Cursor" \ "~/.cursor/hooks.json · ~/.cursor/mcp.json" \ "Covers tool calls made by Cursor's agent, not your own editing." _offer codex "$HAS_CODEX" "Codex CLI" \ "~/.codex/config.toml · ~/.codex/AGENTS.md" \ "Codex has no approval prompt, so a policy that would ask blocks instead. Enables Codex's hooks feature." _offer openclaw "$HAS_OPENCLAW" "OpenClaw" \ "~/.openclaw/settings.json" \ "Hook on every tool call." _offer opencode "$HAS_OPENCODE" "opencode" \ "~/.config/opencode/" \ "Hook on every tool call, via its plugin system." _offer qwen-code "$HAS_QWEN" "Qwen Code" \ "~/.qwen/settings.json" \ "Hook on every tool call; reads Claude Code's hook contract." _offer copilot "$HAS_COPILOT" "GitHub Copilot" \ "~/.copilot/hooks/acp.json" \ "One file for Copilot CLI and VS Code agent mode; reads Claude Code's hook contract. Cloud coding-agent runs need the repo-level copy (see the guide)." _offer hermes "$HAS_HERMES" "Hermes Agent" \ "its pip environment (acp-hermes)" \ "Installs a Python package into the environment that runs hermes." _offer dsh "$HAS_DSH" "DeepSeek Harness" \ "$DSH_HOME_DIR/profiles" \ "Adds a plugin to each profile via its own plugin manager." _offer pi "$HAS_PI" "pi" \ "$PI_EXT_DIR/acp.ts" \ "A global extension file, so governance is on before any repo is opened." _offer prime-agent "$HAS_PRIME" "Prime Agent" \ "$PRIME_EXT_DIR/acp.ts" \ "A global extension file, loaded without a project-trust prompt." _offer muse "$HAS_MUSE" "Muse Code" \ "~/.config/muse/" \ "Plugin bundle. Its background agent makes tool calls of its own, which will appear in your audit." _offer grok "$HAS_GROK" "Grok Build" \ "~/.grok/hooks/acp.json" \ "Purpose-built hook. Grok also auto-loads Claude-format hooks, so this is the one that actually decides." _offer agy "$HAS_AGY" "Antigravity" \ "~/.gemini/config/hooks.json" \ "One registration shared by its CLI, IDE and app. Merged under our own key, never overwriting yours." SELECTED="" _selected() { case " $SELECTED " in *" $1 "*) return 0;; esac; return 1; } # Is this harness ALREADY governed on this machine? Used only by --update, # to tell "refresh what you run" apart from "adopt something new". Each probe # looks for the artifact that harness's own install block writes, so a # half-finished install reads as not-wired and gets repaired rather than # skipped. Only ever called from an `if`, so a false return is a verdict. _already_wired() { case "$1" in claude-code) [ -f "$HOME/.claude/settings.json" ] && grep -q 'govern' "$HOME/.claude/settings.json" 2>/dev/null ;; cursor) [ -f "$HOME/.cursor/hooks.json" ] && grep -q 'govern' "$HOME/.cursor/hooks.json" 2>/dev/null ;; codex) [ -f "$HOME/.codex/config.toml" ] && grep -q 'acp' "$HOME/.codex/config.toml" 2>/dev/null ;; openclaw) [ -f "$HOME/.openclaw/settings.json" ] && grep -q 'govern' "$HOME/.openclaw/settings.json" 2>/dev/null ;; opencode) [ -f "$HOME/.config/opencode/opencode.json" ] && grep -q 'acp' "$HOME/.config/opencode/opencode.json" 2>/dev/null ;; qwen-code) [ -f "$HOME/.qwen/settings.json" ] && grep -q 'govern' "$HOME/.qwen/settings.json" 2>/dev/null ;; copilot) [ -f "$HOME/.copilot/hooks/acp.json" ] && grep -q 'govern' "$HOME/.copilot/hooks/acp.json" 2>/dev/null ;; hermes) [ -f "$HOME/.hermes/SOUL.md" ] && grep -q 'acp:begin' "$HOME/.hermes/SOUL.md" 2>/dev/null ;; dsh) [ -f "$DSH_HOME_DIR/settings.yaml" ] && grep -q 'agenticcontrolplane' "$DSH_HOME_DIR/settings.yaml" 2>/dev/null ;; pi) [ -f "$PI_EXT_DIR/acp.ts" ] ;; prime-agent) [ -f "$PRIME_EXT_DIR/acp.ts" ] ;; muse) [ -f "$HOME/.config/muse/AGENTS.md" ] && grep -q 'acp:begin' "$HOME/.config/muse/AGENTS.md" 2>/dev/null ;; grok) [ -f "$HOME/.grok/hooks/acp.json" ] ;; agy) [ -f "$HOME/.gemini/config/hooks.json" ] && grep -q 'acp' "$HOME/.gemini/config/hooks.json" 2>/dev/null ;; *) return 1 ;; esac } _select_all() { SELECTED=""; for _s in "${HARNESS_SLUG[@]}"; do SELECTED="$SELECTED $_s"; done; } # Non-interactive selection, for CI and for anyone who'd rather not be asked: # --only=claude-code,cursor --all ACP_ONLY=claude-code ACP_ONLY="${ACP_ONLY:-}" for _a in "$@"; do case "$_a" in --only=*) ACP_ONLY="${_a#--only=}" ;; --all|--yes|-y) ACP_ONLY="all" ;; esac done _parse_pick() { local _raw _tok _idx _s _found _raw="$(printf '%s' "$1" | tr ',' ' ')" SELECTED="" for _tok in $_raw; do case "$_tok" in [0-9]*) _idx=$((_tok - 1)) if [ "$_idx" -ge 0 ] && [ "$_idx" -lt "${#HARNESS_SLUG[@]}" ]; then SELECTED="$SELECTED ${HARNESS_SLUG[$_idx]}" else echo " ${C_DIM}Ignoring \"$_tok\" — there is no item $_tok.${C_RESET}" fi ;; *) _found=false for _s in "${HARNESS_SLUG[@]}"; do if [ "$_s" = "$_tok" ]; then SELECTED="$SELECTED $_s"; _found=true; fi done if [ "$_found" != true ]; then echo " ${C_DIM}Ignoring \"$_tok\" — not one of the tools found here.${C_RESET}" fi ;; esac done } if [ "${#HARNESS_SLUG[@]}" -gt 0 ] && [ "$UPDATE_MODE" = false ]; then echo "" echo " Agentic Control Plane" echo " ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" echo "" if [ "${#HARNESS_SLUG[@]}" -eq 1 ]; then echo " Found one agent tool on this machine:" else echo " Found ${#HARNESS_SLUG[@]} agent tools on this machine:" fi echo "" for _i in "${!HARNESS_SLUG[@]}"; do printf " %d) %s\n" "$((_i + 1))" "${HARNESS_NAME[$_i]}" printf " %s\n" "${C_DIM}writes: ${HARNESS_FILES[$_i]}${C_RESET}" printf " %s\n" "${C_DIM}${HARNESS_NOTE[$_i]}${C_RESET}" done echo "" echo " For each one you pick, ACP adds a hook that runs before and after" echo " every tool call your agent makes. The hook records the call — tool" echo " name, a truncated preview of the arguments and the result, and the" echo " decision — to your workspace. The safety floor applies from the first" echo " call: rm -rf on your home or system folders and disk wipes are always" echo " blocked; force-push, destructive SQL, piping a download into a shell," echo " and deleting outside your project are held for your approval. Your own rules apply" echo " once you run /acp-enforce in your agent (with --local they apply from" echo " the first call). Interactive sessions keep working if ACP is unreachable;" echo " unattended runs wait for it." echo "" echo " ${C_DIM}Shared, once: ~/.acp/ plus one marked line adding ~/.acp/bin to PATH" echo " in your shell rc. We append inside acp:begin/acp:end markers and never" echo " overwrite what you wrote.${C_RESET}" echo "" echo " ${C_DIM}Remove all of it: acp-uninstall${C_RESET}" echo " ${C_DIM}What we store: https://agenticcontrolplane.com/trust${C_RESET}" echo "" if [ "$ACP_ONLY" = "all" ]; then _select_all echo " Governing all of them." elif [ -n "$ACP_ONLY" ]; then _parse_pick "$ACP_ONLY" elif [ -r /dev/tty ]; then printf " Which should ACP govern? [Enter = all · 1,3 = pick · n = none]: " _reply="" read -r _reply < /dev/tty || _reply="" echo "" case "$_reply" in "") _select_all ;; n|N|no|NO|none|q|Q|quit) echo " Nothing installed. Nothing was written to this machine." echo "" exit 0 ;; *) _parse_pick "$_reply" ;; esac else _select_all echo " ${C_DIM}No terminal to ask on — governing all of the above. Narrow it with" echo " --only=, or remove everything later with acp-uninstall.${C_RESET}" fi if [ -z "$SELECTED" ]; then echo " Nothing selected, so nothing was written to this machine." echo " Re-run and pick by number, or: --only=claude-code" echo "" exit 0 fi # ── Step 1c: safety floor ────────────────────────────────────────── # On for everyone. Turning it off takes a person at a real terminal, the # same way "Reconfigure?" below does: no /dev/tty (curl|bash in CI, an # agent re-running this) means on, and ACP_FLOOR=off is honoured only when # a terminal is present too. --all/--only skip the question; floor on. # Opening /dev/tty (not just -r) is the real test: the node is readable # even when there is no controlling terminal to open. # ACP_FLOOR is set ONLY when a person typed an answer (Enter on the Y/n # question counts as "on"). Every other path leaves it empty, so the beacon # carries no `floor` field and the workspace records no choice nobody made. # A terminal proves a terminal, not a person (an agent inside tmux has # one), so even ACP_FLOOR=off waits for a typed "y" before it counts. ACP_FLOOR="" echo "" if [ "$LOCAL_MODE" = true ]; then echo " Safety floor: rm -rf /, mkfs and fork bombs are always refused; force-push, destructive SQL, curl|sh and deletes outside the working directory ask first, in every harness above. (on)" else echo " Safety floor: on. Force-push, destructive SQL and curl|sh wait for a person in every harness above." if ( : /dev/null; then _floor_reply="" if [ "$_ACP_FLOOR_ENV" = off ]; then printf " Turn the safety floor off for this workspace? (y/N) " if read -r _floor_reply /dev/null; then _floor_reply="$(printf '%s' "$_floor_reply" | tr 'A-Z' 'a-z' | tr -d '[:space:]')" case "$_floor_reply" in y|yes) ACP_FLOOR=off ;; *) ACP_FLOOR=on ;; esac fi elif [ -z "$ACP_ONLY" ]; then printf " Keep the safety floor on? (Y/n) " if read -r _floor_reply /dev/null; then _floor_reply="$(printf '%s' "$_floor_reply" | tr 'A-Z' 'a-z' | tr -d '[:space:]')" case "$_floor_reply" in n|no) ACP_FLOOR=off ;; *) ACP_FLOOR=on ;; esac fi fi elif [ "$_ACP_FLOOR_ENV" = off ]; then echo " ${C_DIM}ACP_FLOOR=off ignored: turning the floor off needs a terminal. It stays on.${C_RESET}" fi if [ "$ACP_FLOOR" = off ]; then echo " Safety floor off for this workspace. Turn it back on any time from the console's Policies page." fi fi # The gate reaches every install block below through these flags alone — # each block keeps its own logic and its own notes. if ! _selected claude-code; then HAS_CLAUDE=false; fi if ! _selected cursor; then HAS_CURSOR=false; fi if ! _selected codex; then HAS_CODEX=false; fi if ! _selected openclaw; then HAS_OPENCLAW=false; fi if ! _selected opencode; then HAS_OPENCODE=false; fi if ! _selected qwen-code; then HAS_QWEN=false; fi if ! _selected copilot; then HAS_COPILOT=false; fi if ! _selected hermes; then HAS_HERMES=false; fi if ! _selected dsh; then HAS_DSH=false; fi if ! _selected pi; then HAS_PI=false; fi if ! _selected prime-agent; then HAS_PRIME=false; fi if ! _selected muse; then HAS_MUSE=false; fi if ! _selected grok; then HAS_GROK=false; fi if ! _selected agy; then HAS_AGY=false; fi elif [ "${#HARNESS_SLUG[@]}" -gt 0 ] && [ "$UPDATE_MODE" = true ]; then # An update refreshes what you already run. It does NOT adopt a harness # you never chose. Observed 2026-09-17: `acp-update` on a machine wired # for Claude Code, Codex and opencode silently installed governance into # pi and Antigravity as well, because they had appeared on the box since # the original install. Refreshing what is wired is not a new decision; # taking over a new harness is, and an update is the last place someone # expects to be asked to make one. So: name them, touch nothing, and say # exactly how to opt in. _new_found="" for _i in "${!HARNESS_SLUG[@]}"; do if ! _already_wired "${HARNESS_SLUG[$_i]}"; then _new_found="${_new_found:+$_new_found }${HARNESS_SLUG[$_i]}" case "${HARNESS_SLUG[$_i]}" in claude-code) HAS_CLAUDE=false ;; cursor) HAS_CURSOR=false ;; codex) HAS_CODEX=false ;; openclaw) HAS_OPENCLAW=false ;; opencode) HAS_OPENCODE=false ;; qwen-code) HAS_QWEN=false ;; copilot) HAS_COPILOT=false ;; hermes) HAS_HERMES=false ;; dsh) HAS_DSH=false ;; pi) HAS_PI=false ;; prime-agent) HAS_PRIME=false ;; muse) HAS_MUSE=false ;; grok) HAS_GROK=false ;; agy) HAS_AGY=false ;; esac fi done if [ -n "$_new_found" ]; then echo "" echo " New on this machine since you installed ACP:${C_RESET}" for _s in $_new_found; do for _i in "${!HARNESS_SLUG[@]}"; do if [ "${HARNESS_SLUG[$_i]}" = "$_s" ]; then echo " ${HARNESS_NAME[$_i]} ${C_DIM}(${HARNESS_FILES[$_i]})${C_RESET}" fi done done echo " ${C_DIM}Left alone — an update refreshes what you already run, it doesn't" echo " take over something new. To govern them too:${C_RESET}" echo " curl -sf https://agenticcontrolplane.com/install.sh | bash -s -- --only=$(echo "$_new_found" | tr ' ' ',')" echo "" fi fi # Hermes Agent — governed via its native pip plugin. One front door: this # installer performs the plugin install itself (David 2026-07-21: fold every # harness into the one-liner). Fail-open: any step failing degrades to # printing the manual commands, never a broken half-install. # Cloud-only: acp-hermes governs via a workspace token (without one it passes # through), so --local skips the plugin install rather than wiring a no-op. if [ "$HAS_HERMES" = true ] && [ "$LOCAL_MODE" = true ]; then echo " ${C_DIM}Hermes detected — skipped in --local mode (its ACP plugin needs a workspace; local decisions aren't wired there yet).${C_RESET}" echo "" fi if [ "$HAS_HERMES" = true ] && [ "$LOCAL_MODE" = false ]; then echo " Detected Hermes Agent — installing the ACP plugin…" HERMES_PLUGIN_OK=false # If hermes lives in a pipx venv, the plugin must be injected there — # a bare pip install lands in the wrong environment, and pipx venvs ship # without pip, so the shebang fallback below can't reach them either. # The venv is named after the PyPI package (`hermes-agent`, not `hermes`): # read the real name off `pipx list` ("package hermes-agent 0.19.0, ...") # instead of guessing it from the command name. if command -v pipx > /dev/null 2>&1; then HERMES_PIPX_VENV="$(pipx list 2>/dev/null | sed -n 's/^[[:space:]]*package[[:space:]]\{1,\}\(hermes[^[:space:],]*\).*/\1/p' | head -1)" if [ -n "$HERMES_PIPX_VENV" ]; then pipx inject "$HERMES_PIPX_VENV" acp-hermes --force >/dev/null 2>&1 && HERMES_PLUGIN_OK=true fi fi # Otherwise install with the same interpreter that runs hermes (shebang), # falling back to plain pip. PEP 668 boxes will refuse — that's the # fail-open path below, not something to --break-system-packages through. if [ "$HERMES_PLUGIN_OK" = false ]; then HERMES_BIN="$(command -v hermes)" HERMES_PY="$(head -1 "$HERMES_BIN" 2>/dev/null | sed -n 's/^#!//p')" if [ -n "$HERMES_PY" ] && [ -x "$HERMES_PY" ]; then "$HERMES_PY" -m pip install --upgrade acp-hermes >/dev/null 2>&1 && HERMES_PLUGIN_OK=true fi fi if [ "$HERMES_PLUGIN_OK" = false ]; then pip install --upgrade acp-hermes >/dev/null 2>&1 && HERMES_PLUGIN_OK=true fi if [ "$HERMES_PLUGIN_OK" = true ] && hermes plugins enable acp >/dev/null 2>&1; then echo " ${C_GREEN}✓ Hermes governed${C_RESET} — next: acp-hermes login (headless box: set ACP_BEARER_TOKEN instead)" INSTALLED="${INSTALLED:+$INSTALLED, }Hermes" else echo " Couldn't install automatically (often a PEP 668 managed environment)." echo " Run it in your Python env of choice:" echo " pip install acp-hermes && hermes plugins enable acp && acp-hermes login" echo " Guide: https://agenticcontrolplane.com/integrations/hermes" fi echo "" fi # DeepSeek Harness (dsh) — governed via its native plugin system, same # one-front-door rule as Hermes (David 2026-07-21: fold every harness into # the one-liner). Plugins are profile-scoped, so install into every existing # profile; `dsh plugin add` is idempotent (pnpm re-links the same package). # Fail-open: any refusal degrades to printing the manual command. # Cloud-only like Hermes: @agenticcontrolplane/dsh needs a workspace credential; local # decisions aren't wired there yet. if [ "$HAS_DSH" = true ] && [ "$LOCAL_MODE" = true ]; then echo " ${C_DIM}DeepSeek Harness detected — skipped in --local mode (its ACP plugin needs a workspace; local decisions aren't wired there yet).${C_RESET}" echo "" fi if [ "$HAS_DSH" = true ] && [ "$LOCAL_MODE" = false ]; then echo " Detected DeepSeek Harness — installing the ACP plugin…" DSH_PROFILES_INSTALLED=0 DSH_PROFILES_FAILED=0 if command -v dsh > /dev/null 2>&1 && [ -d "$DSH_HOME_DIR/profiles" ]; then for _dsh_prof in "$DSH_HOME_DIR"/profiles/*/; do [ -d "$_dsh_prof" ] || continue _dsh_prof_name="$(basename "$_dsh_prof")" # The installation's shared node_modules dir is not a profile. [ "$_dsh_prof_name" = "node_modules" ] && continue if dsh plugin --profile "$_dsh_prof_name" add @agenticcontrolplane/dsh >/dev/null 2>&1; then DSH_PROFILES_INSTALLED=$((DSH_PROFILES_INSTALLED + 1)) else DSH_PROFILES_FAILED=$((DSH_PROFILES_FAILED + 1)) fi done fi if [ "$DSH_PROFILES_INSTALLED" -gt 0 ] && [ "$DSH_PROFILES_FAILED" -eq 0 ]; then echo " ${C_GREEN}✓ DeepSeek Harness governed${C_RESET} — plugin added to $DSH_PROFILES_INSTALLED profile(s); active from the next dsh boot." INSTALLED="${INSTALLED:+$INSTALLED, }DeepSeek Harness" else # No profiles yet, dsh not on PATH, or an add refused (dsh needs Node 22 — # a Node 20 default breaks it). Print the manual path instead of guessing. echo " Couldn't finish automatically (no profiles yet, or dsh isn't on PATH here — note dsh needs Node 22)." echo " Run it against the profile you use:" echo " dsh plugin --profile add @agenticcontrolplane/dsh" echo " Guide: https://github.com/agentic-control-plane/dsh-acp-plugin" fi echo "" fi # pi (earendil-works) — ships no permission system by design; governed via a # native TypeScript extension on its tool_call / tool_result events. Same # one-front-door rule. Extensions are files under ~/.pi/agent/extensions/; # the global path loads without a project-trust prompt, so governance is on # before any repo is opened. Fail-open: a fetch failure prints the manual path. # Cloud-only like Hermes/dsh: the extension reads ~/.acp/credentials; local # decisions aren't wired there yet. if [ "$HAS_PI" = true ] && [ "$LOCAL_MODE" = true ]; then echo " ${C_DIM}pi detected — skipped in --local mode (its ACP extension needs a workspace; local decisions aren't wired there yet).${C_RESET}" echo "" fi if [ "$HAS_PI" = true ] && [ "$LOCAL_MODE" = false ]; then echo " Detected pi — installing the ACP extension…" PI_EXT_OK=false if mkdir -p "$PI_EXT_DIR" 2>/dev/null && _acp_fetch_pinned \ "https://raw.githubusercontent.com/agentic-control-plane/pi-acp-plugin/$ACP_PIN_PI_REF/index.ts" \ "$ACP_PIN_PI_INDEX_SHA" "$PI_EXT_DIR/acp.ts"; then PI_EXT_OK=true else _acp_pin_warn "the pi extension" "Skipping it." fi if [ "$PI_EXT_OK" = true ]; then echo " ${C_GREEN}✓ pi governed${C_RESET} — extension written to ~/.pi/agent/extensions/acp.ts; active from the next pi session (needs Node 22)." INSTALLED="${INSTALLED:+$INSTALLED, }pi" else # Network refused or the extensions dir isn't writable — print the manual # path rather than guessing. echo " Couldn't fetch automatically. Install it by hand:" echo " mkdir -p ~/.pi/agent/extensions && curl -sf https://raw.githubusercontent.com/agentic-control-plane/pi-acp-plugin/$ACP_PIN_PI_REF/index.ts -o ~/.pi/agent/extensions/acp.ts # expected sha256: $ACP_PIN_PI_INDEX_SHA" echo " Guide: https://agenticcontrolplane.com/integrations/pi" fi echo "" fi # Prime Agent (Prime Intellect) — a pi-mono hard fork that kept pi's extension # API; governed via the same kind of native TypeScript extension on its # tool_call / tool_result events (prime-agent-acp-plugin adds an argv-based # headless fix for prime's hasUI print-mode bug). Same one-front-door rule. # Extensions under ~/.prime/agent/extensions/ load without a project-trust # prompt. Fail-open: a fetch failure prints the manual path. # Cloud-only like pi: the extension reads ~/.acp/credentials; local decisions # aren't wired there yet. if [ "$HAS_PRIME" = true ] && [ "$LOCAL_MODE" = true ]; then echo " ${C_DIM}Prime Agent detected — skipped in --local mode (its ACP extension needs a workspace; local decisions aren't wired there yet).${C_RESET}" echo "" fi if [ "$HAS_PRIME" = true ] && [ "$LOCAL_MODE" = false ]; then echo " Detected Prime Agent — installing the ACP extension…" PRIME_EXT_OK=false if mkdir -p "$PRIME_EXT_DIR" 2>/dev/null && _acp_fetch_pinned \ "https://raw.githubusercontent.com/agentic-control-plane/prime-agent-acp-plugin/$ACP_PIN_PRIME_REF/index.ts" \ "$ACP_PIN_PRIME_INDEX_SHA" "$PRIME_EXT_DIR/acp.ts"; then PRIME_EXT_OK=true else _acp_pin_warn "the Prime Agent extension" "Skipping it." fi if [ "$PRIME_EXT_OK" = true ]; then echo " ${C_GREEN}✓ Prime Agent governed${C_RESET} — extension written to ~/.prime/agent/extensions/acp.ts; active from the next session or /reload (needs Node 22.8+)." else # Network refused or the extensions dir isn't writable — print the manual # path rather than guessing. echo " Couldn't fetch automatically. Install it by hand:" echo " mkdir -p ~/.prime/agent/extensions && curl -sf https://raw.githubusercontent.com/agentic-control-plane/prime-agent-acp-plugin/$ACP_PIN_PRIME_REF/index.ts -o ~/.prime/agent/extensions/acp.ts # expected sha256: $ACP_PIN_PRIME_INDEX_SHA" echo " Guide: https://agenticcontrolplane.com/integrations/prime-agent" fi echo "" fi # Muse Code (Meta) — governed via its native plugin system (behind the # MUSE_EXPERIMENTAL_PLUGINS flag in the 0.2.1 beta; the flag gates only the # management CLI, approved hooks fire without it). Our npm package IS the # plugin bundle. Same one-front-door rule as Hermes/dsh/pi. Fail-open: any # refusal degrades to printing the manual commands. # Cloud-only like Hermes/dsh/pi: Muse clears the hook environment, so the # plugin reads ~/.acp/credentials; local decisions aren't wired there yet. if [ "$HAS_MUSE" = true ] && [ "$LOCAL_MODE" = true ]; then echo " ${C_DIM}Muse Code detected — skipped in --local mode (its ACP plugin needs a workspace; local decisions aren't wired there yet).${C_RESET}" echo "" fi if [ "$HAS_MUSE" = true ] && [ "$LOCAL_MODE" = false ]; then echo " Detected Muse Code — installing the ACP plugin…" MUSE_PLUGIN_OK=false # npm global install, then install+approve the bundle into Muse. The # experimental flag is required for the plugins CLI; approved hooks then run # without it. All three steps must succeed to claim governed. if npm install -g @agenticcontrolplane/muse-code >/dev/null 2>&1; then _muse_pkg="$(npm root -g 2>/dev/null)/@agenticcontrolplane/muse-code" if [ -d "$_muse_pkg" ] \ && MUSE_EXPERIMENTAL_PLUGINS=1 muse plugins install "$_muse_pkg" --scope user >/dev/null 2>&1 \ && MUSE_EXPERIMENTAL_PLUGINS=1 muse plugins approve acp >/dev/null 2>&1; then MUSE_PLUGIN_OK=true fi fi if [ "$MUSE_PLUGIN_OK" = true ]; then echo " ${C_GREEN}✓ Muse Code governed${C_RESET} — plugin installed and approved; active from the next Muse session." INSTALLED="${INSTALLED:+$INSTALLED, }Muse Code" else # npm/muse not on PATH here, or an install/approve step refused — print the # manual commands rather than guessing. echo " Couldn't finish automatically (npm or muse not on PATH here, or a step refused). Run:" echo " npm install -g @agenticcontrolplane/muse-code" echo " MUSE_EXPERIMENTAL_PLUGINS=1 muse plugins install \"\$(npm root -g)/@agenticcontrolplane/muse-code\" --scope user" echo " MUSE_EXPERIMENTAL_PLUGINS=1 muse plugins approve acp" echo " Guide: https://agenticcontrolplane.com/integrations/muse-code" fi echo "" fi # Grok Build (xAI) — hooks register user-globally in ~/.grok/hooks/*.json (no # trust prompt). Two raw-file fetches: the hook itself into ~/.acp/hooks and # the registration JSON into ~/.grok/hooks. NOTE: Grok also auto-loads hooks # from ~/.claude/settings.json but doesn't parse Claude's output vocabulary, # so the Claude hook alone would fire and be ignored — this purpose-built hook # is the governed path. Fail-open: any refusal prints the manual commands. # Cloud-only like Hermes/dsh/pi/Muse: the hook reads ~/.acp/credentials. if [ "$HAS_GROK" = true ] && [ "$LOCAL_MODE" = true ]; then echo " ${C_DIM}Grok Build detected — skipped in --local mode (its ACP hook needs a workspace; local decisions aren't wired there yet).${C_RESET}" echo "" fi if [ "$HAS_GROK" = true ] && [ "$LOCAL_MODE" = false ]; then echo " Detected Grok Build — installing the ACP hook…" GROK_HOOK_OK=false _grok_raw="https://raw.githubusercontent.com/agentic-control-plane/grok-build-acp-plugin/$ACP_PIN_GROK_REF" if mkdir -p "$HOME/.acp/hooks/grok-build" "$HOME/.grok/hooks" 2>/dev/null \ && _acp_fetch_pinned "$_grok_raw/hook.mjs" "$ACP_PIN_GROK_HOOK_SHA" "$HOME/.acp/hooks/grok-build/hook.mjs" \ && _acp_fetch_pinned "$_grok_raw/hooks/acp.json" "$ACP_PIN_GROK_JSON_SHA" "$HOME/.grok/hooks/acp.json"; then GROK_HOOK_OK=true else _acp_pin_warn "a Grok Build hook file" "Hook not registered." fi if [ "$GROK_HOOK_OK" = true ]; then echo " ${C_GREEN}✓ Grok Build governed${C_RESET} — hook registered user-globally; fires in every mode, always-approve included; active from the next Grok session." INSTALLED="${INSTALLED:+$INSTALLED, }Grok Build" else echo " Couldn't finish automatically (curl refused or a directory wasn't writable). Run:" echo " mkdir -p ~/.acp/hooks/grok-build ~/.grok/hooks" echo " curl -fsSL $_grok_raw/hook.mjs -o ~/.acp/hooks/grok-build/hook.mjs # expected sha256: $ACP_PIN_GROK_HOOK_SHA" echo " curl -fsSL $_grok_raw/hooks/acp.json -o ~/.grok/hooks/acp.json # expected sha256: $ACP_PIN_GROK_JSON_SHA" echo " Guide: https://agenticcontrolplane.com/integrations/grok-build" fi echo "" fi # Google Antigravity (agy) — CLI, IDE, and app read ONE shared registration at # ~/.gemini/config/hooks.json. We MERGE under our own "acp" key via node (the # hook needs node anyway) — never overwrite: the file may hold user hooks. if [ "$HAS_AGY" = true ] && [ "$LOCAL_MODE" = true ]; then echo " ${C_DIM}Antigravity detected — skipped in --local mode (its ACP hook needs a workspace; local decisions aren't wired there yet).${C_RESET}" echo "" fi if [ "$HAS_AGY" = true ] && [ "$LOCAL_MODE" = false ]; then echo " Detected Google Antigravity — installing the ACP hook…" AGY_HOOK_OK=false _agy_raw="https://raw.githubusercontent.com/agentic-control-plane/antigravity-acp-plugin/$ACP_PIN_AGY_REF" if command -v node > /dev/null 2>&1 \ && mkdir -p "$HOME/.acp/hooks/antigravity" "$HOME/.gemini/config" 2>/dev/null \ && _acp_fetch_pinned "$_agy_raw/hook.mjs" "$ACP_PIN_AGY_HOOK_SHA" "$HOME/.acp/hooks/antigravity/hook.mjs" \ && _acp_fetch_pinned "$_agy_raw/hooks/acp.json" "$ACP_PIN_AGY_JSON_SHA" "$HOME/.acp/hooks/antigravity/acp.json" \ && node -e 'const fs=require("fs");const p=process.env.HOME+"/.gemini/config/hooks.json";let cur={};try{cur=JSON.parse(fs.readFileSync(p,"utf8"))}catch(e){};const add=JSON.parse(fs.readFileSync(process.env.HOME+"/.acp/hooks/antigravity/acp.json","utf8"));fs.writeFileSync(p,JSON.stringify(Object.assign(cur,add),null,2))' 2>/dev/null; then AGY_HOOK_OK=true else _acp_pin_warn "an Antigravity hook file" "Hook not registered." fi if [ "$AGY_HOOK_OK" = true ]; then echo " ${C_GREEN}✓ Antigravity governed${C_RESET} — registration merged into the shared hooks.json (CLI, IDE, and app); held calls are approved from the console or email; active from the next session." INSTALLED="${INSTALLED:+$INSTALLED, }Antigravity" else echo " Couldn't finish automatically (node/curl refused or a directory wasn't writable). Run:" echo " mkdir -p ~/.acp/hooks/antigravity ~/.gemini/config" echo " curl -fsSL $_agy_raw/hook.mjs -o ~/.acp/hooks/antigravity/hook.mjs # expected sha256: $ACP_PIN_AGY_HOOK_SHA" echo " curl -fsSL $_agy_raw/hooks/acp.json -o ~/.acp/hooks/antigravity/acp.json # expected sha256: $ACP_PIN_AGY_JSON_SHA" echo " node -e 'see https://agenticcontrolplane.com/integrations/antigravity#manual-install'" echo " Guide: https://agenticcontrolplane.com/integrations/antigravity" fi echo "" fi # Plugin-governed harnesses (Hermes, dsh, pi, Prime, Muse, Grok, Antigravity) # are wired above, but they still need what comes AFTER this point: Step 1f # writes their priced launcher, provider block and agent directive, and # Step 2 puts the key on this machine (their plugins read ~/.acp/credentials). # An earlier version exited 0 here on a "hermes-only / pi-only box" — that # skipped all of it, and because bash was still streaming the script from # curl, the early exit broke the pipe and `curl | bash` reported 23 even # though the plugin had installed (harness canary, 2026-10-07). So: only the # truly-nothing-found case stops here; everything else falls through. if [ "$HAS_CLAUDE" = false ] && [ "$HAS_CURSOR" = false ] && [ "$HAS_CODEX" = false ] && [ "$HAS_OPENCLAW" = false ] && [ "$HAS_OPENCODE" = false ] && [ "$HAS_QWEN" = false ] && [ "$HAS_COPILOT" = false ] \ && [ "$HAS_HERMES" = false ] && [ "$HAS_DSH" = false ] && [ "$HAS_PI" = false ] && [ "$HAS_PRIME" = false ] && [ "$HAS_MUSE" = false ] && [ "$HAS_GROK" = false ] && [ "$HAS_AGY" = false ]; then echo " ${C_RED}No supported AI clients detected.${C_RESET}" echo " Supported: Claude Code, Cursor, OpenAI Codex CLI, GitHub Copilot, OpenClaw, opencode, Qwen Code, pi, Prime Agent, Muse Code, Grok Build, Antigravity, Hermes Agent, DeepSeek Harness" echo " Hermes Agent? It has a native pip plugin instead:" echo " pip install acp-hermes && hermes plugins enable acp && acp-hermes login" echo " Guide: https://agenticcontrolplane.com/integrations/hermes" echo " DeepSeek Harness? Same idea, its native plugin system:" echo " dsh plugin --profile add @agenticcontrolplane/dsh" echo " Guide: https://github.com/agentic-control-plane/dsh-acp-plugin" echo " pi (earendil-works)? A native extension file:" echo " mkdir -p ~/.pi/agent/extensions && curl -sf https://raw.githubusercontent.com/agentic-control-plane/pi-acp-plugin/$ACP_PIN_PI_REF/index.ts -o ~/.pi/agent/extensions/acp.ts # expected sha256: $ACP_PIN_PI_INDEX_SHA" echo " Guide: https://agenticcontrolplane.com/integrations/pi" echo " Prime Agent? Same idea, a native extension file:" echo " mkdir -p ~/.prime/agent/extensions && curl -sf https://raw.githubusercontent.com/agentic-control-plane/prime-agent-acp-plugin/$ACP_PIN_PRIME_REF/index.ts -o ~/.prime/agent/extensions/acp.ts # expected sha256: $ACP_PIN_PRIME_INDEX_SHA" echo " Guide: https://agenticcontrolplane.com/integrations/prime-agent" echo "" echo " Install one first, then re-run this script." ACP_OUTCOME="unsupported" exit 1 fi TARGETS="" if [ "$HAS_CLAUDE" = true ]; then TARGETS="Claude Code"; fi if [ "$HAS_CURSOR" = true ]; then if [ -n "$TARGETS" ]; then TARGETS="$TARGETS + Cursor"; else TARGETS="Cursor"; fi fi if [ "$HAS_CODEX" = true ]; then if [ -n "$TARGETS" ]; then TARGETS="$TARGETS + Codex"; else TARGETS="Codex"; fi fi if [ "$HAS_OPENCLAW" = true ]; then if [ -n "$TARGETS" ]; then TARGETS="$TARGETS + OpenClaw"; else TARGETS="OpenClaw"; fi fi if [ "$HAS_OPENCODE" = true ]; then if [ -n "$TARGETS" ]; then TARGETS="$TARGETS + opencode"; else TARGETS="opencode"; fi fi if [ "$HAS_QWEN" = true ]; then if [ -n "$TARGETS" ]; then TARGETS="$TARGETS + Qwen Code"; else TARGETS="Qwen Code"; fi fi if [ "$HAS_COPILOT" = true ]; then if [ -n "$TARGETS" ]; then TARGETS="$TARGETS + GitHub Copilot"; else TARGETS="GitHub Copilot"; fi fi [ "$HAS_HERMES" = true ] && TARGETS="${TARGETS:+$TARGETS + }Hermes" [ "$HAS_DSH" = true ] && TARGETS="${TARGETS:+$TARGETS + }DeepSeek Harness" [ "$HAS_PI" = true ] && TARGETS="${TARGETS:+$TARGETS + }pi" [ "$HAS_PRIME" = true ] && TARGETS="${TARGETS:+$TARGETS + }Prime Agent" [ "$HAS_MUSE" = true ] && TARGETS="${TARGETS:+$TARGETS + }Muse Code" [ "$HAS_GROK" = true ] && TARGETS="${TARGETS:+$TARGETS + }Grok Build" [ "$HAS_AGY" = true ] && TARGETS="${TARGETS:+$TARGETS + }Antigravity" # Machine-readable form of the same detection, sent with the device-code # request so the minted key records WHICH harness it was wired for. The # gateway defaults this to "unknown" when absent, which is what every key # minted through device flow has been labelled until now — and device flow # is the best-converting install path we have, so it was also the only one # we could not attribute. Gateway clips to 64 chars. CLIENT_SLUG="" _add_slug() { if [ -n "$CLIENT_SLUG" ]; then CLIENT_SLUG="$CLIENT_SLUG+$1"; else CLIENT_SLUG="$1"; fi; } [ "$HAS_CLAUDE" = true ] && _add_slug "claude-code" [ "$HAS_CURSOR" = true ] && _add_slug "cursor" [ "$HAS_CODEX" = true ] && _add_slug "codex" [ "$HAS_OPENCLAW" = true ] && _add_slug "openclaw" [ "$HAS_OPENCODE" = true ] && _add_slug "opencode" [ "$HAS_QWEN" = true ] && _add_slug "qwen-code" [ "$HAS_COPILOT" = true ] && _add_slug "copilot" [ "$HAS_HERMES" = true ] && _add_slug "hermes" [ "$HAS_DSH" = true ] && _add_slug "dsh" [ "$HAS_PI" = true ] && _add_slug "pi" [ "$HAS_PRIME" = true ] && _add_slug "prime-agent" [ "$HAS_MUSE" = true ] && _add_slug "muse" [ "$HAS_GROK" = true ] && _add_slug "grok" [ "$HAS_AGY" = true ] && _add_slug "antigravity" [ -n "$CLIENT_SLUG" ] || CLIENT_SLUG="cli" echo "" echo " Wiring $TARGETS" echo " ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" echo "" mkdir -p "$CONFIG_DIR" # ── Shared: write govern.mjs ────────────────────────────────────────── ACP_STEP="govern_mjs" # Single dispatcher script used by non-plugin clients (Cursor, Codex, # opencode) and as the Claude Code fallback. The CANONICAL copy lives in # the plugin repo (bin/govern.mjs — scoped-token exchange + the govern.* # control-plane endpoint); fetch it so hook fixes reach these harnesses # without an installer release. The inline copy below is the offline # fallback only. # Old version, read from whatever is already on disk, before it's # overwritten below — acp-update prints old -> new so a refresh is visible. GOVERN_OLD_VERSION="$(grep -o 'PLUGIN_VERSION = "[^"]*"' "$CONFIG_DIR/govern.mjs" 2>/dev/null | head -1 | sed 's/.*"\(.*\)"/\1/')" echo " [ACP] Installing governance hook script..." GOVERN_RAW_URL="https://raw.githubusercontent.com/agentic-control-plane/$ACP_PIN_GOVERN_REPO/$ACP_PIN_GOVERN_REF/bin/govern.mjs" # In --local mode the fetched copy must actually carry the local decision # path (runLocal). A canonical copy without it would exit silently on every # call — "local mode active" with zero governance and zero audit. Never # brick, never silently: such a copy is rejected in favor of the bundled one. # Pinned (acp-install#29): fetched to a private temp file, sha256-verified # against ACP_PIN_GOVERN_SHA, then renamed into place. Offline, a 404, or a # checksum mismatch all land on the bundled copy below — never silently: a # rejected file warns, an unreachable one prints a one-line notice, and a # verified file that fails the sanity checks says which check. The install # never prompts and never fails here. GOVERN_FETCHED="$CONFIG_DIR/govern.mjs.pinned" rm -f "$GOVERN_FETCHED" GOVERN_PINNED_OK=false if _acp_fetch_pinned "$GOVERN_RAW_URL" "$ACP_PIN_GOVERN_SHA" "$GOVERN_FETCHED"; then if ! head -1 "$GOVERN_FETCHED" | grep -q "node"; then echo " ${C_RED}[ACP] WARNING:${C_RESET} pinned govern.mjs verified but has no node shebang — using the bundled copy." >&2 elif [ "$LOCAL_MODE" = true ] && ! grep -q "runLocal" "$GOVERN_FETCHED"; then echo " ${C_RED}[ACP] WARNING:${C_RESET} pinned govern.mjs verified but lacks the local decision path (runLocal) — using the bundled copy so --local keeps governing." >&2 elif mv -f "$GOVERN_FETCHED" "$CONFIG_DIR/govern.mjs"; then GOVERN_PINNED_OK=true else echo " ${C_RED}[ACP] WARNING:${C_RESET} could not move the verified govern.mjs into place — using the bundled copy." >&2 fi elif [ "$ACP_PIN_FAIL" = "checksum" ]; then _acp_pin_warn "govern.mjs" "Using the bundled copy instead." else echo " ${C_DIM}[ACP] pinned govern.mjs unavailable, using bundled copy${C_RESET}" >&2 fi if [ "$GOVERN_PINNED_OK" = true ]; then GOVERN_SOURCE="canonical (plugin repo, pinned + sha256-verified)" else rm -f "$GOVERN_FETCHED" GOVERN_SOURCE="bundled fallback" # The bundled copy is written to a sibling file first and only promoted # when it is NOT a downgrade. A failed fetch on a machine that already # has a newer govern.mjs must keep that file: on 2026-11-02 a real # customer's 0.28.0 was silently overwritten by this fallback and every # tool call ran the older hook. Never brick, never silently. GOVERN_BUNDLED="$CONFIG_DIR/govern.mjs.bundled" cat > "$GOVERN_BUNDLED" << 'GOVERN' #!/usr/bin/env node import { readFileSync, existsSync, appendFileSync, mkdirSync, writeFileSync, statSync, openSync, readSync, closeSync } from "fs"; import { homedir } from "os"; import { join } from "path"; const ACP_API = process.env.ACP_API_BASE || "https://api.agenticcontrolplane.com"; const PLUGIN_VERSION = "0.5.0"; // Identifies the calling client to the server (per-client policy routing). // Each client's hooks.json sets this env var at invocation time: "claude-code-plugin", // "cursor", "codex", etc. Falls back to claude-code-plugin for backward compat. const ACP_CLIENT = process.env.ACP_CLIENT || "claude-code-plugin"; const POST_HOOK_PAYLOAD_CEILING = 200 * 1024; function readToken() { if (process.env.ACP_BEARER_TOKEN) return process.env.ACP_BEARER_TOKEN; // Both credential paths, in the same order as the plugin's // bin/mcp-auth-headers.sh — these MUST stay in sync. When only proxy-key // exists, MCP authenticates (the install looks healthy) while a // credentials-only hook reads nothing and no-ops, so a missing credentials file must fail the check. for (const name of ["credentials", "proxy-key"]) { try { const value = readFileSync(join(homedir(), ".acp", name), "utf8").trim(); if (value) return value; } catch { /* absent or unreadable — try the next path */ } } return null; } const ACP_DIR = join(homedir(), ".acp"); const token = readToken(); // LOCAL mode: no account, no cloud. Active when there's no token AND either a // local policy exists or ACP_LOCAL=1. Decisions are made on-device by // decide.mjs against ~/.acp/policy.json; calls are logged to ~/.acp/audit.jsonl. const LOCAL = !token && (process.env.ACP_LOCAL === "1" || existsSync(join(ACP_DIR, "policy.json"))); // Read stdin via async iteration, not readFileSync("/dev/stdin"): on Linux a // non-blocking pipe makes the sync read throw EAGAIN, which would silently // skip governance for every call. (Caught by CI on ubuntu.) Read before the // no-credentials check so the warning can name the session and the tool. let input; try { process.stdin.setEncoding("utf8"); let raw = ""; for await (const chunk of process.stdin) raw += chunk; input = JSON.parse(raw); } catch { process.exit(0); } // Wired but uncredentialed: never brick — but NEVER silently: a silent no-op looks like governance. The // canonical bin/govern.mjs warns loudly here; this offline fallback must // match, or the no-network install path keeps the exact silent-ungoverned // hole the front-door fix closed. Banner once per session (marker-deduped); // a lapse.log line every call — the durable, auditable record of the gap. if (!token && !LOCAL) { const sessionId = String(input?.session_id ?? "unknown"); try { mkdirSync(ACP_DIR, { recursive: true }); } catch { /* best-effort */ } try { appendFileSync(join(ACP_DIR, "lapse.log"), `${new Date().toISOString()}\tUNGOVERNED\tno-credentials\tclient=${ACP_CLIENT}\tsession=${sessionId}\ttool=${input?.tool_name ?? "?"}\n`); } catch { /* the lapse log is best-effort — never block a call on it */ } let seen = false; try { seen = readFileSync(join(ACP_DIR, "nocred-session"), "utf8").trim() === sessionId; } catch {} if (!seen) { try { writeFileSync(join(ACP_DIR, "nocred-session"), sessionId); } catch { /* at worst the banner repeats */ } process.stdout.write(JSON.stringify({ systemMessage: "[ACP] ⚠ UNGOVERNED: no API key found at ~/.acp/credentials — tool calls are running WITHOUT policy checks, and ACP has no record of them. " + "Get your key at https://cloud.agenticcontrolplane.com, then: echo 'YOUR_API_KEY' > ~/.acp/credentials — and restart this session.", })); } process.exit(0); } if (LOCAL) { await runLocal(input); process.exit(0); } async function runLocal(input) { const audit = (obj) => { try { appendFileSync(join(ACP_DIR, "audit.jsonl"), JSON.stringify(obj) + "\n"); } catch {} }; const ev = typeof input.hook_event_name === "string" ? input.hook_event_name : "PreToolUse"; if (ev === "PostToolUse") { audit({ ts: new Date().toISOString(), event: "post", client: ACP_CLIENT, tool: input.tool_name }); return; } let policy = { default: "allow", rules: {} }; try { policy = JSON.parse(readFileSync(join(ACP_DIR, "policy.json"), "utf8")); } catch {} let decide; try { ({ decide } = await import("./decide.mjs")); } catch { // Engine missing/corrupt → never brick, but NEVER silently: say it loud // and leave an audit line, same contract as the cloud path's fail-open. audit({ ts: new Date().toISOString(), event: "pre", client: ACP_CLIENT, tool: input.tool_name, decision: "allow", source: "fail-open", reason: "local engine unavailable (~/.acp/decide.mjs)" }); process.stdout.write(JSON.stringify({ systemMessage: "[ACP·local] ⚠ decision engine unavailable (~/.acp/decide.mjs) — this call ran UNGOVERNED and was allowed. Re-run the installer to restore it.", })); return; } const d = decide(input.tool_name, input.tool_input, policy); audit({ ts: new Date().toISOString(), event: "pre", client: ACP_CLIENT, tool: input.tool_name, classified: d.classified, decision: d.decision, source: d.source, reason: d.reason }); if (d.decision === "deny") { process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: `[ACP] ${d.reason}` }, systemMessage: `[ACP·local] Blocked: ${d.reason}`, })); } else if (d.decision === "ask") { process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "ask", permissionDecisionReason: `[ACP] ${d.reason}` }, })); } // allow → no output (silent allow, still logged to audit.jsonl) } const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json", "X-GS-Client": `${ACP_CLIENT}/${PLUGIN_VERSION}`, }; function resolveAgentTier() { const mode = input.permission_mode; if (mode === "auto") return "subagent"; if (mode === "bypassPermissions") return "background"; return "interactive"; } async function handlePreToolUse() { const body = JSON.stringify({ tool_name: input.tool_name, tool_input: input.tool_input, session_id: input.session_id, cwd: input.cwd, hook_event_name: "PreToolUse", agent_tier: resolveAgentTier(), permission_mode: input.permission_mode, }); const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 4000); function deny(reason) { process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: `[ACP] ${reason}`, }, systemMessage: `[ACP] Blocked: ${reason}`, })); process.exit(0); } // Fail mode when ACP is unreachable — a policy DENY always blocks; this // only governs infrastructure failures. POLICY (2026-07-13): everything // fails OPEN by default — like starting in audit mode, we never brick an // agent the user didn't explicitly choose to have brick. Every fail-open // call carries a loud "this ran UNGOVERNED" message. Opt in to blocking: // echo closed > ~/.acp/failmode (or set ACP_FAIL_MODE=closed) function readFailMode() { const env = (process.env.ACP_FAIL_MODE || "").trim().toLowerCase(); if (env === "open" || env === "closed") return env; try { const v = require("fs").readFileSync(require("os").homedir() + "/.acp/failmode", "utf8").trim().toLowerCase(); if (v === "open" || v === "closed") return v; } catch {} return "open"; } function unreachable(detail) { if (readFailMode() === "closed") { deny(`ACP unreachable — tool call blocked (fail-closed). ${detail}`); return; } process.stdout.write(JSON.stringify({ systemMessage: `[ACP] ⚠ gateway unreachable (${detail}) — this call was ALLOWED but ran UNGOVERNED and was not logged. Fail-open is ACP's default for every agent (we never brick you without your say-so); to block instead: echo closed > ~/.acp/failmode`, })); process.exit(0); } // A 401/403 is NOT the gateway being down — it is this machine's key // being revoked, mistyped, or from a deleted workspace. Live session // 2026-09-07: a returning user's May key had been revoked; every hook // call for six hours read "gateway unreachable (HTTP 401)", which sounds // like our outage, and the user ran ungoverned until they happened to // visit the console. Say what it is and what fixes it. function keyRejected(status) { if (readFailMode() === "closed") { deny(`ACP rejected this machine's key (HTTP ${status}) — tool call blocked (fail-closed). Re-run the installer or save a new key to ~/.acp/credentials.`); return; } process.stdout.write(JSON.stringify({ systemMessage: `[ACP] ⚠ KEY REJECTED (HTTP ${status}): the key in ~/.acp/credentials is revoked or invalid — this call was ALLOWED but ran UNGOVERNED and was not logged, and every call will until it is fixed. Fix: re-run the installer (curl -sf https://agenticcontrolplane.com/install.sh | bash) or create a key at https://cloud.agenticcontrolplane.com/settings/api-keys and save it: echo 'gsk_...' > ~/.acp/credentials`, })); process.exit(0); } try { const res = await fetch(`${ACP_API}/govern/tool-use`, { method: "POST", headers, body, signal: controller.signal }); clearTimeout(timeout); if (res.status === 401 || res.status === 403) { keyRejected(res.status); return; } if (!res.ok) { unreachable("HTTP " + res.status); return; } const data = await res.json(); if (data.decision === "deny") deny(data.reason || "denied by policy"); // "ask" surfaces the approval to the harness. Codex has no ask // primitive, so it blocks there instead (same mapping as the canonical // plugin hook). Previously this branch was missing entirely and an ask // verdict silently ALLOWED — the exact fell-open bug the gateway's // step_up→deny change was shipped to kill. if (data.decision === "ask") { if (ACP_CLIENT === "codex") deny(data.reason || "requires approval"); process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "ask", permissionDecisionReason: `[ACP] ${data.reason || "requires approval"}`, }, })); process.exit(0); } // Unknown decision values fail CLOSED: a verdict this hook doesn't // understand must never fall open. Distinct from the outage posture — // the server answered; we just can't obey it correctly. if (data.decision !== undefined && data.decision !== "allow") { deny(`unrecognized decision "${data.decision}" — re-run the ACP installer to update this hook`); } // Grace-zone billing warning: allowed call, loud message on every one. if (data.warning) { process.stdout.write(JSON.stringify({ systemMessage: `⚠ ${data.warning}` })); } } catch { unreachable("no response within 4s"); } finally { clearTimeout(timeout); } process.exit(0); } // Cost from the hook, no proxy required. The harness transcript (Claude // Code's session JSONL, handed to us as transcript_path) records every // model turn's usage. Read only what arrived since the last report — a // per-transcript byte offset in ~/.acp/transcript-offsets.json — and ship // the turns as `model_usage` on the tool-output call we already make. The // gateway prices them at list rates and labels them API-rate equivalents. // Bounded: at most 2 MB read and 50 turns sent per call; any failure // returns nothing and never delays the hook. const TRANSCRIPT_OFFSETS = join(ACP_DIR, "transcript-offsets.json"); const TRANSCRIPT_READ_CAP = 2 * 1024 * 1024; const TRANSCRIPT_MAX_TURNS = 50; function collectTranscriptUsage(path) { if (typeof path !== "string" || !path || !existsSync(path)) return undefined; let offsets = {}; try { offsets = JSON.parse(readFileSync(TRANSCRIPT_OFFSETS, "utf8")) || {}; } catch { offsets = {}; } let size = 0; try { size = statSync(path).size; } catch { return undefined; } let start = typeof offsets[path] === "number" && offsets[path] <= size ? offsets[path] : 0; if (size - start > TRANSCRIPT_READ_CAP) start = size - TRANSCRIPT_READ_CAP; if (size <= start) return undefined; let chunk = ""; try { const fd = openSync(path, "r"); try { const buf = Buffer.alloc(size - start); readSync(fd, buf, 0, buf.length, start); chunk = buf.toString("utf8"); } finally { closeSync(fd); } } catch { return undefined; } // Only consume complete lines; a partial trailing line waits for next time. const lastNl = chunk.lastIndexOf("\n"); if (lastNl < 0) return undefined; const consumed = Buffer.byteLength(chunk.slice(0, lastNl + 1), "utf8"); const turns = []; for (const line of chunk.slice(0, lastNl).split("\n")) { if (!line || line.indexOf('"usage"') < 0) continue; let e; try { e = JSON.parse(line); } catch { continue; } const m = e && e.message; const u = m && m.usage; if (!u || typeof u !== "object" || (e.type !== "assistant" && m.role !== "assistant")) continue; const id = (typeof m.id === "string" && m.id) || (typeof e.requestId === "string" && e.requestId) || (typeof e.uuid === "string" && e.uuid); if (!id || typeof m.model !== "string") continue; turns.push({ id, model: m.model, input_tokens: u.input_tokens || 0, cache_read_input_tokens: u.cache_read_input_tokens || 0, cache_creation_input_tokens: u.cache_creation_input_tokens || 0, output_tokens: u.output_tokens || 0, ts: typeof e.timestamp === "string" ? e.timestamp : undefined, }); } // Advance the offset only past what we are sending; keep the file small. try { const keep = {}; let n = 0; for (const [k, v] of Object.entries(offsets)) { if (k !== path && existsSync(k) && n++ < 40) keep[k] = v; } keep[path] = start + consumed; writeFileSync(TRANSCRIPT_OFFSETS, JSON.stringify(keep)); } catch {} // Same-id turns can repeat across streamed chunks; keep the last (fullest). const byId = new Map(); for (const t of turns) byId.set(t.id, t); const out = Array.from(byId.values()).slice(-TRANSCRIPT_MAX_TURNS); return out.length ? out : undefined; } async function handlePostToolUse() { let outputStr = ""; try { const out = input.tool_response ?? input.tool_output ?? input.output; if (typeof out === "string") outputStr = out; else if (out !== undefined && out !== null) outputStr = JSON.stringify(out); } catch { process.exit(0); } if (Buffer.byteLength(outputStr, "utf8") > POST_HOOK_PAYLOAD_CEILING) { outputStr = outputStr.slice(0, POST_HOOK_PAYLOAD_CEILING); } const body = JSON.stringify({ tool_name: input.tool_name, tool_input: input.tool_input, tool_output: outputStr, session_id: input.session_id, cwd: input.cwd, hook_event_name: "PostToolUse", agent_tier: resolveAgentTier(), model_usage: collectTranscriptUsage(input.transcript_path), }); const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 4000); try { const res = await fetch(`${ACP_API}/govern/tool-output`, { method: "POST", headers, body, signal: controller.signal }); clearTimeout(timeout); if (!res.ok) { process.exit(0); } const data = await res.json(); if (data.action === "redact" || data.action === "block") { process.stdout.write(JSON.stringify({ systemMessage: `[ACP] ${data.action === "block" ? "Blocked" : "Flagged"}: ${data.reason || "governance policy"}`, })); } } catch { // silent pass-through } finally { clearTimeout(timeout); } process.exit(0); } const hookEvent = typeof input.hook_event_name === "string" ? input.hook_event_name : "PreToolUse"; if (hookEvent === "PostToolUse") handlePostToolUse(); else handlePreToolUse(); GOVERN GOVERN_BUNDLED_VERSION="$(grep -o 'PLUGIN_VERSION = "[^"]*"' "$GOVERN_BUNDLED" 2>/dev/null | head -1 | sed 's/.*"\(.*\)"/\1/')" if [ -s "$CONFIG_DIR/govern.mjs" ] && _acp_semver_gt "$GOVERN_OLD_VERSION" "$GOVERN_BUNDLED_VERSION" \ && { [ "$LOCAL_MODE" != true ] || grep -q "runLocal" "$CONFIG_DIR/govern.mjs"; }; then rm -f "$GOVERN_BUNDLED" GOVERN_SOURCE="existing copy kept" echo " ${C_DIM}[ACP] kept existing govern.mjs $GOVERN_OLD_VERSION (fetch failed; bundled fallback is older, $GOVERN_BUNDLED_VERSION)${C_RESET}" >&2 elif mv -f "$GOVERN_BUNDLED" "$CONFIG_DIR/govern.mjs"; then : else rm -f "$GOVERN_BUNDLED" echo " ${C_RED}[ACP] WARNING:${C_RESET} could not write the bundled govern.mjs into place — leaving whatever is already there." >&2 fi fi chmod +x "$CONFIG_DIR/govern.mjs" 2>/dev/null || true echo " ${C_GREEN}✓${C_RESET} [ACP] Governance hook installed ($GOVERN_SOURCE)" GOVERN_NEW_VERSION="$(grep -o 'PLUGIN_VERSION = "[^"]*"' "$CONFIG_DIR/govern.mjs" 2>/dev/null | head -1 | sed 's/.*"\(.*\)"/\1/')" if [ "$UPDATE_MODE" = true ]; then echo " ${C_DIM}govern.mjs: ${GOVERN_OLD_VERSION:-none} → ${GOVERN_NEW_VERSION:-unknown}${C_RESET}" fi # Fresh marker on every install/update run (not just --update): the hook # reads its mtime to stay quiet about being outdated for 24h after a # refresh, instead of nagging the same minute it was just brought current. date +%s > "$CONFIG_DIR/.stale-notice" 2>/dev/null || true # ── Shared: write decide.mjs (LOCAL decision engine — no cloud, no login) ── # Mirrors decide.mjs in the repo verbatim. Pure, self-contained; govern.mjs # imports it only in LOCAL mode. cat > "$CONFIG_DIR/decide.mjs" << 'DECIDE' // decide.mjs — LOCAL decision engine for Agentic Control Plane. // // Runs entirely on your machine. No account, no network, no phone-home: it // classifies a tool call, applies a safety floor, and consults your local // policy file (~/.acp/policy.json). This is the same *shape* of decision the // hosted gateway makes — the hosted product adds the tuned risk classifier, // cross-instance limits, team policy sync, cost X-ray, and the console. // // This module is intentionally pure and self-contained (no imports, no I/O) so // it is trivial to review, run offline, and later publish as the open decision // primitive. The dispatcher (govern.mjs) supplies the policy object and writes // the audit line; this file only decides. // // It is mirrored verbatim into install.sh (~/.acp/decide.mjs at install time); // test/mirror.test.mjs fails CI if the two ever diverge. /** Split a command into argv-ish tokens, honoring quotes and stopping at the * first shell control operator (| ; &). Env-assignments and wrappers are kept * as tokens; callers strip them. */ function shellTokens(cmd) { const out = []; let buf = ""; let quote = null; for (const ch of String(cmd)) { if (quote) { if (ch === quote) quote = null; else buf += ch; continue; } if (ch === '"' || ch === "'") { quote = ch; continue; } if (ch === " " || ch === "\t" || ch === "\n") { if (buf) { out.push(buf); buf = ""; } continue; } if (ch === "|" || ch === ";" || ch === "&") { if (buf) { out.push(buf); buf = ""; } break; } buf += ch; } if (buf) out.push(buf); return out; } // Wrappers that prefix another command. `valueFlags` are the flags whose value // is a SEPARATE token (`sudo -u root`, `nice -n 10`); `operands` is how many // positional operands the wrapper itself consumes before the real command // (`timeout [flags] DURATION cmd…`). Skipping flags but not these operands is // exactly the hole of #19: `timeout 5 rm -rf ~` classified as Bash.5. const WRAPPERS = new Map([ ["sudo", { valueFlags: new Set(["-u", "-g", "-h", "-p", "-C", "-D", "-R", "-T", "-U"]), operands: 0 }], ["doas", { valueFlags: new Set(["-u", "-C"]), operands: 0 }], ["env", { valueFlags: new Set(["-u", "-C", "-P", "-S"]), operands: 0 }], ["nice", { valueFlags: new Set(["-n", "--adjustment"]), operands: 0 }], ["nohup", { valueFlags: new Set(), operands: 0 }], ["setsid", { valueFlags: new Set(), operands: 0 }], ["stdbuf", { valueFlags: new Set(["-i", "-o", "-e"]), operands: 0 }], ["timeout", { valueFlags: new Set(["-s", "--signal", "-k", "--kill-after"]), operands: 1 }], ["time", { valueFlags: new Set(), operands: 0 }], ["xargs", { valueFlags: new Set(["-I", "-n", "-P", "-L", "-d", "-a", "-E", "-s"]), operands: 0 }], ["command", { valueFlags: new Set(), operands: 0 }], ["builtin", { valueFlags: new Set(), operands: 0 }], ]); // Shell keywords are never the governed binary: `if rm -rf /; then …` and // `{ rm -rf /; }` must classify as rm, not stall on the keyword. const SHELL_KEYWORDS = new Set(["if", "then", "elif", "else", "fi", "for", "while", "until", "do", "done", "{", "}", "(", ")", "!"]); /** Split a command line into its piped/chained segments (on unquoted | & ; ( ) * and newlines), so every command in a compound line is inspected, not just * the first (e.g. `echo hi && rm -rf ~`, `( rm -rf ~ )`, `$(rm -rf ~)`). */ function splitSegments(cmd) { const segs = []; let buf = ""; let quote = null; for (const ch of String(cmd)) { if (quote) { buf += ch; if (ch === quote) quote = null; continue; } if (ch === '"' || ch === "'") { quote = ch; buf += ch; continue; } if (ch === "|" || ch === "&" || ch === ";" || ch === "\n" || ch === "(" || ch === ")") { if (buf.trim()) segs.push(buf.trim()); buf = ""; continue; } buf += ch; } if (buf.trim()) segs.push(buf.trim()); return segs; } /** Strip leading env-assignments, shell keywords, and benign wrappers — * including each wrapper's own option-arguments and positional operands * (`sudo -u root …`, `timeout 5 …`, `nice -n 10 …`) — and return * { bin, args } where bin is the canonical binary (basename, no path). */ function parseCommand(cmd) { const toks = shellTokens(cmd); let i = 0; let hops = 0; while (i < toks.length && hops++ < 32) { const t = toks[i]; if (t.includes("=") && !t.startsWith("-")) { i++; continue; } // FOO=bar if (SHELL_KEYWORDS.has(t)) { i++; continue; } // if / { / do … const w = WRAPPERS.get(t); if (w) { i++; while (i < toks.length && toks[i].startsWith("-")) { const flag = toks[i]; i++; if (w.valueFlags.has(flag)) i++; // sudo -u USER } for (let n = 0; n < w.operands && i < toks.length; n++) i++; // timeout DURATION continue; } return { bin: t.split("/").pop(), args: toks.slice(i + 1) }; } return { bin: "", args: [] }; } /** Canonical binary of a shell command (basename), skipping env + wrappers. */ function canonicalBinary(cmd) { return parseCommand(cmd).bin; } /** First http(s) host in a command (for curl/wget), else undefined. */ function firstHost(cmd) { const m = String(cmd).match(/https?:\/\/([^/\s"']+)/i); if (!m) return undefined; return m[1].replace(/^www\./, "").toLowerCase(); } function safeParse(s) { try { return JSON.parse(s); } catch { return {}; } } // Shell subcommands worth policy granularity: `git push` should be governable // without also governing `git status`. Keep this small and obvious. const SUBCOMMAND_BINS = new Set(["git", "gh", "docker", "kubectl", "npm", "pnpm", "yarn", "pip", "pip3", "gcloud", "aws", "systemctl"]); // Global flags whose VALUE is a separate token, so the value is never // mistaken for the subcommand: `git -C /repo push` is a push (was the // malformed key "Bash.git.." — #19), `kubectl -n prod delete` is a delete. const FLAGS_WITH_VALUE = new Set(["-C", "-c", "-H", "-n", "-R", "--git-dir", "--work-tree", "--namespace", "--context", "--cluster", "--kubeconfig", "--prefix", "--profile", "--project", "--config", "--repo"]); /** First non-flag argument (the subcommand), lowercased, or undefined — * skipping over flags AND their separate-token values. */ function firstSubcommand(args) { for (let i = 0; i < args.length; i++) { const a = args[i]; if (a.startsWith("-")) { if (FLAGS_WITH_VALUE.has(a)) i++; // git -C /repo continue; } return a.toLowerCase(); } return undefined; } // ── Compound-command classification ─────────────────────────────────── // A compound command classifies by its MOST PRIVILEGED segment, and decide() // policy-checks EVERY segment (strictest verdict wins) — classifying by the // first segment let `true && gcloud …` run under Bash.true. Rank // mirrors the gateway's fix for this class of bypass: benign // navigational bins lose to unknown bins, which lose to privileged bins. /** Benign / navigational binaries — never the interesting part of a * compound command. */ const BENIGN_BINS = new Set([ "cd", "echo", "printf", "true", "false", "pwd", "ls", "cat", "head", "tail", "less", "more", "grep", "rg", "wc", "sort", "uniq", "cut", "tr", "date", "sleep", "which", "type", "test", "[", "[[", "dirname", "basename", "readlink", "ps", "diff", "jq", "yq", "tee", "read", "exit", "return", "wait", "export", "set", "unset", "shift", "local", "declare", ]); /** Binary classes that outrank an unknown binary when picking a compound * command's classification: deploy/infra, source control, deletion, network * egress, db clients, interpreters. */ const PRIVILEGED_BINS = new Set([ "gcloud", "aws", "azure", "firebase", "terraform", "docker", "kubectl", "git", "gh", "npm", "pnpm", "yarn", "pip", "pip3", "rm", "mv", "chmod", "chown", "curl", "wget", "ssh", "scp", "rsync", "kill", "sed", "find", "psql", "mysql", "mariadb", "sqlite3", "systemctl", "launchctl", "powershell", "pwsh", "python", "python3", "node", "ruby", "perl", "cargo", "go", "make", "stripe", "vercel", "flyctl", "fly", "heroku", "tar", "open", "sh", "bash", "zsh", "dash", "ksh", "fish", "csh", "tcsh", "eval", ]); /** Privilege rank for most-privileged-segment selection: benign 0, * unknown 1, privileged 2. Ties resolve to the EARLIEST unit. */ function privilegeRank(bin) { if (BENIGN_BINS.has(bin)) return 0; if (PRIVILEGED_BINS.has(bin) || isShellBin(bin)) return 2; // every shell, not only the listed ones return 1; } const COMMAND_WORD_RE = /^(?:\[\[?|[\w.][\w.+-]*)$/; /** Every governed unit of a Bash command: one per segment, plus the payload * of any `bash -c "…"` / `eval …` hand-off (recursed, capped), so neither a * benign prefix nor an interpreter hop hides a unit from policy. */ function commandUnits(cmd, depth = 0) { const units = []; if (depth > 3) return units; for (const seg of splitSegments(cmd)) { const { bin, args } = parseCommand(seg); // A residue like `$` from `$(` is not a command word, and must not name // the call Bash.$ — no rule can be written against it. if (!bin || !COMMAND_WORD_RE.test(bin)) continue; units.push({ bin, args, seg }); const inner = innerShellCommand(bin, args); if (inner) units.push(...commandUnits(inner, depth + 1)); } return units; } /** Dotted policy key for one command unit. */ function unitKey(u) { if (u.bin === "curl" || u.bin === "wget") { const host = firstHost(u.seg); return host ? `Bash.curl.${host}` : "Bash.curl"; } if (SUBCOMMAND_BINS.has(u.bin)) { const sub = firstSubcommand(u.args); return sub ? `Bash.${u.bin}.${sub}` : `Bash.${u.bin}`; } return `Bash.${u.bin}`; } /** The units of a Bash-shaped tool call, or null for other tools. */ function bashUnits(toolName, toolInput) { const name = String(toolName || ""); if (name !== "Bash" && name !== "run_terminal_cmd" && name !== "shell") return null; const input = typeof toolInput === "string" ? safeParse(toolInput) : (toolInput || {}); return commandUnits(String(input.command || input.cmd || "")); } /** * Classify a tool call into a dotted policy key, e.g. "Bash.rm", * "Bash.git.push", "Bash.curl.api.github.com", "Write", "WebFetch.example.com". * A non-empty command with no classifiable unit is the explicit * "Bash.unknown" (never a malformed or wrong-segment key): still governable * by a Bash.unknown rule, still falls back to "Bash" in the policy walk, and * honestly labeled as unparsed in the audit line rather than silently benign. */ export function classifyTool(toolName, toolInput) { const name = String(toolName || ""); const input = typeof toolInput === "string" ? safeParse(toolInput) : (toolInput || {}); if (name === "Bash" || name === "run_terminal_cmd" || name === "shell") { const cmd = String(input.command || input.cmd || ""); const units = commandUnits(cmd); if (!units.length) return cmd.trim() ? "Bash.unknown" : "Bash"; let best = units[0]; for (const u of units) if (privilegeRank(u.bin) > privilegeRank(best.bin)) best = u; return unitKey(best); } if (name === "Write" || name === "Edit" || name === "MultiEdit" || name === "create_file" || name === "edit_file") { return "Write"; } if (name === "Read" || name === "read_file" || name === "Glob" || name === "Grep" || name === "LS") { return "Read"; } if (name === "WebFetch" || name === "WebSearch" || name === "web_search") { const host = firstHost(input.url || ""); return host ? `WebFetch.${host}` : "WebFetch"; } return name; } // ── Safety floor ────────────────────────────────────────────────────── // Obvious, catastrophic, hard-to-undo actions denied regardless of policy. // Deliberately conservative and OBVIOUS (not secret heuristics — the tuned // detector lives in the hosted product). The bar: "no legitimate agent task // ever needs this." Token-based where flag order/spelling varies, so the // common phrasings can't slip past (rm -rf ~/ , rm -r -f / , git push -f , …). /** Does this arg list carry short flag `letter` (e.g. -rf, -f) or `--long`? */ function hasShortOrLongFlag(args, letter, longName) { for (const a of args) { if (a === `--${longName}`) return true; if (/^-[a-z]+$/i.test(a) && a.slice(1).toLowerCase().includes(letter)) return true; } return false; } const RM_DANGER_TARGETS = new Set(["/", "/.", "~", "~/", "$HOME", "$HOME/", "${HOME}", ".", "./", "*", "/*", "./*", "~/*"]); /** rm with BOTH recursive and force, aimed at a root/home/cwd/glob target. */ function rmForceFloor(bin, args) { if (bin !== "rm") return null; const recursive = hasShortOrLongFlag(args, "r", "recursive"); const force = hasShortOrLongFlag(args, "f", "force"); if (!recursive || !force) return null; const targets = args.filter((a) => !a.startsWith("-")); for (const t of targets) { const norm = t.replace(/\/+$/, ""); // trailing slash → same target (~/ ≡ ~) if (RM_DANGER_TARGETS.has(t) || RM_DANGER_TARGETS.has(norm) || norm === "") { return "recursive force-delete of a root/home path"; } } return null; } // Force-push is not on this floor (decided 2026-09-23): it is an ask // on every surface, via FORCE_PUSH_RE in the destructive floor, so the same // push behaves the same locally and on the gateway. // Shells whose `-c ` argument is itself a command line: recurse the // floor into it so `bash -c "rm -rf ~"` can't launder past token inspection. // A shape, not a list: any short word ending in "sh" — ash, mksh and // whatever comes next — except ssh, whose -c takes a cipher. function isShellBin(bin) { return bin !== "ssh" && /^[a-z]{0,3}sh$/.test(bin); } /** If this command hands a string to another interpreter (`bash -c '…'`, * `eval …`), return that inner command line; else undefined. */ function innerShellCommand(bin, args) { if (isShellBin(bin)) { for (let i = 0; i < args.length; i++) { if (/^-[a-z]*c[a-z]*$/i.test(args[i])) return args[i + 1]; } return undefined; } if (bin === "eval") return args.join(" "); return undefined; } /** Token floors, per segment, recursing one level into shell -c / eval. */ function tokenFloorScan(cmd, depth = 0) { if (depth > 3) return null; for (const seg of splitSegments(cmd)) { const { bin, args } = parseCommand(seg); const hit = rmForceFloor(bin, args); if (hit) return hit; const inner = innerShellCommand(bin, args); if (inner) { const h = tokenFloorScan(inner, depth + 1); if (h) return h; } } return null; } const REGEX_RULES = [ [/\bmkfs\.[a-z0-9]+\b|\bmkfs\s/i, "filesystem format (mkfs)"], [/\bdd\b[^|;&]*\bof=\/dev\/(sd|nvme|disk|hd)/i, "raw disk overwrite (dd of=/dev/…)"], [/:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/, "fork bomb"], [/\bchmod\s+-R\s+0*777\s+\/(\s|$)/i, "recursive chmod 777 on /"], [/>\s*\/dev\/(sd|nvme|disk|hd)[a-z0-9]*/i, "redirect over a raw disk device"], ]; /** * The safety floor: obvious, catastrophic commands denied regardless of policy. * Returns a deny reason, or null. */ export function hardlineFloor(toolName, toolInput) { const name = String(toolName || ""); if (name !== "Bash" && name !== "run_terminal_cmd" && name !== "shell") return null; const input = typeof toolInput === "string" ? safeParse(toolInput) : (toolInput || {}); const cmd = String(input.command || input.cmd || ""); // Token floors run per-segment so a catastrophe hidden after `&&`/`;`/`|` // (e.g. `echo ok && rm -rf ~`) is still caught, and recurse into // `bash -c "…"` / `eval …` so hand-off to another shell can't launder it. const tokenFloor = tokenFloorScan(cmd); if (tokenFloor) return tokenFloor; const c = cmd.replace(/\s+/g, " ").trim(); for (const [re, why] of REGEX_RULES) if (re.test(c)) return why; return null; } // ── Context guard ───────────────────────────────────────────────────── // Whole-file reads are the cheapest thing an agent does and the most // expensive thing it puts in a frontier model's context. The guard sizes a // read BEFORE it happens: Read (offset/limit-aware) and the shell dumpers // (cat/head/tail/less/more/bat). Piped or redirected dumps pass — those are // targeted. readIntent() is pure parsing; the dispatcher counts the lines // (I/O) and hands them back as `context.files`. const DUMP_BINS = new Set(["cat", "head", "tail", "less", "more", "bat", "batcat"]); /** Split on unquoted | & ; newline, keeping the operator that FOLLOWS each * segment so a pipe after a dump can be told from a chain before it. */ function splitSegmentsWithOps(cmd) { const out = []; let buf = ""; let quote = null; for (const ch of String(cmd)) { if (quote) { buf += ch; if (ch === quote) quote = null; continue; } if (ch === '"' || ch === "'") { quote = ch; buf += ch; continue; } if (ch === "|" || ch === "&" || ch === ";" || ch === "\n") { if (buf.trim()) out.push({ seg: buf.trim(), op: ch }); buf = ""; continue; } buf += ch; } if (buf.trim()) out.push({ seg: buf.trim(), op: "" }); return out; } function unquote(t) { return String(t).replace(/^(['"])(.*)\1$/, "$2"); } function toCount(v) { if (v === null || v === undefined || v === "") return null; const n = Number(v); return Number.isFinite(n) && n >= 0 ? Math.floor(n) : null; } /** head/tail line limits: -N, -nN, -n N, --lines=N, --lines N. Byte ranges * (-c) and follow (-f) are targeted by construction. */ function dumpArgs(bin, args) { let limit = null; let targeted = false; const paths = []; for (let i = 0; i < args.length; i++) { const a = args[i]; if (a === "--") { for (const rest of args.slice(i + 1)) paths.push(unquote(rest)); break; } if (!a.startsWith("-") || a === "-") { paths.push(unquote(a)); continue; } if (bin === "head" || bin === "tail") { let m; if ((m = a.match(/^-(\d+)$/))) { limit = toCount(m[1]); continue; } if ((m = a.match(/^-n\+?(\d+)$/))) { limit = toCount(m[1]); continue; } if ((m = a.match(/^--lines=\+?(\d+)$/))) { limit = toCount(m[1]); continue; } if (a === "-n" || a === "--lines") { limit = toCount(String(args[i + 1] || "").replace(/^\+/, "")); i++; continue; } if (a === "-c" || a === "--bytes") { targeted = true; i++; continue; } if (/^-c\d+$/.test(a) || /^--bytes=/.test(a)) { targeted = true; continue; } if (a === "-f" || a === "-F" || a === "--follow") { targeted = true; continue; } } if (bin === "bat" || bin === "batcat") { let m; if ((m = a.match(/^(?:-r|--line-range)=?(\d+):(\d+)$/))) { limit = Math.max(0, toCount(m[2]) - toCount(m[1]) + 1); continue; } if (a === "-r" || a === "--line-range") { const r = String(args[i + 1] || "").match(/^(\d+):(\d+)$/); if (r) limit = Math.max(0, toCount(r[2]) - toCount(r[1]) + 1); i++; continue; } } } // head/tail with no explicit count print 10 lines. if ((bin === "head" || bin === "tail") && limit === null && !targeted) limit = 10; return { limit, targeted, paths }; } /** * What would this call pull into context? Returns null when the call is not * a whole-file read, else { via, paths, offset, limit, targeted }: * via "Read" | "Bash.cat" | "Bash.head" | … * paths files the dispatcher should size * offset 1-based start line (Read) — lines before it are not read * limit max lines read, or null for "to the end" * targeted true when the shape is already narrow (byte-ranged, followed); * the guard never blocks these */ export function readIntent(toolName, toolInput) { const name = String(toolName || ""); const input = typeof toolInput === "string" ? safeParse(toolInput) : (toolInput || {}); if (name === "Read" || name === "read_file") { const path = input.file_path || input.path || input.target_file || ""; if (!path) return null; const offset = toCount(input.offset); const limit = toCount(input.limit); return { via: "Read", paths: [String(path)], offset: offset && offset > 0 ? offset : null, limit: limit && limit > 0 ? limit : null, targeted: false }; } if (name === "Bash" || name === "run_terminal_cmd" || name === "shell") { const raw = input.command || input.cmd || ""; const cmd = Array.isArray(raw) ? raw.map(String).join(" ") : String(raw); if (!cmd.trim()) return null; for (const { seg, op } of splitSegmentsWithOps(cmd)) { const { bin, args } = parseCommand(seg); if (!DUMP_BINS.has(bin)) continue; if (op === "|") continue; // dump feeds a filter — targeted if (/(^|[^\\])>/.test(seg)) continue; // redirected to a file — never enters context const { limit, targeted, paths } = dumpArgs(bin, args); const files = paths.filter((p) => p && p !== "-"); if (!files.length) continue; // reads stdin return { via: `Bash.${bin}`, paths: files, offset: null, limit, targeted }; } return null; } return null; } const GUARD_MODES = new Set(["off", "shadow", "enforce"]); /** * Size a read against the guard. `files` maps path → { lines, bytes } as the * dispatcher measured them (unmeasured paths are skipped — the tool surfaces * its own not-found error). Returns null when nothing applies, else * { mode, action, lines, effectiveLines, estTokens, maxLines, paths, via, guidance }. */ export function contextGuard(intent, files, guard) { if (!intent || !guard || typeof guard !== "object") return null; const mode = GUARD_MODES.has(guard.mode) ? guard.mode : "off"; if (mode === "off") return null; const maxLines = toCount(guard.maxLines); if (!maxLines) return null; if (intent.targeted) return null; const known = intent.paths.map((p) => [p, files && files[p]]).filter(([, f]) => f && Number.isFinite(f.lines)); if (!known.length) return null; let lines = 0, effectiveLines = 0, bytes = 0; for (const [, f] of known) { lines += f.lines; let eff = f.lines; if (intent.offset) eff = Math.max(0, eff - (intent.offset - 1)); if (intent.limit !== null && intent.limit !== undefined) eff = Math.min(eff, intent.limit); effectiveLines += eff; bytes += Number.isFinite(f.bytes) ? f.bytes : 0; } if (effectiveLines <= maxLines) return null; const avgBytesPerLine = lines > 0 && bytes > 0 ? bytes / lines : 40; const estTokens = Math.round((effectiveLines * avgBytesPerLine) / 4); const action = guard.action === "ask" ? "ask" : "deny"; return { mode, action, lines, effectiveLines, estTokens, maxLines, paths: known.map(([p]) => p), via: intent.via, guidance: typeof guard.guidance === "string" && guard.guidance.trim() ? guard.guidance.trim() : "" }; } /** Default steer, per harness. A block always names the sanctioned path. */ export function contextGuardSteer(harness) { if (harness === "codex") { return "Read just the section you need (sed -n 'START,ENDp' FILE, or grep -n PATTERN FILE), or send the whole-file read to a subagent so it stays out of this context."; } return "Read just the section you need (offset/limit, or grep for the symbol), or hand the whole-file read to a subagent so it stays out of this context."; } /** * Walk a dotted key from most-specific to least, e.g. * "Bash.curl.api.github.com" → [..., "Bash.curl", "Bash"]. */ export function candidates(key) { const parts = String(key).split("."); const out = []; for (let i = parts.length; i >= 1; i--) out.push(parts.slice(0, i).join(".")); return out; } const VALID = new Set(["allow", "ask", "deny"]); // ── Destructive floor (ask-level) ────────────────────────── // One rung below the hardline floor: things a human always wants to be asked // about, in every mode — a force push, destructive SQL handed to a database // client, a remote download piped into a shell, a recursive delete outside // the working directory. Never a deny; a policy deny still wins. Scans what // will EXECUTE, not what appears: a heredoc body written to a file and quoted // prose cannot fire it, and the SQL a client is handed is read in every // spelling (flag, positional, here-string, heredoc, piped literal). Same // rules and fixtures as the gateway's floor, so an offline call and a // governed call agree. const INTERPRETER_BINS = new Set(["sh", "bash", "zsh", "dash", "ksh", "psql", "pgcli", "mysql", "mariadb", "mycli", "sqlite3", "sqlite", "duckdb", "clickhouse-client", "sqlcmd", "python", "python3", "node", "perl", "ruby", "php", "osascript"]); const HEREDOC_RE = /<<(?!<)-?\s*(?:"([A-Za-z_][\w-]*)"|'([A-Za-z_][\w-]*)'|\\?([A-Za-z_][\w-]*))/; /** Drop the bodies of heredocs whose consumer does not execute them * (`cat > f <<'EOF'`, `tee`, `gh … --body-file -`). Bodies fed to a shell, * SQL client, or interpreter stay. An unquoted delimiter still expands * `$( … )` in the body, so those substitutions are kept in its place. */ export function stripDataHeredocs(cmd) { const s = String(cmd); if (!s.includes("<<")) return s; const lines = s.split("\n"); const out = []; for (let i = 0; i < lines.length; i++) { const line = lines[i]; const m = line.match(HEREDOC_RE); if (!m) { out.push(line); continue; } const delim = m[1] ?? m[2] ?? m[3]; const quoted = m[1] !== undefined || m[2] !== undefined || m[0].includes("\\"); let end = lines.length; for (let j = i + 1; j < lines.length; j++) if (lines[j].trim() === delim) { end = j; break; } const body = lines.slice(i + 1, end); out.push(line); const { bin, args } = parseCommand(line.slice(0, m.index)); const shellDashC = isShellBin(bin) && args.some((a) => /^-[a-z]*c[a-z]*$/i.test(a)); if (INTERPRETER_BINS.has(bin) && !shellDashC) out.push(...body); else if (!quoted) { const subs = body.join("\n").match(/\$\([^)]*\)|`[^`]*`/g); if (subs) out.push(subs.join(" ")); } if (end < lines.length) out.push(lines[end]); i = end; } return out.join("\n"); } const SQL_CLIENTS = { psql: { opts: ["-c", "--command"] }, pgcli: { opts: ["-c", "--command"] }, mysql: { opts: ["-e", "--execute"] }, mariadb: { opts: ["-e", "--execute"] }, mycli: { opts: ["-e", "--execute"] }, sqlite3: { opts: ["-cmd"], pos: 1 }, sqlite: { opts: ["-cmd"], pos: 1 }, duckdb: { opts: ["-c", "-s", "--command"], pos: 1 }, "clickhouse-client": { opts: ["-q", "--query"] }, sqlcmd: { opts: ["-Q", "-q"] }, }; /** "drop" | "truncate" | "delete" (DELETE with no WHERE) | null. */ export function sqlStatementKind(sql) { const s = String(sql).replace(/--[^\n]*/g, " ").replace(/\/\*[\s\S]*?\*\//g, " "); if (/\bDROP\s+(?:TABLE|DATABASE|SCHEMA|INDEX|VIEW|SEQUENCE|USER|ROLE)\b/i.test(s)) return "drop"; if (/\bTRUNCATE\b/i.test(s)) return "truncate"; for (const st of s.split(";")) if (/\bDELETE\s+FROM\b/i.test(st) && !/\bWHERE\b/i.test(st)) return "delete"; return null; } /** Every SQL statement a command hands to a database client. Text that is * not handed to a client (`echo "DROP …"`, a grep pattern) is not SQL. */ export function sqlPayloads(cmd) { const out = []; const text = stripDataHeredocs(cmd); const segs = splitSegmentsWithOps(text); for (let i = 0; i < segs.length; i++) { const { bin, args } = parseCommand(segs[i].seg); const spec = SQL_CLIENTS[bin]; if (!spec) continue; const positionals = []; for (let k = 0; k < args.length; k++) { const a = args[k]; let matched = false; for (const opt of spec.opts) { if (a === opt) { if (args[k + 1] !== undefined) out.push(args[++k]); matched = true; break; } if (a.startsWith(`${opt}=`)) { out.push(a.slice(opt.length + 1)); matched = true; break; } if (opt.length === 2 && !a.startsWith("--") && a.startsWith(opt) && a.length > 2) { out.push(a.slice(2)); matched = true; break; } } if (matched) continue; if (a.startsWith("<<<")) { const rest = a.slice(3) || args[++k] || ""; if (rest) out.push(rest); continue; } if (a.startsWith("<<")) continue; // heredoc marker; body handled below if (!a.startsWith("-")) positionals.push(a); } if (spec.pos !== undefined) out.push(...positionals.slice(spec.pos)); // A literal producer piped in: `echo "TRUNCATE t" | psql db`. if (i > 0 && segs[i - 1].op === "|") { const p = parseCommand(segs[i - 1].seg); if (p.bin === "echo" || p.bin === "printf") { const lit = p.args.filter((x) => !x.startsWith("-")).join(" "); if (lit) out.push(lit); } } } // Heredoc bodies fed to a client (kept verbatim by stripDataHeredocs). const lines = text.split("\n"); for (let i = 0; i < lines.length; i++) { const m = lines[i].match(HEREDOC_RE); if (!m) continue; if (!SQL_CLIENTS[parseCommand(lines[i].slice(0, m.index)).bin]) continue; const delim = m[1] ?? m[2] ?? m[3]; const body = []; for (let j = i + 1; j < lines.length && lines[j].trim() !== delim; j++) body.push(lines[j]); if (body.length) out.push(body.join("\n")); } return out.map((x) => x.trim()).filter(Boolean); } // `+main` forces as surely as `+main:main`. const FORCE_PUSH_RE = /\bgit\b[^|;&\n]*\bpush\b[^|;&\n]*(?:\s--force(?!-with-lease|-if-includes)\b|\s-[a-eg-zA-Z]*f[a-zA-Z]*(?=\s|$)|\s\+[^\s:]+(?::|(?=\s|$)))/; const PIPE_TO_SHELL_RE = /\b(?:curl|wget)\b[^|;&\n]*\|\s*(?:sudo\s+(?:-\S+\s+)*)?(?:\S*\/)?(?!ssh\b)[a-z]{0,3}sh\b/; const SHELL_OF_DOWNLOAD_RE = /\b(?!ssh\b)[a-z]{0,3}sh\s+(?:-[a-zA-Z]+\s+)*(?:-c\s+["']?\$\(\s*(?:curl|wget)\b|<\s* ask > allow) — so `true && gcloud …` cannot // slip a gcloud rule behind a benign first segment (#18). const units = bashUnits(toolName, toolInput); const keys = units && units.length ? [...new Set(units.map(unitKey))] : [key]; let hit = null; for (const k of keys) { for (const cand of candidates(k)) { const r = rules[cand]; if (VALID.has(r)) { if (!hit || SEVERITY[r] > SEVERITY[hit.r]) hit = { r, cand }; break; } } } const result = hit ? { decision: hit.r, reason: `local policy: ${hit.cand} → ${hit.r}`, source: "policy", classified: key, contextGuard: shadow } : (() => { const def = VALID.has(policy && policy.default) ? policy.default : "allow"; return { decision: def, reason: `local policy: default → ${def}`, source: "default", classified: key, contextGuard: shadow }; })(); // Destructive floor: tightens an allow to ask in every mode. A // policy deny or ask already stands; a policy allow cannot loosen it. if (result.decision === "allow") { const destructive = destructiveFloor(toolName, toolInput, context); if (destructive) { return { decision: "ask", reason: `destructive floor: ${destructive}`, source: "destructive-floor", classified: key, contextGuard: shadow, floor: destructive }; } } return result; } DECIDE chmod +x "$CONFIG_DIR/decide.mjs" # ── Shared: write acp-session-summary (cloud mode only) ──────────────── # End-of-session line printed by the priced launchers (`claude-acp`, # `codex-acp`): what the session cost + a deep link to its X-ray. Shared # across clients so there's one source of truth for the runs-API call and # the formatting; each launcher passes its own clientName prefix so the # summary picks out ITS session, not another client's, from the same # 6-hour window. Written here (before any per-client Step 1x block) so it # exists regardless of which client ends up wiring a wrapper. if [ "$LOCAL_MODE" = false ]; then mkdir -p "$CONFIG_DIR/bin" cat > "$CONFIG_DIR/bin/acp-session-summary" << 'SUMMARY' #!/bin/sh # ACP end-of-session summary — what the session cost + a deep link to its # X-ray. Called by claude-acp / codex-acp on exit; silent on any failure. # $1: clientName prefix to match this launcher's runs (defaults to # claude-c for callers that don't pass one, i.e. claude-acp). ACP_KEY="$(cat "$HOME/.acp/credentials" 2>/dev/null)" [ -z "$ACP_KEY" ] && exit 0 export ACP_KEY node -e ' const key = process.env.ACP_KEY; const prefix = process.argv[1] || "claude-c"; fetch("https://api.agenticcontrolplane.com/api/v1/runs?window=6h", { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(2500) }) .then((r) => r.json()) .then(({ runs }) => { const mine = (runs ?? []).filter((r) => (r.clientName ?? "").startsWith(prefix)).sort((a, b) => b.endMs - a.endMs)[0]; if (!mine) return; const cost = mine.costCents >= 100 ? `$${(mine.costCents / 100).toFixed(2)}` : `${Math.round(mine.costCents * 10) / 10}¢`; const at = mine.byoAuth ? " @ API rates" : ""; const parts = [`${mine.modelCalls} model call${mine.modelCalls === 1 ? "" : "s"}`, `${mine.toolCalls} tool call${mine.toolCalls === 1 ? "" : "s"}`]; if (mine.costCents > 0) parts.push(`${cost}${at}`); if (mine.denies > 0) parts.push(`${mine.denies} denied`); console.log(`\n ACP · session governed: ${parts.join(" · ")}`); // One advice line at the boundary — bias to silence. Fires only when // side-model calls (permission classifiers, titles, subagents on a model // other than this runs main loop) were a real share of model spend. Never // mid-stream, never a nag, never the backfire "refresh" tip. try { const st = (mine.steps || []).filter((s) => s.model); if (st.length >= 5) { const by = {}; for (const s of st) { const b = (by[s.model] = by[s.model] || { loop: 0, cents: 0 }); if (s.kind === "loop") b.loop++; b.cents += s.costCents || 0; } const dom = Object.entries(by).sort((a, b) => (b[1].loop - a[1].loop) || (b[1].cents - a[1].cents))[0][0]; const modelCents = st.reduce((a, s) => a + (s.costCents || 0), 0); const side = st.filter((s) => s.model !== dom); const sideCents = side.reduce((a, s) => a + (s.costCents || 0), 0); const share = modelCents > 0 ? sideCents / modelCents : 0; if (share >= 0.25 && sideCents >= 5) { const other = [...new Set(side.map((s) => s.model))][0]; console.log(` ↳ ${Math.round(share * 100)}% of model spend was side-calls (${other}) you did not invoke — cut them at cloud.agenticcontrolplane.com/cost`); } } } catch (e) { /* advice is best-effort — never break the summary */ } console.log(` → https://cloud.agenticcontrolplane.com/sessions/${encodeURIComponent(mine.runKey)}\n`); }) .catch(() => {}); ' "${1:-claude-c}" 2>/dev/null exit 0 SUMMARY chmod +x "$CONFIG_DIR/bin/acp-session-summary" # acp-update — refresh govern.mjs, every launcher, hook registration, and # directive block for harnesses already detected here, without repeating # device-flow login. Re-runs this same install.sh with --update, which # Step 2 (Authenticate) below short-circuits before any device code is # requested — ~/.acp/credentials is untouched. This is the command the # governance hook points people at once it can tell it's outdated. cat > "$CONFIG_DIR/bin/acp-update" << 'ACPUPDATE' #!/bin/sh # acp-update — refresh the ACP governance hook, launchers, and harness # registrations in place. Never mints a key: no device flow, no prompts. # Safe to run repeatedly. Docs: agenticcontrolplane.com exec curl -sf https://agenticcontrolplane.com/install.sh | bash -s -- --update "$@" ACPUPDATE chmod +x "$CONFIG_DIR/bin/acp-update" # acp — terminal controls for held calls. `acp holds` lists your pending # holds oldest first; `acp deny ` withdraws one. Deny only: a deny can # only stop a call, so it needs no proof a person is present. Approving # still needs a person (console, approval email, or Slack). cat > "$CONFIG_DIR/bin/acp" << 'ACPCLI' #!/usr/bin/env node // acp: terminal controls for ACP holds. Deny only: approving a hold needs a // person (the console, the approval email, or Slack). // // acp holds list your pending holds, oldest first // acp deny ACP-97F4 [reason...] withdraw a hold by code or approval id "use strict"; const { readFileSync } = require("node:fs"); const { homedir } = require("node:os"); const { join } = require("node:path"); const usage = "usage: acp holds | acp deny [reason]"; const [cmd, target, ...rest] = process.argv.slice(2); if (cmd !== "holds" && cmd !== "deny") { console.error(usage); process.exit(2); } let key = ""; try { key = readFileSync(join(homedir(), ".acp", "credentials"), "utf8").trim(); } catch {} if (!key) { console.error("acp: no ~/.acp/credentials. Run the ACP installer first."); process.exit(1); } const base = (process.env.ACP_API_BASE || "https://api.agenticcontrolplane.com") + "/aarm/holds"; const headers = { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }; const age = (s) => (s < 90 ? `${s}s` : s < 5400 ? `${Math.round(s / 60)}m` : `${Math.round(s / 3600)}h`); async function call(url, init = {}) { const r = await fetch(url, { ...init, headers, signal: AbortSignal.timeout(10000) }); let j = {}; try { j = await r.json(); } catch {} if (!r.ok) { console.error(`acp: ${j.hint || j.error || `HTTP ${r.status}`}`); process.exit(1); } return j; } (async () => { if (cmd === "holds") { const j = await call(base); if (!j.holds || !j.holds.length) { console.log("No pending holds."); return; } for (const x of j.holds) { console.log(`${x.code} ${age(x.age_seconds).padStart(4)} ${String(x.tool).padEnd(10)} ${String(x.summary || "").slice(0, 80)}`); } console.log("Deny one: acp deny . Approving needs a person: the console, the email, or Slack."); return; } if (!target) { console.error(usage); process.exit(2); } const body = /^[0-9a-f-]{36}$/i.test(target) ? { approval_id: target } : { code: target }; if (rest.length) body.reason = rest.join(" "); const j = await call(`${base}/deny`, { method: "POST", body: JSON.stringify(body) }); console.log(`Denied ${j.code || target}. The held call will not run.`); })().catch((e) => { console.error(`acp: ${e.message}`); process.exit(1); }); ACPCLI chmod +x "$CONFIG_DIR/bin/acp" # acp-uninstall — the exit, shipped with the entrance. The script itself # is cached into ~/.acp so removal needs no network and no docs page: # getting out must never depend on us being reachable. The curl is only # the fallback for an install that predates the cached copy. curl -sf --max-time 10 "$SITE_BASE/uninstall.sh" -o "$CONFIG_DIR/uninstall.sh" 2>/dev/null || true if [ -s "$CONFIG_DIR/uninstall.sh" ] && ! grep -q 'Agentic Control Plane' "$CONFIG_DIR/uninstall.sh" 2>/dev/null; then rm -f "$CONFIG_DIR/uninstall.sh" fi cat > "$CONFIG_DIR/bin/acp-uninstall" << 'ACPUNINSTALL' #!/bin/sh # acp-uninstall — remove ACP from this machine: hook registrations, # directive blocks, MCP entries, the PATH line, and ~/.acp itself. # Anything you wrote yourself is preserved. --dry-run previews. # Docs: agenticcontrolplane.com/trust LOCAL="${ACP_HOME:-$HOME}/.acp/uninstall.sh" [ -s "$LOCAL" ] && exec bash "$LOCAL" "$@" exec curl -sf https://agenticcontrolplane.com/uninstall.sh | bash -s -- "$@" ACPUNINSTALL chmod +x "$CONFIG_DIR/bin/acp-uninstall" # Put ~/.acp/bin on PATH (idempotent; marked line so upgrades don't stack). # Shared because either priced launcher (claude-acp, codex-acp) needs it — # written here once so a Codex-only machine gets it too, not just Claude. PATH_LINE='export PATH="$HOME/.acp/bin:$PATH" # acp-installer' ADDED_PATH=false for RC in "$HOME/.zshrc" "$HOME/.bashrc"; do if [ -f "$RC" ] && ! grep -q '\.acp/bin' "$RC" 2>/dev/null; then printf '\n%s\n' "$PATH_LINE" >> "$RC" ADDED_PATH=true fi done if [ ! -f "$HOME/.zshrc" ] && [ ! -f "$HOME/.bashrc" ] && ! grep -q '\.acp/bin' "$HOME/.profile" 2>/dev/null; then printf '\n%s\n' "$PATH_LINE" >> "$HOME/.profile" ADDED_PATH=true fi fi # ── Shared: priced-launcher template + agent-directive writer ───────── # Every "-acp" launcher is generated from ONE template, so a lesson # learned on one harness lands in all of them. (2026-09-07: a Codex agent # hand-rolled the provider flag without the key and read three 401s; the # fixes — key export, fail-open, full-path directive — live here, not in # codex-acp.) Per-harness input is only what genuinely differs: # # acp_write_launcher NAME BIN KEY_VAR SUMMARY_PREFIX LAUNCH_SNIPPET # NAME launcher file name (codex-acp) # BIN the plain harness binary; also the fail-open target # KEY_VAR env var this harness's provider/plugin reads the # workspace key from (ACP_KEY, ACP_BEARER_TOKEN, …). # ACP_KEY is always exported as well. # SUMMARY_PREFIX client-name prefix for acp-session-summary ("" = any) # LAUNCH_SNIPPET the lines that run the harness with the ACP provider # selected for THIS launch. Must pass "$@" through and # leave the harness's exit status in $?. May read # $ACP_KEY and $ACP_TRACE_LEVEL. # # acp_write_directive FILE LABEL LAUNCHER BIN [EXTRA_LINE ...] # FILE global instructions file the harness reads at session start # LABEL harness name as the agent knows it ("Codex") # LAUNCHER launcher path as it should appear ("~/.acp/bin/codex-acp"); # "" = no launcher line (governance-only harness) # BIN the plain binary the launcher replaces # EXTRA harness-specific lines, placed before the launcher line # Delimited + idempotent: only the ACP section is replaced on re-run. acp_write_launcher() { _l_name="$1"; _l_bin="$2"; _l_keyvar="$3"; _l_prefix="$4"; _l_launch="$5" mkdir -p "$CONFIG_DIR/bin" _l_snip="$(mktemp "${TMPDIR:-/tmp}/acp-launch.XXXXXX")" printf '%s\n' "$_l_launch" > "$_l_snip" sed -e "s|__NAME__|$_l_name|g" -e "s|__BIN__|$_l_bin|g" -e "s|__KEYVAR__|$_l_keyvar|g" -e "s|__PREFIX__|$_l_prefix|g" << 'LAUNCHER_TEMPLATE' \ | awk -v f="$_l_snip" '/^__LAUNCH__$/ { while ((getline l < f) > 0) print l; close(f); next } { print }' \ > "$CONFIG_DIR/bin/$_l_name" #!/bin/sh # __NAME__ — __BIN__ with the ACP cost X-ray. # Generated by the ACP installer from one shared launcher template: every # -acp is this file with different parameters, so a fix lands in # all of them. Model calls route through the ACP proxy (priced + governed); # your own provider login is forwarded unchanged, never ACP's. Plain # `__BIN__` stays untouched. Docs: agenticcontrolplane.com ACP_KEY="$(cat "$HOME/.acp/credentials" 2>/dev/null)" if [ -z "$ACP_KEY" ]; then echo "__NAME__: no ACP credentials (~/.acp/credentials) — re-run the installer without --local. Starting plain __BIN__." >&2 exec __BIN__ "$@" fi export ACP_KEY __KEYVAR__="$ACP_KEY"; export __KEYVAR__ # Fail-open, same rule as the hook (~/.acp/failmode / ACP_FAIL_MODE): if # the gateway does not answer at all within 2s, start plain __BIN__ and say # so — a session that isn't priced beats no session. `closed` refuses # instead. Probe GET / (any HTTP answer counts as reachable): Cloud Run's # front end intercepts /healthz and 404s it before the container sees it. _acp_fail_mode="${ACP_FAIL_MODE:-$(cat "$HOME/.acp/failmode" 2>/dev/null)}" if [ "$_acp_fail_mode" != "closed" ] && command -v curl >/dev/null 2>&1; then _acp_probe="$(curl -s -o /dev/null -w '%{http_code}' --max-time 2 -H 'Accept: application/json' "${ACP_GOVERN_BASE:-https://api.agenticcontrolplane.com}/" 2>/dev/null)" if [ -z "$_acp_probe" ] || [ "$_acp_probe" = "000" ]; then echo "__NAME__: ACP gateway unreachable — starting plain __BIN__; this session's model calls will not be priced or governed. (echo closed > ~/.acp/failmode to refuse instead.)" >&2 exec __BIN__ "$@" fi fi # Opt-in trace capture for THIS launch (ACP_TRACE_LEVEL=full): the launch # lines below forward it as the x-trace-level header where the harness can. [ -n "$ACP_TRACE_LEVEL" ] && export ACP_TRACE_LEVEL __LAUNCH__ STATUS=$? # End-of-session: what it cost + a link to the X-ray. Never blocks exit. "$HOME/.acp/bin/acp-session-summary" __PREFIX__ 2>/dev/null || true exit $STATUS LAUNCHER_TEMPLATE rm -f "$_l_snip" chmod +x "$CONFIG_DIR/bin/$_l_name" } acp_write_directive() { _d_file="$1"; _d_label="$2"; _d_launcher="$3"; _d_bin="$4"; shift 4 mkdir -p "$(dirname "$_d_file")" [ -f "$_d_file" ] || touch "$_d_file" node -e ' const fs = require("fs"); const [p, label, launcher, bin, ...extra] = process.argv.slice(1); const START = ""; const END = ""; const lines = [START, "## ACP Governance", "", "You are governed by Agentic Control Plane. Every tool call is logged and policy-checked.", ""]; for (const l of extra) lines.push(l); if (launcher) lines.push( "- **Cost X-ray (model calls priced):** when launching " + label + " for a user, use `" + launcher + "`", " instead of `" + bin + "` (full path — it works before a new shell picks up PATH). It reads the workspace", " key from `~/.acp/credentials` and selects the ACP model provider for that launch only; the user\x27s own", " provider login is forwarded unchanged. Do NOT hand-configure the provider or export the key yourself —", " without the key header every model call is a 401. If ACP is unreachable the launcher starts plain `" + bin + "`."); lines.push("", "Activity log: https://cloud.agenticcontrolplane.com/activity", END, ""); const section = lines.join("\n"); let src = ""; try { src = fs.readFileSync(p, "utf8"); } catch {} const s = src.indexOf(START), e = src.indexOf(END); if (s !== -1 && e !== -1 && e > s) { let t = e + END.length; if (src[t] === "\n") t++; src = src.substring(0, s) + section + src.substring(t); } else { if (src && !src.endsWith("\n")) src += "\n"; src += (src ? "\n" : "") + section; } fs.writeFileSync(p, src); ' "$_d_file" "$_d_label" "$_d_launcher" "$_d_bin" "$@" } # ── Step 1a: Claude Code setup ──────────────────────────────────────── ACP_STEP="claude_code" if [ "$HAS_CLAUDE" = true ]; then echo " [Claude Code] Setting up governance..." # ── Preferred path: install the PLUGIN. It carries the hooks, # the /cost-xray + /acp skills, AND the bundled ACP MCP server, with # marketplace version tracking. Falls back to direct hook wiring on # older Claude Code CLIs. # # acp-install#64: `claude plugin install` is a NO-OP on a plugin that is # already installed — it never switches the active version, even after # `marketplace update` has put a newer release in the cache (a machine # sat on 0.27.0 with 0.29.5 downloaded, every installer run "succeeded"). # Only `claude plugin update` switches it. So: update when present, # install when absent, then read the ACTIVE version back from Claude # Code's own registry and compare it with the marketplace manifest — # and print what actually happened, not a hope. CLAUDE_PLUGIN_OK=false CLAUDE_PLUGIN_MARKET_OK=false CLAUDE_PLUGIN_BEFORE="$(_acp_claude_plugin_active_version)" if [ -n "$(_acp_claude_marketplace_version)" ]; then # Marketplace already registered: refresh its clone (add would be a no-op). if claude plugin marketplace update acp >/dev/null 2>&1 \ || claude plugin marketplace add agentic-control-plane/claude-code-acp-plugin >/dev/null 2>&1; then CLAUDE_PLUGIN_MARKET_OK=true fi elif claude plugin marketplace add agentic-control-plane/claude-code-acp-plugin >/dev/null 2>&1 \ || claude plugin marketplace update acp >/dev/null 2>&1; then CLAUDE_PLUGIN_MARKET_OK=true fi if [ "$CLAUDE_PLUGIN_MARKET_OK" = true ]; then if [ -n "$CLAUDE_PLUGIN_BEFORE" ]; then # `plugin update` is missing on older CLIs; the install fallback keeps # the plugin present and the version check below says what it means. claude plugin update agentic-control-plane@acp >/dev/null 2>&1 \ || claude plugin install agentic-control-plane@acp >/dev/null 2>&1 || true else claude plugin install agentic-control-plane@acp >/dev/null 2>&1 || true fi fi CLAUDE_PLUGIN_AFTER="$(_acp_claude_plugin_active_version)" CLAUDE_PLUGIN_MARKET_VER="$(_acp_claude_marketplace_version)" if [ -n "$CLAUDE_PLUGIN_AFTER" ] || claude plugin list 2>/dev/null | grep -q "agentic-control-plane"; then CLAUDE_PLUGIN_OK=true fi CLAUDE_SETTINGS="$HOME/.claude/settings.json" mkdir -p "$HOME/.claude" if [ ! -f "$CLAUDE_SETTINGS" ]; then echo '{}' > "$CLAUDE_SETTINGS" fi if [ "$CLAUDE_PLUGIN_OK" = true ]; then # The plugin's hooks.json now governs — REMOVE any direct govern.mjs # entries a previous installer wrote, or every tool call is governed # (and logged) twice. Preserves all non-ACP hooks. node -e " const fs = require('fs'); const p = process.argv[1]; let s = {}; try { s = JSON.parse(fs.readFileSync(p, 'utf8')); } catch {} if (s.hooks) { const isGovernEntry = (e) => Array.isArray(e.hooks) && e.hooks.some(h => typeof h.command === 'string' && h.command.includes('govern.mjs')); for (const ev of ['SessionStart', 'PreToolUse', 'PostToolUse']) { if (Array.isArray(s.hooks[ev])) s.hooks[ev] = s.hooks[ev].filter(e => !isGovernEntry(e)); } } fs.writeFileSync(p, JSON.stringify(s, null, 2)); " "$CLAUDE_SETTINGS" # The plugin bundles the ACP MCP server — drop the legacy user-scope # registration so the tools don't appear twice. CLAUDE_JSON="$HOME/.claude.json" if [ -f "$CLAUDE_JSON" ]; then node -e " const fs = require('fs'); const p = process.argv[1]; let c = {}; try { c = JSON.parse(fs.readFileSync(p, 'utf8')); } catch {} if (c.mcpServers && c.mcpServers.acp) { delete c.mcpServers.acp; fs.writeFileSync(p, JSON.stringify(c, null, 2)); } " "$CLAUDE_JSON" fi # Say what happened, with the versions read back — never "auto-updating": # Claude Code does not auto-update a third-party marketplace plugin, and # this installer only just learned to (acp-install#64). if [ -n "$CLAUDE_PLUGIN_BEFORE" ] && [ -n "$CLAUDE_PLUGIN_AFTER" ] && [ "$CLAUDE_PLUGIN_BEFORE" != "$CLAUDE_PLUGIN_AFTER" ]; then echo " ${C_GREEN}✓${C_RESET} [Claude Code] ACP plugin updated v$CLAUDE_PLUGIN_BEFORE → v$CLAUDE_PLUGIN_AFTER (hooks + skills + MCP) — restart Claude Code to run it" elif [ -n "$CLAUDE_PLUGIN_BEFORE" ]; then echo " ${C_GREEN}✓${C_RESET} [Claude Code] ACP plugin v$CLAUDE_PLUGIN_BEFORE (hooks + skills + MCP)" else echo " ${C_GREEN}✓${C_RESET} [Claude Code] ACP plugin installed v${CLAUDE_PLUGIN_AFTER:-?} (hooks + skills + MCP)" fi if [ -n "$CLAUDE_PLUGIN_MARKET_VER" ] && [ -n "$CLAUDE_PLUGIN_AFTER" ] && [ "$CLAUDE_PLUGIN_MARKET_VER" != "$CLAUDE_PLUGIN_AFTER" ]; then echo "" echo " ${C_RED}! [Claude Code] the ACTIVE ACP plugin is v$CLAUDE_PLUGIN_AFTER but the marketplace has v$CLAUDE_PLUGIN_MARKET_VER.${C_RESET}" echo " This installer could not switch it (your Claude Code may predate \`claude plugin update\`)." echo " Run exactly:" echo " ${C_RED}claude plugin update agentic-control-plane@acp${C_RESET}" echo " then restart Claude Code. Until then every session runs v$CLAUDE_PLUGIN_AFTER." echo "" elif [ "$CLAUDE_PLUGIN_MARKET_OK" != true ]; then echo " (the plugin marketplace was unreachable — the plugin stays at v${CLAUDE_PLUGIN_AFTER:-?}; re-run this installer online to pick up updates)" elif [ -z "$CLAUDE_PLUGIN_MARKET_VER" ] || [ -z "$CLAUDE_PLUGIN_AFTER" ]; then echo " (could not read the plugin registry to verify the version — check with: claude plugin list)" fi else # Fallback for Claude Code CLIs without plugin-marketplace support: # direct hook wiring + user-scope MCP, exactly as before. # # SessionStart carries the paired-arrival attestation (/govern/attest) # — the mechanism that proves a hook is really # running. Only govern.mjs 0.9.0+ has a handler for it; older copies # dispatch unknown events to handlePreToolUse, which would POST # /govern/tool-use with an undefined tool_name at every session start # (why #40's unconditional wiring was reverted in #41). So probe the # copy actually written to THIS machine: govern.mjs is fetched from the # plugin repo at install time, so the day a handleSessionStart ships # there, fresh installs start attesting with no installer release — and # the bundled offline fallback (no handler) stays safely un-wired. if grep -q "handleSessionStart" "$CONFIG_DIR/govern.mjs" 2>/dev/null; then ACP_FALLBACK_EVENTS="['SessionStart', 'PreToolUse', 'PostToolUse']" else ACP_FALLBACK_EVENTS="['PreToolUse', 'PostToolUse']" fi node -e " const fs = require('fs'); const p = process.argv[1]; let s = {}; try { s = JSON.parse(fs.readFileSync(p, 'utf8')); } catch {} s.hooks = s.hooks || {}; const hookEntry = { matcher: '.*', hooks: [{ type: 'command', command: 'env ACP_CLIENT=claude-code-plugin node \$HOME/.acp/govern.mjs', timeout: 5 }] }; function isGovernEntry(e) { return Array.isArray(e.hooks) && e.hooks.some(h => typeof h.command === 'string' && h.command.includes('govern.mjs')); } // Which events to wire is decided in bash above (ACP_FALLBACK_EVENTS): // SessionStart only when the installed govern.mjs actually has a // handleSessionStart (0.9.0+). Stale SessionStart govern entries are // cleaned up either way — but never invent an empty hooks array for // an event we neither had nor wire. const events = ${ACP_FALLBACK_EVENTS}; for (const ev of ['SessionStart', 'PreToolUse', 'PostToolUse']) { if (!events.includes(ev) && !Array.isArray(s.hooks[ev])) continue; s.hooks[ev] = (Array.isArray(s.hooks[ev]) ? s.hooks[ev] : []).filter(e => !isGovernEntry(e)); if (events.includes(ev)) s.hooks[ev].push(hookEntry); } fs.writeFileSync(p, JSON.stringify(s, null, 2)); " "$CLAUDE_SETTINGS" CLAUDE_JSON="$HOME/.claude.json" [ -f "$CLAUDE_JSON" ] || echo '{}' > "$CLAUDE_JSON" node -e " const fs = require('fs'); const p = process.argv[1]; let c = {}; try { c = JSON.parse(fs.readFileSync(p, 'utf8')); } catch {} c.mcpServers = c.mcpServers || {}; c.mcpServers.acp = { command: 'sh', args: ['-c', 'exec npx -y mcp-remote https://api.agenticcontrolplane.com/mcp --header \"Authorization: Bearer \$(cat ~/.acp/credentials)\"'], }; fs.writeFileSync(p, JSON.stringify(c, null, 2)); " "$CLAUDE_JSON" echo " ${C_GREEN}✓${C_RESET} [Claude Code] hooks + MCP registered directly (plugin CLI unavailable — update Claude Code for auto-updates)" fi # ── Double-governance check ─────────────────────────── # A machine that ran the direct-wiring path AND has the marketplace # plugin installed ends up with TWO PreToolUse hooks, each calling # /govern/tool-use on every tool call. Found in the wild 2026-08-14: a # v0.3.0 marketplace copy from April was still firing beside the current # hook — doubling gateway load (and so the scale-out latency tail that # turns a slow answer into a fail-closed deny), from a code path nobody # had looked at in four months. # # We DETECT and REPORT rather than delete: hook wiring is governance # config, and governance changes are the operator's to make, in every # direction and regardless of intent. Printing the exact command # is the whole job here. SETTINGS_HAS_HOOK=false if [ -f "$CLAUDE_SETTINGS" ] && grep -q "govern.mjs" "$CLAUDE_SETTINGS" 2>/dev/null; then SETTINGS_HAS_HOOK=true fi # Only an INSTALLED plugin contributes hooks. A marketplace directory is a # catalog clone, not a registration — the first version of this check keyed # on the hooks.json file being present and told a user to uninstall a plugin # they did not have (2026-08-16, on the machine that motivated the check). # Ask the plugin CLI; if it cannot answer, say nothing. A warning that tells # someone to remove governance has to be certain before it speaks. PLUGIN_INSTALLED=false if command -v claude > /dev/null 2>&1; then if claude plugin list 2>/dev/null | grep -q "agentic-control-plane"; then PLUGIN_INSTALLED=true fi fi if [ "$SETTINGS_HAS_HOOK" = true ] && [ "$PLUGIN_INSTALLED" = true ]; then # The marketplace is registered as `acp`, so its clone lives under # marketplaces/acp (not the plugin's name — that path never existed and # the version always read "unknown"). MARKET_HOOKS="$HOME/.claude/plugins/marketplaces/acp/hooks/hooks.json" MARKET_BIN="$HOME/.claude/plugins/marketplaces/acp/bin/govern.mjs" MARKET_VER="unknown" if [ -f "$MARKET_BIN" ]; then MARKET_VER="$(grep -o 'PLUGIN_VERSION = "[^"]*"' "$MARKET_BIN" 2>/dev/null | head -1 | sed 's/.*"\(.*\)"/\1/')" [ -z "$MARKET_VER" ] && MARKET_VER="pre-0.4 (no version marker)" fi echo "" echo " ${C_RED}! Double governance detected.${C_RESET} Two PreToolUse hooks are registered:" echo " 1. $CLAUDE_SETTINGS (this installer's, kept current)" echo " 2. $MARKET_HOOKS (marketplace plugin, version $MARKET_VER)" echo " Both call the gateway on every tool call. That doubles load and," echo " if the plugin copy is stale, runs code you are not tracking." echo " Pick ONE — we don't edit hook config for you:" echo " keep the installer's (simplest): claude plugin uninstall agentic-control-plane" echo " or keep the plugin's: claude plugin update agentic-control-plane@acp" echo " then remove the govern.mjs hook from $CLAUDE_SETTINGS" echo "" fi # ── Marketplace config health ──────────────────────────────────────── # When the plugin CLI can't read its own marketplace registry, every # `claude plugin` call fails and this installer silently falls back to # direct hook wiring — while telling the user their Claude Code is too # old, which is the wrong diagnosis and sends them to the wrong fix. # A stale entry written by an older CLI (e.g. a local-path source whose # schema has since changed) is the common cause. Report the real reason. if command -v claude > /dev/null 2>&1; then MARKET_ERR="$(claude plugin marketplace list 2>&1 > /dev/null)" if [ -n "$MARKET_ERR" ] && echo "$MARKET_ERR" | grep -qi "corrupt\|invalid"; then echo "" echo " ${C_RED}! The plugin CLI cannot read its marketplace registry.${C_RESET}" echo " ${C_DIM}${MARKET_ERR}${C_RESET}" echo " That is why plugin installs fell back to direct hook wiring above —" echo " your Claude Code is fine; the registry entry is stale. Governance IS" echo " active either way; you just don't get plugin auto-updates." echo " Fix (yours to run — we don't edit plugin config):" echo " claude plugin marketplace remove " echo " claude plugin marketplace add agentic-control-plane/claude-code-acp-plugin" echo " Registry file: $HOME/.claude/plugins/known_marketplaces.json" echo "" fi fi # ── Cost X-ray wrapper (pricing out of the box) ───────────────────── # Hooks govern tool calls but can't see model traffic. `claude-acp` also # routes MODEL calls through the ACP proxy so every session is priced # (per agent / session / action). BYO auth: ACP forwards YOUR credential — # subscription OAuth or API key — so Anthropic bills you exactly as # before; ACP only observes and governs. Deliberately a separate command: # plain `claude` stays untouched as the always-working escape hatch. # Cloud-only: model-call pricing needs the proxy, so --local skips all of # this (no wrapper, no PATH edit — local mode touches no shell rc files). if [ "$LOCAL_MODE" = false ]; then # Launch lines only — everything else (key, fail-open, summary) is the # shared template. ANTHROPIC_CUSTOM_HEADERS is newline-separated; the # trace level rides along as x-trace-level when set. # # Headless auto-resume: a `claude -p` run goes through # acp-claude-resume.mjs, which sets ACP_HEADLESS=1. A call held for human # approval is still DENIED; the hook also records it in # ~/.acp/holds//.json. When the run exits, the runner # waits for a decision and resumes the session with a prompt that says # what was decided. Interactive sessions and ACP_RESUME=0 run claude # exactly as before. install.ps1 (Windows) has no runner yet; without # ACP_HEADLESS the hook records nothing, so that is harmless. # No `case` here on purpose: bash 3.2 misparses `)` inside $(cat < "$CONFIG_DIR/bin/acp-claude-resume.mjs" << 'ACPRESUME' #!/usr/bin/env node // acp-claude-resume — claude-acp's runner for headless `claude -p` runs. // Generated by the ACP installer. Docs: agenticcontrolplane.com // // A call held for approval is DENIED by the ACP hook, always. With // ACP_HEADLESS=1 (set here) the hook also appends the hold to // ~/.acp/holds/.json. When claude exits, this runner waits for // every recorded hold to be decided, then runs // claude -p --resume "" // so the agent retries approved calls (the gateway grants the identical // call once) and finishes without denied ones. Off switch: ACP_RESUME=0. // // Why not a PreToolUse defer decision: Claude Code ignores it when a turn has // several tool calls, and the held call then goes through the normal // permission flow (it RUNS under --dangerously-skip-permissions or an allow // rule). A deny cannot fail open that way. import { spawn } from "node:child_process"; import { readFileSync, readdirSync, lstatSync, unlinkSync } from "node:fs"; import { randomUUID } from "node:crypto"; import { homedir } from "node:os"; import { join } from "node:path"; const argv = process.argv.slice(2); const CLAUDE = "claude"; const MAX_RESUMES = 20; const num = (v, d) => { const n = Number(v); return Number.isFinite(n) && n >= 0 ? n : d; }; const POLL_MS = Math.max(50, num(process.env.ACP_RESUME_POLL_SECONDS, 10) * 1000); const POLL_MAX_MS = Math.max(POLL_MS, 60000); const WAIT_S = Math.min(num(process.env.ACP_RESUME_WAIT_SECONDS, 7200), 7 * 86400); const say = (line) => process.stderr.write(`${line}\n`); // claude's own flag shapes (claude --help): which take one value, which // take several, which take an optional one. Needed to tell the prompt // (a positional) apart from flag values when building the resume command. // These sets must track `claude --help`; an unknown value-taking flag will // be mis-parsed (its value read as the prompt and dropped on resume). const ONE = new Set(["--agent", "--agents", "--append-system-prompt", "--append-system-prompt-file", "--autocompact", "--debug-file", "--effort", "--environment", "--fallback-model", "--input-format", "--json-schema", "--max-budget-usd", "--max-turns", "--model", "-n", "--name", "--output-format", "--permission-mode", "--permission-prompt-tool", "--permission-prompts", "--plugin-dir", "--plugin-url", "--remote-control-session-name-prefix", "--session-id", "--setting-sources", "--settings", "--system-prompt", "--system-prompt-file", "--system-prompt-snapshot"]); const MANY = new Set(["--add-dir", "--allowedTools", "--allowed-tools", "--betas", "--disallowedTools", "--disallowed-tools", "--file", "--mcp-config", "--tools"]); const OPTIONAL = new Set(["-d", "--debug", "-r", "--resume", "--cloud", "--from-pr", "--prompt-suggestions", "--remote-control", "--teleport", "-w", "--worktree"]); // Dropped from the resume command: we add our own --resume, and these // would pick a different session or read a new prompt. const STRIP = new Set(["-p", "--print", "-r", "--resume", "-c", "--continue", "--session-id", "--fork-session", "--from-pr", "--input-format"]); function parse(args) { const out = []; for (let i = 0; i < args.length;) { const a = args[i++]; if (a === "--") { while (i < args.length) out.push({ pos: true, parts: [args[i++]] }); break; } if (!a.startsWith("-") || a === "-") { out.push({ pos: true, parts: [a] }); continue; } const eq = a.startsWith("--") ? a.indexOf("=") : -1; const name = eq > 0 ? a.slice(0, eq) : a; const parts = [a]; if (eq < 0) { if (ONE.has(name)) { if (i < args.length) parts.push(args[i++]); } else if (MANY.has(name)) { while (i < args.length && !args[i].startsWith("-")) parts.push(args[i++]); } else if (OPTIONAL.has(name)) { if (i < args.length && !args[i].startsWith("-")) parts.push(args[i++]); } } out.push({ name, value: eq > 0 ? a.slice(eq + 1) : parts[1], parts }); } return out; } const tokens = parse(argv); const flag = (n) => tokens.find((t) => !t.pos && n.includes(t.name)); const fmt = flag(["--output-format"])?.value || "text"; const userSessionId = flag(["--session-id"])?.value || null; const resuming = !!flag(["-r", "--resume", "-c", "--continue", "--fork-session", "--from-pr"]); // The session id must be one this runner can know. json/stream-json: the // result's session_id. Text mode: the user's --session-id, or one we // generate and pass as --session-id. A text-mode run that resumes or // continues an unknown session is not auto-resumed. const injectSessionId = fmt === "text" && !userSessionId && !resuming ? randomUUID() : null; const knownSessionId = userSessionId || injectSessionId; const eligible = process.env.ACP_RESUME !== "0" && !!flag(["-p", "--print"]) && !flag(["--no-session-persistence", "--bg", "--background"]) && flag(["--input-format"])?.value !== "stream-json" && (fmt === "json" || fmt === "stream-json" || !!knownSessionId); function resumeArgs(sessionId, prompt) { const rest = tokens.filter((t) => !t.pos && !STRIP.has(t.name)).flatMap((t) => t.parts); // The prompt sits right after --resume : after a variadic flag such as // --allowedTools it would be read as one more tool name. return ["-p", "--resume", sessionId, prompt, ...rest]; } // Signals: forward to claude, then exit once it closes. Never wait or // resume after one. const STARTED = Date.now(); const SIG_CODE = { SIGINT: 130, SIGTERM: 143, SIGHUP: 129 }; let child = null; let stopped = null; for (const sig of Object.keys(SIG_CODE)) { process.on(sig, () => { stopped = sig; if (child) { try { child.kill(sig); } catch {} } else { cleanupDecided(); process.exit(SIG_CODE[sig]); } }); } // json mode: each run's stdout is buffered, not printed, so the caller gets // ONE JSON document at the end (see main). text and stream-json: passed // straight through (stream-json can carry more than one "result" event). function run(args, env, stdin) { return new Promise((resolve) => { let all = "", buf = "", last = null; const take = (line) => { const s = line.trim(); if (!s.startsWith("{")) return; try { const o = JSON.parse(s); if (o && o.type === "result") last = o; } catch {} }; child = spawn(CLAUDE, args, { env, stdio: [stdin, "pipe", "inherit"] }); child.stdout.on("data", (c) => { if (fmt !== "json") process.stdout.write(c); const s = c.toString("utf8"); if (all.length < 64 * 1024 * 1024) all += s; buf += s; let nl; while ((nl = buf.indexOf("\n")) >= 0) { take(buf.slice(0, nl)); buf = buf.slice(nl + 1); } }); child.on("error", (e) => { child = null; say(`claude-acp: could not start claude (${e.message})`); resolve({ code: 127, result: null, raw: "" }); }); child.on("close", (code, signal) => { child = null; take(buf); if (!last) { try { const o = JSON.parse(all.trim()); if (o && typeof o === "object") last = o; } catch {} } resolve({ code: code ?? (signal ? SIG_CODE[signal] ?? 129 : 1), result: last, raw: all }); }); }); } // Holds: one file per approval at ~/.acp/holds//.json, // written by the hook. Only regular files, only valid ids, only holds // written after this runner started (older ones belong to a dead runner). const holdsDir = (sessionId) => join(homedir(), ".acp", "holds", String(sessionId).replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 120)); function readHolds(sessionId) { const dir = holdsDir(sessionId); try { if (!lstatSync(dir).isDirectory()) return []; } catch { return []; } const out = []; for (const f of readdirSync(dir)) { const m = /^([0-9a-f-]{36})\.json$/i.exec(f); if (!m) continue; const p = join(dir, f); try { if (!lstatSync(p).isFile()) continue; const h = JSON.parse(readFileSync(p, "utf8")); if (!h || h.approvalId !== m[1]) continue; if (!(Date.parse(h.ts) >= STARTED - 5000)) continue; out.push({ ...h, path: p }); } catch {} } return out.sort((a, b) => String(a.ts).localeCompare(String(b.ts))); } const decidedPaths = new Set(); function dropHold(h) { decidedPaths.add(h.path); try { unlinkSync(h.path); decidedPaths.delete(h.path); } catch {} } function cleanupDecided() { for (const p of decidedPaths) { try { unlinkSync(p); } catch {} } } // The key is sent only to ACP or to a loopback test stub, never to an // arbitrary ACP_GOVERN_BASE. function apiBase() { const raw = process.env.ACP_GOVERN_BASE || ""; try { const u = new URL(raw); if (u.protocol === "https:" && (u.hostname === "agenticcontrolplane.com" || u.hostname.endsWith(".agenticcontrolplane.com"))) return u.origin; if (u.protocol === "http:" && (u.hostname === "127.0.0.1" || u.hostname === "localhost")) return u.origin; } catch {} return "https://api.agenticcontrolplane.com"; } function apiKey() { if (process.env.ACP_KEY) return process.env.ACP_KEY; try { return readFileSync(join(homedir(), ".acp", "credentials"), "utf8").trim(); } catch { return ""; } } const toMs = (v) => { if (!v) return 0; if (typeof v === "string") return Date.parse(v) || 0; if (typeof v === "number") return v; const s = v._seconds ?? v.seconds; return typeof s === "number" ? s * 1000 : 0; }; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); // One poll of GET /aarm/approvals/:id (the endpoint the console reads). // Returns { outcome?, expiresMs }: outcome is approved | denied | timeout | // unavailable once decided, undefined while pending or on a network blip. async function pollOnce(approvalId) { const url = `${apiBase()}/aarm/approvals/${encodeURIComponent(approvalId)}`; try { const res = await fetch(url, { headers: { Authorization: `Bearer ${apiKey()}`, Accept: "application/json" }, signal: AbortSignal.timeout(10000) }); if (res.ok) { const doc = await res.json().catch(() => ({})); const st = doc.effectiveStatus || doc.status; const expiresMs = toMs(doc.expiresAt); if (st === "approved") return { outcome: "approved", expiresMs }; if (st === "denied" || st === "rejected") return { outcome: "denied", expiresMs }; if (st && st !== "pending") return { outcome: "timeout", expiresMs }; return { expiresMs }; } // 401/403: the key is revoked or wrong; 404: no such approval. None of // these get better by polling again. if (res.status === 401 || res.status === 403 || res.status === 404) return { outcome: "unavailable" }; } catch { /* keep waiting until the deadline */ } return {}; } // Waits until ANY hold is decided (grants last 30 min, so an early approval // must not sit behind a slow one): 10s between polls backing off to 60s, // never past `deadline` (one for the whole runner) or a hold's own expiry. // Returns Map approvalId -> outcome for the decided holds only; at the // deadline every remaining hold comes back "waitlimit". async function waitAny(holds, deadline) { const outcomes = new Map(); const expiry = new Map(); let interval = POLL_MS; for (;;) { for (const h of holds) { const r = await pollOnce(h.approvalId); if (r.expiresMs) expiry.set(h.approvalId, r.expiresMs + 5000); if (!r.outcome && Date.now() >= (expiry.get(h.approvalId) ?? Infinity)) r.outcome = "timeout"; if (r.outcome) { outcomes.set(h.approvalId, r.outcome); say(`ACP: ${label(h)} ${SAID[r.outcome]}`); } if (stopped) return outcomes; } if (outcomes.size) return outcomes; if (Date.now() >= deadline) { for (const h of holds) { outcomes.set(h.approvalId, "waitlimit"); say(`ACP: ${label(h)} ${SAID.waitlimit}`); } return outcomes; } const next = Math.min(deadline, ...holds.map((h) => expiry.get(h.approvalId) ?? deadline)); await sleep(Math.max(0, Math.min(interval, next - Date.now()))); interval = Math.min(Math.round(interval * 1.5), POLL_MAX_MS); } } const code = (h) => (typeof h.code === "string" && /^[A-Za-z0-9]{1,8}$/.test(h.code) ? h.code : h.approvalId.slice(0, 4)).toUpperCase(); const label = (h) => `ACP-${code(h)}`; const SAID = { approved: "approved", denied: "denied", timeout: "expired without a decision", unavailable: "could not be confirmed (approval not readable with this key)", waitlimit: `could not be confirmed (no decision within ${WAIT_S}s)`, }; // The resume prompt: a fixed template, one line per hold. Nothing derived // from tool input reaches it: only the approval code and the tool key, // both restricted to a tight character set. function promptLine(h, outcome) { const tool = String(h.tool || "").replace(/[^A-Za-z0-9._:-]/g, "").slice(0, 64) || "tool"; const head = `ACP: approval ${label(h)} for the held ${tool} call`; if (outcome === "approved") return `${head} was approved; retry that exact call now, then continue your task.`; if (outcome === "denied") return `${head} was denied; do not retry it; finish the task without it.`; if (outcome === "timeout") return `${head} expired without a decision; do not retry; finish without it.`; return `${head} could not be confirmed; do not retry it; finish the task without it.`; } // json mode prints ONE document: the last run's result, with cost and // duration summed across runs and acp_resumes added. const SUMMED = ["total_cost_usd", "duration_ms", "duration_api_ms"]; function printJson(runs) { const last = runs[runs.length - 1]; for (const r of runs.slice(0, -1)) if (!r.result && r.raw) process.stderr.write(r.raw); // unparseable earlier output: keep it visible, off stdout if (!last.result) { process.stdout.write(last.raw); return; } const doc = { ...last.result }; for (const k of SUMMED) { const vals = runs.map((r) => r.result?.[k]).filter((v) => typeof v === "number"); if (vals.length) doc[k] = vals.reduce((a, b) => a + b, 0); } doc.acp_resumes = runs.length - 1; process.stdout.write(`${JSON.stringify(doc)}\n`); } async function main() { if (!eligible) { const r = await run(argv, process.env, "inherit"); if (fmt === "json") process.stdout.write(r.raw); process.exitCode = r.code; // exitCode, not exit(): let piped stdout drain return; } const env = { ...process.env, ACP_HEADLESS: "1" }; const deadline = STARTED + WAIT_S * 1000; // one deadline for the whole runner const first = injectSessionId ? ["--session-id", injectSessionId, ...argv] : argv; const runs = [await run(first, env, "inherit")]; let r = runs[0]; let resumes = 0; const announced = new Set(); while (!stopped) { // Only THIS session's holds: a nested `claude -p` the agent started // writes under its own session, which this runner never reads. const sid = (fmt !== "text" && r.result?.session_id) || knownSessionId; if (!sid) break; const holds = readHolds(sid); if (!holds.length) break; if (resumes >= MAX_RESUMES) { say(`ACP: ${holds.length} call(s) still held after ${MAX_RESUMES} resumes; stopping.`); break; } if (resumes > 0 && Date.now() >= deadline) { say(`ACP: wait limit (${WAIT_S}s) reached; not waiting for ${holds.length} more call(s).`); break; } for (const h of holds) if (!announced.has(h.approvalId)) { announced.add(h.approvalId); say(`ACP: held for approval ${label(h)}, waiting…`); } const outcomes = await waitAny(holds, deadline); if (stopped) break; const decided = holds.filter((h) => outcomes.has(h.approvalId)); for (const h of decided) dropHold(h); say("ACP: resuming so the agent can carry on"); const prompt = decided.map((h) => promptLine(h, outcomes.get(h.approvalId))).join("\n"); r = await run(resumeArgs(sid, prompt), env, "ignore"); runs.push(r); resumes++; } cleanupDecided(); if (fmt === "json") printJson(runs); process.exitCode = r.code; } main(); ACPRESUME chmod +x "$CONFIG_DIR/bin/acp-claude-resume.mjs" CLAUDE_LAUNCH=$(cat << 'EOF' ACP_HDRS="x-acp-key: $ACP_KEY" if [ -n "$ACP_TRACE_LEVEL" ]; then ACP_HDRS="$ACP_HDRS x-trace-level: $ACP_TRACE_LEVEL"; fi _acp_resume=0 if [ "${ACP_RESUME:-1}" != "0" ] && [ -f "$HOME/.acp/bin/acp-claude-resume.mjs" ] && command -v node >/dev/null 2>&1; then for _acp_a in "$@"; do if [ "$_acp_a" = "-p" ] || [ "$_acp_a" = "--print" ]; then _acp_resume=1; fi done fi if [ "$_acp_resume" = 1 ]; then ANTHROPIC_BASE_URL="${ACP_PROXY_BASE:-https://api.agenticcontrolplane.com/anthropic}" \ ANTHROPIC_CUSTOM_HEADERS="$ACP_HDRS" \ node "$HOME/.acp/bin/acp-claude-resume.mjs" "$@" else ANTHROPIC_BASE_URL="${ACP_PROXY_BASE:-https://api.agenticcontrolplane.com/anthropic}" \ ANTHROPIC_CUSTOM_HEADERS="$ACP_HDRS" \ claude "$@" fi EOF ) acp_write_launcher claude-acp claude ACP_KEY "" "$CLAUDE_LAUNCH" echo " ${C_GREEN}✓${C_RESET} [Claude Code] Cost X-ray wrapper installed: claude-acp" [ "$ADDED_PATH" = true ] && echo " ${C_DIM}Added ~/.acp/bin to PATH (open a new terminal to pick it up)${C_RESET}" # Directive in the file Claude Code reads at every session start. Agents # now set harnesses up on behalf of their users, so the launcher name has # to live where the agent reads, not only in the docs. acp_write_directive "$HOME/.claude/CLAUDE.md" "Claude Code" "~/.acp/bin/claude-acp" claude \ '- **Tool calls** are intercepted by the ACP plugin hooks. Nothing extra to do.' \ '- Do NOT hand-roll ANTHROPIC_BASE_URL / ANTHROPIC_CUSTOM_HEADERS to reach the proxy — the launcher sets both.' echo " ${C_GREEN}✓${C_RESET} [Claude Code] ~/.claude/CLAUDE.md directive installed — agents launch claude-acp for priced sessions" fi # LOCAL_MODE=false (cost X-ray wrapper) INSTALLED="${INSTALLED:+$INSTALLED, }Claude Code" fi # ── Step 1b: Cursor setup ──────────────────────────────────────────── ACP_STEP="cursor" if [ "$HAS_QWEN" = true ]; then echo " [Qwen Code] Setting up governance hooks..." QWEN_SETTINGS="$HOME/.qwen/settings.json" mkdir -p "$HOME/.qwen" if [ ! -f "$QWEN_SETTINGS" ]; then echo '{}' > "$QWEN_SETTINGS" fi node -e " const fs = require('fs'); const p = process.argv[1]; let cfg = {}; try { cfg = JSON.parse(fs.readFileSync(p, 'utf8')); } catch {} cfg.hooks = cfg.hooks || {}; // Qwen Code: matcher '*' = every tool; timeout is milliseconds. const hookEntry = { matcher: '*', hooks: [{ type: 'command', name: 'acp', command: 'env ACP_CLIENT=qwen-code node \$HOME/.acp/govern.mjs', timeout: 5000 }] }; function isGovernEntry(e) { return Array.isArray(e.hooks) && e.hooks.some(h => typeof h.command === 'string' && h.command.includes('govern.mjs')); } // Upgrade-safe: remove any existing govern.mjs entry, then add the current one. for (const ev of ['PreToolUse', 'PostToolUse']) { cfg.hooks[ev] = (Array.isArray(cfg.hooks[ev]) ? cfg.hooks[ev] : []).filter(e => !isGovernEntry(e)); cfg.hooks[ev].push(hookEntry); } // ACP introspection MCP — Qwen Code reads mcpServers from the same file. cfg.mcpServers = cfg.mcpServers || {}; cfg.mcpServers.acp = { command: 'sh', args: ['-c', 'exec npx -y mcp-remote https://api.agenticcontrolplane.com/mcp --header \"Authorization: Bearer \$(cat ~/.acp/credentials)\"'], }; if (cfg.disableAllHooks === true) console.error(' [Qwen Code] warning: disableAllHooks is true in settings.json — hooks (including ACP) will not run until it is removed.'); fs.writeFileSync(p, JSON.stringify(cfg, null, 2)); " "$QWEN_SETTINGS" echo " ${C_GREEN}✓${C_RESET} [Qwen Code] PreToolUse + PostToolUse hooks + MCP connector registered in ~/.qwen/settings.json" INSTALLED="${INSTALLED:+$INSTALLED, }Qwen Code" echo "" fi # GitHub Copilot — Copilot CLI and VS Code's agent mode read the same # user-level directory, ~/.copilot/hooks/*.json, so one file covers both. # PascalCase event names select Copilot CLI's "VS Code compatible" payload: # snake_case fields with tool_name already in Claude Code's vocabulary, which # is the contract govern.mjs speaks. Entries are FLAT — no {matcher, hooks:[…]} # nesting; that is the Claude/Cursor/Qwen shape and Copilot ignores it. # timeoutSec is the CLI's field and timeout is VS Code's, so both are # written and each reader takes its own. ACP_HARNESS=copilot makes # govern.mjs emit every verdict in both output shapes and canonicalize the # tool ids VS Code sends. The file is ours in full (acp.json, beside any # hooks you wrote), so it is written whole, not merged, and the uninstaller # removes it by name. Pre + Post only: Copilot's SessionStart carries none # of the fields the Claude Code attestation reads. if [ "$HAS_COPILOT" = true ]; then echo " [GitHub Copilot] Setting up governance hooks..." COPILOT_HOOKS_DIR="$HOME/.copilot/hooks" mkdir -p "$COPILOT_HOOKS_DIR" node -e " const fs = require('fs'); const p = process.argv[1]; const cmd = 'env ACP_CLIENT=copilot ACP_HARNESS=copilot node \$HOME/.acp/govern.mjs'; const cfg = { version: 1, hooks: {} }; for (const ev of ['PreToolUse', 'PostToolUse']) { cfg.hooks[ev] = [{ type: 'command', command: cmd, timeout: 5, timeoutSec: 5 }]; } fs.writeFileSync(p, JSON.stringify(cfg, null, 2) + '\n'); " "$COPILOT_HOOKS_DIR/acp.json" if grep -qs '"disableAllHooks"[[:space:]]*:[[:space:]]*true' "$HOME/.copilot/settings.json" 2>/dev/null; then echo " ${C_DIM}[GitHub Copilot] warning: disableAllHooks is true in ~/.copilot/settings.json — hooks (including ACP) will not run until it is removed.${C_RESET}" fi echo " ${C_GREEN}✓${C_RESET} [GitHub Copilot] PreToolUse + PostToolUse hooks registered in ~/.copilot/hooks/acp.json (Copilot CLI + VS Code agent mode)" INSTALLED="${INSTALLED:+$INSTALLED, }GitHub Copilot" echo "" fi if [ "$HAS_CURSOR" = true ]; then echo " [Cursor] Setting up governance hooks..." # govern.mjs is shared — written above, before any client-specific steps. CURSOR_HOOKS="$HOME/.cursor/hooks.json" mkdir -p "$HOME/.cursor" if [ ! -f "$CURSOR_HOOKS" ]; then echo '{}' > "$CURSOR_HOOKS" fi # Idempotent merge. Cursor's hook keys are lowercase. node -e " const fs = require('fs'); const p = process.argv[1]; let cfg = {}; try { cfg = JSON.parse(fs.readFileSync(p, 'utf8')); } catch {} cfg.hooks = cfg.hooks || {}; const hookEntry = { matcher: '.*', hooks: [{ type: 'command', command: 'env ACP_CLIENT=cursor node \$HOME/.acp/govern.mjs', timeout: 5 }] }; function isGovernEntry(e) { return Array.isArray(e.hooks) && e.hooks.some(h => typeof h.command === 'string' && h.command.includes('govern.mjs')); } // Upgrade-safe: remove any existing govern.mjs entry, then add the current one. for (const ev of ['preToolUse', 'postToolUse']) { cfg.hooks[ev] = (Array.isArray(cfg.hooks[ev]) ? cfg.hooks[ev] : []).filter(e => !isGovernEntry(e)); cfg.hooks[ev].push(hookEntry); } fs.writeFileSync(p, JSON.stringify(cfg, null, 2)); " "$CURSOR_HOOKS" echo " ${C_GREEN}✓${C_RESET} [Cursor] preToolUse + postToolUse hooks registered" # ACP introspection MCP — same mcp-remote stdio shape as Claude Code, # into Cursor's ~/.cursor/mcp.json. CURSOR_MCP="$HOME/.cursor/mcp.json" [ -f "$CURSOR_MCP" ] || echo '{}' > "$CURSOR_MCP" node -e " const fs = require('fs'); const p = process.argv[1]; let c = {}; try { c = JSON.parse(fs.readFileSync(p, 'utf8')); } catch {} c.mcpServers = c.mcpServers || {}; c.mcpServers.acp = { command: 'sh', args: ['-c', 'exec npx -y mcp-remote https://api.agenticcontrolplane.com/mcp --header \"Authorization: Bearer \$(cat ~/.acp/credentials)\"'], }; fs.writeFileSync(p, JSON.stringify(c, null, 2)); " "$CURSOR_MCP" echo " ${C_GREEN}✓${C_RESET} [Cursor] ACP introspection MCP registered" INSTALLED="${INSTALLED:+$INSTALLED, }Cursor" fi # ── Step 1c: Codex CLI setup ────────────────────────────────────────── ACP_STEP="codex" if [ "$HAS_CODEX" = true ]; then echo " [Codex] Setting up governance hooks..." # Enable the hooks feature in ~/.codex/config.toml. The flag was renamed: # `codex_hooks` was the original (Stage::UnderDevelopment, off by default), # and `hooks` is canonical from 0.145.0 onward — Stable and default-enabled, # with `codex_hooks` kept as a deprecated alias that warns on every launch. # Writing the wrong one is not cosmetic in either direction: `hooks` on an # old build is an unknown key (hooks stay off, governance dark), and # `codex_hooks` on a new build nags the user forever. So detect and pick. # # Non-Bash tools are unhooked on every version; they go through the MCP # connector plus the AGENTS.md directive below. See /integrations/codex. CODEX_TOML="$HOME/.codex/config.toml" mkdir -p "$HOME/.codex" [ -f "$CODEX_TOML" ] || touch "$CODEX_TOML" # "codex-cli 0.145.0" -> "0.145.0"; empty if codex isn't runnable. CODEX_VER="$(codex --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)" # Idempotent: only touch config.toml if the right flag isn't already set. # Uses node for string manipulation; avoids a TOML parser dependency. node -e " const fs = require('fs'); const p = process.argv[1]; const ver = process.argv[2] || ''; // Unknown version => assume old build and keep the alias. It warns but // works on new builds; the canonical key would silently no-op on old ones. // Governance staying ON is worth a deprecation notice. const parts = ver.split('.').map(Number); const canonical = parts.length === 3 && !parts.some(isNaN) && (parts[0] > 0 || parts[1] > 145 || (parts[1] === 145 && parts[2] >= 0)); const key = canonical ? 'hooks' : 'codex_hooks'; let src = ''; try { src = fs.readFileSync(p, 'utf8'); } catch {} const wanted = new RegExp('^\\\\s*' + key + '\\\\s*=\\\\s*true\\\\s*\$', 'm'); if (wanted.test(src)) process.exit(0); // On a canonical build, retire the deprecated alias rather than stacking // both keys — two sources of truth is how the nag survives an 'upgrade'. if (canonical) src = src.replace(/^[ \t]*codex_hooks[ \t]*=[ \t]*true[ \t]*\r?\n?/m, ''); // Match the header line only — never the newline after it, or the insert // re-adds one and leaves a blank line behind. if (/^\[features\][ \t]*\r?\$/m.test(src)) { src = src.replace(/^(\[features\][ \t]*)\r?\$/m, '\$1\n' + key + ' = true'); } else { if (src.length && !src.endsWith('\n')) src += '\n'; src += (src.length ? '\n' : '') + '[features]\n' + key + ' = true\n'; } if (!src.endsWith('\n')) src += '\n'; fs.writeFileSync(p, src); " "$CODEX_TOML" "$CODEX_VER" # Add [mcp_servers.acp] block if not present. Uses sh -c so the # Authorization header reads ~/.acp/credentials at runtime — no install- # time API key needed, and credential rotation is automatic (overwrite # the file, restart Codex). # Cloud-only: the MCP connector and the AGENTS.md directive both talk to # the hosted gateway. --local wires neither — local mode must make zero # network calls. The PreToolUse/PostToolUse hooks (registered below) are # unaffected either way and cover every local tool call, not just shell commands. if [ "$LOCAL_MODE" = false ] && ! grep -q "^\[mcp_servers\.acp\]" "$CODEX_TOML"; then cat >> "$CODEX_TOML" << 'MCPBLOCK' [mcp_servers.acp] command = "sh" args = ["-c", 'exec npx -y mcp-remote https://api.agenticcontrolplane.com/mcp --header "Authorization: Bearer $(cat ~/.acp/credentials)"'] MCPBLOCK fi # Add [model_providers.acp] block if not present — the cost X-ray for # Codex's MODEL calls (the MCP connector above governs TOOL calls and # never sees token usage; this is the other plane, same split as # /blog/codex-cli-cost-tracking documents). Written but not selected: # this does NOT set `model_provider = "acp"` as the file's default, so # plain `codex` is completely unaffected. `codex-acp` (below) opts a # single invocation in via `-c model_provider=acp`, symmetric with how # `claude-acp` opts in via env vars instead of touching Claude Code's # own config. `env_http_headers` reads the ACP_KEY env var at Codex # launch — codex-acp sets it — so no key is ever written to config.toml. # Exact block per agenticcontrolplane.com/blog/codex-cli-cost-tracking # (hero copy) and /integrations/codex (both agree on it). # Cloud-only: same reasoning as the MCP connector above — it's a hosted # proxy, so --local skips it. if [ "$LOCAL_MODE" = false ] && ! grep -q "^\[model_providers\.acp\]" "$CODEX_TOML"; then cat >> "$CODEX_TOML" << 'PROVIDERBLOCK' [model_providers.acp] name = "Agentic Control Plane" base_url = "https://api.agenticcontrolplane.com/openai/v1" requires_openai_auth = true wire_api = "responses" env_http_headers = { "x-acp-key" = "ACP_KEY" } PROVIDERBLOCK fi # Register Pre- and Post-ToolUse hooks in ~/.codex/hooks.json. # # ACP_HARNESS=codex is load-bearing, not decoration. govern.mjs branches on # it twice: (1) Codex has no `ask` semantic on the wire and acts on `deny` # only, so an ask must be emitted as deny-plus-approval-link or the human # gate silently passes through as allowed; (2) Codex rejects `updatedInput`, # so the scoped-token injection path must be skipped or the hook is marked # failed and the tool runs anyway, minus the token. Without this var # govern.mjs defaults to HARNESS=claude-code and does neither. # Same JSON shape as Claude Code settings.json. CODEX_HOOKS="$HOME/.codex/hooks.json" [ -f "$CODEX_HOOKS" ] || echo '{}' > "$CODEX_HOOKS" node -e " const fs = require('fs'); const p = process.argv[1]; let s = {}; try { s = JSON.parse(fs.readFileSync(p, 'utf8')); } catch {} s.hooks = s.hooks || {}; const hookEntry = { matcher: '.*', hooks: [{ type: 'command', command: 'env ACP_CLIENT=codex ACP_HARNESS=codex node \$HOME/.acp/govern.mjs', timeout: 5 }] }; function isGovernEntry(e) { return Array.isArray(e.hooks) && e.hooks.some(h => typeof h.command === 'string' && h.command.includes('govern.mjs')); } // Upgrade-safe: remove any existing govern.mjs entry, then add the current one. for (const ev of ['PreToolUse', 'PostToolUse']) { s.hooks[ev] = (Array.isArray(s.hooks[ev]) ? s.hooks[ev] : []).filter(e => !isGovernEntry(e)); s.hooks[ev].push(hookEntry); } fs.writeFileSync(p, JSON.stringify(s, null, 2)); " "$CODEX_HOOKS" # Write/update ~/.codex/AGENTS.md with the ACP governance directive. # Codex reads AGENTS.md at every session start. The PreToolUse/PostToolUse # hooks registered above use matcher '.*' — every local tool call, not just # Bash — so the directive says the same thing the Claude Code one does: hooks # already govern local tools, don't call acp_check per tool (hosted tools such # as web search never fire hooks; acp_check stays available for those). # Idempotent: the ACP section is delimited by markers, so re-running # replaces only our section and preserves every other instruction. if [ "$LOCAL_MODE" = false ]; then acp_write_directive "$HOME/.codex/AGENTS.md" "Codex" "~/.acp/bin/codex-acp" codex \ '- **Tool calls** (shell, `apply_patch`, MCP tools, other local tools) are intercepted by the ACP' \ ' PreToolUse/PostToolUse hooks. Nothing extra to do.' \ '- **`acp_check`** (MCP tool from the `acp` server) is for explicit questions only — e.g. the user asks' \ ' "am I allowed to do X?" — and for hosted tools that never reach a hook (web search). Do NOT call it' \ ' before local tool calls; the hooks already cover them, Bash and non-Bash alike.' \ '- Do NOT hand-roll `codex -c model_provider=acp`: `[model_providers.acp]` in `~/.codex/config.toml` reads' \ ' the key from the `ACP_KEY` environment variable, which only the launcher sets. For headless priced runs' \ ' use `~/.acp/bin/codex-acp exec …`.' echo " [Codex] AGENTS.md directive installed — hooks govern every tool call, acp_check available on request" echo " ${C_GREEN}✓${C_RESET} [Codex] hooks feature enabled + PreToolUse/PostToolUse hooks + MCP connector wired" # ── Cost X-ray wrapper (pricing out of the box) ───────────────────── # Same split as Claude Code: hooks + MCP connector govern what Codex # DOES; they never see the model call, so they can't price it. The # [model_providers.acp] block above makes pricing possible but does not # turn it on for plain `codex` — `codex-acp` is the opt-in launcher, # symmetric with `claude-acp`. BYO auth: `requires_openai_auth = true` # means ACP forwards YOUR ChatGPT/API-key login, never its own; OpenAI # bills you exactly as before, ACP only observes and governs. # Launch lines only — key, fail-open and summary come from the shared # template. Codex reads env_http_headers values from the environment, so # the trace level never lands in config.toml. Summary prefix "codex" # matches both the TUI ("codex") and `codex exec` ("codex_exec"). CODEX_LAUNCH=$(cat << 'EOF' if [ -n "$ACP_TRACE_LEVEL" ]; then codex -c model_provider=acp -c 'model_providers.acp.env_http_headers={ "x-acp-key" = "ACP_KEY", "x-trace-level" = "ACP_TRACE_LEVEL" }' "$@" else codex -c model_provider=acp "$@" fi EOF ) acp_write_launcher codex-acp codex ACP_KEY codex "$CODEX_LAUNCH" echo " ${C_GREEN}✓${C_RESET} [Codex] Cost X-ray wrapper installed: codex-acp" [ "$ADDED_PATH" = true ] && echo " ${C_DIM}Added ~/.acp/bin to PATH (open a new terminal to pick it up)${C_RESET}" else echo " ${C_GREEN}✓${C_RESET} [Codex] hooks feature enabled + PreToolUse/PostToolUse hooks (local: shell commands governed on-device)" fi # LOCAL_MODE (Codex cloud wiring) # Codex gates hooks behind a one-time review (its hook trust store): # a hooks.json it hasn't been told to trust is listed but silently never # run. There is no flag we could (or should) set for the user — the # review is the point. Say it, loudly, or the hook is dead on arrival. echo " ${C_RED}!${C_RESET} [Codex] One-time step: run ${C_DIM}/hooks${C_RESET} inside Codex and trust the ACP hook." echo " Codex silently skips hooks it hasn't reviewed — until you do this, Codex is not governed." echo " Re-run this installer and you must trust it again — the hash covers the hook command." INSTALLED="${INSTALLED:+$INSTALLED, }Codex" fi # ── Step 1d: OpenClaw setup ─────────────────────────────────────────── ACP_STEP="openclaw" if [ "$HAS_OPENCLAW" = true ]; then echo " [OpenClaw] Installing the ACP plugin..." openclaw plugins install @agenticcontrolplane/openclaw 2>/dev/null && { echo " ${C_GREEN}✓${C_RESET} [OpenClaw] Plugin installed" INSTALLED="${INSTALLED:+$INSTALLED, }OpenClaw" } || { echo " ${C_RED}✗${C_RESET} [OpenClaw] Plugin install failed — try: openclaw plugins install @agenticcontrolplane/openclaw" } fi # ── Step 1e: opencode setup ─────────────────────────────────────────── ACP_STEP="opencode" # Cloud-only: the acp-opencode plugin is npm-fetched by opencode itself and # governs via the workspace token — local decisions aren't wired there yet, # so --local skips it (same rule as the Codex MCP connector). if [ "$HAS_OPENCODE" = true ] && [ "$LOCAL_MODE" = true ]; then echo " ${C_DIM}[opencode] Skipped in --local mode (its ACP plugin needs a workspace; local decisions aren't wired there yet).${C_RESET}" fi if [ "$HAS_OPENCODE" = true ] && [ "$LOCAL_MODE" = false ]; then echo " [opencode] Registering governance plugin..." # opencode governs via the published acp-opencode plugin (npm), which it # auto-installs from its own config on next start. Unlike Claude Code / # Cursor / Codex (which shell out to ~/.acp/govern.mjs), opencode runs the # plugin's hooks in-process: permission.ask (allow/deny/ask), a deny # backstop, and a zero-credential local metering plane. Same # ~/.acp/credentials token, so one auth covers every harness. OPENCODE_JSON="$HOME/.config/opencode/opencode.json" mkdir -p "$HOME/.config/opencode" [ -f "$OPENCODE_JSON" ] || printf '{\n "$schema": "https://opencode.ai/config.json"\n}\n' > "$OPENCODE_JSON" # Migration: older installers wrote an inline plugin here. Remove it so the # npm plugin doesn't end up governing every tool call twice. rm -f "$HOME/.config/opencode/plugin/acp-govern.ts" node -e ' const fs = require("fs"); const p = process.argv[1]; let c = {}; try { c = JSON.parse(fs.readFileSync(p, "utf8")); } catch {} c.plugin = Array.isArray(c.plugin) ? c.plugin : []; // The npm package is @agenticcontrolplane/opencode. "acp-opencode" is the // OLD name: deprecated on npm at 0.2.1 ("Renamed to @agenticcontrolplane/opencode"), // so every install that registered it has been loading 0.2.1 — none of the // notices, local metering or the OpenCode 2.0 entry ever reached those // users. Migrate the old entry in place; keep // the existing order and any options tuple attached to it. (No apostrophes // in this block: it lives inside a single-quoted node -e string.) const PKG = "@agenticcontrolplane/opencode"; const isOurs = (e) => e === "acp-opencode" || e === PKG || (Array.isArray(e) && (e[0] === "acp-opencode" || e[0] === PKG)); c.plugin = c.plugin.map((e) => (e === "acp-opencode" ? PKG : Array.isArray(e) && e[0] === "acp-opencode" ? [PKG, ...e.slice(1)] : e)); if (!c.plugin.some(isOurs)) c.plugin.push(PKG); // permission "ask" is what lets ACP allow/ask reach a tool call; fill gaps // only, never override a choice the user set deliberately. c.permission = c.permission || {}; for (const t of ["bash", "edit", "webfetch"]) if (!c.permission[t]) c.permission[t] = "ask"; // ACP introspection MCP (opencode.ai/docs/mcp-servers). c.mcp = c.mcp || {}; c.mcp.acp = { type: "local", command: ["sh", "-c", "exec npx -y mcp-remote https://api.agenticcontrolplane.com/mcp --header \"Authorization: Bearer $(cat ~/.acp/credentials)\""], enabled: true, }; // Cost X-ray provider — the block /blog/opencode-cost-tracking used to // ask people to paste by hand. Written but NOT selected: no top-level // "model" change, so plain opencode keeps its backend; opencode-acp // (below) selects acp/ for one launch, same contract as // claude-acp / codex-acp. Fill-only: a provider the user already // configured under "acp" is left exactly as they wrote it. c.provider = c.provider || {}; if (!c.provider.acp) { c.provider.acp = { npm: "@ai-sdk/openai-compatible", name: "Agentic Control Plane", options: { baseURL: "https://api.agenticcontrolplane.com/v1", apiKey: "{env:ACP_BEARER_TOKEN}", }, models: { "gemini-3.5-flash": {} }, }; } fs.writeFileSync(p, JSON.stringify(c, null, 2)); ' "$OPENCODE_JSON" && { echo " ${C_GREEN}✓${C_RESET} [opencode] Plugin registered (@agenticcontrolplane/opencode) + permission gate + introspection MCP + cost X-ray provider" echo " Restart opencode — it installs the plugin from npm and governs every tool call." INSTALLED="${INSTALLED:+$INSTALLED, }opencode" } || { echo " ${C_RED}✗${C_RESET} [opencode] Config update failed — add \"plugin\": [\"@agenticcontrolplane/opencode\"] to $OPENCODE_JSON" } # opencode-acp — same shared launcher template as claude-acp / codex-acp. # The plugin and the provider block above both read ACP_BEARER_TOKEN. # Launch lines: select the ACP provider for this launch. ACP_OPENCODE_MODEL # picks the model id behind the proxy (routed by id: gemini-*, gpt-*, # claude-*). OpenCode 1.x advertises a top-level --model, so pass it. # OpenCode 2.x has no top-level --model (only `run --model`; the TUI has # none), so select the model through OPENCODE_CONFIG_CONTENT, the env config # layer 2.x still reads (packages/core/src/config.ts at v2.0.32), merged into # whatever the caller already put there. An explicit `run --model` the user # passes still wins over a config value. Without this, 2.x silently ran its # own default model and nothing was priced. OPENCODE_LAUNCH=$(cat << 'EOF' _acp_model="acp/${ACP_OPENCODE_MODEL:-gemini-3.5-flash}" if opencode --help 2>&1 | grep -q -- "--model"; then opencode --model "$_acp_model" "$@" elif _acp_cfg="$(_ACP_MODEL="$_acp_model" node -e 'let c = {}; try { c = JSON.parse(process.env.OPENCODE_CONFIG_CONTENT || "{}") } catch (e) {} if (!c || typeof c !== "object" || Array.isArray(c)) c = {}; c.model = process.env._ACP_MODEL; process.stdout.write(JSON.stringify(c))' 2>/dev/null)" && [ -n "$_acp_cfg" ]; then OPENCODE_CONFIG_CONTENT="$_acp_cfg" opencode "$@" else echo "opencode-acp: could not select $_acp_model (no --model flag and no node) — pick it in the model picker." >&2 opencode "$@" fi EOF ) acp_write_launcher opencode-acp opencode ACP_BEARER_TOKEN opencode "$OPENCODE_LAUNCH" echo " ${C_GREEN}✓${C_RESET} [opencode] Cost X-ray wrapper installed: opencode-acp" # Directive in the global rules file opencode reads (~/.config/opencode/AGENTS.md). acp_write_directive "$HOME/.config/opencode/AGENTS.md" "opencode" "~/.acp/bin/opencode-acp" opencode \ '- **Tool calls** are governed by the @agenticcontrolplane/opencode plugin. Nothing extra to do.' \ '- The `acp` provider block is already in `~/.config/opencode/opencode.json` and reads `ACP_BEARER_TOKEN`' \ ' from the environment; do not edit it or set a top-level "model" — the launcher selects `acp/`.' echo " ${C_GREEN}✓${C_RESET} [opencode] ~/.config/opencode/AGENTS.md directive installed — agents launch opencode-acp for priced sessions" fi # ── Step 1f: priced launchers for the plugin-governed harnesses ──────── ACP_STEP="launchers" # # Every harness whose model traffic can be pointed at the proxy per launch # gets the same "-acp" launcher from the shared template, plus the # directive in the file its agent reads at session start. One place, one # pattern: a fix to the template above reaches all of these. Harnesses # whose model traffic CANNOT be redirected (Cursor CLI, Antigravity, fx — # no base-URL override exists) are governance-only and are listed as such # on /cost-tracking; nothing is written for them here. # Cloud-only: pricing needs the proxy, so --local skips this whole step. if [ "$LOCAL_MODE" = false ]; then # Hermes Agent — Anthropic-native backends take the proxy per launch via # env (ANTHROPIC_BASE_URL + ANTHROPIC_AUTH_TOKEN=, workspace- # billed Anthropic). OpenAI-compatible backends read base_url from # Hermes's own config; `acp-hermes proxy-setup --verify` registers the # proxy there once, and the launcher says so when it isn't done. if [ "$HAS_HERMES" = true ]; then HERMES_LAUNCH=$(cat << 'EOF' if ! grep -qs "api.agenticcontrolplane.com" "$HOME/.hermes/config.yaml" "$HOME/.hermes/config.toml" "$HOME/.hermes/config.json" 2>/dev/null; then echo "hermes-acp: Anthropic-native model calls are priced via env; for an OpenAI-compatible backend run once: acp-hermes proxy-setup --verify" >&2 fi ANTHROPIC_BASE_URL="${ACP_PROXY_BASE:-https://api.agenticcontrolplane.com/anthropic}/v1" \ ANTHROPIC_AUTH_TOKEN="$ACP_KEY" \ hermes "$@" EOF ) acp_write_launcher hermes-acp hermes ACP_BEARER_TOKEN hermes "$HERMES_LAUNCH" acp_write_directive "$HOME/.hermes/SOUL.md" "Hermes" "~/.acp/bin/hermes-acp" hermes \ '- **Tool calls** are governed by the acp-hermes plugin. Nothing extra to do.' echo " ${C_GREEN}✓${C_RESET} [Hermes] Cost X-ray wrapper installed: hermes-acp (+ ~/.hermes/SOUL.md directive)" fi # Qwen Code — reads OPENAI_BASE_URL / OPENAI_API_KEY / OPENAI_MODEL from # the environment when its auth type is "openai" (Gemini-CLI lineage). # The launcher sets all three for one launch; ACP_QWEN_MODEL picks the # model id behind the proxy (routed by id: gemini-*, gpt-*, claude-*). if [ "$HAS_QWEN" = true ]; then QWEN_LAUNCH=$(cat << 'EOF' if ! grep -qs '"selectedType": *"openai"' "$HOME/.qwen/settings.json" 2>/dev/null; then echo "qwen-acp: Qwen Code only honours OPENAI_BASE_URL when its auth type is openai — pick 'OpenAI' under /auth once, then this launch is priced." >&2 fi OPENAI_BASE_URL="${ACP_PROXY_BASE_OPENAI:-https://api.agenticcontrolplane.com/v1}" \ OPENAI_API_KEY="$ACP_KEY" \ OPENAI_MODEL="${ACP_QWEN_MODEL:-gemini-3.5-flash}" \ qwen "$@" EOF ) acp_write_launcher qwen-acp qwen ACP_BEARER_TOKEN qwen "$QWEN_LAUNCH" acp_write_directive "$HOME/.qwen/QWEN.md" "Qwen Code" "~/.acp/bin/qwen-acp" qwen \ '- **Tool calls** (shell, `apply_patch`, MCP tools, other local tools) are intercepted by the ACP' \ ' PreToolUse/PostToolUse hooks. Nothing extra to do.' \ '- Do NOT export OPENAI_BASE_URL / OPENAI_API_KEY yourself to reach the proxy — the launcher sets them for one launch.' echo " ${C_GREEN}✓${C_RESET} [Qwen Code] Cost X-ray wrapper installed: qwen-acp (+ ~/.qwen/QWEN.md directive)" fi # pi — no env override; the proxy is a named provider in # ~/.pi/agent/models.json (exact block from /integrations/pi), which the # installer writes fill-only, and `--model acp/` selects it for one # launch. pi resolves the key itself from "!cat ~/.acp/credentials". if [ "$HAS_PI" = true ]; then PI_MODELS="$HOME/.pi/agent/models.json" mkdir -p "$HOME/.pi/agent" [ -f "$PI_MODELS" ] || printf '{}\n' > "$PI_MODELS" node -e ' const fs = require("fs"); const p = process.argv[1]; let c = {}; try { c = JSON.parse(fs.readFileSync(p, "utf8")); } catch {} c.providers = c.providers || {}; if (!c.providers.acp) { c.providers.acp = { baseUrl: "https://api.agenticcontrolplane.com/v1", api: "openai-completions", apiKey: "!cat ~/.acp/credentials", compat: { supportsDeveloperRole: false, supportsReasoningEffort: false }, models: [{ id: "gemini-3.5-flash" }], }; fs.writeFileSync(p, JSON.stringify(c, null, 2) + "\n"); } ' "$PI_MODELS" 2>/dev/null || echo " ${C_RED}✗${C_RESET} [pi] Could not update $PI_MODELS — add the acp provider from /integrations/pi by hand" PI_LAUNCH=$(cat << 'EOF' pi --model "acp/${ACP_PI_MODEL:-gemini-3.5-flash}" "$@" EOF ) acp_write_launcher pi-acp pi ACP_BEARER_TOKEN pi "$PI_LAUNCH" acp_write_directive "$HOME/.pi/agent/AGENTS.md" "pi" "~/.acp/bin/pi-acp" pi \ '- **Tool calls** are governed by the ACP extension in ~/.pi/agent/extensions. Nothing extra to do.' \ '- The `acp` provider is already in `~/.pi/agent/models.json`; do not add it again — the launcher passes `--model acp/`.' echo " ${C_GREEN}✓${C_RESET} [pi] Cost X-ray wrapper installed: pi-acp (+ acp provider in models.json, ~/.pi/agent/AGENTS.md directive)" fi # Prime Agent (pi fork) — providers are registered by extensions # (pi.registerProvider, verified in pi's core/extensions/types.ts). The # extension below is GATED on ACP_PROXY=1, which only prime-acp sets, so # plain `prime` never loads it. apiKey "$ACP_KEY" is env-interpolated by # pi's resolve-config-value. Paths follow the confirmed # ~/.prime/agent/extensions/ convention. if [ "$HAS_PRIME" = true ]; then PRIME_EXT_DIR="$HOME/.prime/agent/extensions" mkdir -p "$PRIME_EXT_DIR" cat > "$PRIME_EXT_DIR/acp-proxy.ts" << 'PRIMEEXT' // acp-proxy — ACP cost X-ray provider for Prime Agent. Written by the ACP // installer; active ONLY when launched via ~/.acp/bin/prime-acp (ACP_PROXY=1). // Plain `prime` never loads this provider. Docs: agenticcontrolplane.com export default function (pi: any) { if (process.env.ACP_PROXY !== "1") return; pi.registerProvider("acp", { name: "Agentic Control Plane", baseUrl: "https://api.agenticcontrolplane.com/v1", apiKey: "$ACP_KEY", api: "openai-completions", models: [{ id: process.env.ACP_PRIME_MODEL || "gemini-3.5-flash", name: process.env.ACP_PRIME_MODEL || "gemini-3.5-flash" }], }); } PRIMEEXT # Binary name differs by install (`prime-agent` from npm, `prime` alias); # resolve once here so the launcher and its fail-open target agree. PRIME_BIN=prime command -v prime-agent > /dev/null 2>&1 && PRIME_BIN=prime-agent PRIME_LAUNCH="ACP_PROXY=1 $PRIME_BIN --model \"acp/\${ACP_PRIME_MODEL:-gemini-3.5-flash}\" \"\$@\"" acp_write_launcher prime-acp "$PRIME_BIN" ACP_BEARER_TOKEN prime "$PRIME_LAUNCH" acp_write_directive "$HOME/.prime/agent/AGENTS.md" "Prime Agent" "~/.acp/bin/prime-acp" prime \ '- **Tool calls** are governed by the ACP extension in ~/.prime/agent/extensions. Nothing extra to do.' \ '- The `acp` provider is registered by ~/.prime/agent/extensions/acp-proxy.ts only when ACP_PROXY=1 — the launcher sets it; do not register a provider by hand.' echo " ${C_GREEN}✓${C_RESET} [Prime Agent] Cost X-ray wrapper installed: prime-acp (+ acp-proxy extension, ~/.prime/agent/AGENTS.md directive)" fi # Grok Build — custom model = [model.] in ~/.grok/config.toml with # base_url + env_key (xAI settings reference: "prefer env_key over # hardcoding api_key"), selected per launch with `-m acp`; [models] # default is left alone. Fill-only: an existing [model.acp] is kept. if [ "$HAS_GROK" = true ]; then GROK_TOML="${GROK_HOME:-$HOME/.grok}/config.toml" mkdir -p "$(dirname "$GROK_TOML")" [ -f "$GROK_TOML" ] || touch "$GROK_TOML" if ! grep -q "^\[model\.acp\]" "$GROK_TOML"; then cat >> "$GROK_TOML" << 'GROKBLOCK' [model.acp] name = "Agentic Control Plane" model = "gemini-3.5-flash" base_url = "https://api.agenticcontrolplane.com/v1" env_key = "ACP_KEY" api_backend = "chat_completions" GROKBLOCK fi GROK_LAUNCH=$(cat << 'EOF' grok -m acp "$@" EOF ) acp_write_launcher grok-acp grok ACP_BEARER_TOKEN grok "$GROK_LAUNCH" acp_write_directive "${GROK_HOME:-$HOME/.grok}/AGENTS.md" "Grok Build" "~/.acp/bin/grok-acp" grok \ '- **Tool calls** are intercepted by the ACP hook in ~/.grok/hooks. Nothing extra to do.' \ '- `[model.acp]` is already in ~/.grok/config.toml and reads the key from the `ACP_KEY` environment variable; do not add an api_key — the launcher passes `-m acp`.' echo " ${C_GREEN}✓${C_RESET} [Grok Build] Cost X-ray wrapper installed: grok-acp (+ [model.acp] in config.toml, AGENTS.md directive)" fi # DeepSeek Harness — provider block in $DSH_HOME/settings.yaml (verbatim # shape from docs/user/guide/providers.md; apiKeyEnv reads the launcher's # env). dsh has no --model flag: the model is chosen per profile, so the # launcher exports the key and says how to select the provider. Fill-only # and comment-preserving: written only when no acp provider exists. if [ "$HAS_DSH" = true ]; then DSH_SETTINGS="${DSH_HOME:-$HOME/.dsh}/settings.yaml" mkdir -p "$(dirname "$DSH_SETTINGS")" [ -f "$DSH_SETTINGS" ] || touch "$DSH_SETTINGS" if ! grep -qE "^\s+acp:\s*$" "$DSH_SETTINGS" && ! grep -q "api.agenticcontrolplane.com" "$DSH_SETTINGS"; then if grep -q "^llm-pi-ai:" "$DSH_SETTINGS" && grep -q "^ providers:" "$DSH_SETTINGS"; then echo " ${C_DIM}[dsh] settings.yaml already has llm-pi-ai.providers — add the acp provider from /integrations/dsh by hand (installer never rewrites your YAML).${C_RESET}" else cat >> "$DSH_SETTINGS" << 'DSHBLOCK' # Agentic Control Plane cost X-ray provider (written by the ACP installer). # Select it in a profile's default model as provider "acp"; dsh-acp exports the key. llm-pi-ai: providers: acp: apiKeyEnv: ACP_BEARER_TOKEN api: openai-completions baseURL: https://api.agenticcontrolplane.com/v1 compat: supportsDeveloperRole: false maxTokensField: max_tokens models: - id: gemini-3.5-flash DSHBLOCK fi fi DSH_LAUNCH=$(cat << 'EOF' # dsh has no --model flag: pick provider "acp" as the default model in the # profile you launch (dsh --profile

); the key travels via ACP_BEARER_TOKEN. dsh "$@" EOF ) acp_write_launcher dsh-acp dsh ACP_BEARER_TOKEN dsh "$DSH_LAUNCH" acp_write_directive "${DSH_HOME:-$HOME/.dsh}/AGENTS.md" "DeepSeek Harness" "~/.acp/bin/dsh-acp" dsh \ '- **Tool calls** are governed by the ACP Cordis plugin. Nothing extra to do.' \ '- The `acp` provider is already in settings.yaml (reads ACP_BEARER_TOKEN); select it as the default model of the profile you run. Do not paste a key into settings.yaml.' echo " ${C_GREEN}✓${C_RESET} [dsh] Cost X-ray wrapper installed: dsh-acp (+ acp provider in settings.yaml, AGENTS.md directive)" fi # Not written here, and why (see the table on /cost-tracking): # Cursor CLI, Antigravity, fx, Muse Code — no way to redirect model # traffic to an external base URL; tool governance only. # OpenClaw — a long-lived gateway daemon; the model endpoint is # persistent config (openclaw config set models.providers.acp …), not # a per-launch choice, so /integrations/openclaw documents it instead. fi # LOCAL_MODE=false (Step 1f) # ── Local mode: skip login, seed a default policy, done ─────────────── if [ "$LOCAL_MODE" = true ]; then if [ ! -f "$CONFIG_DIR/policy.json" ]; then cat > "$CONFIG_DIR/policy.json" << 'POLICY' { "_comment": "Local ACP policy — edit freely. decide.mjs walks keys most-specific → least (e.g. Bash.curl.api.github.com → Bash.curl → Bash). Values: allow | ask | deny. The safety floor applies regardless of this file: rm -rf on your home or root, mkfs, dd onto a disk, and fork bombs are always denied; force-push, destructive SQL, piping a download into a shell, and a recursive delete outside the working directory are always held for your approval (a deny here can tighten that, nothing can loosen it). 'default' applies when no rule matches. 'contextGuard' sizes whole-file reads (Read, cat, head, tail, less, more) before they happen: mode shadow only records what a read over maxLines would have put into context (see ~/.acp/audit.jsonl → contextGuard.estTokens); set mode to enforce to block them with a steer toward offset/limit, grep, or a subagent.", "default": "allow", "rules": { "Bash.rm": "ask", "Bash.curl": "ask", "Bash.git.push": "ask", "Bash.chmod": "ask", "Bash.chown": "ask" }, "contextGuard": { "maxLines": 350, "mode": "shadow", "action": "deny" } } POLICY fi echo "" echo " ${C_GREEN}ALLOW${C_RESET} local mode active — no account, nothing leaves your machine" echo " ${C_DIM}Hooks installed for:${C_RESET} $INSTALLED" [ "$HAS_CODEX" = true ] && echo " ${C_DIM}Codex note: PreToolUse/PostToolUse hooks cover every local tool call, not just shell commands.${C_RESET}" echo "" echo " Decisions run on-device from ${C_DIM}~/.acp/policy.json${C_RESET} (edit it — allow / ask / deny)." echo " Every call is logged to ${C_DIM}~/.acp/audit.jsonl${C_RESET}:" echo " ${C_DIM}tail -f ~/.acp/audit.jsonl${C_RESET}" echo "" echo " Your rules apply from the first call; there is no mode switch in local mode." echo " The safety floor applies regardless: rm -rf on your home or root, disk wipes," echo " and fork bombs are always blocked; force-push, destructive SQL, piping a download" echo " into a shell, and deleting outside your project are held for your approval." echo "" echo " Restart your AI client to activate the hook." echo " Want team control, cost X-ray, and a shared console across everyone's agents?" echo " Re-run without ${C_DIM}--local${C_RESET} to connect a workspace." echo "" echo " If ACP is useful, a star helps others find it: https://github.com/agentic-control-plane/claude-code-acp-plugin" echo "" exit 0 fi # ── Step 2: Authenticate ────────────────────────────────────────────── ACP_STEP="auth" if [ "$UPDATE_MODE" = true ]; then # --update never mints a key. Everything above (govern.mjs, launchers, # hooks, directive blocks) has already been refreshed for every harness # detected on this machine; ~/.acp/credentials is left exactly as it was. if [ ! -f "$CREDS_FILE" ]; then echo "" echo " ${C_DIM}--update found no existing ~/.acp/credentials — nothing to refresh a key against.${C_RESET}" echo " Run the installer once without --update first:" echo " curl -sf https://agenticcontrolplane.com/install.sh | bash" echo "" exit 1 fi echo "" echo " ${C_GREEN}✓${C_RESET} Updated. Hooks installed for: $INSTALLED" echo " Credentials unchanged (~/.acp/credentials)." echo "" exit 0 fi if [ -f "$CREDS_FILE" ]; then echo " Credentials already configured." echo "" # No TTY (an agent re-running the installer for its user, CI, a piped # shell): keep the existing key and finish cleanly instead of dying on # /dev/tty — found by scripts/test-install-sandbox.sh, 2026-09-07. # ACP_RECONFIGURE=1 forces a re-login without a prompt. REPLY="" if [ "${ACP_RECONFIGURE:-0}" = 1 ]; then REPLY=y elif [ -r /dev/tty ] && read -p " Reconfigure? (y/N) " -n 1 -r /dev/null; then : else echo " (no terminal — keeping the existing key; set ACP_RECONFIGURE=1 to re-login)" fi echo "" if [[ ! $REPLY =~ ^[Yy]$ ]]; then echo "" echo " You're all set. View your audit logs:" echo " $DASHBOARD_BASE/activity" echo "" # Hooks were rewritten with the existing key, so this is a finished # install; report it so a typed floor answer (step 1c) reaches the # workspace (no answer typed = no `floor` field). step=rerun keeps these out of the first-install funnel (install_completed # with step=done is the number the funnel counts). ACP_STEP="rerun" _acp_report completed 0 >/dev/null exit 0 fi fi # Snapshot any pre-existing key so the verify step below can tell a # freshly pasted key apart from one left over before a reconfigure. CREDS_BEFORE="" if [ -f "$CREDS_FILE" ]; then CREDS_BEFORE="$(cat "$CREDS_FILE" 2>/dev/null || true)" fi # ── Done ────────────────────────────────────────────────────────────── echo "" echo " ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" echo " Hooks installed for: $INSTALLED" echo " ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" echo "" # ── Get the key ONTO THIS MACHINE (device code, RFC 8628) ───────────── ACP_STEP="device_flow" # April's c099916 removed the token paste on the grounds that "browser # handles provisioning now". Provisioning did move to the browser — but a # web page cannot write ~/.acp/credentials, so *delivery* silently became a # human copy-paste, and anyone who closed the tab ended up with hooks and no # key. Device code closes that: the human approves a short code in a browser # they're already signed into, and THIS SCRIPT writes the key. Nothing is # ever pasted, so nothing depends on shell quoting (which is what made the # original paste flow unfixable on Windows and in curl|bash). KEY_SEEN=false ACP_UNGOVERNED=false DEVICE_BUDGET=300 # seconds; the code itself lives longer, but a curl|bash # must not hang indefinitely if the user walks away. DEVICE_INFO="$(node -e ' const API = process.argv[1]; (async () => { try { const r = await fetch(API + "/device/code", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client: process.argv[2] || "cli", platform: process.platform, installer: "sh" }), }); if (!r.ok) process.exit(1); const d = await r.json(); if (!d.device_code || !d.user_code) process.exit(1); process.stdout.write([ d.user_code, d.verification_uri_complete || d.verification_uri, d.device_code, d.interval || 5, ].join("\t")); } catch { process.exit(1); } })(); ' "$API_BASE" "$CLIENT_SLUG" 2>/dev/null || true)" USER_CODE="$(printf "%s" "$DEVICE_INFO" | cut -f1)" VERIFY_URL="$(printf "%s" "$DEVICE_INFO" | cut -f2)" DEVICE_CODE="$(printf "%s" "$DEVICE_INFO" | cut -f3)" DEVICE_INTERVAL="$(printf "%s" "$DEVICE_INFO" | cut -f4)" if [ -n "$DEVICE_CODE" ]; then echo " Approve this machine — your code is:" echo "" echo " ${C_GREEN}$USER_CODE${C_RESET}" echo "" # Always print the URL. Over SSH or on a headless box xdg-open exists but # opens nothing, and a code with nowhere to type it is a dead end. echo " Approve at: $VERIFY_URL" if command -v open > /dev/null 2>&1; then open "$VERIFY_URL" 2>/dev/null || true echo " ${C_DIM}Opening your browser (code is pre-filled)…${C_RESET}" elif command -v xdg-open > /dev/null 2>&1; then xdg-open "$VERIFY_URL" 2>/dev/null || true echo " ${C_DIM}Opening your browser (code is pre-filled)…${C_RESET}" fi echo "" printf " %sWaiting for approval (up to %ss; Ctrl+C is safe — re-run any time)%s " \ "$C_DIM" "$DEVICE_BUDGET" "$C_RESET" # Writes the key itself on success. Progress goes to stderr so stdout # stays clean for anything piping this installer. if printf '%s' "$DEVICE_CODE" | node -e ' const fs = require("fs"); // The device code arrives on stdin, never argv: argv is world-readable // via ps, and anyone who reads the code can race us for the minted key. const [API, credsFile, budget, interval] = process.argv.slice(1); const deviceCode = fs.readFileSync(0, "utf8").trim(); const deadline = Date.now() + Number(budget) * 1000; let wait = Number(interval) * 1000; (async () => { while (Date.now() < deadline) { await new Promise((r) => setTimeout(r, wait)); let res, body; try { res = await fetch(API + "/device/token", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ device_code: deviceCode }), }); body = await res.json(); } catch { process.stderr.write("~"); continue; } if (res.ok && typeof body.apiKey === "string" && body.apiKey.trim()) { fs.writeFileSync(credsFile, body.apiKey.trim() + "\n", { mode: 0o600 }); try { fs.chmodSync(credsFile, 0o600); } catch {} process.exit(0); } if (body && body.error === "slow_down") { wait += 5000; process.stderr.write("_"); continue; } if (body && body.error === "authorization_pending") { process.stderr.write("."); continue; } process.exit(1); // expired_token, access_denied, anything unexpected } process.exit(1); })(); ' "$API_BASE" "$CREDS_FILE" "$DEVICE_BUDGET" "$DEVICE_INTERVAL"; then KEY_SEEN=true fi else # Never brick: if /device/code is unreachable, fall back to the browser # page and the manual one-liner rather than leaving the user with nothing. AUTH_URL="$DASHBOARD_BASE/plugin/authorize?setup=cli" if command -v open > /dev/null 2>&1; then open "$AUTH_URL" 2>/dev/null || true elif command -v xdg-open > /dev/null 2>&1; then xdg-open "$AUTH_URL" 2>/dev/null || true fi echo " ${C_DIM}Automatic setup unavailable — finish in the browser:${C_RESET}" echo " $AUTH_URL" echo "" echo " Then save the key it shows you:" echo "" echo " echo 'YOUR_API_KEY' > ~/.acp/credentials" fi # Reconfigure edge: approval didn't complete but a key was already here — # verify that one rather than declaring the machine ungoverned. if [ "$KEY_SEEN" = false ] && [ -n "$CREDS_BEFORE" ]; then KEY_SEEN=true fi echo "" echo "" if [ "$KEY_SEEN" = true ]; then ACP_KEY="$(head -n 1 "$CREDS_FILE" 2>/dev/null | tr -d '[:space:]')" HTTP_CODE="$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 \ -H "Authorization: Bearer $ACP_KEY" \ "$API_BASE/api/v1/runs?window=6h" 2>/dev/null || true)" if [ "$HTTP_CODE" = "200" ]; then # First GOVERNED call, through the real hook path (node + govern.mjs + # gateway + audit log). Distinguishes "installed and idle" from "hook # broken" server-side, and the user's dashboard gets its first row. BEACON_SESSION="install-$(date +%s)" printf '{"tool_name":"install.verify","tool_input":{"harness":"%s","installer":"sh"},"session_id":"%s","hook_event_name":"PreToolUse"}' \ "$INSTALLED" "$BEACON_SESSION" \ | env ACP_CLIENT=installer node "$CONFIG_DIR/govern.mjs" >/dev/null 2>&1 || true echo " ${C_GREEN}ALLOW${C_RESET} install.verify · key valid · first governed call logged" # The first-value permalink: first value is a URL in # the terminal — the governed run this install just created, by its key # (runKey == session_id), not a generic dashboard page. echo " ${C_DIM}Your first governed run:${C_RESET} $DASHBOARD_BASE/sessions/$BEACON_SESSION" # Two-plane coverage report: what this # workspace's traffic actually has, per client, with the exact missing # step — the same contract the console Coverage card renders. On a fresh # workspace there's only the beacon, so print the one-liner instead. SLUG="$(printf '%s' "$ACP_KEY" | cut -d_ -f2)" COV_JSON="$(curl -s --max-time 10 -H "Authorization: Bearer $ACP_KEY" "$API_BASE/$SLUG/admin/coverage" 2>/dev/null || true)" if [ -n "$COV_JSON" ]; then printf '%s' "$COV_JSON" | node -e ' let raw=""; process.stdin.on("data",(d)=>raw+=d); process.stdin.on("end",()=>{ try{ const d=JSON.parse(raw); if(!d.ok||!Array.isArray(d.clients)) return; const real=d.clients.filter((c)=>c.client!=="installer"); console.log(""); console.log(" Coverage — interception governs tool calls, the proxy prices model calls:"); if(!real.length){ console.log(" interception ✓ (verified just now) · proxy comes up with your first model call through it"); } for(const c of real){ const m=(p)=>p&&p.active?"✓":"✗"; console.log(" "+c.client.padEnd(22)+" interception "+m(c.interception)+" · proxy "+m(c.proxy)); if(c.fix) console.log(" → "+c.fix.run); } }catch(e){} });' 2>/dev/null || true echo " ${C_DIM}Live checklist:${C_RESET} $DASHBOARD_BASE (Coverage card, per agent)" fi else echo " ${C_RED}Couldn't verify the key${C_RESET} (HTTP ${HTTP_CODE:-000})." echo " ${C_DIM}Check that ~/.acp/credentials contains exactly the key the page showed,${C_RESET}" echo " ${C_DIM}then confirm your first calls at${C_RESET} $DASHBOARD_BASE/activity" fi else # Not fine. Hooks without a key are a silent no-op: govern.mjs finds no # token and lets every call through without a policy check or an audit # row, and the server cannot tell that machine apart from one that never # installed. Saying "that's fine" here is what left real users believing # they were governed while they weren't. ACP_UNGOVERNED=true echo " ${C_RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${C_RESET}" echo " ${C_RED}! NOT GOVERNED YET — no API key saved${C_RESET}" echo " ${C_RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${C_RESET}" echo "" echo " The hooks are installed, but with no key they cannot reach ACP." echo " Until you save one, every tool call runs UNCHECKED and nothing is" echo " audited. This install is not protecting you yet." echo "" echo " Finish logging in, then run:" echo "" echo " echo 'YOUR_API_KEY' > ~/.acp/credentials" echo "" echo " Then restart your agent and confirm at $DASHBOARD_BASE/activity" fi echo "" if [ "$HAS_CLAUDE" = true ]; then echo " Then restart Claude Code (Ctrl+C, then claude --continue)" echo "" echo " Claude Code — two ways to run:" echo " claude tool calls governed + audited (hooks)" echo " claude-acp the above PLUS every model call priced —" echo " the cost X-ray, billed to your own account" fi if [ "$HAS_CURSOR" = true ]; then echo " Then restart Cursor to activate the hook" fi if [ "$HAS_CODEX" = true ]; then echo " Then restart Codex (Ctrl+C, then codex) to activate the hook" echo "" echo " Codex — two ways to run:" echo " codex tool calls governed + audited (hooks)" echo " codex-acp the above PLUS every model call priced —" echo " the cost X-ray, billed to your own account" fi if [ "$HAS_OPENCODE" = true ] && [ "$LOCAL_MODE" = false ]; then echo "" echo " opencode — two ways to run:" echo " opencode tool calls governed + audited (plugin)" echo " opencode-acp the above PLUS every model call priced —" echo " the cost X-ray via the acp/ provider" fi # Same two-line summary for every launcher Step 1f generated. for _lb in hermes qwen pi prime grok dsh; do if [ "$LOCAL_MODE" = false ] && [ -x "$CONFIG_DIR/bin/$_lb-acp" ]; then echo "" echo " $_lb — two ways to run:" echo " $_lb tool calls governed + audited" echo " $_lb-acp the above PLUS every model call priced (the cost X-ray)" fi done if [ "$HAS_OPENCLAW" = true ]; then echo " Then restart OpenClaw to activate the plugin" fi if [ "$HAS_QWEN" = true ]; then echo " Then restart Qwen Code (Ctrl+C, then qwen) to activate the hook — headless runs (qwen --prompt) resolve any ask to deny" fi if [ "$HAS_COPILOT" = true ]; then echo " Then restart Copilot CLI (and reload VS Code) to activate the hook — hook files are read at startup." echo " Cloud coding-agent runs read only the repo's .github/hooks/: https://agenticcontrolplane.com/integrations/copilot#repo" fi echo "" # The exit, named at the entrance. Someone who cannot see how to leave # reads the install as something done TO them; the removal path is part of # the pitch, not an admission. Also lists what we wrote, because the # alternative is them discovering it later and grepping for our marker. echo " ${C_DIM}What this wrote, and how to undo it: $SITE_BASE/trust" echo " Remove everything, keeping your own config: acp-uninstall${C_RESET}" echo "" if [ "${ACP_UNGOVERNED:-false}" != true ]; then echo " If ACP is useful, a star helps others find it: https://github.com/agentic-control-plane/claude-code-acp-plugin" echo "" fi # Exit non-zero when the install finished without a usable key, so the state # is detectable by a wrapper, a CI check, or the user's shell — not only by # reading the banner. Distinct code (2) so it is not confused with a crash. if [ "${ACP_UNGOVERNED:-false}" = true ]; then ACP_STEP="no_key" exit 2 fi ACP_STEP="done" [ "$UPDATE_MODE" = false ] && _acp_report completed 0 >/dev/null exit 0 }