Skip to content

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

test(hooks): run child-to-owner hook injection against a stub upstream

Jack Rudenkodb5bb0db440c
diff --git a/packages/cli/src/hooks/session/cross-process.integration.test.ts b/packages/cli/src/hooks/session/cross-process.integration.test.ts
new file mode 100644
index 00000000..c2f375b2
--- /dev/null
+++ b/packages/cli/src/hooks/session/cross-process.integration.test.ts
@@ -0,0 +1,362 @@
+/**
+ * Cross-process session hooks (hook-system architecture §2.3, §11.3 "Cross-process"):
+ * the owner (a real channel `SessionManager` in this process) + the REAL child claudish
+ * (`src/index.ts` as `CLAUDISH_BIN`) in a real magmux pane + the fake Claude Code in
+ * proxied mode (`FAKE_CLAUDE_PROXY=1`), whose every turn is a streaming `/v1/messages`
+ * through the child's proxy to a stub upstream (`stub@fake-model` via `customEndpoints`
+ * in the `CLAUDISH_CONFIG` file).
+ *
+ * The child loads its hooks from that config; the owner's engine is built here. What
+ * crosses the process boundary is only the owner-created inbox file.
+ */
+
+import { afterAll, describe, expect, spyOn, test } from "bun:test";
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { SessionManager } from "../../channel/session-manager.js";
+import * as logger from "../../logger.js";
+import {
+ MAGMUX,
+ NO_MAGMUX_MESSAGE,
+ type PaneTestEnv,
+ killLeftovers,
+ makePaneTestEnv,
+ waitNoOrphans,
+ writeFakeClaudeWrapper,
+} from "../../pane/test-helpers/hermetic-env.js";
+import {
+ type StubScript,
+ type StubUpstream,
+ startStubUpstream,
+ stubEndpointConfig,
+} from "../../test-helpers/stub-upstream.js";
+import { HookEngine } from "../engine.js";
+import type { JournalEntry } from "../journal.js";
+import type { HookDefinition, TurnAnnotation } from "../public.js";
+import { HookRegistry, type UserHookInput } from "../registry.js";
+import { resetOwnerWithoutHooksReportForTests } from "./binding.js";
+
+const INDEX = join(import.meta.dir, "..", "..", "index.ts");
+const T = 90_000;
+
+const open = new Set<{ t: PaneTestEnv; stub: StubUpstream }>();
+afterAll(() => {
+ for (const o of open) {
+ o.stub.stop();
+ killLeftovers({ sockRoot: o.t.sockRoot });
+ o.t.cleanup();
+ }
+});
+
+function ownerEngine(...defs: Array<Omit<HookDefinition, "apiVersion">>) {
+ const journal: JournalEntry[] = [];
+ const users: UserHookInput[] = defs.map((d, i) => ({
+ id: `hook:owner/${d.id}`,
+ module: "/hooks/owner.ts",
+ moduleIndex: 0,
+ exportIndex: i,
+ def: { apiVersion: 1, ...d } as HookDefinition,
+ }));
+ const engine = new HookEngine({
+ registry: new HookRegistry([], users, undefined),
+ config: {},
+ hostMode: "mcp",
+ journalSink: (e) => journal.push(e),
+ warn: () => {},
+ drainTelemetryOutbox: false,
+ });
+ return { engine, journal };
+}
+
+interface Rig {
+ t: PaneTestEnv;
+ stub: StubUpstream;
+ manager: SessionManager;
+ id: string;
+ keylog(): string[];
+ info(): ReturnType<SessionManager["getSession"]>;
+ output(): string;
+}
+
+/**
+ * One session: the child's hook module source (written to the test's temp dir and named
+ * in `hooks.modules`), the stub's script, and the owner's engine.
+ */
+async function rig(o: {
+ childHooks: string;
+ stub: StubScript;
+ engine: HookEngine;
+ prompt?: string | null;
+ extraEnv?: Record<string, string>;
+}): Promise<Rig> {
+ const stub = startStubUpstream({ format: "openai-sse", script: o.stub });
+ const t = makePaneTestEnv();
+ open.add({ t, stub });
+ const module = join(t.tmp, "child-hooks.js");
+ writeFileSync(module, o.childHooks);
+ const config = join(t.tmp, "claudish-config.json");
+ writeFileSync(
+ config,
+ JSON.stringify({ ...stubEndpointConfig(stub), hooks: { modules: [module] } }, null, 2)
+ );
+ Object.assign(t.env, {
+ CLAUDISH_BIN: INDEX,
+ CLAUDE_PATH: writeFakeClaudeWrapper(t.tmp),
+ CLAUDISH_CONFIG: config,
+ FAKE_CLAUDE_PROXY: "1",
+ FAKE_KEYLOG: join(t.tmp, "keylog.txt"),
+ CONTRACT_FAKE_MAX_MS: "80000",
+ ...o.extraEnv,
+ });
+ const manager = new SessionManager({
+ maxSessions: 4,
+ sessionsDir: join(t.tmp, "sessions"),
+ hostPid: 1,
+ parentEnv: t.env,
+ paneTimings: { replStableMs: 200, corroborationMs: 200 },
+ hookEngine: async () => o.engine,
+ });
+ const prompt = o.prompt === undefined ? "Reply first." : o.prompt;
+ const id = await manager.createSession({
+ model: "stub@fake-model",
+ cwd: t.cwd,
+ ...(prompt ? { prompt } : {}),
+ });
+ return {
+ t,
+ stub,
+ manager,
+ id,
+ keylog: () => {
+ const p = t.env.FAKE_KEYLOG as string;
+ return existsSync(p) ? readFileSync(p, "utf8").split("\n").filter(Boolean) : [];
+ },
+ info: () => manager.getSession(id),
+ output: () => manager.getOutput(id).output,
+ };
+}
+
+async function finish(r: Rig): Promise<void> {
+ await r.manager.shutdownAll();
+ const left = await waitNoOrphans({ sockRoot: r.t.sockRoot }, 10_000);
+ r.stub.stop();
+ killLeftovers({ sockRoot: r.t.sockRoot });
+ for (const o of open) if (o.t === r.t) open.delete(o);
+ r.t.cleanup();
+ expect(left).toEqual({ processes: [], files: [] });
+}
+
+async function until(pred: () => boolean, what: string, ms = 45_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(50);
+ }
+}
+
+const TERMINAL = ["COMPLETED", "FAILED", "CANCELLED", "TIMEOUT", "EMPTY"];
+
+/** A child hook that injects once and annotates every response (never on the injected turn). */
+const INJECT_ONCE = `export default [{
+ apiVersion: 1,
+ id: "inject",
+ on: {
+ responseEnd(ctx) {
+ const last = ctx.request.messages[ctx.request.messages.length - 1];
+ const text = typeof last?.content === "string" ? last.content : "";
+ if (text.includes("INJECTED")) return [];
+ return [
+ { type: "injectUserTurn", text: "INJECTED-TURN" },
+ { type: "annotateTurn", key: "seen", value: text },
+ ];
+ },
+ },
+}];
+`;
+
+describe.skipIf(!MAGMUX)(`cross-process injection ${MAGMUX ? "" : NO_MAGMUX_MESSAGE}`, () => {
+ test(
+ "a responseEnd hook in the child injects; the owner delivers it as the next turn; its annotation reaches sessionIdle",
+ async () => {
+ const seen: TurnAnnotation[][] = [];
+ const { engine } = ownerEngine({
+ id: "idle",
+ on: {
+ sessionIdle: (ctx) => {
+ seen.push([...ctx.turn.annotations]);
+ return [];
+ },
+ },
+ });
+ const r = await rig({
+ childHooks: INJECT_ONCE,
+ stub: [{ parts: [{ text: "STUB-ONE" }] }, { parts: [{ text: "STUB-TWO" }] }],
+ engine,
+ });
+ try {
+ await until(() => TERMINAL.includes(r.info().state), "a terminal state");
+ const info = r.info();
+ expect(info.state).toBe("COMPLETED");
+ expect(info.turnsCompleted).toBe(2);
+ expect(r.keylog()).toContain("INJECTED-TURN");
+ const out = r.output();
+ expect(out).toContain("STUB-ONE");
+ expect(out).toContain("STUB-TWO");
+ // the child's proxy really carried both turns
+ expect(r.stub.requests.length).toBe(2);
+ expect(seen[0]).toEqual([
+ { hookId: "hook:child-hooks/inject", key: "seen", value: "Reply first." },
+ ]);
+ // the injected turn's response annotated nothing
+ expect(seen[1]).toEqual([]);
+ } finally {
+ await finish(r);
+ }
+ },
+ T
+ );
+
+ test(
+ "the child is killed between stop and end: the owner's wait ends at the exit, not at the 30.5 s bound",
+ async () => {
+ // the child's responseEnd never resolves (timeout 30 s): `stop` is on disk, `end` is not
+ const hang = `export default [{
+ apiVersion: 1, id: "hang", timeoutMs: 30000,
+ on: { responseEnd: () => new Promise(() => {}) },
+}];
+`;
+ const { engine } = ownerEngine({
+ id: "end",
+ timeoutMs: 30_000,
+ on: { responseEnd: () => [] },
+ });
+ const r = await rig({ childHooks: hang, stub: [{ parts: [{ text: "STUB-ONE" }] }], engine });
+ try {
+ await until(() => r.manager.getDiagnostics(r.id).phase === "SETTLING", "the hold");
+ await Bun.sleep(300);
+ expect(r.manager.getDiagnostics(r.id).phase).toBe("SETTLING");
+ const pid = r.info().panePid as number;
+ const t0 = Date.now();
+ process.kill(pid, "SIGKILL");
+ await until(() => TERMINAL.includes(r.info().state), "a terminal state", 15_000);
+ expect(Date.now() - t0).toBeLessThan(5_000);
+ expect(r.info().state).toBe("COMPLETED");
+ expect(r.output()).toContain("STUB-ONE");
+ } finally {
+ await finish(r);
+ }
+ },
+ T
+ );
+
+ test(
+ "a request still streaming at settle (no stop) is not waited for; its later inject is delivered at the next settle",
+ async () => {
+ // turn 1 is answered at once; a side request (a background subagent's stream) is
+ // fired and not awaited, and its stream takes ~4 s. Its responseEnd injects.
+ const side = `export default [{
+ apiVersion: 1, id: "side",
+ on: {
+ responseEnd(ctx) {
+ const last = ctx.request.messages[ctx.request.messages.length - 1];
+ const text = typeof last?.content === "string" ? last.content : "";
+ return text === "SIDE-REQUEST" ? [{ type: "injectUserTurn", text: "FROM-SIDE" }] : [];
+ },
+ },
+}];
+`;
+ const { engine } = ownerEngine({ id: "end", on: { responseEnd: () => [] } });
+ const lastText = (body: unknown) => {
+ const msgs = (body as { messages?: Array<{ content?: unknown }> }).messages ?? [];
+ return JSON.stringify(msgs[msgs.length - 1]?.content ?? "");
+ };
+ const r2 = await rig({
+ childHooks: side,
+ engine,
+ prompt: null,
+ extraEnv: { FAKE_CLAUDE_SIDE: "SIDE-REQUEST" },
+ stub: (req) => {
+ const last = lastText(req.body);
+ if (last.includes("SIDE-REQUEST"))
+ return { parts: [{ text: "SIDE-ANSWER" }], deltaChars: 1, chunkDelayMs: 350 };
+ if (last.includes("FROM-SIDE")) return { parts: [{ text: "STUB-THREE" }] };
+ if (last.includes("second")) return { parts: [{ text: "STUB-TWO" }] };
+ return { parts: [{ text: "STUB-ONE" }] };
+ },
+ });
+ const { manager, id } = r2;
+ try {
+ await until(() => r2.info().state === "AWAITING_INPUT", "boot");
+ const t0 = Date.now();
+ manager.sendInput(id, "Reply first.");
+ await until(
+ () => r2.info().turnsCompleted === 1 && r2.info().state === "AWAITING_INPUT",
+ "turn 1 settled"
+ );
+ // settled (and the hold done) while the side stream (~4 s) is still running
+ expect(Date.now() - t0).toBeLessThan(3_500);
+ expect(r2.keylog()).not.toContain("FROM-SIDE");
+ // the side stream ends; its inject waits for the next settle
+ await until(
+ () =>
+ readFileSync(
+ join(manager.getDiagnostics(id).sessionDir, "hook-inbox.jsonl"),
+ "utf8"
+ ).includes("FROM-SIDE"),
+ "the side inject in the inbox",
+ 20_000
+ );
+ expect(r2.keylog()).not.toContain("FROM-SIDE");
+ manager.sendInput(id, "Reply second.");
+ await until(
+ () => r2.keylog().includes("FROM-SIDE"),
+ "FROM-SIDE delivered at the next settle"
+ );
+ await until(() => r2.info().turnsCompleted === 3, "turn 3");
+ expect(r2.output()).toContain("STUB-THREE");
+ } finally {
+ await finish(r2);
+ }
+ },
+ T
+ );
+
+ test(
+ "an owner without session hooks and a child whose responseEnd injects: owner_without_hooks at reap, one stderr line",
+ async () => {
+ resetOwnerWithoutHooksReportForTests();
+ const stderr = spyOn(logger, "logStderr");
+ const { engine, journal } = ownerEngine(); // no session hook: no binding
+ const r = await rig({
+ childHooks: INJECT_ONCE,
+ stub: [{ parts: [{ text: "STUB-ONE" }] }],
+ engine,
+ });
+ try {
+ await until(() => TERMINAL.includes(r.info().state), "a terminal state");
+ expect(r.info().state).toBe("COMPLETED");
+ expect(r.info().turnsCompleted).toBe(1);
+ expect(r.keylog()).not.toContain("INJECTED-TURN");
+ await until(
+ () => journal.some((j) => j.detail === "owner_without_hooks"),
+ "the reap check",
+ 20_000
+ );
+ const lines = stderr.mock.calls
+ .map((c) => String(c[0]))
+ .filter((l) => l.includes("loaded no session hooks"));
+ expect(lines).toEqual([
+ "a pane child produced hook injections, but this process loaded no session hooks: restart the MCP server after changing hooks.modules",
+ ]);
+ // the owner deletes the inbox at reap
+ expect(
+ existsSync(join(r.manager.getDiagnostics(r.id).sessionDir, "hook-inbox.jsonl"))
+ ).toBe(false);
+ } finally {
+ stderr.mockRestore();
+ await finish(r);
+ }
+ },
+ T
+ );
+});
diff --git a/packages/cli/src/test-helpers/stub-upstream.test.ts b/packages/cli/src/test-helpers/stub-upstream.test.ts
new file mode 100644
index 00000000..81873c68
--- /dev/null
+++ b/packages/cli/src/test-helpers/stub-upstream.test.ts
@@ -0,0 +1,128 @@
+/**
+ * The stub upstream harness (hook-system §11.2): every format streams the scripted
+ * parts, records the request, and can split a multi-byte character across chunks.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import {
+ type StubFormat,
+ type StubUpstream,
+ startStubUpstream,
+ stubChunks,
+ stubEndpointConfig,
+ stubEvents,
+} from "./stub-upstream.js";
+
+let stub: StubUpstream | null = null;
+afterEach(() => {
+ stub?.stop();
+ stub = null;
+});
+
+const dataOf = (sse: string) =>
+ sse
+ .split("\n\n")
+ .flatMap((e) => e.split("\n"))
+ .filter((l) => l.startsWith("data: ") && !l.includes("[DONE]"))
+ .map((l) => JSON.parse(l.slice(6)));
+
+async function readChunks(res: Response): Promise<Uint8Array[]> {
+ const out: Uint8Array[] = [];
+ const reader = (res.body as ReadableStream<Uint8Array>).getReader();
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) return out;
+ out.push(value);
+ }
+}
+
+describe("startStubUpstream", () => {
+ for (const format of ["openai-sse", "anthropic-sse", "openai-responses-sse"] as StubFormat[]) {
+ test(`${format}: text, thinking and a tool call stream in order; the request is recorded`, async () => {
+ stub = startStubUpstream({
+ format,
+ script: [
+ {
+ parts: [
+ { thinking: "hmm" },
+ { text: "héllo" },
+ { toolCall: { name: "Write", args: { p: 1 } } },
+ ],
+ deltaChars: 2,
+ },
+ ],
+ });
+ const res = await fetch(`${stub.url}/v1/chat/completions`, {
+ method: "POST",
+ body: JSON.stringify({ model: "fake-model", messages: [{ role: "user", content: "hi" }] }),
+ });
+ expect(res.headers.get("content-type")).toBe("text/event-stream");
+ const text = await res.text();
+ const events = dataOf(text);
+ const blob = JSON.stringify(events);
+ // deltas of 2 characters: "héllo" → "hé", "ll", "o"
+ for (const piece of ["hm", "hé", "ll", "Write"]) expect(blob).toContain(piece);
+ expect(stub.requests).toHaveLength(1);
+ expect(stub.requests[0]?.path).toBe("/v1/chat/completions");
+ expect((stub.requests[0]?.body as { model: string }).model).toBe("fake-model");
+ });
+ }
+
+ test("a tool-only response finishes with tool_calls (openai) / tool_use (anthropic)", () => {
+ const r = { parts: [{ toolCall: { name: "Bash", args: { command: "ls" } } }] };
+ expect(JSON.stringify(dataOf(stubEvents("openai-sse", r).join("")))).toContain(
+ '"finish_reason":"tool_calls"'
+ );
+ expect(JSON.stringify(dataOf(stubEvents("anthropic-sse", r).join("")))).toContain(
+ '"stop_reason":"tool_use"'
+ );
+ });
+
+ test("splitMultibyte cuts one network chunk inside a multi-byte character", async () => {
+ const events = stubEvents("openai-sse", { parts: [{ text: "答え" }] });
+ const chunks = stubChunks(events, true);
+ expect(chunks.length).toBe(events.length + 1);
+ const dec = new TextDecoder("utf-8", { fatal: true });
+ // some chunk ends mid-character: a fatal decoder rejects it on its own
+ expect(
+ chunks.some((c) => {
+ try {
+ dec.decode(c);
+ return false;
+ } catch {
+ return true;
+ }
+ })
+ ).toBe(true);
+ // and the stream reassembles byte-exactly
+ stub = startStubUpstream({
+ format: "openai-sse",
+ script: [{ parts: [{ text: "答え" }], splitMultibyte: true }],
+ });
+ const res = await fetch(`${stub.url}/v1/chat/completions`, { method: "POST", body: "{}" });
+ const got = await readChunks(res);
+ const joined = new TextDecoder().decode(Buffer.concat(got.map((c) => Buffer.from(c))));
+ expect(joined).toBe(events.join(""));
+ });
+
+ test("chunkDelayMs paces the chunks; a script function answers per request; status errors", async () => {
+ stub = startStubUpstream({
+ format: "anthropic-sse",
+ script: (_req, n) =>
+ n === 0 ? { parts: [{ text: "a" }], chunkDelayMs: 40 } : { parts: [], status: 503 },
+ });
+ const t0 = Date.now();
+ await (await fetch(stub.url, { method: "POST", body: "{}" })).text();
+ expect(Date.now() - t0).toBeGreaterThanOrEqual(40 * 5);
+ expect((await fetch(stub.url, { method: "POST", body: "{}" })).status).toBe(503);
+ });
+
+ test("stubEndpointConfig routes stub@<model> through a keyless simple openai endpoint", () => {
+ stub = startStubUpstream({ format: "openai-sse", script: [] });
+ expect(stubEndpointConfig(stub)).toEqual({
+ customEndpoints: {
+ stub: { kind: "simple", url: `${stub.url}/v1`, format: "openai", authScheme: "none" },
+ },
+ });
+ });
+});
diff --git a/packages/cli/src/test-helpers/stub-upstream.ts b/packages/cli/src/test-helpers/stub-upstream.ts
new file mode 100644
index 00000000..bf4a3c6e
--- /dev/null
+++ b/packages/cli/src/test-helpers/stub-upstream.ts
@@ -0,0 +1,453 @@
+/**
+ * A scripted provider for hermetic end-to-end hook tests (hook-system §11.2). Test-only.
+ *
+ * `startStubUpstream({ format, script })` starts a `Bun.serve` on 127.0.0.1 that
+ * answers EVERY POST with the next scripted response in the given stream format and
+ * records each request body. A pane child reaches it through a `customEndpoints`
+ * entry in the config file named by `CLAUDISH_CONFIG` (`stubEndpointConfig`), so
+ * `stub@fake-model` routes here.
+ *
+ * A response is a list of parts — text, thinking, tool calls (a tool-only response
+ * is a list with only tool calls) — streamed as one event per delta. Chunk size and
+ * the delay between network chunks are controllable, and `splitMultibyte` cuts one
+ * network chunk inside a multi-byte UTF-8 character, so a parser's decoder must carry
+ * the partial character across reads.
+ */
+
+export type StubFormat = "openai-sse" | "anthropic-sse" | "openai-responses-sse";
+
+export type StubPart =
+ | { text: string }
+ | { thinking: string }
+ | { toolCall: { name: string; args: Record<string, unknown>; id?: string } };
+
+export interface StubResponse {
+ parts: StubPart[];
+ /** split each text/thinking part into deltas of this many characters (default: one delta) */
+ deltaChars?: number;
+ /** delay before each network chunk after the first (default 0) */
+ chunkDelayMs?: number;
+ /** cut one network chunk inside the first multi-byte character of the body */
+ splitMultibyte?: boolean;
+ /** an HTTP error status instead of a stream */
+ status?: number;
+}
+
+export interface StubRequest {
+ path: string;
+ body: unknown;
+ at: number;
+}
+
+export interface StubUpstream {
+ url: string;
+ requests: StubRequest[];
+ stop(): void;
+}
+
+export type StubScript = StubResponse[] | ((req: StubRequest, n: number) => StubResponse);
+
+function pieces(s: string, n: number | undefined): string[] {
+ if (!n || n <= 0 || s.length <= n) return [s];
+ const out: string[] = [];
+ const chars = Array.from(s);
+ for (let i = 0; i < chars.length; i += n) out.push(chars.slice(i, i + n).join(""));
+ return out;
+}
+
+const sse = (data: unknown, event?: string) =>
+ `${event ? `event: ${event}\n` : ""}data: ${typeof data === "string" ? data : JSON.stringify(data)}\n\n`;
+
+/** Every event of one response, as SSE text, in order. */
+export function stubEvents(format: StubFormat, r: StubResponse, model = "fake-model"): string[] {
+ switch (format) {
+ case "openai-sse":
+ return openaiEvents(r, model);
+ case "anthropic-sse":
+ return anthropicEvents(r, model);
+ case "openai-responses-sse":
+ return responsesEvents(r, model);
+ }
+}
+
+function openaiEvents(r: StubResponse, model: string): string[] {
+ const base = { id: "chatcmpl-stub", object: "chat.completion.chunk", created: 0, model };
+ const chunk = (delta: Record<string, unknown>, finish: string | null = null) =>
+ sse({ ...base, choices: [{ index: 0, delta, finish_reason: finish }] });
+ const out = [chunk({ role: "assistant", content: "" })];
+ let tool = 0;
+ for (const p of r.parts) {
+ if ("text" in p) for (const t of pieces(p.text, r.deltaChars)) out.push(chunk({ content: t }));
+ else if ("thinking" in p)
+ for (const t of pieces(p.thinking, r.deltaChars)) out.push(chunk({ reasoning_content: t }));
+ else {
+ const args = JSON.stringify(p.toolCall.args);
+ const id = p.toolCall.id ?? `call_stub_${tool}`;
+ out.push(
+ chunk({
+ tool_calls: [
+ {
+ index: tool,
+ id,
+ type: "function",
+ function: { name: p.toolCall.name, arguments: "" },
+ },
+ ],
+ })
+ );
+ for (const a of pieces(args, r.deltaChars))
+ out.push(chunk({ tool_calls: [{ index: tool, function: { arguments: a } }] }));
+ tool++;
+ }
+ }
+ out.push(chunk({}, tool > 0 ? "tool_calls" : "stop"));
+ out.push(
+ sse({
+ ...base,
+ choices: [],
+ usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },
+ })
+ );
+ out.push(sse("[DONE]"));
+ return out;
+}
+
+function anthropicEvents(r: StubResponse, model: string): string[] {
+ const out = [
+ sse(
+ {
+ type: "message_start",
+ message: {
+ id: "msg_stub",
+ type: "message",
+ role: "assistant",
+ model,
+ content: [],
+ stop_reason: null,
+ stop_sequence: null,
+ usage: { input_tokens: 10, output_tokens: 0 },
+ },
+ },
+ "message_start"
+ ),
+ ];
+ let index = 0;
+ let tool = 0;
+ for (const p of r.parts) {
+ if ("text" in p) {
+ out.push(
+ sse(
+ { type: "content_block_start", index, content_block: { type: "text", text: "" } },
+ "content_block_start"
+ )
+ );
+ for (const t of pieces(p.text, r.deltaChars))
+ out.push(
+ sse(
+ { type: "content_block_delta", index, delta: { type: "text_delta", text: t } },
+ "content_block_delta"
+ )
+ );
+ } else if ("thinking" in p) {
+ out.push(
+ sse(
+ { type: "content_block_start", index, content_block: { type: "thinking", thinking: "" } },
+ "content_block_start"
+ )
+ );
+ for (const t of pieces(p.thinking, r.deltaChars))
+ out.push(
+ sse(
+ { type: "content_block_delta", index, delta: { type: "thinking_delta", thinking: t } },
+ "content_block_delta"
+ )
+ );
+ out.push(
+ sse(
+ {
+ type: "content_block_delta",
+ index,
+ delta: { type: "signature_delta", signature: "c3R1Yg==" },
+ },
+ "content_block_delta"
+ )
+ );
+ } else {
+ const id = p.toolCall.id ?? `toolu_stub_${tool++}`;
+ out.push(
+ sse(
+ {
+ type: "content_block_start",
+ index,
+ content_block: { type: "tool_use", id, name: p.toolCall.name, input: {} },
+ },
+ "content_block_start"
+ )
+ );
+ for (const a of pieces(JSON.stringify(p.toolCall.args), r.deltaChars))
+ out.push(
+ sse(
+ {
+ type: "content_block_delta",
+ index,
+ delta: { type: "input_json_delta", partial_json: a },
+ },
+ "content_block_delta"
+ )
+ );
+ }
+ out.push(sse({ type: "content_block_stop", index }, "content_block_stop"));
+ index++;
+ }
+ const toolUse = r.parts.some((p) => "toolCall" in p);
+ out.push(
+ sse(
+ {
+ type: "message_delta",
+ delta: { stop_reason: toolUse ? "tool_use" : "end_turn", stop_sequence: null },
+ usage: { output_tokens: 5 },
+ },
+ "message_delta"
+ )
+ );
+ out.push(sse({ type: "message_stop" }, "message_stop"));
+ return out;
+}
+
+function responsesEvents(r: StubResponse, model: string): string[] {
+ const out = [
+ sse(
+ { type: "response.created", response: { id: "resp_stub", model, status: "in_progress" } },
+ "response.created"
+ ),
+ ];
+ let item = 0;
+ for (const p of r.parts) {
+ if ("text" in p) {
+ const id = `msg_stub_${item}`;
+ out.push(
+ sse(
+ {
+ type: "response.output_item.added",
+ output_index: item,
+ item: { id, type: "message", role: "assistant", content: [] },
+ },
+ "response.output_item.added"
+ )
+ );
+ for (const t of pieces(p.text, r.deltaChars))
+ out.push(
+ sse(
+ {
+ type: "response.output_text.delta",
+ item_id: id,
+ output_index: item,
+ content_index: 0,
+ delta: t,
+ },
+ "response.output_text.delta"
+ )
+ );
+ out.push(
+ sse(
+ {
+ type: "response.output_item.done",
+ output_index: item,
+ item: {
+ id,
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: p.text }],
+ },
+ },
+ "response.output_item.done"
+ )
+ );
+ } else if ("thinking" in p) {
+ const id = `rs_stub_${item}`;
+ out.push(
+ sse(
+ {
+ type: "response.output_item.added",
+ output_index: item,
+ item: { id, type: "reasoning", summary: [] },
+ },
+ "response.output_item.added"
+ )
+ );
+ for (const t of pieces(p.thinking, r.deltaChars))
+ out.push(
+ sse(
+ {
+ type: "response.reasoning_summary_text.delta",
+ item_id: id,
+ output_index: item,
+ summary_index: 0,
+ delta: t,
+ },
+ "response.reasoning_summary_text.delta"
+ )
+ );
+ out.push(
+ sse(
+ {
+ type: "response.output_item.done",
+ output_index: item,
+ item: { id, type: "reasoning" },
+ },
+ "response.output_item.done"
+ )
+ );
+ } else {
+ const id = `fc_stub_${item}`;
+ const callId = p.toolCall.id ?? `call_stub_${item}`;
+ const args = JSON.stringify(p.toolCall.args);
+ out.push(
+ sse(
+ {
+ type: "response.output_item.added",
+ output_index: item,
+ item: {
+ id,
+ type: "function_call",
+ call_id: callId,
+ name: p.toolCall.name,
+ arguments: "",
+ },
+ },
+ "response.output_item.added"
+ )
+ );
+ for (const a of pieces(args, r.deltaChars))
+ out.push(
+ sse(
+ {
+ type: "response.function_call_arguments.delta",
+ item_id: id,
+ output_index: item,
+ delta: a,
+ },
+ "response.function_call_arguments.delta"
+ )
+ );
+ out.push(
+ sse(
+ {
+ type: "response.output_item.done",
+ output_index: item,
+ item: {
+ id,
+ type: "function_call",
+ call_id: callId,
+ name: p.toolCall.name,
+ arguments: args,
+ },
+ },
+ "response.output_item.done"
+ )
+ );
+ }
+ item++;
+ }
+ out.push(
+ sse(
+ {
+ type: "response.completed",
+ response: {
+ id: "resp_stub",
+ model,
+ status: "completed",
+ usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 },
+ },
+ },
+ "response.completed"
+ )
+ );
+ return out;
+}
+
+/** The network chunks of one response: one per event, or split inside a multi-byte character. */
+export function stubChunks(events: string[], splitMultibyte = false): Uint8Array[] {
+ const enc = new TextEncoder();
+ const chunks = events.map((e) => enc.encode(e));
+ if (!splitMultibyte) return chunks;
+ for (let i = 0; i < chunks.length; i++) {
+ const c = chunks[i] as Uint8Array;
+ const at = c.findIndex((b) => b >= 0xc0); // the lead byte of a multi-byte sequence
+ if (at >= 0) {
+ return [
+ ...chunks.slice(0, i),
+ c.subarray(0, at + 1),
+ c.subarray(at + 1),
+ ...chunks.slice(i + 1),
+ ];
+ }
+ }
+ return chunks;
+}
+
+export function startStubUpstream(opts: { format: StubFormat; script: StubScript }): StubUpstream {
+ const requests: StubRequest[] = [];
+ const pick = (req: StubRequest, n: number): StubResponse => {
+ if (typeof opts.script === "function") return opts.script(req, n);
+ const list = opts.script;
+ return (list[Math.min(n, list.length - 1)] ?? { parts: [{ text: "" }] }) as StubResponse;
+ };
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ async fetch(request) {
+ const url = new URL(request.url);
+ if (request.method !== "POST") return Response.json({ data: [] });
+ let body: unknown = null;
+ try {
+ body = await request.json();
+ } catch {
+ body = null;
+ }
+ const rec: StubRequest = { path: url.pathname, body, at: Date.now() };
+ const n = requests.length;
+ requests.push(rec);
+ const r = pick(rec, n);
+ if (r.status && r.status >= 400)
+ return Response.json(
+ { error: { message: `stub error ${r.status}` } },
+ { status: r.status }
+ );
+ const model = (body as { model?: string } | null)?.model ?? "fake-model";
+ const chunks = stubChunks(stubEvents(opts.format, r, model), r.splitMultibyte);
+ let i = 0;
+ const stream = new ReadableStream<Uint8Array>({
+ async pull(controller) {
+ if (i >= chunks.length) {
+ controller.close();
+ return;
+ }
+ if (i > 0 && r.chunkDelayMs) await Bun.sleep(r.chunkDelayMs);
+ controller.enqueue(chunks[i++] as Uint8Array);
+ },
+ });
+ return new Response(stream, {
+ headers: { "content-type": "text/event-stream", "cache-control": "no-cache" },
+ });
+ },
+ });
+ return {
+ url: `http://127.0.0.1:${server.port}`,
+ requests,
+ stop: () => server.stop(true),
+ };
+}
+
+/**
+ * The `customEndpoints` entry that routes `stub@<model>` to a stub (openai-sse only:
+ * a `simple` endpoint speaks chat completions). Merge it into the config file a pane
+ * child reads through `CLAUDISH_CONFIG`.
+ */
+export function stubEndpointConfig(stub: StubUpstream, name = "stub"): Record<string, unknown> {
+ return {
+ customEndpoints: {
+ [name]: { kind: "simple", url: `${stub.url}/v1`, format: "openai", authScheme: "none" },
+ },
+ };
+}