Skip to content

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

feat(hooks): add SessionHookBinding for pane owners

Jack Rudenko06c35c7512ca
diff --git a/packages/cli/src/hooks/injection/inbox.test.ts b/packages/cli/src/hooks/injection/inbox.test.ts
new file mode 100644
index 00000000..85dc6bca
--- /dev/null
+++ b/packages/cli/src/hooks/injection/inbox.test.ts
@@ -0,0 +1,203 @@
+/**
+ * The owner's inbox reader (architecture §2.3 steps 5-6): incremental by byte offset,
+ * waits only for requests with a `stop` and no `end`, keeps reading past the recorded
+ * length while it waits, carries other requests' lines, bounded and abortable.
+ */
+
+import { afterAll, describe, expect, test } from "bun:test";
+import { appendFileSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { InboxReader, createHookInbox, inboxHasPayload } from "./inbox.js";
+
+const dir = mkdtempSync(join(tmpdir(), "hook-inbox-"));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+let n = 0;
+function inbox(lines: object[] = []): string {
+ const p = join(dir, `inbox-${++n}.jsonl`);
+ writeFileSync(p, lines.map((l) => `${JSON.stringify(l)}\n`).join(""));
+ return p;
+}
+const append = (p: string, ...lines: object[]) =>
+ appendFileSync(p, lines.map((l) => `${JSON.stringify(l)}\n`).join(""));
+
+const stop = (req: string) => ({ v: 1, kind: "stop", req });
+const end = (req: string, aborted?: boolean) => ({
+ v: 1,
+ kind: "end",
+ req,
+ ...(aborted ? { aborted } : {}),
+});
+const inject = (req: string, text: string) => ({
+ v: 1,
+ kind: "inject",
+ req,
+ hookId: "hook:m/i",
+ text,
+ at: "x",
+});
+const annotate = (req: string, key: string, value: unknown) => ({
+ v: 1,
+ kind: "annotate",
+ req,
+ hookId: "hook:m/a",
+ key,
+ value,
+ at: "x",
+});
+
+describe("InboxReader.drain", () => {
+ test("a finished request's payload is taken at once, with no wait", async () => {
+ const p = inbox([stop("r1"), inject("r1", "P"), annotate("r1", "k", { a: 1 }), end("r1")]);
+ const r = new InboxReader(p);
+ expect(r.hasUnread()).toBe(true);
+ const t0 = Date.now();
+ const d = await r.drain(5_000);
+ expect(Date.now() - t0).toBeLessThan(100);
+ expect(d.injections).toEqual([{ req: "r1", hookId: "hook:m/i", text: "P" }]);
+ expect(d.annotations).toEqual([{ req: "r1", hookId: "hook:m/a", key: "k", value: { a: 1 } }]);
+ expect(r.hasUnread()).toBe(false);
+ // incremental: a second drain reads nothing again
+ expect((await r.drain(5_000)).injections).toEqual([]);
+ });
+
+ test("H-36: lines past the recorded length are taken for a waited request; others are carried", async () => {
+ const p = inbox([stop("r1")]);
+ const r = new InboxReader(p);
+ setTimeout(() => append(p, inject("r1", "P"), end("r1"), inject("r2", "Q")), 150);
+ const t0 = Date.now();
+ const d = await r.drain(1_000);
+ const took = Date.now() - t0;
+ expect(d.injections.map((i) => i.text)).toEqual(["P"]);
+ expect(took).toBeGreaterThanOrEqual(140);
+ expect(took).toBeLessThan(600); // at ~150 ms plus one poll, never the 1 s bound
+ // r2 had no stop: never waited for; its line is the next settle's
+ expect(r.hasUnread()).toBe(true);
+ expect((await r.drain(1_000)).injections.map((i) => i.text)).toEqual(["Q"]);
+ });
+
+ test("a request with no stop (still streaming) is never waited for", async () => {
+ const p = inbox([inject("bg", "LATER-MAYBE")]);
+ const t0 = Date.now();
+ const d = await new InboxReader(p).drain(2_000);
+ expect(Date.now() - t0).toBeLessThan(100);
+ expect(d.injections.map((i) => i.text)).toEqual(["LATER-MAYBE"]);
+ });
+
+ test("a stop without an end is waited for up to the bound, then its later lines go to the next drain", async () => {
+ const p = inbox([stop("r1")]);
+ const r = new InboxReader(p);
+ const t0 = Date.now();
+ const d = await r.drain(250);
+ expect(Date.now() - t0).toBeGreaterThanOrEqual(240);
+ expect(d.timedOut).toEqual(["r1"]);
+ append(p, inject("r1", "LATE"), end("r1"));
+ const t1 = Date.now();
+ const d2 = await r.drain(5_000);
+ expect(Date.now() - t1).toBeLessThan(100); // not waited for again
+ expect(d2.injections.map((i) => i.text)).toEqual(["LATE"]);
+ });
+
+ test("the wait ends at once when the signal aborts", async () => {
+ const p = inbox([stop("r1")]);
+ const ac = new AbortController();
+ setTimeout(() => ac.abort("exit"), 120);
+ const t0 = Date.now();
+ await new InboxReader(p).drain(30_500, ac.signal);
+ const took = Date.now() - t0;
+ expect(took).toBeLessThan(400);
+ });
+
+ test("an aborted end and a capped line are reported", async () => {
+ const p = inbox([stop("r1"), end("r1", true), { v: 1, kind: "capped" }]);
+ const d = await new InboxReader(p).drain(1_000);
+ expect(d.capped).toBe(true);
+ expect(d.injections).toEqual([]);
+ });
+
+ test("a partial last line is held until it is complete; garbage lines are skipped", async () => {
+ const p = inbox([]);
+ appendFileSync(p, 'not json\n{"v":1,"kind":"inject","req":"r","hookId":"h","te');
+ const r = new InboxReader(p);
+ expect((await r.drain(100)).injections).toEqual([]);
+ appendFileSync(p, 'xt":"WHOLE"}\n');
+ expect((await r.drain(100)).injections.map((i) => i.text)).toEqual(["WHOLE"]);
+ });
+});
+
+describe("inbox files", () => {
+ test("createHookInbox: 0600, exclusive, replacing a stale file of an earlier run", () => {
+ const d = mkdtempSync(join(dir, "s-"));
+ const p = createHookInbox(d) as string;
+ expect(p).toBe(join(d, "hook-inbox.jsonl"));
+ expect(statSync(p).mode & 0o777).toBe(0o600);
+ appendFileSync(p, "stale\n");
+ expect(createHookInbox(d)).toBe(p);
+ expect(statSync(p).size).toBe(0);
+ expect(createHookInbox(join(d, "missing-dir"))).toBeNull();
+ });
+
+ test("inboxHasPayload: only inject or annotate lines count", () => {
+ expect(inboxHasPayload(inbox([stop("r"), end("r")]))).toBe(false);
+ expect(inboxHasPayload(inbox([stop("r"), annotate("r", "k", 1), end("r")]))).toBe(true);
+ expect(inboxHasPayload(join(dir, "absent.jsonl"))).toBe(false);
+ });
+});
+
+describe("review fixes", () => {
+ test("a capped line written while a request is waited for is reported in THIS drain", async () => {
+ const p = inbox([stop("r1")]);
+ const r = new InboxReader(p);
+ setTimeout(() => append(p, { v: 1, kind: "capped" }, end("r1")), 150);
+ const d = await r.drain(2_000);
+ expect(d.capped).toBe(true);
+ expect(d.timedOut).toEqual([]);
+ });
+
+ test("a request that ended before message_stop (end only) is forgotten", async () => {
+ const p = inbox([end("a", true), end("b", true), stop("c"), end("c")]);
+ const r = new InboxReader(p);
+ await r.drain(100);
+ const sets = r as unknown as { stopped: Set<string>; ended: Set<string> };
+ expect(sets.ended.size).toBe(0);
+ expect(sets.stopped.size).toBe(0);
+ });
+
+ test("a multi-byte character split across two reads arrives whole", async () => {
+ const text = "héllo 🙂 wörld";
+ const line = Buffer.from(`${JSON.stringify(inject("r1", text))}\n`, "utf8");
+ // cut inside the 4-byte emoji
+ const cut = line.indexOf(Buffer.from("🙂", "utf8")) + 2;
+ const p = inbox([stop("r1")]);
+ appendFileSync(p, line.subarray(0, cut));
+ const r = new InboxReader(p);
+ setTimeout(() => {
+ appendFileSync(p, line.subarray(cut));
+ append(p, end("r1"));
+ }, 150);
+ const d = await r.drain(2_000);
+ expect(d.injections.map((i) => i.text)).toEqual([text]);
+ });
+
+ test("payload lines are re-validated: a slash command, an oversized text, a bad key are rejected", async () => {
+ const p = inbox([
+ stop("r1"),
+ inject("r1", "/exit"),
+ inject("r1", " /model opus"),
+ inject("r1", "x".repeat(100_001)),
+ inject("r1", "FINE"),
+ annotate("r1", "has space", 1),
+ annotate("r1", "ok", 2),
+ end("r1"),
+ ]);
+ const d = await new InboxReader(p).drain(100);
+ expect(d.injections.map((i) => i.text)).toEqual(["FINE"]);
+ expect(d.annotations.map((a) => a.key)).toEqual(["ok"]);
+ expect(d.invalid.map((x) => [x.kind, x.reason])).toEqual([
+ ["inject", "slash_command"],
+ ["inject", "slash_command"],
+ ["inject", "too_long"],
+ ["annotate", "invalid_key"],
+ ]);
+ });
+});
diff --git a/packages/cli/src/hooks/injection/inbox.ts b/packages/cli/src/hooks/injection/inbox.ts
new file mode 100644
index 00000000..e5330891
--- /dev/null
+++ b/packages/cli/src/hooks/injection/inbox.ts
@@ -0,0 +1,392 @@
+/**
+ * The pane owner's side of the hook inbox (architecture §2.3 steps 5-6).
+ *
+ * A pane child appends one JSON object per line to `hook-inbox.jsonl`:
+ * `stop` before a response's `message_stop` can reach Claude Code, then the
+ * `inject` / `annotate` payload its `responseEnd` hooks returned, then `end` once
+ * those hooks resolved (or `end` with `aborted` when the stream died first).
+ *
+ * At a settle the owner records the file length and reads every line up to it,
+ * incrementally by byte offset. It waits only for requests that have a `stop` and
+ * no `end` by then: their `responseEnd` hooks are still running. While it waits it
+ * keeps reading past the recorded length, because those requests' lines can only
+ * appear there; lines past the length that belong to OTHER requests are carried to
+ * the next settle. A request with no `stop` is still streaming (a background
+ * subagent, a side request) and is never waited for. The wait polls every 100 ms,
+ * is bounded, and ends at once when the signal aborts.
+ */
+
+import {
+ closeSync,
+ existsSync,
+ fstatSync,
+ openSync,
+ readFileSync,
+ readSync,
+ rmSync,
+ statSync,
+} from "node:fs";
+import { join } from "node:path";
+import { validateAction } from "../actions.js";
+import type { JsonValue } from "../public.js";
+
+export const INBOX_POLL_MS = 100;
+
+export type InboxLine =
+ | { v: 1; kind: "stop"; req: string }
+ | { v: 1; kind: "inject"; req: string; hookId: string; text: string; at?: string }
+ | {
+ v: 1;
+ kind: "annotate";
+ req: string;
+ hookId: string;
+ key: string;
+ value: JsonValue;
+ at?: string;
+ }
+ | { v: 1; kind: "end"; req: string; aborted?: boolean }
+ | { v: 1; kind: "capped" };
+
+/** What one drain produced, in arrival order. */
+export interface InboxDrain {
+ injections: Array<{ req: string; hookId: string; text: string }>;
+ annotations: Array<{ req: string; hookId: string; key: string; value: JsonValue }>;
+ /** a `capped` line was read in this drain (the child stopped appending payload) */
+ capped: boolean;
+ /** requests still without `end` when the bound expired (their later lines go to the next drain) */
+ timedOut: string[];
+ /**
+ * payload lines that fail the action rules the child applies: a slash
+ * command, an over-long text, a bad annotation key or value. Never delivered.
+ */
+ invalid: Array<{ req: string; hookId: string; kind: "inject" | "annotate"; reason: string }>;
+}
+
+/**
+ * Re-apply, at the owner, the rules `validateAction` applies to these actions
+ * in the child. The inbox is a same-user file; a line in it is not proof that a hook
+ * produced it, so it is held to what a hook could have produced. Null when valid.
+ */
+function payloadProblem(line: InboxLine): string | null {
+ if (line.kind === "inject") {
+ const v = validateAction("responseEnd", { type: "injectUserTurn", text: line.text });
+ return v.ok ? null : v.reason;
+ }
+ if (line.kind === "annotate") {
+ const v = validateAction("responseEnd", {
+ type: "annotateTurn",
+ key: line.key,
+ value: line.value,
+ });
+ return v.ok ? null : v.reason;
+ }
+ return null;
+}
+
+function parseLine(text: string): InboxLine | null {
+ let v: unknown;
+ try {
+ v = JSON.parse(text);
+ } catch {
+ return null;
+ }
+ if (!v || typeof v !== "object") return null;
+ const o = v as Record<string, unknown>;
+ if (o.v !== 1) return null;
+ switch (o.kind) {
+ case "capped":
+ return { v: 1, kind: "capped" };
+ case "stop":
+ case "end":
+ return typeof o.req === "string" ? (o as InboxLine) : null;
+ case "inject":
+ return typeof o.req === "string" && typeof o.hookId === "string" && typeof o.text === "string"
+ ? (o as InboxLine)
+ : null;
+ case "annotate":
+ return typeof o.req === "string" && typeof o.hookId === "string" && typeof o.key === "string"
+ ? (o as InboxLine)
+ : null;
+ default:
+ return null;
+ }
+}
+
+/**
+ * Where an `InboxReader` takes its lines from. The pane child's file is one source;
+ * the interactive launcher's in-process sink is the other (`MemoryInbox`), so the
+ * owner's drain rule — wait only for a `stop` without its `end`, bounded, abortable,
+ * carry other requests' lines — is one implementation for both (§2.3).
+ */
+export interface InboxLineSource {
+ /** Every line appended since the last call, in order. */
+ readNew(): InboxLine[];
+ /** Lines were appended that `readNew()` has not returned yet. */
+ hasNew(): boolean;
+}
+
+/**
+ * The interactive launcher's inbox: the same lines the pane child appends to its
+ * file, kept in memory, because proxy and session events share one process there.
+ */
+export class MemoryInbox implements InboxLineSource {
+ private lines: InboxLine[] = [];
+
+ append(line: InboxLine): void {
+ this.lines.push(line);
+ }
+
+ readNew(): InboxLine[] {
+ const out = this.lines;
+ this.lines = [];
+ return out;
+ }
+
+ hasNew(): boolean {
+ return this.lines.length > 0;
+ }
+}
+
+/** The pane child's `hook-inbox.jsonl`, read incrementally by byte offset. */
+class FileInbox implements InboxLineSource {
+ /** bytes read from the file so far */
+ private offset = 0;
+ /**
+ * The bytes of a partial line at the end of the last read, undecoded: a read can
+ * end inside a multi-byte character, which decodes whole only with the rest.
+ */
+ private partial: Buffer = Buffer.alloc(0);
+
+ constructor(readonly path: string) {}
+
+ hasNew(): boolean {
+ try {
+ return statSync(this.path).size > this.offset;
+ } catch {
+ return false;
+ }
+ }
+
+ /** Read every complete line appended since the last read. */
+ readNew(): InboxLine[] {
+ if (!existsSync(this.path)) return [];
+ let fd: number;
+ try {
+ fd = openSync(this.path, "r");
+ } catch {
+ return [];
+ }
+ try {
+ const size = fstatSync(fd).size;
+ if (size <= this.offset) return [];
+ const buf = Buffer.alloc(size - this.offset);
+ const n = readSync(fd, buf, 0, buf.length, this.offset);
+ const bytes = Buffer.concat([this.partial, buf.subarray(0, n)]);
+ // 0x0A never occurs inside a multi-byte UTF-8 sequence: cutting there is safe
+ const nl = bytes.lastIndexOf(0x0a);
+ const complete = nl === -1 ? "" : bytes.subarray(0, nl).toString("utf8");
+ this.partial = Buffer.from(nl === -1 ? bytes : bytes.subarray(nl + 1));
+ this.offset += n;
+ const out: InboxLine[] = [];
+ for (const raw of complete.split("\n")) {
+ if (!raw.trim()) continue;
+ const line = parseLine(raw);
+ if (line) out.push(line);
+ }
+ return out;
+ } finally {
+ closeSync(fd);
+ }
+ }
+}
+
+export class InboxReader {
+ /** lines read earlier that belong to a later drain */
+ private carried: InboxLine[] = [];
+ /** requests that wrote `stop`, and those that wrote `end` */
+ private readonly stopped = new Set<string>();
+ private readonly ended = new Set<string>();
+ private readonly source: InboxLineSource;
+ /** the inbox file, or null for an in-memory source */
+ readonly path: string | null;
+
+ constructor(source: string | InboxLineSource) {
+ if (typeof source === "string") {
+ this.path = source;
+ this.source = new FileInbox(source);
+ } else {
+ this.path = null;
+ this.source = source;
+ }
+ }
+
+ /** Lines appended since the last read, or lines carried for the next drain. */
+ hasUnread(): boolean {
+ return this.carried.length > 0 || this.source.hasNew();
+ }
+
+ private readNew(): InboxLine[] {
+ return this.source.readNew();
+ }
+
+ /**
+ * Forget requests that are finished, so a long session's sets stay small. A request
+ * that ended before `message_stop` wrote only its `end` and was never in `stopped`;
+ * it is forgotten too. An `end` is always its request's last line.
+ */
+ private prune(): void {
+ for (const req of this.ended) this.stopped.delete(req);
+ this.ended.clear();
+ }
+
+ private note(line: InboxLine): void {
+ if (line.kind === "stop") this.stopped.add(line.req);
+ else if (line.kind === "end") this.ended.add(line.req);
+ }
+
+ /**
+ * One settle's drain. `boundMs` caps the wait for requests whose `responseEnd`
+ * hooks are still running; `signal` ends it at once (pane exit, terminal state,
+ * an aborted hold).
+ */
+ async drain(boundMs: number, signal?: AbortSignal): Promise<InboxDrain> {
+ const out: InboxDrain = {
+ injections: [],
+ annotations: [],
+ capped: false,
+ timedOut: [],
+ invalid: [],
+ };
+ const take = (line: InboxLine) => {
+ if (line.kind === "inject" || line.kind === "annotate") {
+ const reason = payloadProblem(line);
+ if (reason !== null) {
+ out.invalid.push({ req: line.req, hookId: line.hookId, kind: line.kind, reason });
+ return;
+ }
+ }
+ if (line.kind === "inject")
+ out.injections.push({ req: line.req, hookId: line.hookId, text: line.text });
+ else if (line.kind === "annotate")
+ out.annotations.push({
+ req: line.req,
+ hookId: line.hookId,
+ key: line.key,
+ value: line.value,
+ });
+ else if (line.kind === "capped") out.capped = true;
+ };
+
+ // Everything up to the recorded length, plus what an earlier drain carried.
+ const upTo = [...this.carried, ...this.readNew()];
+ this.carried = [];
+ for (const line of upTo) {
+ this.note(line);
+ take(line);
+ }
+ // Requests whose hooks are still running: a `stop`, no `end`.
+ const waiting = new Set<string>();
+ for (const req of this.stopped) if (!this.ended.has(req)) waiting.add(req);
+ if (waiting.size === 0) {
+ this.prune();
+ return out;
+ }
+
+ const deadline = Date.now() + Math.max(0, boundMs);
+ while (waiting.size > 0 && !signal?.aborted && Date.now() < deadline) {
+ await sleepOrAbort(Math.min(INBOX_POLL_MS, Math.max(0, deadline - Date.now())), signal);
+ for (const line of this.readNew()) {
+ // The cap is the inbox's, not a request's: this settle reports it.
+ if (line.kind === "capped") {
+ take(line);
+ continue;
+ }
+ const req = line.req;
+ if (waiting.has(req)) {
+ this.note(line);
+ take(line);
+ if (line.kind === "end") waiting.delete(req);
+ } else {
+ // Another request's line: the next settle takes it.
+ this.carried.push(line);
+ }
+ }
+ }
+ // Still waiting at the bound: those requests' later lines go to the next drain.
+ // They are not waited for again (their `stop` is remembered as ended).
+ for (const req of waiting) {
+ out.timedOut.push(req);
+ this.ended.add(req);
+ }
+ this.prune();
+ return out;
+ }
+
+ /**
+ * The session is over and its writer gone: every payload line not taken yet, carried
+ * or never read, with no wait. The caller journals them.
+ */
+ takeRemaining(): Array<Extract<InboxLine, { kind: "inject" | "annotate" }>> {
+ const lines = [...this.carried, ...this.readNew()];
+ this.carried = [];
+ return lines.filter(
+ (l): l is Extract<InboxLine, { kind: "inject" | "annotate" }> =>
+ l.kind === "inject" || l.kind === "annotate"
+ );
+ }
+}
+
+function sleepOrAbort(ms: number, signal?: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ if (signal?.aborted) return resolve();
+ const done = () => {
+ clearTimeout(t);
+ signal?.removeEventListener("abort", done);
+ resolve();
+ };
+ const t = setTimeout(done, ms);
+ signal?.addEventListener("abort", done, { once: true });
+ });
+}
+
+/** Every parseable line of an inbox file; [] when it is absent or unreadable. */
+export function readInboxLines(path: string): InboxLine[] {
+ let text: string;
+ try {
+ text = readFileSync(path, "utf8");
+ } catch {
+ return [];
+ }
+ const out: InboxLine[] = [];
+ for (const raw of text.split("\n")) {
+ if (!raw.trim()) continue;
+ const line = parseLine(raw);
+ if (line) out.push(line);
+ }
+ return out;
+}
+
+/** The inbox holds an `inject` or `annotate` line (the reap check of an owner without hooks). */
+export function inboxHasPayload(path: string): boolean {
+ return readInboxLines(path).some((l) => l.kind === "inject" || l.kind === "annotate");
+}
+
+/** The inbox file name in a channel session's directory (§2.3 step 1). */
+export const HOOK_INBOX_FILE = "hook-inbox.jsonl";
+
+/**
+ * Create `<dir>/<name>` for a pane child, 0600 with an exclusive create (a stale file
+ * of an earlier run on the same dir is removed first, so the create never follows a
+ * planted path). Null when it cannot be created: the child then has no inbox, which
+ * costs its injections, never the session.
+ */
+export function createHookInbox(dir: string, name: string = HOOK_INBOX_FILE): string | null {
+ const path = join(dir, name);
+ try {
+ rmSync(path, { force: true });
+ closeSync(openSync(path, "wx", 0o600));
+ return path;
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/cli/src/hooks/injection/queue.test.ts b/packages/cli/src/hooks/injection/queue.test.ts
new file mode 100644
index 00000000..417db2f4
--- /dev/null
+++ b/packages/cli/src/hooks/injection/queue.test.ts
@@ -0,0 +1,145 @@
+/**
+ * The pure injection queue policy (architecture §7.2, §4.7 rules 1-7), with a fake clock.
+ */
+
+import { describe, expect, test } from "bun:test";
+import {
+ type HookQueueItem,
+ INJECTION_EXPIRY_MS,
+ type InjectionQueueState,
+ type QueueItem,
+ afterAdmission,
+ emptyQueueState,
+ next,
+} from "./queue.js";
+
+const T0 = 1_000_000;
+const always = () => true;
+
+function hook(
+ text: string,
+ callerSeq: number,
+ queuedAt = T0,
+ hookIds = ["hook:m/a"]
+): HookQueueItem {
+ return { kind: "hook", text, hookIds, queuedAt, callerSeq };
+}
+
+function state(items: QueueItem[], over: Partial<InjectionQueueState> = {}): InjectionQueueState {
+ return { ...emptyQueueState(3), items, callerAdmitted: 1, ...over };
+}
+
+describe("next(): delivery only in IDLE, caller first", () => {
+ test("a caller item is delivered before any hook item, and the hook item stays queued", () => {
+ const h = hook("HOOK", 1);
+ const r = next(state([h, { kind: "caller", text: "CALLER" }]), T0, "IDLE", always);
+ expect(r.deliver).toEqual({ kind: "caller", text: "CALLER" });
+ expect(r.drop).toEqual([]);
+ expect(r.remaining).toEqual([h]);
+ });
+
+ for (const phase of ["RUNNING", "ADMITTING", "BOOTING"] as const) {
+ test(`${phase}: nothing is delivered and nothing dropped`, () => {
+ const items = [hook("HOOK", 1), { kind: "caller" as const, text: "C" }];
+ const r = next(state(items), T0, phase, always);
+ expect(r.deliver).toBeUndefined();
+ expect(r.drop).toEqual([]);
+ expect(r.pressEscape).toBe(false);
+ expect(r.remaining).toEqual(items);
+ });
+ }
+
+ test("QUESTION/PERMISSION: a queue of hook items only never presses Esc (§7.2)", () => {
+ for (const phase of ["QUESTION", "PERMISSION"] as const) {
+ expect(next(state([hook("HOOK", 1)]), T0, phase, always).pressEscape).toBe(false);
+ expect(
+ next(state([hook("HOOK", 1), { kind: "caller", text: "C" }]), T0, phase, always).pressEscape
+ ).toBe(true);
+ }
+ });
+});
+
+describe("next(): staleness is counted in caller admissions", () => {
+ test("a sessionStart item queued after the initial prompt (callerSeq 1) survives it", () => {
+ // the initial prompt was admitted: callerAdmitted 1; sessionStart fired after that
+ const r = next(state([hook("START", 1)], { callerAdmitted: 1 }), T0, "IDLE", always);
+ expect(r.deliver?.text).toBe("START");
+ expect(r.drop).toEqual([]);
+ });
+
+ test("a hook item queued before a later caller turn was admitted is stale", () => {
+ const h = hook("OLD", 1);
+ const r = next(state([h], { callerAdmitted: 2 }), T0, "IDLE", always);
+ expect(r.deliver).toBeUndefined();
+ expect(r.drop).toEqual([{ item: h, reason: "stale" }]);
+ expect(r.remaining).toEqual([]);
+ });
+});
+
+describe("next(): merge, cap, expiry, delivery check", () => {
+ test("every live hook item merges into ONE turn: queue order, \\n\\n, duplicates once", () => {
+ const items = [
+ hook("from-start", 1, T0, ["hook:a/s"]),
+ hook("proxy-1", 1, T0 + 5, ["hook:b/p"]),
+ hook("from-start", 1, T0 + 6, ["hook:c/dup"]),
+ hook("idle", 1, T0 + 7, ["hook:d/i"]),
+ ];
+ const r = next(state(items), T0 + 10, "IDLE", always);
+ expect(r.deliver).toMatchObject({
+ kind: "hook",
+ text: "from-start\n\nproxy-1\n\nidle",
+ hookIds: ["hook:a/s", "hook:b/p", "hook:c/dup", "hook:d/i"],
+ queuedAt: T0,
+ callerSeq: 1,
+ });
+ expect(r.remaining).toEqual([]);
+ });
+
+ test("over the cap of consecutive hook-caused turns: dropped capped", () => {
+ const h = hook("HOOK", 1);
+ const r = next(state([h], { consecutiveHookTurns: 3 }), T0, "IDLE", always);
+ expect(r.drop).toEqual([{ item: h, reason: "capped" }]);
+ expect(next(state([h], { consecutiveHookTurns: 2 }), T0, "IDLE", always).deliver?.text).toBe(
+ "HOOK"
+ );
+ });
+
+ test("the cap resets only when a CALLER turn is admitted; a hook admission extends the run", () => {
+ let s = state([], { consecutiveHookTurns: 0 });
+ for (let i = 0; i < 3; i++) Object.assign(s, afterAdmission(s, hook("h", 1)));
+ expect(s.consecutiveHookTurns).toBe(3);
+ expect(s.callerAdmitted).toBe(1);
+ s = { ...s, ...afterAdmission(s, { kind: "caller", text: "c" }) };
+ expect(s.consecutiveHookTurns).toBe(0);
+ expect(s.callerAdmitted).toBe(2);
+ });
+
+ test("an injection not delivered within 10 minutes is dropped expired", () => {
+ const h = hook("OLD", 1, T0);
+ const fresh = hook("NEW", 1, T0 + INJECTION_EXPIRY_MS);
+ const r = next(state([h, fresh]), T0 + INJECTION_EXPIRY_MS + 1, "IDLE", always);
+ expect(r.drop).toEqual([{ item: h, reason: "expired" }]);
+ expect(r.deliver?.text).toBe("NEW");
+ });
+
+ test("a merge that cannot be delivered (multi-line, no Read) is dropped delivery_unavailable", () => {
+ const a = hook("line one", 1);
+ const b = hook("line two", 1);
+ // the merged text is two lines: only a file delivery could carry it
+ const canDeliver = (t: string) => !t.includes("\n");
+ const r = next(state([a, b]), T0, "IDLE", canDeliver);
+ expect(r.deliver).toBeUndefined();
+ expect(r.drop).toEqual([
+ { item: a, reason: "delivery_unavailable" },
+ { item: b, reason: "delivery_unavailable" },
+ ]);
+ expect(r.remaining).toEqual([]);
+ });
+
+ test("next() is pure: the state passed in is not changed", () => {
+ const s = state([hook("H", 0)], { callerAdmitted: 1 });
+ const before = structuredClone(s);
+ next(s, T0, "IDLE", always);
+ expect(s).toEqual(before);
+ });
+});
diff --git a/packages/cli/src/hooks/injection/queue.ts b/packages/cli/src/hooks/injection/queue.ts
new file mode 100644
index 00000000..a0274dbf
--- /dev/null
+++ b/packages/cli/src/hooks/injection/queue.ts
@@ -0,0 +1,164 @@
+/**
+ * The injection queue policy (architecture §7.2, §4.7 rules 1-7). Pure: every
+ * function takes the state and returns a decision or a new state, with the clock
+ * passed in. `PaneSession` owns one state and applies what `next` decides.
+ *
+ * Two item kinds share one queue:
+ *
+ * - `caller`: `send_input` text (or a session's initial prompt). Always first.
+ * It is the only kind that may press Esc on a dialog (D17, unchanged).
+ * - `hook`: an injection a hook returned. Delivered only in IDLE, never over a
+ * dialog or a running turn. It goes STALE once a caller turn is admitted after
+ * it was queued: staleness is counted in caller admissions (`callerSeq`), so a
+ * `sessionStart` injection, queued after the initial prompt started admission,
+ * survives that prompt.
+ *
+ * At one idle every live hook item merges into ONE turn: texts joined with
+ * "\n\n" in queue order, exact duplicates once. The merged text is checked
+ * against the delivery rules BEFORE admission; one that cannot be delivered is
+ * dropped `delivery_unavailable` and never retried.
+ */
+
+import type { Phase } from "../../pane/slot-state.js";
+
+/** An injection delivered more than this long after it was queued is dropped `expired`. */
+export const INJECTION_EXPIRY_MS = 10 * 60_000;
+
+/** Where a hook item came from; decides merge order and how drops are journaled. */
+export type InjectionSource = "sessionStart" | "proxy" | "sessionIdle";
+
+export type QueueItem =
+ | { kind: "caller"; text: string }
+ | {
+ kind: "hook";
+ text: string;
+ hookIds: string[];
+ queuedAt: number;
+ /** `callerAdmitted` when the item was queued; stale once a later caller turn is admitted */
+ callerSeq: number;
+ source?: InjectionSource;
+ };
+
+export type HookQueueItem = Extract<QueueItem, { kind: "hook" }>;
+
+export interface InjectionQueueState {
+ items: QueueItem[];
+ /** caller/human turns admitted so far, the initial prompt included */
+ callerAdmitted: number;
+ consecutiveHookTurns: number;
+ maxConsecutive: number;
+}
+
+export type DropReason = "stale" | "expired" | "capped" | "delivery_unavailable";
+
+export interface NextResult {
+ /** the item to admit now: the first caller item, or the merged hook item */
+ deliver?: QueueItem;
+ /** hook items removed without delivery, with why */
+ drop: Array<{ item: HookQueueItem; reason: DropReason }>;
+ /** Esc a dialog: only a CALLER item does that, and only in QUESTION / PERMISSION */
+ pressEscape: boolean;
+ /** the queue after this decision: `deliver` and every dropped or merged item removed */
+ remaining: QueueItem[];
+}
+
+export function emptyQueueState(maxConsecutive: number): InjectionQueueState {
+ return { items: [], callerAdmitted: 0, consecutiveHookTurns: 0, maxConsecutive };
+}
+
+export function callerCount(state: InjectionQueueState): number {
+ let n = 0;
+ for (const i of state.items) if (i.kind === "caller") n++;
+ return n;
+}
+
+export function hookCount(state: InjectionQueueState): number {
+ return state.items.length - callerCount(state);
+}
+
+/** A hook item is stale once a caller turn was admitted after it was queued. */
+export function isStale(state: InjectionQueueState, item: HookQueueItem): boolean {
+ return state.callerAdmitted > item.callerSeq;
+}
+
+/**
+ * Decide what the queue does now. Delivery happens only in IDLE; in a dialog only
+ * the Esc decision is made. Pure: the caller replaces `state.items` with
+ * `remaining` (and, when it admits `deliver`, applies `afterAdmission`).
+ */
+export function next(
+ state: InjectionQueueState,
+ now: number,
+ phase: Phase,
+ canDeliver: (text: string) => boolean
+): NextResult {
+ const firstCaller = state.items.find((i) => i.kind === "caller");
+ if (phase === "QUESTION" || phase === "PERMISSION") {
+ return { drop: [], pressEscape: firstCaller !== undefined, remaining: state.items };
+ }
+ if (phase !== "IDLE") return { drop: [], pressEscape: false, remaining: state.items };
+
+ if (firstCaller) {
+ return {
+ deliver: firstCaller,
+ drop: [],
+ pressEscape: false,
+ remaining: state.items.filter((i) => i !== firstCaller),
+ };
+ }
+
+ const drop: NextResult["drop"] = [];
+ const live: HookQueueItem[] = [];
+ const overCap = state.consecutiveHookTurns >= state.maxConsecutive;
+ for (const item of state.items) {
+ if (item.kind !== "hook") continue;
+ if (isStale(state, item)) drop.push({ item, reason: "stale" });
+ else if (now - item.queuedAt > INJECTION_EXPIRY_MS) drop.push({ item, reason: "expired" });
+ else if (overCap) drop.push({ item, reason: "capped" });
+ else live.push(item);
+ }
+ if (live.length === 0) return { drop, pressEscape: false, remaining: [] };
+
+ const merged = mergeHookItems(live);
+ if (!canDeliver(merged.text)) {
+ for (const item of live) drop.push({ item, reason: "delivery_unavailable" });
+ return { drop, pressEscape: false, remaining: [] };
+ }
+ return { deliver: merged, drop, pressEscape: false, remaining: [] };
+}
+
+/** Every live hook item as one: queue order, "\n\n", exact duplicates once. */
+export function mergeHookItems(items: ReadonlyArray<HookQueueItem>): HookQueueItem {
+ const texts: string[] = [];
+ const hookIds: string[] = [];
+ for (const item of items) {
+ if (!texts.includes(item.text)) texts.push(item.text);
+ for (const id of item.hookIds) if (!hookIds.includes(id)) hookIds.push(id);
+ }
+ const first = items[0] as HookQueueItem;
+ return {
+ kind: "hook",
+ text: texts.join("\n\n"),
+ hookIds,
+ queuedAt: Math.min(...items.map((i) => i.queuedAt)),
+ callerSeq: Math.max(...items.map((i) => i.callerSeq)),
+ ...(items.length === 1 && first.source ? { source: first.source } : {}),
+ };
+}
+
+/**
+ * The counters after an item was taken off the queue for admission (L1): a caller
+ * turn counts as admitted and resets the hook-turn run; a hook item extends it.
+ * An admission that is later abandoned still counts.
+ */
+export function afterAdmission(
+ state: InjectionQueueState,
+ item: QueueItem
+): Pick<InjectionQueueState, "callerAdmitted" | "consecutiveHookTurns"> {
+ return item.kind === "caller"
+ ? { callerAdmitted: state.callerAdmitted + 1, consecutiveHookTurns: 0 }
+ : {
+ callerAdmitted: state.callerAdmitted,
+ consecutiveHookTurns: state.consecutiveHookTurns + 1,
+ };
+}
diff --git a/packages/cli/src/hooks/session/binding.test.ts b/packages/cli/src/hooks/session/binding.test.ts
new file mode 100644
index 00000000..0646a833
--- /dev/null
+++ b/packages/cli/src/hooks/session/binding.test.ts
@@ -0,0 +1,580 @@
+/**
+ * The real `SessionHookBinding` over a real engine (architecture §4.10, §7.3, §11.5
+ * H-35 and H-36, and the `holdBoundMs` terms of H-21b). No pane: the tests call
+ * `settle()` the way `PaneSession` does and abort its signal with each reason.
+ */
+
+import { afterAll, beforeEach, describe, expect, test } from "bun:test";
+import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { HookEngine } from "../engine.js";
+import type { JournalEntry } from "../journal.js";
+import type { HookDefinition, SessionIdleContext, SessionInfo } from "../public.js";
+import { HookRegistry, type UserHookInput } from "../registry.js";
+import {
+ HOLD_WATCHDOG_MARGIN_MS,
+ type HoldInjection,
+ type HoldTurnInfo,
+ createSessionHookBinding,
+ inboxBoundFor,
+ reportOwnerWithoutHooks,
+ resetOwnerWithoutHooksReportForTests,
+ sessionHooksNeedBinding,
+} from "./binding.js";
+
+const dir = mkdtempSync(join(tmpdir(), "hook-binding-"));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+const SESSION: SessionInfo = {
+ kind: "channel",
+ role: null,
+ id: "abcd1234",
+ claudeSessionId: "11111111-2222-3333-4444-555555555555",
+ model: "glm-5",
+ cwd: "/w",
+ shape: "one-shot",
+ injection: "available",
+};
+const TURN: HoldTurnInfo = {
+ index: 1,
+ answer: "A1",
+ stopReason: "end_turn",
+ apiError: false,
+ hookCaused: false,
+};
+
+function user(id: string, def: Omit<HookDefinition, "apiVersion" | "id">): UserHookInput {
+ return {
+ id: `hook:t/${id}`,
+ module: "/hooks/t.ts",
+ moduleIndex: 0,
+ exportIndex: 0,
+ def: { apiVersion: 1, id, ...def } as HookDefinition,
+ };
+}
+
+function engineOf(...users: UserHookInput[]) {
+ const journal: JournalEntry[] = [];
+ const engine = new HookEngine({
+ registry: new HookRegistry([], users, undefined),
+ config: {},
+ hostMode: "mcp",
+ journalSink: (e) => journal.push(e),
+ warn: () => {},
+ drainTelemetryOutbox: false,
+ });
+ return { engine, journal };
+}
+
+let n = 0;
+function inbox(lines: object[]): string {
+ const p = join(dir, `inbox-${++n}.jsonl`);
+ writeFileSync(p, lines.map((l) => `${JSON.stringify(l)}\n`).join(""));
+ return p;
+}
+
+const stopR1 = { v: 1, kind: "stop", req: "r1" };
+const injectP = { v: 1, kind: "inject", req: "r1", hookId: "hook:c/p", text: "P", at: "x" };
+const annotateK = {
+ v: 1,
+ kind: "annotate",
+ req: "r1",
+ hookId: "hook:c/a",
+ key: "k",
+ value: 7,
+ at: "x",
+};
+const endR1 = { v: 1, kind: "end", req: "r1" };
+
+const texts = (xs: HoldInjection[]) => xs.map((x) => x.text);
+
+describe("hasIdleWork and holdBoundMs", () => {
+ test("no session hook, empty inbox, nothing queued: no idle work (no hold, today's timing)", () => {
+ const { engine } = engineOf();
+ const b = createSessionHookBinding(engine, SESSION, inbox([]));
+ expect(b.hasIdleWork(false)).toBe(false);
+ expect(b.hasIdleWork(true)).toBe(true);
+ });
+
+ test("unread inbox bytes and an applicable sessionIdle hook each make idle work", () => {
+ const { engine } = engineOf();
+ expect(createSessionHookBinding(engine, SESSION, inbox([stopR1])).hasIdleWork(false)).toBe(
+ true
+ );
+ const idle = engineOf(user("i", { on: { sessionIdle: () => [] } })).engine;
+ expect(createSessionHookBinding(idle, SESSION, null).hasIdleWork(false)).toBe(true);
+ });
+
+ test("the inbox bound is the responseEnd dispatch bound + 500 ms, never below the default", () => {
+ expect(inboxBoundFor(engineOf().engine)).toBe(5_500);
+ const slow = engineOf(user("e", { timeoutMs: 20_000, on: { responseEnd: () => [] } })).engine;
+ expect(inboxBoundFor(slow)).toBe(20_500);
+ expect(sessionHooksNeedBinding(slow)).toBe(true);
+ expect(sessionHooksNeedBinding(engineOf().engine)).toBe(false);
+ });
+
+ test("with two responseEnd hooks the inbox bound is their sum, capped at the 30 s budget", () => {
+ const two = engineOf(
+ user("e1", { timeoutMs: 8_000, on: { responseEnd: () => [] } }),
+ user("e2", { on: { responseEnd: () => [] } })
+ ).engine;
+ expect(inboxBoundFor(two)).toBe(8_000 + 5_000 + 500);
+ const capped = engineOf(
+ user("e1", { timeoutMs: 20_000, on: { responseEnd: () => [] } }),
+ user("e2", { timeoutMs: 20_000, on: { responseEnd: () => [] } })
+ ).engine;
+ expect(inboxBoundFor(capped)).toBe(30_000 + 500);
+ });
+
+ test("H-21b/M-2: holdBoundMs adds what remains of a RUNNING sessionStart dispatch bound", async () => {
+ let now = 10_000;
+ const { engine } = engineOf(
+ user("start", {
+ timeoutMs: 4_000,
+ on: { sessionStart: () => new Promise((r) => setTimeout(() => r([]), 300)) },
+ }),
+ user("idle", { timeoutMs: 2_000, on: { sessionIdle: () => [] } })
+ );
+ const b = createSessionHookBinding(engine, SESSION, null, {
+ inboxBoundMs: 200,
+ now: () => now,
+ });
+ expect(b.holdBoundMs()).toBe(200 + 2_000 + HOLD_WATCHDOG_MARGIN_MS);
+ b.fireStart();
+ now += 50; // the hold starts 50 ms into the dispatch
+ expect(b.holdBoundMs()).toBe(3_950 + 200 + 2_000 + HOLD_WATCHDOG_MARGIN_MS);
+ expect(b.hasIdleWork(false)).toBe(true);
+ await Bun.sleep(400);
+ expect(b.holdBoundMs()).toBe(200 + 2_000 + HOLD_WATCHDOG_MARGIN_MS);
+ });
+
+ test("holdBoundMs sums the sessionStart and sessionIdle hooks' step timeouts, capped at the budget", async () => {
+ let now = 10_000;
+ const { engine } = engineOf(
+ user("start1", {
+ timeoutMs: 4_000,
+ on: { sessionStart: () => new Promise((r) => setTimeout(() => r([]), 100)) },
+ }),
+ user("start2", { timeoutMs: 1_000, on: { sessionStart: () => [] } }),
+ user("idle1", { timeoutMs: 2_000, on: { sessionIdle: () => [] } }),
+ user("idle2", { timeoutMs: 3_000, on: { sessionIdle: () => [] } })
+ );
+ const b = createSessionHookBinding(engine, SESSION, null, {
+ inboxBoundMs: 200,
+ now: () => now,
+ });
+ expect(b.holdBoundMs()).toBe(200 + 5_000 + HOLD_WATCHDOG_MARGIN_MS);
+ b.fireStart();
+ now += 50;
+ expect(b.holdBoundMs()).toBe(4_950 + 200 + 5_000 + HOLD_WATCHDOG_MARGIN_MS);
+ await Bun.sleep(200);
+
+ const capped = engineOf(
+ user("idle1", { timeoutMs: 20_000, on: { sessionIdle: () => [] } }),
+ user("idle2", { timeoutMs: 20_000, on: { sessionIdle: () => [] } })
+ ).engine;
+ const c = createSessionHookBinding(capped, SESSION, null, { inboxBoundMs: 200 });
+ expect(c.holdBoundMs()).toBe(200 + 30_000 + HOLD_WATCHDOG_MARGIN_MS);
+ });
+});
+
+describe("settle()", () => {
+ test("merge order: sessionStart, then proxy (arrival order), then sessionIdle; annotations reach ctx.turn", async () => {
+ let seen: SessionIdleContext | null = null;
+ const { engine, journal } = engineOf(
+ user("start", {
+ on: {
+ sessionStart: () =>
+ new Promise((r) => setTimeout(() => r([{ type: "injectUserTurn", text: "S0" }]), 150)),
+ },
+ }),
+ user("idle", {
+ on: {
+ sessionIdle: (ctx) => {
+ seen = ctx;
+ return [{ type: "injectUserTurn", text: "I1" }];
+ },
+ },
+ })
+ );
+ const p = inbox([stopR1, injectP, annotateK, endR1, { ...injectP, req: "r2", text: "P2" }]);
+ const b = createSessionHookBinding(engine, SESSION, p, { inboxBoundMs: 200 });
+ b.fireStart();
+ // the hold starts before the dispatch returns: settle() waits for it (H11)
+ const r = await b.settle(
+ { ...TURN, consecutiveHookTurns: 2, callerInputPending: false },
+ new AbortController().signal
+ );
+ expect(texts(r.injections)).toEqual(["S0", "P", "P2", "I1"]);
+ expect(r.injections.map((i) => i.source)).toEqual([
+ "sessionStart",
+ "proxy",
+ "proxy",
+ "sessionIdle",
+ ]);
+ const ctx = seen as unknown as SessionIdleContext;
+ expect(ctx.turn.annotations).toEqual([{ hookId: "hook:c/a", key: "k", value: 7 }]);
+ expect(ctx.turn.index).toBe(1);
+ expect(ctx.consecutiveHookTurns).toBe(2);
+ expect(ctx.session.id).toBe("abcd1234");
+ expect(journal.filter((j) => j.decision === "queued").map((j) => j.hookId)).toEqual([
+ "hook:t/start",
+ "hook:c/p",
+ "hook:c/p",
+ "hook:t/idle",
+ ]);
+ });
+
+ test("H-36: a request's lines past the recorded length resolve this settle at ~150 ms; another request's line is the next settle's", async () => {
+ const { engine } = engineOf();
+ const p = inbox([stopR1]);
+ const b = createSessionHookBinding(engine, SESSION, p, { inboxBoundMs: 1_000 });
+ setTimeout(
+ () =>
+ appendFileSync(
+ p,
+ [injectP, endR1, { ...injectP, req: "r2", text: "Q" }]
+ .map((l) => `${JSON.stringify(l)}\n`)
+ .join("")
+ ),
+ 150
+ );
+ const t0 = Date.now();
+ const r = await b.settle(TURN, new AbortController().signal);
+ const took = Date.now() - t0;
+ expect(texts(r.injections)).toEqual(["P"]);
+ expect(took).toBeGreaterThanOrEqual(140);
+ expect(took).toBeLessThan(700);
+ expect(b.hasIdleWork(false)).toBe(true);
+ const r2 = await b.settle({ ...TURN, index: 2 }, new AbortController().signal);
+ expect(texts(r2.injections)).toEqual(["Q"]);
+ });
+
+ test("an inbox capped line becomes one pane anomaly and one journal line", async () => {
+ const { engine, journal } = engineOf();
+ const b = createSessionHookBinding(engine, SESSION, inbox([{ v: 1, kind: "capped" }]), {
+ inboxBoundMs: 100,
+ });
+ const r = await b.settle(TURN, new AbortController().signal);
+ expect(r.anomalies).toEqual(["hook_injection_dropped:inbox_cap"]);
+ expect(journal.some((j) => j.decision === "dropped" && j.detail === "inbox_cap")).toBe(true);
+ });
+});
+
+describe("H-35: drained items on every abort reason (§4.7 rule 12)", () => {
+ async function abortedRun(reason: string) {
+ let called!: () => void;
+ const idleCalled = new Promise<void>((r) => {
+ called = r;
+ });
+ let calls = 0;
+ const { engine, journal } = engineOf(
+ user("idle", {
+ timeoutMs: 30_000,
+ on: {
+ sessionIdle: (ctx) => {
+ calls++;
+ if (calls === 1) {
+ called();
+ // waits on its signal: only the abort ends it
+ return new Promise((r) =>
+ ctx.signal.addEventListener("abort", () =>
+ r([{ type: "injectUserTurn", text: "S" }])
+ )
+ );
+ }
+ return [];
+ },
+ },
+ })
+ );
+ const b = createSessionHookBinding(
+ engine,
+ SESSION,
+ inbox([stopR1, injectP, annotateK, endR1]),
+ {
+ inboxBoundMs: 200,
+ }
+ );
+ const ac = new AbortController();
+ const settled = b.settle(TURN, ac.signal);
+ await idleCalled; // the inbox is drained before sessionIdle runs
+ ac.abort(reason);
+ const r = await settled;
+ expect(r.injections).toEqual([]);
+ return { b, journal };
+ }
+
+ test("rewake: P and k are offered at the next settle() of the same turn", async () => {
+ const { b, journal } = await abortedRun("rewake");
+ expect(journal.filter((j) => j.decision === "dropped" && j.hookId === "hook:c/p")).toEqual([]);
+ expect(b.hasIdleWork(false)).toBe(true);
+ // the next settle of the SAME turn carries P (and k into ctx.turn.annotations)
+ const r = await b.settle(TURN, new AbortController().signal);
+ expect(texts(r.injections)).toEqual(["P"]);
+ });
+
+ test("rewake: the carried annotation reaches the next settle's sessionIdle", async () => {
+ let seen: SessionIdleContext | null = null;
+ let calls = 0;
+ const { engine } = engineOf(
+ user("idle", {
+ on: {
+ sessionIdle: (ctx) => {
+ calls++;
+ if (calls === 1)
+ return new Promise((r) => ctx.signal.addEventListener("abort", () => r([])));
+ seen = ctx;
+ return [];
+ },
+ },
+ })
+ );
+ const b = createSessionHookBinding(
+ engine,
+ SESSION,
+ inbox([stopR1, injectP, annotateK, endR1]),
+ {
+ inboxBoundMs: 200,
+ }
+ );
+ const ac = new AbortController();
+ const first = b.settle(TURN, ac.signal);
+ while (calls === 0) await Bun.sleep(5);
+ ac.abort("rewake");
+ await first;
+ await b.settle(TURN, new AbortController().signal);
+ expect((seen as unknown as SessionIdleContext).turn.annotations).toEqual([
+ { hookId: "hook:c/a", key: "k", value: 7 },
+ ]);
+ });
+
+ const dropped = (journal: JournalEntry[], hookId: string) =>
+ journal.filter((j) => j.decision === "dropped" && j.hookId === hookId).map((j) => j.detail);
+
+ test("caller: P and k are journaled dropped stale", async () => {
+ const { b, journal } = await abortedRun("caller");
+ expect(dropped(journal, "hook:c/p")).toEqual(["stale"]);
+ expect(dropped(journal, "hook:c/a")).toEqual(["stale"]);
+ expect(b.hasIdleWork(false)).toBe(true); // only the idle hook itself remains
+ });
+
+ for (const reason of ["watchdog", "error"]) {
+ test(`${reason}: dropped, detail hold_ended`, async () => {
+ const { journal } = await abortedRun(reason);
+ expect(dropped(journal, "hook:c/p")).toEqual(["hold_ended"]);
+ expect(dropped(journal, "hook:c/a")).toEqual(["hold_ended"]);
+ });
+ }
+
+ for (const reason of ["exit", "terminal"]) {
+ test(`${reason}: dropped, detail session_ended`, async () => {
+ const { journal } = await abortedRun(reason);
+ expect(dropped(journal, "hook:c/p")).toEqual(["session_ended"]);
+ expect(dropped(journal, "hook:c/a")).toEqual(["session_ended"]);
+ });
+ }
+
+ test("items a re-wake carried that no later settle takes are dropped session_ended at the end", async () => {
+ const { b, journal } = await abortedRun("rewake");
+ b.fireEnd({ state: "TIMEOUT", reason: "timeout", exitCode: null });
+ expect(dropped(journal, "hook:c/p")).toEqual(["session_ended"]);
+ expect(dropped(journal, "hook:c/a")).toEqual(["session_ended"]);
+ });
+});
+
+describe("a result settle() returned, abandoned by the pane (§4.7 rule 12)", () => {
+ const dropped = (journal: JournalEntry[], hookId: string) =>
+ journal.filter((j) => j.decision === "dropped" && j.hookId === hookId).map((j) => j.detail);
+
+ /** A settle that RETURNS (no abort): P from the inbox, k annotated, S from sessionIdle. */
+ async function returned() {
+ let seen: SessionIdleContext | null = null;
+ let calls = 0;
+ const { engine, journal } = engineOf(
+ user("idle", {
+ on: {
+ sessionIdle: (ctx) => {
+ calls++;
+ if (calls === 1) return [{ type: "injectUserTurn", text: "S" }];
+ seen = ctx;
+ return [];
+ },
+ },
+ })
+ );
+ const b = createSessionHookBinding(
+ engine,
+ SESSION,
+ inbox([stopR1, injectP, annotateK, endR1]),
+ { inboxBoundMs: 200 }
+ );
+ const r = await b.settle(TURN, new AbortController().signal);
+ expect(texts(r.injections)).toEqual(["P", "S"]);
+ expect(r.annotations).toEqual([{ hookId: "hook:c/a", key: "k", value: 7 }]);
+ return { b, r, journal, seen: () => seen };
+ }
+
+ test("rewake: P and k are carried to the next settle of the same turn; S is dropped rewake", async () => {
+ const { b, r, journal, seen } = await returned();
+ b.abandon?.(r, "rewake");
+ expect(dropped(journal, "hook:c/p")).toEqual([]);
+ expect(dropped(journal, "hook:t/idle")).toEqual(["rewake"]);
+ expect(b.hasIdleWork(false)).toBe(true);
+ const next = await b.settle(TURN, new AbortController().signal);
+ expect(texts(next.injections)).toEqual(["P"]);
+ expect((seen() as unknown as SessionIdleContext).turn.annotations).toEqual([
+ { hookId: "hook:c/a", key: "k", value: 7 },
+ ]);
+ });
+
+ test("caller: every item and annotation is dropped stale; nothing is carried", async () => {
+ const { b, r, journal } = await returned();
+ b.abandon?.(r, "caller");
+ expect(dropped(journal, "hook:c/p")).toEqual(["stale"]);
+ expect(dropped(journal, "hook:t/idle")).toEqual(["stale"]);
+ expect(dropped(journal, "hook:c/a")).toEqual(["stale"]);
+ const next = await b.settle(TURN, new AbortController().signal);
+ expect(next.injections).toEqual([]);
+ });
+});
+
+describe("sessionStart outside a hold, and the other events", () => {
+ test("a dispatch no hold took is queued into the attached pane", async () => {
+ const { engine } = engineOf(
+ user("start", { on: { sessionStart: () => [{ type: "injectUserTurn", text: "HELLO" }] } })
+ );
+ const b = createSessionHookBinding(engine, SESSION, null);
+ const queued: HoldInjection[][] = [];
+ b.attach?.({ queueInjections: (items) => queued.push(items) });
+ b.fireStart();
+ b.fireStart(); // once per session
+ await Bun.sleep(20);
+ expect(queued.map(texts)).toEqual([["HELLO"]]);
+ expect(queued[0]?.[0]?.source).toBe("sessionStart");
+ });
+
+ test("sessionBlocked and sessionEnd fire, observe-only, with their facts", async () => {
+ const seen: string[] = [];
+ const { engine } = engineOf(
+ user("obs", {
+ on: {
+ sessionBlocked: (ctx) => void seen.push(`blocked:${ctx.block.kind}:${ctx.block.text}`),
+ sessionEnd: (ctx) => void seen.push(`end:${ctx.outcome.state}:${ctx.outcome.exitCode}`),
+ },
+ })
+ );
+ const b = createSessionHookBinding(engine, SESSION, null);
+ b.fireBlocked({ kind: "question", text: "Which?" });
+ b.fireEnd({ state: "COMPLETED", reason: null, exitCode: 0 });
+ b.fireEnd({ state: "COMPLETED", reason: null, exitCode: 0 });
+ await Bun.sleep(20);
+ expect(seen).toEqual(["blocked:question:Which?", "end:COMPLETED:0"]);
+ });
+});
+
+describe("an owner without hooks (§2.3 step 1)", () => {
+ beforeEach(() => resetOwnerWithoutHooksReportForTests());
+
+ test("an inject in the inbox at reap: journaled owner_without_hooks, one stderr line per process", () => {
+ const { engine, journal } = engineOf();
+ const lines: string[] = [];
+ const p = inbox([stopR1, injectP, endR1]);
+ expect(reportOwnerWithoutHooks(p, engine, { model: "m" }, (l) => lines.push(l))).toBe(true);
+ expect(reportOwnerWithoutHooks(p, engine, { model: "m" }, (l) => lines.push(l))).toBe(true);
+ expect(journal.filter((j) => j.detail === "owner_without_hooks")).toHaveLength(2);
+ expect(lines).toEqual([
+ "a pane child produced hook injections, but this process loaded no session hooks: restart the MCP server after changing hooks.modules",
+ ]);
+ });
+
+ test("bookkeeping lines only: nothing reported", () => {
+ const lines: string[] = [];
+ expect(
+ reportOwnerWithoutHooks(inbox([stopR1, endR1]), null, { model: "m" }, (l) => lines.push(l))
+ ).toBe(false);
+ expect(lines).toEqual([]);
+ });
+});
+
+describe("inbox lines the settle did not take", () => {
+ test("an inbox line that fails the action rules is journaled invalid and never offered", async () => {
+ const { engine, journal } = engineOf(user("e", { on: { responseEnd: () => [] } }));
+ const b = createSessionHookBinding(
+ engine,
+ SESSION,
+ inbox([stopR1, { ...injectP, text: "/exit" }, injectP, endR1]),
+ { inboxBoundMs: 100 }
+ );
+ const r = await b.settle(TURN, new AbortController().signal);
+ expect(texts(r.injections)).toEqual(["P"]);
+ expect(r.anomalies).toContain("hook_injection_dropped:invalid");
+ expect(
+ journal
+ .filter((j) => j.decision === "invalid" && j.hookId === "hook:c/p")
+ .map((j) => j.detail)
+ ).toEqual(["inbox: slash_command"]);
+ });
+
+ test("a request still running at the bound is recorded, not silent", async () => {
+ const { engine, journal } = engineOf(user("e", { on: { responseEnd: () => [] } }));
+ const b = createSessionHookBinding(engine, SESSION, inbox([stopR1]), { inboxBoundMs: 100 });
+ const r = await b.settle(TURN, new AbortController().signal);
+ expect(r.anomalies).toContain("hook_inbox_wait_timeout");
+ expect(journal.some((j) => j.decision === "timeout" && j.hookId === "inbox")).toBe(true);
+ });
+
+ test("payload that arrives after the last settle is journaled session_ended at the sweep", async () => {
+ const { engine, journal } = engineOf(user("e", { on: { responseEnd: () => [] } }));
+ const path = inbox([stopR1]);
+ const b = createSessionHookBinding(engine, SESSION, path, { inboxBoundMs: 100 });
+ await b.settle(TURN, new AbortController().signal); // r1 times out
+ appendFileSync(path, `${JSON.stringify(injectP)}\n${JSON.stringify(annotateK)}\n`);
+ b.fireEnd({ state: "COMPLETED", reason: null, exitCode: 0 });
+ b.sweepInbox?.();
+ const dropped = journal.filter((j) => j.decision === "dropped" && j.detail === "session_ended");
+ expect(dropped.map((j) => [j.hookId, j.action])).toEqual([
+ ["hook:c/p", "injectUserTurn"],
+ ["hook:c/a", "annotateTurn"],
+ ]);
+ });
+});
+
+describe("a sessionStart dispatch a hold claimed, and the hold's abort", () => {
+ for (const order of ["abort lands after the dispatch resolved", "abort lands first"] as const) {
+ test(`${order}: the items are queued into the pane, never lost`, async () => {
+ let release!: () => void;
+ const gate = new Promise<void>((r) => {
+ release = r;
+ });
+ const { engine, journal } = engineOf(
+ user("start", {
+ on: {
+ sessionStart: () => gate.then(() => [{ type: "injectUserTurn", text: "HELLO" }]),
+ },
+ })
+ );
+ const b = createSessionHookBinding(engine, SESSION, null);
+ const queued: HoldInjection[][] = [];
+ b.attach?.({ queueInjections: (items) => queued.push(items) });
+ b.fireStart();
+ const ac = new AbortController();
+ const entry = (b as unknown as { start: { promise: Promise<unknown> } }).start;
+ // Registered BEFORE settle(): runs after the binding's own handler (which sees the
+ // claim and leaves the items to the hold) and before the hold's race sees them.
+ if (order === "abort lands after the dispatch resolved")
+ void entry.promise.then(() => ac.abort("rewake"));
+ const settled = b.settle(TURN, ac.signal);
+ if (order === "abort lands first") ac.abort("rewake");
+ release();
+ const r = await settled;
+ await Bun.sleep(20);
+ expect(r.injections).toEqual([]);
+ expect(queued.map(texts)).toEqual([["HELLO"]]);
+ expect(journal.filter((j) => j.hookId === "hook:t/start").map((j) => j.decision)).toEqual([
+ "queued",
+ ]);
+ });
+ }
+});
diff --git a/packages/cli/src/hooks/session/binding.ts b/packages/cli/src/hooks/session/binding.ts
new file mode 100644
index 00000000..84881668
--- /dev/null
+++ b/packages/cli/src/hooks/session/binding.ts
@@ -0,0 +1,693 @@
+/**
+ * `SessionHookBinding`: what a pane owner (the MCP server's `SessionManager`, the
+ * team orchestrator) hands each `PaneSession` whose session hooks need one
+ * (architecture §4.10, §7.3).
+ *
+ * The pane calls `settle()` once per settled turn, while it holds the turn in
+ * `SETTLING`. `settle()` awaits, in order: a `sessionStart` dispatch still running
+ * (its injections must not be stranded by a fast first answer), the inbox drain
+ * (proxy-event `injectUserTurn` / `annotateTurn` from the pane child), and the
+ * `sessionIdle` hook chain. It returns every candidate injection in the merge
+ * order of §4.7 rule 4: `sessionStart`, then proxy events in arrival order, then
+ * `sessionIdle` in hook-chain order. The pane applies the queue policy.
+ *
+ * Every session event is one dispatch run as a hook chain (§4.4.1): the session
+ * and turn facts are read once, at the start of the dispatch, and a later hook
+ * sees the injections earlier hooks returned in `ctx.prior`.
+ *
+ * The pane aborts `signal` with a reason when the hold ends without this result.
+ * The reason decides what happens to what this hold already drained (§4.7 rule 12):
+ * `rewake` carries the proxy items and annotations to the next settle of the same
+ * turn and drops the `sessionIdle` results; `caller` drops everything `stale`;
+ * `watchdog` and `error` drop it with detail `hold_ended`; `exit` and `terminal`
+ * with detail `session_ended`. Every drop is a journal line, so nothing drained is
+ * lost silently.
+ */
+
+import { logStderr } from "../../logger.js";
+import { maxConsecutiveInjections } from "../config.js";
+import {
+ type ChainStep,
+ EVENT_TIMEOUTS,
+ type HookEngine,
+ type JournalMeta,
+ dispatchBoundMs,
+} from "../engine.js";
+import { frozenClone } from "../freeze.js";
+import { type InboxLineSource, InboxReader, inboxHasPayload } from "../injection/inbox.js";
+import type { InjectionSource } from "../injection/queue.js";
+import type { SessionAction, SessionInfo, TurnAnnotation } from "../public.js";
+import type { ApplicableHook, HookEventName } from "../registry.js";
+
+/** What the pane tells `settle()` about the turn it holds. */
+export interface HoldTurnInfo {
+ index: number;
+ answer: string;
+ stopReason: string | null;
+ apiError: boolean;
+ hookCaused: boolean;
+ /** hook-caused turns in a row so far (`ctx.consecutiveHookTurns`); 0 when absent */
+ consecutiveHookTurns?: number;
+ /** caller input is queued (`ctx.callerInputPending`); false when absent */
+ callerInputPending?: boolean;
+ /** the session's shape now (a send converts one-shot to interactive) */
+ shape?: "interactive" | "one-shot";
+}
+
+export interface HoldInjection {
+ text: string;
+ hookIds: string[];
+ source: InjectionSource;
+}
+
+export interface HoldResult {
+ injections: HoldInjection[];
+ /** set when the settle failed; the hold concludes with no injection */
+ error?: string;
+ /** pane anomaly keys this settle produced (`hook_injection_dropped:inbox_cap`) */
+ anomalies?: string[];
+ /** the annotations this hold drained, so an abandoned result can carry them (rule 12) */
+ annotations?: TurnAnnotation[];
+}
+
+/** Why the pane aborted a hold. */
+export type HoldAbortReason = "rewake" | "caller" | "watchdog" | "error" | "exit" | "terminal";
+
+/** What the binding may push into its pane: `sessionStart` injections that no hold took. */
+export interface BindingPane {
+ queueInjections(injections: HoldInjection[]): void;
+}
+
+export interface SessionHookBinding {
+ /**
+ * true while a sessionIdle hook applies, a sessionStart dispatch is running, the inbox has
+ * unread bytes, items are carried from an aborted hold, or a hook item is queued
+ */
+ hasIdleWork(queueHasHookItem: boolean): boolean;
+ /**
+ * The pane aborts `signal` with a `HoldAbortReason` when the hold ends without this
+ * result. The reason decides what happens to proxy items already drained.
+ */
+ settle(turn: HoldTurnInfo, signal: AbortSignal): Promise<HoldResult>;
+ /**
+ * A result `settle()` returned that the pane did not apply: the hold ended another way
+ * after it arrived (a re-wake or a human prompt found when the result was re-checked, a
+ * caller, an exit). Handled exactly as an abort with `reason` (§4.7 rule 12).
+ */
+ abandon?(result: HoldResult, reason: HoldAbortReason): void;
+ /**
+ * The hold watchdog, read when a hold starts: what remains of a running sessionStart
+ * dispatch (its start + its dispatch bound − now, or 0) + the inbox bound + the
+ * sessionIdle dispatch bound + 1,000 ms. A dispatch bound is min(event budget, sum of
+ * the applicable hooks' step timeouts) (§4.5). Each term bounds one stage settle() awaits.
+ */
+ holdBoundMs(): number;
+ fireStart(): void;
+ fireBlocked(block: { kind: "question" | "permission"; text: string }): void;
+ fireEnd(outcome: { state: string; reason: string | null; exitCode: number | null }): void;
+ /** `hooks.injection.maxConsecutive`; the pane uses 3 when absent */
+ readonly maxConsecutive?: number;
+ /** The pane registers itself so a sessionStart dispatch no hold took can be queued. */
+ attach?(pane: BindingPane): void;
+ /** An injection the pane dropped (stale, capped, pane_exited, …): one journal line per hook. */
+ noteDropped?(item: { text: string; hookIds: string[] }, reason: string): void;
+ /** An injection the pane admitted. */
+ noteDelivered?(item: { text: string; hookIds: string[] }): void;
+ /**
+ * The interactive driver learned (or `/clear` changed) the Claude Code session id:
+ * later contexts and journal lines carry it.
+ */
+ updateSession?(patch: Partial<Pick<SessionInfo, "id" | "claudeSessionId" | "injection">>): void;
+ /**
+ * The `sessionEnd` dispatch `fireEnd` started, settled; resolves at once when none
+ * runs. The interactive launcher awaits it (≤ 1.5 s) before shutting its proxy down.
+ */
+ endSettled?(): Promise<void>;
+ /**
+ * The session is over and nothing writes its inbox any more (the pane was reaped, or
+ * the launcher is shutting its proxy down): every payload line no settle took is
+ * journaled dropped `session_ended`, so a late `responseEnd` result is never
+ * lost without a trace.
+ */
+ sweepInbox?(): void;
+}
+
+export interface SessionHookBindingOptions {
+ /** the inbox wait bound; production: the responseEnd dispatch bound (never below the default timeout) + 500 ms */
+ inboxBoundMs?: number;
+ now?: () => number;
+}
+
+/** Added to the `responseEnd` dispatch bound to bound the inbox wait (§2.3 step 5). */
+export const INBOX_WAIT_MARGIN_MS = 500;
+/** Added to the sum of the stage bounds for the hold watchdog (§4.5). */
+export const HOLD_WATCHDOG_MARGIN_MS = 1_000;
+
+/** The events whose hooks make a pane owner attach a binding. */
+const BINDING_EVENTS: ReadonlyArray<HookEventName> = [
+ "responseEnd",
+ "sessionStart",
+ "sessionIdle",
+ "sessionBlocked",
+ "sessionEnd",
+];
+
+/** True when this engine has a hook a pane owner must drive a binding for. */
+export function sessionHooksNeedBinding(engine: HookEngine): boolean {
+ return BINDING_EVENTS.some((e) => engine.select(e).length > 0);
+}
+
+/**
+ * The production inbox wait bound for this engine: the `responseEnd` dispatch
+ * bound, never below the default timeout, + 500 ms (5.5 s with one default hook;
+ * 30.5 s at most, the budget).
+ */
+export function inboxBoundFor(engine: HookEngine): number {
+ const bound = dispatchBoundMs("responseEnd", engine.select("responseEnd"));
+ return Math.max(EVENT_TIMEOUTS.responseEnd.default, bound) + INBOX_WAIT_MARGIN_MS;
+}
+
+/**
+ * The step functions of a `sessionStart` or `sessionIdle` chain: the working
+ * state is the injections accepted so far, which later hooks see in `ctx.prior`.
+ */
+function injectionStep(
+ source: "sessionStart" | "sessionIdle",
+ context: (base: object) => object
+): ChainStep<SessionAction, HoldInjection[]> {
+ return {
+ context: (_a, base) => context(base),
+ apply: (accepted, items) => {
+ const next = [...accepted];
+ const applied: (typeof items)[number][] = [];
+ for (const p of items) {
+ if (p.action.type !== "injectUserTurn") continue;
+ next.push({ text: p.action.text, hookIds: [p.hookId], source });
+ applied.push(p);
+ }
+ // Journaled `queued` when the hold (or the pane) takes them.
+ return { state: next, results: [], applied };
+ },
+ };
+}
+
+const ABORTED = Symbol("aborted");
+
+/**
+ * `p`'s value, or ABORTED when `signal` aborts first. `onLate` receives a value that
+ * arrives after the abort won, so a caller that claimed `p` can hand it back.
+ */
+function raceAbort<T>(
+ p: Promise<T>,
+ signal: AbortSignal,
+ onLate: (v: T) => void = () => {}
+): Promise<T | typeof ABORTED> {
+ if (signal.aborted) return Promise.resolve(ABORTED);
+ return new Promise((resolve) => {
+ let lost = false;
+ const onAbort = () => {
+ lost = true;
+ resolve(ABORTED);
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ p.then(
+ (v) => {
+ signal.removeEventListener("abort", onAbort);
+ if (lost) onLate(v);
+ else resolve(v);
+ },
+ () => {
+ signal.removeEventListener("abort", onAbort);
+ resolve([] as unknown as T);
+ }
+ );
+ });
+}
+
+interface StartDispatch {
+ promise: Promise<HoldInjection[]>;
+ startedAt: number;
+ bound: number;
+ /** a hold awaits it: its injections go to that hold, not to the pane */
+ claimed: boolean;
+ /** its injections were taken, by a hold or by the pane: never twice, never none */
+ taken: boolean;
+}
+
+interface Drained {
+ start: HoldInjection[];
+ proxy: HoldInjection[];
+ annotations: TurnAnnotation[];
+ idle: HoldInjection[];
+}
+
+class EngineSessionHookBinding implements SessionHookBinding {
+ readonly maxConsecutive: number;
+ private readonly inbox: InboxReader | null;
+ private readonly inboxBoundMs: number;
+ private readonly now: () => number;
+ private meta: JournalMeta;
+ private session: SessionInfo;
+ private endDispatch: Promise<unknown> | null = null;
+ private pane: BindingPane | null = null;
+ private start: StartDispatch | null = null;
+ private startFired = false;
+ private ended = false;
+ private cappedReported = false;
+ /** sessionStart injections that resolved with no pane attached and no hold waiting */
+ private startPending: HoldInjection[] = [];
+ /** carried from a hold a re-wake abandoned (§4.7 rule 12) */
+ private carried: { injections: HoldInjection[]; annotations: TurnAnnotation[] } = {
+ injections: [],
+ annotations: [],
+ };
+
+ constructor(
+ private readonly engine: HookEngine,
+ session: SessionInfo,
+ inbox: string | InboxLineSource | null,
+ opts: SessionHookBindingOptions
+ ) {
+ this.session = session;
+ this.inbox = inbox ? new InboxReader(inbox) : null;
+ this.inboxBoundMs = opts.inboxBoundMs ?? inboxBoundFor(engine);
+ this.now = opts.now ?? Date.now;
+ this.maxConsecutive = maxConsecutiveInjections(engine.config);
+ this.meta = {
+ model: session.model,
+ provider: "",
+ ...(session.claudeSessionId ? { sessionId: session.claudeSessionId } : {}),
+ };
+ }
+
+ updateSession(patch: Partial<Pick<SessionInfo, "id" | "claudeSessionId" | "injection">>): void {
+ this.session = Object.freeze({ ...this.session, ...patch });
+ this.meta = {
+ model: this.session.model,
+ provider: "",
+ ...(this.session.claudeSessionId ? { sessionId: this.session.claudeSessionId } : {}),
+ };
+ }
+
+ endSettled(): Promise<void> {
+ return this.endDispatch ? this.endDispatch.then(() => {}) : Promise.resolve();
+ }
+
+ attach(pane: BindingPane): void {
+ this.pane = pane;
+ if (this.startPending.length > 0) {
+ const items = this.startPending;
+ this.startPending = [];
+ pane.queueInjections(items);
+ }
+ }
+
+ private scope() {
+ return { sessionModel: this.session.model };
+ }
+
+ private idleHooks(): ApplicableHook[] {
+ return this.engine.select("sessionIdle", this.scope());
+ }
+
+ hasIdleWork(queueHasHookItem: boolean): boolean {
+ return (
+ queueHasHookItem ||
+ this.idleHooks().length > 0 ||
+ this.start !== null ||
+ this.startPending.length > 0 ||
+ this.carried.injections.length > 0 ||
+ this.carried.annotations.length > 0 ||
+ (this.inbox?.hasUnread() ?? false)
+ );
+ }
+
+ holdBoundMs(): number {
+ const s = this.start;
+ const startRemaining = s ? Math.max(0, s.startedAt + s.bound - this.now()) : 0;
+ const idle = dispatchBoundMs("sessionIdle", this.idleHooks());
+ return startRemaining + this.inboxBoundMs + idle + HOLD_WATCHDOG_MARGIN_MS;
+ }
+
+ /* ───────────── settle ───────────── */
+
+ async settle(turn: HoldTurnInfo, signal: AbortSignal): Promise<HoldResult> {
+ const anomalies: string[] = [];
+ const d: Drained = {
+ start: [...this.startPending],
+ proxy: [...this.carried.injections],
+ annotations: [...this.carried.annotations],
+ idle: [],
+ };
+ this.startPending = [];
+ this.carried = { injections: [], annotations: [] };
+
+ // 1. A sessionStart dispatch still running holds this settle, within its own bound.
+ const start = this.start;
+ if (start) {
+ start.claimed = true;
+ // An abort can win the race after the dispatch resolved and its own handler left
+ // the items to this claim: they are handed back, not lost.
+ const got = await raceAbort(start.promise, signal, (items) => this.unclaimed(start, items));
+ if (got === ABORTED) start.claimed = false;
+ else {
+ start.taken = true;
+ d.start.push(...got);
+ }
+ }
+
+ // 2. The inbox: proxy-event injections and annotations of this turn's responses.
+ if (!signal.aborted && this.inbox) {
+ const drained = await this.inbox.drain(this.inboxBoundMs, signal);
+ for (const i of drained.injections)
+ d.proxy.push({ text: i.text, hookIds: [i.hookId], source: "proxy" });
+ for (const a of drained.annotations)
+ d.annotations.push({ hookId: a.hookId, key: a.key, value: a.value });
+ // held to the child's action rules; never offered
+ for (const x of drained.invalid) {
+ anomalies.push("hook_injection_dropped:invalid");
+ this.engine.journal({
+ ...this.meta,
+ event: "responseEnd",
+ hookId: x.hookId,
+ action: x.kind === "inject" ? "injectUserTurn" : "annotateTurn",
+ decision: "invalid",
+ detail: `inbox: ${x.reason}`,
+ });
+ }
+ // a request whose responseEnd outran the bound; its later lines go to the
+ // next settle, or to the sweep when there is none
+ for (const req of drained.timedOut) {
+ anomalies.push("hook_inbox_wait_timeout");
+ this.engine.journal({
+ ...this.meta,
+ event: "responseEnd",
+ hookId: "inbox",
+ action: "injectUserTurn",
+ decision: "timeout",
+ detail: `request ${req} still running at the ${this.inboxBoundMs} ms inbox bound`,
+ });
+ }
+ if (drained.capped && !this.cappedReported) {
+ this.cappedReported = true;
+ anomalies.push("hook_injection_dropped:inbox_cap");
+ this.journalDrop("responseEnd", "injectUserTurn", "inbox", "inbox_cap");
+ }
+ }
+
+ // 3. The sessionIdle chain, with this turn's annotations. The session and
+ // turn facts are read once, here, at the start of the dispatch.
+ if (!signal.aborted) {
+ const hooks = this.idleHooks();
+ if (hooks.length > 0) {
+ // A deep-frozen copy: an annotation's value can be an object or an array, and
+ // `d.annotations` is carried into the hold result and across a re-wake.
+ const annotations = frozenClone(d.annotations);
+ const session = this.sessionFor(turn);
+ const facts = {
+ event: "sessionIdle",
+ session,
+ turn: Object.freeze({
+ index: turn.index,
+ answer: turn.answer,
+ stopReason: turn.stopReason,
+ apiError: turn.apiError,
+ hookCaused: turn.hookCaused,
+ annotations,
+ }),
+ consecutiveHookTurns: turn.consecutiveHookTurns ?? 0,
+ callerInputPending: turn.callerInputPending ?? false,
+ };
+ const chain = await this.engine.runChain(
+ "sessionIdle",
+ hooks,
+ injectionStep("sessionIdle", (base) => ({ ...base, ...facts })),
+ this.meta,
+ { initial: [], signal }
+ );
+ d.idle.push(...chain.state);
+ }
+ }
+
+ if (signal.aborted) {
+ this.onAborted(signal.reason, d);
+ return { injections: [], anomalies };
+ }
+ const injections = [...d.start, ...d.proxy, ...d.idle];
+ for (const i of injections) this.journalItem(i, "queued");
+ return { injections, anomalies, annotations: d.annotations };
+ }
+
+ abandon(result: HoldResult, reason: HoldAbortReason): void {
+ const of = (s: InjectionSource) => result.injections.filter((i) => i.source === s);
+ this.onAborted(reason, {
+ start: of("sessionStart"),
+ proxy: of("proxy"),
+ idle: of("sessionIdle"),
+ annotations: [...(result.annotations ?? [])],
+ });
+ }
+
+ /** §4.7 rule 12: what a hold that ended without its result does with what it drained. */
+ private onAborted(reason: unknown, d: Drained): void {
+ const r = (typeof reason === "string" ? reason : "error") as HoldAbortReason;
+ if (r === "rewake" && !this.ended) {
+ this.carried = {
+ injections: [...this.carried.injections, ...d.start, ...d.proxy],
+ annotations: [...this.carried.annotations, ...d.annotations],
+ };
+ for (const i of d.idle) this.journalItem(i, "dropped", "rewake");
+ return;
+ }
+ // A re-wake after the session ended has no next settle to carry to.
+ const detail =
+ r === "caller" ? "stale" : r === "watchdog" || r === "error" ? "hold_ended" : "session_ended";
+ for (const i of [...d.start, ...d.proxy, ...d.idle]) this.journalItem(i, "dropped", detail);
+ for (const a of d.annotations) this.journalAnnotation(a, detail);
+ }
+
+ /* ───────────── other events ───────────── */
+
+ fireStart(): void {
+ if (this.startFired || this.ended) return;
+ this.startFired = true;
+ const hooks = this.engine.select("sessionStart", this.scope());
+ if (hooks.length === 0) return;
+ const bound = dispatchBoundMs("sessionStart", hooks);
+ const session = this.sessionFor();
+ const promise = this.engine
+ .runChain(
+ "sessionStart",
+ hooks,
+ injectionStep("sessionStart", (base) => ({ ...base, event: "sessionStart", session })),
+ this.meta,
+ { initial: [] }
+ )
+ .then((r) => r.state)
+ .catch(() => [] as HoldInjection[]);
+ const entry: StartDispatch = {
+ promise,
+ startedAt: this.now(),
+ bound,
+ claimed: false,
+ taken: false,
+ };
+ this.start = entry;
+ void promise.then((items) => {
+ if (this.start === entry) this.start = null;
+ if (entry.claimed) return; // the hold awaiting it takes them
+ this.unclaimed(entry, items);
+ });
+ }
+
+ /** A sessionStart dispatch's injections that no hold took: the pane's, or dropped. */
+ private unclaimed(entry: StartDispatch, items: HoldInjection[]): void {
+ if (entry.taken) return;
+ entry.taken = true;
+ if (this.ended) {
+ for (const i of items) this.journalItem(i, "dropped", "session_ended");
+ return;
+ }
+ for (const i of items) this.journalItem(i, "queued");
+ if (this.pane) this.pane.queueInjections(items);
+ else this.startPending.push(...items);
+ }
+
+ fireBlocked(block: { kind: "question" | "permission"; text: string }): void {
+ if (this.ended) return;
+ const hooks = this.engine.select("sessionBlocked", this.scope());
+ if (hooks.length === 0) return;
+ const session = this.sessionFor();
+ const facts = { event: "sessionBlocked", session, block: Object.freeze({ ...block }) };
+ // Only `warn` is allowed: an observing chain, nothing to apply. Never rejects
+ // into the caller, as fireStart/fireEnd do not.
+ void this.engine
+ .runChain(
+ "sessionBlocked",
+ hooks,
+ { context: (_a, base) => ({ ...base, ...facts }) },
+ this.meta,
+ { initial: undefined }
+ )
+ .catch(() => undefined);
+ }
+
+ fireEnd(outcome: { state: string; reason: string | null; exitCode: number | null }): void {
+ if (this.ended) return;
+ this.ended = true;
+ // Items a re-wake carried that no later settle took (§4.7 rule 12).
+ for (const i of [...this.carried.injections, ...this.startPending])
+ this.journalItem(i, "dropped", "session_ended");
+ for (const a of this.carried.annotations) this.journalAnnotation(a, "session_ended");
+ this.carried = { injections: [], annotations: [] };
+ this.startPending = [];
+ const hooks = this.engine.select("sessionEnd", this.scope());
+ if (hooks.length === 0) return;
+ const session = this.sessionFor();
+ const facts = { event: "sessionEnd", session, outcome: Object.freeze({ ...outcome }) };
+ // The 1.5 s budget bounds the whole chain, so the launcher's exit wait holds.
+ this.endDispatch = this.engine
+ .runChain(
+ "sessionEnd",
+ hooks,
+ { context: (_a, base) => ({ ...base, ...facts }) },
+ this.meta,
+ { initial: undefined }
+ )
+ .catch(() => undefined);
+ }
+
+ sweepInbox(): void {
+ if (!this.inbox) return;
+ let lines: ReturnType<InboxReader["takeRemaining"]>;
+ try {
+ lines = this.inbox.takeRemaining();
+ } catch {
+ return;
+ }
+ for (const l of lines)
+ this.journalDrop(
+ "responseEnd",
+ l.kind === "inject" ? "injectUserTurn" : "annotateTurn",
+ l.hookId,
+ "session_ended"
+ );
+ }
+
+ noteDropped(item: { text: string; hookIds: string[] }, reason: string): void {
+ for (const hookId of item.hookIds)
+ this.engine.journal({
+ ...this.meta,
+ event: "sessionIdle",
+ hookId,
+ action: "injectUserTurn",
+ decision: "dropped",
+ detail: reason,
+ });
+ }
+
+ noteDelivered(item: { text: string; hookIds: string[] }): void {
+ for (const hookId of item.hookIds)
+ this.engine.journal({
+ ...this.meta,
+ event: "sessionIdle",
+ hookId,
+ action: "injectUserTurn",
+ decision: "delivered",
+ });
+ }
+
+ /* ───────────── helpers ───────────── */
+
+ private sessionFor(turn?: HoldTurnInfo): SessionInfo {
+ return Object.freeze({ ...this.session, ...(turn?.shape ? { shape: turn.shape } : {}) });
+ }
+
+ private eventOf(source: InjectionSource): HookEventName {
+ return source === "proxy" ? "responseEnd" : source;
+ }
+
+ private journalItem(i: HoldInjection, decision: "queued" | "dropped", detail?: string): void {
+ for (const hookId of i.hookIds)
+ this.engine.journal({
+ ...this.meta,
+ event: this.eventOf(i.source),
+ hookId,
+ action: "injectUserTurn",
+ decision,
+ ...(detail ? { detail } : {}),
+ });
+ }
+
+ private journalAnnotation(a: TurnAnnotation, detail: string): void {
+ this.engine.journal({
+ ...this.meta,
+ event: "responseEnd",
+ hookId: a.hookId,
+ action: "annotateTurn",
+ decision: "dropped",
+ detail,
+ });
+ }
+
+ private journalDrop(event: HookEventName, action: string, hookId: string, detail: string): void {
+ this.engine.journal({ ...this.meta, event, hookId, action, decision: "dropped", detail });
+ }
+}
+
+/**
+ * The real binding. `inbox` is a pane child's inbox file, the interactive launcher's
+ * in-memory source (`InProcessSink.inbox`), or null. `inboxBoundMs` and `now` exist for
+ * tests (H-21b, H-35, H-36); production passes neither, and the inbox bound is §2.3
+ * step 5's.
+ */
+export function createSessionHookBinding(
+ engine: HookEngine,
+ session: SessionInfo,
+ inbox: string | InboxLineSource | null,
+ opts: SessionHookBindingOptions = {}
+): SessionHookBinding {
+ return new EngineSessionHookBinding(engine, session, inbox, opts);
+}
+
+/* ───────────── owner without hooks (§2.3 step 1) ───────────── */
+
+let ownerWithoutHooksReported = false;
+
+/**
+ * At reap, an owner WITHOUT a binding checks its child's inbox once: a child that
+ * loaded hooks this process did not (a config edit after the server started) may
+ * have produced injections nobody will deliver. Journals
+ * `hook_injection_dropped:owner_without_hooks` and prints one stderr line per
+ * process. Returns true when it found any.
+ */
+export function reportOwnerWithoutHooks(
+ inboxPath: string,
+ engine: HookEngine | null,
+ meta: { model: string; sessionId?: string },
+ warn: (line: string) => void = logStderr
+): boolean {
+ if (!inboxHasPayload(inboxPath)) return false;
+ engine?.journal({
+ model: meta.model,
+ provider: "",
+ ...(meta.sessionId ? { sessionId: meta.sessionId } : {}),
+ event: "sessionEnd",
+ hookId: "inbox",
+ action: "injectUserTurn",
+ decision: "dropped",
+ detail: "owner_without_hooks",
+ });
+ if (!ownerWithoutHooksReported) {
+ ownerWithoutHooksReported = true;
+ warn(
+ "a pane child produced hook injections, but this process loaded no session hooks: restart the MCP server after changing hooks.modules"
+ );
+ }
+ return true;
+}
+
+/** Test seam: let the next owner-without-hooks report print its stderr line again. */
+export function resetOwnerWithoutHooksReportForTests(): void {
+ ownerWithoutHooksReported = false;
+}