Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(mcp): add pane launch: env snapshot, sh shim, launcher, flag check
Jack Rudenko1789253a9efb
diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.tsindex 8d1fc0a7..17394dab 100644--- a/packages/cli/src/config.ts+++ b/packages/cli/src/config.ts@@ -79,6 +79,10 @@ export const ENV = {CLAUDISH_PANE_CHILD: "CLAUDISH_PANE_CHILD", // "1" in a pane child, nowhere elseCLAUDISH_PANE_ENV: "CLAUDISH_PANE_ENV", // JSON snapshot of the MCP server's environment; re-applied, then deletedCLAUDISH_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>).+ // A location, like CLAUDISH_SESSIONS_DIR: test suites that start a real MCP server point+ // it at their own root so the startup sweep and the pane limit stay inside the test.+ CLAUDISH_PANE_ROOT: "CLAUDISH_PANE_ROOT",} as const;// OpenRouter API Configurationdiff --git a/packages/cli/src/pane/child-flags.test.ts b/packages/cli/src/pane/child-flags.test.tsnew file mode 100644index 00000000..e1a9e18c--- /dev/null+++ b/packages/cli/src/pane/child-flags.test.ts@@ -0,0 +1,111 @@+import { describe, expect, test } from "bun:test";+import { classifyPassthroughTokens } from "../cli.js";+import {+ PRINT_ONLY_FLAGS,+ SUBCOMMAND_WORDS,+ checkChildFlags,+ flagsRemoveRead,+} from "./pane-launch.js";++function refused(flags: string[]): string {+ const r = checkChildFlags(flags);+ if (r.ok) throw new Error(`expected a refusal for ${JSON.stringify(flags)}`);+ return r.message;+}++describe("checkChildFlags — reserved tokens (D18)", () => {+ const RESERVED: string[][] = [+ ["-i"],+ ["--model", "x"],+ ["-m", "x"],+ ["-y"],+ ["--auto-approve"],+ ["--no-auto-approve"],+ ["--quiet"],+ ["--session-id", "u"],+ ["-p"],+ ["--print"],+ ["--stdin"],+ ["--output-format", "json"],+ ["--output-format=json"],+ ["--input-format", "stream-json"],+ ["--bg"],+ ["--background"],+ ["--resume", "abc"],+ ["--continue"],+ ["--from-pr", "1"],+ ["--teleport"],+ ["--fork-session"],+ ["-w"],+ ["--worktree", "x"],+ ["--no-session-persistence"],+ ["--team", "a,b"],+ ["--file", "x"],+ ["--probe", "m"],+ ["--monitor"],+ ["--advisor", "m"],+ ["--version"],+ ["--help"],+ ["-h"],+ ];+ test("every reserved token is refused", () => {+ for (const flags of RESERVED) expect(checkChildFlags(flags).ok).toBe(false);+ });++ test("--no-auto-approve is reserved: it defeats -y (phase-2 s09); --permission-mode default is not", () => {+ expect(refused(["--no-auto-approve"])).toContain("set by claudish itself");+ expect(checkChildFlags(["--permission-mode", "default"]).ok).toBe(true);+ expect(checkChildFlags(["--permission-mode", "plan"]).ok).toBe(true);+ });++ test("print-only flags are refused naming the loss", () => {+ for (const f of PRINT_ONLY_FLAGS)+ expect(refused([f, "3"])).toBe(+ `${f} works only with --print; team slots and sessions are interactive panes, so it would be silently ignored`+ );+ });++ test("allowed: --add-dir, --agent, --allowedTools with one comma value, -v", () => {+ expect(+ checkChildFlags(["--add-dir", "/x", "--agent", "rev", "--allowedTools", "Read,Bash", "-v"]).ok+ ).toBe(true);+ });+});++describe("checkChildFlags — positionals and subcommand words", () => {+ test("two values for one flag would become a -p prompt: refused with the hint", () => {+ expect(refused(["--allowedTools", "Read", "Bash"])).toContain(+ "write `--allowedTools Read,Bash`"+ );+ });++ test("a -- separator is refused", () => {+ expect(refused(["--", "--effort", "high"])).toContain("`--`");+ });++ test("a subcommand word as a flag value would dispatch that subcommand", () => {+ for (const w of SUBCOMMAND_WORDS) expect(refused(["--agent", w])).toContain("subcommand");+ });++ test("the walker the check uses agrees with classifyPassthroughTokens", () => {+ for (const flags of [+ ["--agent", "x"],+ ["--allowedTools", "Read", "Bash"],+ ["-v", "--settings", "/s.json"],+ ]) {+ const c = classifyPassthroughTokens(flags);+ expect(checkChildFlags(flags).ok).toBe(c.positionals.length === 0 && c.separatorAt === null);+ }+ });+});++describe("flagsRemoveRead (§2.3 rule 4)", () => {+ test("--disallowedTools containing Read, or a --tools list without it", () => {+ expect(flagsRemoveRead(["--disallowedTools", "Bash,Read"])).toBe(true);+ expect(flagsRemoveRead(["--disallowedTools=Read"])).toBe(true);+ expect(flagsRemoveRead(["--tools", "Bash,Edit"])).toBe(true);+ expect(flagsRemoveRead(["--tools", "Read,Bash"])).toBe(false);+ expect(flagsRemoveRead(["--disallowedTools", "ReadMcpResource"])).toBe(false);+ expect(flagsRemoveRead([])).toBe(false);+ });+});diff --git a/packages/cli/src/pane/pane-launch.test.ts b/packages/cli/src/pane/pane-launch.test.tsnew file mode 100644index 00000000..67db6b97--- /dev/null+++ b/packages/cli/src/pane/pane-launch.test.ts@@ -0,0 +1,268 @@+import { afterEach, describe, expect, test } from "bun:test";+import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import {+ HOST_IDENTITY_VARS,+ LINUX_ENV_STRING_LIMIT,+ OWNER_START36,+ PaneEnvTooLargeError,+ PaneRootError,+ SHELL_SHIM,+ buildClaudishPaneArgv,+ buildPaneEnv,+ ensureSockRoot,+ isValidPaneId,+ launcherScript,+ mintPaneId,+ paneCommand,+ sockPathFor,+ sockRootFor,+ versionAtLeast,+} from "./pane-launch.js";+import { WATCHER_ARGV0, WATCHER_SCRIPT, watcherArgv } from "./process-identity.js";++const dirs: string[] = [];+afterEach(() => {+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });+});++function tmp(): string {+ const d = mkdtempSync(join(tmpdir(), "pl-"));+ dirs.push(d);+ return d;+}++describe("launcher and shim", () => {+ test("the launcher cds to the realpath cwd, then execs claudish; no watcher, no PATH line", () => {+ const s = launcherScript(+ "/tmp/a b/it's",+ { command: "/opt/bun", prefixArgs: ["run", "/x/index.ts"] },+ ["-i", "--model", "fake-answer"]+ );+ expect(s).toBe(+ `cd -- '/tmp/a b/it'\\''s' || exit 97\nexec '/opt/bun' 'run' '/x/index.ts' '-i' '--model' 'fake-answer'\n`+ );+ expect(s).not.toContain("PATH");+ expect(s).not.toContain("watcher");+ });++ test("the shim drops -l and execs /bin/sh, so no login profile runs", () => {+ expect(SHELL_SHIM).toBe('#!/bin/sh\n[ "$1" = -l ] && shift\nexec /bin/sh "$@"\n');+ });++ test("the -e value never names claude (magmux's controller would attach)", () => {+ expect(paneCommand("/tmp/claudish-mux-501/launch-AbC123")).toBe(+ ". '/tmp/claudish-mux-501/launch-AbC123/pane-launch.sh'"+ );+ expect(() => paneCommand("/tmp/claude ")).toThrow();+ });++ test("argv is -i --model X -y --quiet --session-id U --add-dir D, then the caller flags", () => {+ expect(buildClaudishPaneArgv("m", "u", "/d", ["--agent", "x"])).toEqual([+ "-i",+ "--model",+ "m",+ "-y",+ "--quiet",+ "--session-id",+ "u",+ "--add-dir",+ "/d",+ "--agent",+ "x",+ ]);+ });+});++describe("pane environment", () => {+ const parentEnv = {+ PATH: "/usr/bin",+ HOME: "/h",+ SHELL: "/bin/zsh",+ OPENAI_API_KEY: "k",+ CLAUDECODE: "1",+ CLAUDE_CODE_CHILD_SESSION: "1",+ MAGMUX_SOCK: "/tmp/outer.sock",+ MAGMUX_SOCK_DIR: "/tmp/outer",+ TMUX: "/tmp/tmux-501/default,1,0",+ TERM_PROGRAM: "iTerm.app",+ ITERM_SESSION_ID: "w0",+ VSCODE_PID: "1",+ COLUMNS: "80",+ LINES: "24",+ TERM: "xterm",+ SHLVL: "2",+ PWD: "/elsewhere",+ CLAUDISH_LAUNCHER_PID: "10",+ CLAUDISH_LAUNCHER_PPID: "9",+ CLAUDE_CODE_SESSION_ID: "host-session",+ };++ test("strips child, magmux, terminal-identity and host-identity keys; sets geometry and markers", () => {+ const { magmuxEnv } = buildPaneEnv({+ parentEnv,+ slotEnv: { CLAUDISH_TOKEN_FILE: "/t.json" },+ cwd: "/real/cwd",+ ctlDir: "/root/launch-AAAAAA",+ });+ for (const k of [+ "CLAUDECODE",+ "CLAUDE_CODE_CHILD_SESSION",+ "MAGMUX_SOCK",+ "MAGMUX_SOCK_DIR",+ "TMUX",+ "TERM_PROGRAM",+ "ITERM_SESSION_ID",+ "VSCODE_PID",+ ...HOST_IDENTITY_VARS,+ ])+ expect(magmuxEnv[k]).toBeUndefined();+ expect(magmuxEnv.COLUMNS).toBe("160");+ expect(magmuxEnv.LINES).toBe("50");+ expect(magmuxEnv.CLAUDISH_PANE_CHILD).toBe("1");+ expect(magmuxEnv.CLAUDISH_PANE_CWD).toBe("/real/cwd");+ expect(magmuxEnv.CLAUDISH_TOKEN_FILE).toBe("/t.json");+ expect(magmuxEnv.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC).toBe("1");+ expect(magmuxEnv.SHELL).toBe("/root/launch-AAAAAA/sh-shim");+ });++ test("the snapshot keeps the REAL SHELL and excludes shell-managed keys and itself", () => {+ const { magmuxEnv } = buildPaneEnv({+ parentEnv,+ slotEnv: {},+ cwd: "/c",+ ctlDir: "/r/launch-AAAAAA",+ });+ const snap = JSON.parse(magmuxEnv.CLAUDISH_PANE_ENV as string);+ expect(snap.SHELL).toBe("/bin/zsh");+ expect(snap.OPENAI_API_KEY).toBe("k");+ for (const k of [+ "COLUMNS",+ "LINES",+ "TERM",+ "SHLVL",+ "PWD",+ "MAGMUX_SOCK",+ "CLAUDISH_PANE_ENV",+ "TMUX",+ ])+ expect(snap[k]).toBeUndefined();+ expect(snap.CLAUDISH_PANE_CHILD).toBe("1");+ });++ test("a caller's own CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC is kept", () => {+ const { magmuxEnv } = buildPaneEnv({+ parentEnv: { ...parentEnv, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "0" },+ slotEnv: {},+ cwd: "/c",+ ctlDir: "/r/launch-AAAAAA",+ });+ expect(magmuxEnv.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC).toBe("0");+ });++ test("Linux refuses a snapshot over 131,000 bytes; macOS has no per-string limit", () => {+ const big = { ...parentEnv, BIG: "x".repeat(LINUX_ENV_STRING_LIMIT) };+ expect(() =>+ buildPaneEnv({+ parentEnv: big,+ slotEnv: {},+ cwd: "/c",+ ctlDir: "/r/launch-AAAAAA",+ platform: "linux",+ })+ ).toThrow(PaneEnvTooLargeError);+ expect(() =>+ buildPaneEnv({+ parentEnv: big,+ slotEnv: {},+ cwd: "/c",+ ctlDir: "/r/launch-AAAAAA",+ platform: "linux",+ })+ ).toThrow(/over Linux's 131072-byte limit per variable/);+ expect(() =>+ buildPaneEnv({+ parentEnv: big,+ slotEnv: {},+ cwd: "/c",+ ctlDir: "/r/launch-AAAAAA",+ platform: "darwin",+ })+ ).not.toThrow();+ });+});++describe("ids, socket paths and the socket root", () => {+ test("minted ids are valid, ≤ 40 chars, embed the owner pid and start", () => {+ const id = mintPaneId("t", "01-slot/with spaces");+ expect(isValidPaneId(id)).toBe(true);+ expect(id.length).toBeLessThanOrEqual(40);+ expect(id.startsWith(`c${process.pid}-${OWNER_START36}-t`)).toBe(true);+ expect(mintPaneId("s", "x")).not.toBe(mintPaneId("s", "x"));+ });++ test("ids: all digits and bad characters are refused (magmux would ignore them)", () => {+ expect(isValidPaneId("12345")).toBe(false);+ expect(isValidPaneId("a/b")).toBe(false);+ expect(isValidPaneId("x".repeat(65))).toBe(false);+ expect(isValidPaneId("c1-a-t01-abcdef")).toBe(true);+ });++ test("a socket path of 100 bytes or more is refused", () => {+ expect(sockPathFor("/tmp/r", "c1-x")).toBe("/tmp/r/magmux-c1-x.sock");+ expect(() => sockPathFor(`/tmp/${"d".repeat(80)}`, "c1-abcdefghij")).toThrow(PaneRootError);+ });++ test("CLAUDISH_PANE_ROOT overrides the default root", () => {+ expect(sockRootFor({ CLAUDISH_PANE_ROOT: "/tmp/cpt-1" })).toBe("/tmp/cpt-1");+ expect(sockRootFor({})).toMatch(/^\/tmp\/claudish-mux-\d+$/);+ });++ test("ensureSockRoot creates 0700 dirs and refuses a symlink or a group/world-readable dir", () => {+ const base = tmp();+ const root = join(base, "root");+ expect(ensureSockRoot(root)).toBe(root);+ const link = join(base, "link");+ symlinkSync(root, link);+ expect(() => ensureSockRoot(link)).toThrow(/not a real directory/);+ const open = join(base, "open");+ mkdirSync(open);+ chmodSync(open, 0o755);+ expect(() => ensureSockRoot(open)).toThrow(/must be 0700/);+ });+});++describe("watcher argv and version gate", () => {+ test("values reach the watcher only as positional parameters, under argv0 claudish-pane-watcher", () => {+ const a = watcherArgv({+ paneId: "c1-x-t01-abcdef",+ sessionUuid: "u'; rm -rf /",+ ctlDir: "/r/launch-AAAAAA",+ sockPath: "/r/magmux-c1-x-t01-abcdef.sock",+ recordPath: "/r/panes/c1-x-t01-abcdef.json",+ turnDir: "/r/launch-BBBBBB",+ sockRoot: "/r",+ });+ expect(a[0]).toBe("-c");+ expect(a[1]).toBe(WATCHER_SCRIPT);+ expect(a[2]).toBe(WATCHER_ARGV0);+ expect(a.slice(3)).toEqual([+ "c1-x-t01-abcdef",+ "u'; rm -rf /",+ "/r/launch-AAAAAA",+ "/r/magmux-c1-x-t01-abcdef.sock",+ "/r/panes/c1-x-t01-abcdef.json",+ "/r/launch-BBBBBB",+ "/r",+ ]);+ expect(WATCHER_SCRIPT).not.toContain("u'; rm -rf /");+ });++ test("versionAtLeast", () => {+ expect(versionAtLeast("0.14.0", "0.14.0")).toBe(true);+ expect(versionAtLeast("0.15.2", "0.14.0")).toBe(true);+ expect(versionAtLeast("0.13.9", "0.14.0")).toBe(false);+ expect(versionAtLeast("1.0.0", "0.14.0")).toBe(true);+ });+});diff --git a/packages/cli/src/pane/pane-launch.ts b/packages/cli/src/pane/pane-launch.tsnew file mode 100644index 00000000..b703a972--- /dev/null+++ b/packages/cli/src/pane/pane-launch.ts@@ -0,0 +1,557 @@+/**+ * Everything that happens before a pane exists (architecture §2.3): the socket root,+ * pane ids, the child's environment, the launcher and shell shim, the caller-flag check,+ * and the two spawns — the pane watcher, then magmux.+ *+ * The pane child must run in EXACTLY the MCP server's environment and cwd (D16), which+ * a pipe spawn gave for free and a pane does not: magmux starts the pane through+ * `$SHELL -l -c`, a login shell that would run the user's profile. So the environment+ * travels as a JSON snapshot in `CLAUDISH_PANE_ENV` (inherited, never on disk) that the+ * child re-applies (`child-env.ts`), and `$SHELL` is a generated shim that drops `-l`, so+ * no profile runs at all (X-M15).+ *+ * The pane command must never name `claude`: magmux attaches its ClaudeCodeController+ * to such a pane, and that controller's mtime-based transcript discovery can lock onto+ * the parent's or a sibling's transcript (research-magmux §3).+ */++import { type ChildProcess, execFileSync, spawn } from "node:child_process";+import { randomBytes } from "node:crypto";+import { chmodSync, lstatSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { CLAUDISH_EXITING_FLAGS, CLAUDISH_FLAG_ARITY, classifyPassthroughTokens } from "../cli.js";+import { ENV } from "../config.js";+import { findMagmuxBinaryOrNull } from "../launcher/magmux-binary.js";+import { STRIPPED_CHILD_VARS } from "../launcher/magmux-wrapper.js";+import { resolveClaudishSpawn } from "../spawn-claudish.js";+import { isPaneShellManagedKey } from "./child-env.js";+import { type WatcherArgs, sockPathOf, watcherArgv } from "./process-identity.js";++/* ───────────────────────────── socket root ───────────────────────────── */++function uid(): number {+ return typeof process.getuid === "function" ? process.getuid() : 0;+}++/**+ * The socket root for `env`: `CLAUDISH_PANE_ROOT` when set (a location, like+ * `CLAUDISH_SESSIONS_DIR`; every check below still applies), else `/tmp/claudish-mux-<uid>`.+ */+export function sockRootFor(env: Record<string, string | undefined> = process.env): string {+ const override = env[ENV.CLAUDISH_PANE_ROOT]?.trim();+ return override ? override : `/tmp/claudish-mux-${uid()}`;+}++/** The default socket root of this process. */+export const SOCK_ROOT: string = sockRootFor();++export class PaneRootError extends Error {+ readonly code = "pane_root";+}++function assertPrivateDir(p: string): void {+ const st = lstatSync(p);+ if (st.isSymbolicLink() || !st.isDirectory())+ throw new PaneRootError(`pane socket root ${p} is not a real directory`);+ if (st.uid !== uid())+ throw new PaneRootError(`pane socket root ${p} is not owned by uid ${uid()}`);+ if ((st.mode & 0o077) !== 0)+ throw new PaneRootError(+ `pane socket root ${p} has mode ${(st.mode & 0o777).toString(8)}; it must be 0700`+ );+}++/** Create (0700) and verify the socket root and its `panes/` record dir. Returns `root`. */+export function ensureSockRoot(root: string = sockRootFor()): string {+ try {+ mkdirSync(root, { mode: 0o700 });+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code === "ENOENT")+ mkdirSync(root, { recursive: true, mode: 0o700 });+ else if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;+ }+ assertPrivateDir(root);+ const panes = join(root, "panes");+ try {+ mkdirSync(panes, { mode: 0o700 });+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;+ }+ assertPrivateDir(panes);+ return root;+}++/* ───────────────────────────── ids ───────────────────────────── */++/** This process's start time in ms, base 36: with the pid it makes a reused owner pid detectable. */+export const OWNER_START36 = Math.round(Date.now() - process.uptime() * 1000).toString(36);++const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;++export function isValidPaneId(id: string): boolean {+ return ID_RE.test(id) && !/^\d+$/.test(id);+}++/** `c<pid>-<ownerStart36>-<kind><label>-<6 hex>`, at most 40 characters. */+export function mintPaneId(kind: "t" | "s", label: string): string {+ const head = `c${process.pid}-${OWNER_START36}-${kind}`;+ const tail = `-${randomBytes(3).toString("hex")}`;+ const room = Math.max(0, 40 - head.length - tail.length);+ const clean = label.replace(/[^A-Za-z0-9_]/g, "").slice(0, room);+ const id = `${head}${clean}${tail}`;+ if (!isValidPaneId(id)) throw new Error(`minted an invalid pane id: ${id}`);+ return id;+}++/** Unix socket paths must stay under 100 bytes, or magmux silently binds elsewhere. */+export function sockPathFor(root: string, id: string): string {+ const p = sockPathOf(root, id);+ if (Buffer.byteLength(p) >= 100)+ throw new PaneRootError(+ `pane socket path ${p} is ${Buffer.byteLength(p)} bytes; it must be < 100`+ );+ return p;+}++/* ───────────────────────────── environment ───────────────────────────── */++/** Variables that steer a TUI's rendering and integrations (X-M16): never in a pane. */+export const TERMINAL_IDENTITY_VARS = [+ "TMUX",+ "TMUX_PANE",+ "TERM_PROGRAM",+ "TERM_PROGRAM_VERSION",+ "TERM_SESSION_ID",+ "COLORTERM",+ "LC_TERMINAL",+ "LC_TERMINAL_VERSION",+ "WT_SESSION",+ "CLAUDE_CODE_SSE_PORT",+ "ENABLE_IDE_INTEGRATION",+] as const;++export const TERMINAL_IDENTITY_PREFIXES = [+ "ITERM_",+ "KITTY_",+ "WEZTERM_",+ "ALACRITTY_",+ "GHOSTTY_",+ "VSCODE_",+] as const;++/** The MCP server's HOST identity: describes the server's host, not the pane's fresh session. */+export const HOST_IDENTITY_VARS = [+ "CLAUDISH_LAUNCHER_PID",+ "CLAUDISH_LAUNCHER_PPID",+ "CLAUDE_CODE_SESSION_ID",+] as const;++/** Linux's per-variable limit (MAX_ARG_STRLEN 131,072) with a margin. */+export const LINUX_ENV_STRING_LIMIT = 131_000;++function strippedFromPane(key: string): boolean {+ return (+ (STRIPPED_CHILD_VARS as readonly string[]).includes(key) ||+ key.startsWith("MAGMUX_") ||+ (TERMINAL_IDENTITY_VARS as readonly string[]).includes(key) ||+ TERMINAL_IDENTITY_PREFIXES.some((p) => key.startsWith(p)) ||+ (HOST_IDENTITY_VARS as readonly string[]).includes(key)+ );+}++export class PaneEnvTooLargeError extends Error {+ readonly code = "pane_lost";+}++export interface PaneEnvInput {+ parentEnv: Record<string, string | undefined>;+ slotEnv: Record<string, string>;+ /** realpath of the spawn cwd */+ cwd: string;+ /** the control directory holding `sh-shim` */+ ctlDir: string;+ platform?: NodeJS.Platform;+}++/**+ * magmux's environment: the parent's minus the stripped, terminal-identity and host-+ * identity keys, plus the geometry, the slot env, the pane markers, the snapshot, and+ * finally `SHELL=<ctlDir>/sh-shim` (after the snapshot, which keeps the real `SHELL`).+ */+export function buildPaneEnv(input: PaneEnvInput): { magmuxEnv: Record<string, string> } {+ const env: Record<string, string> = {};+ for (const [k, v] of Object.entries(input.parentEnv)) {+ if (v === undefined || strippedFromPane(k)) continue;+ env[k] = v;+ }+ env.COLUMNS = "160";+ env.LINES = "50";+ if (input.parentEnv.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC === undefined)+ env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1";+ Object.assign(env, input.slotEnv);+ env[ENV.CLAUDISH_PANE_CHILD] = "1";+ env[ENV.CLAUDISH_PANE_CWD] = input.cwd;+ delete env[ENV.CLAUDISH_PANE_ENV];++ const snapshot: Record<string, string> = {};+ for (const [k, v] of Object.entries(env)) {+ if (isPaneShellManagedKey(k) || k === ENV.CLAUDISH_PANE_ENV) continue;+ snapshot[k] = v;+ }+ const json = JSON.stringify(snapshot);+ const entryBytes = Buffer.byteLength(`${ENV.CLAUDISH_PANE_ENV}=${json}`);+ if ((input.platform ?? process.platform) === "linux" && entryBytes > LINUX_ENV_STRING_LIMIT)+ throw new PaneEnvTooLargeError(+ `pane environment snapshot is ${entryBytes} bytes, over Linux's 131072-byte limit per variable`+ );+ env[ENV.CLAUDISH_PANE_ENV] = json;+ env.SHELL = join(input.ctlDir, "sh-shim");+ return { magmuxEnv: env };+}++/* ───────────────────────────── child argv and flags ───────────────────────────── */++export function buildClaudishPaneArgv(+ spawnModel: string,+ sessionUuid: string,+ turnDir: string,+ callerFlags: string[]+): string[] {+ return [+ "-i",+ "--model",+ spawnModel,+ "-y",+ "--quiet",+ "--session-id",+ sessionUuid,+ "--add-dir",+ turnDir,+ ...callerFlags,+ ];+}++/** Our own argv, plus `--no-auto-approve`, which defeats `-y` (phase-2 s09). */+const OWN_ARGV = [+ "-i",+ "--interactive",+ "--model",+ "-m",+ "-y",+ "--auto-approve",+ "--no-auto-approve",+ "--quiet",+ "-q",+ "--session-id",+];++const TRANSPORT_BREAKERS = [+ "-p",+ "--print",+ "--stdin",+ "--output-format",+ "--input-format",+ "--include-partial-messages",+ "--replay-user-messages",+ "--json",+ "--bg",+ "--background",+];++const IDENTITY_BREAKERS = [+ "--resume",+ "-r",+ "--continue",+ "-c",+ "--from-pr",+ "--teleport",+ "--fork-session",+ "-w",+ "--worktree",+ "--no-session-persistence",+];++/** Claude Code flags that only work with `--print` (X-M3). */+export const PRINT_ONLY_FLAGS = [+ "--max-turns",+ "--max-budget-usd",+ "--fallback-model",+ "--json-schema",+ "--permission-prompt-tool",+];++/** claudish's own mode flags: each would start a different claudish mode in the pane (X-L2). */+const MODE_FLAGS = [+ "--team",+ "-f",+ "--file",+ "--grid",+ "--probe",+ "--models",+ "--monitor",+ "--advisor",+ "--mcp",+ "--kimi-login",+ "--kimi-logout",+ ...CLAUDISH_EXITING_FLAGS,+];++/**+ * Words index.ts treats as a SUBCOMMAND anywhere in argv (`args.includes("update")`,+ * the first non-dash token, …): a caller flag VALUE equal to one of them would dispatch+ * a subcommand instead of the REPL, which the child-side assertion cannot catch.+ */+export const SUBCOMMAND_WORDS = [+ "update",+ "init",+ "profile",+ "config",+ "telemetry",+ "stats",+ "serve",+ "providers",+ "keychain",+ "behavior",+ "team",+ "login",+ "logout",+ "quota",+ "usage",+];++export type FlagCheck = { ok: true } | { ok: false; message: string };++function reservedMessage(flag: string): string | null {+ if (PRINT_ONLY_FLAGS.includes(flag))+ return `${flag} works only with --print; team slots and sessions are interactive panes, so it would be silently ignored`;+ if (OWN_ARGV.includes(flag))+ return `${flag} is set by claudish itself for a pane child (-i --model <m> -y --quiet --session-id <uuid>)`;+ if (TRANSPORT_BREAKERS.includes(flag))+ return `${flag} would break the interactive pane transport`;+ if (IDENTITY_BREAKERS.includes(flag))+ return `${flag} would move the session to another transcript or directory`;+ if ((MODE_FLAGS as readonly string[]).includes(flag))+ return `${flag} would start a different claudish mode inside the pane`;+ return null;+}++/** Whether the flags visibly remove the Read tool (§2.3 rule 4). */+export function flagsRemoveRead(flags: string[]): boolean {+ for (let i = 0; i < flags.length; i++) {+ const [name, inline] = splitFlag(flags[i] as string);+ const value = inline ?? flags[i + 1] ?? "";+ if (name === "--disallowedTools" || name === "--disallowed-tools") {+ if (/(^|[\s,])Read([\s,(]|$)/.test(value)) return true;+ }+ if (name === "--tools") {+ if (!/(^|[\s,])Read([\s,(]|$)/.test(value)) return true;+ }+ }+ return false;+}++function splitFlag(token: string): [string, string | undefined] {+ if (!token.startsWith("-")) return [token, undefined];+ const eq = token.indexOf("=");+ return eq > 0 ? [token.slice(0, eq), token.slice(eq + 1)] : [token, undefined];+}++/**+ * The server-side check of `claude_flags` (D18): reserved tokens, subcommand words, and+ * any positional token or `--` (claudish would turn a positional into a `-p` prompt).+ */+export function checkChildFlags(flags: string[]): FlagCheck {+ for (const token of flags) {+ if (typeof token !== "string") return { ok: false, message: "claude_flags must be strings" };+ const [name] = splitFlag(token);+ const msg = token.startsWith("-") ? reservedMessage(name) : null;+ if (msg) return { ok: false, message: msg };+ if (SUBCOMMAND_WORDS.includes(token))+ return {+ ok: false,+ message: `"${token}" is a claudish subcommand name and would start that subcommand inside the pane`,+ };+ }+ // `--flag=value` is one token to parseArgs as well, so the original tokens are classified.+ const c = classifyPassthroughTokens(flags);+ if (c.separatorAt !== null)+ return {+ ok: false,+ message:+ "claude_flags may not contain `--`: claudish would treat what follows as a prompt; claudish takes one value per flag: write `--allowedTools Read,Bash`",+ };+ if (c.positionals.length > 0)+ return {+ ok: false,+ message: `claude_flags contains a positional token (${JSON.stringify(c.positionals[0])}); claudish takes one value per flag: write \`--allowedTools Read,Bash\``,+ };+ return { ok: true };+}++/** Known claudish flags (exported for the drift test). */+export const KNOWN_CLAUDISH_FLAGS: readonly string[] = Object.keys(CLAUDISH_FLAG_ARITY);++/* ───────────────────────────── magmux binary ───────────────────────────── */++export const MIN_MAGMUX_VERSION = "0.14.0";++export class MagmuxUnavailableError extends Error {+ readonly code = "magmux_unavailable";+}++export function versionAtLeast(v: string, min: string): boolean {+ const a = v.split(/[.-]/).map((x) => Number.parseInt(x, 10));+ const b = min.split(".").map((x) => Number.parseInt(x, 10));+ for (let i = 0; i < 3; i++) {+ const x = a[i] ?? 0;+ const y = b[i] ?? 0;+ if (!Number.isFinite(x)) return false;+ if (x !== y) return x > y;+ }+ return true;+}++let magmuxCache: { binary: string; version: string } | null = null;++/** The magmux binary and its version (≥ 0.14.0), cached per process. Never a `-p` fallback. */+export async function assertMagmuxAvailable(+ binary?: string+): Promise<{ binary: string; version: string }> {+ if (!binary && magmuxCache) return magmuxCache;+ const found = binary ?? findMagmuxBinaryOrNull();+ if (!found)+ throw new MagmuxUnavailableError(+ "magmux_unavailable: magmux not found (bundled package or PATH); install it: brew install MadAppGang/tap/magmux"+ );+ let out = "";+ try {+ out = execFileSync(found, ["--version"], { encoding: "utf8", timeout: 5000 });+ } catch (e) {+ throw new MagmuxUnavailableError(+ `magmux_unavailable: ${found} --version failed: ${e instanceof Error ? e.message : String(e)}`+ );+ }+ const version = out.match(/(\d+\.\d+\.\d+)/)?.[1] ?? "";+ if (!version || !versionAtLeast(version, MIN_MAGMUX_VERSION))+ throw new MagmuxUnavailableError(+ `magmux_unavailable: ${found} is version ${version || "unknown"}; panes need >= ${MIN_MAGMUX_VERSION}`+ );+ const result = { binary: found, version };+ if (!binary) magmuxCache = result;+ return result;+}++/* ───────────────────────────── launcher ───────────────────────────── */++export interface ClaudishLaunch {+ command: string;+ prefixArgs: string[];+}++export class ClaudishNotFoundError extends Error {+ readonly code = "pane_lost";+}++/** Which claudish the launcher `exec`s: `CLAUDISH_BIN` (`*.ts` → `<bun> run <file>`), else PATH. */+export function resolveClaudishLaunch(+ parentEnv: Record<string, string | undefined>+): ClaudishLaunch {+ const t = resolveClaudishSpawn(parentEnv as NodeJS.ProcessEnv);+ if (t.command.includes("/")) return t;+ const found = Bun.which(t.command, { PATH: parentEnv.PATH ?? "" });+ if (!found) throw new ClaudishNotFoundError(`${t.command} not found on PATH`);+ return { command: found, prefixArgs: t.prefixArgs };+}++/** POSIX single-quote escaping. */+export function shq(s: string): string {+ return `'${s.replaceAll("'", `'\\''`)}'`;+}++/** The launcher: `cd` to the realpath cwd, then `exec` claudish (no watcher, no PATH line). */+export function launcherScript(cwd: string, launch: ClaudishLaunch, argv: string[]): string {+ const words = [launch.command, ...launch.prefixArgs, ...argv].map(shq).join(" ");+ return `cd -- ${shq(cwd)} || exit 97\nexec ${words}\n`;+}++export const SHELL_SHIM = '#!/bin/sh\n[ "$1" = -l ] && shift\nexec /bin/sh "$@"\n';++/** The `-e` value. It never names `claude` (research-magmux §3). */+export function paneCommand(ctlDir: string): string {+ const cmd = `. ${shq(join(ctlDir, "pane-launch.sh"))}`;+ if (/claude /.test(cmd) || /claude$/.test(cmd) || /(^|\/)claude['"]?$/.test(cmd))+ throw new Error(`pane command would attach magmux's Claude Code controller: ${cmd}`);+ return cmd;+}++export interface LaunchDirs {+ /** control directory: pane-launch.sh, sh-shim, magmux.pid, group — never shown to the model */+ ctlDir: string;+ /** turn directory: turn-<n>.md only; the child's `--add-dir` (R3-M2) */+ turnDir: string;+}++export function createLaunchDirs(root: string): LaunchDirs {+ const ctlDir = mkdtempSync(join(root, "launch-"));+ chmodSync(ctlDir, 0o700);+ const turnDir = mkdtempSync(join(root, "launch-"));+ chmodSync(turnDir, 0o700);+ return { ctlDir, turnDir };+}++export function writeLauncherFiles(ctlDir: string, script: string): void {+ writeFileSync(join(ctlDir, "pane-launch.sh"), script, { mode: 0o600, flag: "wx" });+ writeFileSync(join(ctlDir, "sh-shim"), SHELL_SHIM, { mode: 0o700, flag: "wx" });+}++/* ───────────────────────────── spawns ───────────────────────────── */++/**+ * The pane watcher (D15 layer 1): a detached `/bin/sh` whose stdin is a pipe from this+ * process. EOF on it — this process ended, by any means — makes it verify and kill the+ * pane's group and magmux, then clean the files; `done` ends it after a clean reap.+ */+export function spawnPaneWatcher(args: WatcherArgs): ChildProcess {+ const proc = spawn("/bin/sh", watcherArgv(args), {+ stdio: ["pipe", "ignore", "ignore"],+ detached: true,+ env: { PATH: "/bin:/usr/bin:/usr/sbin:/sbin", LC_ALL: "C" },+ });+ // EPIPE on `done\n` means the watcher is already gone, which is not an error (R3-M1).+ proc.stdin?.on("error", () => {});+ proc.on("error", () => {});+ proc.unref();+ (proc.stdin as unknown as { unref?: () => void } | null)?.unref?.();+ return proc;+}++/** Fatal magmux stderr: it ignores an invalid id or socket dir and binds somewhere else. */+export const FATAL_MAGMUX_STDERR = /ignoring --id|ignoring --sock-dir|magmux: socket/;++export interface MagmuxSpawnInput {+ binary: string;+ paneId: string;+ sockRoot: string;+ ctlDir: string;+ cwd: string;+ env: Record<string, string>;+}++export function spawnPaneMagmux(input: MagmuxSpawnInput): ChildProcess {+ const proc = spawn(+ input.binary,+ [+ "--headless",+ "--no-status",+ "--id",+ input.paneId,+ "--sock-dir",+ input.sockRoot,+ "-e",+ paneCommand(input.ctlDir),+ ],+ { cwd: input.cwd, env: input.env, stdio: ["ignore", "ignore", "pipe"], detached: true }+ );+ proc.on("error", () => {});+ return proc;+}