Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
Merge origin/main (v10.6.3) into worktree-claudish-mcp-update
Jack Rudenko826b81900565
diff --cc CLAUDE.mdindex b29735a5,30b42267..23d92215--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -24,15 -24,15 +24,15 @@@ lives in `ROADMAP.md`- `pane-session.md` — MCP and CLI `team` slots and `create_session` as interactive Claude Code inheadless magmux panes: transcript turn oracle, settle on `turn_duration` (32 s quiet path gatedon Stop hooks), prompt delivery by file with read coverage, boot dialogs never accepted, the pane- watcher and identity-checked reap, socket traps, the frozen mod contract v1, the session registry- read as telemetry (and why no in-child mod or argv prompt). Read before editing `pane/`, team spawn- or MCP session spawn+ watcher and identity-checked reap, socket traps, one level of nesting (`CLAUDISH_PANE_CHILD` kept,+ the nested refusal), the frozen mod contract v1, the session registry read as telemetry (and why no- in-child mod or argv prompt). Read before editing `pane/`, team spawn or channel spawn++ in-child mod or argv prompt). Read before editing `pane/`, team spawn or MCP session spawn- `custom-endpoints.md`, `predefined-endpoints.md` — user config; the 25-vendor bundled catalog- `onepassword.md` — secret resolution, the four denial causes, the handshake lock, route pinning- `keychain.md` — the macOS Keychain backend: enumerate-for-presence vs read-for-value, the `security` traps, the Providers-tab write/delete- - `mcp-sessions.md` — the 14-tool MCP surface and its four groups, sessions on panes (`send_input`- queueing, `capture_session`, the session records the magus monitor reads), `run_prompt`'s Claude- Code print path, progress keepalive-- `mcp-channel.md` — the 14-tool MCP surface and the 4-tool nested mode, channel sessions on panes (`send_input` queueing,- `capture_session`, the session records the magus monitor reads), channel wire format- (`awaiting_permission`, no `finishing`), progress keepalive++- `mcp-sessions.md` — the 14-tool MCP surface and its four groups, the 4-tool nested mode, sessions++ on panes (`send_input` queueing, `capture_session`, the session records the magus monitor reads),++ `run_prompt`'s Claude Code print path, progress keepalive- `team-capture.md` — why `team`'s exit 0 proves nothing, and why a slot's answer is everyassistant message of its turn, from the transcript, starting after the task file was read- `team-lifecycle.md` — why no slot is ever killed on a timer, why `run` returns once everydiff --cc ai-docs/architecture/README.mdindex b5a6f656,aefa6253..06e8d1db--- a/ai-docs/architecture/README.md+++ b/ai-docs/architecture/README.md@@@ -31,12 -31,12 +31,12 @@@ three earlier write-ups this material c| [`network-recovery.md`](network-recovery.md) | The two-tier connection hold: why the deadline is DERIVED from `API_TIMEOUT_MS` (measured 359.607 s, a default and not a watchdog), why the tier-2 status is 503 and never 429, why the banner is magmux's `overlay` and never a pane of ours (closing a pane wedged Claude Code), why its lease is renewed on its own tick and not by ladder events, the five sites where a network failure wore an auth status code, and why a pane child gets no watchdog | touch the retry ladder, `recovery/`, the tier-2 status, the recovery banner, or any `x-claudish-recovery` reader || [`behavior-layer.md`](behavior-layer.md) | Layer 4, the harness-convention SUPERVISOR: the rule engine, the four hooks, the 115-call plan-mode measurement it was built on, and opt-in telemetry | write a `behavior/` rule, or change harness-conformance handling || [`advisor.md`](advisor.md) | `--advisor` for any main model: why it is independent of `--monitor` yet keeps four of its launch bits, the decorator around the ROUTED handler, id capture by tool name (the `toolu_` prefix that made it a no-op on every foreign provider), the tee and retained session-keyed state, the ten stub paths and advice origin, Claude Code's advisor gates, metered panel billing, and the inherited-placeholder 401 | touch `--advisor`, `advisor-decorator.ts`, `native-handler-advisor.ts`, `advisor-startup.ts`, monitor-gated launch code, or native auth in `claude-runner.ts` |-| [`headless-vs-interactive.md`](headless-vs-interactive.md) | Why `-p` is NOT interactive-without-a-TTY: an UNKNOWN `--agent` is SILENTLY unvalidated under `--input-format stream-json` (measured, exit 0, no stream frame, `result: success`), upstream closed it as not planned, why magmux is in the dependency tree, why the MCP server no longer starts any child with `-p`, and why a driver cannot rely on magmux's pane states | drive Claude Code headlessly, add a child-spawn flag, or assume a headless run behaves like an interactive one |-| [`pane-session.md`](pane-session.md) | MCP `team` slots, CLI `team` and `create_session` as interactive Claude Code in headless magmux panes: the transcript as turn oracle, boot from screen content and closed dialog lists ("never accept"), the four settle paths with the measured `secondaryQuietMs` (32 s), prompt delivery by file with read coverage and exact `require_pattern` semantics, the environment snapshot and shell shim, one level of nesting (`inMcpSession`/`isPaneChild`, the nested refusal), the pane watcher and the identity-checked reap, the socket traps, `seq` ownership, the D9/D10 bounds, the phase table, and the frozen mod contract v1 | edit `pane/`, team or channel spawn, the settle rule, prompt delivery, the reap or sweep, or any field the mod contract carries |+| [`headless-vs-interactive.md`](headless-vs-interactive.md) | Why `-p` is NOT interactive-without-a-TTY: an UNKNOWN `--agent` is SILENTLY unvalidated under `--input-format stream-json` (measured, exit 0, no stream frame, `result: success`), upstream closed it as not planned, why magmux is in the dependency tree, the one `-p` the MCP server starts (`run_prompt` on a Claude model) and why it is safe, and why a driver cannot rely on magmux's pane states | drive Claude Code headlessly, add a child-spawn flag, or assume a headless run behaves like an interactive one |- | [`pane-session.md`](pane-session.md) | MCP `team` slots, CLI `team` and `create_session` as interactive Claude Code in headless magmux panes: the transcript as turn oracle, boot from screen content and closed dialog lists ("never accept"), the four settle paths with the measured `secondaryQuietMs` (32 s), prompt delivery by file with read coverage and exact `require_pattern` semantics, the environment snapshot and shell shim, the pane watcher and the identity-checked reap, the socket traps, `seq` ownership, the D9/D10 bounds, the phase table, and the frozen mod contract v1 | edit `pane/`, team or MCP session spawn, the settle rule, prompt delivery, the reap or sweep, or any field the mod contract carries |++| [`pane-session.md`](pane-session.md) | MCP `team` slots, CLI `team` and `create_session` as interactive Claude Code in headless magmux panes: the transcript as turn oracle, boot from screen content and closed dialog lists ("never accept"), the four settle paths with the measured `secondaryQuietMs` (32 s), prompt delivery by file with read coverage and exact `require_pattern` semantics, the environment snapshot and shell shim, one level of nesting (`inMcpSession`/`isPaneChild`, the nested refusal), the pane watcher and the identity-checked reap, the socket traps, `seq` ownership, the D9/D10 bounds, the phase table, and the frozen mod contract v1 | edit `pane/`, team or MCP session spawn, the settle rule, prompt delivery, the reap or sweep, or any field the mod contract carries || [`picker.md`](picker.md) | The OpenTUI model picker: why it is an inline dialog and not a dashboard (the density gate that manufactured the rejected build), the provider list as the default screen with nothing prefetched (3915 → 1436 ms), the discovery outcome that stopped `[]` meaning five things, the local served-by index (22 network queries measured at 10 018 ms), the no-terminal gate's complement law, and the capture and compile traps | change `picker/`, `selectModel`, discovery outcomes or fetchers, `should-open-picker.ts`, or a TUI test that asserts on a frame || [`context-window.md`](context-window.md) | Why setting one env lever accomplishes nothing, why the status line reports the ENFORCED window, and local-model token accounting | change context-window resolution, the status line, or token accounting || [`theming.md`](theming.md) | One detected theme for every surface, and the module-load palette-snapshot bug class it keeps producing (found six times) | add a colored CLI line or TUI surface |- | [`mcp-sessions.md`](mcp-sessions.md) | The 14-tool MCP surface (groups low-level / agentic / session / debug, `CLAUDISH_MCP_TOOLS`), sessions on panes: the flag check, the owner's verdict, `send_input` queueing, the session records (`spawn.json`, `waits.jsonl`, `meta.json`, `events.jsonl`, `screen.txt`) and what the monitor reads, `get_diagnostics`; `run_prompt`'s two paths (the Claude Code print call on the user's login, the proxy with no `max_tokens`); why the channel push was removed; and the `notifications/progress` keepalive | add or rename an MCP tool or group, change `run_prompt`, or change sessions or their records |-| [`mcp-channel.md`](mcp-channel.md) | The 14-tool MCP surface (7 channel tools, `capture_session` among them) and the 4-tool nested-mode surface, channel sessions on panes: the flag check, the owner's verdict, `send_input` queueing, the session records (`spawn.json`, `waits.jsonl`, `meta.json`, `events.jsonl`, `screen.txt`) and what the monitor reads, `get_diagnostics`; the channel wire format (`awaiting_permission` in, `finishing` out), the client-side conditions gating channel rendering, and the `notifications/progress` keepalive | add or rename an MCP tool, or change channel sessions, their records or their notifications |++| [`mcp-sessions.md`](mcp-sessions.md) | The 14-tool MCP surface (groups low-level / agentic / session / debug, `CLAUDISH_MCP_TOOLS`) and the 4-tool nested-mode surface, sessions on panes: the flag check, the owner's verdict, `send_input` queueing, the session records (`spawn.json`, `waits.jsonl`, `meta.json`, `events.jsonl`, `screen.txt`) and what the monitor reads, `get_diagnostics`; `run_prompt`'s two paths (the Claude Code print call on the user's login, the proxy with no `max_tokens`); why the channel push was removed; and the `notifications/progress` keepalive | add or rename an MCP tool or group, change `run_prompt` or nested mode, or change sessions or their records || [`team-capture.md`](team-capture.md) | Why exit 0 proves nothing under `claude -p` (the measurement behind `require_pattern`), and why a slot's answer is every assistant message of its turn, read from the transcript, starting after the task file was read | change how `team` classifies output or builds `response-<slot>.md` || [`team-lifecycle.md`](team-lifecycle.md) | Why nothing kills a slot on a timer, the measurement that removed the deadline, why `run` returns once every prompt is accepted (≤ 120 s), the run registry by `run_id`, the `blocked` rule, the team record ended exactly once, and one driver with two owners | add a deadline, change when `team` returns, or touch per-slot liveness, cancel or the run record || [`debugging.md`](debugging.md) | Debug logging, `CLAUDISH_UPSTREAM_ERROR_LOG`, raw SSE capture, and the failed-translation workflow | diagnose a model producing wrong, empty, or garbled output |diff --cc ai-docs/architecture/mcp-sessions.mdindex 116ce7e2,89fa555f..e2fc07ed--- a/ai-docs/architecture/mcp-sessions.md+++ b/ai-docs/architecture/mcp-sessions.md@@@ -336,116 -335,36 +336,147 @@@ The tool list is pinned by an EXACT froadding or removing a tool without updating that test fails CI. That is deliberate:it is a wire contract, and an accidental change to the tool surface should be loud.-Tool gating via `CLAUDISH_MCP_TOOLS` env var: `all` (default), `low-level`, `agentic`, `channel`.+Tool gating via the `CLAUDISH_MCP_TOOLS` env var (lower-cased, `resolveToolGroups` in+`mcp-server.ts`):++| Value | Tools |+|---|---|+| unset, `all` | all 14 |+| `low-level` | `run_prompt`, `list_models`, `search_models` |+| `agentic` | `preflight`, `team`, `report_error` |+| `session` | the 7 session tools |+| `debug` | `compare_models` |+| `channel`, or any other value | all 14, plus one stderr line naming the value and the valid ones (`unknownToolModeWarning`); for `channel` it says the group was renamed to `session` |++Unknown values keep selecting everything, because a server that lists fewer tools than its host+expects fails later and quietly. The stderr line is there so a typo is not read as `all` with+no trace.++`session` was `channel` until 10.7.0. The rename removed the old name with no alias, per the+thesaurus rule, so `channel` now falls into the unknown-value rule and selects everything. The+stderr startup line shows `tools: channel, 14 tools` after the unknown-value warning, but an MCP+host does not show stderr.+`compare_models` moved to `debug` at the same time: it sends one prompt to several models in+sequence and shows raw answers, which is a route check, not work. Real multi-model work is `team`.++## `run_prompt`: two paths++`run_prompt` (and each entry of `compare_models`) is one quick prompt to one model: one request,+one answer, no tools, no session. `runPrompt` in `mcp-server.ts` picks the path with+`nativeRouteFor()` (`providers/native-route.ts`) FIRST — the proxy's own gate, so the tool cannot+disagree with the proxy (the CLAUDE.md invariant about bare Claude names):++| Model | Path |+|---|---|+| a bare Claude name: `claude-*`, `opus`, `sonnet`, `haiku`, `opusplan`, `internal`, `default` | `runPromptViaClaudeCode` (`mcp/run-prompt-claude-code.ts`): one Claude Code print-mode call through claudish |+| everything else, including `anthropic@claude-*` (metered), `dv@claude-*` and `anthropic/claude-*` | `runPromptViaProxy`: one Anthropic Messages request to the in-process proxy, which routes it like any request |++**Why a Claude name cannot use the proxy.** Until 10.7.0 every model took the proxy path, and+`run_prompt {model: "claude-opus-5-5"}` answered `Proxy error: 401 … x-api-key header is+required`: the proxy's native route forwards the CALLER's credential, and an MCP tool call has+none. claudish must never read the Claude Code OAuth token or its Keychain item, so the only way+onto the user's subscription is the unmodified `claude` binary signing in on its own login.++**The Claude Code print call.** `resolveClaudishLaunch` (`CLAUDISH_BIN`, else `claudish` on PATH —+the same claudish the panes start) runs:++```+<claudish> -p --model <model> --output-format json --tools "" --strict-mcp-config+ --setting-sources "" --disable-slash-commands --no-session-persistence+ (--system-prompt-file <file> | --system-prompt "")+```++The original model string is passed; claudish's CLI owns alias normalisation. Measured on Claude+Code 2.1.301 (session `dev-feature-mcp-run-prompt-claude-20261016-a7c3`):++| Choice | Why |+|---|---|+| prompt on stdin, system prompt in a file | claudish's passthrough parser takes a flag value only when it does not start with `-` (`cli.ts` `passthroughFlagTakesValue`), so a prompt or value starting with `-` would be misparsed. stdin reaches `claude -p` unchanged (`- Say OK` answered correctly), and keeps the prompt out of `ps` |+| `--system-prompt ""` when none is given | omitting it loads Claude Code's default system prompt (3 232 input tokens against 586); the proxy path sends no system prompt either |+| a new empty working directory | `--setting-sources ""` does NOT stop CLAUDE.md and memory loading: 8 718 input tokens in this repo, 580–597 in an empty directory. The cwd is `<tmp>/claudish-run-prompt-*/cwd`; the system prompt file sits beside it, so the cwd is empty even then. Both are removed after the call |+| `--setting-sources ""` | still authenticates: `apiKeySource: "none"`, the Keychain login. The login is not a settings source |+| `--strict-mcp-config`, `--tools ""` | without them the child loads the user's plugins and starts another `claudish --mcp`; with them the init frame shows `mcp_servers: []`, `tools: []` |+| no `--bare` | `--bare` reads only `ANTHROPIC_API_KEY`/`apiKeyHelper`, never the login, and 401s again |++**The environment.** `claudeCodePrintEnv` is the server's environment minus+`isStrippedFromChildEnv` (`pane/pane-launch.ts`, the list the pane spawner uses: `CLAUDECODE`,+`CLAUDE_CODE_CHILD_SESSION`, `MAGMUX_*`, terminal identity, `CLAUDE_CODE_SESSION_ID` and the launcher- pids), minus `PANE_MARKER_VARS` (a marker would make the child a pane child, which refuses `-p`- and exits 64), minus `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_BASE_URL`.++pids), minus the pane markers (`PANE_LAUNCH_VARS` and `CLAUDISH_PANE_CHILD`: in a nested server++the flag would make `assertNotNested` refuse `-p` with exit 64; the child is a leaf, so dropping++it opens no second level), minus `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_BASE_URL`.+`ANTHROPIC_API_KEY` goes unconditionally, not only claudish's placeholder: a bare Claude name in+`run_prompt` runs on the Claude Code login, and a user who wants the metered Anthropic API names+it as `anthropic@claude-*`.++**Process handling.** All three stdio streams are pipes: this process's stdin and stdout are the+JSON-RPC transport, and an inherited one would eat the host's requests or corrupt the stream. The+child is `detached` and stopped by its process group (SIGTERM, SIGKILL 5 s later), because+`claudish` on PATH may be the `bin/claudish.cjs` launcher, which orphans the real process on a+plain SIGTERM. There is no wall-clock deadline, as on the proxy path: the child stops on the call's+`AbortSignal` (`ToolCallContext.signal`, from the SDK's `extra.signal`: `notifications/cancelled`+or the host's own timeout) or at server shutdown (`stopAllClaudeCodePrintChildren` in+`installMcpShutdown`). Measured end to end: 1.3 s for a 404, 2.4 s for a Haiku answer.++**The answer.** Claude Code 2.1.301 `--output-format json` prints a JSON ARRAY of frames+(`system/init`, `assistant`, `rate_limit_event`, `result`); older releases printed one result+object. `parseClaudeCodePrintOutput` accepts both and reads the last `type: "result"` frame and the+`system/init` frame. `result` is the answer; `usage.input_tokens + cache_creation_input_tokens ++cache_read_input_tokens` is the input (a cached prefix is context the model saw); the init frame's+`apiKeySource` becomes the `Auth:` line (`"none"` → `Auth: Claude Code login (subscription)`).+`total_cost_usd` is not shown: on a subscription it is a list-price equivalent+(`costBasis: "list"`), not money spent. Exit 0 proves nothing; the verdict is the result frame:++| Condition | Error text |+|---|---|+| `is_error: true` (API error, "Not logged in") | `Claude Code: <result>` plus ` (HTTP <api_error_status>)` when it is a number |+| the executable cannot start | `cannot start claudish (<command>): <code>` |+| no result frame | `claudish -p exited <code>: <stderr tail, sanitized>` (the missing-`claude` case lands here) |+| empty `result` | `Model returned empty response` |+| the call's signal fired | `cancelled` |++**No `max_tokens` on either path.** `run_prompt` and `compare_models` have no output-limit+parameter, and `runPromptViaProxy`'s body has no `max_tokens`. Step 5w strips every limit field the+adapters write and adds the wire's `tokenParam` only when the request carries a limit, so the+upstream applies its own default and no number is pinned ([`wire.md`](wire.md)). Measured 200 with+no limit on chat-completions (`mm@MiniMax-M3`, `kimi-k3`), responses (`gpt-6.1-sol`) and+anthropic-messages (`mmc@MiniMax-M3`). The one known host that REQUIRES `max_tokens` is+`api.anthropic.com`, reached now only by the explicit metered `anthropic@claude-*`; if it 400s,+the fix belongs in step 5w (write the connection's catalog `maxOutputTokens` for+`anthropic-messages`), never in the MCP server.++Why `-p` is acceptable for this one call, when the session tools refuse it:+[`headless-vs-interactive.md`](headless-vs-interactive.md) "The one `-p` the MCP server starts".+ ### Nested mode++ A claudish MCP server whose environment has `CLAUDISH_PANE_CHILD=1` (`inMcpSession()`) runs inside a+ session that a claudish owner started: Claude Code in a `create_session` or `team` pane started it+ as a plugin server. One level of nesting is the limit (why, and the CLI side of the rule:+ [`pane-session.md`](pane-session.md) § One level of nesting). Such a server:++ - registers only `NESTED_MCP_TOOL_NAMES` (`mcp/nested-mode.ts`): `run_prompt`, `compare_models`,+ `list_models`, `search_models`. The rule is that a tool is kept only if it is a one-shot call that- starts no session, no pane and no claudish child. `team` and every channel tool start or act on- sessions. `preflight` and `report_error` are out as well, so the nested surface is exactly the- low-level group;++ starts no session, no pane and no claudish child that could start one. `team` and every session++ tool start or act on sessions. `preflight` and `report_error` are out as well, so the nested++ surface is the low-level group plus `compare_models` from the debug group. `run_prompt` on a++ Claude model does start a `claudish -p`, a leaf with no tools and no MCP servers (see++ § `run_prompt`: two paths, The environment);+ - INTERSECTS that list with the groups `CLAUDISH_MCP_TOOLS` enables and never widens them:- `all`, unset or `low-level` give 4 tools, `agentic` or `channel` give 0. Any value still yields no- session tool, which matters because madbench forces `all` and an env snapshot can carry the- variable;++ `all` or unset give 4 tools, `low-level` 3, `debug` 1 (`compare_models`), `agentic` or `session`++ 0. Any value still yields no session tool, which matters because madbench forces `all` and an env++ snapshot can carry the variable;+ - filters by NAME and fails closed. A tool added later is absent in nested mode until someone lists+ it, whereas a group filter would admit any future tool of its group;-- declares no `claude/channel` capability and sends no channel frames (`channelEnabled` is false);-- answers `initialize` with `NESTED_INSTRUCTIONS` in place of the channel-mode text, so the model++- declares only the `tools` capability, as every claudish MCP server now does;++- answers `initialize` with `NESTED_INSTRUCTIONS` in place of the normal instructions, so the model+ reads why the session tools are absent;+ - drops the "use the `report_error` tool" hint from `run_prompt`'s and `compare_models`' error+ texts, since that tool is not registered;+ - logs `[claudish] MCP server started (tools: nested, 4 tools)`.++ A call to a removed tool takes the ordinary unknown-tool path:+ `isError: true`, `Error: Unknown tool "create_session"`.+## Tool Registration PatternUses a `ToolDefinition[]` registry with raw JSON Schema (not Zod). Two `setRequestHandler` calls replace McpServer's ergonomic API:diff --cc ai-docs/architecture/pane-session.mdindex 0041dafb,552e57e4..35e9ebc2--- a/ai-docs/architecture/pane-session.md+++ b/ai-docs/architecture/pane-session.md@@@ -141,15 -134,8 +141,16 @@@ What blocks boot is decided by **"no inaccepting one on the user's behalf (trusting a folder, enabling a project's MCP servers) is adecision claudish has no standing to make. The bypass-permissions dialog is the one that `-y`itself would cause, so it is suppressed instead: a pane child's `--settings` overlay carries- `skipDangerousModePermissionPrompt: true`, gated on `CLAUDISH_PANE_CHILD=1` so no other launch- gets it (D5). The same overlay, on the same marker, carries `editorMode: "normal"`: a user- `editorMode: "vim"` leaves the box in `-- INSERT --`, the submit Enter is swallowed, the typed- prompt sits unsent, and every slot fails `prompt_not_accepted` with anomaly `resent_enter`- (measured 2026-10-16, Claude Code 2.1.301, magmux 0.15.1). Claude Code merges settings per key, so- the user's other settings still apply. Claude Code keeps only the LAST `--settings` flag, so a- caller's `claude_flags --settings` is merged into claudish's temp file (`mergeUserSettingsIfPresent`)- and one `--settings <path>` is emitted; in a pane `editorMode` is forced over the caller's. magmux 0.16.0 forces the same value for its panes; once it- is the minimum, this key can go. The API-key dialog was not recaptured on 2.1.290 (it needs a foreign route with+ `skipDangerousModePermissionPrompt: true`, gated on `isPaneChild()` (`CLAUDISH_PANE_CHILD=1` AND-`CLAUDISH_PANE_CWD`) so no other launch gets it (D5). The API-key dialog was not recaptured on 2.1.290 (it needs a foreign route with++`CLAUDISH_PANE_CWD`) so no other launch gets it (D5). The same overlay, on the same gate, carries++`editorMode: "normal"`: a user `editorMode: "vim"` leaves the box in `-- INSERT --`, the submit++Enter is swallowed, the typed prompt sits unsent, and every slot fails `prompt_not_accepted` with++anomaly `resent_enter` (measured 2026-10-16, Claude Code 2.1.301, magmux 0.15.1). Claude Code++merges settings per key, so the user's other settings still apply. Claude Code keeps only the LAST++`--settings` flag, so a caller's `claude_flags --settings` is merged into claudish's temp file++(`mergeUserSettingsIfPresent`) and one `--settings <path>` is emitted; in a pane `editorMode` is++forced over the caller's. magmux 0.16.0 forces the same value for its panes; once it is the++minimum, this key can go. The API-key dialog was not recaptured on 2.1.290 (it needs a foreign route with`ANTHROPIC_API_KEY` set); its marker is the verbatim 2.1.287 text.**An unknown `--agent` is refused by the child itself**, which is why the old `claude -p` agent@@@ -390,11 -366,63 +391,66 @@@ run the user's profileargv, and any positional token or `--`, by claudish's own value-consumption rule). After`parseArgs` the child asserts it is interactive, not a team run, with no positional prompt;otherwise it prints `claudish: pane child refused: <reason>` and exits 64 (FAILED `child_exited`).- - The markers `CLAUDISH_PANE_CHILD`, `CLAUDISH_PANE_ENV`, `CLAUDISH_PANE_CWD` are deleted from- Claude Code's own environment, so a claudish started from a slot's Bash tool is an ordinary launch.+ - `CLAUDISH_PANE_ENV` and `CLAUDISH_PANE_CWD` (`PANE_LAUNCH_VARS`) are deleted from Claude Code's+ own environment. `CLAUDISH_PANE_CHILD` is KEPT there; the next section says why.++ **One level of nesting.** A `create_session` child (gpt-6.1-sol) once called the claudish MCP+ `create_session` itself; that session (#969aa2) failed `prompt_not_accepted`. It was a claudish MCP+ session inside a claudish MCP session. claude-runner then deleted all three markers from Claude+ Code's environment, so the claudish MCP server that the child's plugins started saw no marker and+ registered every tool. Nothing checked depth anywhere.++ `CLAUDISH_PANE_CHILD=1` now means "this process runs inside a session a claudish owner started", and+ claude-runner keeps it, so it reaches everything the session starts: the Bash tool, hooks, plugin MCP+ servers. `scrubChildEnv` deletes only `PANE_LAUNCH_VARS`. Putting the flag back in that list+ silently re-enables the recursion. Two predicates in `pane/child-env.ts` read it:++ - `inMcpSession()`: the flag alone (exactly `"1"`). True for the pane child, its Claude Code and+ everything below them.+ - `isPaneChild()`: the flag AND a non-empty `CLAUDISH_PANE_CWD`. True only for the claudish the pane+ launcher started, because Claude Code's environment no longer has `CLAUDISH_PANE_CWD`. The pane+ child's bootstrap, its REPL assertion and the `skipDangerousModePermissionPrompt` overlay gate on+ this one.++ A process with `inMcpSession() && !isPaneChild()` is one level deep already. Two things act on it:++ - **A model-running CLI launch is refused.** `assertNotNested()` prints+ `claudish: nested session refused: already inside a session started by the claudish MCP server; one level of nesting is the limit`+ and exits 64. It has two call sites. The first is `index.ts`, right before+ `assertPaneChildInteractive`, which covers `-p`, `--stdin`, interactive, `--team` and resume. The+ second is `team-cli.ts`, for every `claudish team` subcommand except `status` (and `--help`):+ `team` is dispatched before `runCli`, so the first site never sees it. A new model-running+ subcommand dispatched before `runCli` needs its own call. Everything that exits inside `parseArgs`+ (`--version`, `--help`, `--models`, `--probe`) and every non-model subcommand (`config`, `update`,+ `login`, `stats`, …) still runs. The pane-child refusal (`pane child refused: …`) is a different+ line and is not used for nesting.+ - **`claudish --mcp` is restricted, not refused.** It registers only `run_prompt`, `compare_models`,+ `list_models` and `search_models`, declares no channel capability and uses the nested- instructions; see [`mcp-channel.md`](mcp-channel.md) § Nested mode. `run_prompt` and- `compare_models` start no child: they call a proxy in the MCP server's own process- (`runPromptViaProxy`), so no `claudish -p` exists to be refused.++ instructions; see [`mcp-sessions.md`](mcp-sessions.md) § Nested mode. `compare_models`, and++ `run_prompt` on a foreign model, start no child: they call a proxy in the MCP server's own++ process (`runPromptViaProxy`). `run_prompt` on a Claude model starts one `claudish -p` with++ `CLAUDISH_PANE_CHILD` dropped from its environment, so the nested refusal does not apply to it.++ That child is a leaf: no tools, no MCP servers, no setting sources, no slash commands++ (`mcp/run-prompt-claude-code.ts`), so it cannot start a session and the depth stays one.++ This stops ACCIDENTAL recursion, a model reaching for the tools it was given. It is not a+ containment boundary: `env -u CLAUDISH_PANE_CHILD claudish -p …` passes it, and so does anything+ that starts claudish with a fresh environment. Two such routes are known and accepted. madbench+ starts its MCP server through `env -i` with an explicit allowlist (`madbench/session.ts`), so the+ flag never reaches it; forwarding it would put every bench of `create_session` run from inside a+ session into nested mode. CLI `--grid` children (`team-grid.ts`) are print-mode children in a+ visible magmux and carry no markers, so a grid child's Claude Code can still start a claudish MCP+ session; that is one level below a human-visible grid, not below an MCP session.++ The rule relies on Claude Code passing its full environment to plugin MCP servers (verified: a+ running `claudish --mcp` showed `TMUX`, `CLAUDECODE` and `CLAUDE_CODE_SESSION_ID`). A Claude Code+ that passed only the MCP SDK's default allowlist would turn nested mode off silently; the live check+ is a `create_session` child listing its own `mcp__plugin_claudish_claudish__*` tools.**No recovery watchdog in a pane child (D22).** `magmuxPaneCapability()` answers- `{kind:"none", reason:"pane-child"}` before its ambient branch, so a pane child exports no+ `{kind:"none", reason:"pane-child"}` for any process inside an MCP-started session+ (`inMcpSession()`), before its ambient branch. Only the pane child reaches it in production, since a+ nested launch is refused first. A pane child exports no`CLAUDE_CODE_RETRY_WATCHDOG`, installs no recovery UI and draws no overlay on the screen theclassifier reads. `network-recovery.md` §7 accepts ~300 client attempts only where a person can seethe banner; a headless pane has no viewer. Tier 1's hold still runs; an exhausted episode answers andiff --cc docs/usage/mcp-server.mdindex b7ef6589,044bef61..aa5c9cba--- a/docs/usage/mcp-server.md+++ b/docs/usage/mcp-server.md@@@ -249,49 -228,27 +249,51 @@@ The session tools are in the `session`}```-`CLAUDISH_MCP_TOOLS` accepts: `all` (default), `channel`, `agentic`, or `low-level`. Channel tools are included in `all` by default.+`CLAUDISH_MCP_TOOLS` selects the tools the server lists:++| `CLAUDISH_MCP_TOOLS` | Tools |+|---|---|+| unset, `all` | all 14 |+| `low-level` | `run_prompt`, `list_models`, `search_models` |+| `agentic` | `preflight`, `team`, `report_error` |+| `session` | `create_session`, `send_input`, `get_output`, `cancel_session`, `list_sessions`, `get_diagnostics`, `capture_session` |+| `debug` | `compare_models` |+| any other value | all 14, with a warning on stderr |+ Inside a session that claudish itself started (a `create_session` or `team` pane), the server runs in nested mode. Whatever `CLAUDISH_MCP_TOOLS` says, it offers at most the four one-shot tools (`run_prompt`, `compare_models`, `list_models`, `search_models`) and no session tools. A model-running `claudish` launched from that session's shell (`-p`, interactive, `team run`) exits 64 with `nested session refused`. One level of nesting is the limit.+-### Channel events+Any other value still selects all 14 tools, and the server writes one line to stderr naming the+value and the valid ones:-When a session runs, Claude Code receives `<channel source="claudish">` notifications with these event types:+```+[claudish] CLAUDISH_MCP_TOOLS="agentc" is not a tool mode; selecting all tools. Valid values: all, low-level, agentic, session, debug+```++`channel` was the old name of the `session` group. It is no longer a group, so it selects all 14+tools, and the warning says it was renamed to `session`.-| Event | Meaning |-|-------|---------|-| `starting` | Claude Code is booting in the session's pane. Note the `session_id` for future calls. |-| `running` | The session's turn is running: its prompt was accepted. |-| `tool_executing` | Model is using a tool (Read, Write, Bash, etc.); the notification carries `tool` and `tool_count`. |-| `waiting_for_input` | The session waits for `send_input`: an interactive session between turns, or a session stopped on a question (`activity` `AskUserQuestion`). A send during a question declines it and becomes the next prompt. Its SEP-1686 `status` is `input_required`. |-| `awaiting_permission` | A permission or plan-approval dialog is open (only when your `claude_flags` ask for one, e.g. `--permission-mode plan`). A send declines it and becomes the next prompt. Also `input_required`. |-| `completed` | Session finished. Call `get_output` for the full response. |-| `failed` | The session failed: Claude Code could not boot, the prompt was never accepted or its task file never fully read, the child exited, an API error, or the pane was lost. The content says which; call `get_diagnostics` for the rest. |-| `timeout` | The session reached its `timeout_seconds`; the pane was closed. |-| `cancelled` | Session was cancelled via `cancel_session`. |+### Polling workflow-### Workflow example+1. `create_session` returns `{session_id, state: "STARTING"}` at once while Claude Code boots.+2. Poll `list_sessions` (`include_completed: true`) about once every 10 seconds. Each row has+ `state`, `activity`, `idle_seconds` and accounting:+ - `STARTING`: booting, or the first prompt is not yet accepted.+ - `RUNNING`: a turn is in progress (`activity` names the tool in use).+ - `AWAITING_INPUT`: waiting for `send_input` — an interactive session between turns, or a turn+ stopped on a question (`activity` `AskUserQuestion`). A send declines a question and becomes+ the next prompt.+ - `AWAITING_PERMISSION`: a permission or plan-approval dialog is open (only when your+ `claude_flags` ask for one, e.g. `--permission-mode plan`). A send declines it and becomes+ the next prompt.+ - `COMPLETED`, `FAILED`, `TIMEOUT`, `CANCELLED`, `EMPTY`: finished.+3. `send_input` may be called at any time; it is queued until the session is idle.+4. `COMPLETED`: call `get_output` for the answer.+5. `FAILED` or `TIMEOUT` — or `COMPLETED` with an empty or surprising answer — call+ `get_diagnostics`. It returns the child's final screen, the upstream error bodies, the recent+ state records, the resolved model chain and the paths to the full records. It needs no re-run+ and no debug flag.+6. `capture_session` reads a session's current screen; `cancel_session` stops it. Nothing stops a+ session for being idle: a child inside a long build is silent and working.One-shot — a `prompt` is given, so the session ends on its own after its answer:diff --cc packages/cli/src/claude-runner.tsindex 058694db,f094d461..3ef1f58b--- a/packages/cli/src/claude-runner.ts+++ b/packages/cli/src/claude-runner.ts@@@ -1008,19 -1014,11 +1014,20 @@@ export function scrubChildEnv* `forceLoginMethod: "claudeai"` would block that at startup. In native-Anthropic /* --monitor mode we leave it out so the user's real claude.ai subscription keeps working.* - `skipDangerousModePermissionPrompt: true` is added ONLY in an MCP pane child- * (`CLAUDISH_PANE_CHILD=1`). The pane runs `--dangerously-skip-permissions`, and its- * one-time confirmation dialog defaults to "No, exit": nobody is at a headless pane to- * answer it, so every slot would fail at boot. Verified to suppress the dialog at this- * tier. Gated on the marker so no other launch changes.+ * (`isPaneChild()`: `CLAUDISH_PANE_CHILD=1` AND `CLAUDISH_PANE_CWD`). The pane runs+ * `--dangerously-skip-permissions`, and its one-time confirmation dialog defaults to+ * "No, exit": nobody is at a headless pane to answer it, so every slot would fail at+ * boot. Verified to suppress the dialog at this tier. Gated on `isPaneChild()`, not+ * the session flag alone, so no other launch changes.+ * - `editorMode: "normal"` is added ONLY in an MCP pane child, for the same reason- * and on the same marker. A user `editorMode: "vim"` puts the REPL box in vim++ * and on the same gate. A user `editorMode: "vim"` puts the REPL box in vim+ * INSERT mode, where the Enter claudish sends to submit the typed prompt is+ * swallowed: the prompt sits in the box and the slot fails `prompt_not_accepted`.+ * Interactive use outside a pane keeps the user's editorMode. magmux 0.16.0 forces+ * the same value for its panes; once that is the minimum, this key can go.+ *+ * Claude Code merges settings sources per key, so every other key of the user's+ * settings files still applies; this overlay only wins on the keys it sets.** (The OS *managed* tier can't be overridden — that case aborts before we get here.)*/diff --cc packages/cli/src/force-login-method.test.tsindex cca66f96,6fc6db7e..cda34747--- a/packages/cli/src/force-login-method.test.ts+++ b/packages/cli/src/force-login-method.test.ts@@@ -98,29 -98,19 +98,50 @@@ describe("buildClaudishSettingsOverlay").toBe(false);});- test.each([true, false])("pane editorMode follows the marker (proxy=%p)", (proxyAuthMode) => {- const saved = process.env.CLAUDISH_PANE_CHILD;++ test.each([true, false])("pane editorMode needs the flag and cwd (proxy=%p)", (proxyAuthMode) => {++ const savedFlag = process.env.CLAUDISH_PANE_CHILD;++ const savedCwd = process.env.CLAUDISH_PANE_CWD;+ try {- for (const marker of ["1", undefined, "0", ""]) {- if (marker === undefined) delete process.env.CLAUDISH_PANE_CHILD;- else process.env.CLAUDISH_PANE_CHILD = marker;- const overlay = buildClaudishSettingsOverlay(statusLine, proxyAuthMode);- if (marker === "1") expect(overlay.editorMode).toBe("normal");- else expect(Object.hasOwn(overlay, "editorMode")).toBe(false);- expect(overlay.statusLine).toBe(statusLine);- if (proxyAuthMode) expect(overlay.forceLoginMethod).toBe("console");- else expect(Object.hasOwn(overlay, "forceLoginMethod")).toBe(false);++ for (const cwd of ["/w", undefined, ""]) {++ if (cwd === undefined) delete process.env.CLAUDISH_PANE_CWD;++ else process.env.CLAUDISH_PANE_CWD = cwd;++ for (const marker of ["1", undefined, "0", ""]) {++ if (marker === undefined) delete process.env.CLAUDISH_PANE_CHILD;++ else process.env.CLAUDISH_PANE_CHILD = marker;++ const overlay = buildClaudishSettingsOverlay(statusLine, proxyAuthMode);++ if (marker === "1" && cwd) {++ expect(overlay.editorMode).toBe("normal");++ expect(overlay.skipDangerousModePermissionPrompt).toBe(true);++ } else {++ expect(Object.hasOwn(overlay, "editorMode")).toBe(false);++ expect(Object.hasOwn(overlay, "skipDangerousModePermissionPrompt")).toBe(false);++ }++ expect(overlay.statusLine).toBe(statusLine);++ if (proxyAuthMode) expect(overlay.forceLoginMethod).toBe("console");++ else expect(Object.hasOwn(overlay, "forceLoginMethod")).toBe(false);++ }+ }+ } finally {- if (saved === undefined) delete process.env.CLAUDISH_PANE_CHILD;- else process.env.CLAUDISH_PANE_CHILD = saved;++ if (savedFlag === undefined) delete process.env.CLAUDISH_PANE_CHILD;++ else process.env.CLAUDISH_PANE_CHILD = savedFlag;++ if (savedCwd === undefined) delete process.env.CLAUDISH_PANE_CWD;++ else process.env.CLAUDISH_PANE_CWD = savedCwd;+ }+ });+- test("the default reads the CLAUDISH_PANE_CHILD marker", () => {- const saved = process.env.CLAUDISH_PANE_CHILD;+ test("T-U-8: the default skips the prompt only with the flag and a pane cwd", () => {+ const savedFlag = process.env.CLAUDISH_PANE_CHILD;+ const savedCwd = process.env.CLAUDISH_PANE_CWD;try {process.env.CLAUDISH_PANE_CHILD = "1";+ delete process.env.CLAUDISH_PANE_CWD;+ expect(+ "skipDangerousModePermissionPrompt" in buildClaudishSettingsOverlay(statusLine, true)+ ).toBe(false);+ process.env.CLAUDISH_PANE_CWD = "/w";+ expect(+ "skipDangerousModePermissionPrompt" in buildClaudishSettingsOverlay(statusLine, true)+ ).toBe(true);expect(buildClaudishSettingsOverlay(statusLine, true).skipDangerousModePermissionPrompt).toBe(true);@@@ -162,54 -141,6 +185,70 @@@ describe("mergeUserSettingsIfPresent",}};+ for (const form of ["inline", "file"] as const) {+ test.each([true, false])(+ `pane editorMode overrides caller vim in ${form} settings (proxy=%p)`,+ (proxyAuthMode) => {- const saved = process.env.CLAUDISH_PANE_CHILD;++ const savedFlag = process.env.CLAUDISH_PANE_CHILD;++ const savedCwd = process.env.CLAUDISH_PANE_CWD;+ try {+ process.env.CLAUDISH_PANE_CHILD = "1";++ delete process.env.CLAUDISH_PANE_CWD;++ expect(merged({ editorMode: "vim", x: 1 }, undefined, proxyAuthMode, form)).toMatchObject(++ {++ editorMode: "vim",++ x: 1,++ statusLine,++ }++ );++ const nestedSettings = merged({ x: 1 }, undefined, proxyAuthMode, form);++ expect(Object.hasOwn(nestedSettings, "editorMode")).toBe(false);++ expect(Object.hasOwn(nestedSettings, "skipDangerousModePermissionPrompt")).toBe(false);++++ process.env.CLAUDISH_PANE_CWD = "/w";+ const settings = merged({ editorMode: "vim", x: 1 }, undefined, proxyAuthMode, form);+ expect(settings).toMatchObject({ editorMode: "normal", x: 1, statusLine });+ if (proxyAuthMode) expect(settings.forceLoginMethod).toBe("console");+ else expect(Object.hasOwn(settings, "forceLoginMethod")).toBe(false);++ delete process.env.CLAUDISH_PANE_CHILD;+ expect(merged({ editorMode: "vim", x: 1 }, undefined, proxyAuthMode, form)).toMatchObject(+ {+ editorMode: "vim",+ x: 1,+ statusLine,+ }+ );+ expect(+ Object.hasOwn(merged({ x: 1 }, undefined, proxyAuthMode, form), "editorMode")+ ).toBe(false);+ } finally {- if (saved === undefined) delete process.env.CLAUDISH_PANE_CHILD;- else process.env.CLAUDISH_PANE_CHILD = saved;++ if (savedFlag === undefined) delete process.env.CLAUDISH_PANE_CHILD;++ else process.env.CLAUDISH_PANE_CHILD = savedFlag;++ if (savedCwd === undefined) delete process.env.CLAUDISH_PANE_CWD;++ else process.env.CLAUDISH_PANE_CWD = savedCwd;+ }+ }+ );++ test.each([true, false])(+ `editorMode does not change forceLoginMethod precedence in ${form} settings (pane=%p)`,+ (paneChild) => {+ const caller = { editorMode: "vim", forceLoginMethod: "claudeai", x: 1 };+ expect(merged(caller, paneChild, true, form)).toMatchObject({+ forceLoginMethod: "claudeai",+ editorMode: paneChild ? "normal" : "vim",+ x: 1,+ });+ expect(merged(caller, paneChild, false, form)).toMatchObject({+ forceLoginMethod: "claudeai",+ editorMode: paneChild ? "normal" : "vim",+ x: 1,+ });+ }+ );+ }+test("a pane child's merged settings carry skipDangerousModePermissionPrompt", () => {expect(merged({ model: "x" }, true).skipDangerousModePermissionPrompt).toBe(true);});diff --cc packages/cli/src/mcp-blackbox/tool-surface.blackbox.test.tsindex 44dc18eb,bbb6f04d..5a507593--- a/packages/cli/src/mcp-blackbox/tool-surface.blackbox.test.ts+++ b/packages/cli/src/mcp-blackbox/tool-surface.blackbox.test.ts@@@ -7,7 -7,8 +7,9 @@@import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { existsSync } from "node:fs";import { join } from "node:path";+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";+import { version as packageVersion } from "../../package.json";import { useBlackboxEnv } from "../test-helpers/blackbox-env.js";import {McpServer,@@@ -64,21 -28,19 +66,23 @@@ const TOOL_GROUPS: Array<{ value: strinlet layout: TempLayout;let server: McpServer;- beforeEach(async () => {- layout = makeTempLayout("bbsurface");- server = await McpServer.start({ env: serverEnv(layout), cwd: layout.cwd });- });+ function useStandardServer(): void {+ beforeEach(async () => {+ layout = makeTempLayout("bbsurface");+ server = await McpServer.start({ env: serverEnv(layout), cwd: layout.cwd });+ });- afterEach(async () => {- await server.close();- const report = await paneOrphans(layout);- layout.cleanup();- expect(report).toEqual({ processes: [], files: [] });- // REQ-19: none of these public calls may emit the removed push notification.- expect(server.notifications.filter((n) => n.method === "notifications/claude/channel")).toEqual(- []- );- });+ afterEach(async () => {+ await server.close();+ const report = await paneOrphans(layout);+ layout.cleanup();+ expect(report).toEqual({ processes: [], files: [] });++ // REQ-19: none of these public calls may emit the removed push notification.++ expect(server.notifications.filter((n) => n.method === "notifications/claude/channel")).toEqual(++ []++ );+ });+ }function contractError(r: ToolResult, code: string): void {expect(r.isError).toBe(true);@@@ -89,164 -51,8 +93,167 @@@expect(typeof (body.error as Json).message).toBe("string");}+/** Capture the first initialize response on a fresh public stdio connection.+ * McpServer.start deliberately discards it; sending initialize twice would test+ * an unsupported MCP lifecycle rather than the contract's initialization.+ */+async function initializeOnce(env: Record<string, string>): Promise<Json> {+ const child = Bun.spawn([process.execPath, SERVER_ENTRY, "--mcp"], {+ env,+ cwd: layout.cwd,+ stdin: "pipe",+ stdout: "pipe",+ stderr: "pipe",+ });+ const stderr = new Response(child.stderr).text();+ const reader = child.stdout.getReader();+ const decoder = new TextDecoder();+ const timer = setTimeout(() => child.kill("SIGKILL"), 20_000);+ let buffer = "";+ try {+ child.stdin.write(+ `${JSON.stringify({+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: "2025-06-18",+ capabilities: {},+ clientInfo: { name: "quick-prompt-blackbox", version: "0.0.0" },+ },+ })}\n`+ );+ child.stdin.flush();+ for (;;) {+ const chunk = await reader.read();+ if (chunk.done) throw new Error(`MCP initialize ended without a response: ${await stderr}`);+ buffer += decoder.decode(chunk.value, { stream: true });+ for (;;) {+ const newline = buffer.indexOf("\n");+ if (newline === -1) break;+ const line = buffer.slice(0, newline).trim();+ buffer = buffer.slice(newline + 1);+ if (!line.startsWith("{")) continue;+ const message = JSON.parse(line) as Json;+ if (message.id !== 1) continue;+ expect(message.error).toBeUndefined();+ child.stdin.write(+ `${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}\n`+ );+ child.stdin.flush();+ return message.result as Json;+ }+ }+ } finally {+ reader.releaseLock();+ child.stdin.end();+ const ended = await Promise.race([+ child.exited.then(() => true),+ Bun.sleep(3_000).then(() => false),+ ]);+ if (!ended) child.kill("SIGKILL");+ await child.exited;+ clearTimeout(timer);+ await stderr;+ }+}++describe("quick-prompt public surface", () => {++ useStandardServer();+ for (const { value, names } of TOOL_GROUPS) {+ test(`REQ-15 REQ-18: CLAUDISH_MCP_TOOLS=${value ?? "unset"} exposes the exact sorted set and polling-only initialization`, async () => {+ if (value !== undefined) {+ await server.close();+ server = await McpServer.start({+ env: serverEnv(layout, { CLAUDISH_MCP_TOOLS: value }),+ cwd: layout.cwd,+ });+ }+ const tools = await server.listTools();+ expect(tools.map((tool) => tool.name).sort()).toEqual(names);++ const result = await initializeOnce(serverEnv(layout, { CLAUDISH_MCP_TOOLS: value }));+ expect(result.serverInfo).toEqual({ name: "claudish", version: packageVersion });+ const capabilities = result.capabilities as Json;+ expect(Object.hasOwn(capabilities, "tools")).toBe(true);+ expect(capabilities.experimental).toBeUndefined();+ expect(Object.hasOwn(capabilities, "experimental")).toBe(false);+ expect(typeof result.instructions).toBe("string");+ const instructions = result.instructions as string;+ expect(instructions).toContain("list_sessions");+ expect(instructions).toContain("get_output");+ expect(instructions).not.toContain("<channel");+ expect(instructions.toLowerCase()).not.toContain("notification");+ }, 30_000);+ }++ test("REQ-16 REQ-17: quick-prompt schemas omit output limits and descriptions distinguish prompts from sessions/debug", async () => {+ const tools = await server.listTools();+ const prompt = tools.find((tool) => tool.name === "run_prompt");+ const compare = tools.find((tool) => tool.name === "compare_models");+ expect(prompt).toBeDefined();+ expect(compare).toBeDefined();+ expect(Object.keys(prompt?.inputSchema?.properties ?? {}).sort()).toEqual([+ "model",+ "prompt",+ "system_prompt",+ ]);+ expect(prompt?.inputSchema?.required).toEqual(["model", "prompt"]);+ expect(prompt?.inputSchema?.properties).not.toHaveProperty("max_tokens");+ expect(Object.keys(compare?.inputSchema?.properties ?? {}).sort()).toEqual([+ "models",+ "prompt",+ "system_prompt",+ ]);+ expect(compare?.inputSchema?.required).toEqual(["models", "prompt"]);+ expect(compare?.inputSchema?.properties).not.toHaveProperty("max_tokens");+ const promptDescription = (prompt as unknown as { description: string }).description;+ const compareDescription = (compare as unknown as { description: string }).description;+ expect(promptDescription.startsWith("One quick prompt, straight to one model's API")).toBe(+ true+ );+ expect(promptDescription).toContain("create_session");+ expect(promptDescription).toContain("team");+ expect(compareDescription.startsWith("DEBUG.")).toBe(true);+ }, 30_000);+});++describe("CLAUDISH_MCP_TOOLS startup warnings", () => {++ useStandardServer();+ for (const value of ["channel", "lowlevel", undefined, "all", "session", "debug"]) {+ test(`${value ?? "unset"}: warns exactly once only for an unknown value`, async () => {+ if (value !== undefined) {+ await server.close();+ server = await McpServer.start({+ env: serverEnv(layout, { CLAUDISH_MCP_TOOLS: value }),+ cwd: layout.cwd,+ });+ }+ const tools = await server.listTools();+ await server.close();+ const warnings = server.stderrText+ .split(/\r?\n/)+ .filter((line) => line.includes("CLAUDISH_MCP_TOOLS"));+ if (value === "channel" || value === "lowlevel") {+ expect(tools.map((tool) => tool.name).sort()).toEqual(ALL_TOOLS);+ expect(tools).toHaveLength(14);+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toContain(value);+ expect(warnings[0]).toContain("all, low-level, agentic, session, debug");+ if (value === "channel") {+ expect(warnings[0]).toContain("renamed to");+ expect(warnings[0]).toContain("session");+ }+ } else {+ expect(warnings).toEqual([]);+ }+ }, 30_000);+ }+});++// REQ-20 (TEST-21–TEST-26): preserve the existing pane-free session/team regressions.describe("tool list (FR11, §4)", () => {+ useStandardServer();test("14 tools, capture_session among them, team modes are exactly the seven", async () => {const tools = await server.listTools();const names = tools.map((t) => t.name);@@@ -374,7 -181,8 +382,8 @@@ describe("team: mode and argument error});});-describe("channel: argument errors that need no pane", () => {+describe("session: argument errors that need no pane", () => {+ useStandardServer();test("create_session refuses a print-mode flag with text `Error: invalid_args:`", async () => {const r = await server.callTool("create_session", {model: "contract-fake-model",@@@ -386,3 -194,130 +395,152 @@@expect((list.json as Json).sessions).toEqual([]);});});++ describe("nested MCP server over stdio", () => {+ let layout: TempLayout;+ let client: Client | undefined;+ let transport: StdioClientTransport | undefined;+ let stderr: string;++ beforeEach(() => {+ layout = makeTempLayout("nested-surface");+ client = undefined;+ transport = undefined;+ stderr = "";+ });++ afterEach(async () => {+ try {+ if (client) await client.close();+ } finally {+ try {+ await transport?.close();+ } finally {+ const report = await paneOrphans(layout);+ layout.cleanup();+ expect(report).toEqual({ processes: [], files: [] });+ }+ }+ }, 30_000);++ async function connect(mode: string | undefined, nested = true): Promise<Client> {+ transport = new StdioClientTransport({+ command: process.execPath,+ args: ["run", SERVER_ENTRY, "--mcp"],+ cwd: layout.cwd,+ env: serverEnv(layout, {+ CLAUDISH_PANE_CHILD: nested ? "1" : undefined,+ CLAUDISH_MCP_TOOLS: mode,+ }),+ stderr: "pipe",+ });+ transport.stderr?.on("data", (chunk: Buffer) => {+ stderr += chunk.toString();+ });+ client = new Client({ name: "nested-surface-tests", version: "1.0.0" }, { capabilities: {} });+ await client.connect(transport);+ return client;+ }+++ async function waitForStartup(): Promise<void> {++ // stderr and stdout are separate pipes: wait for the startup line to be drained.++ const deadline = Date.now() + 2000;++ while (!stderr.includes("MCP server started") && Date.now() < deadline) await Bun.sleep(10);++ expect(stderr).toContain("MCP server started");++ }+++ const fourTools = ["compare_models", "list_models", "run_prompt", "search_models"];+ const removedTools = [+ "team",+ "create_session",+ "send_input",+ "get_output",+ "cancel_session",+ "list_sessions",+ "get_diagnostics",+ "capture_session",+ "preflight",+ "report_error",+ ];++ test("T-MCP-1: all exposes exactly four nested tools and logs the nested startup line", async () => {+ const c = await connect("all");+ const names = (await c.listTools()).tools.map((tool) => tool.name).sort();+ expect(names).toEqual(fourTools);+ for (const name of removedTools) expect(names).not.toContain(name);- // stderr and stdout are separate pipes: wait briefly for the startup line to be drained.- const deadline = Date.now() + 2000;- while (!stderr.includes("MCP server started") && Date.now() < deadline) await Bun.sleep(10);++ await waitForStartup();+ expect(stderr.split(/\r?\n/)).toContain(+ "[claudish] MCP server started (tools: nested, 4 tools)"+ );+ }, 30_000);++ for (const [mode, expected] of [- ["channel", []],- ["low-level", fourTools],++ ["channel", fourTools],++ ["low-level", ["list_models", "run_prompt", "search_models"]],+ ["agentic", []],++ ["session", []],++ ["debug", ["compare_models"]],++ ["all", fourTools],+ [undefined, fourTools],+ ] as const) {+ test(`T-MCP-2: ${mode ?? "unset"} intersects its tool group with nested tools`, async () => {+ const c = await connect(mode);+ expect((await c.listTools()).tools.map((tool) => tool.name).sort()).toEqual([...expected]);+ expect(c.getServerCapabilities()).toHaveProperty("tools");+ expect(c.getServerCapabilities()).not.toHaveProperty("experimental");+ expect(c.getInstructions()).toContain("## Nested mode — no sessions");+ expect(c.getInstructions()).not.toContain("Channel Mode");++ await waitForStartup();++ expect(stderr.split(/\r?\n/)).toContain(++ `[claudish] MCP server started (tools: nested, ${expected.length} tools)`++ );++ const warnings = stderr.split(/\r?\n/).filter((line) => line.includes("CLAUDISH_MCP_TOOLS"));++ if (mode === "channel") {++ expect(warnings).toHaveLength(1);++ expect(warnings[0]).toContain("channel");++ expect(warnings[0]).toContain("renamed to");++ expect(warnings[0]).toContain("all, low-level, agentic, session, debug");++ } else {++ expect(warnings).toEqual([]);++ }+ }, 30_000);+ }++ test("T-MCP-3: initialize advertises tools without channels and gives nested instructions", async () => {+ const c = await connect("all");+ expect(c.getServerCapabilities()).toHaveProperty("tools");+ expect(c.getServerCapabilities()).not.toHaveProperty("experimental");+ const instructions = c.getInstructions();+ const { NESTED_INSTRUCTIONS } = await import("../mcp/nested-mode.js");+ expect(instructions).toBe(NESTED_INSTRUCTIONS);+ expect(+ instructions?.startsWith(+ "Claudish MCP server provides access to external AI models for one-shot calls."+ )+ ).toBe(true);+ expect(instructions).toContain("## Nested mode — no sessions");+ expect(instructions).toContain("nested session refused");+ expect(instructions).not.toContain("Channel Mode");+ expect(instructions).not.toMatch(/^- (?:preflight|report_error):/m);+ }, 30_000);++ test("T-MCP-4: removed session tools answer Unknown tool and leave no panes", async () => {+ const c = await connect("all");+ for (const name of ["create_session", "team"]) {+ const result = await c.callTool({ name, arguments: { model: "x", prompt: "y" } });+ expect(result.isError).toBe(true);+ expect(result.content).toEqual([{ type: "text", text: `Error: Unknown tool "${name}"` }]);+ }+ expect(await paneOrphans(layout)).toEqual({ processes: [], files: [] });+ }, 30_000);+- test("T-MCP-5: without the flag all still exposes 14 tools and the channel capability", async () => {++ test("T-MCP-5: without the flag all still exposes 14 tools without an experimental capability", async () => {+ const c = await connect("all", false);+ const tools = (await c.listTools()).tools;+ expect(tools).toHaveLength(14);+ expect(new Set(tools.map((tool) => tool.name)).size).toBe(14);- expect(c.getServerCapabilities()?.experimental?.["claude/channel"]).toBeDefined();++ expect(c.getServerCapabilities()).toHaveProperty("tools");++ expect(c.getServerCapabilities()).not.toHaveProperty("experimental");+ expect(c.getInstructions()).not.toContain("## Nested mode — no sessions");+ }, 30_000);+ });diff --cc packages/cli/src/mcp-server.tsindex d8af5af7,356a9e33..152b7c55--- a/packages/cli/src/mcp-server.ts+++ b/packages/cli/src/mcp-server.ts@@@ -21,30 -21,22 +21,25 @@@ import { CallToolRequestSchema, ListTooimport { config } from "dotenv";import { searchCatalogModels } from "./adapters/model-catalog.js";import { prehydrateCredentialsForSpawn } from "./auth/credentials/prehydrate.js";-import { installWireTap, watchNotificationResult, wrapStateChange } from "./channel/diagnostics.js";-import { SessionManager } from "./channel/index.js";-import { parentSessionForCall } from "./channel/parent-session.js";-import type { ChannelEventType } from "./channel/types.js";import { isSubscriptionProvider } from "./handlers/shared/remote-provider-types.js";+import { SessionManager } from "./mcp-session/index.js";+import { parentSessionForCall } from "./mcp-session/parent-session.js";+ import { NESTED_INSTRUCTIONS, NESTED_MCP_TOOL_NAMES } from "./mcp/nested-mode.js";import {type HeartbeatHandle,NOOP_HEARTBEAT,resolveProgressIntervalMs,startHeartbeat,} from "./mcp/progress-heartbeat.js";+import {+ type RunPromptResult,+ runPromptViaClaudeCode,+ stopAllClaudeCodePrintChildren,+} from "./mcp/run-prompt-claude-code.js";- import {- type RecommendedModelGroup,- type RecommendedModelsDoc,- collectRoutingPrefixes,- computeQuickPicks,- formatListingPrice,- getRecommendedModels,- groupRecommendedModels,- normalizePricingDisplay,- } from "./model-loader.js";+ import { type RecommendedModelsDoc, getRecommendedModels } from "./model-loader.js";+ // Imported for the predicate only. child-env's import-time bootstrap is a no-op here:+ // a claudish MCP server is never the pane child (it carries no CLAUDISH_PANE_CWD).+ import { inMcpSession } from "./pane/child-env.js";import {ContractErrorException,type FailureReason,@@@ -844,9 -792,44 +838,13 @@@ const sanitize = sanitizeForReport// ─── Tool Definitions ────────────────────────────────────────────────────────- function defineTools(sessionManager: SessionManager): ToolDefinition[] {-/**- * Pushes a live progress frame to the client, or is a no-op when the channel- * capability is not enabled. `team` uses this to report per-model token/cost- * stats while a multi-minute run is still in flight.- *- * Channels are the ONLY measured-working push mechanism FOR RENDERING:- * `notifications/progress` renders nowhere on Claude Code 2.1.220 — verified empty- * in both the agent's context and the interactive terminal UI. See- * ai-docs/sessions/dev-arch-20260729-171308-1dad34b5/capability-findings.md.- *- * That says nothing about KEEPALIVE, which is the opposite result: a progress frame- * resets the client's MCP idle timer and a channel frame does not (measured- * 2026-08-14 on 2.1.231 — a real `team` run died at exactly 1800s while emitting- * channel frames throughout). See- * ai-docs/sessions/mcp-progress-idle-timeout-20260814-000000-b7e21f4a/findings.md.- * The two mechanisms are complementary and both stay: channel is the visible- * surface, `notifications/progress` (mcp/progress-heartbeat.ts) is the keepalive.- */-type ChannelNotifier = (params: {- content: string;- sessionId: string;- event: string;- model: string;- elapsedSeconds: number;- createdAt: string;-}) => void;--function defineTools(- sessionManager: SessionManager,- notifyChannel: ChannelNotifier,- nested: boolean-): ToolDefinition[] {++function defineTools(sessionManager: SessionManager, nested: boolean): ToolDefinition[] {const tools: ToolDefinition[] = [];+ // A nested server does not register `report_error` (mcp/nested-mode.ts), so an+ // error text must not point at it.+ const reportHint = (text: string): string => (nested ? "" : text);+// ── Low-Level Tools ──────────────────────────────────────────────────/**@@@ -2322,19 -2277,23 +2255,24 @@@ function unknownToolModeWarning(mode: sasync function main() {const toolMode = (process.env.CLAUDISH_MCP_TOOLS || "all").toLowerCase();+ // Inside a session a claudish owner started, one level of nesting is the limit:+ // only the one-shot tools of NESTED_MCP_TOOL_NAMES, intersected with the groups+ // CLAUDISH_MCP_TOOLS enables (never widened), no channel capability, and the+ // nested instructions. See pane-session.md § One level of nesting.+ const nested = inMcpSession();const enabledGroups = resolveToolGroups(toolMode);- const channelEnabled = !nested && enabledGroups.has("channel");+ const toolModeWarning = unknownToolModeWarning(toolMode);+ if (toolModeWarning) console.error(toolModeWarning);- // Create server with channel capability+ // Tools only, for every tool mode. No `experimental: {"claude/channel": {}}`: the+ // server pushes nothing; a host polls `list_sessions` and reads the records.const server = new Server(- { name: "claudish", version: "9.0.0" },+ // `version.ts` is generated from packages/cli/package.json, so serverInfo names+ // the release the host is actually talking to.+ { name: "claudish", version: VERSION },{- capabilities: {- ...(channelEnabled ? { experimental: { "claude/channel": {} } } : {}),- tools: {},- },+ capabilities: { tools: {} },- instructions: INSTRUCTIONS,+ instructions: nested ? NESTED_INSTRUCTIONS : INSTRUCTIONS,});@@@ -2347,11 -2379,16 +2285,16 @@@const progressIntervalMs = resolveProgressIntervalMs();// Build tool registry- const allTools = defineTools(sessionManager);- const enabledTools = allTools.filter((t) => enabledGroups.has(t.group));- const allTools = defineTools(sessionManager, notifyChannel, nested);++ const allTools = defineTools(sessionManager, nested);+ const nestedNames: readonly string[] = NESTED_MCP_TOOL_NAMES;+ const enabledTools = allTools.filter(+ (t) => enabledGroups.has(t.group) && (!nested || nestedNames.includes(t.name))+ );const toolMap = new Map(enabledTools.map((t) => [t.name, t]));- console.error(`[claudish] MCP server started (tools: ${toolMode}, ${enabledTools.length} tools)`);+ console.error(+ `[claudish] MCP server started (tools: ${nested ? "nested" : toolMode}, ${enabledTools.length} tools)`+ );// Register ListTools handlerserver.setRequestHandler(ListToolsRequestSchema, async () => ({diff --cc packages/cli/src/mcp-session/e2e-sessions.test.tsindex 72a17262,130af1c3..67f8cc05--- a/packages/cli/src/mcp-session/e2e-sessions.test.ts+++ b/packages/cli/src/mcp-session/e2e-sessions.test.ts@@@ -231,14 -259,17 +234,17 @@@ describe("Group 1b: MCP Protocol — setransport = new StdioClientTransport({command: "bun",args: ["run", SERVER_ENTRY, "--mcp"],- env: {- ...process.env,- CLAUDISH_MCP_TOOLS: "session",- CLAUDISH_SESSIONS_DIR: SESSIONS_DIR,- },+ env: Object.fromEntries(+ Object.entries({+ ...process.env,+ CLAUDISH_PANE_CHILD: undefined,- CLAUDISH_MCP_TOOLS: "channel",++ CLAUDISH_MCP_TOOLS: "session",+ CLAUDISH_SESSIONS_DIR: SESSIONS_DIR,+ }).filter((entry): entry is [string, string] => entry[1] !== undefined)+ ),stderr: "pipe",});- client = new Client({ name: "test-client-channel", version: "1.0.0" }, { capabilities: {} });+ client = new Client({ name: "test-client-session", version: "1.0.0" }, { capabilities: {} });await client.connect(transport);}, 15000);@@@ -295,63 -329,6 +304,66 @@@ describe("Group 1b: MCP Protocol — lo});});+for (const [toolMode, expected] of [+ [+ "channel",+ [+ "cancel_session",+ "capture_session",+ "compare_models",+ "create_session",+ "get_diagnostics",+ "get_output",+ "list_models",+ "list_sessions",+ "preflight",+ "report_error",+ "run_prompt",+ "search_models",+ "send_input",+ "team",+ ],+ ],+ ["debug", ["compare_models"]],+] as const) {+ describe(`Group 1b: MCP Protocol — CLAUDISH_MCP_TOOLS=${toolMode}`, () => {+ let client: Client;+ let transport: StdioClientTransport;++ beforeAll(async () => {+ transport = new StdioClientTransport({+ command: "bun",+ args: ["run", SERVER_ENTRY, "--mcp"],- env: {- ...process.env,- CLAUDISH_MCP_TOOLS: toolMode,- CLAUDISH_SESSIONS_DIR: SESSIONS_DIR,- },++ env: Object.fromEntries(++ Object.entries({++ ...process.env,++ CLAUDISH_PANE_CHILD: undefined,++ CLAUDISH_MCP_TOOLS: toolMode,++ CLAUDISH_SESSIONS_DIR: SESSIONS_DIR,++ }).filter((entry): entry is [string, string] => entry[1] !== undefined)++ ),+ stderr: "pipe",+ });+ client = new Client(+ { name: `test-client-${toolMode}`, version: "1.0.0" },+ { capabilities: {} }+ );+ await client.connect(transport);+ }, 15000);++ afterAll(async () => {+ try {+ await transport.close();+ } catch {}+ });++ test(`lists the exact tools for CLAUDISH_MCP_TOOLS=${toolMode}`, async () => {+ const result = await client.listTools();+ expect(result.tools.map((tool) => tool.name).sort()).toEqual([...expected]);+ });+ });+}+// ─── Group 2: Real Claude Code Integration ───────────────────────────────────// Spawns `claude -p` with our MCP server registered via --mcp-config.// Validates that Claude Code sees our tools and can call them.diff --cc packages/cli/src/mcp/nested-mode.tsindex 00000000,0cbd5280..62621722mode 000000,100644..100644--- a/packages/cli/src/mcp/nested-mode.ts+++ b/packages/cli/src/mcp/nested-mode.ts@@@ -1,0 -1,38 +1,39 @@@+ /**+ * The claudish MCP server's surface inside a session that a claudish owner started+ * (`CLAUDISH_PANE_CHILD=1`, read by `inMcpSession()`), where one level of nesting is- * the limit. See `ai-docs/architecture/mcp-channel.md` § Nested mode and++ * the limit. See `ai-docs/architecture/mcp-sessions.md` § Nested mode and+ * `pane-session.md` § One level of nesting.+ *+ * A leaf module that imports nothing, so a test can read the list without importing+ * `mcp-server.ts`, which loads `.env` at import time.+ */++ /**+ * The tools a nested server registers, by NAME. The rule: keep a tool only if it is a- * one-shot call that starts no session, no pane and no claudish child. `run_prompt` and- * `compare_models` answer through an in-process proxy; the two catalog reads start- * nothing. The list fails closed: a tool added later is absent in nested mode until++ * one-shot call that starts no session, no pane and no claudish child that could start++ * one. `run_prompt` and `compare_models` answer through an in-process proxy, except++ * `run_prompt` on a Claude model: that starts one `claudish -p` leaf with no tools and++ * no MCP servers (mcp/run-prompt-claude-code.ts). The two catalog reads start nothing. The list fails closed: a tool added later is absent in nested mode until+ * someone lists it here, which a group filter would not guarantee.+ *+ * Nested mode INTERSECTS this list with the groups `CLAUDISH_MCP_TOOLS` enables; it+ * never widens them.+ */+ export const NESTED_MCP_TOOL_NAMES = [+ "run_prompt",+ "list_models",+ "search_models",+ "compare_models",+ ] as const;++ /** The server instructions in nested mode, in place of the channel-mode text. */+ export const NESTED_INSTRUCTIONS = `Claudish MCP server provides access to external AI models for one-shot calls.++ ## Nested mode — no sessions++ This server runs inside a session that a claudish MCP server started (CLAUDISH_PANE_CHILD=1). One level of nesting is the limit, so these tools are not registered: create_session, team, send_input, get_output, cancel_session, list_sessions, get_diagnostics, capture_session, preflight, report_error. No channel notifications are sent.++ - run_prompt or compare_models: a one-shot answer from another model.+ - list_models, search_models: find a model.++ Do not start a claudish session another way: \`claudish -p\`, an interactive claudish or \`claudish team\` run from this session's shell exits 64 with "nested session refused".`;diff --cc packages/cli/src/mcp/run-prompt-claude-code.env.test.tsindex 00000000,00000000..228f8f5bnew file mode 100644--- /dev/null+++ b/packages/cli/src/mcp/run-prompt-claude-code.env.test.ts@@@ -1,0 -1,0 +1,107 @@@++import { describe, expect, test } from "bun:test";++import { STRIPPED_CHILD_VARS } from "../launcher/magmux-wrapper.js";++import { nestedLaunchRefusal } from "../pane/child-env.js";++import {++ HOST_IDENTITY_VARS,++ TERMINAL_IDENTITY_PREFIXES,++ TERMINAL_IDENTITY_VARS,++ isStrippedFromChildEnv,++} from "../pane/pane-launch.js";++import { claudeCodePrintEnv } from "./run-prompt-claude-code.js";++++describe("claudeCodePrintEnv", () => {++ test("drops all three pane markers from a pane-launch environment", () => {++ const parent = Object.freeze({++ CLAUDISH_PANE_CHILD: "1",++ CLAUDISH_PANE_ENV: JSON.stringify({ FOO: "bar" }),++ CLAUDISH_PANE_CWD: "/sandbox/work",++ FOO: "bar",++ });++++ const child = claudeCodePrintEnv(parent);++ for (const key of ["CLAUDISH_PANE_CHILD", "CLAUDISH_PANE_ENV", "CLAUDISH_PANE_CWD"]) {++ expect(Object.hasOwn(child, key)).toBe(false);++ }++ expect(child).toEqual({ FOO: "bar" });++ });++++ test.each(["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"])(++ "drops %s regardless of its value",++ (key) => {++ for (const value of ["inherited", ""]) {++ const parent = Object.freeze({ [key]: value, FOO: "bar" });++ const child = claudeCodePrintEnv(parent);++ expect(Object.hasOwn(child, key)).toBe(false);++ expect(child).toEqual({ FOO: "bar" });++ }++ }++ );++++ test("strips every shared child-env key and terminal-identity prefix", () => {++ const strippedKeys = [++ ...STRIPPED_CHILD_VARS,++ ...HOST_IDENTITY_VARS,++ ...TERMINAL_IDENTITY_VARS,++ "MAGMUX_SOCK",++ "MAGMUX_UNRECOGNIZED",++ ...TERMINAL_IDENTITY_PREFIXES.map((prefix) => `${prefix}UNRECOGNIZED`),++ ];++ const parent = Object.freeze({++ ...Object.fromEntries(strippedKeys.map((key) => [key, "inherited"])),++ FOO: "bar",++ });++ const child = claudeCodePrintEnv(parent);++++ for (const key of strippedKeys) {++ expect(isStrippedFromChildEnv(key)).toBe(true);++ expect(Object.hasOwn(child, key)).toBe(false);++ }++ expect(child).toEqual({ FOO: "bar" });++ });++++ test("keeps unrelated values unchanged, omits undefined, and does not mutate the parent", () => {++ const parent = Object.freeze({++ PATH: "/sandbox/bin:/usr/bin:/bin",++ HOME: "/sandbox/home",++ FOO: "bar",++ EMPTY: "",++ ZERO: "0",++ UNSET: undefined,++ });++ const child = claudeCodePrintEnv(parent);++++ expect(child).toEqual({++ PATH: parent.PATH,++ HOME: parent.HOME,++ FOO: "bar",++ EMPTY: "",++ ZERO: "0",++ });++ expect(Object.hasOwn(child, "UNSET")).toBe(false);++ expect(child).not.toBe(parent);++ expect(parent).toEqual({++ PATH: "/sandbox/bin:/usr/bin:/bin",++ HOME: "/sandbox/home",++ FOO: "bar",++ EMPTY: "",++ ZERO: "0",++ UNSET: undefined,++ });++ });++++ test("a nested server's print child does not trigger the nested launch refusal", () => {++ // A nested server inherits the flag but no longer has the pane launch cwd.++ const parent = Object.freeze({++ PATH: "/sandbox/bin:/usr/bin:/bin",++ HOME: "/sandbox/home",++ FOO: "bar",++ CLAUDISH_PANE_CHILD: "1",++ });++ expect(nestedLaunchRefusal(parent)).toContain("one level of nesting is the limit");++++ const child = claudeCodePrintEnv(parent);++ expect(nestedLaunchRefusal(child)).toBeNull();++ expect(child).toEqual({ PATH: parent.PATH, HOME: parent.HOME, FOO: "bar" });++ expect(parent.CLAUDISH_PANE_CHILD).toBe("1");++ });++});diff --cc packages/cli/src/mcp/run-prompt-claude-code.tsindex 0d2c7518,00000000..e867a709mode 100644,000000..100644--- a/packages/cli/src/mcp/run-prompt-claude-code.ts+++ b/packages/cli/src/mcp/run-prompt-claude-code.ts@@@ -1,376 -1,0 +1,390 @@@+/**+ * `run_prompt` (and `compare_models`) for a Claude model: one Claude Code print-mode+ * call through claudish, signed in with Claude Code's own login.+ *+ * Why not the in-process proxy: for a bare Claude name the proxy takes the native+ * route, which forwards the CALLER's credential, and an MCP tool call has none — the+ * request reached Anthropic with no `x-api-key` and came back 401. claudish must never+ * read the Claude Code OAuth token or its Keychain item itself, so the only way onto+ * the user's subscription is the unmodified `claude` binary signing in on its own:+ *+ * <claudish> -p --model <model> --output-format json --tools "" --strict-mcp-config+ * --setting-sources "" --disable-slash-commands --no-session-persistence+ * (--system-prompt-file <file> | --system-prompt "")+ *+ * The prompt goes on stdin, the child runs in an empty temporary directory (otherwise+ * CLAUDE.md and memory load: 8 718 input tokens instead of ~590), and the child's+ * environment drops the three `ANTHROPIC_*` variables that would take the request off+ * the login. Rationale and measurements: ai-docs/architecture/mcp-sessions.md+ * ("run_prompt") and headless-vs-interactive.md (why `-p` is safe for this one call).+ */++import { type ChildProcess, spawn } from "node:child_process";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";- import { PANE_MARKER_VARS } from "../pane/child-env.js";++import { ENV } from "../config.js";++import { PANE_LAUNCH_VARS } from "../pane/child-env.js";+import { isStrippedFromChildEnv, resolveClaudishLaunch } from "../pane/pane-launch.js";+import { sanitizeForReport } from "../redact.js";++/** What one `run_prompt` call answers, on either path. */+export interface RunPromptResult {+ /** The model's answer, verbatim. */+ content: string;+ /** Same shape as `runPromptViaProxy`'s. */+ usage?: { input: number; output: number };+ /**+ * Claude path only: how Claude Code authenticated, from the init frame's+ * `apiKeySource`. `"subscription"` when that is `"none"` (the Claude Code login),+ * any other value verbatim.+ */+ auth?: string;+}++/** The two frames of Claude Code's `--output-format json` this module reads. */+export interface ClaudeCodePrintResult {+ /** The result frame's `result`; `""` when absent. */+ result: string;+ isError: boolean;+ /** `api_error_status` when it is a number, else null. */+ apiErrorStatus: number | null;+ terminalReason?: string;+ usage?: { input: number; output: number };+ /** The init frame's `apiKeySource`, when an init frame was printed. */+ apiKeySource?: string;+}++/** The flags every print child gets, in order, before the system-prompt flag. */+const PRINT_FLAGS = [+ "-p",+ "--output-format",+ "json",+ "--tools",+ "",+ "--strict-mcp-config",+ "--setting-sources",+ "",+ "--disable-slash-commands",+ "--no-session-persistence",+] as const;++/**+ * The argv after claudish's own launch words. No positional prompt and no flag value+ * that could start with `-`: claudish's passthrough parser takes a value only when it+ * does not start with `-`, so the prompt travels on stdin and the system prompt in a+ * file. `--system-prompt ""` replaces Claude Code's default system prompt (3 232 input+ * tokens) when the caller gave none, because the proxy path sends none either.+ */+export function claudeCodePrintArgv(model: string, systemPromptFile: string | undefined): string[] {+ const head = [PRINT_FLAGS[0], "--model", model, ...PRINT_FLAGS.slice(1)];+ return systemPromptFile !== undefined+ ? [...head, "--system-prompt-file", systemPromptFile]+ : [...head, "--system-prompt", ""];+}+++/**++ * The pane markers the print child must not inherit: the launch markers, and++ * `CLAUDISH_PANE_CHILD`. Inside a session (a nested server) the flag would make++ * `assertNotNested` refuse `-p` with exit 64, and `run_prompt` is one of the tools++ * nested mode keeps. Dropping it does not open a second level of nesting: the++ * child runs with no tools, no MCP servers, no setting sources and no slash++ * commands (PRINT_FLAGS), so it cannot start a session, a pane or a claudish.++ */++const PRINT_CHILD_DROPPED_MARKERS: readonly string[] = [++ ...PANE_LAUNCH_VARS,++ ENV.CLAUDISH_PANE_CHILD,++];+++/**+ * The print child's environment: the server's, minus the set no claudish child may- * inherit (the same predicate the pane spawner uses), minus the pane markers (with- * one set, the child would refuse `-p` and exit 64), minus the three `ANTHROPIC_*`++ * inherit (the same predicate the pane spawner uses), minus the pane markers++ * (PRINT_CHILD_DROPPED_MARKERS), minus the three `ANTHROPIC_*`+ * variables. `ANTHROPIC_API_KEY` goes unconditionally: a Claude model in `run_prompt`+ * runs on the Claude Code login; the metered Anthropic API is `anthropic@claude-*`,+ * which is not native and never reaches this module.+ */+export function claudeCodePrintEnv(+ parent: Record<string, string | undefined>+): Record<string, string> {+ const env: Record<string, string> = {};+ for (const [k, v] of Object.entries(parent)) {+ if (v === undefined || isStrippedFromChildEnv(k)) continue;- if ((PANE_MARKER_VARS as readonly string[]).includes(k)) continue;++ if (PRINT_CHILD_DROPPED_MARKERS.includes(k)) continue;+ env[k] = v;+ }+ delete env.ANTHROPIC_API_KEY;+ delete env.ANTHROPIC_AUTH_TOKEN;+ delete env.ANTHROPIC_BASE_URL;+ return env;+}++type Frame = Record<string, unknown>;++function isFrame(v: unknown): v is Frame {+ return typeof v === "object" && v !== null && !Array.isArray(v);+}++function parseJsonDocument(stdout: string): unknown {+ const text = stdout.trim();+ if (!text) return undefined;+ try {+ return JSON.parse(text);+ } catch {+ // A stray non-JSON line before the document (a banner) must not hide it: try the+ // last line that looks like a JSON document.+ const lines = text.split("\n");+ for (let i = lines.length - 1; i >= 0; i--) {+ const line = lines[i].trim();+ if (!line.startsWith("[") && !line.startsWith("{")) continue;+ try {+ return JSON.parse(line);+ } catch {+ // keep looking+ }+ }+ return undefined;+ }+}++function num(v: unknown): number {+ return typeof v === "number" && Number.isFinite(v) ? v : 0;+}++/**+ * Read Claude Code's `--output-format json` output: an ARRAY of frames on 2.1.301+ * (`system/init`, `assistant`, `rate_limit_event`, `result`), a single result object in+ * older releases. Takes the last `type: "result"` frame and the `system/init` frame.+ * Null when there is no result frame, so an unknown shape is never a false success.+ */+export function parseClaudeCodePrintOutput(stdout: string): ClaudeCodePrintResult | null {+ const doc = parseJsonDocument(stdout);+ const frames: Frame[] = Array.isArray(doc) ? doc.filter(isFrame) : isFrame(doc) ? [doc] : [];+ let result: Frame | undefined;+ let init: Frame | undefined;+ for (const f of frames) {+ if (f.type === "result") result = f;+ else if (f.type === "system" && f.subtype === "init" && init === undefined) init = f;+ }+ if (!result) return null;++ const parsed: ClaudeCodePrintResult = {+ result: typeof result.result === "string" ? result.result : "",+ isError: result.is_error === true,+ apiErrorStatus: typeof result.api_error_status === "number" ? result.api_error_status : null,+ };+ if (typeof result.terminal_reason === "string") parsed.terminalReason = result.terminal_reason;+ if (isFrame(result.usage)) {+ const u = result.usage;+ // A cached prefix is still context the model saw, so it counts as input.+ parsed.usage = {+ input:+ num(u.input_tokens) + num(u.cache_creation_input_tokens) + num(u.cache_read_input_tokens),+ output: num(u.output_tokens),+ };+ }+ if (init && typeof init.apiKeySource === "string") parsed.apiKeySource = init.apiKeySource;+ return parsed;+}++/** `apiKeySource` → the `auth` field: `"none"` is the Claude Code login. */+function authFrom(apiKeySource: string | undefined): string | undefined {+ if (apiKeySource === undefined) return undefined;+ return apiKeySource === "none" ? "subscription" : apiKeySource;+}++/* ───────────────────────────── process lifetime ───────────────────────────── */++/** Print children still running, so server shutdown can stop them. */+const inFlight = new Set<ChildProcess>();++const KILL_GRACE_MS = 5000;++/**+ * Stop a print child's whole process group: SIGTERM, then SIGKILL after 5 s. The+ * group, not the pid, because `claudish` on PATH may be the `bin/claudish.cjs`+ * launcher, which orphans the real process on a plain SIGTERM.+ */+function killGroup(proc: ChildProcess): void {+ const send = (sig: NodeJS.Signals): void => {+ if (proc.exitCode !== null || proc.signalCode !== null) return;+ try {+ if (proc.pid !== undefined) process.kill(-proc.pid, sig);+ else proc.kill(sig);+ } catch {+ try {+ proc.kill(sig);+ } catch {+ // already gone+ }+ }+ };+ send("SIGTERM");+ const timer = setTimeout(() => send("SIGKILL"), KILL_GRACE_MS);+ timer.unref?.();+}++/** Stop every print child still running. Called from the MCP server's shutdown. */+export function stopAllClaudeCodePrintChildren(): void {+ for (const proc of inFlight) killGroup(proc);+}++const STDERR_TAIL_CHARS = 2000;++function stderrTail(stderr: string): string {+ return sanitizeForReport(stderr.slice(-STDERR_TAIL_CHARS).trim());+}++interface ChildOutcome {+ code: number | null;+ signal: NodeJS.Signals | null;+ stdout: string;+ stderr: string;+}++/**+ * Run one Claude model prompt as `claudish -p` and return its answer. Throws an+ * `Error` whose message is the `run_prompt` error text (without the `Error: ` prefix).+ *+ * There is no wall-clock deadline, as on the proxy path: the child stops only on the+ * call's `signal` (the host cancelled or timed out) or server shutdown.+ */+export async function runPromptViaClaudeCode(+ model: string,+ prompt: string,+ systemPrompt: string | undefined,+ opts: { signal?: AbortSignal; parentEnv?: Record<string, string | undefined> } = {}+): Promise<RunPromptResult> {+ const signal = opts.signal;+ if (signal?.aborted) throw new Error("cancelled");+ const parentEnv = opts.parentEnv ?? process.env;++ let launch: ReturnType<typeof resolveClaudishLaunch>;+ try {+ launch = resolveClaudishLaunch(parentEnv);+ } catch (e) {+ throw new Error(+ `cannot start claudish (${parentEnv.CLAUDISH_BIN?.trim() || "claudish"}): ${+ e instanceof Error ? e.message : String(e)+ }`+ );+ }++ // The child's cwd is a subdirectory, so it is EMPTY when Claude Code starts; the+ // system prompt file sits beside it, never inside it.+ const root = mkdtempSync(join(tmpdir(), "claudish-run-prompt-"));+ try {+ const cwd = join(root, "cwd");+ mkdirSync(cwd, { mode: 0o700 });+ let systemPromptFile: string | undefined;+ if (typeof systemPrompt === "string" && systemPrompt.length > 0) {+ systemPromptFile = join(root, "system-prompt.txt");+ writeFileSync(systemPromptFile, systemPrompt, { mode: 0o600 });+ }++ const argv = claudeCodePrintArgv(model, systemPromptFile);+ const outcome = await runChild(+ launch,+ argv,+ cwd,+ claudeCodePrintEnv(parentEnv),+ prompt,+ signal+ );++ if (signal?.aborted) throw new Error("cancelled");++ const parsed = parseClaudeCodePrintOutput(outcome.stdout);+ if (parsed === null) {+ const how =+ outcome.code !== null ? `exited ${outcome.code}` : `exited ${outcome.signal ?? "?"}`;+ const tail = stderrTail(outcome.stderr);+ const noFrame = outcome.code === 0 ? " with no result frame in its output" : "";+ throw new Error(`claudish -p ${how}${noFrame}${tail ? `: ${tail}` : ""}`);+ }+ if (parsed.isError) {+ const status = parsed.apiErrorStatus !== null ? ` (HTTP ${parsed.apiErrorStatus})` : "";+ throw new Error(`Claude Code: ${parsed.result || parsed.terminalReason || "error"}${status}`);+ }+ if (parsed.result === "") throw new Error("Model returned empty response");++ const answer: RunPromptResult = { content: parsed.result };+ if (parsed.usage) answer.usage = parsed.usage;+ const auth = authFrom(parsed.apiKeySource);+ if (auth !== undefined) answer.auth = auth;+ return answer;+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+}++/**+ * Spawn the child with all three stdio streams PIPED: this process's stdin and stdout+ * are the MCP JSON-RPC transport, so an inherited stdin would eat the host's requests+ * and an inherited stdout would corrupt the stream. `detached` gives the child its own+ * process group for `killGroup`.+ */+function runChild(+ launch: { command: string; prefixArgs: string[] },+ argv: string[],+ cwd: string,+ env: Record<string, string>,+ prompt: string,+ signal: AbortSignal | undefined+): Promise<ChildOutcome> {+ return new Promise((resolvePromise, reject) => {+ let proc: ChildProcess;+ try {+ proc = spawn(launch.command, [...launch.prefixArgs, ...argv], {+ cwd,+ env,+ stdio: ["pipe", "pipe", "pipe"],+ detached: true,+ });+ } catch (e) {+ reject(startError(launch.command, e));+ return;+ }++ let stdout = "";+ let stderr = "";+ let settled = false;+ const onAbort = (): void => killGroup(proc);+ const finish = (fn: () => void): void => {+ if (settled) return;+ settled = true;+ inFlight.delete(proc);+ signal?.removeEventListener("abort", onAbort);+ fn();+ };++ proc.stdout?.setEncoding("utf8");+ proc.stderr?.setEncoding("utf8");+ proc.stdout?.on("data", (chunk: string) => {+ stdout += chunk;+ });+ proc.stderr?.on("data", (chunk: string) => {+ stderr += chunk;+ });+ // EPIPE when the child exits before reading its stdin is not an error of its own;+ // the exit code and output say what happened.+ proc.stdin?.on("error", () => {});++ proc.on("error", (e) => finish(() => reject(startError(launch.command, e))));+ proc.on("close", (code, sig) =>+ finish(() => resolvePromise({ code, signal: sig, stdout, stderr }))+ );++ inFlight.add(proc);+ signal?.addEventListener("abort", onAbort, { once: true });+ if (signal?.aborted) onAbort();+ proc.stdin?.end(prompt);+ });+}++function startError(command: string, e: unknown): Error {+ const code = (e as { code?: unknown } | null)?.code;+ const detail =+ typeof code === "string" ? code : e instanceof Error ? e.message : String(e ?? "unknown");+ return new Error(`cannot start claudish (${command}): ${detail}`);+}