Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(mcp): apply the CLAUDISH_PANE_ENV snapshot in a pane child claudish
Jack Rudenkoaa9c5a22ba2e
diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.tsindex dba1a128..8d1fc0a7 100644--- a/packages/cli/src/config.ts+++ b/packages/cli/src/config.ts@@ -72,6 +72,13 @@ 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+ 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} as const;// OpenRouter API Configurationdiff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 86109d9e..232fadbf 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -1,5 +1,10 @@#!/usr/bin/env bun+// 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";+// Load .env file before anything else (quiet mode to suppress verbose output)import { config } from "dotenv";config({ quiet: true }); // Loads .env from current working directory@@ -590,7 +595,7 @@ async function runCli() {getMissingKeyResolutions,getMissingKeysError,} = await import("./providers/provider-resolver.js");- const { initLogger, getLogFilePath, getAlwaysOnLogPath, setDiagOutput } = await import(+ const { initLogger, getLogFilePath, getAlwaysOnLogPath, setDiagOutput, log } = await import("./logger.js");const { createDiagOutput } = await import("./diag-output.js");@@ -627,6 +632,11 @@ 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)));+ // 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.+ assertPaneChildInteractive(cliConfig);+// Register the bundled endpoint catalog before ANYTHING enumerates or// validates providers. Two consumers below need it and both run long before// the proxy (which has always registered endpoints for the request path):@@ -784,6 +794,7 @@ async function runCli() {// Initialize logger: always-on structural logging + optional debug logginginitLogger(cliConfig.debug, cliConfig.logLevel, cliConfig.noLogs);+ for (const note of paneChildBootNotes()) log(note);// Initialize telemetry (reads consent, generates session_id)// Must come after parseArgs() so cliConfig.interactive is knowndiff --git a/packages/cli/src/pane/child-env.test.ts b/packages/cli/src/pane/child-env.test.tsnew file mode 100644index 00000000..8cb80844--- /dev/null+++ b/packages/cli/src/pane/child-env.test.ts@@ -0,0 +1,259 @@+/**+ * 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+ * 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 { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import {+ PANE_CHILD_REFUSED_EXIT,+ PANE_MARKER_VARS,+ applyPaneEnvSnapshot,+ enterPaneCwd,+ isPaneChild,+ isPaneShellManagedKey,+ 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);+ });++ test("the marker set is the three CLAUDISH_PANE_* names", () => {+ expect([...PANE_MARKER_VARS]).toEqual([+ "CLAUDISH_PANE_CHILD",+ "CLAUDISH_PANE_ENV",+ "CLAUDISH_PANE_CWD",+ ]);+ });+});++describe("applyPaneEnvSnapshot", () => {+ test("sets snapshot keys, removes extras, keeps shell-managed keys, deletes the snapshot", () => {+ const env: Record<string, string | undefined> = {+ CLAUDISH_PANE_CHILD: "1",+ CLAUDISH_PANE_CWD: "/w",+ OPENAI_API_KEY: "from-profile",+ PROFILE_ONLY: "x",+ SHELL: "/tmp/launch-abc/sh-shim",+ TERM: "xterm-256color",+ COLUMNS: "160",+ LINES: "50",+ SHLVL: "2",+ PWD: "/",+ OLDPWD: "/x",+ _: "/usr/bin/env",+ MAGMUX_SOCK: "/tmp/m.sock",+ CLAUDISH_PANE_ENV: JSON.stringify({+ CLAUDISH_PANE_CHILD: "1",+ CLAUDISH_PANE_CWD: "/w",+ OPENAI_API_KEY: "from-server",+ SHELL: "/bin/zsh",+ CLAUDE_CONFIG_DIR: "/cfg",+ }),+ };+ expect(applyPaneEnvSnapshot(env)).toEqual({ ok: true });+ expect(env).toEqual({+ CLAUDISH_PANE_CHILD: "1",+ CLAUDISH_PANE_CWD: "/w",+ OPENAI_API_KEY: "from-server",+ SHELL: "/bin/zsh",+ CLAUDE_CONFIG_DIR: "/cfg",+ TERM: "xterm-256color",+ COLUMNS: "160",+ LINES: "50",+ SHLVL: "2",+ PWD: "/",+ OLDPWD: "/x",+ _: "/usr/bin/env",+ MAGMUX_SOCK: "/tmp/m.sock",+ });+ });++ test("a snapshot that lacks the markers does not remove them", () => {+ const env: Record<string, string | undefined> = {+ CLAUDISH_PANE_CHILD: "1",+ CLAUDISH_PANE_CWD: "/w",+ CLAUDISH_PANE_ENV: JSON.stringify({ A: "1" }),+ };+ applyPaneEnvSnapshot(env);+ expect(env).toEqual({ CLAUDISH_PANE_CHILD: "1", CLAUDISH_PANE_CWD: "/w", A: "1" });+ });++ test("no snapshot leaves the environment alone", () => {+ const env = { CLAUDISH_PANE_CHILD: "1", KEEP: "me" };+ expect(applyPaneEnvSnapshot(env)).toEqual({ ok: true });+ expect(env).toEqual({ CLAUDISH_PANE_CHILD: "1", KEEP: "me" });+ });++ for (const [name, raw] of [+ ["not JSON", "{nope"],+ ["an array", "[]"],+ ["null", "null"],+ ["a non-string value", JSON.stringify({ A: 1 })],+ ] as const) {+ test(`refuses ${name} without changing anything`, () => {+ const env = { CLAUDISH_PANE_CHILD: "1", CLAUDISH_PANE_ENV: raw, KEEP: "me" };+ expect(applyPaneEnvSnapshot(env)).toEqual({ ok: false, reason: "bad env snapshot" });+ expect(env.KEEP).toBe("me");+ });+ }++ 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);+ }+ });+});++describe("enterPaneCwd", () => {+ const ops = (here: string, chdirs: string[], fail = false) => ({+ cwd: () => here,+ realpath: (p: string) => p,+ chdir: (p: string) => {+ if (fail) throw new Error("ENOENT");+ chdirs.push(p);+ },+ });++ test("changes directory when the realpath differs, and says so", () => {+ const chdirs: string[] = [];+ const result = enterPaneCwd({ CLAUDISH_PANE_CWD: "/work" }, ops("/", chdirs));+ expect(chdirs).toEqual(["/work"]);+ expect(result).toEqual({ ok: true, note: "[pane-child] cwd / -> /work" });+ });++ test("does nothing when already there or when no cwd is named", () => {+ const chdirs: string[] = [];+ expect(enterPaneCwd({ CLAUDISH_PANE_CWD: "/work" }, ops("/work", chdirs))).toEqual({+ ok: true,+ });+ expect(enterPaneCwd({}, ops("/", chdirs))).toEqual({ ok: true });+ expect(chdirs).toEqual([]);+ });++ test("an unreachable cwd is a refusal", () => {+ const result = enterPaneCwd({ CLAUDISH_PANE_CWD: "/gone" }, ops("/", [], true));+ expect(result).toEqual({ ok: false, reason: "cannot enter /gone: ENOENT" });+ });+});++describe("paneChildRefusal", () => {+ test("an interactive REPL passes", () => {+ expect(paneChildRefusal({ interactive: true })).toBeNull();+ });++ test("each non-REPL shape names its reason", () => {+ expect(paneChildRefusal({ interactive: true, team: ["a", "b"] })).toContain("--team");+ expect(paneChildRefusal({ interactive: false, _hasPrintFlag: true })).toContain("-p/--print");+ expect(paneChildRefusal({ interactive: false, stdin: true })).toContain("--stdin");+ expect(paneChildRefusal({ interactive: false, _hasPositionalPrompt: true })).toContain(+ "positional prompt"+ );+ expect(paneChildRefusal({ interactive: false })).toBe("the child is not interactive");+ });+});++// ── Subprocesses ─────────────────────────────────────────────────────────────++const cliDir = resolve(import.meta.dir, "../..");+const childEnvPath = resolve(import.meta.dir, "child-env.ts");++/** 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",+ TMPDIR: tmpdir(),+ HOME: home,+ CLAUDE_CONFIG_DIR: join(home, ".claude"),+ XDG_CONFIG_HOME: join(scratch, "xdg"),+ CLAUDISH_DISABLE_KEYCHAIN: "1",+ CLAUDISH_DISABLE_OP: "1",+ CLAUDISH_DISABLE_CATALOG_WARM: "1",+ CLAUDISH_NO_PREDEFINED_ENDPOINTS: "1",+ ...extra,+ };+}++describe("the import-time bootstrap", () => {+ test("applies the snapshot and enters the cwd before anything else runs", () => {+ const work = join(scratch, "work dir_1");+ mkdirSync(work, { recursive: true });+ const script = `await import(${JSON.stringify(childEnvPath)});+process.stdout.write(JSON.stringify({ cwd: process.cwd(), env: process.env }));`;+ const env = hermeticEnv({+ CLAUDISH_PANE_CHILD: "1",+ CLAUDISH_PANE_CWD: work,+ INHERITED_ONLY: "drop me",+ });+ env.CLAUDISH_PANE_ENV = JSON.stringify({+ ...env,+ FROM_SERVER: "yes",+ INHERITED_ONLY: undefined,+ });+ const r = Bun.spawnSync([process.execPath, "-e", script], { cwd: scratch, env });+ expect(r.stderr.toString()).toBe("");+ expect(r.exitCode).toBe(0);+ const out = JSON.parse(r.stdout.toString()) as { cwd: string; env: Record<string, string> };+ expect(out.cwd).toBe(work);+ expect(out.env.FROM_SERVER).toBe("yes");+ expect(out.env.INHERITED_ONLY).toBeUndefined();+ expect(out.env.CLAUDISH_PANE_ENV).toBeUndefined();+ expect(out.env.CLAUDISH_PANE_CHILD).toBe("1");+ });++ 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" }) }+ );+ expect(r.exitCode).toBe(PANE_CHILD_REFUSED_EXIT);+ expect(r.stderr.toString()).toBe("claudish: pane child refused: bad env snapshot\n");+ });++ test("without the marker the snapshot is ignored", () => {+ const script = `await import(${JSON.stringify(childEnvPath)});+process.stdout.write(process.env.CLAUDISH_PANE_ENV ?? "gone");`;+ const r = Bun.spawnSync([process.execPath, "-e", script], {+ cwd: scratch,+ env: hermeticEnv({ CLAUDISH_PANE_ENV: "{bad" }),+ });+ expect(r.exitCode).toBe(0);+ expect(r.stdout.toString()).toBe("{bad");+ });+});++describe("the CLI entry asserts an interactive REPL after parseArgs", () => {+ for (const [name, argv, reason] of [+ ["a positional prompt", ["-i", "--model", "claude-sonnet-4-5", "hello"], "positional prompt"],+ ["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`, () => {+ const r = Bun.spawnSync([process.execPath, "run", "src/index.ts", ...argv], {+ cwd: cliDir,+ env: hermeticEnv({ CLAUDISH_PANE_CHILD: "1" }),+ timeout: 60_000,+ });+ expect(r.stderr.toString()).toContain("claudish: pane child refused: ");+ expect(r.stderr.toString()).toContain(reason);+ expect(r.exitCode).toBe(PANE_CHILD_REFUSED_EXIT);+ }, 60_000);+ }+});diff --git a/packages/cli/src/pane/child-env.ts b/packages/cli/src/pane/child-env.tsnew file mode 100644index 00000000..05cbf951--- /dev/null+++ b/packages/cli/src/pane/child-env.ts@@ -0,0 +1,212 @@+/**+ * 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"`.+ *+ * 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:+ *+ * - magmux starts the pane through `$SHELL -l -c`, so a login profile could re-export+ * `OPENAI_API_KEY`, `CLAUDE_CONFIG_DIR`, `PATH`, or `cd` somewhere else. The server+ * therefore passes a JSON snapshot of its environment as `CLAUDISH_PANE_ENV`+ * (inherited, never written to disk), and `applyPaneEnvSnapshot` re-applies it+ * here: every snapshot key is set, every key the snapshot lacks is removed, except+ * the shell-managed set below, which the pane's own shell and terminal own.+ * - the cwd: `CLAUDISH_PANE_CWD` is the realpath the server spawned in, and Claude+ * Code derives the transcript directory from the cwd, so a profile `cd` would move+ * the transcript out of the place the server reads it from.+ *+ * 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.+ *+ * After `parseArgs`, `assertPaneChildInteractive` refuses any flag combination that+ * would make the pane child anything but an interactive Claude Code REPL. The server+ * checks `claude_flags` first; this is the defence in depth for a token its walker+ * mis-classifies (architecture §2.3 rule 3).+ *+ * Every refusal prints `claudish: pane child refused: <reason>` and exits 64, which the+ * server reports as FAILED `child_exited` with that line.+ */++import { realpathSync } from "node:fs";+import { ENV } from "../config.js";++/** Exit status of a refused pane child (EX_USAGE). */+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.+ */+export const PANE_MARKER_VARS = [+ ENV.CLAUDISH_PANE_CHILD,+ 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.+ * Excluded from the snapshot when it is built and kept when it is applied. Every+ * `MAGMUX_*` key belongs here too: `MAGMUX_SOCK`, injected by magmux into the pane,+ * is what tells the child it is already inside a multiplexer.+ */+export const PANE_SHELL_MANAGED_KEYS = [+ "COLUMNS",+ "LINES",+ "TERM",+ "SHLVL",+ "PWD",+ "OLDPWD",+ "_",+] as const;++export function isPaneShellManagedKey(key: string): boolean {+ return key.startsWith("MAGMUX_") || (PANE_SHELL_MANAGED_KEYS as readonly string[]).includes(key);+}++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 {+ return env[ENV.CLAUDISH_PANE_CHILD] === "1";+}++export type PaneBootResult = { ok: true; note?: string } | { ok: false; reason: string };++/**+ * Re-apply the server's environment snapshot onto `env`, in place.+ *+ * Set every snapshot key; delete every key the snapshot lacks, except the shell-managed+ * set and the pane markers (a snapshot missing the marker must not turn the child back+ * into an ordinary launch); delete `CLAUDISH_PANE_ENV`. No snapshot is not an error:+ * the child then runs with what it inherited.+ */+export function applyPaneEnvSnapshot(env: Env): PaneBootResult {+ const raw = env[ENV.CLAUDISH_PANE_ENV];+ if (raw === undefined) return { ok: true };+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return { ok: false, reason: "bad env snapshot" };+ }+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {+ return { ok: false, reason: "bad env snapshot" };+ }+ const snapshot = parsed as Record<string, unknown>;+ for (const value of Object.values(snapshot)) {+ if (typeof value !== "string") return { ok: false, reason: "bad env snapshot" };+ }+ const keep = new Set<string>([ENV.CLAUDISH_PANE_CHILD, ENV.CLAUDISH_PANE_CWD]);+ for (const key of Object.keys(env)) {+ if (Object.hasOwn(snapshot, key) || keep.has(key) || isPaneShellManagedKey(key)) continue;+ delete env[key];+ }+ for (const [key, value] of Object.entries(snapshot as Record<string, string>)) {+ env[key] = value;+ }+ delete env[ENV.CLAUDISH_PANE_ENV];+ return { ok: true };+}++export interface CwdOps {+ cwd: () => string;+ realpath: (path: string) => string;+ chdir: (path: string) => void;+}++const processCwdOps: CwdOps = {+ cwd: () => process.cwd(),+ realpath: (path) => realpathSync(path),+ chdir: (path) => process.chdir(path),+};++/**+ * Move into `CLAUDISH_PANE_CWD` when the process is not already there. A failed+ * `chdir` is a refusal: the transcript would land in a directory the server does not+ * read, and the slot would look like it never answered.+ */+export function enterPaneCwd(env: Env, ops: CwdOps = processCwdOps): PaneBootResult {+ const target = env[ENV.CLAUDISH_PANE_CWD];+ if (!target) return { ok: true };+ let here: string | null;+ try {+ here = ops.realpath(ops.cwd());+ } catch {+ here = null;+ }+ if (here === target) return { ok: true };+ try {+ ops.chdir(target);+ } catch (e) {+ const why = e instanceof Error ? e.message : String(e);+ return { ok: false, reason: `cannot enter ${target}: ${why}` };+ }+ return { ok: true, note: `[pane-child] cwd ${here ?? "(unresolvable)"} -> ${target}` };+}++/** The `parseArgs` fields the interactive assertion reads. */+export interface PaneChildConfigView {+ interactive?: boolean;+ team?: string[];+ stdin?: boolean;+ _hasPositionalPrompt?: boolean;+ _hasPrintFlag?: boolean;+}++/**+ * Why this parsed configuration cannot run as a pane child, or null when it can.+ * A pane child is an interactive REPL, never a team run, never print mode, and never+ * has a positional prompt (the prompt is typed into the REPL by the server).+ */+export function paneChildRefusal(config: PaneChildConfigView): string | null {+ if (config.team !== undefined) return "--team would start a team run instead of a REPL";+ if (config._hasPrintFlag) return "-p/--print would start print mode instead of a REPL";+ if (config.stdin) return "--stdin would start print mode instead of a REPL";+ if (config._hasPositionalPrompt) {+ return "a positional prompt reached the child; claudish takes one value per flag: write `--allowedTools Read,Bash`";+ }+ if (!config.interactive) return "the child is not interactive";+ return null;+}++function refuse(reason: string): never {+ process.stderr.write(`claudish: pane child refused: ${reason}\n`);+ process.exit(PANE_CHILD_REFUSED_EXIT);+}++/** Notes recorded before the logger exists; `logPaneChildBootNotes` flushes them. */+const bootNotes: string[] = [];++export function paneChildBootNotes(): readonly string[] {+ return bootNotes;+}++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.+ */+export function bootstrapPaneChild(env: Env = process.env): void {+ if (bootstrapped || !isPaneChild(env)) return;+ bootstrapped = true;+ const snapshot = applyPaneEnvSnapshot(env);+ if (!snapshot.ok) refuse(snapshot.reason);+ const cwd = enterPaneCwd(env);+ if (!cwd.ok) refuse(cwd.reason);+ if (cwd.note) bootNotes.push(cwd.note);+}++/** Exit 64 unless the parsed configuration is an interactive REPL (§2.3 rule 3). */+export function assertPaneChildInteractive(+ config: PaneChildConfigView,+ env: Env = process.env+): void {+ if (!isPaneChild(env)) return;+ const reason = paneChildRefusal(config);+ if (reason !== null) refuse(reason);+}++bootstrapPaneChild();