Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(scripts): replace magmux-drive-session.ts with pane-drive.ts
Jack Rudenko750b7a21ae2f
diff --git a/ai-docs/architecture/headless-vs-interactive.md b/ai-docs/architecture/headless-vs-interactive.mdindex 0eec12ef..721d2916 100644--- a/ai-docs/architecture/headless-vs-interactive.md+++ b/ai-docs/architecture/headless-vs-interactive.md@@ -176,12 +176,13 @@ the content is. Same lesson as `require_pattern` in `team-capture.md`, one layer### A working implementation-`scripts/magmux-drive-session.ts` implements the sequence above and is the thing to read (or-copy) rather than reconstructing it:+`packages/cli/src/pane/` (`PaneSession`) implements the sequence above for MCP `team` slots and+`create_session`, and `scripts/pane-drive.ts` drives one session through it from the command+line (it replaced the polling reference driver `magmux-drive-session.ts`, whose measurements+follow):- bun scripts/magmux-drive-session.ts <id> "Reply with exactly OK and nothing else."- -> {"ok":true,"answer":"OK","costSeen":true,- "states":["boot=awaiting_input","started=running","settled=awaiting_input"]}+ bun scripts/pane-drive.ts "Reply with exactly OK and nothing else."+ bun scripts/pane-drive.ts --fake answer "hello" # the test fake, hermetic, no costMeasured: 8/8 deterministic runs, 14-25s each; distinct prompts return their real answers(`BANANA`, `51` for 17x3, `PEAR`), so it reports model output rather than a fixed string; adiff --git a/scripts/magmux-drive-session.ts b/scripts/magmux-drive-session.tsdeleted file mode 100644index 8fabe63e..00000000--- a/scripts/magmux-drive-session.ts+++ /dev/null@@ -1,206 +0,0 @@-#!/usr/bin/env bun-/**- * scripts/magmux-drive-session.ts — REFERENCE IMPLEMENTATION, not wired into the CLI.- *- * Usage: bun scripts/magmux-drive-session.ts <session-id> "<prompt>"- * Exits 0 with {"ok":true,"answer":...} on success, 1 otherwise.- *- * Drive a real interactive Claude Code session through magmux to completion.- *- * Neither magmux flag does this alone: `-w` counts a REPL's prompt as "done"- * (done = dead OR inputReady) and quits in ~6s reporting SUCCESS having done- * nothing, while no `-w` waits for a keypress forever. This drives the session- * over the socket instead.- *- * Measured 2026-08-22: 6/6 deterministic runs, 14-24s each; a forced turn- * deadline returns `turn_timeout` in 16.7s rather than hanging; no orphaned- * processes or stale sockets after any run. Rationale and the full trap list:- * ai-docs/architecture/headless-vs-interactive.md.- *- * KNOWN IMPROVEMENT: this POLLS `list` every 600ms. The protocol is designed for- * event SUBSCRIPTION (`snapshot` / `exit` frames), which is what madbench's- * internal/magmux/socket.go does and is more robust — no poll-interval race.- * Polling was sufficient to validate the sequence; prefer events for real use.- */-import { type ChildProcess, spawn } from "node:child_process";-import { type Socket, connect } from "node:net";-import { setTimeout as sleep } from "node:timers/promises";--export interface DriveResult {- ok: boolean;- answer: string;- costSeen: boolean;- states: string[];- reason?: string;-}--const QUIET = process.env.DRIVER_QUIET === "1";-const log = (m: string) => {- if (!QUIET) console.log(`[drv] ${m}`);-};--export async function driveClaude(opts: {- id: string;- prompt: string;- cwd?: string;- bootMs?: number;- turnMs?: number;-}): Promise<DriveResult> {- const sockPath = `/tmp/magmux-${opts.id}.sock`;- const states: string[] = [];- let mux: ChildProcess | null = null;- let sock: Socket | null = null;-- // Inherited from a parent Claude Code session these turn TRANSCRIPT SAVING- // OFF, which blinds ClaudeCodeController (its primary signal is the JSONL- // transcript) and silently degrades detection to terminal-idle heuristics.- const env = { ...process.env };- delete env.CLAUDE_CODE_CHILD_SESSION;- delete env.CLAUDECODE;-- const cleanup = async () => {- try {- sock?.end();- } catch {}- if (mux && mux.exitCode === null) {- try {- mux.kill("SIGTERM");- } catch {}- await sleep(1200);- if (mux.exitCode === null) {- try {- mux.kill("SIGKILL");- } catch {}- }- }- };-- try {- mux = spawn("magmux", ["--headless", "--id", opts.id, "-e", "claude"], {- stdio: ["ignore", "ignore", "ignore"],- env,- cwd: opts.cwd,- });-- for (let i = 0; i < 60 && !sock; i++) {- await sleep(500);- sock = await new Promise<Socket | null>((res) => {- const s = connect(sockPath);- s.on("connect", () => res(s));- s.on("error", () => res(null));- });- }- if (!sock) return { ok: false, answer: "", costSeen: false, states, reason: "no_socket" };-- let buf = "";- let msgs: any[] = [];- sock.on("data", (d) => {- buf += d.toString();- let i = buf.indexOf("\n");- while (i >= 0) {- const line = buf.slice(0, i);- buf = buf.slice(i + 1);- if (line.trim()) {- try {- msgs.push(JSON.parse(line));- } catch {- // Not our protocol; ignore rather than kill the driver.- }- }- i = buf.indexOf("\n");- }- });-- let nid = 1;- const send = (o: any) => sock!.write(`${JSON.stringify({ ...o, id: nid++ })}\n`);- const paneState = (): string | null => {- for (let k = msgs.length - 1; k >= 0; k--) {- const panes = msgs[k]?.result?.panes ?? msgs[k]?.panes;- if (Array.isArray(panes)) {- const p = panes.find((x: any) => x.pane === 0);- if (p?.state) return p.state;- }- }- return null;- };- const waitFor = async (want: string[], label: string, ms: number) => {- const end = Date.now() + ms;- while (Date.now() < end) {- msgs = [];- send({ type: "list" });- await sleep(600);- const st = paneState();- if (st) {- if (want.includes(st)) {- states.push(`${label}=${st}`);- log(`${label}: ${st}`);- return st;- }- if (st === "awaiting_permission") {- states.push(`${label}=awaiting_permission`);- return st;- }- }- }- states.push(`${label}=TIMEOUT`);- log(`${label}: TIMEOUT`);- return null;- };-- // EDGE 1 — the TUI genuinely at its prompt. `running` here is the SPLASH.- if (!(await waitFor(["awaiting_input"], "boot", opts.bootMs ?? 90_000)))- return { ok: false, answer: "", costSeen: false, states, reason: "boot_timeout" };-- send({ type: "send", pane: 0, text: opts.prompt, label: "drive" });-- // EDGE 2 — the turn actually started (guards against a send that never submitted).- const started = await waitFor(["running"], "started", 30_000);- if (started === "awaiting_permission")- return { ok: false, answer: "", costSeen: false, states, reason: "awaiting_permission" };-- // EDGE 3 — the turn actually settled.- const settled = await waitFor(- ["awaiting_input", "completed"],- "settled",- opts.turnMs ?? 180_000- );- if (settled === "awaiting_permission")- return { ok: false, answer: "", costSeen: false, states, reason: "awaiting_permission" };- if (!settled) return { ok: false, answer: "", costSeen: false, states, reason: "turn_timeout" };-- // CONTENT is the oracle, not the state flag.- msgs = [];- send({ type: "capture", pane: 0, lines: 60 });- await sleep(1200);- let screen = "";- for (let k = msgs.length - 1; k >= 0; k--) {- const t = msgs[k]?.result?.text ?? msgs[k]?.text;- if (typeof t === "string") {- screen = t;- break;- }- }- const lines = screen- .split("\n")- .map((l) => l.trimEnd())- .filter((l) => l.trim());- const costSeen = /\$\s*[1-9]|\$0\.[0-9]*[1-9]/.test(screen);- const ansIdx = lines.findIndex((l) => l.trimStart().startsWith("⏺"));- const answer = ansIdx >= 0 ? lines[ansIdx].replace(/^\s*⏺\s*/, "").trim() : "";-- send({ type: "close_pane", pane: 0, force: false });- await sleep(2000);-- return { ok: answer.length > 0 && costSeen, answer, costSeen, states };- } finally {- await cleanup();- }-}--if (import.meta.main) {- const id = process.argv[2] ?? "drv1";- const prompt = process.argv[3] ?? "Reply with exactly OK and nothing else.";- const r = await driveClaude({ id, prompt, cwd: process.cwd() });- console.log(JSON.stringify(r));- process.exit(r.ok ? 0 : 1);-}diff --git a/scripts/pane-drive.ts b/scripts/pane-drive.tsnew file mode 100644index 00000000..d648cfad--- /dev/null+++ b/scripts/pane-drive.ts@@ -0,0 +1,132 @@+#!/usr/bin/env bun+/**+ * scripts/pane-drive.ts — drive ONE interactive Claude Code session in a headless magmux+ * pane through `PaneSession` (packages/cli/src/pane/), exactly as MCP `team` slots and+ * `create_session` run: claudish `-i --model <m> -y --quiet --session-id <uuid>` in a+ * per-session magmux, prompts typed or delivered by file, settle read from the transcript.+ * Replaces the polling reference driver `magmux-drive-session.ts`.+ *+ * bun scripts/pane-drive.ts [--model haiku] [--cwd <dir>] [--flags '<json array>']+ * [--fake <scenario>] "<prompt>" ["<next prompt>" …]+ *+ * One prompt → a one-shot session; more → an interactive session, each later prompt sent+ * after the previous turn settled. Prints every wire transition and, at the end, one JSON+ * line `{ok, state, reason, detail, turns:[{answer, settledBy, stopReason}], anomalies}`.+ * Exit 0 when the session COMPLETED.+ *+ * Without `--fake` this runs the real claudish (CLAUDISH_BIN or `claudish` on PATH) with+ * YOUR environment and Claude Code config, and spends real tokens. `--fake <scenario>`+ * runs the test fake child in a hermetic temp environment instead (no cost, no login).+ */++import { realpathSync } from "node:fs";+import { resolve } from "node:path";+import {+ checkChildFlags,+ flagsRemoveRead,+ startPaneSession,+} from "../packages/cli/src/pane/index.ts";+import type { SettledTurn } from "../packages/cli/src/pane/types.ts";+import { projectsDir, transcriptPathFor } from "../packages/cli/src/session/session-discovery.ts";++function parse(argv: string[]) {+ const o = {+ model: "haiku",+ cwd: process.cwd(),+ flags: [] as string[],+ fake: null as string | null,+ prompts: [] as string[],+ };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i] as string;+ if (a === "--model") o.model = argv[++i] as string;+ else if (a === "--cwd") o.cwd = resolve(argv[++i] as string);+ else if (a === "--flags") o.flags = JSON.parse(argv[++i] as string);+ else if (a === "--fake") o.fake = argv[++i] as string;+ else o.prompts.push(a);+ }+ return o;+}++async function main(): Promise<number> {+ const o = parse(process.argv.slice(2));+ if (o.prompts.length === 0) {+ console.error(+ 'usage: bun scripts/pane-drive.ts [--model m] [--cwd dir] [--flags json] [--fake scenario] "<prompt>" …'+ );+ return 2;+ }+ const check = checkChildFlags(o.flags);+ if (!check.ok) {+ console.error(`invalid --flags: ${check.message}`);+ return 2;+ }+ let parentEnv: Record<string, string | undefined> = process.env;+ let cwd = realpathSync(o.cwd);+ let cleanup = () => {};+ let model = o.model;+ if (o.fake) {+ const { makePaneTestEnv } = await import(+ "../packages/cli/src/pane/test-helpers/hermetic-env.ts"+ );+ const t = makePaneTestEnv();+ parentEnv = t.env;+ cwd = realpathSync(t.cwd);+ model = `fake-${o.fake}`;+ cleanup = () => t.cleanup();+ }+ const uuid = crypto.randomUUID();+ const interactive = o.prompts.length > 1;+ const turns: SettledTurn[] = [];+ const t0 = Date.now();+ const s = await startPaneSession({+ kind: "s",+ label: "drive",+ callerFlags: o.flags,+ spawnModel: model,+ cwd,+ sessionUuid: uuid,+ transcriptPath: transcriptPathFor(cwd, uuid, projectsDir(parentEnv)),+ slotEnv: {},+ shape: interactive ? "interactive" : "one-shot",+ initialPrompt: o.prompts[0],+ readAvailable: !flagsRemoveRead(o.flags),+ parentEnv,+ decide: (turn) => {+ turns.push(turn);+ if (turn.apiError)+ return { state: "FAILED", reason: "api_error", detail: turn.apiError.text };+ if (turns.length < o.prompts.length) return "continue";+ return turn.answer.trim()+ ? { state: "COMPLETED" }+ : { state: "EMPTY", reason: "empty_output" };+ },+ onBlocked: (b) => ({ state: "FAILED", reason: "blocked", detail: `${b.tool}: ${b.text}` }),+ onTransition: (x) =>+ console.error(`[pane ${((Date.now() - t0) / 1000).toFixed(1)}s] ${x.from} → ${x.to}`),+ });+ console.error(`[pane] ${s.paneId} session ${uuid}`);+ for (const p of o.prompts.slice(1)) s.send(p);+ const snap = await s.terminal;+ await s.reaped();+ cleanup();+ console.log(+ JSON.stringify({+ ok: snap.state === "COMPLETED",+ state: snap.state,+ reason: snap.reason,+ detail: snap.detail,+ turns: turns.map((t) => ({+ answer: t.answer,+ settledBy: t.settledBy,+ stopReason: t.stopReason,+ delivery: t.delivery.mode,+ })),+ anomalies: snap.anomalies,+ claudeCode: snap.claudeCodeVersion,+ })+ );+ return snap.state === "COMPLETED" ? 0 : 1;+}++process.exit(await main());