Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(hooks): run session hooks in claudish -i through InteractiveDriver
Jack Rudenko47125a9798fa
diff --git a/packages/cli/src/hooks/session/interactive-driver.integration.test.ts b/packages/cli/src/hooks/session/interactive-driver.integration.test.tsnew file mode 100644index 00000000..5c77075f--- /dev/null+++ b/packages/cli/src/hooks/session/interactive-driver.integration.test.ts@@ -0,0 +1,1137 @@+/**+ * The interactive driver (hook-system architecture §7.5, §11.3 "Interactive driver").+ *+ * A HEADLESS magmux stands in for the visible one: the driver gets its socket path and+ * pane id (the injection seam), and the pane runs the fake interactive child in scripted+ * mode (`fake-scripted`, `FAKE_SCRIPT`, `FAKE_KEYLOG`). A second `MagmuxClient` plays the+ * human: it types into the same pane, as a person at the keyboard would.+ *+ * The binding is a test double whose `settle()` returns a promise the test resolves,+ * except where a test says "real binding". The last two blocks drive production code+ * end to end: the own-pane search inside a real two-pane magmux, and the real+ * `claudish -i` (ambient mode, minted session id, `--add-dir`) with the proxied fake+ * and a stub upstream, where a `responseEnd` annotation crosses the in-process sink+ * into `sessionIdle`, whose injection becomes the next turn.+ */++import { afterAll, describe, expect, test } from "bun:test";+import { type ChildProcess, spawn } from "node:child_process";+import { createHash, randomBytes, randomUUID } from "node:crypto";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { MagmuxClient } from "../../pane/magmux-client.js";+import {+ FAKE_CHILD,+ MAGMUX,+ NO_MAGMUX_MESSAGE,+ type PaneTestEnv,+ killLeftovers,+ makePaneTestEnv,+ writeFakeClaudeWrapper,+} from "../../pane/test-helpers/hermetic-env.js";+import { TranscriptFollower } from "../../pane/transcript-follower.js";+import {+ type StubUpstream,+ startStubUpstream,+ stubEndpointConfig,+} from "../../test-helpers/stub-upstream.js";+import { HookEngine } from "../engine.js";+import { InProcessSink } from "../injection/sinks.js";+import type { JournalEntry } from "../journal.js";+import type { HookDefinition } from "../public.js";+import { HookRegistry, type UserHookInput } from "../registry.js";+import type {+ BindingPane,+ HoldInjection,+ HoldResult,+ HoldTurnInfo,+ SessionHookBinding,+} from "./binding.js";+import { InteractiveDriver, type InteractiveDriverOptions } from "./interactive-driver.js";++const T = 60_000;+const INDEX = join(import.meta.dir, "..", "..", "index.ts");+const PROBE = join(import.meta.dir, "test-helpers", "own-pane-probe.ts");++/* ───────────────────────────── the test double binding ───────────────────────────── */++interface SettleCall {+ turn: HoldTurnInfo;+ signal: AbortSignal;+ resolve(r: HoldResult): void;+}++function controlled(o: { idle?: boolean } = {}) {+ const calls: SettleCall[] = [];+ const dropped: Array<{ text: string; reason: string }> = [];+ const delivered: Array<{ text: string; at: number }> = [];+ const abandoned: Array<{ text: string; reason: string }> = [];+ const blocked: Array<{ kind: string; text: string }> = [];+ const ends: Array<{ state: string; exitCode: number | null }> = [];+ let starts = 0;+ let pane: BindingPane | null = null;+ const binding: SessionHookBinding = {+ maxConsecutive: 3,+ hasIdleWork: () => o.idle ?? true,+ settle: (turn, signal) =>+ new Promise<HoldResult>((resolve) => calls.push({ turn, signal, resolve })),+ holdBoundMs: () => 30_000,+ fireStart() {+ starts++;+ },+ fireBlocked: (b) => void blocked.push(b),+ fireEnd: (e) => void ends.push(e),+ attach(p) {+ pane = p;+ },+ noteDropped: (item, reason) => void dropped.push({ text: item.text, reason }),+ noteDelivered: (item) => void delivered.push({ text: item.text, at: Date.now() }),+ abandon: (res, reason) => {+ for (const i of res.injections) abandoned.push({ text: i.text, reason });+ },+ };+ return {+ binding,+ calls,+ dropped,+ abandoned,+ delivered,+ blocked,+ ends,+ starts: () => starts,+ pane: () => pane as BindingPane | null,+ };+}++const inject = (text: string): HoldResult => ({+ injections: [{ text, hookIds: ["hook:t/x"], source: "sessionIdle" }],+});+const nothing: HoldResult = { injections: [] };++function engineOf(...defs: Array<Omit<HookDefinition, "apiVersion">>) {+ const journal: JournalEntry[] = [];+ const users: UserHookInput[] = defs.map((d, i) => ({+ id: `hook:t/${d.id}`,+ module: "/hooks/t.ts",+ moduleIndex: 0,+ exportIndex: i,+ def: { apiVersion: 1, ...d } as HookDefinition,+ }));+ const engine = new HookEngine({+ registry: new HookRegistry([], users, undefined),+ config: {},+ hostMode: "interactive",+ journalSink: (e) => journal.push(e),+ warn: () => {},+ drainTelemetryOutbox: false,+ });+ return { engine, journal };+}++/* ───────────────────────────── the rig ───────────────────────────── */++interface TurnScript {+ say?: string;+ ask?: string;+ noWitness?: boolean;+ delayMs?: number;+ rewake?: {+ delayMs: number;+ say: string;+ workingMs?: number;+ quietMs?: number;+ gateFile?: string;+ };+}++interface Rig {+ t: PaneTestEnv;+ uuid: string;+ sock: string;+ transcript: string;+ turnDir: string;+ magmux: ChildProcess;+ human: MagmuxClient;+ driver: InteractiveDriver | null;+ sink: InProcessSink;+ keylog(): string[];+ /** type into the pane as the human does */+ type(text: string, enter?: boolean): Promise<void>;+ startDriver(o?: Partial<InteractiveDriverOptions>): Promise<InteractiveDriver>;+}++const rigs = new Set<Rig>();+afterAll(() => {+ for (const r of rigs) cleanupRig(r);+});++function cleanupRig(r: Rig): void {+ rigs.delete(r);+ r.human.close();+ try {+ if (r.magmux.pid) process.kill(-r.magmux.pid, "SIGKILL");+ } catch {+ // gone+ }+ killLeftovers({ sockRoot: r.t.sockRoot, ids: [r.uuid] });+ r.t.cleanup();+}++async function finish(r: Rig): Promise<void> {+ await r.driver?.stop({ state: "COMPLETED", reason: null, exitCode: 0 });+ cleanupRig(r);+}++const shq = (s: string) => `'${s.replace(/'/g, "'\\''")}'`;++/** Spawn a headless magmux whose pane 0 runs the scripted fake, and dial it as the human. */+async function rig(+ script: TurnScript[],+ o: {+ binding?: SessionHookBinding;+ extraEnv?: Record<string, string>;+ driver?: Partial<InteractiveDriverOptions>;+ startDriver?: boolean;+ } = {}+): Promise<Rig> {+ const t = makePaneTestEnv({+ FAKE_SCRIPT: JSON.stringify(script),+ CONTRACT_FAKE_MAX_MS: "60000",+ COLUMNS: "160",+ LINES: "50",+ ...o.extraEnv,+ });+ t.env.FAKE_KEYLOG = join(t.tmp, "keylog.txt");+ mkdirSync(t.sockRoot, { recursive: true });+ const uuid = randomUUID();+ const id = `drv${randomBytes(3).toString("hex")}`;+ const sock = join(t.sockRoot, `magmux-${id}.sock`);+ const turnDir = mkdtempSync(join(t.tmp, "turns-"));+ const cmd = `exec ${shq(process.execPath)} ${shq(FAKE_CHILD)} --model fake-scripted --session-id ${uuid}`;+ const magmux = spawn(+ MAGMUX as string,+ ["--headless", "--no-status", "--id", id, "--sock-dir", t.sockRoot, "-e", cmd],+ { cwd: t.cwd, env: t.env, stdio: ["ignore", "ignore", "ignore"], detached: true }+ );+ magmux.on("error", () => {});+ const human = await MagmuxClient.connect(sock, { timeoutMs: 10_000 });+ const sink = new InProcessSink(undefined, undefined, () => {});+ const r: Rig = {+ t,+ uuid,+ sock,+ transcript: t.transcriptPathFor(uuid),+ turnDir,+ magmux,+ human,+ driver: null,+ sink,+ keylog: () => {+ const p = t.env.FAKE_KEYLOG as string;+ return existsSync(p) ? readFileSync(p, "utf8").split("\n").filter(Boolean) : [];+ },+ async type(text, enter = true) {+ const res = await human.request({ type: "send", pane: 0, text, typed: true, enter });+ if (!res.ok) throw new Error(`human send failed: ${res.code} ${res.error}`);+ },+ async startDriver(extra = {}) {+ const d = new InteractiveDriver({+ mode: "wrap",+ sockPath: sock,+ pane: 0,+ cwd: t.cwd,+ sessionId: uuid,+ projectsRoot: join(t.configDir, "projects"),+ turnDir,+ readAvailable: true,+ model: "fake-scripted",+ sink,+ warn: () => {},+ ...(o.binding ? { binding: o.binding } : {}),+ ...o.driver,+ ...extra,+ // merged last, so a test's own timings refine the fast defaults, never replace them+ timings: {+ tickMs: 100,+ typingHoldMs: 300,+ replStableMs: 200,+ corroborationMs: 200,+ ...o.driver?.timings,+ ...extra.timings,+ },+ });+ r.driver = d;+ await d.start();+ return d;+ },+ };+ rigs.add(r);+ if (o.startDriver !== false) await r.startDriver();+ return r;+}++async function until(pred: () => boolean, what: string, ms = 20_000): Promise<void> {+ const end = Date.now() + ms;+ while (!pred()) {+ if (Date.now() > end) throw new Error(`timed out waiting for ${what}`);+ await Bun.sleep(25);+ }+}++const sha8 = (s: string) => createHash("sha1").update(s).digest("hex").slice(0, 8);++/* ───────────────────────────── turns and the latch ───────────────────────────── */++describe.skipIf(!MAGMUX)(`interactive driver: turns ${MAGMUX ? "" : NO_MAGMUX_MESSAGE}`, () => {+ test(+ "the human witness opens turns; one settle per settled turn across ticks; sessionStart at the first empty box",+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1" }, { say: "A2" }], { binding: dbl.binding });+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ expect(dbl.starts()).toBe(1);+ await r.type("first prompt");+ await until(() => dbl.calls.length === 1, "the first settle");+ expect(dbl.calls[0]?.turn).toMatchObject({+ index: 1,+ answer: "A1",+ hookCaused: false,+ apiError: false,+ });+ expect(d.snapshot().phase).toBe("SETTLING");+ // ≥ 10 ticks and frames: the latch holds, nothing settles the turn again+ await Bun.sleep(1_200);+ expect(dbl.calls.length).toBe(1);+ dbl.calls[0]?.resolve(nothing);+ await until(() => d.snapshot().phase === "OPEN", "OPEN after the hold");+ await Bun.sleep(600);+ expect(dbl.calls.length).toBe(1);+ await r.type("second prompt");+ await until(() => dbl.calls.length === 2, "the second settle");+ expect(dbl.calls[1]?.turn).toMatchObject({ index: 2, answer: "A2", hookCaused: false });+ expect(d.snapshot()).toMatchObject({ callerAdmitted: 2, consecutiveHookTurns: 0 });+ expect(dbl.starts()).toBe(1);+ // the human's lines reached the fake; the driver typed nothing+ expect(r.keylog()).toEqual(["first prompt", "second prompt"]);+ } finally {+ await finish(r);+ }+ },+ T+ );++ test(+ "a command-line prompt written before boot-ready opens turn 1 (offset 0)",+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1" }], {+ binding: dbl.binding,+ extraEnv: { FAKE_INITIAL_PROMPT: "prompt from argv" },+ startDriver: false,+ });+ try {+ // The record and its answer are on disk BEFORE the driver exists.+ await until(+ () =>+ existsSync(r.transcript) &&+ readFileSync(r.transcript, "utf8").includes("turn_duration"),+ "the argv turn in the transcript"+ );+ // Control: a turn opened at the current size — the offset a driver would take if+ // it did not open turn 1 at 0 — never sees the prompt.+ const control = new TranscriptFollower(r.transcript, join(r.t.tmp, "none"));+ control.poll();+ control.openTurn({ index: 1, offset: control.size(), witness: { kind: "human" } });+ control.poll();+ expect(control.view().current?.acceptedAt).toBeNull();++ const d = await r.startDriver();+ await until(() => dbl.calls.length === 1, "the argv turn's settle");+ expect(dbl.calls[0]?.turn).toMatchObject({ index: 1, answer: "A1", hookCaused: false });+ expect(d.snapshot().callerAdmitted).toBe(1);+ expect(r.keylog()).toEqual([]);+ } finally {+ await finish(r);+ }+ },+ T+ );+});++/* ───────────────────────────── delivery ───────────────────────────── */++describe.skipIf(!MAGMUX)(`interactive driver: delivery ${MAGMUX ? "" : NO_MAGMUX_MESSAGE}`, () => {+ test(+ "an injection returned at settle is typed as the next turn, which settles hook-caused",+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1" }, { say: "A2" }], { binding: dbl.binding });+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ await r.type("go");+ await until(() => dbl.calls.length === 1, "settle 1");+ dbl.calls[0]?.resolve(inject("HOOK-PING"));+ await until(() => r.keylog().includes("HOOK-PING"), "the injected line");+ await until(() => dbl.calls.length === 2, "settle 2");+ expect(dbl.calls[1]?.turn).toMatchObject({ index: 2, answer: "A2", hookCaused: true });+ expect(dbl.calls[1]?.turn.consecutiveHookTurns).toBe(1);+ expect(dbl.delivered.map((x) => x.text)).toEqual(["HOOK-PING"]);+ expect(dbl.dropped).toEqual([]);+ expect(d.snapshot()).toMatchObject({ callerAdmitted: 1, consecutiveHookTurns: 1 });+ } finally {+ await finish(r);+ }+ },+ T+ );++ test(+ "a long injection goes to a turn file in the --add-dir turn dir, and the child reads it",+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1" }, {}], { binding: dbl.binding });+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ await r.type("go");+ await until(() => dbl.calls.length === 1, "settle 1");+ const long = `line one of the hook's message\n${"x".repeat(700)}\nlast line`;+ dbl.calls[0]?.resolve(inject(long));+ await until(() => dbl.calls.length === 2, "settle 2");+ const typed = r.keylog()[1] as string;+ expect(typed).toStartWith(`Your task is in the file \`${join(r.turnDir, "turn-1.md")}\``);+ expect(readdirSync(r.turnDir)).toEqual(["turn-1.md"]);+ expect(readFileSync(join(r.turnDir, "turn-1.md"), "utf8")).toBe(long);+ // the fake answers with the hash of what it READ: the whole text arrived+ expect(dbl.calls[1]?.turn).toMatchObject({+ index: 2,+ hookCaused: true,+ answer: `ANSWER fake-scripted ${sha8(long)}`,+ });+ } finally {+ await finish(r);+ }+ },+ T+ );++ test(+ "the gate: never while the box holds text; only after the box was empty and unchanged for the typing hold",+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1" }, { say: "A2" }], {+ binding: dbl.binding,+ driver: { timings: { typingHoldMs: 1_500 } },+ });+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ await r.type("go");+ await until(() => dbl.calls.length === 1, "settle 1");+ await r.type("half-typed", false);+ await Bun.sleep(400);+ dbl.calls[0]?.resolve(inject("HOOK"));+ await Bun.sleep(2_500);+ expect(dbl.delivered).toEqual([]);+ expect(r.keylog()).toEqual(["go"]);+ expect(d.snapshot().pendingHookInputs).toBe(1);+ // the human clears the box (ctrl-u): the hold restarts from that change+ await r.type("\u0015", false);+ const cleared = Date.now();+ await until(() => dbl.delivered.length === 1, "delivery after the hold");+ const waited = (dbl.delivered[0]?.at as number) - cleared;+ expect(waited).toBeGreaterThanOrEqual(1_400);+ expect(waited).toBeLessThan(4_000);+ await until(() => r.keylog().includes("HOOK"), "the injected line");+ expect(r.keylog()).not.toContain("half-typed");+ } finally {+ await finish(r);+ }+ },+ T+ );++ test(+ "a human prompt witnessed before delivery makes the pending injection stale",+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1" }, { say: "A2" }], { binding: dbl.binding });+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ await r.type("go");+ await until(() => dbl.calls.length === 1, "settle 1");+ await r.type("draft", false);+ // Let the draft reach the screen first: a keystroke inside the last frame before+ // the send is the accepted residual race (§7.5), not what this test is about.+ await Bun.sleep(600);+ dbl.calls[0]?.resolve(inject("HOOK"));+ await until(() => d.snapshot().phase === "OPEN", "OPEN");+ // the human replaces the draft and submits it+ await r.type("\u0015the human's own turn");+ await until(() => dbl.calls.length === 2, "settle 2");+ expect(dbl.calls[1]?.turn).toMatchObject({ index: 2, answer: "A2", hookCaused: false });+ dbl.calls[1]?.resolve(nothing);+ await until(() => dbl.dropped.length === 1, "the stale drop");+ expect(dbl.dropped).toEqual([{ text: "HOOK", reason: "stale" }]);+ await Bun.sleep(800);+ expect(r.keylog()).toEqual(["go", "the human's own turn"]);+ expect(dbl.delivered).toEqual([]);+ expect(d.snapshot()).toMatchObject({ callerAdmitted: 2, pendingHookInputs: 0 });+ } finally {+ await finish(r);+ }+ },+ T+ );++ test(+ "never Esc: an injection queued during a question waits, and no key but its own line is ever sent",+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1" }, { ask: "Which one?" }], { binding: dbl.binding });+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ await r.type("go");+ await until(() => dbl.calls.length === 1, "settle 1");+ dbl.calls[0]?.resolve(nothing);+ await until(() => d.snapshot().phase === "OPEN", "OPEN");+ await r.type("ask me");+ await until(() => dbl.blocked.length === 1, "sessionBlocked");+ expect(dbl.blocked[0]?.kind).toBe("question");+ const pane = dbl.pane();+ expect(pane).not.toBeNull();+ pane?.queueInjections([+ { text: "HOOK", hookIds: ["hook:t/x"], source: "sessionStart" } satisfies HoldInjection,+ ]);+ await Bun.sleep(2_500);+ expect(r.keylog()).toEqual(["go", "ask me"]);+ expect(r.keylog()).not.toContain("<ESC>");+ expect(dbl.delivered).toEqual([]);+ expect(d.snapshot()).toMatchObject({ phase: "RUNNING", pendingHookInputs: 1 });+ expect(dbl.blocked.length).toBe(1);+ } finally {+ await finish(r);+ }+ },+ T+ );++ test(+ "acceptance: an injected line whose witness never appears is dropped send_not_accepted",+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1" }, { noWitness: true }], {+ binding: dbl.binding,+ driver: { timings: { acceptMs: 1_000 } },+ });+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ await r.type("go");+ await until(() => dbl.calls.length === 1, "settle 1");+ dbl.calls[0]?.resolve(inject("HOOK"));+ await until(() => r.keylog().includes("HOOK"), "the typed line");+ expect(d.snapshot().phase).toBe("ADMITTING");+ await until(() => dbl.dropped.length === 1, "the acceptance timeout", 5_000);+ expect(dbl.dropped).toEqual([{ text: "HOOK", reason: "send_not_accepted" }]);+ expect(d.snapshot().phase).toBe("OPEN");+ expect(dbl.calls.length).toBe(1);+ } finally {+ await finish(r);+ }+ },+ T+ );+});++/* ───────────────────────────── re-wake (D23) ───────────────────────────── */++describe.skipIf(!MAGMUX)(+ `interactive driver: a lost send reply ${MAGMUX ? "" : NO_MAGMUX_MESSAGE}`,+ () => {+ /**+ * The driver's send of `text` reaches magmux (with `enter` as given here), and its+ * reply is then reported lost (`client_timeout`), as a dropped socket would.+ */+ function loseReplyOf(text: string, enter: boolean): () => void {+ const proto = MagmuxClient.prototype as unknown as {+ request(msg: Record<string, unknown>, ms?: number): Promise<unknown>;+ };+ const original = proto.request;+ proto.request = async function (this: unknown, msg: Record<string, unknown>, ms?: number) {+ if (msg.type !== "send" || msg.text !== text) return original.call(this, msg, ms);+ await original.call(this, { ...msg, enter }, ms);+ return { ok: false, code: "client_timeout", error: "no reply (test)" };+ };+ return () => {+ proto.request = original;+ };+ }++ /**+ * The driver's send of `text` is typed without its Enter, then the connection+ * closes before the reply: the old client can deliver nothing more.+ */+ function dropConnectionAfter(text: string): () => void {+ const proto = MagmuxClient.prototype as unknown as {+ request(msg: Record<string, unknown>, ms?: number): Promise<unknown>;+ };+ const original = proto.request;+ proto.request = async function (+ this: MagmuxClient,+ msg: Record<string, unknown>,+ ms?: number+ ) {+ if (msg.type !== "send" || msg.text !== text) return original.call(this, msg, ms);+ await original.call(this, { ...msg, enter: false }, ms);+ // as `onClose` does: the reply is reported lost once the socket has closed+ this.close();+ while (!this.isClosed) await Bun.sleep(5);+ return { ok: false, code: "client_lost", error: "connection closed (test)" };+ };+ return () => {+ proto.request = original;+ };+ }++ test(+ "the connection closed after the line was typed, its Enter lost: Enter goes through the new connection",+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1" }, { say: "A2" }], { binding: dbl.binding });+ const restore = dropConnectionAfter("HOOK-LOST");+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ await r.type("go");+ await until(() => dbl.calls.length === 1, "settle 1");+ dbl.calls[0]?.resolve(inject("HOOK-LOST"));+ await until(() => dbl.calls.length === 2, "settle 2", 25_000);+ expect(dbl.dropped).toEqual([]);+ expect(dbl.calls[1]?.turn).toMatchObject({ index: 2, answer: "A2", hookCaused: true });+ expect(r.keylog()).toEqual(["go", "HOOK-LOST"]);+ } finally {+ restore();+ await finish(r);+ }+ },+ T+ );++ for (const enter of [true, false]) {+ test(+ `the line was typed${enter ? " and entered" : ", its Enter lost"}: the injection is accepted as the hook's turn`,+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1" }, { say: "A2" }], { binding: dbl.binding });+ const restore = loseReplyOf("HOOK-LOST", enter);+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ await r.type("go");+ await until(() => dbl.calls.length === 1, "settle 1");+ dbl.calls[0]?.resolve(inject("HOOK-LOST"));+ await until(() => dbl.calls.length === 2, "settle 2", 25_000);+ expect(dbl.dropped).toEqual([]);+ expect(dbl.calls[1]?.turn).toMatchObject({ index: 2, answer: "A2", hookCaused: true });+ expect(d.snapshot()).toMatchObject({ callerAdmitted: 1, consecutiveHookTurns: 1 });+ expect(r.keylog()).toEqual(["go", "HOOK-LOST"]);+ } finally {+ restore();+ await finish(r);+ }+ },+ T+ );+ }+ }+);++describe.skipIf(!MAGMUX)(`interactive driver: re-wake ${MAGMUX ? "" : NO_MAGMUX_MESSAGE}`, () => {+ test(+ "a notification during a pending injection neither drops it stale nor resets the cap; the turn settles again with its index",+ async () => {+ const dbl = controlled();+ const r = await rig(+ [{ say: "A1", rewake: { delayMs: 1_200, say: "A1b" } }, { say: "A2" }, { say: "A3" }],+ { binding: dbl.binding, driver: { timings: { typingHoldMs: 3_500 } } }+ );+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ await r.type("go");+ await until(() => dbl.calls.length === 1, "settle 1");+ dbl.calls[0]?.resolve(inject("HOOK"));+ await until(() => d.snapshot().phase === "OPEN", "OPEN with the injection pending");+ expect(d.snapshot().pendingHookInputs).toBe(1);+ // the background notification wakes the model: the SAME turn settles again+ await until(() => dbl.calls.length === 2, "the re-woken turn's settle");+ expect(dbl.calls[1]?.turn).toMatchObject({ index: 1, hookCaused: false });+ expect(dbl.calls[1]?.turn.answer).toContain("A1b");+ expect(d.snapshot()).toMatchObject({ callerAdmitted: 1, consecutiveHookTurns: 0 });+ expect(dbl.dropped).toEqual([]);+ dbl.calls[1]?.resolve(nothing);+ // the injection survived and is delivered once the gate opens+ await until(() => r.keylog().includes("HOOK"), "the injection", 10_000);+ await until(() => dbl.calls.length === 3, "the hook turn's settle");+ expect(dbl.calls[2]?.turn).toMatchObject({ index: 2, hookCaused: true, answer: "A2" });+ expect(dbl.dropped).toEqual([]);+ } finally {+ await finish(r);+ }+ },+ T+ );++ test(+ "a re-wake DURING the hold aborts it with reason rewake; the same turn is held again",+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1", rewake: { delayMs: 1_000, say: "A1b" } }], {+ binding: dbl.binding,+ });+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ await r.type("go");+ await until(() => dbl.calls.length === 1, "settle 1");+ await until(() => dbl.calls[0]?.signal.aborted === true, "the hold's abort");+ expect(dbl.calls[0]?.signal.reason).toBe("rewake");+ await until(() => dbl.calls.length === 2, "the second hold of turn 1");+ expect(dbl.calls[1]?.turn.index).toBe(1);+ // a late result of the abandoned hold changes nothing+ dbl.calls[0]?.resolve(inject("LATE"));+ dbl.calls[1]?.resolve(nothing);+ await Bun.sleep(1_000);+ expect(r.keylog()).toEqual(["go"]);+ expect(d.snapshot()).toMatchObject({ phase: "OPEN", callerAdmitted: 1 });+ } finally {+ await finish(r);+ }+ },+ T+ );++ test(+ "a human prompt DURING the hold aborts it with reason caller",+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1" }, { say: "A2" }], { binding: dbl.binding });+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ await r.type("go");+ await until(() => dbl.calls.length === 1, "settle 1");+ await r.type("again");+ await until(() => dbl.calls[0]?.signal.aborted === true, "the hold's abort");+ expect(dbl.calls[0]?.signal.reason).toBe("caller");+ dbl.calls[0]?.resolve(inject("HOOK"));+ await until(() => dbl.calls.length === 2, "settle 2");+ expect(dbl.calls[1]?.turn).toMatchObject({ index: 2, answer: "A2", hookCaused: false });+ dbl.calls[1]?.resolve(nothing);+ await Bun.sleep(800);+ expect(r.keylog()).toEqual(["go", "again"]);+ } finally {+ await finish(r);+ }+ },+ T+ );++ test(+ "a re-wake already in the transcript when the hold's result arrives: nothing is typed; the result is abandoned rewake",+ async () => {+ const dbl = controlled();+ // the fake starts its re-wake when this file exists: after the test saw the hold+ const gate = join(tmpdir(), `claudish-rewake-gate-${randomUUID()}`);+ const r = await rig(+ [+ { say: "A1", rewake: { gateFile: gate, delayMs: 100, quietMs: 3_000, say: "A1-B" } },+ { say: "A2" },+ ],+ { binding: dbl.binding }+ );+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ await r.type("go");+ await until(() => dbl.calls.length === 1, "settle 1");+ writeFileSync(gate, "");+ // The re-wake's records land with no redraw: the screen still shows the idle box,+ // and the driver's last poll is older than them. Resolve the instant they exist.+ const end = Date.now() + 20_000;+ while (!readFileSync(r.transcript, "utf8").includes("A1-B")) {+ if (Date.now() > end) throw new Error("timed out waiting for the re-wake's records");+ await Bun.sleep(2);+ }+ dbl.calls[0]?.resolve(inject("HOOK-LATE"));+ await until(+ () => dbl.calls.length === 2 || r.keylog().includes("HOOK-LATE"),+ "the re-woken turn's settle, or the injection typed over it"+ );+ expect(r.keylog()).toEqual(["go"]);+ // Either the result came back (abandoned rewake), or, rarely, the driver's own+ // backstop poll saw the records first and ended the hold before it arrived.+ if ((dbl.calls[0]?.signal.reason as string | undefined) !== "rewake")+ expect(dbl.abandoned).toEqual([{ text: "HOOK-LATE", reason: "rewake" }]);+ expect(dbl.delivered).toEqual([]);+ expect(dbl.calls[1]?.turn.index).toBe(1);+ expect(dbl.calls[1]?.turn.answer).toContain("A1-B");+ expect(d.snapshot()).toMatchObject({ callerAdmitted: 1, consecutiveHookTurns: 0 });+ } finally {+ rmSync(gate, { force: true });+ await finish(r);+ }+ },+ T+ );+});++/* ───────────────────────────── the session id from requests ───────────────────────────── */++describe.skipIf(!MAGMUX)(+ `interactive driver: session from requests ${MAGMUX ? "" : NO_MAGMUX_MESSAGE}`,+ () => {+ test(+ "--resume: no id at boot; the first request's id opens the turn at its last human prompt",+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1", delayMs: 400 }, { say: "A2" }], {+ binding: dbl.binding,+ driver: { sessionId: null },+ });+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ expect(d.snapshot()).toMatchObject({ phase: "NONE", sessionId: null });+ await r.type("resumed prompt");+ // Claude Code writes the prompt, THEN sends the request that names the session.+ await until(+ () =>+ existsSync(r.transcript) &&+ readFileSync(r.transcript, "utf8").includes("resumed prompt"),+ "the prompt record"+ );+ r.sink.noteSessionId(r.uuid);+ expect(d.snapshot().sessionId).toBe(r.uuid);+ await until(() => dbl.calls.length === 1, "the turn's settle");+ expect(dbl.calls[0]?.turn).toMatchObject({ index: 1, answer: "A1", hookCaused: false });+ dbl.calls[0]?.resolve(nothing);+ // a late request naming no other session changes nothing; the next turn is followed+ r.sink.noteSessionId(r.uuid);+ await r.type("next");+ await until(() => dbl.calls.length === 2, "the next settle");+ expect(dbl.calls[1]?.turn).toMatchObject({ index: 2, answer: "A2" });+ } finally {+ await finish(r);+ }+ },+ T+ );++ test(+ "an id whose transcript never appears is not followed",+ async () => {+ const dbl = controlled();+ const r = await rig([{ say: "A1" }], {+ binding: dbl.binding,+ driver: { timings: { tickMs: 100 } },+ });+ try {+ const d = r.driver as InteractiveDriver;+ await until(() => d.snapshot().booted, "boot");+ r.sink.noteSessionId(randomUUID());+ await Bun.sleep(500);+ expect(d.snapshot().sessionId).toBe(r.uuid);+ await r.type("still followed");+ await until(() => dbl.calls.length === 1, "the settle on the original session");+ } finally {+ await finish(r);+ }+ },+ T+ );+ }+);++/* ───────────────────────────── real binding: sessionStart, sessionEnd ───────────────────────────── */++describe.skipIf(!MAGMUX)(+ `interactive driver: real binding ${MAGMUX ? "" : NO_MAGMUX_MESSAGE}`,+ () => {+ test(+ "a sessionStart injection is typed at the first idle; stop() fires sessionEnd and waits for it",+ async () => {+ let endSeen = null as { state: string; exitCode: number | null } | null;+ const { engine, journal } = engineOf(+ {+ id: "start",+ on: { sessionStart: () => [{ type: "injectUserTurn", text: "START-PING" }] },+ },+ {+ id: "end",+ on: {+ sessionEnd: async (ctx) => {+ await Bun.sleep(300);+ endSeen = { state: ctx.outcome.state, exitCode: ctx.outcome.exitCode };+ return [];+ },+ },+ }+ );+ const r = await rig([{ say: "S1" }], { startDriver: false });+ try {+ const d = await r.startDriver({ engine });+ await until(() => r.keylog().includes("START-PING"), "the sessionStart injection");+ await until(() => d.snapshot().settles === 1, "its turn's settle");+ expect(d.snapshot()).toMatchObject({ consecutiveHookTurns: 1, callerAdmitted: 0 });+ expect(+ journal.some(+ (j) =>+ j.hookId === "hook:t/start" &&+ j.decision === "delivered" &&+ j.action === "injectUserTurn"+ )+ ).toBe(true);+ const t0 = Date.now();+ await d.stop({ state: "COMPLETED", reason: null, exitCode: 0 });+ expect(endSeen).toEqual({ state: "COMPLETED", exitCode: 0 });+ expect(Date.now() - t0).toBeLessThan(1_500);+ } finally {+ await finish(r);+ }+ },+ T+ );++ test(+ "stop() waits at most 1.5 s for a sessionEnd hook that never returns",+ async () => {+ const { engine } = engineOf({+ id: "hang",+ on: { sessionEnd: () => new Promise(() => {}) },+ });+ const r = await rig([], { startDriver: false });+ try {+ const d = await r.startDriver({ engine });+ await until(() => d.snapshot().booted, "boot");+ const t0 = Date.now();+ await d.stop({ state: "COMPLETED", reason: null, exitCode: 0 });+ const took = Date.now() - t0;+ expect(took).toBeGreaterThanOrEqual(1_000);+ expect(took).toBeLessThan(2_500);+ } finally {+ await finish(r);+ }+ },+ T+ );+ }+);++/* ───────────────────────────── ambient: the own pane ───────────────────────────── */++describe.skipIf(!MAGMUX)(`ambient: own pane ${MAGMUX ? "" : NO_MAGMUX_MESSAGE}`, () => {+ test(+ "found via list + ancestry: pane 1 of a grid, not 0, in both layouts",+ async () => {+ const t = makePaneTestEnv();+ mkdirSync(t.sockRoot, { recursive: true });+ const procs: ChildProcess[] = [];+ try {+ for (const layout of ["exec", "child-of-shell"] as const) {+ const out = join(t.tmp, `probe-${layout}.json`);+ const run = `${shq(process.execPath)} ${shq(PROBE)} ${shq(out)}`;+ const id = `own${randomBytes(3).toString("hex")}`;+ const m = spawn(+ MAGMUX as string,+ [+ "--headless",+ "--no-status",+ "--id",+ id,+ "--sock-dir",+ t.sockRoot,+ "-e",+ "sleep 30",+ "-e",+ // (a) the probe IS the pane process; (b) a shell stays the pane process+ layout === "exec" ? `exec ${run}` : `${run}; sleep 1`,+ ],+ { cwd: t.cwd, env: t.env, stdio: "ignore", detached: true }+ );+ m.on("error", () => {});+ procs.push(m);+ await until(() => existsSync(out), `the probe's answer (${layout})`);+ const got = JSON.parse(readFileSync(out, "utf8"));+ expect(got.pane).toBe(1);+ expect(got.listed.panes.find((p: { pane: number }) => p.pane === 0).pid).not.toBe(+ got.pid+ );+ }+ } finally {+ for (const m of procs)+ try {+ if (m.pid) process.kill(-m.pid, "SIGKILL");+ } catch {+ // gone+ }+ killLeftovers({ sockRoot: t.sockRoot });+ t.cleanup();+ }+ },+ T+ );+});++/* ───────────────────────────── end to end: claudish -i ───────────────────────────── */++/**+ * The hermetic twin of live check 1: the REAL `claudish -i` runs inside a magmux pane,+ * so it is in AMBIENT mode (the pane exports `MAGMUX_SOCK`): it mints the session id,+ * adds the turn dir, installs the in-process sink, finds its own pane by ancestry and+ * starts the driver. Claude Code is the proxied fake; its every turn goes through+ * claudish's proxy to the stub upstream. The child's hooks come from `CLAUDISH_CONFIG`:+ * `responseEnd` annotates each response (through the in-process sink), and+ * `sessionIdle` injects HOOK-PING once, only when that annotation arrived.+ */+const E2E_HOOKS = (endMarker: string) => `import { writeFileSync } from "node:fs";+export default [{+ apiVersion: 1,+ id: "ping",+ on: {+ responseEnd(ctx) {+ return [{ type: "annotateTurn", key: "seen", value: ctx.response.text }];+ },+ sessionIdle(ctx) {+ if (ctx.turn.hookCaused) return [];+ if (!ctx.turn.annotations.some((a) => a.key === "seen" && a.value === "STUB-ONE")) return [];+ return [{ type: "injectUserTurn", text: "HOOK-PING" }];+ },+ sessionEnd(ctx) {+ writeFileSync(${JSON.stringify(endMarker)}, JSON.stringify({ session: ctx.session, outcome: ctx.outcome }));+ return [];+ },+ },+}];+`;++describe.skipIf(!MAGMUX)(`end to end: claudish -i ${MAGMUX ? "" : NO_MAGMUX_MESSAGE}`, () => {+ let stub: StubUpstream | null = null;+ afterAll(() => stub?.stop());++ test("ambient claudish -i: a sessionIdle injection fed by a responseEnd annotation becomes the next turn", async () => {+ stub = startStubUpstream({+ format: "openai-sse",+ script: [{ parts: [{ text: "STUB-ONE" }] }, { parts: [{ text: "STUB-TWO" }] }],+ });+ const t = makePaneTestEnv({ COLUMNS: "160", LINES: "50", CONTRACT_FAKE_MAX_MS: "80000" });+ mkdirSync(t.sockRoot, { recursive: true });+ const endMarker = join(t.tmp, "session-end.json");+ const module = join(t.tmp, "e2e-hooks.js");+ writeFileSync(module, E2E_HOOKS(endMarker));+ const config = join(t.tmp, "claudish-config.json");+ writeFileSync(+ config,+ JSON.stringify({ ...stubEndpointConfig(stub), hooks: { modules: [module] } }, null, 2)+ );+ const dump = join(t.tmp, "fake-claude-dump.json");+ Object.assign(t.env, {+ CLAUDE_PATH: writeFakeClaudeWrapper(t.tmp),+ CLAUDISH_CONFIG: config,+ FAKE_CLAUDE_PROXY: "1",+ FAKE_CLAUDE_DUMP: dump,+ FAKE_KEYLOG: join(t.tmp, "keylog.txt"),+ });+ const id = `e2e${randomBytes(3).toString("hex")}`;+ const sock = join(t.sockRoot, `magmux-${id}.sock`);+ const cmd = `exec ${shq(process.execPath)} --no-env-file ${shq(INDEX)} -i --model stub@fake-model -y --quiet --no-recovery`;+ const m = spawn(+ MAGMUX as string,+ ["--headless", "--no-status", "--id", id, "--sock-dir", t.sockRoot, "-e", cmd],+ { cwd: t.cwd, env: t.env, stdio: "ignore", detached: true }+ );+ m.on("error", () => {});+ const human = await MagmuxClient.connect(sock, { timeoutMs: 10_000 });+ const keylog = () => {+ const p = t.env.FAKE_KEYLOG as string;+ return existsSync(p) ? readFileSync(p, "utf8").split("\n").filter(Boolean) : [];+ };+ try {+ // Claude Code's argv: the minted id and the turn dir lead, `--settings` ends the list+ await until(() => existsSync(dump), "the fake Claude Code's argv dump", 30_000);+ const argv = JSON.parse(readFileSync(dump, "utf8")).argv as string[];+ expect(argv[0]).toBe("--session-id");+ const sid = argv[1] as string;+ expect(sid).toMatch(/^[0-9a-f-]{36}$/);+ expect(argv[2]).toBe("--add-dir");+ expect(argv[4]).toBe("--settings");+ // wait for the REPL, then type as the human+ await Bun.sleep(1_500);+ const sent = await human.request({+ type: "send",+ pane: 0,+ text: "Reply first.",+ typed: true,+ enter: true,+ });+ expect(sent.ok).toBe(true);+ await until(() => keylog().includes("HOOK-PING"), "the injected turn", 40_000);+ const transcript = t.transcriptPathFor(sid);+ await until(+ () => existsSync(transcript) && readFileSync(transcript, "utf8").includes("STUB-TWO"),+ "the injected turn's answer",+ 30_000+ );+ const records = readFileSync(transcript, "utf8")+ .split("\n")+ .filter(Boolean)+ .map((l) => JSON.parse(l));+ const texts = records.map((r) =>+ r.type === "user"+ ? `user:${typeof r.message?.content === "string" ? r.message.content : ""}`+ : r.type === "assistant"+ ? `assistant:${(r.message?.content ?? []).map((b: { text?: string }) => b.text ?? "").join("")}`+ : null+ );+ const order = texts.filter((x): x is string => x !== null);+ expect(order).toEqual([+ "user:Reply first.",+ "assistant:STUB-ONE",+ "user:HOOK-PING",+ "assistant:STUB-TWO",+ ]);+ expect(stub.requests.length).toBe(2);+ expect(keylog()).toEqual(["Reply first.", "HOOK-PING"]);+ // the human quits: sessionEnd runs before claudish exits+ await human.request({ type: "send", pane: 0, text: "/exit", typed: true, enter: true });+ await until(() => existsSync(endMarker), "sessionEnd", 15_000);+ const end = JSON.parse(readFileSync(endMarker, "utf8"));+ expect(end.outcome).toEqual({ state: "COMPLETED", reason: null, exitCode: 0 });+ expect(end.session).toMatchObject({ kind: "interactive", id: sid, claudeSessionId: sid });+ } finally {+ human.close();+ try {+ if (m.pid) process.kill(-m.pid, "SIGKILL");+ } catch {+ // gone+ }+ killLeftovers({ sockRoot: t.sockRoot });+ t.cleanup();+ }+ }, 90_000);+});diff --git a/packages/cli/src/hooks/session/interactive-driver.ts b/packages/cli/src/hooks/session/interactive-driver.tsnew file mode 100644index 00000000..65c5a7b7--- /dev/null+++ b/packages/cli/src/hooks/session/interactive-driver.ts@@ -0,0 +1,1116 @@+/**+ * `InteractiveDriver`: session hooks for `claudish -i` (hook-system architecture §7.5).+ *+ * In `wrap` mode claudish launched a visible `-w` magmux and Claude Code is pane 0. In+ * `ambient` mode claudish runs inside a magmux someone else started (a `team --grid`+ * pane, a pane the user opened) and its pane is found by process ancestry+ * (`pane/own-pane.ts`). Either way the driver is a SECOND client on that socket (S2,+ * measured: `watch` frames and `send {typed:true}` both work there), and it is the only+ * part of claudish that types into the human's session.+ *+ * What it does, per turn:+ *+ * - **Turns.** One `TranscriptFollower` on the session's transcript. The first turn+ * opens at offset 0 with the HUMAN witness, so a prompt given on the command line,+ * which Claude Code may write before the REPL is drawn, is witnessed. After each+ * settle the next turn opens at the current offset with the same witness; an+ * injected turn uses the `text` witness of the line it typed. The human witness is+ * matched by provenance (`isHumanPrompt`): a task notification never matches it,+ * so a background re-wake (D23) stays the turn it woke — it never makes a pending+ * injection stale and never resets the cap.+ * - **Settle.** `decideSettle`, with the same screen facts as a pane. The phase is the+ * latch: one `binding.settle()` per settled turn, `SETTLING` while it runs, and a+ * re-wake or a human prompt during the hold ends it (`rewake`, `caller`).+ * - **Delivery gate.** An injection is typed only when the turn is idle, the box is+ * drawn, empty, and has not changed for `typingHoldMs` (1,500 ms), no dialog or+ * working row shows, no menu is open, and the recovery banner holds no lease. It is+ * ONE `send {typed:true, enter:true}` of a plain line, or of the instruction to Read+ * a turn file in the `--add-dir` turn directory. Never Esc, never into a dialog. The+ * residual race — a keystroke landing between the last check and the send — is+ * accepted: magmux has no atomic "send if empty".+ * - **Acceptance.** The typed line's witness must appear within `acceptMs` (30 s),+ * else the injection is dropped `send_not_accepted`.+ * - **Session events.** `sessionStart` at the first empty REPL box; `sessionBlocked`+ * on a question or a permission dialog; `sessionEnd` from `stop()`, which the+ * launcher awaits for at most 1.5 s.+ * - **Session id.** The minted `--session-id` from boot; then whatever id the proxy's+ * requests carry (`InProcessSink.onSessionId`), so `/clear` retargets the follower+ * and a `--resume`d launch finds its transcript. Until an id is known the driver+ * opens no turn and types nothing; queued injections wait under the 10-minute rule.+ */++import { existsSync, statSync } from "node:fs";+import { join } from "node:path";+import { log, logStderr } from "../../logger.js";+import { MagmuxClient } from "../../pane/magmux-client.js";+import { findOwnPane } from "../../pane/own-pane.js";+import {+ type Delivery,+ deliveryRefusal,+ planDelivery,+ writeTurnFile,+} from "../../pane/prompt-delivery.js";+import {+ choiceDialog,+ hasChoiceDialog,+ inputBox,+ isWorking,+ readBoot,+} from "../../pane/screen-classifier.js";+import {+ type MagmuxFrame,+ type ScreenState,+ applyFrame,+ emptyScreen,+} from "../../pane/screen-model.js";+import {+ CORROBORATION_MS,+ SECONDARY_QUIET_MS,+ type ScreenFacts,+ decideSettle,+} from "../../pane/settle-rule.js";+import {+ TranscriptFollower,+ type TranscriptView,+ type TurnDelivery,+ type TurnView,+ type Witness,+ lastHumanPromptOffset,+} from "../../pane/transcript-follower.js";+import { transcriptPathFor } from "../../session/session-discovery.js";+import type { HookEngine } from "../engine.js";+import {+ type HookQueueItem,+ type InjectionQueueState,+ afterAdmission,+ emptyQueueState,+ hookCount,+ next as nextQueueDecision,+} from "../injection/queue.js";+import { type InProcessSink, reportInjectionUnavailable } from "../injection/sinks.js";+import type { SessionInfo } from "../public.js";+import {+ type HoldAbortReason,+ type HoldInjection,+ type HoldResult,+ type SessionHookBinding,+ createSessionHookBinding,+} from "./binding.js";++/** The box must have been empty and unchanged this long before an injection is typed. */+export const TYPING_HOLD_MS = 1_500;+/** The typed line's witness must appear within this long. */+export const ACCEPT_TIMEOUT_MS = 30_000;+/** `sessionEnd` hooks get at most this long before the launcher shuts its proxy down. */+export const SESSION_END_WAIT_MS = 1_500;+const TICK_MS = 250;+const WATCH_FPS = 4;+/** The REPL box must read empty this long before `sessionStart` fires. */+const REPL_STABLE_MS = 500;+/** How long a session id learned from a request may wait for its transcript to appear. */+const RETARGET_WAIT_MS = 10_000;+/** How long a lost send reply waits for `reconnect()` before the admission fails. */+const RECONNECT_WAIT_MS = 10_000;+const DEFAULT_MAX_CONSECUTIVE = 3;++/* ───────────────────────────── the turn phase ───────────────────────────── */++/**+ * The driver's turn phase. Unlike a pane it never ends the session: Claude Code is the+ * human's, and claudish only waits, reads and (rarely) types.+ *+ * NONE no session id known yet: nothing is followed+ * OPEN a human-witness turn is open and not yet accepted: the session is idle+ * ADMITTING an injection was typed; its text witness is awaited+ * RUNNING the turn was accepted and has not settled+ * SETTLING settled and recorded; `binding.settle()` runs (the latch)+ * STOPPED Claude Code exited, or the launcher stopped the driver+ */+export type DriverPhase = "NONE" | "OPEN" | "ADMITTING" | "RUNNING" | "SETTLING" | "STOPPED";++type DriverEvent =+ | "session_known"+ | "human_accepted"+ | "deliver"+ | "hook_accepted"+ | "admit_failed"+ | "settle_open"+ | "settle_hold"+ | "hold_done"+ | "rewake"+ | "retarget"+ | "stop";++const EDGES = {+ NONE: { session_known: "OPEN", stop: "STOPPED" },+ OPEN: {+ human_accepted: "RUNNING",+ deliver: "ADMITTING",+ rewake: "RUNNING",+ retarget: "OPEN",+ stop: "STOPPED",+ },+ ADMITTING: {+ hook_accepted: "RUNNING",+ admit_failed: "OPEN",+ retarget: "OPEN",+ stop: "STOPPED",+ },+ RUNNING: { settle_open: "OPEN", settle_hold: "SETTLING", retarget: "OPEN", stop: "STOPPED" },+ SETTLING: {+ hold_done: "OPEN",+ rewake: "RUNNING",+ human_accepted: "RUNNING",+ retarget: "OPEN",+ stop: "STOPPED",+ },+ STOPPED: {},+} as const satisfies Record<DriverPhase, Partial<Record<DriverEvent, DriverPhase>>>;++/** The next phase, or null when `ev` is not legal from `phase`. */+export function nextDriverPhase(phase: DriverPhase, ev: DriverEvent): DriverPhase | null {+ const row = EDGES[phase] as Partial<Record<DriverEvent, DriverPhase>>;+ return row[ev] ?? null;+}++/* ───────────────────────────── options ───────────────────────────── */++export interface InteractiveDriverOptions {+ mode: "wrap" | "ambient";+ /** the wrap's `--id` control socket, or the ambient `MAGMUX_SOCK` */+ sockPath: string;+ /** Claude Code's pane: 0 in a wrap. Absent → found by ancestry (ambient). */+ pane?: number;+ /** test seam for the ancestry search; `list` returns the `list` reply's result */+ findPane?: (list: () => Promise<unknown>) => Promise<number | null>;+ /** Claude Code's working directory (the transcript slug is its realpath) */+ cwd: string;+ /** the minted or user-given `--session-id`; null after `--resume`/`--continue`/`--fork-session` */+ sessionId: string | null;+ /** Claude Code's projects directory (`projectsDir(childEnv)`) */+ projectsRoot: string;+ /** the `--add-dir` turn directory (0700) where long injections are written */+ turnDir: string;+ /** false when Claude Code's flags remove the Read tool */+ readAvailable: boolean;+ /** the model as the user asked for it (`ctx.session.model`) */+ model: string;+ /** the launcher's in-process sink: proxy-event lines and request session ids */+ sink: InProcessSink;+ /** the engine a binding is built over; ignored when `binding` is given */+ engine?: HookEngine;+ /** test seam: any `SessionHookBinding` */+ binding?: SessionHookBinding;+ /** the recovery banner holds the pane (`recoveryOverlayHeld`) */+ overlayHeld?: () => boolean;+ /** stderr, for the one-line "unavailable" notices */+ warn?: (line: string) => void;+ /** test seams; production passes none */+ timings?: {+ tickMs?: number;+ typingHoldMs?: number;+ acceptMs?: number;+ replStableMs?: number;+ secondaryQuietMs?: number;+ corroborationMs?: number;+ connectMs?: number;+ };+}++/** What the driver can tell a test or the debug log about itself. */+export interface DriverSnapshot {+ phase: DriverPhase;+ pane: number | null;+ sessionId: string | null;+ booted: boolean;+ turnIndex: number;+ settles: number;+ callerAdmitted: number;+ consecutiveHookTurns: number;+ pendingHookInputs: number;+ available: boolean;+}++interface OpenTurn {+ index: number;+ offset: number;+ witness: Witness;+ delivery: TurnDelivery | null;+ hookCaused: boolean;+}++interface Admission {+ item: HookQueueItem;+ startedAt: number;+}++/* ───────────────────────────── the driver ───────────────────────────── */++export class InteractiveDriver {+ private phase: DriverPhase = "NONE";+ private readonly o: InteractiveDriverOptions;+ private readonly binding: SessionHookBinding;+ private readonly warn: (line: string) => void;+ private client: MagmuxClient | null = null;+ private pane: number | null;+ private screen: ScreenState = emptyScreen(160, 50);+ private framePending = false;+ private follower: TranscriptFollower | null = null;+ private sessionId: string | null;+ /** ids this driver followed and left (`/clear`): a late request naming one is ignored */+ private readonly retired = new Set<string>();+ private pendingSid: { id: string; since: number } | null = null;++ private q: InjectionQueueState;+ private current: OpenTurn | null = null;+ /** the turn that settled last, kept so a re-wake can re-open it */+ private settledTurn: OpenTurn | null = null;+ private lastAcceptedIndex = 0;+ private fileSeq = 0;+ private admission: Admission | null = null;+ private settles = 0;+ private blockedToolId: string | null = null;++ private booted = false;+ private bootKind: string | null = null;+ private bootKindSince = 0;+ private startCallerSeq = 1;++ private holdGen = 0;+ private holdController: AbortController | null = null;+ private holdWatchdog: ReturnType<typeof setTimeout> | null = null;++ private lastBoxKey: string | null = null;+ private boxChangedAt = Date.now();+ private lastPollAt = 0;+ private lastChatOffset: number | null = null;+ private lastChatSeenAt = Date.now();+ private readonly startedAt = Date.now();++ private ticker: ReturnType<typeof setInterval> | null = null;+ private unsubscribeSession: (() => void) | null = null;+ private unavailable = false;+ private stopping: Promise<void> | null = null;++ constructor(o: InteractiveDriverOptions) {+ this.o = o;+ this.warn = o.warn ?? logStderr;+ this.pane = o.pane ?? null;+ this.sessionId = o.sessionId;+ const session: SessionInfo = {+ kind: "interactive",+ role: null,+ id: o.sessionId ?? "",+ claudeSessionId: o.sessionId,+ model: o.model,+ cwd: o.cwd,+ shape: "interactive",+ injection: "available",+ };+ if (o.binding) this.binding = o.binding;+ else if (o.engine) this.binding = createSessionHookBinding(o.engine, session, o.sink.inbox);+ else throw new Error("InteractiveDriver needs an engine or a binding");+ this.q = emptyQueueState(this.binding.maxConsecutive ?? DEFAULT_MAX_CONSECUTIVE);+ this.binding.attach?.({+ queueInjections: (items) => this.step(() => this.queueInjections(items)),+ });+ }++ /* ───────────────────────────── lifecycle ───────────────────────────── */++ /**+ * Connect, find the pane, subscribe to its frames and start following. Never throws:+ * a driver that cannot reach its pane makes injection `unavailable` (one stderr line)+ * and still fires `sessionStart` and `sessionEnd`.+ */+ async start(): Promise<void> {+ this.unsubscribeSession = this.o.sink.onSessionId((sid) =>+ this.step(() => this.noteRequestSession(sid))+ );+ if (this.sessionId) this.follow(this.sessionId, 0);+ try {+ this.client = await MagmuxClient.connect(this.o.sockPath, {+ timeoutMs: this.o.timings?.connectMs ?? 10_000,+ alive: () => this.phase !== "STOPPED",+ });+ } catch (err) {+ this.goUnavailable(`cannot reach magmux at ${this.o.sockPath}: ${String(err)}`);+ return;+ }+ if (this.currentPhase() === "STOPPED") {+ this.client.close();+ return;+ }+ if (this.pane === null) {+ const client = this.client;+ const list = async () => {+ const r = await client.request({ type: "list" });+ return r.ok ? r.result : null;+ };+ this.pane = await (this.o.findPane ?? ((l) => findOwnPane(l)))(list);+ if (this.pane === null) {+ this.goUnavailable("this claudish's magmux pane was not found");+ return;+ }+ }+ await this.subscribe(this.client);+ this.ticker = setInterval(() => this.step(() => this.evaluate()), this.ms("tickMs", TICK_MS));+ log(+ `[hooks] interactive driver on magmux pane ${this.pane} (${this.o.mode}), session ${this.sessionId ?? "(not known yet)"}`+ );+ }++ /**+ * Claude Code exited (or the launcher is shutting down): end any hold, drop what is+ * queued, fire `sessionEnd` and wait for it at most `SESSION_END_WAIT_MS`. Idempotent.+ */+ stop(outcome: { state: string; reason: string | null; exitCode: number | null }): Promise<void> {+ if (this.stopping) return this.stopping;+ this.stopping = (async () => {+ this.step(() => {+ if (this.phase === "SETTLING") this.endHold("terminal");+ this.admission = null;+ this.transition("stop");+ for (const item of this.q.items)+ if (item.kind === "hook") this.dropInjection(item, "session_ended");+ this.q.items = [];+ });+ if (this.ticker) clearInterval(this.ticker);+ this.ticker = null;+ this.unsubscribeSession?.();+ this.o.sink.markUnavailable();+ try {+ this.binding.fireEnd(outcome);+ } catch {+ // a binding's failure must not hold the launcher+ }+ await raceTimeout(this.binding.endSettled?.() ?? Promise.resolve(), SESSION_END_WAIT_MS);+ // what no settle took is journaled before the launcher shuts its proxy down+ try {+ this.binding.sweepInbox?.();+ } catch {+ // journaling never holds the launcher+ }+ this.client?.close();+ this.client = null;+ })();+ return this.stopping;+ }++ snapshot(): DriverSnapshot {+ return {+ phase: this.phase,+ pane: this.pane,+ sessionId: this.sessionId,+ booted: this.booted,+ turnIndex: this.current?.index ?? this.lastAcceptedIndex,+ settles: this.settles,+ callerAdmitted: this.q.callerAdmitted,+ consecutiveHookTurns: this.q.consecutiveHookTurns,+ pendingHookInputs: hookCount(this.q),+ available: !this.unavailable,+ };+ }++ private goUnavailable(why: string): void {+ this.unavailable = true;+ this.o.sink.markUnavailable();+ log(`[hooks] interactive driver: ${why}; hook injection is unavailable for this session`);+ reportInjectionUnavailable(this.warn);+ this.binding.updateSession?.({ injection: "unavailable" });+ // No screen to find the REPL box on: the session started when Claude Code did.+ this.fireStart();+ }++ private async subscribe(client: MagmuxClient): Promise<void> {+ const pane = this.pane as number;+ client.on("frame", (f: MagmuxFrame) => {+ if (f.pane !== undefined && f.pane !== pane) return;+ this.screen = applyFrame(this.screen, f);+ this.framePending = true;+ this.noteBox();+ this.step(() => this.evaluate());+ });+ client.on("disconnected", () => {+ if (this.client === client) this.client = null;+ if (this.phase !== "STOPPED") void this.reconnect();+ });+ const r = await client.request({ type: "watch", pane, mode: "frames", fps: WATCH_FPS });+ if (!r.ok) log(`[hooks] interactive driver: watch pane ${pane} refused: ${r.code} ${r.error}`);+ }++ /** magmux keeps its panes when a client leaves: redial while the session lives. */+ private async reconnect(): Promise<void> {+ let delay = 100;+ for (let i = 0; i < 20 && this.phase !== "STOPPED" && !this.client; i++) {+ await Bun.sleep(delay);+ try {+ const c = await MagmuxClient.dial(this.o.sockPath);+ if (this.currentPhase() === "STOPPED") {+ c.close();+ return;+ }+ this.client = c;+ await this.subscribe(c);+ return;+ } catch {+ delay = Math.min(1_000, delay * 2);+ }+ }+ }++ /* ───────────────────────────── the step ───────────────────────────── */++ private step(fn: () => void): void {+ try {+ fn();+ } catch (err) {+ // The driver must never take the launcher down with it.+ log(+ `[hooks] interactive driver step failed: ${err instanceof Error ? err.stack : String(err)}`+ );+ }+ }++ /** The phase, read through a call so a narrowing from an earlier check never sticks. */+ private currentPhase(): DriverPhase {+ return this.phase;+ }++ private transition(ev: DriverEvent): boolean {+ const next = nextDriverPhase(this.phase, ev);+ if (!next) {+ log(`[hooks] interactive driver: illegal ${this.phase} --${ev}`);+ return false;+ }+ this.phase = next;+ return true;+ }++ private ms(key: keyof NonNullable<InteractiveDriverOptions["timings"]>, dflt: number): number {+ return this.o.timings?.[key] ?? dflt;+ }++ /* ───────────────────────────── the session id ───────────────────────────── */++ /** Start following `sid`'s transcript, with the first turn at `offset`. */+ private follow(sid: string, offset: number): void {+ const path = transcriptPathFor(this.o.cwd, sid, this.o.projectsRoot);+ this.follower = new TranscriptFollower(path, join(path.replace(/\.jsonl$/, ""), "subagents"));+ this.sessionId = sid;+ this.settledTurn = null;+ this.lastPollAt = Date.now();+ this.binding.updateSession?.({ id: sid, claudeSessionId: sid });+ // From a mid-file offset the follower must start reading THERE, not at byte 0.+ this.openHumanTurn(offset, offset > 0);+ if (this.phase === "NONE") this.transition("session_known");+ }++ /** A proxy request named `sid`: a `/clear`, or the session of a resumed launch. */+ private noteRequestSession(sid: string): void {+ if (this.phase === "STOPPED" || sid === this.sessionId || this.retired.has(sid)) return;+ if (this.pendingSid?.id !== sid) this.pendingSid = { id: sid, since: Date.now() };+ this.tryRetarget();+ }++ /**+ * Follow the pending session id once its transcript exists. The turn opens at its+ * last human prompt: Claude Code writes the prompt before the request that names the+ * session, so that prompt is the running turn's witness.+ */+ private tryRetarget(): void {+ const p = this.pendingSid;+ if (!p) return;+ const path = transcriptPathFor(this.o.cwd, p.id, this.o.projectsRoot);+ if (!existsSync(path)) {+ if (Date.now() - p.since > RETARGET_WAIT_MS) {+ log(`[hooks] interactive driver: no transcript for session ${p.id}; not following it`);+ this.pendingSid = null;+ }+ return;+ }+ this.pendingSid = null;+ if (this.phase === "SETTLING") this.endHold("caller");+ if (this.admission) {+ this.dropInjection(this.admission.item, "stale");+ this.admission = null;+ }+ if (this.sessionId) this.retired.add(this.sessionId);+ log(`[hooks] interactive driver: following session ${p.id}`);+ const offset = lastHumanPromptOffset(path) ?? fileSizeOf(path);+ const wasNone = this.phase === "NONE";+ this.follow(p.id, offset);+ if (!wasNone && this.phase !== "OPEN") this.transition("retarget");+ }++ /* ───────────────────────────── evaluation ───────────────────────────── */++ private pollFollower(force = false): TranscriptView | null {+ const f = this.follower;+ if (!f) return null;+ const now = Date.now();+ if (force || this.framePending || now - this.lastPollAt >= 1_000) {+ f.poll();+ this.lastPollAt = now;+ this.framePending = false;+ }+ const view = f.view();+ const off = view.current?.lastChatOffset ?? null;+ if (off !== this.lastChatOffset) {+ this.lastChatOffset = off;+ this.lastChatSeenAt = now;+ }+ return view;+ }++ private evaluate(): void {+ if (this.phase === "STOPPED") return;+ if (this.pendingSid) this.tryRetarget();+ this.checkBoot();+ const view = this.pollFollower();+ if (!view) return;+ const t = view.current;+ // Read after the steps above, any of which can move the phase.+ const phase: DriverPhase = this.currentPhase();+ switch (phase) {+ case "NONE":+ case "STOPPED":+ return;+ case "OPEN":+ if (t?.acceptedAt) this.humanAccepted();+ else if (this.settledTurn && t?.unwitnessedChatOffset != null) this.rewake();+ else this.pump();+ return;+ case "ADMITTING":+ this.evalAdmission(t);+ return;+ case "RUNNING":+ this.evalRunning(view);+ return;+ case "SETTLING":+ if (t?.acceptedAt) {+ // A human prompt during the hold ends it at once: the human goes first (rule 3).+ this.endHold("caller");+ this.humanAccepted();+ } else if (t?.unwitnessedChatOffset != null) {+ this.endHold("rewake");+ this.rewake();+ }+ return;+ default:+ assertNeverPhase(phase);+ }+ }++ /** `sessionStart` fires at the first empty REPL box, held stable for `replStableMs`. */+ private checkBoot(): void {+ if (this.booted || this.unavailable || this.screen.seq === 0) return;+ const r = readBoot(this.screen);+ const now = Date.now();+ if (r.kind !== this.bootKind) {+ this.bootKind = r.kind;+ this.bootKindSince = now;+ }+ if (r.kind === "repl" && now - this.bootKindSince >= this.ms("replStableMs", REPL_STABLE_MS)) {+ this.booted = true;+ this.fireStart();+ }+ }++ private fireStart(): void {+ // The session's first human turn counts as its initial prompt (§4.7 rule 3): a+ // `sessionStart` injection survives it, whether it was given on the command line+ // (already admitted here) or typed after the box appeared.+ this.startCallerSeq = Math.max(1, this.q.callerAdmitted);+ try {+ this.binding.fireStart();+ } catch {+ // a binding's failure must not break the driver+ }+ }++ private openHumanTurn(offset: number, readFromOffset = false): void {+ const turn: OpenTurn = {+ index: this.lastAcceptedIndex + 1,+ offset,+ witness: { kind: "human" },+ delivery: null,+ hookCaused: false,+ };+ if (readFromOffset) this.follower?.rewindTo(turn);+ else this.follower?.openTurn(turn);+ this.current = turn;+ this.blockedToolId = null;+ }++ /** Close what the follower has read so far, then open a human turn at its end. */+ private openHumanTurnHere(): void {+ this.follower?.poll();+ this.lastPollAt = Date.now();+ this.openHumanTurn(this.follower?.size() ?? 0);+ }++ private humanAccepted(): void {+ const cur = this.current;+ if (!cur) return;+ // Rule 3 and the cap: a human turn is a caller admission. Hook items queued before it+ // are stale, and the run of hook-caused turns ends.+ Object.assign(this.q, afterAdmission(this.q, { kind: "caller", text: "" }));+ this.lastAcceptedIndex = cur.index;+ this.lastChatSeenAt = Date.now();+ this.transition("human_accepted");+ }++ /**+ * A background notification woke the model after its turn settled (D23). The driver+ * had opened the next turn, which the notification does not witness, so the settled+ * turn is re-opened from its own offset and runs on as the SAME turn: no caller+ * admission, no cap reset, the same index when it settles again.+ */+ private rewake(): void {+ const turn = this.settledTurn;+ if (!turn || !this.follower) return;+ this.follower.rewindTo(turn);+ this.current = turn;+ this.lastChatSeenAt = Date.now();+ this.transition("rewake");+ }++ private evalAdmission(t: TurnView | null): void {+ const adm = this.admission;+ if (!adm) return;+ if (t?.acceptedAt) {+ this.admission = null;+ this.lastAcceptedIndex = this.current?.index ?? this.lastAcceptedIndex + 1;+ this.lastChatSeenAt = Date.now();+ this.transition("hook_accepted");+ return;+ }+ if (Date.now() - adm.startedAt >= this.ms("acceptMs", ACCEPT_TIMEOUT_MS))+ this.admitFailed("no witness in time");+ }++ private admitFailed(why: string): void {+ const adm = this.admission;+ if (!adm || this.phase !== "ADMITTING") return;+ this.admission = null;+ log(`[hooks] interactive driver: injection not accepted (${why})`);+ this.dropInjection(adm.item, "send_not_accepted");+ this.openHumanTurnHere();+ this.transition("admit_failed");+ }++ private screenFacts(): ScreenFacts | null {+ if (!this.client) return null;+ const box = inputBox(this.screen);+ return {+ boxEmpty: !!box && box.text === "",+ choiceDialog: hasChoiceDialog(this.screen),+ working: isWorking(this.screen),+ aboveBoxQuietMs: Date.now() - this.screen.aboveBoxChangedAt,+ };+ }++ private evalRunning(view: TranscriptView): void {+ const t = view.current;+ if (!t) return;+ this.checkBlocked(t);+ const now = Date.now();+ const decision = decideSettle({+ turn: t,+ session: view.session,+ transcriptQuietMs: now - (view.lastAppendAt ?? this.startedAt),+ chatQuietMs: now - this.lastChatSeenAt,+ screen: this.screenFacts(),+ paneExited: false,+ secondaryQuietMs: this.ms("secondaryQuietMs", SECONDARY_QUIET_MS),+ corroborationMs: this.ms("corroborationMs", CORROBORATION_MS),+ });+ if (decision.settled) this.record(t, decision.by === "local_command", decision.stopReason);+ }++ /** `sessionBlocked`, once per blocking tool: a question, or a permission/plan dialog. */+ private checkBlocked(t: TurnView): void {+ const pending = t.pendingTool;+ if (!pending) {+ this.blockedToolId = null;+ return;+ }+ if (pending.id === this.blockedToolId) return;+ let kind: "question" | "permission" | null = null;+ if (pending.name === "AskUserQuestion") kind = "question";+ else if (this.client && hasChoiceDialog(this.screen)) kind = "permission";+ if (!kind) return;+ this.blockedToolId = pending.id;+ const text = choiceDialog(this.screen)?.text ?? pending.name;+ try {+ this.binding.fireBlocked({ kind, text });+ } catch {+ // observe-only+ }+ }++ /* ───────────────────────────── settle, hold ───────────────────────────── */++ /**+ * The turn settled: open the next (human) turn at the current offset, then hold for+ * the session hooks when they have work, else go straight to OPEN.+ */+ private record(t: TurnView, localCommand: boolean, stopReason: string | null): void {+ const cur = this.current;+ if (!cur) return;+ this.settles++;+ this.settledTurn = cur;+ const info = {+ index: cur.index,+ answer: localCommand ? (t.localCommandOutput ?? "") : t.assistantText.join("\n\n"),+ stopReason,+ apiError: t.apiError !== null,+ hookCaused: cur.hookCaused,+ consecutiveHookTurns: this.q.consecutiveHookTurns,+ callerInputPending: false,+ shape: "interactive" as const,+ };+ this.openHumanTurnHere();+ let work = false;+ try {+ work = this.binding.hasIdleWork(hookCount(this.q) > 0);+ } catch {+ work = false;+ }+ if (!work) {+ this.transition("settle_open");+ this.pump();+ return;+ }+ this.startHold(info);+ }++ private startHold(info: Parameters<SessionHookBinding["settle"]>[0]): void {+ this.holdGen++;+ const gen = this.holdGen;+ this.transition("settle_hold");+ const ctl = new AbortController();+ this.holdController = ctl;+ let bound: number;+ try {+ bound = this.binding.holdBoundMs();+ } catch {+ bound = 0;+ }+ let p: Promise<HoldResult>;+ try {+ p = Promise.resolve(this.binding.settle(info, ctl.signal));+ } catch (e) {+ p = Promise.reject(e);+ }+ p.catch((err: unknown) => ({ injections: [], error: String(err) }) as HoldResult)+ .then((r) => this.step(() => this.completeHold(gen, r)))+ .catch(() => {});+ this.holdWatchdog = setTimeout(+ () => this.step(() => this.completeHold(gen, { injections: [], error: "watchdog" })),+ Math.max(0, bound)+ );+ }++ /** End the hold without its result; the binding acts on `reason` (§4.7 rule 12). */+ private endHold(reason: HoldAbortReason): void {+ this.holdGen++;+ if (this.holdWatchdog) clearTimeout(this.holdWatchdog);+ this.holdWatchdog = null;+ const ctl = this.holdController;+ this.holdController = null;+ if (ctl && !ctl.signal.aborted) ctl.abort(reason);+ }++ private completeHold(gen: number, r: HoldResult): void {+ if (gen !== this.holdGen || this.phase !== "SETTLING") return;+ for (const a of r.anomalies ?? []) log(`[hooks] interactive driver: ${a}`);+ // the last tick's poll can be up to a second old. A human prompt or a re-wake+ // that reached the transcript since ends the hold HERE, exactly as if a tick had seen+ // it during the hold, and the result goes back to the binding under that reason.+ const t = this.pollFollower(true)?.current;+ const ended: HoldAbortReason | null = t?.acceptedAt+ ? "caller"+ : t?.unwitnessedChatOffset != null+ ? "rewake"+ : null;+ if (ended) {+ // a settle still running (the watchdog fired) learns the reason through its signal+ this.endHold(ended);+ if (r.error === undefined) {+ try {+ this.binding.abandon?.(r, ended);+ } catch {+ // journaling never breaks the driver+ }+ }+ if (ended === "caller") this.humanAccepted();+ else this.rewake();+ return;+ }+ if (r.error !== undefined) {+ log(+ `[hooks] interactive driver: ${r.error === "watchdog" ? "hook_hold_watchdog" : `hook_hold_error ${r.error}`}`+ );+ this.endHold(r.error === "watchdog" ? "watchdog" : "error");+ } else {+ this.holdGen++;+ if (this.holdWatchdog) clearTimeout(this.holdWatchdog);+ this.holdWatchdog = null;+ this.holdController = null;+ }+ const now = Date.now();+ for (const i of r.injections) this.q.items.push(this.hookItemOf(i, now));+ this.transition("hold_done");+ this.pump();+ }++ /* ───────────────────────────── the queue and the gate ───────────────────────────── */++ /** `sessionStart` injections no hold took (the binding's `attach`). */+ private queueInjections(items: HoldInjection[]): void {+ if (this.phase === "STOPPED" || this.unavailable) {+ for (const i of items)+ this.dropInjection(i, this.unavailable ? "unavailable" : "session_ended");+ return;+ }+ const now = Date.now();+ for (const i of items) this.q.items.push(this.hookItemOf(i, now));+ this.pump();+ }++ private hookItemOf(i: HoldInjection, now: number): HookQueueItem {+ return {+ kind: "hook",+ text: i.text,+ hookIds: [...i.hookIds],+ queuedAt: now,+ callerSeq: i.source === "sessionStart" ? this.startCallerSeq : this.q.callerAdmitted,+ source: i.source,+ };+ }++ /** As in a pane: typed text or a file, never a slash command. */+ private readonly canDeliver = (text: string): boolean =>+ !text.trimStart().startsWith("/") && deliveryRefusal(text, this.o.readAvailable) === null;++ /**+ * The delivery gate (§7.5). Every condition is read from the screen and the open+ * turn at this instant; nothing here waits.+ */+ private gateOpen(now: number): boolean {+ if (this.phase !== "OPEN" || !this.booted || this.unavailable) return false;+ if (!this.client || this.pane === null || !this.follower) return false;+ const t = this.follower.view().current;+ if (!t || t.acceptedAt !== null || t.unwitnessedChatOffset !== null) return false;+ const box = inputBox(this.screen);+ if (!box || box.text !== "" || box.menuOpen) return false;+ if (hasChoiceDialog(this.screen) || isWorking(this.screen)) return false;+ if (now - this.boxChangedAt < this.ms("typingHoldMs", TYPING_HOLD_MS)) return false;+ if (this.o.overlayHeld?.()) return false;+ return true;+ }++ /**+ * Read the transcript NOW, before the gate decides, and act on what it shows. A+ * human prompt or a re-wake written since the last tick moves the phase (the item stays+ * queued); typing on the strength of an older poll is typing over a running turn.+ * `deliver` takes its turn boundary from this same read.+ */+ private openTurnIdleNow(): boolean {+ if (this.phase !== "OPEN") return false;+ const t = this.pollFollower(true)?.current;+ if (t?.acceptedAt) {+ this.humanAccepted();+ return false;+ }+ if (this.settledTurn && t?.unwitnessedChatOffset != null) {+ this.rewake();+ return false;+ }+ return true;+ }++ /** The box's text (or its absence) changed: the typing hold restarts. */+ private noteBox(): void {+ const box = inputBox(this.screen);+ const key = box ? box.text : "\u0000none";+ if (key !== this.lastBoxKey) {+ this.lastBoxKey = key;+ this.boxChangedAt = Date.now();+ }+ }++ private pump(): void {+ if (this.q.items.length === 0) return;+ if (!this.openTurnIdleNow()) return;+ const now = Date.now();+ if (!this.gateOpen(now)) return;+ const d = nextQueueDecision(this.q, now, "IDLE", this.canDeliver);+ this.q.items = d.remaining;+ for (const { item, reason } of d.drop) this.dropInjection(item, reason);+ if (d.deliver?.kind === "hook") this.deliver(d.deliver);+ }++ private deliver(item: HookQueueItem): void {+ const follower = this.follower;+ const client = this.client;+ const pane = this.pane;+ if (!follower || !client || pane === null) return;+ Object.assign(this.q, afterAdmission(this.q, item));+ // the turn boundary is the read `openTurnIdleNow` just checked (same step)+ const offset = follower.size();+ const plan: Delivery = planDelivery(+ item.text,+ this.o.turnDir,+ ++this.fileSeq,+ this.o.readAvailable+ );+ if (plan.mode !== "typed" && plan.mode !== "file") {+ // canDeliver already refused anything else; a slash command is invalid at the action+ this.dropInjection(item, "delivery_unavailable");+ return;+ }+ try {+ writeTurnFile(plan);+ } catch (err) {+ log(`[hooks] interactive driver: turn file not written: ${String(err)}`);+ this.dropInjection(item, "delivery_unavailable");+ return;+ }+ const turn: OpenTurn = {+ index: this.lastAcceptedIndex + 1,+ offset,+ witness: plan.witness,+ delivery: plan.mode === "file" ? { file: plan.file, text: plan.fileContent } : null,+ hookCaused: true,+ };+ follower.openTurn(turn);+ this.current = turn;+ this.admission = { item, startedAt: Date.now() };+ try {+ this.binding.noteDelivered?.(item);+ } catch {+ // journaling never breaks delivery+ }+ this.transition("deliver");+ const adm = this.admission;+ void client+ .request({ type: "send", pane, text: plan.line, typed: true, enter: true }, 10_000)+ .then(async (r) => {+ if (r.ok || this.admission !== adm) return;+ // a lost REPLY is not a refusal. The line may already be typed, or typed+ // and entered; the screen and the transcript decide, as in a pane (`typeLine`).+ // Once it landed, the text witness accepts it within `acceptMs` as usual.+ const lost = r.code === "client_timeout" || r.code === "client_lost";+ if (lost && (await this.landedAfterLostReply(adm, pane, plan.line))) return;+ if (this.admission === adm)+ this.step(() => this.admitFailed(`send refused: ${r.code} ${r.error}`));+ });+ }++ /**+ * After a lost send reply: the line is in the box (its Enter was lost: press it now),+ * or it was submitted (its witness, or its echo above the box). False when neither.+ *+ * A lost reply can mean a lost connection, whose client delivers nothing more: the+ * screen is judged, and Enter sent, through the client connected NOW, after a frame+ * it delivered. Enter goes only while `adm` is still the pending admission, and only+ * its own reply, or the transcript and screen after it, says the line landed.+ */+ private async landedAfterLostReply(adm: Admission, pane: number, line: string): Promise<boolean> {+ const head = line.slice(0, 40);+ // Twice: the Enter itself can meet a connection that is closing.+ for (let attempt = 0; attempt < 2; attempt++) {+ const seen = this.screen.seq;+ const client = await this.connectedClient(RECONNECT_WAIT_MS);+ if (!client) return false;+ await this.frameAfter(seen, 1_000);+ if (!inputBox(this.screen)?.text.startsWith(head)) break;+ if (this.admission !== adm) return false;+ log("[hooks] interactive driver: send reply lost; the line is in the box, pressing Enter");+ const r = await client.request({ type: "send", pane, keys: ["enter"], enter: false }, 10_000);+ if (r.ok) return true;+ log(`[hooks] interactive driver: Enter after a lost reply: ${r.code} ${r.error}`);+ }+ const landed = this.submitted(head);+ if (landed) log("[hooks] interactive driver: send reply lost; the line was submitted");+ return landed;+ }++ /** The line starting with `head` was submitted: its witness, or its echo above the box. */+ private submitted(head: string): boolean {+ const t = this.pollFollower(true)?.current;+ return (+ (t?.acceptedAt ?? null) !== null || this.screen.lines.some((l) => l.startsWith(`❯ ${head}`))+ );+ }++ /** The client that is connected now, waiting up to `ms` for `reconnect()` to replace a lost one. */+ private async connectedClient(ms: number): Promise<MagmuxClient | null> {+ const end = Date.now() + ms;+ for (;;) {+ const c = this.client;+ if (c && !c.isClosed) return c;+ if (Date.now() >= end || this.phase === "STOPPED") return null;+ await Bun.sleep(25);+ }+ }++ /** Resolves once a frame newer than `seq` arrived, or after `ms`. */+ private frameAfter(seq: number, ms: number): Promise<void> {+ if (this.screen.seq !== seq) return Promise.resolve();+ return this.nextFrame(ms);+ }++ /** Resolves on the next frame, or after `ms`. */+ private nextFrame(ms: number): Promise<void> {+ const seq = this.screen.seq;+ const end = Date.now() + ms;+ return new Promise((resolve) => {+ const check = () => {+ if (this.screen.seq !== seq || Date.now() >= end) resolve();+ else setTimeout(check, 25);+ };+ check();+ });+ }++ private dropInjection(item: { text: string; hookIds: string[] }, reason: string): void {+ log(`[hooks] interactive driver: hook_injection_dropped:${reason}`);+ try {+ this.binding.noteDropped?.(item, reason);+ } catch {+ // journaling never breaks the driver+ }+ }+}++function assertNeverPhase(p: never): never {+ throw new Error(`unhandled driver phase ${String(p)}`);+}++function fileSizeOf(path: string): number {+ try {+ return statSync(path).size;+ } catch {+ return 0;+ }+}++function raceTimeout(p: Promise<unknown>, ms: number): Promise<void> {+ return new Promise((resolve) => {+ const t = setTimeout(resolve, ms);+ p.then(+ () => {+ clearTimeout(t);+ resolve();+ },+ () => {+ clearTimeout(t);+ resolve();+ }+ );+ });+}diff --git a/packages/cli/src/hooks/session/no-surface.ts b/packages/cli/src/hooks/session/no-surface.tsnew file mode 100644index 00000000..111e8e12--- /dev/null+++ b/packages/cli/src/hooks/session/no-surface.ts@@ -0,0 +1,57 @@+/**+ * Session hooks for a launch with no pane to drive (hook-system §2.1, §4.4): `claudish+ * -i` with no TTY or no magmux, and `claudish -p`. Only the process lifecycle is known,+ * so `sessionStart` fires at spawn and `sessionEnd` at exit; `sessionIdle` and+ * `sessionBlocked` never fire. Every injection is dropped `unavailable`, with the one+ * stderr line per process of §4.7 rule 8.+ */++import type { HookEngine } from "../engine.js";+import { reportInjectionUnavailable } from "../injection/sinks.js";+import type { SessionInfo } from "../public.js";+import { createSessionHookBinding } from "./binding.js";++export interface NoSurfaceSession {+ /** Fire `sessionEnd` and wait for it, at most `waitMs`. */+ end(+ outcome: { state: string; reason: string | null; exitCode: number | null },+ waitMs?: number+ ): Promise<void>;+}++export function startNoSurfaceSession(+ engine: HookEngine,+ session: Omit<SessionInfo, "injection">,+ warn?: (line: string) => void+): NoSurfaceSession {+ const binding = createSessionHookBinding(engine, { ...session, injection: "unavailable" }, null);+ binding.attach?.({+ queueInjections(items) {+ reportInjectionUnavailable(warn);+ for (const i of items) binding.noteDropped?.(i, "unavailable");+ },+ });+ binding.fireStart();+ let ended: Promise<void> | null = null;+ return {+ end(outcome, waitMs = 1_500) {+ if (ended) return ended;+ binding.fireEnd(outcome);+ const settled = binding.endSettled?.() ?? Promise.resolve();+ ended = new Promise<void>((resolve) => {+ const t = setTimeout(resolve, waitMs);+ settled.then(+ () => {+ clearTimeout(t);+ resolve();+ },+ () => {+ clearTimeout(t);+ resolve();+ }+ );+ });+ return ended;+ },+ };+}diff --git a/packages/cli/src/hooks/session/test-helpers/own-pane-probe.ts b/packages/cli/src/hooks/session/test-helpers/own-pane-probe.tsnew file mode 100644index 00000000..a0985c10--- /dev/null+++ b/packages/cli/src/hooks/session/test-helpers/own-pane-probe.ts@@ -0,0 +1,28 @@+#!/usr/bin/env bun+/**+ * Test-only: run INSIDE a magmux pane (ambient mode). Finds this process's own pane+ * through `MAGMUX_SOCK` with the production rule (`findOwnPane`) and writes the answer,+ * with the pane list it saw, as JSON to argv[2]. Then idles so the pane stays alive+ * until the test reads the file.+ */++import { writeFileSync } from "node:fs";+import { MagmuxClient } from "../../../pane/magmux-client.js";+import { findOwnPane } from "../../../pane/own-pane.js";++const out = process.argv[2] as string;+const sock = process.env.MAGMUX_SOCK;+if (!sock) {+ writeFileSync(out, JSON.stringify({ error: "no MAGMUX_SOCK" }));+ process.exit(0);+}+const client = await MagmuxClient.connect(sock, { timeoutMs: 5_000 });+let listed: unknown = null;+const pane = await findOwnPane(async () => {+ const r = await client.request({ type: "list" });+ listed = r.ok ? r.result : null;+ return listed;+});+writeFileSync(out, JSON.stringify({ pane, listed, pid: process.pid }));+client.close();+setTimeout(() => process.exit(0), 20_000);