Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

docs(pane): record the one-level nesting rule and CLAUDISH_PANE_CHILD

Jack Rudenko6a19ee53bf05
diff --git a/CLAUDE.md b/CLAUDE.md
index e70cd0c7..30b42267 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -24,13 +24,13 @@ lives in `ROADMAP.md`.
- `pane-session.md` — MCP and CLI `team` slots and `create_session` as interactive Claude Code in
headless magmux panes: transcript turn oracle, settle on `turn_duration` (32 s quiet path gated
on 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 channel 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
- `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-channel.md` — the 14-tool MCP surface, channel sessions on panes (`send_input` queueing,
+- `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
- `team-capture.md` — why `team`'s exit 0 proves nothing, and why a slot's answer is every
@@ -132,6 +132,7 @@ negative case: if you are about to type one of those words, stop and use the lef
- A connection failure can arrive wearing an AUTH status code, at FIVE sites in `composed-handler.ts` (`refreshAuth`, `forceRefreshAuth`, the parameter-recovery re-fetch, `getHeaders`, the primary fetch). 401 is retryable to `FallbackHandler`, so answering it for a network fault walks a subscription user onto metered billing mid-outage; an unclassified THROW is the same bug one layer out (`{status: 0}` + an unconditional advance, with no cost warning). Classify first or rethrow unchanged — never invent a status. `getHeaders()` is the non-obvious one: for `gk@` it is the request's first network touch, and refresh-conditional, so it is rare rather than safe. A TRANSPORT's own `refreshAuth` catch that returns normally is the same bug one layer earlier: `openai-codex.ts` swallowed an unreachable token host and fell through to the metered api-key path.
- Anything that renders a TUI to **stderr** must `setStderrQuiet(true)` for as long as it owns the screen, and release it in a `finally`. `logStderr` writes there too, so the two interleave inside one frame: the TUI repaints its own cells over part of the line and the surviving fragments read as a layout bug. `--probe` hit this — the tell was a stray `[c`, the head of `[claudish] `, left in a failed row. The message is not lost; `logStderr` always writes the debug log as well.
- A `route binding` names one endpoint AND one credential silo. A provider that owns neither does not belong in `CATALOG_ROUTE_BINDINGS`, even when its name matches the `routeId`: since `routingProvidersForRoute` returns every provider bound to a route, a placeholder listed there becomes a route candidate and `--probe` prints a hop no key can ever satisfy. A name that only READS catalog data through a route (a vendor slug such as `anthropic` for the savings-panel price, `moonshotai` for the Kimi picker list) goes in `LOOKUP_ONLY_ROUTE_BINDINGS`, which the lookups consult and routing never does; a test pins that table's members. Do NOT fix that by filtering `reason: "virtual"` out of the gatherer — `native-anthropic` is virtual and genuinely routable through the native passthrough, so that filter takes `claude-*` away from anyone holding an `ANTHROPIC_API_KEY`.
+- `CLAUDISH_PANE_CHILD` must never be scrubbed from Claude Code's env: `scrubChildEnv` deletes only `PANE_LAUNCH_VARS` (`CLAUDISH_PANE_ENV`, `CLAUDISH_PANE_CWD`). The flag is how a claudish or claudish MCP server started inside a session knows it is one level deep; scrubbing it silently re-enables `create_session` inside `create_session`, with no error. See `pane-session.md` § One level of nesting.
## Commands
diff --git a/ai-docs/architecture/README.md b/ai-docs/architecture/README.md
index 0da7a4d2..aefa6253 100644
--- a/ai-docs/architecture/README.md
+++ b/ai-docs/architecture/README.md
@@ -32,11 +32,11 @@ three earlier write-ups this material cites were lost.
| [`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, 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 |
+| [`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 |
| [`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-channel.md`](mcp-channel.md) | The 14-tool MCP surface (7 channel tools, `capture_session` among them), 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-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 |
| [`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 --git a/ai-docs/architecture/mcp-channel.md b/ai-docs/architecture/mcp-channel.md
index 3013aca0..89fa555f 100644
--- a/ai-docs/architecture/mcp-channel.md
+++ b/ai-docs/architecture/mcp-channel.md
@@ -337,6 +337,34 @@ it is a wire contract, and an accidental change to the tool surface should be lo
Tool gating via `CLAUDISH_MCP_TOOLS` env var: `all` (default), `low-level`, `agentic`, `channel`.
+### 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;
+- 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;
+- 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
+ 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 Pattern
Uses a `ToolDefinition[]` registry with raw JSON Schema (not Zod). Two `setRequestHandler` calls replace McpServer's ergonomic API:
diff --git a/ai-docs/architecture/pane-session.md b/ai-docs/architecture/pane-session.md
index f85a100a..552e57e4 100644
--- a/ai-docs/architecture/pane-session.md
+++ b/ai-docs/architecture/pane-session.md
@@ -134,8 +134,8 @@ What blocks boot is decided by **"no input box"**, and named by a closed list:
accepting one on the user's behalf (trusting a folder, enabling a project's MCP servers) is a
decision 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 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
`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
@@ -366,11 +366,63 @@ run the user's profile.
argv, 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.
+
+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 the
classifier reads. `network-recovery.md` §7 accepts ~300 client attempts only where a person can see
the banner; a headless pane has no viewer. Tier 1's hold still runs; an exhausted episode answers an
@@ -532,7 +584,8 @@ type and new fields may only be added.
| `pane/pane-launch.ts` | root, ids, environment, launcher, shim, flag check, magmux check, spawns |
| `pane/process-identity.ts` | the identity predicates and the generated watcher script |
| `pane/pane-registry.ts` | records, the cross-process limit, shutdown hooks, the sweep |
-| `pane/child-env.ts` | the pane child: snapshot, cwd, refusal |
+| `pane/child-env.ts` | the pane child: snapshot, cwd, pane-child refusal; `inMcpSession`/`isPaneChild` and the nested refusal |
+| `mcp/nested-mode.ts` | the nested MCP tool list and instructions |
| `pane/contract.ts` | the frozen mod contract v1 |
| `pane/session-registry.ts` | the child's session-registry record, by session id (telemetry) |
| `scripts/boot-canary.ts` | boot every spawn shape against one Claude Code binary; `.github/workflows/boot-canary.yml` runs it per release on macOS and Linux |
diff --git a/ai-docs/architecture/testing.md b/ai-docs/architecture/testing.md
index 310e0774..1579d952 100644
--- a/ai-docs/architecture/testing.md
+++ b/ai-docs/architecture/testing.md
@@ -207,6 +207,15 @@ short, so socket paths stay under magmux's 100-byte limit, and never the user's
`/tmp/claudish-mux-<uid>`, whose startup sweep and 48-pane limit belong to the user's own
sessions.
+**Drop `CLAUDISH_PANE_CHILD` from any env spread from `process.env`.** The flag reaches everything a
+claudish-started session runs ([`pane-session.md`](pane-session.md) § One level of nesting), so a
+suite launched from inside one (a runner in a `create_session` pane) inherits it. A claudish child
+spawned with `...process.env` then refuses to run a model (exit 64, `nested session refused`), and
+an MCP server spawned that way lists 4 tools instead of 14. Build the env by allowlist, or set
+`CLAUDISH_PANE_CHILD: undefined` explicitly. `scripts/guard-real-config.ts` deletes the flag for
+`bun run test:safe` as a second layer; a hand-run `bun test <file>` from such a session gets no
+such help.
+
**Every test asserts that nothing outlived it** (`assertNoOrphans`, `paneOrphans(layout)`): no
process whose argv contains the test's root or a session uuid, no process left in any pane
process group, and no socket, pane record or launcher directory in the root. That assertion is