Skip to content

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

fix(pane): refuse claudish -p and team run inside an MCP-started session

Jack Rudenko9c5cd84ffeeb
diff --git a/packages/cli/src/channel/e2e-channel.test.ts b/packages/cli/src/channel/e2e-channel.test.ts
index 7e340d2a..130af1c3 100644
--- a/packages/cli/src/channel/e2e-channel.test.ts
+++ b/packages/cli/src/channel/e2e-channel.test.ts
@@ -50,13 +50,16 @@ describe("Group 1: MCP Protocol — channel capability", () => {
transport = new StdioClientTransport({
command: "bun",
args: ["run", SERVER_ENTRY, "--mcp"],
- env: {
- ...process.env,
- CLAUDISH_MCP_TOOLS: "all",
- CLAUDISH_SESSIONS_DIR: SESSIONS_DIR,
- // create_session children would otherwise resolve the installed binary through PATH.
- CLAUDISH_BIN: SERVER_ENTRY,
- },
+ env: Object.fromEntries(
+ Object.entries({
+ ...process.env,
+ CLAUDISH_PANE_CHILD: undefined,
+ CLAUDISH_MCP_TOOLS: "all",
+ CLAUDISH_SESSIONS_DIR: SESSIONS_DIR,
+ // create_session children would otherwise resolve the installed binary through PATH.
+ CLAUDISH_BIN: SERVER_ENTRY,
+ }).filter((entry): entry is [string, string] => entry[1] !== undefined)
+ ),
stderr: "pipe",
});
client = new Client({ name: "test-client", version: "1.0.0" }, { capabilities: {} });
@@ -256,11 +259,14 @@ describe("Group 1b: MCP Protocol — channel-only tools", () => {
transport = new StdioClientTransport({
command: "bun",
args: ["run", SERVER_ENTRY, "--mcp"],
- env: {
- ...process.env,
- CLAUDISH_MCP_TOOLS: "channel",
- CLAUDISH_SESSIONS_DIR: SESSIONS_DIR,
- },
+ env: Object.fromEntries(
+ Object.entries({
+ ...process.env,
+ CLAUDISH_PANE_CHILD: undefined,
+ CLAUDISH_MCP_TOOLS: "channel",
+ 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: {} });
@@ -296,11 +302,14 @@ describe("Group 1b: MCP Protocol — low-level-only tools", () => {
transport = new StdioClientTransport({
command: "bun",
args: ["run", SERVER_ENTRY, "--mcp"],
- env: {
- ...process.env,
- CLAUDISH_MCP_TOOLS: "low-level",
- CLAUDISH_SESSIONS_DIR: SESSIONS_DIR,
- },
+ env: Object.fromEntries(
+ Object.entries({
+ ...process.env,
+ CLAUDISH_PANE_CHILD: undefined,
+ CLAUDISH_MCP_TOOLS: "low-level",
+ CLAUDISH_SESSIONS_DIR: SESSIONS_DIR,
+ }).filter((entry): entry is [string, string] => entry[1] !== undefined)
+ ),
stderr: "pipe",
});
client = new Client({ name: "test-client-low-level", version: "1.0.0" }, { capabilities: {} });
@@ -387,7 +396,7 @@ async function runClaudeWithMcp(
prompt,
],
{
- env: { ...process.env, ...opts?.extraEnv },
+ env: { ...process.env, ...opts?.extraEnv, CLAUDISH_PANE_CHILD: undefined },
stdio: ["pipe", "pipe", "pipe"],
}
);
diff --git a/packages/cli/src/channel/host-pid.contract.test.ts b/packages/cli/src/channel/host-pid.contract.test.ts
index 39673bec..f976ac11 100644
--- a/packages/cli/src/channel/host-pid.contract.test.ts
+++ b/packages/cli/src/channel/host-pid.contract.test.ts
@@ -124,7 +124,7 @@ describe.skipIf(!MAGMUX_AVAILABLE)(
[
`const child = Bun.spawn([process.execPath, ${JSON.stringify(SERVER_ENTRY)}, "--mcp"], {`,
` stdin: "inherit", stdout: "inherit", stderr: "inherit",`,
- " env: { ...process.env, CLAUDISH_LAUNCHER_PID: String(process.pid), CLAUDISH_LAUNCHER_PPID: String(process.ppid) },",
+ " env: { ...process.env, CLAUDISH_PANE_CHILD: undefined, CLAUDISH_LAUNCHER_PID: String(process.pid), CLAUDISH_LAUNCHER_PPID: String(process.ppid) },",
"});",
`process.on("SIGTERM", () => { child.kill("SIGTERM"); });`,
"process.exitCode = await child.exited;",
diff --git a/packages/cli/src/claude-runner-child-env.test.ts b/packages/cli/src/claude-runner-child-env.test.ts
index 7d97f41f..538f8b1f 100644
--- a/packages/cli/src/claude-runner-child-env.test.ts
+++ b/packages/cli/src/claude-runner-child-env.test.ts
@@ -30,7 +30,7 @@ describe("scrubChildEnv", () => {
});
for (const interactive of [true, false]) {
- test(`the CLAUDISH_PANE_* markers never reach Claude Code (interactive: ${interactive})`, () => {
+ test(`T-U-7: launch variables are removed and the session flag reaches Claude Code (interactive: ${interactive})`, () => {
const env: Record<string, string | undefined> = {
CLAUDISH_PANE_CHILD: "1",
CLAUDISH_PANE_ENV: "{}",
@@ -38,7 +38,7 @@ describe("scrubChildEnv", () => {
CLAUDISH_TOKEN_FILE: "/run/a.json",
};
scrubChildEnv(env, { interactive });
- expect(env).toEqual({ CLAUDISH_TOKEN_FILE: "/run/a.json" });
+ expect(env).toEqual({ CLAUDISH_PANE_CHILD: "1", CLAUDISH_TOKEN_FILE: "/run/a.json" });
});
}
});
diff --git a/packages/cli/src/claude-runner.ts b/packages/cli/src/claude-runner.ts
index 4ea8429e..f094d461 100644
--- a/packages/cli/src/claude-runner.ts
+++ b/packages/cli/src/claude-runner.ts
@@ -25,7 +25,7 @@ import {
// Aliased: runClaudeWithProxy declares its own local `log` (a quiet-aware
// console printer), and an unaliased import would be shadowed inside it.
import { log as debugLog, logStderr } from "./logger.js";
-import { PANE_MARKER_VARS, isPaneChild } from "./pane/child-env.js";
+import { PANE_LAUNCH_VARS, isPaneChild } from "./pane/child-env.js";
import { loadConfig } from "./profile-config.js";
import { discoverContextWindow } from "./providers/model-discovery.js";
import { parseModelSpec } from "./providers/model-parser.js";
@@ -982,11 +982,17 @@ export function createTempSettingsFile(
* writes no transcript. Only the magmux-wrap path stripped it before. Print mode is
* left as it was.
*
- * Every launch loses the `CLAUDISH_PANE_*` markers (`PANE_MARKER_VARS`). They describe
- * THIS claudish (an MCP pane child), not Claude Code; inherited, a claudish started
- * from the slot's Bash tool would take itself for a pane child (re-apply a stale
- * environment snapshot, refuse a prompt, lose its recovery surface). The markers stay
- * in this process's own `process.env`, which `magmuxPaneCapability()` reads.
+ * Every launch loses `CLAUDISH_PANE_ENV` and `CLAUDISH_PANE_CWD` (`PANE_LAUNCH_VARS`).
+ * They describe THIS claudish (an MCP pane child), not Claude Code; inherited, a
+ * claudish started from the slot's Bash tool would take itself for the pane child
+ * (re-apply a stale environment snapshot, chdir). They stay in this process's own
+ * `process.env`, which `isPaneChild()` and `magmuxPaneCapability()` read.
+ *
+ * `CLAUDISH_PANE_CHILD` is KEPT. It says "this session was started by a claudish
+ * owner", which is true of everything the session starts: a claudish run from its
+ * Bash tool refuses to nest (`assertNotNested`), and the claudish MCP server its
+ * plugins start registers no session tools. Deleting it here silently re-enables a
+ * claudish MCP session inside a claudish MCP session.
*/
export function scrubChildEnv(
env: Record<string, string | undefined>,
@@ -995,7 +1001,7 @@ export function scrubChildEnv(
if (opts.interactive) {
for (const key of STRIPPED_CHILD_VARS) delete env[key];
}
- for (const key of PANE_MARKER_VARS) delete env[key];
+ for (const key of PANE_LAUNCH_VARS) delete env[key];
}
/**
@@ -1008,10 +1014,11 @@ 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.
*
* (The OS *managed* tier can't be overridden — that case aborts before we get here.)
*/
diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts
index a986868b..e2d6f3fd 100644
--- a/packages/cli/src/config.ts
+++ b/packages/cli/src/config.ts
@@ -76,11 +76,17 @@ export const ENV = {
// is READ, never written, because it is the hard ceiling any in-request hold
// must land inside. See recovery/settings.ts's resolveTier1DeadlineMs.
API_TIMEOUT_MS: "API_TIMEOUT_MS",
- // Internal markers of an MCP pane child: the claudish an MCP `team` slot or
- // `create_session` starts inside a headless magmux pane. Set by the pane
- // launcher, consumed by `pane/child-env.ts`, deleted from Claude Code's
- // environment by claude-runner. Never set by a user.
- CLAUDISH_PANE_CHILD: "CLAUDISH_PANE_CHILD", // "1" in a pane child, nowhere else
+ // Internal markers set by the pane launcher on the claudish an MCP `team` slot,
+ // `create_session` or CLI `team --mode json` starts inside a headless magmux
+ // pane ("the pane child"), consumed by `pane/child-env.ts`. Never set by a user.
+ //
+ // CLAUDISH_PANE_CHILD is "1" inside ANY session a claudish owner started: the
+ // pane child, its Claude Code and everything that starts. claude-runner KEEPS
+ // it, and `inMcpSession()` reads it to hold nesting to one level.
+ // CLAUDISH_PANE_ENV and CLAUDISH_PANE_CWD are carried by the launched pane child
+ // only: claude-runner deletes them from Claude Code's environment
+ // (`PANE_LAUNCH_VARS`), which is how `isPaneChild()` tells the child apart.
+ CLAUDISH_PANE_CHILD: "CLAUDISH_PANE_CHILD", // "1" anywhere inside a claudish-started session
CLAUDISH_PANE_ENV: "CLAUDISH_PANE_ENV", // JSON snapshot of the MCP server's environment; re-applied, then deleted
CLAUDISH_PANE_CWD: "CLAUDISH_PANE_CWD", // realpath of the cwd the pane child must run in
// Where pane sockets, records and launcher dirs live (default /tmp/claudish-mux-<uid>).
diff --git a/packages/cli/src/force-login-method.test.ts b/packages/cli/src/force-login-method.test.ts
index f19e89b8..6fc6db7e 100644
--- a/packages/cli/src/force-login-method.test.ts
+++ b/packages/cli/src/force-login-method.test.ts
@@ -98,10 +98,19 @@ describe("buildClaudishSettingsOverlay", () => {
).toBe(false);
});
- 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
);
@@ -110,8 +119,10 @@ describe("buildClaudishSettingsOverlay", () => {
"skipDangerousModePermissionPrompt" in buildClaudishSettingsOverlay(statusLine, true)
).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;
}
});
});
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 64355d42..4da0e521 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -3,7 +3,11 @@
// FIRST import, on purpose: in an MCP pane child it restores the server's exact
// environment and cwd at import time — before `.env` loading and before any module
// below reads the environment while it is being evaluated. A no-op everywhere else.
-import { assertPaneChildInteractive, paneChildBootNotes } from "./pane/child-env.js";
+import {
+ assertNotNested,
+ assertPaneChildInteractive,
+ paneChildBootNotes,
+} from "./pane/child-env.js";
// Load .env file before anything else (quiet mode to suppress verbose output)
import { config } from "dotenv";
@@ -632,6 +636,12 @@ async function runCli() {
// --version/--models/--probe exit inside — the exit-hook fallback covers them)
const cliConfig = await traceSpan("startup:parse-args", () => parseArgs(process.argv.slice(2)));
+ // One level of nesting is the limit: a model-running claudish started from
+ // inside an MCP-started session (anything but the pane child itself: its
+ // Bash tool, a hook, a script) would be a second level, so it exits 64 here.
+ // The `team` subcommand is dispatched before runCli and guards itself.
+ assertNotNested();
+
// An MCP pane child must be an interactive REPL: a positional prompt, -p,
// --stdin or --team that slipped past the server's flag check exits 64 here,
// before any team dispatch or proxy start. A no-op outside a pane child.
diff --git a/packages/cli/src/launcher/magmux-wrapper.ts b/packages/cli/src/launcher/magmux-wrapper.ts
index 0fd67b60..7e986679 100644
--- a/packages/cli/src/launcher/magmux-wrapper.ts
+++ b/packages/cli/src/launcher/magmux-wrapper.ts
@@ -47,7 +47,7 @@ import {
} from "node:fs";
import { type Socket, connect as netConnect } from "node:net";
import { join } from "node:path";
-import { isPaneChild } from "../pane/child-env.js";
+import { inMcpSession } from "../pane/child-env.js";
import { findMagmuxBinaryOrNull } from "./magmux-binary.js";
/**
@@ -185,7 +185,11 @@ export function magmuxPaneCapability(
// re-POSTs. The recovery overlay would also paint over the screen the MCP
// server reads to classify the pane. What remains is tier 1's bounded hold
// (`TIER1_DEADLINE_MS`) and, with no lease, an inline 400 at exhaustion.
- if (isPaneChild(parentEnv)) return { kind: "none", reason: "pane-child" };
+ // The gate is `inMcpSession`, so it covers every process inside an MCP-started
+ // session, the pane child and anything it starts. Only the pane child reaches
+ // this in production (a nested launch is refused by `assertNotNested` first);
+ // the wider gate is kept for consistency with D22's reason, which holds for all.
+ if (inMcpSession(parentEnv)) return { kind: "none", reason: "pane-child" };
if (!input.interactive) return { kind: "none", reason: "not-interactive" };
// ALREADY INSIDE A MULTIPLEXER — do not nest one.
//
diff --git a/packages/cli/src/pane/child-env.test.ts b/packages/cli/src/pane/child-env.test.ts
index 8cb80844..ba216558 100644
--- a/packages/cli/src/pane/child-env.test.ts
+++ b/packages/cli/src/pane/child-env.test.ts
@@ -1,41 +1,67 @@
/**
* The pane child's bootstrap: the server's environment snapshot is applied exactly,
* the cwd is entered, and a configuration that is not an interactive REPL is refused
- * with exit 64. The pure functions are tested on passed objects; two subprocess tests
+ * with exit 64. The pure functions are tested on passed objects; subprocess tests
* prove the import-time side effect and the `index.ts` wiring, each with its own
* environment built from an allowlist (never `process.env`).
*/
import { afterAll, describe, expect, test } from "bun:test";
-import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join, resolve } from "node:path";
+import { dirname, join, resolve } from "node:path";
import {
+ NESTED_SESSION_REFUSAL,
PANE_CHILD_REFUSED_EXIT,
- PANE_MARKER_VARS,
+ PANE_LAUNCH_VARS,
applyPaneEnvSnapshot,
enterPaneCwd,
+ inMcpSession,
isPaneChild,
- isPaneShellManagedKey,
+ nestedLaunchRefusal,
paneChildRefusal,
} from "./child-env.js";
const scratch = realpathSync(mkdtempSync(join(tmpdir(), "claudish-child-env-")));
afterAll(() => rmSync(scratch, { recursive: true, force: true }));
-describe("isPaneChild", () => {
- test("only the exact marker value", () => {
- expect(isPaneChild({ CLAUDISH_PANE_CHILD: "1" })).toBe(true);
- expect(isPaneChild({ CLAUDISH_PANE_CHILD: "true" })).toBe(false);
- expect(isPaneChild({})).toBe(false);
+describe("MCP session and pane-child predicates", () => {
+ test("T-U-1: only the exact session flag counts", () => {
+ expect(inMcpSession({ CLAUDISH_PANE_CHILD: "1" })).toBe(true);
+ expect(inMcpSession({ CLAUDISH_PANE_CHILD: "true" })).toBe(false);
+ expect(inMcpSession({})).toBe(false);
});
- test("the marker set is the three CLAUDISH_PANE_* names", () => {
- expect([...PANE_MARKER_VARS]).toEqual([
- "CLAUDISH_PANE_CHILD",
- "CLAUDISH_PANE_ENV",
- "CLAUDISH_PANE_CWD",
- ]);
+ test("T-U-2: a session flag alone is not a pane child", () => {
+ expect(isPaneChild({ CLAUDISH_PANE_CHILD: "1" })).toBe(false);
+ });
+
+ test("T-U-3: a pane child needs both the exact flag and a non-empty cwd", () => {
+ expect(isPaneChild({ CLAUDISH_PANE_CHILD: "1", CLAUDISH_PANE_CWD: "/w" })).toBe(true);
+ expect(isPaneChild({ CLAUDISH_PANE_CWD: "/w" })).toBe(false);
+ expect(isPaneChild({ CLAUDISH_PANE_CHILD: "1", CLAUDISH_PANE_CWD: "" })).toBe(false);
+ expect(isPaneChild({ CLAUDISH_PANE_CHILD: "true", CLAUDISH_PANE_CWD: "/w" })).toBe(false);
+ });
+
+ test("T-U-4: launch variables exclude the inherited session flag", () => {
+ expect([...PANE_LAUNCH_VARS]).toEqual(["CLAUDISH_PANE_ENV", "CLAUDISH_PANE_CWD"]);
+ });
+
+ test("T-U-5: only a session descendant without a pane cwd is refused", () => {
+ expect(nestedLaunchRefusal({})).toBeNull();
+ expect(nestedLaunchRefusal({ CLAUDISH_PANE_CHILD: "1" })).toBe(NESTED_SESSION_REFUSAL);
+ expect(nestedLaunchRefusal({ CLAUDISH_PANE_CHILD: "1", CLAUDISH_PANE_CWD: "/w" })).toBeNull();
+ expect(nestedLaunchRefusal({ CLAUDISH_PANE_CHILD: "1", CLAUDISH_PANE_CWD: "" })).toBe(
+ NESTED_SESSION_REFUSAL
+ );
+ expect(nestedLaunchRefusal({ CLAUDISH_PANE_CHILD: "true" })).toBeNull();
+ });
+
+ test("T-U-6: the nested refusal text is exact", () => {
+ expect(PANE_CHILD_REFUSED_EXIT).toBe(64);
+ expect(NESTED_SESSION_REFUSAL).toBe(
+ "already inside a session started by the claudish MCP server; one level of nesting is the limit"
+ );
});
});
@@ -110,13 +136,18 @@ describe("applyPaneEnvSnapshot", () => {
});
}
- test("shell-managed keys are the measured set plus every MAGMUX_* key", () => {
- for (const k of ["COLUMNS", "LINES", "TERM", "SHLVL", "PWD", "OLDPWD", "_", "MAGMUX_X"]) {
- expect(isPaneShellManagedKey(k)).toBe(true);
- }
- for (const k of ["SHELL", "PATH", "HOME", "CLAUDE_CONFIG_DIR"]) {
- expect(isPaneShellManagedKey(k)).toBe(false);
- }
+ test("snapshot application preserves shell-managed keys and replaces other keys", () => {
+ const shellKeys = ["COLUMNS", "LINES", "TERM", "SHLVL", "PWD", "OLDPWD", "_", "MAGMUX_X"];
+ const replacedKeys = ["SHELL", "PATH", "HOME", "CLAUDE_CONFIG_DIR"];
+ const env: Record<string, string | undefined> = {
+ ...Object.fromEntries([...shellKeys, ...replacedKeys].map((key) => [key, "shell"])),
+ CLAUDISH_PANE_ENV: JSON.stringify(
+ Object.fromEntries(replacedKeys.map((key) => [key, "snapshot"]))
+ ),
+ };
+ expect(applyPaneEnvSnapshot(env)).toEqual({ ok: true });
+ for (const key of shellKeys) expect(env[key]).toBe("shell");
+ for (const key of replacedKeys) expect(env[key]).toBe("snapshot");
});
});
@@ -172,15 +203,21 @@ describe("paneChildRefusal", () => {
const cliDir = resolve(import.meta.dir, "../..");
const childEnvPath = resolve(import.meta.dir, "child-env.ts");
+// A regression must never find a real Claude Code, even if the old code passes the gate.
+const claudeShim = join(scratch, "claude-exits-73");
+writeFileSync(claudeShim, "#!/bin/sh\nexit 73\n", { mode: 0o755 });
/** An allowlisted environment with a scratch HOME — nothing from the real one. */
function hermeticEnv(extra: Record<string, string>): Record<string, string> {
const home = join(scratch, "home");
mkdirSync(home, { recursive: true });
return {
- PATH: process.env.PATH ?? "/usr/bin:/bin",
+ PATH: `${dirname(process.execPath)}:/usr/bin:/bin`,
+ CLAUDE_PATH: claudeShim,
+ CLAUDISH_PANE_ROOT: join(scratch, "panes"),
TMPDIR: tmpdir(),
HOME: home,
+ ZDOTDIR: home,
CLAUDE_CONFIG_DIR: join(home, ".claude"),
XDG_CONFIG_HOME: join(scratch, "xdg"),
CLAUDISH_DISABLE_KEYCHAIN: "1",
@@ -221,7 +258,14 @@ process.stdout.write(JSON.stringify({ cwd: process.cwd(), env: process.env }));`
test("a bad snapshot exits 64 with the refusal line", () => {
const r = Bun.spawnSync(
[process.execPath, "-e", `await import(${JSON.stringify(childEnvPath)});`],
- { cwd: scratch, env: hermeticEnv({ CLAUDISH_PANE_CHILD: "1", CLAUDISH_PANE_ENV: "{bad" }) }
+ {
+ cwd: scratch,
+ env: hermeticEnv({
+ CLAUDISH_PANE_CHILD: "1",
+ CLAUDISH_PANE_CWD: scratch,
+ CLAUDISH_PANE_ENV: "{bad",
+ }),
+ }
);
expect(r.exitCode).toBe(PANE_CHILD_REFUSED_EXIT);
expect(r.stderr.toString()).toBe("claudish: pane child refused: bad env snapshot\n");
@@ -245,15 +289,81 @@ describe("the CLI entry asserts an interactive REPL after parseArgs", () => {
["a team run", ["-i", "--team", "a,b"], "--team"],
["print mode", ["--model", "claude-sonnet-4-5", "-p", "hi"], "-p/--print"],
] as const) {
- test(`${name} exits 64`, () => {
+ test(`T-CLI-7: ${name} exits 64 with the pane-child refusal`, () => {
const r = Bun.spawnSync([process.execPath, "run", "src/index.ts", ...argv], {
cwd: cliDir,
- env: hermeticEnv({ CLAUDISH_PANE_CHILD: "1" }),
+ env: hermeticEnv({ CLAUDISH_PANE_CHILD: "1", CLAUDISH_PANE_CWD: scratch }),
timeout: 60_000,
});
expect(r.stderr.toString()).toContain("claudish: pane child refused: ");
expect(r.stderr.toString()).toContain(reason);
+ expect(r.stderr.toString()).not.toContain("nested session refused");
expect(r.exitCode).toBe(PANE_CHILD_REFUSED_EXIT);
}, 60_000);
}
});
+
+describe("nested CLI launches", () => {
+ for (const [id, name, argv] of [
+ ["T-CLI-1", "print mode", ["--model", "claude-sonnet-4-5", "-p", "hi"]],
+ ["T-CLI-2", "stdin mode", ["--stdin", "--model", "claude-sonnet-4-5"]],
+ ["T-CLI-3", "interactive mode", ["-i", "--model", "claude-sonnet-4-5"]],
+ ["T-CLI-4", "team run before argument validation", ["team", "run"]],
+ ] as const) {
+ test(`${id}: ${name} exits 64 with the exact nested refusal line`, () => {
+ const r = Bun.spawnSync([process.execPath, "run", "src/index.ts", ...argv], {
+ cwd: cliDir,
+ env: hermeticEnv({ CLAUDISH_PANE_CHILD: "1" }),
+ stdin: "ignore",
+ timeout: 60_000,
+ });
+ expect(r.exitCode).toBe(PANE_CHILD_REFUSED_EXIT);
+ expect(r.stderr.toString().split("\n")).toContain(
+ "claudish: nested session refused: already inside a session started by the claudish MCP server; one level of nesting is the limit"
+ );
+ expect(r.stderr.toString()).toEndWith("\n");
+ expect(r.stderr.toString()).not.toContain("pane child refused");
+ }, 60_000);
+ }
+
+ test("T-CLI-5: --version still succeeds inside an MCP session", () => {
+ const r = Bun.spawnSync([process.execPath, "run", "src/index.ts", "--version"], {
+ cwd: cliDir,
+ env: hermeticEnv({ CLAUDISH_PANE_CHILD: "1" }),
+ timeout: 60_000,
+ });
+ expect(r.exitCode).toBe(0);
+ expect(r.stdout.toString()).toMatch(/\b\d+\.\d+\.\d+\b/);
+ expect(r.stderr.toString()).not.toContain("refused");
+ }, 60_000);
+
+ test("T-CLI-6: team status is allowed with a path under its cwd", () => {
+ const statusPath = mkdtempSync(join(cliDir, ".nested-team-status-"));
+ try {
+ const r = Bun.spawnSync(
+ [process.execPath, "run", "src/index.ts", "team", "status", "--path", statusPath],
+ {
+ cwd: cliDir,
+ env: hermeticEnv({ CLAUDISH_PANE_CHILD: "1" }),
+ timeout: 60_000,
+ }
+ );
+ expect(r.stderr.toString()).not.toContain("nested session refused");
+ } finally {
+ rmSync(statusPath, { recursive: true, force: true });
+ }
+ }, 60_000);
+
+ test("T-CLI-8: importing child-env with only the session flag keeps cwd and the flag", () => {
+ const script = `await import(${JSON.stringify(childEnvPath)});
+process.stdout.write(JSON.stringify({ cwd: process.cwd(), flag: process.env.CLAUDISH_PANE_CHILD }));`;
+ const r = Bun.spawnSync([process.execPath, "-e", script], {
+ cwd: scratch,
+ env: hermeticEnv({ CLAUDISH_PANE_CHILD: "1" }),
+ timeout: 60_000,
+ });
+ expect(r.exitCode).toBe(0);
+ expect(r.stderr.toString()).toBe("");
+ expect(JSON.parse(r.stdout.toString())).toEqual({ cwd: scratch, flag: "1" });
+ }, 60_000);
+});
diff --git a/packages/cli/src/pane/child-env.ts b/packages/cli/src/pane/child-env.ts
index 05cbf951..e3de3648 100644
--- a/packages/cli/src/pane/child-env.ts
+++ b/packages/cli/src/pane/child-env.ts
@@ -1,7 +1,21 @@
/**
* Runs inside the claudish that an MCP `team` slot or `create_session` starts in a
- * headless magmux pane — "the pane child". Nothing here runs anywhere else: every
- * entry point returns at once unless `CLAUDISH_PANE_CHILD === "1"`.
+ * headless magmux pane — "the pane child" — and decides the one-level nesting rule
+ * for every claudish started below it.
+ *
+ * Two predicates, one flag:
+ *
+ * - `inMcpSession()`: `CLAUDISH_PANE_CHILD === "1"`. True for the pane child, its
+ * Claude Code and everything that Claude Code starts (Bash tool, hooks, plugin MCP
+ * servers): claude-runner keeps the flag in Claude Code's environment.
+ * - `isPaneChild()`: the flag AND a non-empty `CLAUDISH_PANE_CWD`. True only for the
+ * claudish the pane launcher started: claude-runner deletes `CLAUDISH_PANE_CWD`
+ * and `CLAUDISH_PANE_ENV` (`PANE_LAUNCH_VARS`) from Claude Code's environment.
+ *
+ * A process in a session that is not the pane child is one level deep already. It may
+ * not start another session: `assertNotNested` refuses a model-running launch, and the
+ * claudish MCP server registers only its one-shot tools (`mcp/nested-mode.ts`). This
+ * stops ACCIDENTAL recursion; it is not a containment boundary (`env -u` passes it).
*
* The pane child must run in EXACTLY the environment and working directory of the MCP
* server that started it (D16). Two things stand between them:
@@ -18,7 +32,7 @@
*
* This module is imported FIRST by the CLI entry (`index.ts`), before `.env` loading
* and before any module that reads the environment at import time. Its one side
- * effect is `bootstrapPaneChild()` at the bottom, which is a no-op without the marker.
+ * effect is `bootstrapPaneChild()` at the bottom, which is a no-op outside the pane child.
*
* After `parseArgs`, `assertPaneChildInteractive` refuses any flag combination that
* would make the pane child anything but an interactive Claude Code REPL. The server
@@ -36,14 +50,12 @@ import { ENV } from "../config.js";
export const PANE_CHILD_REFUSED_EXIT = 64;
/**
- * The internal markers. claude-runner deletes all three from Claude Code's
- * environment, so a claudish started from a slot's Bash tool is an ordinary launch.
+ * The markers that describe the LAUNCHED claudish only. claude-runner deletes them
+ * from Claude Code's environment. `CLAUDISH_PANE_CHILD` is deliberately not here: it
+ * is inherited by everything the session starts, so a claudish or a claudish MCP
+ * server started from inside it knows it is already one level deep.
*/
-export const PANE_MARKER_VARS = [
- ENV.CLAUDISH_PANE_CHILD,
- ENV.CLAUDISH_PANE_ENV,
- ENV.CLAUDISH_PANE_CWD,
-] as const;
+export const PANE_LAUNCH_VARS = [ENV.CLAUDISH_PANE_ENV, ENV.CLAUDISH_PANE_CWD] as const;
/**
* Keys owned by the pane's shell and terminal, not by the server's environment.
@@ -67,11 +79,47 @@ export function isPaneShellManagedKey(key: string): boolean {
type Env = Record<string, string | undefined>;
-/** Whether this process is a pane child. The one predicate every reader uses. */
-export function isPaneChild(env: Env = process.env): boolean {
+/**
+ * Whether this process runs inside a session a claudish owner started: the pane child
+ * itself, its Claude Code, and everything that Claude Code starts (tool shells,
+ * plugin MCP servers). Only the exact string "1" counts.
+ */
+export function inMcpSession(env: Env = process.env): boolean {
return env[ENV.CLAUDISH_PANE_CHILD] === "1";
}
+/**
+ * Whether this process IS the pane child: the claudish the pane launcher started.
+ * Only it still carries `CLAUDISH_PANE_CWD`, which claude-runner deletes from
+ * Claude Code's environment. An empty value counts as absent.
+ */
+export function isPaneChild(env: Env = process.env): boolean {
+ return inMcpSession(env) && Boolean(env[ENV.CLAUDISH_PANE_CWD]);
+}
+
+/** The reason in the nested refusal line. */
+export const NESTED_SESSION_REFUSAL =
+ "already inside a session started by the claudish MCP server; one level of nesting is the limit";
+
+/**
+ * Why this launch is a second level of nesting, or null when it is not. A claudish
+ * that runs a model from inside an MCP-started session (`claudish -p` from the
+ * session's Bash tool, an interactive claudish, a team run) would be a session inside
+ * a session. The pane child itself is the first level, never refused here.
+ */
+export function nestedLaunchRefusal(env: Env = process.env): string | null {
+ if (!inMcpSession(env) || isPaneChild(env)) return null;
+ return NESTED_SESSION_REFUSAL;
+}
+
+/** Exit 64 when this launch would nest a session inside an MCP-started session. */
+export function assertNotNested(env: Env = process.env): void {
+ const reason = nestedLaunchRefusal(env);
+ if (reason === null) return;
+ process.stderr.write(`claudish: nested session refused: ${reason}\n`);
+ process.exit(PANE_CHILD_REFUSED_EXIT);
+}
+
export type PaneBootResult = { ok: true; note?: string } | { ok: false; reason: string };
/**
@@ -187,7 +235,9 @@ let bootstrapped = false;
/**
* Restore the server's environment and cwd. Runs once, at import time from the CLI
- * entry; a no-op without the marker. Exits 64 on a bad snapshot or an unreachable cwd.
+ * entry; a no-op unless this process is the pane child (the flag AND
+ * `CLAUDISH_PANE_CWD`): a nested process carries neither launch variable, so it has
+ * nothing to restore. Exits 64 on a bad snapshot or an unreachable cwd.
*/
export function bootstrapPaneChild(env: Env = process.env): void {
if (bootstrapped || !isPaneChild(env)) return;
diff --git a/packages/cli/src/pane/pane-child-real-claudish.integration.test.ts b/packages/cli/src/pane/pane-child-real-claudish.integration.test.ts
index 9a598f42..5b498124 100644
--- a/packages/cli/src/pane/pane-child-real-claudish.integration.test.ts
+++ b/packages/cli/src/pane/pane-child-real-claudish.integration.test.ts
@@ -84,7 +84,7 @@ async function run(callerFlags: string[] = []) {
describe.skipIf(!MAGMUX)(
`the real pane child claudish (${MAGMUX ? "" : NO_MAGMUX_MESSAGE})`,
() => {
- test("snapshot and cwd restored; overlay key; markers, child-session and watchdog stripped; answered", async () => {
+ test("T-INT-1: snapshot and cwd restored; session flag kept; launch variables and child-session stripped; answered", async () => {
const { t, snap, dump, tokenFile, left } = await run();
expect(snap.state).toBe("COMPLETED");
expect(left).toEqual({ processes: [], files: [] });
@@ -100,12 +100,8 @@ describe.skipIf(!MAGMUX)(
expect(d.env.PANE_TEST_CANARY).toBe("kept");
expect(d.env.CLAUDE_CONFIG_DIR).toBe(t.configDir);
expect(d.cwd.endsWith("/cwd")).toBe(true);
- for (const k of [
- "CLAUDISH_PANE_CHILD",
- "CLAUDISH_PANE_ENV",
- "CLAUDISH_PANE_CWD",
- "CLAUDE_CODE_CHILD_SESSION",
- ])
+ expect(d.env.CLAUDISH_PANE_CHILD).toBe("1");
+ for (const k of ["CLAUDISH_PANE_ENV", "CLAUDISH_PANE_CWD", "CLAUDE_CODE_CHILD_SESSION"])
expect(d.env[k]).toBeUndefined();
expect(d.env.CLAUDE_CODE_RETRY_WATCHDOG).toBeUndefined();
expect(typeof d.settings === "object" && d.settings !== null).toBe(true);
diff --git a/packages/cli/src/recovery/settings.test.ts b/packages/cli/src/recovery/settings.test.ts
index 8d373d89..25da7b26 100644
--- a/packages/cli/src/recovery/settings.test.ts
+++ b/packages/cli/src/recovery/settings.test.ts
@@ -344,6 +344,21 @@ describe("an MCP pane child is never eligible for a recovery surface (D22)", ()
).toEqual({ kind: "none", reason: "pane-child" });
});
+ test("T-U-9: flag and pane cwd disable recovery before the ambient branch", () => {
+ expect(
+ magmuxPaneCapability({
+ interactive: true,
+ stdoutIsTty: true,
+ parentEnv: {
+ CLAUDISH_PANE_CHILD: "1",
+ CLAUDISH_PANE_CWD: "/w",
+ MAGMUX_SOCK: "/tmp/x.sock",
+ },
+ magmuxBinary: "/opt/magmux",
+ })
+ ).toEqual({ kind: "none", reason: "pane-child" });
+ });
+
test("the same environment without the marker is still ambient", () => {
expect(
magmuxPaneCapability({
diff --git a/packages/cli/src/team-cli.ts b/packages/cli/src/team-cli.ts
index 74303447..732b8dc3 100644
--- a/packages/cli/src/team-cli.ts
+++ b/packages/cli/src/team-cli.ts
@@ -1,5 +1,6 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
+import { assertNotNested } from "./pane/child-env.js";
import { installPaneShutdownHooks } from "./pane/index.js";
import {
type TeamRunOptions,
@@ -117,6 +118,11 @@ export async function teamCommand(args: string[]): Promise<void> {
const legacySubs = ["run", "judge", "run-and-judge", "status"];
const subcommand = legacySubs.includes(firstArg) ? firstArg : "run";
+ // run, judge and run-and-judge start models; inside an MCP-started session that
+ // is a second level of nesting (exit 64). Checked before any argument validation.
+ // `status` only reads a session directory, so it stays usable.
+ if (subcommand !== "status") assertNotNested();
+
const rawSessionPath = getFlag(args, "--path") ?? ".";
let sessionPath: string;
try {
diff --git a/scripts/guard-real-config.ts b/scripts/guard-real-config.ts
index 2c8410a2..4bcd5783 100644
--- a/scripts/guard-real-config.ts
+++ b/scripts/guard-real-config.ts
@@ -228,15 +228,22 @@ for (const g of GUARDED) {
// whose home directory never holds the file, stayed green. A fresh directory
// per run means no run can read a sentinel an earlier run wrote either.
const sentinelDir = mkdtempSync(join(tmpdir(), "claudish-guard-sentinel-"));
+const childEnv: Record<string, string | undefined> = {
+ ...process.env,
+ CLAUDISH_DISABLE_KEYCHAIN: "1",
+ CLAUDISH_DISABLE_OP: "1",
+ CLAUDISH_DISABLE_CATALOG_WARM: "1",
+ CLAUDISH_CATALOG_INCOMPATIBLE_PATH: join(sentinelDir, "catalog-incompatible.json"),
+};
+// `CLAUDISH_PANE_CHILD` reaches everything a claudish-started session runs, a test
+// run included (a runner is often such a session). Inherited, it puts every
+// claudish child and MCP server the suite spawns with `...process.env` into nested
+// mode (four tools, model launches refused with exit 64). The tests drop it
+// themselves; this is the second layer.
+delete childEnv.CLAUDISH_PANE_CHILD;
const child = spawn(cmd[0], cmd.slice(1), {
stdio: "inherit",
- env: {
- ...process.env,
- CLAUDISH_DISABLE_KEYCHAIN: "1",
- CLAUDISH_DISABLE_OP: "1",
- CLAUDISH_DISABLE_CATALOG_WARM: "1",
- CLAUDISH_CATALOG_INCOMPATIBLE_PATH: join(sentinelDir, "catalog-incompatible.json"),
- },
+ env: childEnv,
});
/** Report one file's mutation, put the original bytes back, and explain the fix. */