From 7602dfa9f0d227c089155dd6b997563f10fc324f Mon Sep 17 00:00:00 2001 From: Amandeep Khurana Date: Wed, 9 Sep 2026 18:32:57 +0000 Subject: [PATCH] fix(acp): start the claude CLI without the bypass-permissions flag claude-agent-acp asks the Agent SDK for allowDangerouslySkipPermissions on every non-root session, which puts --allow-dangerously-skip-permissions on the claude command line. That flag is the capability to enter bypassPermissions, the one mode in which the adapter never sends session/request_permission. Crew never selects that mode, and the adapter gives an ACP client no way to turn the option off. The claude backend now points CLAUDE_CODE_EXECUTABLE at a small node launcher shipped in the package. It drops that one flag and starts the real CLI with every other argument, stdio and the environment unchanged. An operator-set CLAUDE_CODE_EXECUTABLE is still the CLI that runs. Sessions no longer fail on a CLI that refuses the flag in its environment. The ACP spec no longer claims the adapter is vendored into the build; nothing in this repository ships it. --- MANIFEST.in | 2 + docs/system-specs/modules/acp-client.md | 2 +- .../modules/claude-code-provider.md | 61 ++++- setup.cfg | 4 + src/kiro_crew/acp/claude_launcher.mjs | 68 +++++ src/kiro_crew/acp/client.py | 89 +++++-- test/test_claude_launcher.py | 233 ++++++++++++++++++ 7 files changed, 438 insertions(+), 21 deletions(-) create mode 100755 src/kiro_crew/acp/claude_launcher.mjs create mode 100644 test/test_claude_launcher.py diff --git a/MANIFEST.in b/MANIFEST.in index 4e59a0c82895..f71bb09ac90b 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -43,6 +43,8 @@ recursive-include src/kiro_crew/docs *.md # a missing line here drops the file from every published artifact. recursive-include src/kiro_crew/docs *.json recursive-include src/kiro_crew/tests_fixtures * +# The claude CLI launcher the Claude backend starts its CLI through (acp/client.py). +include src/kiro_crew/acp/claude_launcher.mjs # --- Pruning: never ship test trees, vendored node deps, or build cruft ------ prune test diff --git a/docs/system-specs/modules/acp-client.md b/docs/system-specs/modules/acp-client.md index 982269b7f380..dd834884781c 100644 --- a/docs/system-specs/modules/acp-client.md +++ b/docs/system-specs/modules/acp-client.md @@ -18,7 +18,7 @@ expose new global files in order for later MCP callbacks to identify themselves. `AcpClient(acp_backend=...)` selects which subprocess to launch: - `""` (default): `kiro-cli acp --agent ` (resolved by `_resolve_kiro_bin`). Per-session kiro settings are layered in via the workspace overlay `/.kiro/settings/cli.json` (written by `AcpProvider`, not the client): reasoning **effort** (`chat.modelDefaults`) and **MCP Tool Search** (`toolSearch.enabled` + activation thresholds from `agent.tool_search_min_pct` / `tool_search_min_tokens`, gated by `agent.tool_search`, default on) — see providers.md. -- `"claude"` (`ACP_BACKEND_CLAUDE`): `claude-agent-acp` (resolved by `_resolve_claude_acp_bin` → `(list[str] | None, str)` (argv plus the augmented PATH actually searched)). Resolution order: `CLAUDE_AGENT_ACP_BIN` env var, then the **vendored copy** (`_resolve_vendored_claude_acp` — `/@agentclientprotocol/claude-agent-acp/dist/index.js` found under the package's `_vendor/node_modules` from the distribution bundle, the sibling `KiroCrewWebsite/node_modules` in a source checkout, or `KIROCREW_PROJECT_DIR`; needs no global npm install or network — matters on hosts that have no package-registry token at gateway runtime), then `mise which claude-agent-acp` (respects MISE_DATA_DIR and all mise config), then a direct glob under mise's Node installs dir (`_mise_node_installs_dir` — `/installs/node`, root from `env.mise_data_dir` so MISE_DATA_DIR / XDG_DATA_HOME are honoured), then augmented PATH (`env.augmented_path` — mise shims, `~/.npm-packages/bin`, `~/.volta/bin`, `/opt/homebrew/bin`, plus EVERY per-version manager bin dir via `env.node_all_bin_dirs` (mise/asdf/nvm/fnm, all installed versions — a global npm binary can live under any of them), so a non-login launchd/systemd gateway also finds globally-installed binaries). The adapter is vendored into the distribution bundle and the pip build by `setup.py` (`_vendor_acp_into_pkg` → `kiro_crew/_vendor/node_modules`), so every install method ships it without asking the user to `npm i -g`. Vendoring copies the adapter **plus its full transitive dependency closure** (`_acp_dependency_closure` walks `dependencies`/`optionalDependencies` from the resolved website `node_modules`, ~96 flat top-level packages) — npm hoists deps like `@agentclientprotocol/sdk` flat, so copying only the adapter package crashes the ESM loader with `ERR_MODULE_NOT_FOUND`. `_resolve_vendored_claude_acp` accepts a root only when the hoisted dependency marker `@agentclientprotocol/sdk` is present alongside the entry, so an incomplete vendored copy is skipped in favour of a complete one instead of being spawned and crashed. For scripts under mise installs, returns `[node_binary, script_path]` to bypass `#!/usr/bin/env node` shebang resolution which fails in non-interactive daemon contexts. For standalone binaries, returns `[binary_path]`. Pre-spawn the client writes `/.claude/settings.local.json` with `defaultMode: default` so the adapter routes every tool decision back to Kiro Crew via `session/request_permission`. This makes claude-agent-acp participate in the same approve / trust_reads / trust / yolo protocol as kiro-cli — dashboard, subagents, channel agents, cron, and heartbeat all share the path. Kiro Crew still enforces per-tool security via `HooksConfig.auto_deny_tools` (evaluated by `HookManager.on_tool_call` in `hooks.py`) on every `session/request_permission` event. `CLAUDE_CONFIG_DIR` (an isolated config root, distinct from the project-scope `/.claude/settings.local.json` the client writes itself) is **not** set by this core: `_spawn` merges a caller's `extra_env` into the child environment, so an edition can point the adapter's `SettingsManager` and the SDK at a seeded root, but with nothing supplied they read the user's global `~/.claude` — which is a live gate-bypass hazard for inherited `permissions.allow` entries, recorded as a known gap in claude-code-provider.md. The env also carries `CLAUDE_CODE_EXECUTABLE` (claude backend only, set in `_spawn` when unset): the adapter delegates the model turn to `@anthropic-ai/claude-agent-sdk`, which needs a per-platform native Claude binary (~250 MB each) shipped as npm `optionalDependencies` that the website install omits — so the vendored closure does **not** include it and the SDK fails `session/new` with `Claude native binary not found for `. The SDK does **not** search PATH for `claude` itself (so the host merely having the external agent CLI installed is not enough), and bundling a quarter-GB binary per platform is not viable; instead `_resolve_claude_code_executable` finds an existing `claude` (`CLAUDE_CODE_EXECUTABLE` override → `mise which claude` → augmented PATH incl. `~/.toolbox/bin`, where a managed distribution may ship the external agent CLI) and the adapter forwards it to the SDK as `pathToClaudeCodeExecutable` (no version check). If none is found the var is left unset (with a warning) so the adapter's native-binary error surfaces rather than a guessed bad path; an explicit operator-set value always wins. +- `"claude"` (`ACP_BACKEND_CLAUDE`): `claude-agent-acp` (resolved by `_resolve_claude_acp_bin` → `(list[str] | None, str)` (argv plus the augmented PATH actually searched)). Resolution order: `CLAUDE_AGENT_ACP_BIN` env var, then a **project-local copy** (`_resolve_vendored_claude_acp` — `/@agentclientprotocol/claude-agent-acp/dist/index.js` found under the package's optional `_vendor/node_modules` or under `KIROCREW_PROJECT_DIR/node_modules`; needs no global npm install or network at gateway runtime), then `mise which claude-agent-acp` (respects MISE_DATA_DIR and all mise config), then a direct glob under mise's Node installs dir (`_mise_node_installs_dir` — `/installs/node`, root from `env.mise_data_dir` so MISE_DATA_DIR / XDG_DATA_HOME are honoured), then augmented PATH (`env.augmented_path` — mise shims, `~/.npm-packages/bin`, `~/.volta/bin`, `/opt/homebrew/bin`, plus EVERY per-version manager bin dir via `env.node_all_bin_dirs` (mise/asdf/nvm/fnm, all installed versions — a global npm binary can live under any of them), so a non-login launchd/systemd gateway also finds globally-installed binaries). This build does **not** ship the adapter: neither `setup.py` nor `website/package.json` carries it, so the operator installs it (`npm i -g @agentclientprotocol/claude-agent-acp`, the command `agent_sdk.backend_install` prints) or drops a copy into one of the roots above. A copy there must include the adapter's full dependency closure — npm hoists deps like `@agentclientprotocol/sdk` flat, and the adapter package alone crashes the ESM loader with `ERR_MODULE_NOT_FOUND`. `_resolve_vendored_claude_acp` accepts a root only when the hoisted dependency marker `@agentclientprotocol/sdk` is present alongside the entry, so an incomplete vendored copy is skipped in favour of a complete one instead of being spawned and crashed. For scripts under mise installs, returns `[node_binary, script_path]` to bypass `#!/usr/bin/env node` shebang resolution which fails in non-interactive daemon contexts. For standalone binaries, returns `[binary_path]`. Pre-spawn the client writes `/.claude/settings.local.json` with `defaultMode: default` so the adapter routes every tool decision back to Kiro Crew via `session/request_permission`. This makes claude-agent-acp participate in the same approve / trust_reads / trust / yolo protocol as kiro-cli — dashboard, subagents, channel agents, cron, and heartbeat all share the path. Kiro Crew still enforces per-tool security via `HooksConfig.auto_deny_tools` (evaluated by `HookManager.on_tool_call` in `hooks.py`) on every `session/request_permission` event. `CLAUDE_CONFIG_DIR` (an isolated config root, distinct from the project-scope `/.claude/settings.local.json` the client writes itself) is **not** set by this core: `_spawn` merges a caller's `extra_env` into the child environment, so an edition can point the adapter's `SettingsManager` and the SDK at a seeded root, but with nothing supplied they read the user's global `~/.claude` — which is a live gate-bypass hazard for inherited `permissions.allow` entries, recorded as a known gap in claude-code-provider.md. The env also carries `CLAUDE_CODE_EXECUTABLE` (claude backend only, set in `_spawn` when unset): the adapter delegates the model turn to `@anthropic-ai/claude-agent-sdk`, which needs a per-platform native Claude binary (~250 MB each) shipped as npm `optionalDependencies` that the website install omits — so the vendored closure does **not** include it and the SDK fails `session/new` with `Claude native binary not found for `. The SDK does **not** search PATH for `claude` itself (so the host merely having the external agent CLI installed is not enough), and bundling a quarter-GB binary per platform is not viable; instead `_point_adapter_at_claude_cli` names an existing `claude` (an operator-set `CLAUDE_CODE_EXECUTABLE` wins; else `_resolve_claude_code_executable`: `mise which claude` → augmented PATH incl. `~/.toolbox/bin`, where a managed distribution may ship the external agent CLI; no version check). It does not hand that path to the adapter directly: `CLAUDE_CODE_EXECUTABLE` is set to **`acp/claude_launcher.mjs`** and the real CLI travels in `KIROCREW_CLAUDE_CODE_EXECUTABLE`. The SDK runs a `.mjs` executable with node, and the launcher drops `--allow-dangerously-skip-permissions` (which the adapter adds for every non-root session) before it starts the real CLI with every other argument, stdio and the environment unchanged, `CLAUDE_CODE_EXECUTABLE` set back to the real path — see [claude-code-provider.md](claude-code-provider.md#the-bypass-capability-is-withheld-by-a-launcher). If no CLI is found the vars are left unset (with a warning) so the adapter's native-binary error surfaces rather than a guessed bad path; a launcher missing from the install falls back to the direct path, with a warning. The resolution runs off the loop through `_to_thread_guarding_sandbox`. When the Claude adapter is not found, the spawn error reports the augmented PATH captured by that resolution attempt. The failed result and its PATH are cached diff --git a/docs/system-specs/modules/claude-code-provider.md b/docs/system-specs/modules/claude-code-provider.md index bc77bfda6337..30529b8b17b8 100644 --- a/docs/system-specs/modules/claude-code-provider.md +++ b/docs/system-specs/modules/claude-code-provider.md @@ -48,12 +48,13 @@ plain public build: returns `(argv, searched_path)`; the result is memoized process-wide in `_claude_acp_argv_cache`, so the search runs once and the "not found" message names exactly the directories that were searched. -- `_resolve_claude_code_executable()` finds the `claude` CLI and `_spawn` exports - it as `CLAUDE_CODE_EXECUTABLE` when the caller has not set one. The adapter - forwards it to `@anthropic-ai/claude-agent-sdk` as - `pathToClaudeCodeExecutable`; without it the SDK fails `session/new` with +- `_point_adapter_at_claude_cli()` names the `claude` CLI (an operator-set + `CLAUDE_CODE_EXECUTABLE` wins, else `_resolve_claude_code_executable()`). The + adapter forwards `CLAUDE_CODE_EXECUTABLE` to `@anthropic-ai/claude-agent-sdk` + as `pathToClaudeCodeExecutable`; without it the SDK fails `session/new` with "Claude native binary not found", because it does not search `PATH` for - `claude` on its own. + `claude` on its own. Crew points that variable at its own launcher rather than + at the CLI; see below. - The adapter is a **public** npm package, `CLAUDE_ACP_NPM_PKG = "@agentclientprotocol/claude-agent-acp"`. Nothing on this path is edition-private. @@ -124,6 +125,56 @@ the untrusted copy being read at all. Whether `claude-agent-acp` forwards either ACP is not answered in this repository, and is the prerequisite for Crew gating *every* Claude tool call rather than every call Claude asks about. +### The bypass capability is withheld by a launcher + +The adapter sets the Agent SDK option `allowDangerouslySkipPermissions` for every +session that is not running as root (`ALLOW_BYPASS = !IS_ROOT || +!!process.env.IS_SANDBOX`), and assigns it after spreading the caller's +`_meta.claudeCode.options`, so a host cannot turn it off over ACP. The SDK turns +it into `--allow-dangerously-skip-permissions` on the `claude` command line: the +*capability* to enter `bypassPermissions`, the one mode in which the adapter never +sends `session/request_permission` at all. Crew never selects that mode +(`CC_PERMISSION_MODE_BYPASS` is named only so guards have one spelling), and it +does not ship the adapter, so it cannot patch that line either. + +What Crew does own is `CLAUDE_CODE_EXECUTABLE`. `_point_adapter_at_claude_cli` +sets it to `acp/claude_launcher.mjs` and passes the real CLI in +`KIROCREW_CLAUDE_CODE_EXECUTABLE`. The SDK runs a `.mjs` executable with node, +and the launcher drops exactly that one flag, then starts the real CLI with +every other argument in order, stdio inherited, the exit status and a +terminating signal propagated, and `CLAUDE_CODE_EXECUTABLE` set back to the real +path so the CLI's own environment is the one it would have had without the hop. +The launcher carries a `#!/usr/bin/env node` shebang and the executable bit, +because the adapter also spawns `CLAUDE_CODE_EXECUTABLE` directly for `claude +auth status`; without them that spawn fails with `EACCES` and every session logs +an auth-status failure even though the session itself runs. + +On Windows the launcher is not used: `_point_adapter_at_claude_cli` starts the +CLI directly there, the pre-launcher path, and logs that the capability is not +withheld. An npm-installed `claude` resolves to a `.cmd` shim on Windows, and +neither the SDK running a `.mjs` executable under node on win32 nor a cmd.exe +routing of that shim has been exercised on a Windows host; a wrong guess on +either would fail every Windows Claude session at `session/new` where the +direct path works today. Enabling the launcher on Windows waits on an +end-to-end verification there, and is a change to this paragraph plus +`test_windows_starts_the_cli_directly_until_verified`. +The operator's choice of binary is kept; only the capability request is +withheld. A CLI that refuses the flag in its environment — it does so as root, +for example — therefore starts instead of failing `session/new` with `Claude +Code process exited with code 1`. + +Scope, stated exactly: the launcher withholds the capability flag and nothing +else. An explicit `--permission-mode bypassPermissions` — which the adapter +passes when a settings file Crew did not author sets `defaultMode` to it — goes +through unchanged, so the inherited-settings boundary described above and in +the known gap below is not closed by this. Such a session still starts: the CLI +accepts `--permission-mode bypassPermissions` without the capability flag when +not running as root (verified on Claude Code 2.1.269), and as root it refuses +exactly as it did before the launcher existed. A launcher missing from the install +falls back to starting the CLI directly, with a warning. Pinned by +`test/test_claude_launcher.py`, which runs the launcher under node against fake +CLIs and pins that the kiro spawn gets neither variable. + ### MCP tools on a Claude session The `claude-agent-acp` adapter reads **no** agent file: the `mcpServers` array on diff --git a/setup.cfg b/setup.cfg index c31ce6af78bb..632cdc3bc035 100644 --- a/setup.cfg +++ b/setup.cfg @@ -229,6 +229,10 @@ kiro_crew = # Without this entry the `apple` STT provider silently reports unavailable on # every pip/DMG install while working perfectly from a source checkout. apple_speech/*.swift + # Launcher the claude-agent-acp adapter's SDK runs in place of the claude CLI + # (acp/client.py, _point_adapter_at_claude_cli). Without it every Claude + # session falls back to starting the CLI directly. + acp/claude_launcher.mjs config/defaults.json config/prompt.md config/prompt-orchestrator.md diff --git a/src/kiro_crew/acp/claude_launcher.mjs b/src/kiro_crew/acp/claude_launcher.mjs new file mode 100755 index 000000000000..b60ed136ec97 --- /dev/null +++ b/src/kiro_crew/acp/claude_launcher.mjs @@ -0,0 +1,68 @@ +#!/usr/bin/env node +// Runs the claude CLI for the claude-agent-acp adapter without asking for the +// bypassPermissions capability. +// +// The adapter sets the Agent SDK option allowDangerouslySkipPermissions for +// every session that is not running as root, and the SDK turns that into +// --allow-dangerously-skip-permissions on the CLI command line. That flag is +// the capability to enter bypassPermissions, the one permission mode in which +// the adapter stops sending session/request_permission, so a session in it +// never reaches the host gate. Kiro Crew never selects that mode, so this +// launcher drops the flag before it starts the real CLI. A CLI that refuses +// the flag in its environment (it does so as root, for example) then starts +// normally instead of failing session/new. +// +// Everything else passes through: the remaining arguments in order, stdio, +// and the environment. An explicit --permission-mode is not rewritten. +// +// Wiring (acp/client.py): CLAUDE_CODE_EXECUTABLE points here, which makes the +// SDK run this file with node, and KIROCREW_CLAUDE_CODE_EXECUTABLE names the +// real CLI. The child sees CLAUDE_CODE_EXECUTABLE set back to the real CLI and +// no KIROCREW_CLAUDE_CODE_EXECUTABLE, so its environment is the one it would +// have had without this hop. +import { spawn } from 'node:child_process' + +const TARGET_ENV = 'KIROCREW_CLAUDE_CODE_EXECUTABLE' +const DROPPED_FLAGS = new Set(['--allow-dangerously-skip-permissions']) +// A JavaScript entry point cannot be exec'd on every platform, so run it with +// this node, the way the SDK itself runs a script-valued executable. +const SCRIPT_SUFFIXES = ['.js', '.mjs', '.cjs'] +// Exit status when the real CLI could not be started at all. +const EXIT_CANNOT_EXECUTE = 127 + +const target = process.env[TARGET_ENV] +if (!target) { + process.stderr.write(`claude launcher: ${TARGET_ENV} is not set\n`) + process.exit(EXIT_CANNOT_EXECUTE) +} + +const args = process.argv.slice(2).filter((arg) => !DROPPED_FLAGS.has(arg)) +const env = { ...process.env, CLAUDE_CODE_EXECUTABLE: target } +delete env[TARGET_ENV] + +const isScript = SCRIPT_SUFFIXES.some((suffix) => target.toLowerCase().endsWith(suffix)) +const command = isScript ? process.execPath : target +const argv = isScript ? [target, ...args] : args + +const child = spawn(command, argv, { stdio: 'inherit', env, windowsHide: true }) + +for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) { + process.on(signal, () => { + if (child.exitCode === null && child.signalCode === null) child.kill(signal) + }) +} + +child.on('error', (err) => { + process.stderr.write(`claude launcher: cannot start ${target}: ${err.message}\n`) + process.exit(EXIT_CANNOT_EXECUTE) +}) + +child.on('exit', (code, signal) => { + if (signal) { + // Die the way the child died, so the SDK sees the same termination. + process.removeAllListeners(signal) + process.kill(process.pid, signal) + return + } + process.exit(code ?? 1) +}) diff --git a/src/kiro_crew/acp/client.py b/src/kiro_crew/acp/client.py index 0fd48d0b2c0e..28a5d094ab95 100644 --- a/src/kiro_crew/acp/client.py +++ b/src/kiro_crew/acp/client.py @@ -257,6 +257,13 @@ # action when the binary is on PATH; otherwise the adapter surfaces its own # native-binary error. CLAUDE_CODE_BIN = "claude" +# Kiro Crew's launcher for that CLI (``claude_launcher.mjs`` beside this module). +# ``CLAUDE_CODE_EXECUTABLE`` points at it and ``_ENV_CLAUDE_LAUNCHER_TARGET`` names +# the real CLI, so the adapter's SDK starts the CLI through it; the launcher drops +# ``--allow-dangerously-skip-permissions``, which the adapter adds for every +# non-root session. See :func:`_point_adapter_at_claude_cli`. +_CLAUDE_LAUNCHER = Path(__file__).with_name("claude_launcher.mjs") +_ENV_CLAUDE_LAUNCHER_TARGET = "KIROCREW_CLAUDE_CODE_EXECUTABLE" # npm package that provides the claude-agent-acp binary. Install it publicly # with ``npm i -g @agentclientprotocol/claude-agent-acp`` (or add it as a # project dependency); resolution also accepts a copy under a project-local @@ -906,6 +913,65 @@ def _resolve_claude_code_executable() -> str | None: return _normalize_exe_casing(shutil.which(CLAUDE_CODE_BIN, path=search_path)) +def _point_adapter_at_claude_cli(env: dict[str, str]) -> None: + """Name the claude CLI in *env* for a claude-agent-acp child, via the launcher. + + The adapter hands ``CLAUDE_CODE_EXECUTABLE`` to its SDK as + ``pathToClaudeCodeExecutable``, and the SDK does not search ``PATH`` for + ``claude`` on its own, so the spawn has to name one: an explicit + ``CLAUDE_CODE_EXECUTABLE`` already in *env* (the operator's environment or the + caller's ``extra_env``) wins, else :func:`_resolve_claude_code_executable`. + + That CLI is started through :data:`_CLAUDE_LAUNCHER`. The adapter sets the SDK + option ``allowDangerouslySkipPermissions`` for every non-root session, which + puts ``--allow-dangerously-skip-permissions`` on the CLI command line: the + capability to enter ``bypassPermissions``, the one mode in which the adapter + stops sending ``session/request_permission`` and so stops reaching the host + gate. Crew never selects that mode, so the launcher drops the flag and passes + everything else through. The operator's choice of binary is kept; only the + capability request is withheld. + + A launcher missing from the install starts the CLI directly, with a warning, + which is the behaviour before the launcher existed. So does Windows, on + purpose: an npm-installed ``claude`` resolves to a ``.cmd`` shim there, and + neither "the SDK runs a ``.mjs`` executable under node on win32" nor a + cmd.exe routing of that shim has been exercised on a Windows host, so the + pre-launcher direct path stays until one verifies it end to end. The bypass + capability is therefore still requested on Windows; the log line says so. + Blocking (``which``, a possible ``mise`` subprocess, a stat), so the caller + runs it off the loop. + """ + claude_exe = env.get("CLAUDE_CODE_EXECUTABLE") or _resolve_claude_code_executable() + if not claude_exe: + logger.warning( + "%s not found on PATH; the claude-agent-acp adapter will " + "fail with 'Claude native binary not found'. Set " + "CLAUDE_CODE_EXECUTABLE.", + CLAUDE_CODE_BIN, + ) + return + if platform_compat.IS_WINDOWS: + logger.info( + "Windows: starting %s directly; the claude launcher is not yet verified " + "on this platform, so the adapter's --allow-dangerously-skip-permissions " + "is not withheld here.", + claude_exe, + ) + env["CLAUDE_CODE_EXECUTABLE"] = claude_exe + return + if not _CLAUDE_LAUNCHER.is_file(): + logger.warning( + "claude launcher missing at %s; starting %s directly, so it receives " + "--allow-dangerously-skip-permissions from the adapter.", + _CLAUDE_LAUNCHER, + claude_exe, + ) + env["CLAUDE_CODE_EXECUTABLE"] = claude_exe + return + env[_ENV_CLAUDE_LAUNCHER_TARGET] = claude_exe + env["CLAUDE_CODE_EXECUTABLE"] = str(_CLAUDE_LAUNCHER) + + def _claude_settings_usable(path: Path) -> bool: """Whether Crew may create *path* at all. @@ -6091,21 +6157,14 @@ async def _spawn(self) -> None: if self._extra_env: env.update(self._extra_env) env["PATH"] = augmented_path(env.get("PATH", "")) - if self._is_claude and not env.get("CLAUDE_CODE_EXECUTABLE"): - # Dormant seam (see _spawn docstring): the adapter's SDK needs a - # native Claude binary we don't vendor and does NOT search PATH for - # `claude` itself, so point it at one explicitly when the seam is - # driven. Only set when unset so an operator override always wins. - claude_exe = _resolve_claude_code_executable() - if claude_exe: - env["CLAUDE_CODE_EXECUTABLE"] = claude_exe - else: - logger.warning( - "%s not found on PATH; the claude-agent-acp adapter will " - "fail with 'Claude native binary not found'. Set " - "CLAUDE_CODE_EXECUTABLE.", - CLAUDE_CODE_BIN, - ) + if self._is_claude: + # The adapter's SDK needs a claude CLI and does NOT search PATH for + # one, so name it -- an operator-set CLAUDE_CODE_EXECUTABLE wins -- + # and start it through Crew's launcher, which withholds the + # bypass-permissions capability the adapter always asks for. Off-loop + # and guarded: it may run `which`/`mise`, and the sandbox temp file + # is live from here to the exec. + await self._to_thread_guarding_sandbox(_point_adapter_at_claude_cli, env) if self._is_opencode and self._opencode_config_content: # The seed the read-back above verified, applied unconditionally: the # merge in ``_opencode_routing_config`` already preserved every key the diff --git a/test/test_claude_launcher.py b/test/test_claude_launcher.py new file mode 100644 index 000000000000..886ee792c8d8 --- /dev/null +++ b/test/test_claude_launcher.py @@ -0,0 +1,233 @@ +"""The claude CLI launcher: the Claude backend never asks for the bypass capability. + +claude-agent-acp sets the Agent SDK option ``allowDangerouslySkipPermissions`` for +every non-root session, which puts ``--allow-dangerously-skip-permissions`` on the +claude command line -- the capability to enter ``bypassPermissions``, the one mode +in which the adapter stops sending ``session/request_permission``. Crew never +selects that mode, so ``_spawn`` points ``CLAUDE_CODE_EXECUTABLE`` at +``acp/claude_launcher.mjs``, which drops that flag and starts the real CLI. + +Two halves are pinned here: the wiring in ``acp/client.py`` (which executable the +adapter is told about), and the launcher itself, run under node against fake CLIs. +""" + +from __future__ import annotations + +import json +import logging +import os +import shutil +import subprocess +import sys +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from kiro_crew.acp import client as client_mod +from kiro_crew.acp.client import AcpClient +from kiro_crew.acp.types import ACP_BACKEND_CLAUDE + +_REPO_ROOT = Path(__file__).resolve().parents[1] +_NODE = shutil.which("node") +_NEEDS_NODE = pytest.mark.skipif(_NODE is None, reason="the launcher runs under node") +_POSIX_ONLY = pytest.mark.skipif(sys.platform == "win32", reason="POSIX exec semantics") +_TARGET_ENV = "KIROCREW_CLAUDE_CODE_EXECUTABLE" +_BYPASS_FLAG = "--allow-dangerously-skip-permissions" + +# A fake claude CLI: reports the argv and the two env vars the launcher manages, +# then exits with FAKE_EXIT so exit-status propagation is observable. +_FAKE_CLI_JS = """ +process.stdout.write(JSON.stringify({ + argv: process.argv.slice(2), + executable: process.env.CLAUDE_CODE_EXECUTABLE ?? null, + target: process.env.KIROCREW_CLAUDE_CODE_EXECUTABLE ?? null, +})) +process.exit(Number(process.env.FAKE_EXIT ?? 0)) +""" + + +class TestPointAdapterAtClaudeCli: + @pytest.fixture(autouse=True) + def _posix(self, monkeypatch): + # The launcher path is POSIX-only until a Windows host verifies it; pin + # the platform so these assertions mean the same thing on every shard. + monkeypatch.setattr(client_mod.platform_compat, "IS_WINDOWS", False) + + def test_windows_starts_the_cli_directly_until_verified(self, monkeypatch, caplog): + monkeypatch.setattr(client_mod.platform_compat, "IS_WINDOWS", True) + monkeypatch.setattr(client_mod, "_resolve_claude_code_executable", lambda: "C:\\claude.cmd") + env: dict[str, str] = {} + with caplog.at_level(logging.INFO, logger=client_mod.logger.name): + client_mod._point_adapter_at_claude_cli(env) + assert env == {"CLAUDE_CODE_EXECUTABLE": "C:\\claude.cmd"} + assert "not yet verified" in caplog.text + + def test_resolved_cli_is_started_through_the_launcher(self, monkeypatch): + monkeypatch.setattr(client_mod, "_resolve_claude_code_executable", lambda: "/opt/claude") + env: dict[str, str] = {} + client_mod._point_adapter_at_claude_cli(env) + assert env["CLAUDE_CODE_EXECUTABLE"] == str(client_mod._CLAUDE_LAUNCHER) + assert env[_TARGET_ENV] == "/opt/claude" + + def test_operator_choice_of_binary_is_kept(self, monkeypatch): + def _must_not_resolve(): + raise AssertionError("an explicit CLAUDE_CODE_EXECUTABLE must win") + + monkeypatch.setattr(client_mod, "_resolve_claude_code_executable", _must_not_resolve) + env = {"CLAUDE_CODE_EXECUTABLE": "/custom/claude"} + client_mod._point_adapter_at_claude_cli(env) + assert env[_TARGET_ENV] == "/custom/claude" + assert env["CLAUDE_CODE_EXECUTABLE"] == str(client_mod._CLAUDE_LAUNCHER) + + def test_no_cli_found_sets_nothing_and_warns(self, monkeypatch, caplog): + monkeypatch.setattr(client_mod, "_resolve_claude_code_executable", lambda: None) + env: dict[str, str] = {} + with caplog.at_level(logging.WARNING, logger=client_mod.logger.name): + client_mod._point_adapter_at_claude_cli(env) + assert env == {} + assert "Claude native binary not found" in caplog.text + + def test_missing_launcher_starts_the_cli_directly(self, monkeypatch, tmp_path, caplog): + monkeypatch.setattr(client_mod, "_resolve_claude_code_executable", lambda: "/opt/claude") + monkeypatch.setattr(client_mod, "_CLAUDE_LAUNCHER", tmp_path / "absent.mjs") + env: dict[str, str] = {} + with caplog.at_level(logging.WARNING, logger=client_mod.logger.name): + client_mod._point_adapter_at_claude_cli(env) + assert env == {"CLAUDE_CODE_EXECUTABLE": "/opt/claude"} + assert "launcher missing" in caplog.text + + def test_the_launcher_ships_with_the_package(self): + assert client_mod._CLAUDE_LAUNCHER.is_file() + rel = "acp/claude_launcher.mjs" + assert rel in (_REPO_ROOT / "setup.cfg").read_text(encoding="utf-8") + assert f"src/kiro_crew/{rel}" in (_REPO_ROOT / "MANIFEST.in").read_text(encoding="utf-8") + + def test_the_launcher_is_directly_executable(self): + # The SDK runs a script-valued CLAUDE_CODE_EXECUTABLE under node, but the + # adapter also spawns that path directly for ``claude auth status``: a + # launcher without a shebang and the executable bit answers that spawn + # with EACCES, and the adapter logs an auth failure for every session. + first_line = client_mod._CLAUDE_LAUNCHER.read_text(encoding="utf-8").splitlines()[0] + assert first_line == "#!/usr/bin/env node" + if os.name == "posix": + assert os.access(client_mod._CLAUDE_LAUNCHER, os.X_OK) + + +class TestSpawnEnvironment: + @pytest.fixture(autouse=True) + def _posix(self, monkeypatch): + monkeypatch.setattr(client_mod.platform_compat, "IS_WINDOWS", False) + + async def _spawn_env(self, tmp_path, monkeypatch, **client_kw) -> dict: + monkeypatch.delenv("CLAUDE_CODE_EXECUTABLE", raising=False) + monkeypatch.delenv(_TARGET_ENV, raising=False) + client = AcpClient(work_dir=tmp_path, **client_kw) + with ( + patch( + "kiro_crew.acp.client._resolve_claude_acp_bin", + return_value=(["/usr/bin/node", "/x/acp.js"], ""), + ), + patch("kiro_crew.acp.client._resolve_kiro_bin", return_value="/usr/bin/kiro-cli"), + patch( + "kiro_crew.acp.client._resolve_claude_code_executable", + return_value="/opt/claude/bin/claude", + ), + patch("kiro_crew.acp.client.wrap_argv", return_value=(["/usr/bin/true"], None)), + patch("asyncio.create_subprocess_exec", new_callable=AsyncMock) as mock_exec, + patch("kiro_crew.session._track_pid"), + patch("kiro_crew.session._track_session_pid"), + ): + mock_proc = MagicMock() + mock_proc.pid = 12345 + mock_proc.returncode = None + mock_exec.return_value = mock_proc + await client._spawn() + env = mock_exec.call_args.kwargs["env"] + task = client._stderr_task + if task is not None and not task.done(): + task.cancel() + return env + + @pytest.mark.asyncio + async def test_claude_child_is_pointed_at_the_launcher(self, tmp_path, monkeypatch): + env = await self._spawn_env(tmp_path, monkeypatch, acp_backend=ACP_BACKEND_CLAUDE) + assert env["CLAUDE_CODE_EXECUTABLE"] == str(client_mod._CLAUDE_LAUNCHER) + assert env[_TARGET_ENV] == "/opt/claude/bin/claude" + + @pytest.mark.asyncio + async def test_kiro_child_gets_neither_variable(self, tmp_path, monkeypatch): + env = await self._spawn_env(tmp_path, monkeypatch) + assert "CLAUDE_CODE_EXECUTABLE" not in env + assert _TARGET_ENV not in env + + +@_NEEDS_NODE +class TestLauncher: + def _fake_cli(self, tmp_path: Path) -> Path: + cli = tmp_path / "fake-claude.mjs" + cli.write_text(_FAKE_CLI_JS, encoding="utf-8") + return cli + + def _run(self, target, *args: str, **extra_env: str) -> subprocess.CompletedProcess: + env = {k: v for k, v in os.environ.items() if k not in ("CLAUDE_CODE_EXECUTABLE",)} + env.pop(_TARGET_ENV, None) + env["CLAUDE_CODE_EXECUTABLE"] = str(client_mod._CLAUDE_LAUNCHER) + if target is not None: + env[_TARGET_ENV] = str(target) + env.update(extra_env) + return subprocess.run( + [_NODE, str(client_mod._CLAUDE_LAUNCHER), *args], + capture_output=True, + text=True, + encoding="utf-8", + env=env, + timeout=60, + check=False, + ) + + def test_drops_only_the_bypass_flag_and_keeps_order(self, tmp_path): + cli = self._fake_cli(tmp_path) + args = ["--output-format", "stream-json", _BYPASS_FLAG, "--verbose", "--model", "m"] + result = self._run(cli, *args) + assert result.returncode == 0, result.stderr + seen = json.loads(result.stdout) + assert seen["argv"] == ["--output-format", "stream-json", "--verbose", "--model", "m"] + + def test_child_environment_names_the_real_cli(self, tmp_path): + cli = self._fake_cli(tmp_path) + seen = json.loads(self._run(cli, _BYPASS_FLAG).stdout) + assert seen["executable"] == str(cli) + assert seen["target"] is None + + def test_an_explicit_permission_mode_passes_through(self, tmp_path): + # The launcher withholds the capability flag only; it does not rewrite a + # mode, so a bypassPermissions defaultMode from the user's own settings + # still reaches the CLI (the disclosed boundary in claude-code-provider.md). + cli = self._fake_cli(tmp_path) + args = ["--permission-mode", "bypassPermissions", _BYPASS_FLAG] + seen = json.loads(self._run(cli, *args).stdout) + assert seen["argv"] == ["--permission-mode", "bypassPermissions"] + + def test_exit_status_propagates(self, tmp_path): + result = self._run(self._fake_cli(tmp_path), FAKE_EXIT="3") + assert result.returncode == 3 + + def test_missing_target_variable_fails_loudly(self): + result = self._run(None) + assert result.returncode == 127 + assert _TARGET_ENV in result.stderr + + def test_unstartable_target_fails_loudly(self, tmp_path): + result = self._run(tmp_path / "no-such-claude") + assert result.returncode == 127 + assert "cannot start" in result.stderr + + @_POSIX_ONLY + def test_native_target_is_executed_directly(self, tmp_path): + cli = tmp_path / "claude" + cli.write_text('#!/bin/sh\nprintf "%s\\n" "$@"\n', encoding="utf-8") + cli.chmod(0o755) + result = self._run(cli, "-p", _BYPASS_FLAG, "hello world") + assert result.returncode == 0, result.stderr + assert result.stdout.splitlines() == ["-p", "hello world"]