Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(hooks): add the response seam above every stream parser
Jack Rudenko97a4e870ce85
diff --git a/packages/cli/src/behavior/engine.ts b/packages/cli/src/behavior/engine.tsindex 8790bd6c..aa0c7b8c 100644--- a/packages/cli/src/behavior/engine.ts+++ b/packages/cli/src/behavior/engine.ts@@ -452,9 +452,9 @@ export class BehaviorSession {/** Advisory only. Never awaited, never throws into the request path. */private async consultObserver(toolName: string, args: Record<string, any>): Promise<void> {try {- const { buildDigest } = await import("./observer/digest.js");- const { observe } = await import("./observer/client.js");- const { recordLiveDivergence } = await import("./observer/live-log.js");+ const { buildDigest } = await import("../hooks/observer/digest.js");+ const { observe } = await import("../hooks/observer/client.js");+ const { recordLiveDivergence } = await import("../hooks/observer/live-log.js");const digest = buildDigest({model: this.modelId,diff --git a/packages/cli/src/behavior/index.ts b/packages/cli/src/behavior/index.tsindex 4931b567..a8c99a8b 100644--- a/packages/cli/src/behavior/index.ts+++ b/packages/cli/src/behavior/index.ts@@ -15,12 +15,12 @@ export { BehaviorEngine, BehaviorSession } from "./engine.js";export { parseBehaviorConfig, resolveSeverity } from "./config.js";export { detectHarnessFacts } from "../hooks/harness.js";export { loadHookRules } from "./hooks.js";-export { buildDigest } from "./observer/digest.js";-export type { ObserverDigest } from "./observer/digest.js";-export { observe, resetObserverModelCache } from "./observer/client.js";-export type { ObserverVerdict } from "./observer/client.js";-export { buildCorpus, replayTranscript } from "./observer/corpus.js";-export type { CorpusResult, Divergence } from "./observer/corpus.js";+export { buildDigest } from "../hooks/observer/digest.js";+export type { ObserverDigest } from "../hooks/observer/digest.js";+export { observe, resetObserverModelCache } from "../hooks/observer/client.js";+export type { ObserverVerdict } from "../hooks/observer/client.js";+export { buildCorpus, replayTranscript } from "../hooks/observer/corpus.js";+export type { CorpusResult, Divergence } from "../hooks/observer/corpus.js";export {TELEMETRY_SCHEMA_VERSION,contextFillPct,diff --git a/packages/cli/src/format-translation.test.ts b/packages/cli/src/format-translation.test.tsindex 23ff0aa5..3dc7772c 100644--- a/packages/cli/src/format-translation.test.ts+++ b/packages/cli/src/format-translation.test.ts@@ -524,14 +524,10 @@ describe("Regression: Anthropic SSE abandoned streams emit a terminal tail", ()delta: { type: "text_delta", text: "answer" },}),]);- let turnEndCalls = 0;let tokenUpdate: [number, number] | null = null as [number, number] | null;const response = createAnthropicPassthroughStream(createMockContext(), fixture, {modelName: "test-model",- onTurnEnd: () => {- turnEndCalls++;- },onTokenUpdate: (input, output) => {tokenUpdate = [input, output];},@@ -548,7 +544,6 @@ describe("Regression: Anthropic SSE abandoned streams emit a terminal tail", ()expect(extractText(events)).toBe("partial answer");expect(events.some((event) => event.data?.type === "message_stop")).toBe(true);- expect(turnEndCalls).toBe(1);expect(tokenUpdate).toEqual([12, 0]);} finally {if (timeout) clearTimeout(timeout);diff --git a/packages/cli/src/handlers/composed-handler-seam.test.ts b/packages/cli/src/handlers/composed-handler-seam.test.tsnew file mode 100644index 00000000..e82bda7e--- /dev/null+++ b/packages/cli/src/handlers/composed-handler-seam.test.ts@@ -0,0 +1,330 @@+/**+ * The response seam end to end through ComposedHandler: a stubbed upstream,+ * the real parser, `withHooks`, the built-in hooks.+ *+ * - A request no rewriting hook claims streams byte-identically to the handler+ * without hooks, and the seam hands back the handler's own Response object.+ * - Plan-mode tool repair works again: in plan mode a Write aimed at an+ * invented file in the plan directory reaches Claude Code redirected to the+ * assigned plan file, on the openai-sse and anthropic-sse wires. Outside plan+ * mode nothing is held or changed.+ */++import { afterEach, describe, expect, it } from "bun:test";+import { AnthropicAPIFormat } from "../adapters/anthropic-api-format.js";+import { OpenAIAPIFormat } from "../adapters/openai-api-format.js";+import { builtinHooks } from "../hooks/builtins/index.js";+import { HookEngine } from "../hooks/engine.js";+import type { JournalEntry } from "../hooks/journal.js";+import type { HookDefinition } from "../hooks/public.js";+import { HookRegistry, type UserHookInput } from "../hooks/registry.js";+import { withHooks } from "../hooks/response-seam.js";+import type { ProviderTransport } from "../providers/transport/types.js";+import { normalizeWire } from "../test-fixtures/parser-goldens/golden-format.js";+import { ComposedHandler } from "./composed-handler.js";+import type { ModelHandler } from "./types.js";++const realFetch = globalThis.fetch;+afterEach(() => {+ globalThis.fetch = realFetch;+});++const PLAN_DIR = "/tmp/seam-e2e/plans";+const ASSIGNED = `${PLAN_DIR}/assigned-plan.md`;+const INVENTED = `${PLAN_DIR}/my-own-name.md`;++const encoder = new TextEncoder();++/** Stub every fetch with a fresh streaming body of `chunks`. */+function stubStream(chunks: string[]): void {+ globalThis.fetch = (async () =>+ new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));+ controller.close();+ },+ }),+ { status: 200, headers: { "content-type": "text/event-stream" } }+ )) as unknown as typeof fetch;+}++function transport(streamFormat: string): ProviderTransport {+ return {+ name: "test-provider",+ displayName: "Test",+ streamFormat,+ getEndpoint: () => "http://localhost/v1/chat/completions",+ getHeaders: async () => ({}),+ } as unknown as ProviderTransport;+}++function context(): any {+ const vars = new Map<string, unknown>();+ return {+ req: {+ header: (name?: string) =>+ name === undefined ? {} : name === "x-claudish-no-recovery" ? "1" : undefined,+ },+ header: () => {},+ body: (body: BodyInit | null, init?: ResponseInit) => new Response(body, init),+ json: (body: unknown, status?: number) =>+ new Response(JSON.stringify(body), { status: status ?? 200 }),+ get: (k: string) => vars.get(k),+ set: (k: string, v: unknown) => vars.set(k, v),+ };+}++function engineWith(users: UserHookInput[] = []) {+ const journal: JournalEntry[] = [];+ const config = {};+ const engine = new HookEngine({+ registry: new HookRegistry(builtinHooks(config), users, undefined),+ config,+ hostMode: "other",+ journalSink: (e) => journal.push(e),+ warn: () => {},+ drainTelemetryOutbox: false,+ });+ return { engine, journal };+}++const user = (def: Omit<HookDefinition, "apiVersion">): UserHookInput => ({+ id: `hook:e2e/${def.id}`,+ module: "/e2e.ts",+ moduleIndex: 0,+ exportIndex: 0,+ def: { apiVersion: 1, ...def } as HookDefinition,+});++const WRITE_TOOL = {+ name: "Write",+ description: "Write a file",+ input_schema: {+ type: "object",+ properties: { file_path: { type: "string" }, content: { type: "string" } },+ required: ["file_path", "content"],+ },+};++function payload(planMode: boolean, stream = true): any {+ return {+ model: "glm-5",+ max_tokens: 64,+ stream,+ messages: [+ {+ role: "user",+ content: planMode+ ? `Plan mode is active. No plan file exists yet. You should create your plan at ${ASSIGNED} using the Write tool.`+ : "Write the plan.",+ },+ ],+ tools: [WRITE_TOOL],+ };+}++const openAiFrame = (data: unknown) => `data: ${JSON.stringify(data)}\n\n`;++/** An OpenAI chat-completions stream: some text, then one Write call in two fragments. */+function openAiWriteStream(path: string): string[] {+ const args = JSON.stringify({ file_path: path, content: "# Plan" });+ return [+ openAiFrame({ choices: [{ delta: { role: "assistant", content: "Writing the plan." } }] }),+ openAiFrame({+ choices: [+ {+ delta: {+ tool_calls: [+ {+ index: 0,+ id: "call_w",+ type: "function",+ function: { name: "Write", arguments: args.slice(0, 20) },+ },+ ],+ },+ },+ ],+ }),+ openAiFrame({+ choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: args.slice(20) } }] } }],+ }),+ openAiFrame({ choices: [{ delta: {}, finish_reason: "tool_calls" }] }),+ "data: [DONE]\n\n",+ ];+}++const anthropicFrame = (event: string, data: unknown) =>+ `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;++/** A native Anthropic-format stream: one Write call whose arguments arrive in two fragments. */+function anthropicWriteStream(path: string): string[] {+ const args = JSON.stringify({ file_path: path, content: "# Plan" });+ return [+ anthropicFrame("message_start", {+ type: "message_start",+ message: {+ id: "msg_a",+ type: "message",+ role: "assistant",+ content: [],+ model: "glm-5",+ usage: { input_tokens: 5, output_tokens: 1 },+ },+ }),+ anthropicFrame("content_block_start", {+ type: "content_block_start",+ index: 0,+ content_block: { type: "tool_use", id: "toolu_w", name: "Write", input: {} },+ }),+ anthropicFrame("content_block_delta", {+ type: "content_block_delta",+ index: 0,+ delta: { type: "input_json_delta", partial_json: args.slice(0, 20) },+ }),+ anthropicFrame("content_block_delta", {+ type: "content_block_delta",+ index: 0,+ delta: { type: "input_json_delta", partial_json: args.slice(20) },+ }),+ anthropicFrame("content_block_stop", { type: "content_block_stop", index: 0 }),+ anthropicFrame("message_delta", {+ type: "message_delta",+ delta: { stop_reason: "tool_use", stop_sequence: null },+ usage: { output_tokens: 9 },+ }),+ anthropicFrame("message_stop", { type: "message_stop" }),+ ];+}++/** The Write call's arguments as the client assembles them. */+function writeArgs(wire: string): Record<string, unknown> {+ let json = "";+ for (const line of wire.split("\n")) {+ if (!line.startsWith("data: ") || line === "data: [DONE]") continue;+ const p = JSON.parse(line.slice(6));+ if (p.type === "content_block_delta" && p.delta?.type === "input_json_delta") {+ json += p.delta.partial_json;+ }+ }+ return JSON.parse(json);+}++/** Read a body chunk by chunk, normalizing each. */+async function chunksOf(res: Response): Promise<string[]> {+ const out: string[] = [];+ const reader = res.body!.getReader();+ const decoder = new TextDecoder();+ for (;;) {+ const r = await reader.read();+ if (r.done) return out;+ out.push(normalizeWire(decoder.decode(r.value)));+ }+}++function openAiHandler(): ComposedHandler {+ return new ComposedHandler(transport("openai-sse"), "glm-5", "glm-5", 8080, {+ adapter: new OpenAIAPIFormat("glm-5"),+ });+}++describe("an unclaimed request streams byte-identically", () => {+ it("the seam returns the handler's own Response, and the bytes match a run without hooks", async () => {+ const upstream = openAiWriteStream("/repo/src/file.ts");+ // Hooks are loaded and run (a request hook and every built-in), but none+ // claims the response: no plan mode, observer off, no rewrite or end hook.+ const { engine } = engineWith([user({ id: "req-only", on: { request: () => [] } })]);++ stubStream(upstream);+ const plain = await chunksOf(await openAiHandler().handle(context(), payload(false)));++ stubStream(upstream);+ const handler = openAiHandler();+ let inner: Response | undefined;+ const spy: ModelHandler = {+ handle: async (c, p) => {+ inner = await handler.handle(c, p);+ return inner;+ },+ shutdown: () => handler.shutdown(),+ };+ const outer = await withHooks(spy, engine).handle(context(), payload(false));+ expect(outer).toBe(inner as Response);+ const hooked = await chunksOf(outer);++ // Same bytes, same chunk boundaries.+ expect(hooked).toEqual(plain);+ expect(writeArgs(hooked.join(""))).toEqual({+ file_path: "/repo/src/file.ts",+ content: "# Plan",+ });+ });++ it("with only an observe consumer (a responseEnd hook) the bytes and chunking are unchanged too", async () => {+ const upstream = openAiWriteStream("/repo/src/file.ts");+ const { engine } = engineWith([user({ id: "end", on: { responseEnd: () => [] } })]);++ stubStream(upstream);+ const plain = await chunksOf(await openAiHandler().handle(context(), payload(false)));+ stubStream(upstream);+ const tapped = await chunksOf(+ await withHooks(openAiHandler(), engine).handle(context(), payload(false))+ );+ expect(tapped).toEqual(plain);+ });+});++describe("plan-mode tool repair through ComposedHandler", () => {+ it("openai-sse: a Write to an invented plan filename reaches the client redirected", async () => {+ const { engine, journal } = engineWith();+ stubStream(openAiWriteStream(INVENTED));+ const res = await withHooks(openAiHandler(), engine).handle(context(), payload(true));+ const wire = await res.text();++ expect(writeArgs(wire)).toEqual({ file_path: ASSIGNED, content: "# Plan" });+ expect(wire).not.toContain("my-own-name.md");+ expect(wire).toContain('"type":"message_stop"');+ const repaired = journal.find(+ (e) => e.hookId === "plan-mode/plan-file-path" && e.decision === "repaired"+ );+ expect(repaired?.toolName).toBe("Write");+ expect(repaired?.pathRelation).toBe("same_dir_wrong_name");+ });++ it("openai-sse control: outside plan mode the same call is not touched", async () => {+ const { engine, journal } = engineWith();+ stubStream(openAiWriteStream(INVENTED));+ const wire = await (+ await withHooks(openAiHandler(), engine).handle(context(), payload(false))+ ).text();+ expect(writeArgs(wire)).toEqual({ file_path: INVENTED, content: "# Plan" });+ expect(journal.some((e) => e.decision === "repaired")).toBe(false);+ });++ it("anthropic-sse: the repaired block is framed correctly (the old interceptor's defect is gone)", async () => {+ const { engine } = engineWith();+ stubStream(anthropicWriteStream(INVENTED));+ const handler = new ComposedHandler(transport("anthropic-sse"), "glm-5", "glm-5", 8080, {+ adapter: new AnthropicAPIFormat("glm-5"),+ });+ const wire = await (await withHooks(handler, engine).handle(context(), payload(true))).text();++ expect(writeArgs(wire)).toEqual({ file_path: ASSIGNED, content: "# Plan" });+ // One delta, then a stop that carries its own event name.+ expect(wire).toContain(+ 'event: content_block_stop\ndata: {"type":"content_block_stop","index":0}\n\n'+ );+ expect(wire).not.toContain("event: content_block_stop\nevent:");+ });++ it("stream:false: the JSON message carries the repaired input", async () => {+ const { engine } = engineWith();+ stubStream(openAiWriteStream(INVENTED));+ const res = await withHooks(openAiHandler(), engine).handle(context(), payload(true, false));+ expect(res.headers.get("content-type")).toContain("application/json");+ const message = await res.json();+ const tool = message.content.find((b: any) => b.type === "tool_use");+ expect(tool.input).toEqual({ file_path: ASSIGNED, content: "# Plan" });+ });+});diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.tsindex a9614525..9d7e4f94 100644--- a/packages/cli/src/handlers/composed-handler.ts+++ b/packages/cli/src/handlers/composed-handler.ts@@ -2751,9 +2751,9 @@ export class ComposedHandler implements ModelHandler {* end-of-session summary, which must work for every model on every wire, so* every parser below gets it unconditionally.*- * The parsers' behavior plumbing (tool buffering, argument repair, output- * observation) is no longer passed: tool interception moves to the hook- * response seam, above every parser.+ * The parsers carry no tool buffering, argument repair or output+ * observation: tool interception is the hook response seam's job, above+ * every parser (`hooks/response-seam.ts`).*/const observeToolCall = (name: string): void => {this.tokenTracker.recordToolUse(name);diff --git a/packages/cli/src/handlers/shared/stream-parsers/anthropic-sse.ts b/packages/cli/src/handlers/shared/stream-parsers/anthropic-sse.tsindex 4064b29f..84461ad6 100644--- a/packages/cli/src/handlers/shared/stream-parsers/anthropic-sse.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/anthropic-sse.ts@@ -20,101 +20,11 @@ interface AnthropicPassthroughOpts {/** Optional adapter — used to check shouldFilterThinking(). */adapter?: BaseAPIFormat;/**- * Behavior layer (Layer 4) tool-call repair.- *- * This parser is a byte-level passthrough, so interception here is strictly- * opt-in per tool: only a tool that `shouldBufferTool` names has its- * `input_json_delta` frames withheld and rewritten. Every other block — text,- * thinking, and any tool no rule cares about — is forwarded untouched, so the- * passthrough contract is preserved for everything the layer is not targeting.+ * Called once per `tool_use` block start, for the token tracker's tool count.+ * Tool-argument interception is not this parser's job: it happens at the hook+ * response seam, above every parser.*/- shouldBufferTool?: (name: string) => boolean;- repairToolArgs?: (name: string, argsJson: string) => string | null | undefined;- /** Layer 4 observation — normalized text, not raw frames. */- onAssistantText?: (text: string, kind?: "text" | "reasoning") => void;onToolCallObserved?: (name: string) => void;- onTurnEnd?: () => void;-}--/**- * Build the tool-repair frame interceptor for one stream.- *- * Returns a function that maps a parsed frame to the exact bytes to enqueue- * (trailing newline included, matching the passthrough's `${line}\n`- * convention), or null to suppress the frame.- *- * Only three frame shapes are ever diverted, and only for tools a rule named- * via `shouldBufferTool`. Everything else — text, thinking, and any untargeted- * tool — round-trips byte-for-byte, which is what keeps this a passthrough.- *- * Module-level (not nested in the stream closure) so it is independently- * testable and does not inflate the stream function's complexity.- */-function createToolRepairInterceptor(- opts: Pick<AnthropicPassthroughOpts, "shouldBufferTool" | "repairToolArgs">-): (data: any, line: string) => string | null {- /** Withheld tool blocks, keyed by the content-block index upstream assigned. */- const heldTools = new Map<number, { name: string; args: string }>();-- const flush = (index: number, stopFrame: string): string => {- const held = heldTools.get(index);- if (!held) return stopFrame;- heldTools.delete(index);-- let finalArgs = held.args;- try {- const repaired = opts.repairToolArgs?.(held.name, finalArgs);- if (typeof repaired === "string" && repaired !== finalArgs) {- log(`[AnthropicSSE] tool call repaired: ${held.name}`);- finalArgs = repaired;- }- } catch (err) {- // A failing rule must never corrupt the stream — emit what the model sent.- log(`[AnthropicSSE] repairToolArgs threw for ${held.name}: ${err}`);- }-- const deltaFrame = `event: content_block_delta\ndata: ${JSON.stringify({- type: "content_block_delta",- index,- delta: { type: "input_json_delta", partial_json: finalArgs },- })}\n\n`;- return `${deltaFrame}${stopFrame}`;- };-- /** Start withholding a tool block if a rule named it. */- const noteToolStart = (data: any): void => {- if (data.content_block?.type !== "tool_use") return;- const name = data.content_block.name;- if (typeof name !== "string") return;- if (!opts.shouldBufferTool?.(name)) return;- heldTools.set(data.index, { name, args: "" });- };-- /** Accumulate a withheld fragment. Returns true if the frame was swallowed. */- const absorbFragment = (data: any): boolean => {- if (data.delta?.type !== "input_json_delta") return false;- const held = heldTools.get(data.index);- if (!held) return false;- held.args += data.delta.partial_json ?? "";- return true;- };-- return (data: any, line: string): string | null => {- const asIs = `${line}\n`;- if (!opts.repairToolArgs || !opts.shouldBufferTool) return asIs;-- switch (data?.type) {- case "content_block_start":- noteToolStart(data);- return asIs; // the start frame itself is always forwarded- case "content_block_delta":- return absorbFragment(data) ? null : asIs;- case "content_block_stop":- return heldTools.has(data.index) ? flush(data.index, asIs) : asIs;- default:- return asIs;- }- };}/**@@ -138,8 +48,6 @@ export function createAnthropicPassthroughStream(const filterThinking = opts.adapter?.shouldFilterThinking() ?? false;- const interceptToolFrame = createToolRepairInterceptor(opts);-/*** An `event:` line held back until we know whether its `data:` line survives.*@@ -212,18 +120,11 @@ export function createAnthropicPassthroughStream(pendingEventLine = null;};- /** Enqueue a parsed data line through the tool interceptor. */+ /** Enqueue a parsed data line, preceded by its held `event:` line. */const enqueueData = (controller: any, data: any, line: string): void => {if (isClosed) return;- const out = interceptToolFrame(data, line);- if (out === null) {- // Frame withheld by the tool interceptor — discard its event line too,- // for the same reason the thinking filter must.- pendingEventLine = null;- return;- }flushPendingEvent(controller);- controller.enqueue(encoder.encode(out));+ controller.enqueue(encoder.encode(`${line}\n`));noteLifecycle(data, typeof data?.index === "number" ? data.index : null);};@@ -512,9 +413,7 @@ export function createAnthropicPassthroughStream(return; // stop processing further lines}- // No error — check index bounds before passing through- // (still via the tool interceptor, which is a no-op unless- // a rule asked for this tool).+ // No error — check index bounds before passing through.emitIndexed(controller, data, line);// Usage/debug tracking, in its OWN try. The outer catch@@ -539,7 +438,6 @@ export function createAnthropicPassthroughStream(data.delta?.type === "text_delta") {const txt = data.delta.text || "";- opts.onAssistantText?.(txt, "text");textChunks++;log(`[AnthropicSSE] Text chunk: "${txt.substring(0, 30).replace(/\n/g, "\\n")}" (${txt.length} chars)`@@ -608,7 +506,6 @@ export function createAnthropicPassthroughStream(outputTokens = data.usage.output_tokens || outputTokens;}if (data.type === "content_block_delta" && data.delta?.type === "text_delta") {- opts.onAssistantText?.(data.delta.text || "", "text");textChunks++;}if (@@ -631,8 +528,6 @@ export function createAnthropicPassthroughStream(`[AnthropicSSE] Stream complete for ${opts.modelName}: ${totalLines} lines, ${textChunks} text chunks, ${toolUseBlocks} tool_use blocks, stop_reason=${stopReason}${filterThinking ? `, filtered ${thinkingBlocksSuppressed} thinking blocks` : ""}`);- opts.onTurnEnd?.();-if (opts.onTokenUpdate) {opts.onTokenUpdate(inputTokens, outputTokens);}@@ -650,12 +545,9 @@ export function createAnthropicPassthroughStream(// The upstream socket dropped mid-answer (Z.AI, MiniMax and Kimi all do// this under load). Closing the controller here without a terminal event// handed Claude Code a stream that stopped but never ended, and the turn- // hung. Emit the tail first, then close, and still run the turn-end hooks- // so Layer 4 and the token file see a completed turn rather than nothing.+ // hung. Emit the tail first, then close, and still report the tokens so+ // the token file sees a completed turn rather than nothing.finalizeAbandonedStream(controller);- try {- opts.onTurnEnd?.();- } catch {}try {opts.onTokenUpdate?.(inputTokens, outputTokens);} catch {}diff --git a/packages/cli/src/handlers/shared/stream-parsers/behavior-repair.test.ts b/packages/cli/src/handlers/shared/stream-parsers/behavior-repair.test.tsdeleted file mode 100644index ddcad578..00000000--- a/packages/cli/src/handlers/shared/stream-parsers/behavior-repair.test.ts+++ /dev/null@@ -1,314 +0,0 @@-import { describe, expect, it } from "bun:test";--import { createAnthropicPassthroughStream } from "./anthropic-sse.js";-import { createGeminiSseStream } from "./gemini-sse.js";-import { createResponsesStreamHandler } from "./openai-responses-sse.js";-import { createStreamingResponseHandler } from "./openai-sse.js";--const TARGET_TOOL = "target_tool";-const UNTARGETED_TOOL = "untargeted_tool";-const ORIGINAL_VALUE = "model-original";-const REPAIRED_VALUE = "behavior-repaired";-const ORIGINAL_ARGS = JSON.stringify({ value: ORIGINAL_VALUE });-const REPAIRED_ARGS = JSON.stringify({ value: REPAIRED_VALUE });--const ctx: any = {- body: (stream: any, init: any) => new Response(stream, init),- json: () => {- throw new Error("Unexpected no-body error path");- },-};--const sseResponse = (frames: string[]) =>- new Response(- new ReadableStream({- start(controller) {- const encoder = new TextEncoder();- for (const frame of frames) controller.enqueue(encoder.encode(frame));- controller.close();- },- }),- { headers: { "content-type": "text/event-stream" } }- );--const dataFrame = (data: unknown) => `data: ${JSON.stringify(data)}\n\n`;--const anthropicFrame = (event: string, data: unknown) =>- `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;--function fakeSession() {- const repair = (name: string, _argsJson: string) =>- name === TARGET_TOOL ? REPAIRED_ARGS : undefined;-- return {- shouldBufferTool: (name: string) => name === TARGET_TOOL,- onToolCall: repair,- repairToolArgs: repair,- };-}--const toolSchemas = [TARGET_TOOL, UNTARGETED_TOOL].map((name) => ({- name,- input_schema: {- type: "object",- properties: { value: { type: "string" } },- required: ["value"],- },-}));--function openAiToolFrames(name: string, args = ORIGINAL_ARGS): string[] {- return [- dataFrame({- choices: [- {- delta: {- tool_calls: [- {- index: 0,- id: "call_openai_0",- type: "function",- function: { name, arguments: args },- },- ],- },- finish_reason: null,- },- ],- }),- dataFrame({ choices: [{ delta: {}, finish_reason: "tool_calls" }] }),- "data: [DONE]\n\n",- ];-}--function parseOpenAiTool(name: string, behavior = fakeSession(), args = ORIGINAL_ARGS): Response {- return createStreamingResponseHandler(- ctx,- sseResponse(openAiToolFrames(name, args)),- {},- "test-model",- null,- undefined,- toolSchemas,- undefined,- undefined,- behavior- );-}--function responsesToolFrames(name: string, fragments = [ORIGINAL_ARGS]): string[] {- const item = {- type: "function_call",- id: "fc_responses_item_0",- call_id: "responses_call_0",- name,- };-- return [- dataFrame({ type: "response.output_item.added", item }),- ...fragments.map((delta) =>- dataFrame({- type: "response.function_call_arguments.delta",- call_id: item.call_id,- item_id: item.id,- delta,- })- ),- dataFrame({ type: "response.output_item.done", item }),- dataFrame({- type: "response.completed",- response: { usage: { input_tokens: 5, output_tokens: 3 } },- }),- ];-}--function parseResponsesTool(- name: string,- fragments = [ORIGINAL_ARGS],- session = fakeSession()-): Response {- return createResponsesStreamHandler(ctx, sseResponse(responsesToolFrames(name, fragments)), {- modelName: "test-model",- shouldBufferTool: session.shouldBufferTool,- onToolCall: session.onToolCall,- });-}--function anthropicToolFrames(name: string, fragments = [ORIGINAL_ARGS]): string[] {- return [- anthropicFrame("content_block_start", {- type: "content_block_start",- index: 0,- content_block: { type: "tool_use", id: "toolu_anthropic_0", name, input: {} },- }),- ...fragments.map((partial_json) =>- anthropicFrame("content_block_delta", {- type: "content_block_delta",- index: 0,- delta: { type: "input_json_delta", partial_json },- })- ),- anthropicFrame("content_block_stop", { type: "content_block_stop", index: 0 }),- ];-}--function parseAnthropicTool(- name: string,- fragments = [ORIGINAL_ARGS],- withBehavior = true-): Response {- const session = fakeSession();- return createAnthropicPassthroughStream(ctx, sseResponse(anthropicToolFrames(name, fragments)), {- modelName: "test-model",- ...(withBehavior- ? {- shouldBufferTool: session.shouldBufferTool,- repairToolArgs: session.repairToolArgs,- }- : {}),- });-}--function geminiToolFrames(name: string): string[] {- return [- dataFrame({- candidates: [- {- content: {- role: "model",- parts: [{ functionCall: { name, args: { value: ORIGINAL_VALUE } } }],- },- finishReason: "STOP",- },- ],- }),- ];-}--function inputJsonDeltas(wire: string): string[] {- const deltas: string[] = [];- for (const line of wire.split("\n")) {- if (!line.startsWith("data: ") || line === "data: [DONE]") continue;- try {- const data = JSON.parse(line.slice(6));- if (data.type === "content_block_delta" && data.delta?.type === "input_json_delta") {- deltas.push(data.delta.partial_json);- }- } catch {}- }- return deltas;-}--function stripPingFrames(wire: string): string {- return wire.replaceAll('event: ping\ndata: {"type":"ping"}\n\n', "");-}--describe("openai-sse behavior repair", () => {- it("rewrites arguments for a targeted tool", async () => {- const out = await parseOpenAiTool(TARGET_TOOL).text();-- expect(out).toContain(REPAIRED_VALUE);- expect(out).not.toContain(ORIGINAL_VALUE);- });-- it("passes an untargeted tool through unchanged", async () => {- const out = await parseOpenAiTool(UNTARGETED_TOOL).text();-- expect(out).toContain(ORIGINAL_VALUE);- expect(out).not.toContain(REPAIRED_VALUE);- });-- it("emits the model arguments when a repair rule throws", async () => {- const session = fakeSession();- const out = await parseOpenAiTool(TARGET_TOOL, {- ...session,- onToolCall: () => {- throw new Error("synthetic repair failure");- },- }).text();-- expect(out).toContain(ORIGINAL_VALUE);- expect(out).not.toContain(REPAIRED_VALUE);- expect(out).toContain('"type":"message_stop"');- });-});--describe("openai-responses-sse behavior repair", () => {- it("rewrites arguments for a targeted tool", async () => {- const out = await parseResponsesTool(TARGET_TOOL).text();-- expect(out).toContain(REPAIRED_VALUE);- expect(out).not.toContain(ORIGINAL_VALUE);- });-- it("passes an untargeted tool through unchanged", async () => {- const out = await parseResponsesTool(UNTARGETED_TOOL).text();-- expect(out).toContain(ORIGINAL_VALUE);- expect(out).not.toContain(REPAIRED_VALUE);- });-- it("keeps untargeted argument fragments incremental", async () => {- const fragments = ['{"value":"incremental-', 'delivery"}'];- const out = await parseResponsesTool(UNTARGETED_TOOL, fragments).text();-- expect(inputJsonDeltas(out)).toEqual(fragments);- });-});--describe("anthropic-sse behavior repair", () => {- it("reassembles fragmented targeted arguments, repairs them, and emits one delta", async () => {- const originalFragments = ['{"value":"model-', 'original"}'];- const out = await parseAnthropicTool(TARGET_TOOL, originalFragments).text();-- expect(inputJsonDeltas(out)).toEqual([REPAIRED_ARGS]);- expect(out).toContain(REPAIRED_VALUE);- for (const fragment of originalFragments) expect(out).not.toContain(fragment);- expect(out).not.toContain(ORIGINAL_VALUE);- });-- it("passes an untargeted tool through unchanged", async () => {- const out = await parseAnthropicTool(UNTARGETED_TOOL).text();-- expect(out).toContain(ORIGINAL_VALUE);- expect(out).not.toContain(REPAIRED_VALUE);- });-- it("is byte-identical for an untargeted tool after generated pings are stripped", async () => {- const frames = anthropicToolFrames(UNTARGETED_TOOL, ['{"value":"byte-', 'identical"}']);- const session = fakeSession();- const baseline = await createAnthropicPassthroughStream(ctx, sseResponse(frames), {- modelName: "test-model",- }).text();- const withBehavior = await createAnthropicPassthroughStream(ctx, sseResponse(frames), {- modelName: "test-model",- shouldBufferTool: session.shouldBufferTool,- repairToolArgs: session.repairToolArgs,- }).text();-- expect(stripPingFrames(withBehavior)).toBe(stripPingFrames(baseline));- });-});--describe("gemini-sse behavior repair", () => {- it("rewrites arguments for a targeted tool", async () => {- const session = fakeSession();- const out = await createGeminiSseStream(ctx, sseResponse(geminiToolFrames(TARGET_TOOL)), {- modelName: "test-model",- repairToolArgs: session.repairToolArgs,- }).text();-- expect(out).toContain(REPAIRED_VALUE);- expect(out).not.toContain(ORIGINAL_VALUE);- });-- it("passes an untargeted tool through unchanged", async () => {- const session = fakeSession();- const out = await createGeminiSseStream(ctx, sseResponse(geminiToolFrames(UNTARGETED_TOOL)), {- modelName: "test-model",- repairToolArgs: session.repairToolArgs,- }).text();-- expect(out).toContain(ORIGINAL_VALUE);- expect(out).not.toContain(REPAIRED_VALUE);- });-});diff --git a/packages/cli/src/handlers/shared/stream-parsers/devin-connect.ts b/packages/cli/src/handlers/shared/stream-parsers/devin-connect.tsindex 21e250ac..a6598f46 100644--- a/packages/cli/src/handlers/shared/stream-parsers/devin-connect.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/devin-connect.ts@@ -98,29 +98,12 @@ export interface DevinConnectOptions {/** The uid the backend reports serving (field `7.9`), when it differs from the request. */onServedModel?: (uid: string) => void;- // ── Layer 4 — the same five hooks the gemini-sse case passes ──────────────/**- * Behavior-layer tool-call repair. Consulted once per COMPLETED tool call- * with the fully accumulated argument JSON; return replacement JSON, or- * null/undefined to leave it untouched.- *- * Only reached for tools `shouldBufferTool` opted in — see below.+ * Called once per `tool_use` block start, for the token tracker's tool count.+ * Tool-argument interception is not this parser's job: it happens at the hook+ * response seam, above every parser.*/- repairToolArgs?: (name: string, argsJson: string) => string | null | undefined;- /**- * Whether a tool's arguments must be withheld until the call completes.- *- * Repair is only POSSIBLE for buffered calls: this backend emits argument- * fragments the instant they arrive, so by the time a call is complete its- * arguments are already on the wire. Buffering is therefore opt-in per tool- * AND per request — outside an armed rule nothing is buffered and streaming is- * byte-for-byte what it would have been.- */- shouldBufferTool?: (name: string) => boolean;- /** Normalized observation, so rules never have to understand this wire. */- onAssistantText?: (text: string, kind?: "text" | "reasoning") => void;onToolCallObserved?: (name: string) => void;- onTurnEnd?: () => void;/** Restore truncated tool names (Layer 1 may have shortened them). */toolNameMap?: Map<string, string>;}@@ -130,9 +113,7 @@ interface StreamingToolCall {id: string;name: string;blockIndex: number;- /** Withhold `input_json_delta` until the call completes so it can be repaired. */- buffered: boolean;- /** Accumulated argument JSON (always tracked — cheap, and repair needs it). */+ /** Accumulated argument JSON: an empty one gets an explicit `{}` at close. */args: string;/** Incremental UTF-8 decoder: a multi-byte char can straddle two fragments. */decoder: TextDecoder;@@ -212,34 +193,13 @@ export function createDevinConnectStream(textStarted = false;};- /** Close the in-flight tool call, repairing + flushing buffered arguments. */+ /** Close the in-flight tool call. */const closeCurrentTool = () => {if (!current || current.closed) return;const call = current;current = null;- if (call.buffered) {- let args = call.args;- if (opts.repairToolArgs) {- try {- const repaired = opts.repairToolArgs(call.name, args);- if (typeof repaired === "string" && repaired !== args) {- log(`[DevinConnect] tool call repaired: ${call.name}`);- args = repaired;- }- } catch (err) {- // A failing rule must never corrupt the stream.- log(`[DevinConnect] repairToolArgs threw for ${call.name}: ${err}`);- }- }- send("content_block_delta", {- type: "content_block_delta",- index: call.blockIndex,- // An empty argument object is still valid JSON the client can parse;- // an empty string is not.- delta: { type: "input_json_delta", partial_json: args || "{}" },- });- } else if (!call.args) {+ if (!call.args) {// A no-argument tool emitted no fragments at all. Claude Code needs a// parseable object, so supply the empty one explicitly.send("content_block_delta", {@@ -293,7 +253,6 @@ export function createDevinConnectStream(output_tokens: outputTokens,},});- opts.onTurnEnd?.();send("message_stop", { type: "message_stop" });}@@ -363,7 +322,6 @@ export function createDevinConnectStream(id: toolId,name: restored,blockIndex,- buffered: opts.shouldBufferTool?.(restored) ?? false,args: "",decoder: new TextDecoder(),closed: false,@@ -390,13 +348,11 @@ export function createDevinConnectStream(return;}current.args += chunk;- if (!current.buffered) {- send("content_block_delta", {- type: "content_block_delta",- index: current.blockIndex,- delta: { type: "input_json_delta", partial_json: chunk },- });- }+ send("content_block_delta", {+ type: "content_block_delta",+ index: current.blockIndex,+ delta: { type: "input_json_delta", partial_json: chunk },+ });};/** One protobuf message frame (`flags = 0`). */@@ -418,7 +374,6 @@ export function createDevinConnectStream(});textStarted = true;}- opts.onAssistantText?.(text, "text");send("content_block_delta", {type: "content_block_delta",index: textIdx,@@ -439,7 +394,6 @@ export function createDevinConnectStream(});thinkingStarted = true;}- opts.onAssistantText?.(thinking, "reasoning");send("content_block_delta", {type: "content_block_delta",index: thinkingIdx,diff --git a/packages/cli/src/handlers/shared/stream-parsers/gemini-sse.ts b/packages/cli/src/handlers/shared/stream-parsers/gemini-sse.tsindex a0269660..05a745b8 100644--- a/packages/cli/src/handlers/shared/stream-parsers/gemini-sse.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/gemini-sse.ts@@ -21,22 +21,11 @@ export interface GeminiSseOptions {/** Store tool call info (id, name, thoughtSignature) for future request context */onToolCall?: (toolId: string, name: string, thoughtSignature?: string) => void;/**- * Behavior layer (Layer 4) tool-call repair. Deliberately NOT merged into- * `onToolCall` above, which is an unrelated pre-existing hook for recording- * thought signatures.- *- * No buffering is needed on this path: Gemini delivers each `functionCall`- * with its complete `args` object in one part, so the full arguments are- * always in hand at emit time.+ * Called once per `tool_use` block, for the token tracker's tool count.+ * Tool-argument interception is not this parser's job: it happens at the hook+ * response seam, above every parser.*/- repairToolArgs?: (name: string, argsJson: string) => string | null | undefined;- /**- * Behavior-layer observation (Layer 4). Called with normalized text so rules- * never have to understand this parser's event shape.- */- onAssistantText?: (text: string, kind?: "text" | "reasoning") => void;onToolCallObserved?: (name: string) => void;- onTurnEnd?: () => void;/** Last request's context size — seeds message_start.usage (see message-start-usage.ts) */priorInputTokens?: number;@@ -177,7 +166,6 @@ export function createGeminiSseStream(output_tokens: outputTokens,},});- opts.onTurnEnd?.();send("message_stop", { type: "message_stop" });}} finally {@@ -313,21 +301,7 @@ export function createGeminiSseStream(const toolId = `toolu_${Date.now()}_${toolIdx}`;const blockIndex = curIdx++;opts.onToolCallObserved?.(part.functionCall.name);- let args = JSON.stringify(part.functionCall.args || {});- if (opts.repairToolArgs) {- try {- const repaired = opts.repairToolArgs(part.functionCall.name, args);- if (typeof repaired === "string" && repaired !== args) {- log(`[GeminiSSE] tool call repaired: ${part.functionCall.name}`);- args = repaired;- }- } catch (err) {- // A failing rule must never corrupt the stream.- log(- `[GeminiSSE] repairToolArgs threw for ${part.functionCall.name}: ${err}`- );- }- }+ const args = JSON.stringify(part.functionCall.args || {});const t = {id: toolId,diff --git a/packages/cli/src/handlers/shared/stream-parsers/openai-responses-sse.ts b/packages/cli/src/handlers/shared/stream-parsers/openai-responses-sse.tsindex ba71358f..379b956b 100644--- a/packages/cli/src/handlers/shared/stream-parsers/openai-responses-sse.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/openai-responses-sse.ts@@ -55,30 +55,11 @@ export function createResponsesStreamHandler(*/middlewareManager?: any;/**- * Behavior-layer tool-call interception. Called once per completed tool call- * with the fully accumulated argument JSON; return replacement JSON to repair- * the call, or null/undefined to leave it untouched.- *- * Only consulted for tools that `shouldBufferTool` opted in — see below.+ * Called once per `tool_use` block start, for the token tracker's tool+ * count. Tool-argument interception is not this parser's job: it happens at+ * the hook response seam, above every parser.*/- onToolCall?: (name: string, argsJson: string) => string | null | undefined;- /**- * Whether a tool's arguments must be withheld until the call completes.- *- * Repair is only possible for buffered calls: this parser streams- * `input_json_delta` the instant each fragment arrives, so by the time a call- * is complete its arguments are already on the wire to the client. Buffering- * is therefore opt-in PER TOOL — a tool no rule cares about keeps streaming- * incrementally, so the default path keeps its current latency profile.- */- shouldBufferTool?: (name: string) => boolean;- /**- * Behavior-layer observation (Layer 4). Called with normalized text so rules- * never have to understand this parser's event shape.- */- onAssistantText?: (text: string, kind?: "text" | "reasoning") => void;onToolCallObserved?: (name: string) => void;- onTurnEnd?: () => void;}): Response {const reader = response.body?.getReader();@@ -123,8 +104,6 @@ export function createResponsesStreamHandler(arguments: string;index: number;claudeId?: string;- /** Withhold input_json_delta until the call completes so it can be repaired. */- buffered?: boolean;};/** Shared across every chunk hook in this stream; handed to afterStreamComplete. */@@ -182,20 +161,11 @@ export function createResponsesStreamHandler(};const closeTools = () => {for (const fnCall of openToolBlocks) {- // A buffered call that never reached output_item.done (truncated or- // failed stream) still has to emit what it accumulated. Withholding it- // would turn "partial arguments" into "no arguments", which is strictly- // worse — the non-buffered path would already have streamed the same- // fragments. What the client then DOES with malformed JSON is decided- // by how the turn ends, not here: only an `error` event reliably stops- // Claude Code executing the fragment (see the catch block below).- if (fnCall.buffered && fnCall.arguments) {- send("content_block_delta", {- type: "content_block_delta",- index: fnCall.index,- delta: { type: "input_json_delta", partial_json: fnCall.arguments },- });- }+ // A call that never reached output_item.done (truncated or failed+ // stream) has already streamed its fragments. What the client then+ // DOES with malformed JSON is decided by how the turn ends, not here:+ // only an `error` event reliably stops Claude Code executing the+ // fragment (see the catch block below).send("content_block_stop", { type: "content_block_stop", index: fnCall.index });}openToolBlocks.clear();@@ -289,7 +259,6 @@ export function createResponsesStreamHandler(}if (event.type === "response.output_text.delta") {- opts.onAssistantText?.(event.delta ?? "", "text");closeReasoning();if (textIdx < 0) {textIdx = curIdx++;@@ -322,7 +291,6 @@ export function createResponsesStreamHandler(arguments: "",index: curIdx++,claudeId: callId,- buffered: opts.shouldBufferTool?.(fnName) === true,};functionCalls.set(openaiCallId, fnCallData);@@ -352,7 +320,6 @@ export function createResponsesStreamHandler(// than a summary of it; a thinking block all the same.event.type === "response.reasoning_text.delta") {- opts.onAssistantText?.(event.delta ?? "", "reasoning");// Reasoning is the model's chain of thought, not its answer — it// belongs in a thinking block, or Claude Code renders it as the reply.const summaryIndex =@@ -390,15 +357,11 @@ export function createResponsesStreamHandler(const fnCall = functionCalls.get(callId);if (fnCall) {fnCall.arguments += event.delta || "";- // Buffered calls emit nothing here — the whole argument object- // goes out in one delta at output_item.done, after any repair.- if (!fnCall.buffered) {- send("content_block_delta", {- type: "content_block_delta",- index: fnCall.index,- delta: { type: "input_json_delta", partial_json: event.delta || "" },- });- }+ send("content_block_delta", {+ type: "content_block_delta",+ index: fnCall.index,+ delta: { type: "input_json_delta", partial_json: event.delta || "" },+ });}} else if (event.type === "response.output_item.done") {if (event.item?.type === "reasoning" && event.item.encrypted_content) {@@ -415,27 +378,6 @@ export function createResponsesStreamHandler(const callId = event.item.call_id || event.item.id;const fnCall = functionCalls.get(callId) || functionCalls.get(event.item.id);if (fnCall && openToolBlocks.has(fnCall)) {- if (fnCall.buffered) {- // Give the behavior layer its one chance to rewrite the call,- // then emit the complete argument object as a single delta.- let finalArgs = fnCall.arguments;- try {- const repaired = opts.onToolCall?.(fnCall.name, finalArgs);- if (typeof repaired === "string" && repaired !== finalArgs) {- log(`[ResponsesSSE] tool call repaired: ${fnCall.name}`);- finalArgs = repaired;- }- } catch (err) {- // A failing rule must never corrupt the stream — emit the- // model's original arguments and carry on.- log(`[ResponsesSSE] onToolCall threw for ${fnCall.name}: ${err}`);- }- send("content_block_delta", {- type: "content_block_delta",- index: fnCall.index,- delta: { type: "input_json_delta", partial_json: finalArgs },- });- }send("content_block_stop", { type: "content_block_stop", index: fnCall.index });openToolBlocks.delete(fnCall);}@@ -558,7 +500,6 @@ export function createResponsesStreamHandler(if (opts.middlewareManager) {await opts.middlewareManager.afterStreamComplete(opts.modelName, streamMetadata);}- opts.onTurnEnd?.();safeClose();} catch (error) {if (pingInterval) {diff --git a/packages/cli/src/handlers/shared/stream-parsers/openai-sse.ts b/packages/cli/src/handlers/shared/stream-parsers/openai-sse.tsindex 39c41c00..e46cce94 100644--- a/packages/cli/src/handlers/shared/stream-parsers/openai-sse.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/openai-sse.ts@@ -255,49 +255,16 @@ export function createStreamingResponseHandler(toolNameMap?: Map<string, string>, // Truncated → original tool name mappingpriorInputTokens?: number, // Last request's context size — seeds message_start.usage/**- * Behavior layer (Layer 4) tool-call interception. Grouped into one object- * rather than two more positional parameters — this signature already carries- * nine.- *- * Unlike the Responses parser, this path already buffers tool arguments- * whenever the request carries tools (see `buffered` below), so hooking repair- * in costs nothing extra: the complete argument object is assembled here- * regardless. `shouldBufferTool` only matters for the rare case of a rule- * wanting a tool the schema-validation path would not have buffered.+ * Observation callbacks, grouped into one object rather than another+ * positional parameter — this signature already carries nine.+ * `onToolCallObserved` feeds the token tracker's tool count. Tool-argument+ * interception is not this parser's job: it happens at the hook response+ * seam, above every parser.*/- behavior?: {- shouldBufferTool?: (name: string) => boolean;- onToolCall?: (name: string, argsJson: string) => string | null | undefined;- /**- * Layer 4 observation. Normalized text, so rules never parse this parser's- * event shape.- */- onAssistantText?: (text: string, kind?: "text" | "reasoning") => void;+ observers?: {onToolCallObserved?: (name: string) => void;- onTurnEnd?: () => void;}): Response {- /**- * Offer a COMPLETE argument object to the behavior layer.- *- * Only ever called where the full object is in hand. The incremental- * `partial_json` fragment path must never route through here — repairing a- * fragment would emit malformed JSON.- */- const repairArgs = (toolName: string, argsJson: string): string => {- if (!behavior?.onToolCall) return argsJson;- try {- const repaired = behavior.onToolCall(toolName, argsJson);- if (typeof repaired === "string" && repaired !== argsJson) {- log(`[Streaming] tool call repaired by behavior layer: ${toolName}`);- return repaired;- }- } catch (err) {- // A failing rule must never corrupt the stream.- log(`[Streaming] behavior onToolCall threw for ${toolName}: ${err}`);- }- return argsJson;- };log(`[Streaming] ===== HANDLER STARTED for ${target} =====`);let isClosed = false;let ping: NodeJS.Timeout | null = null;@@ -318,15 +285,14 @@ export function createStreamingResponseHandler(//// This parser declared `onToolCallObserved` and never called it — so on the// busiest wire in claudish (GLM, Kimi, Grok, DeepSeek, Qwen, OpenRouter,- // LiteLLM) the behaviour layer's tool-name list was always empty and the- // session summary would have reported zero tools. Hooking the writer instead+ // LiteLLM) the session summary would have reported zero tools. Hooking the writer instead// of the emission sites makes that class of omission impossible: a new// tool_use path cannot forget to opt in, and because exactly one// `content_block_start` is emitted per tool call, it cannot double count// either. The `input_json_delta` frames deliberately do not match.if (e === "content_block_start" && d?.content_block?.type === "tool_use") {try {- behavior?.onToolCallObserved?.(String(d.content_block.name ?? ""));+ observers?.onToolCallObserved?.(String(d.content_block.name ?? ""));} catch (err) {log(`[Streaming] onToolCallObserved threw: ${err}`);}@@ -354,7 +320,6 @@ export function createStreamingResponseHandler(*/const emitSplitContent = ({ thinking, text }: ThinkSplit): void => {if (thinking) {- behavior?.onAssistantText?.(thinking, "reasoning");writer.append(writer.openThinking(), thinking);}if (!text) return;@@ -583,7 +548,7 @@ export function createStreamingResponseHandler(const toolIdx = writer.reserve();const toolId = `tool_${Date.now()}_${toolIdx}`;const ref = writer.openTool({ id: toolId, name: tc.name, index: toolIdx });- writer.append(ref, repairArgs(tc.name, JSON.stringify(tc.arguments)));+ writer.append(ref, JSON.stringify(tc.arguments));writer.close(ref);}}@@ -614,11 +579,8 @@ export function createStreamingResponseHandler();if (validation.valid || (validation.repaired && validation.repairedArgs)) {- const argsJson = repairArgs(- t.name,- JSON.stringify(- validation.repaired ? validation.repairedArgs : validation.parsedArgs- )+ const argsJson = JSON.stringify(+ validation.repaired ? validation.repairedArgs : validation.parsedArgs);log(`[Streaming] Sending buffered tool call (finish_reason!=tool_calls): ${t.name} with args: ${argsJson}`@@ -636,7 +598,7 @@ export function createStreamingResponseHandler(}} else {// No schemas to validate against — send as-is- const argsJson = repairArgs(t.name, t.arguments || "{}");+ const argsJson = t.arguments || "{}";log(`[Streaming] Sending buffered tool call (no validation): ${t.name} with args: ${argsJson}`);@@ -790,7 +752,6 @@ export function createStreamingResponseHandler(output_tokens: state.usage?.completion_tokens || 0,},});- behavior?.onTurnEnd?.();send("message_stop", { type: "message_stop" });}@@ -908,7 +869,6 @@ export function createStreamingResponseHandler(// providers whose chat template opens `<think>` server-side and// leaks the bare close into the content.thinkSplitter.disarmOpen();- behavior?.onAssistantText?.(reasoningText, "reasoning");state.lastActivity = Date.now();// Reasoning arriving AFTER text used to open a thinking block// while the text block was still open — two open blocks, which@@ -919,7 +879,6 @@ export function createStreamingResponseHandler(// Handle text contentconst txt = delta.content || "";- if (txt) behavior?.onAssistantText?.(txt, "text");log(`[Streaming] Text chunk: "${txt.substring(0, 30).replace(/\n/g, "\\n")}" (${txt.length} chars)`);@@ -997,12 +956,9 @@ export function createStreamingResponseHandler(// index before the name did are drained in here.arguments: state.pendingToolArgs.get(idx) ?? "",ref: null,- // Buffer if we have schemas to validate, OR if a behavior- // rule wants to rewrite this call — repair is only- // possible while the arguments are still withheld.- buffered:- (!!toolSchemas && toolSchemas.length > 0) ||- behavior?.shouldBufferTool?.(restoredName) === true,+ // Buffer if we have schemas to validate the+ // completed arguments against.+ buffered: !!toolSchemas && toolSchemas.length > 0,};if (t.arguments) {log(@@ -1029,9 +985,7 @@ export function createStreamingResponseHandler();} else {t.name = restoredName;- t.buffered =- (!!toolSchemas && toolSchemas.length > 0) ||- behavior?.shouldBufferTool?.(restoredName) === true;+ t.buffered = !!toolSchemas && toolSchemas.length > 0;if (isWebSearchToolCall(restoredName)) {warnWebSearchUnsupported(restoredName, target);}@@ -1106,10 +1060,7 @@ export function createStreamingResponseHandler(log(`[Streaming] Tool call ${t.name} was repaired with inferred parameters`);- const repairedJson = repairArgs(- t.name,- JSON.stringify(validation.repairedArgs)- );+ const repairedJson = JSON.stringify(validation.repairedArgs);log(`[Streaming] Sending repaired tool call: ${t.name} with args: ${repairedJson}`);@@ -1176,10 +1127,7 @@ export function createStreamingResponseHandler(// Valid tool call - send if buffered, close if notif (t.buffered && !t.started) {- const argsJson = repairArgs(- t.name,- JSON.stringify(validation.parsedArgs)- );+ const argsJson = JSON.stringify(validation.parsedArgs);t.ref = writer.openTool({id: t.id,name: t.name,diff --git a/packages/cli/src/hooks/builtins/index.ts b/packages/cli/src/hooks/builtins/index.tsindex cd09bc76..f856907d 100644--- a/packages/cli/src/hooks/builtins/index.ts+++ b/packages/cli/src/hooks/builtins/index.ts@@ -7,8 +7,22 @@* bucket.*/+import type { HooksConfig } from "../config.js";import type { BuiltinHook } from "../registry.js";+import { createObserverHook } from "./observer.js";import { planModeHook } from "./plan-mode.js";import { sessionContextHook } from "./session-context.js";+/** The built-ins that need no configuration. */export const BUILTIN_HOOKS: ReadonlyArray<BuiltinHook> = [planModeHook, sessionContextHook];++/** Every built-in for one config: the fixed ones, then the observer it configures. */+export function builtinHooks(config: HooksConfig): ReadonlyArray<BuiltinHook> {+ return [+ ...BUILTIN_HOOKS,+ createObserverHook(+ config,+ BUILTIN_HOOKS.map((h) => h.id)+ ),+ ];+}diff --git a/packages/cli/src/hooks/builtins/observer.test.ts b/packages/cli/src/hooks/builtins/observer.test.tsnew file mode 100644index 00000000..0983d5db--- /dev/null+++ b/packages/cli/src/hooks/builtins/observer.test.ts@@ -0,0 +1,139 @@+/**+ * The observer built-in (`observer/divergence`): an observe-mode `toolCall` hook+ * over `hooks.observer.watchTools`, off unless the observer is enabled, and+ * never holding the stream.+ */++import { afterEach, describe, expect, it } from "bun:test";+import { HookEngine } from "../engine.js";+import { UnavailableSink } from "../injection/sinks.js";+import type { RequestContext, ToolCallContext } from "../public.js";+import { HookRegistry } from "../registry.js";+import { RequestHooks } from "../request-stage.js";+import { applyResponseSeam, planSeam } from "../response-seam.js";+import { builtinHooks } from "./index.js";+import {+ DEFAULT_WATCH_TOOLS,+ OBSERVER_HOOK_ID,+ createObserverHook,+ observerEnabled,+} from "./observer.js";++const realFetch = globalThis.fetch;+afterEach(() => {+ globalThis.fetch = realFetch;+});++const ctx = {} as RequestContext;++describe("observer built-in definition", () => {+ it("keeps the observer's id, is foreign-scoped, and observes without holding", () => {+ const hook = createObserverHook({}, ["plan-mode/plan-file-path"]);+ expect(hook.id).toBe(OBSERVER_HOOK_ID);+ expect(hook.routes).toBe("foreign");+ expect(hook.on?.toolCall?.observe).toBe(true);+ expect(hook.on?.toolCall?.tools).toEqual(DEFAULT_WATCH_TOOLS);+ expect(DEFAULT_WATCH_TOOLS).toEqual(["Write", "Edit", "NotebookEdit", "ExitPlanMode"]);+ });++ it("watches hooks.observer.watchTools when set", () => {+ const hook = createObserverHook({ observer: { watchTools: ["Bash"] } }, []);+ expect(hook.on?.toolCall?.tools).toEqual(["Bash"]);+ });++ it("is armed only when enabled and not in mode off", () => {+ const armed = (observer: object | undefined) =>+ createObserverHook({ observer } as never, []).on?.toolCall?.armed?.(ctx);+ expect(armed(undefined)).toBe(false);+ expect(armed({ enabled: false })).toBe(false);+ expect(armed({ enabled: true })).toBe(true);+ expect(armed({ enabled: true, mode: "suggest" })).toBe(true);+ expect(armed({ enabled: true, mode: "off" })).toBe(false);+ expect(observerEnabled({ observer: { enabled: true, mode: "off" } })).toBe(false);+ });++ it("returns no actions at once: the consultation is fire-and-forget", () => {+ const hook = createObserverHook({}, []);+ const result = hook.on?.toolCall?.handle({+ route: { modelId: "m", provider: "p", native: false },+ request: { tools: [] },+ harness: { planModeActive: false },+ tool: { id: "t", name: "Write", args: {}, rawArgs: "{}" },+ } as unknown as ToolCallContext);+ expect(result).toEqual([]);+ });++ it("is registered among the built-ins with the other built-ins as its vocabulary", () => {+ const ids = builtinHooks({}).map((h) => h.id);+ expect(ids).toEqual([+ "plan-mode/plan-file-path",+ "session-context/no-harness-echo",+ OBSERVER_HOOK_ID,+ ]);+ });+});++describe("observer through the seam", () => {+ it("consults the local model about the delivered call, without holding or changing the stream", async () => {+ const digests: any[] = [];+ globalThis.fetch = (async (_url: unknown, init?: RequestInit) => {+ const body = JSON.parse(String(init?.body));+ digests.push(JSON.parse(body.messages[1].content));+ return new Response(+ JSON.stringify({ message: { content: JSON.stringify({ ruleId: null, confidence: 0 }) } }),+ { headers: { "content-type": "application/json" } }+ );+ }) as unknown as typeof fetch;++ const config = { observer: { enabled: true, model: "tiny-local" } };+ const engine = new HookEngine({+ registry: new HookRegistry(builtinHooks(config), [], undefined),+ config,+ hostMode: "other",+ journalSink: () => {},+ warn: () => {},+ drainTelemetryOutbox: false,+ });+ const c = new Map<string, unknown>();+ const scope = await new RequestHooks(engine, null, new UnavailableSink(() => {})).beginAttempt(+ { get: (k: string) => c.get(k), set: (k: string, v: unknown) => c.set(k, v) } as never,+ {+ claudeRequest: {+ messages: [{ role: "user", content: "write it" }],+ tools: [{ name: "Write", input_schema: { type: "object" } }],+ },+ route: { modelId: "glm-5", provider: "zai", native: false },+ model: "glm-5",+ stream: true,+ }+ );+ expect(planSeam(scope)).toEqual({ mode: "none", tap: true });++ const wire = [+ 'event: content_block_start\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t1","name":"Write","input":{}}}\n\n',+ 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\\"file_path\\":\\"/p/x.md\\",\\"content\\":\\"secret\\"}"}}\n\n',+ 'event: content_block_stop\ndata: {"type":"content_block_stop","index":0}\n\n',+ 'event: message_stop\ndata: {"type":"message_stop"}\n\n',+ ];+ const res = await applyResponseSeam(+ new Response(wire.join(""), { headers: { "content-type": "text/event-stream" } }),+ scope+ );+ expect(await res.text()).toBe(wire.join(""));++ const deadline = Date.now() + 2_000;+ while (digests.length === 0 && Date.now() < deadline) await Bun.sleep(5);+ expect(digests).toHaveLength(1);+ expect(digests[0].proposedCall).toEqual({+ name: "Write",+ argKeys: ["file_path", "content"],+ paths: ["/p/x.md"],+ });+ // A digest carries no argument values other than paths.+ expect(JSON.stringify(digests[0])).not.toContain("secret");+ expect(digests[0].ruleVocabulary).toEqual([+ "plan-mode/plan-file-path",+ "session-context/no-harness-echo",+ ]);+ });+});diff --git a/packages/cli/src/hooks/builtins/observer.ts b/packages/cli/src/hooks/builtins/observer.tsnew file mode 100644index 00000000..ccd1dbcf--- /dev/null+++ b/packages/cli/src/hooks/builtins/observer.ts@@ -0,0 +1,111 @@+/**+ * Built-in hook `observer/divergence`: the local advisory observer.+ *+ * A small LOCAL model (hooks/observer/client.ts) is asked whether a tool call+ * the model just made violates one of claudish's conformance rules. It sees a+ * digest — tool names, harness facts, the call's argument keys and path-like+ * values — never conversation text. Its verdict lands in the divergence log+ * (`~/.claudish/behavior-divergences.jsonl`), the input for rules that do not+ * exist yet.+ *+ * An observe-mode `toolCall` hook: it never holds the stream and can only warn,+ * so turning the observer on no longer suppresses incremental delivery of+ * `Write` content, as the behavior layer's buffering did. The consultation is+ * fire-and-forget: the handler returns at once, and the observer keeps its own+ * timeout (`hooks.observer.timeoutMs`), so a slow local model never counts as a+ * hook timeout.+ *+ * Off unless `hooks.observer.enabled` is true and the mode is not `off`.+ * `enforce` is rejected by the config schema: the observer is advisory.+ */++import { log } from "../../logger.js";+import type { HooksConfig } from "../config.js";+import { observe } from "../observer/client.js";+import { buildDigest } from "../observer/digest.js";+import { recordLiveDivergence } from "../observer/live-log.js";+import type { ToolCallAction, ToolCallContext } from "../public.js";+import type { BuiltinHook } from "../registry.js";++export const OBSERVER_HOOK_ID = "observer/divergence";++/** Watched when `hooks.observer.watchTools` is not set (unchanged from the behavior layer). */+export const DEFAULT_WATCH_TOOLS: ReadonlyArray<string> = [+ "Write",+ "Edit",+ "NotebookEdit",+ "ExitPlanMode",+];++/** True when the config turns the observer on. */+export function observerEnabled(config: Pick<HooksConfig, "observer">): boolean {+ return config.observer?.enabled === true && (config.observer.mode ?? "suggest") !== "off";+}++/** Ask the observer about one delivered call. Advisory only: never throws, never awaited by the seam. */+async function consult(+ config: Pick<HooksConfig, "observer">,+ ruleVocabulary: ReadonlyArray<string>,+ ctx: ToolCallContext+): Promise<void> {+ try {+ const digest = buildDigest({+ model: ctx.route.modelId,+ toolNames: ctx.request.tools.map((t) => t.name),+ harness: { ...ctx.harness },+ ruleVocabulary: [...ruleVocabulary],+ call: { name: ctx.tool.name, args: { ...ctx.tool.args } },+ });+ const verdict = await observe(digest, config);+ if (!verdict?.ruleId) return;+ log(+ `[hooks:observer] flagged ${ctx.tool.name} as ${verdict.ruleId} ` ++ `(confidence ${verdict.confidence})${verdict.note ? `: ${verdict.note}` : ""}`+ );+ await recordLiveDivergence({+ source: "observer",+ ts: new Date().toISOString(),+ model: ctx.route.modelId,+ toolName: ctx.tool.name,+ ruleId: verdict.ruleId,+ confidence: verdict.confidence,+ note: verdict.note,+ paths: digest.proposedCall?.paths,+ });+ } catch (err) {+ log(`[hooks:observer] consult failed: ${err}`);+ }+}++/**+ * The observer built-in for one config. `ruleVocabulary` is the rule ids the+ * observer may name (every other built-in's id); anything else it returns is a+ * hallucination and is discarded.+ */+export function createObserverHook(+ config: Pick<HooksConfig, "observer">,+ ruleVocabulary: ReadonlyArray<string>+): BuiltinHook {+ return {+ apiVersion: 1,+ id: OBSERVER_HOOK_ID,+ description:+ "Ask a small local model whether a delivered tool call breaks a conformance rule; " ++ "log its verdict. Advisory, off by default (hooks.observer).",+ defaultSeverity: "fix",+ // The measured divergences are foreign models'; native Claude honours+ // Claude Code's conventions itself.+ routes: "foreign",+ on: {+ toolCall: {+ tools: config.observer?.watchTools ?? DEFAULT_WATCH_TOOLS,+ observe: true,+ armed: () => observerEnabled(config),+ handle(ctx: ToolCallContext): ToolCallAction[] {+ void consult(config, ruleVocabulary, ctx);+ return [];+ },+ },+ },+ };+}diff --git a/packages/cli/src/hooks/builtins/plan-mode.test.ts b/packages/cli/src/hooks/builtins/plan-mode.test.tsindex 49efea96..28033444 100644--- a/packages/cli/src/hooks/builtins/plan-mode.test.ts+++ b/packages/cli/src/hooks/builtins/plan-mode.test.ts@@ -1,12 +1,19 @@/**- * Ported from behavior/rules/plan-mode.test.ts (`planFilePathRule.onRequest`).- * The tool half (`onToolCall` → `on.toolCall`) is ported with the response seam.+ * Ported 1:1 from behavior/rules/plan-mode.test.ts: `planFilePathRule.onRequest`+ * → `on.request`, `planFilePathRule.onToolCall` → `on.toolCall.handle`, and the+ * rule's `armed` gate → `on.toolCall.armed`.*/import { describe, expect, it } from "bun:test";-import type { HarnessFacts, RequestContext } from "../public.js";+import type { HarnessFacts, RequestContext, ToolCallContext } from "../public.js";import { BUILTIN_HOOKS } from "./index.js";-import { PLAN_MODE_HOOK_ID, planModeHook, planModeRequest } from "./plan-mode.js";+import {+ PLAN_MODE_HOOK_ID,+ PLAN_WRITE_TOOLS,+ planModeHook,+ planModeRequest,+ planModeToolCall,+} from "./plan-mode.js";const assignedPath = "/workspace/.custom-plans/assigned-session.md";const planDir = "/workspace/.custom-plans";@@ -60,7 +67,67 @@ describe("plan-mode/plan-file-path request handler", () => {});});+function toolCallContext(+ args: Record<string, unknown>,+ harness: HarnessFacts = { planModeActive: true, planFilePath: assignedPath, planDir }+): ToolCallContext {+ return {+ ...requestContext({ harness }),+ event: "toolCall",+ tool: { id: "toolu_1", name: "Write", args, rawArgs: JSON.stringify(args) },+ } as unknown as ToolCallContext;+}++describe("plan-mode/plan-file-path toolCall handler", () => {+ it("redirects an invented filename inside the assigned plan directory", () => {+ const actions = planModeToolCall(+ toolCallContext({ file_path: `${planDir}/invented-name.md`, content: "# Plan" })+ );++ expect(actions).toHaveLength(1);+ const [action] = actions;+ if (action?.type !== "repairToolArgs") throw new Error("expected repairToolArgs action");+ expect(action.args).toEqual({ file_path: assignedPath, content: "# Plan" });+ });++ it("does not touch a normal project file outside the plan directory", () => {+ expect(+ planModeToolCall(+ toolCallContext({ file_path: "/workspace/src/implementation.ts", content: "source" })+ )+ ).toEqual([]);+ });++ it("does not touch the already-correct assigned path", () => {+ expect(+ planModeToolCall(toolCallContext({ file_path: assignedPath, content: "# Correct plan" }))+ ).toEqual([]);+ });++ it("ignores missing and non-string file_path values", () => {+ expect(planModeToolCall(toolCallContext({ content: "missing" }))).toEqual([]);+ expect(planModeToolCall(toolCallContext({ file_path: 42, content: "number" }))).toEqual([]);+ expect(planModeToolCall(toolCallContext({ file_path: null, content: "null" }))).toEqual([]);+ });++ it("does nothing without a plan file path and directory", () => {+ expect(+ planModeToolCall(toolCallContext({ file_path: `${planDir}/x.md` }, { planModeActive: true }))+ ).toEqual([]);+ });+});+describe("plan-mode built-in definition", () => {+ it("intercepts the write tools, armed only in plan mode", () => {+ const tc = planModeHook.on?.toolCall;+ expect(tc?.tools).toEqual(PLAN_WRITE_TOOLS);+ expect(tc?.tools).toEqual(["Write", "Edit", "NotebookEdit"]);+ expect(tc?.observe).toBeUndefined();+ expect(tc?.armed?.(requestContext())).toBe(true);+ // Outside plan mode it must not make the seam hold Write/Edit arguments.+ expect(tc?.armed?.(requestContext({ harness: { planModeActive: false } }))).toBe(false);+ });+it("keeps its id, defaults to fix, and is scoped to foreign routes", () => {expect(planModeHook.id).toBe("plan-mode/plan-file-path");expect(planModeHook.defaultSeverity).toBe("fix");diff --git a/packages/cli/src/hooks/builtins/plan-mode.ts b/packages/cli/src/hooks/builtins/plan-mode.tsindex 976a665d..cd79122a 100644--- a/packages/cli/src/hooks/builtins/plan-mode.ts+++ b/packages/cli/src/hooks/builtins/plan-mode.ts@@ -1,5 +1,5 @@/**- * Built-in hook `plan-mode/plan-file-path` — the request half.+ * Built-in hook `plan-mode/plan-file-path`.** Background (measured, not assumed). Claude Code 2.1.220's ExitPlanModeV2 takes* NO plan parameter — its advertised schema is `{allowedPrompts?}` and the tool@@ -29,16 +29,32 @@* action is applied at stage B, after tool conversion, so `--summarize-tools`* (first sentence, 150 characters) can never cut it.*- * The tool half (redirecting a Write/Edit aimed at the plan directory onto the- * assigned path) needs the response seam's tool interception and is ported- * with it.+ * The tool half redirects a Write/Edit/NotebookEdit that is ALREADY aimed at+ * the plan directory onto the assigned plan file. It is armed only in plan+ * mode: outside it the hook cannot fire, so it must not make the seam hold+ * Write/Edit arguments, which would suppress incremental streaming of file+ * contents on every ordinary request.*/-import { type RequestAction, type RequestContext, act } from "../public.js";+import {+ type RequestAction,+ type RequestContext,+ type ToolCallAction,+ type ToolCallContext,+ act,+} from "../public.js";import type { BuiltinHook } from "../registry.js";export const PLAN_MODE_HOOK_ID = "plan-mode/plan-file-path";+/** Tools that can create the plan file, and so can target the wrong path. */+export const PLAN_WRITE_TOOLS: ReadonlyArray<string> = ["Write", "Edit", "NotebookEdit"];++function directoryOf(filePath: string): string | undefined {+ const slash = filePath.lastIndexOf("/");+ return slash > 0 ? filePath.slice(0, slash) : undefined;+}+/** The text appended to the ExitPlanMode description. Unchanged from the behavior rule. */export function planFileInstruction(planFilePath: string): string {return `@@ -60,6 +76,27 @@ export function planModeRequest(ctx: RequestContext): RequestAction[] {return [act.rewriteToolDescription("ExitPlanMode", planFileInstruction(planFilePath))];}+/** The tool-call handler, exported for unit tests. */+export function planModeToolCall(ctx: ToolCallContext): ToolCallAction[] {+ const { planFilePath, planDir } = ctx.harness;+ if (!planFilePath || !planDir) return [];++ const filePath = ctx.tool.args.file_path;+ if (typeof filePath !== "string" || filePath === planFilePath) return [];++ // Only ever redirect writes that are ALREADY aimed at the plan directory. A+ // model writing source files, docs, or session artifacts elsewhere is doing+ // normal work and must not be touched.+ if (directoryOf(filePath) !== planDir) return [];++ return [+ act.repairToolArgs(+ { ...ctx.tool.args, file_path: planFilePath },+ `redirected ${ctx.tool.name} from ${filePath} to the session's assigned plan file ${planFilePath}`+ ),+ ];+}+export const planModeHook: BuiltinHook = {apiVersion: 1,id: PLAN_MODE_HOOK_ID,@@ -70,5 +107,12 @@ export const planModeHook: BuiltinHook = {// Native Claude models are already 87/87 on this; running the hook for them// would be pure risk with no upside.routes: "foreign",- on: { request: planModeRequest },+ on: {+ request: planModeRequest,+ toolCall: {+ tools: PLAN_WRITE_TOOLS,+ armed: (ctx) => ctx.harness.planModeActive === true,+ handle: planModeToolCall,+ },+ },};diff --git a/packages/cli/src/hooks/index.ts b/packages/cli/src/hooks/index.tsindex 0110acb4..7e8ed6d1 100644--- a/packages/cli/src/hooks/index.ts+++ b/packages/cli/src/hooks/index.ts@@ -16,7 +16,7 @@import { log } from "../logger.js";import { loadConfig } from "../profile-config.js";-import { BUILTIN_HOOKS } from "./builtins/index.js";+import { builtinHooks } from "./builtins/index.js";import {type HooksConfig,hooksConfigDir,@@ -85,13 +85,14 @@ async function buildEngine(hostMode: HostMode): Promise<HookEngine> {log(`[hooks] user hook loading failed, built-in hooks only: ${errorText(err)}`);}+ const builtins = builtinHooks(config);const engine = new HookEngine({- registry: new HookRegistry(BUILTIN_HOOKS, users, config.severity),+ registry: new HookRegistry(builtins, users, config.severity),config,hostMode,});log(- `[hooks] engine ready (host ${hostMode}): ${BUILTIN_HOOKS.length} built-in, ${users.length} user hook(s)`+ `[hooks] engine ready (host ${hostMode}): ${builtins.length} built-in, ${users.length} user hook(s)`);return engine;}diff --git a/packages/cli/src/hooks/injection/sinks.test.ts b/packages/cli/src/hooks/injection/sinks.test.tsnew file mode 100644index 00000000..0361c801--- /dev/null+++ b/packages/cli/src/hooks/injection/sinks.test.ts@@ -0,0 +1,109 @@+import { afterEach, describe, expect, it } from "bun:test";+import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import {+ HOOK_INBOX_ENV,+ InboxFileSink,+ UnavailableSink,+ resetUnavailableSinkReportForTests,+ sinkFromEnv,+} from "./sinks.js";++const dirs: string[] = [];+function inbox(): string {+ const dir = mkdtempSync(join(tmpdir(), "claudish-inbox-"));+ dirs.push(dir);+ return join(dir, "hook-inbox.jsonl");+}+afterEach(() => {+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });+});++const lines = (path: string) =>+ readFileSync(path, "utf8")+ .split("\n")+ .filter(Boolean)+ .map((l) => JSON.parse(l));++const at = () => new Date("2026-10-14T00:00:00.000Z");++describe("InboxFileSink", () => {+ it("appends one JSON object per line in the documented shapes", () => {+ const path = inbox();+ const sink = new InboxFileSink(path, undefined, at);+ sink.stop("r1");+ expect(sink.inject("r1", "hook:a/b", "HOOK-PING")).toBe("queued");+ expect(sink.annotate("r1", "hook:a/b", "k", [1, "x"])).toBe("queued");+ sink.end("r1", false);+ sink.end("r2", true);+ expect(lines(path)).toEqual([+ { v: 1, kind: "stop", req: "r1" },+ {+ v: 1,+ kind: "inject",+ req: "r1",+ hookId: "hook:a/b",+ text: "HOOK-PING",+ at: at().toISOString(),+ },+ {+ v: 1,+ kind: "annotate",+ req: "r1",+ hookId: "hook:a/b",+ key: "k",+ value: [1, "x"],+ at: at().toISOString(),+ },+ { v: 1, kind: "end", req: "r1" },+ { v: 1, kind: "end", req: "r2", aborted: true },+ ]);+ expect(statSync(path).mode & 0o777).toBe(0o600);+ });++ it("caps payload lines only: past the cap it writes one capped line and keeps writing stop/end", () => {+ const path = inbox();+ const sink = new InboxFileSink(path, 150, at);+ expect(sink.inject("r", "h", "x".repeat(20))).toBe("queued");+ expect(sink.inject("r", "h", "y".repeat(80))).toBe("inbox_cap");+ expect(sink.inject("r", "h", "z")).toBe("inbox_cap");+ for (let i = 0; i < 20; i++) {+ sink.stop(`s${i}`);+ sink.end(`s${i}`, false);+ }+ const kinds = lines(path).map((l) => l.kind);+ expect(kinds.slice(0, 2)).toEqual(["inject", "capped"]);+ expect(kinds.filter((k) => k === "capped")).toHaveLength(1);+ expect(kinds.filter((k) => k === "stop")).toHaveLength(20);+ });++ it("fails open when the file cannot be written", () => {+ const sink = new InboxFileSink(join(inbox(), "missing-dir", "x.jsonl"));+ expect(() => sink.stop("r")).not.toThrow();+ expect(sink.inject("r", "h", "t")).toBe("write_failed");+ });+});++describe("UnavailableSink and sinkFromEnv", () => {+ it("drops injections with one stderr line per process, annotations silently", () => {+ resetUnavailableSinkReportForTests();+ const warned: string[] = [];+ const sink = new UnavailableSink((l) => warned.push(l));+ expect(sink.inject()).toBe("unavailable");+ expect(sink.inject()).toBe("unavailable");+ expect(sink.annotate()).toBe("unavailable");+ expect(warned).toHaveLength(1);+ expect(sink.available).toBe(false);+ });++ it("uses the inbox the owner named, else none", () => {+ const path = inbox();+ const sink = sinkFromEnv({ [HOOK_INBOX_ENV]: path });+ expect(sink).toBeInstanceOf(InboxFileSink);+ expect((sink as InboxFileSink).path).toBe(path);+ // One sink per file: the payload cap spans every request of the process.+ expect(sinkFromEnv({ [HOOK_INBOX_ENV]: path })).toBe(sink);+ expect(sinkFromEnv({})).toBeInstanceOf(UnavailableSink);+ });+});diff --git a/packages/cli/src/hooks/injection/sinks.ts b/packages/cli/src/hooks/injection/sinks.tsnew file mode 100644index 00000000..664e9a8a--- /dev/null+++ b/packages/cli/src/hooks/injection/sinks.ts@@ -0,0 +1,158 @@+/**+ * Where a proxy event's cross-process actions go: `injectUserTurn` and+ * `annotateTurn` returned from `responseEnd`, plus the `stop` / `end`+ * bookkeeping that tells the session owner which responses are still running+ * their `responseEnd` hooks (§2.3).+ *+ * - `InboxFileSink`: a pane child. The owner created `hook-inbox.jsonl` and+ * named it in `CLAUDISH_HOOK_INBOX`; every line is one synchronous append, so+ * a `stop` written before the `message_stop` chunk is enqueued is on disk+ * before Claude Code can read that chunk.+ * - `UnavailableSink`: no session driver in this process (`serve`, the MCP+ * server's own proxy, a no-surface interactive launch). Injections and+ * annotations are dropped `unavailable`.+ *+ * The in-process sink of the interactive launcher arrives with its driver.+ */++import { appendFileSync } from "node:fs";+import { log, logStderr } from "../../logger.js";+import type { JsonValue } from "../public.js";++/** The pane-child env var naming the owner-created inbox file. */+export const HOOK_INBOX_ENV = "CLAUDISH_HOOK_INBOX";++/** Payload bytes (`inject` + `annotate` lines) one inbox accepts before it caps. */+export const INBOX_PAYLOAD_CAP_BYTES = 1024 * 1024;++/** What happened to one injection or annotation handed to a sink. */+export type SinkOutcome = "queued" | "unavailable" | "inbox_cap" | "write_failed";++export interface InjectionSink {+ /** False when nothing in this process can deliver an injection. */+ readonly available: boolean;+ /** A response's `message_stop` is about to reach the client. Synchronous. */+ stop(req: string): void;+ inject(req: string, hookId: string, text: string): SinkOutcome;+ annotate(req: string, hookId: string, key: string, value: JsonValue): SinkOutcome;+ /** Every `responseEnd` hook of `req` resolved or timed out, or the stream was aborted. */+ end(req: string, aborted: boolean): void;+}++/** A pane child's sink: one JSON object per line, appended synchronously. */+export class InboxFileSink implements InjectionSink {+ readonly available = true;+ private payloadBytes = 0;+ private capped = false;++ constructor(+ readonly path: string,+ private readonly capBytes: number = INBOX_PAYLOAD_CAP_BYTES,+ private readonly now: () => Date = () => new Date()+ ) {}++ stop(req: string): void {+ this.append({ v: 1, kind: "stop", req });+ }++ inject(req: string, hookId: string, text: string): SinkOutcome {+ return this.payload({ v: 1, kind: "inject", req, hookId, text, at: this.now().toISOString() });+ }++ annotate(req: string, hookId: string, key: string, value: JsonValue): SinkOutcome {+ return this.payload({+ v: 1,+ kind: "annotate",+ req,+ hookId,+ key,+ value,+ at: this.now().toISOString(),+ });+ }++ end(req: string, aborted: boolean): void {+ this.append(aborted ? { v: 1, kind: "end", req, aborted: true } : { v: 1, kind: "end", req });+ }++ private payload(line: Record<string, unknown>): SinkOutcome {+ if (this.capped) return "inbox_cap";+ const text = `${JSON.stringify(line)}\n`;+ const bytes = Buffer.byteLength(text);+ if (this.payloadBytes + bytes > this.capBytes) {+ // Past the cap the child stops appending payload, says so once, and keeps+ // writing `stop` and `end`, so the owner's settle never waits on a request+ // that will not report.+ this.capped = true;+ this.append({ v: 1, kind: "capped" });+ return "inbox_cap";+ }+ if (!this.appendText(text)) return "write_failed";+ this.payloadBytes += bytes;+ return "queued";+ }++ private append(line: Record<string, unknown>): void {+ this.appendText(`${JSON.stringify(line)}\n`);+ }++ private appendText(text: string): boolean {+ try {+ appendFileSync(this.path, text, { mode: 0o600 });+ return true;+ } catch (err) {+ // Fail open: a lost inbox line costs one injection, never the response.+ log(`[hooks] inbox ${this.path}: append failed: ${err instanceof Error ? err.message : err}`);+ return false;+ }+ }+}++let unavailableReported = false;++/** No session driver: injections are dropped, with one stderr line per process. */+export class UnavailableSink implements InjectionSink {+ readonly available = false;++ constructor(private readonly warn: (line: string) => void = logStderr) {}++ stop(): void {}+ end(): void {}++ inject(): SinkOutcome {+ if (!unavailableReported) {+ unavailableReported = true;+ this.warn(+ "hook injection dropped: this claudish process has no Claude Code session to deliver it to"+ );+ }+ return "unavailable";+ }++ annotate(): SinkOutcome {+ return "unavailable";+ }+}++/** Test seam: let the next unavailable injection print its stderr line again. */+export function resetUnavailableSinkReportForTests(): void {+ unavailableReported = false;+}++/** One sink per inbox file, so the payload cap counts the whole file, not one request. */+const inboxSinks = new Map<string, InboxFileSink>();++/**+ * The sink for this process: the inbox a pane owner named, or none. The proxy+ * builds its per-request hooks often; every one of them shares the file's sink.+ */+export function sinkFromEnv(env: NodeJS.ProcessEnv = process.env): InjectionSink {+ const path = env[HOOK_INBOX_ENV];+ if (!path) return new UnavailableSink();+ let sink = inboxSinks.get(path);+ if (!sink) {+ sink = new InboxFileSink(path);+ inboxSinks.set(path, sink);+ }+ return sink;+}diff --git a/packages/cli/src/behavior/observer/client.ts b/packages/cli/src/hooks/observer/client.tssimilarity index 86%rename from packages/cli/src/behavior/observer/client.tsrename to packages/cli/src/hooks/observer/client.tsindex 4b34d19b..01ff3126 100644--- a/packages/cli/src/behavior/observer/client.ts+++ b/packages/cli/src/hooks/observer/client.ts@@ -1,5 +1,5 @@/**- * The behavior observer: a small LOCAL model that flags harness divergences the+ * The hook observer: a small LOCAL model that flags harness divergences the* declarative rules do not yet encode.** Built on the services/vision-proxy.ts contract — hard timeout, `null` on any@@ -15,11 +15,14 @@import { log } from "../../logger.js";import { fetchOllamaModels, ollamaBaseUrl } from "../../providers/ollama-discovery.js";-import type { BehaviorConfig } from "../types.js";+import type { HooksConfig } from "../config.js";import type { ObserverDigest } from "./digest.js";const DEFAULT_TIMEOUT_MS = 1_500;+/** The slice of the config the observer reads (`hooks.observer`). */+export type ObserverConfig = Pick<HooksConfig, "observer">;+export interface ObserverVerdict {/** A rule id from the digest's vocabulary, or null for "nothing to report". */ruleId: string | null;@@ -56,7 +59,7 @@ function isGenuinelyLocal(model: { name: string; size?: number }): boolean {/** Resolved once per process — discovery costs an HTTP round trip. */let cachedModel: string | null | undefined;-async function resolveObserverModel(config: BehaviorConfig): Promise<string | null> {+async function resolveObserverModel(config: ObserverConfig): Promise<string | null> {if (config.observer?.model) return config.observer.model;if (cachedModel !== undefined) return cachedModel;@@ -64,7 +67,7 @@ async function resolveObserverModel(config: BehaviorConfig): Promise<string | nuconst models = await fetchOllamaModels({ enrichCapabilities: false });const usable = models.filter((m) => !m.isEmbeddingModel && isGenuinelyLocal(m));if (usable.length === 0) {- log("[behavior:observer] No local Ollama models found — observer disabled for this run");+ log("[hooks:observer] No local Ollama models found — observer disabled for this run");cachedModel = null;return null;}@@ -74,10 +77,10 @@ async function resolveObserverModel(config: BehaviorConfig): Promise<string | nu(a, b) => (a.size ?? Number.MAX_SAFE_INTEGER) - (b.size ?? Number.MAX_SAFE_INTEGER));cachedModel = usable[0].name;- log(`[behavior:observer] Using discovered local model: ${cachedModel}`);+ log(`[hooks:observer] Using discovered local model: ${cachedModel}`);return cachedModel;} catch (err) {- log(`[behavior:observer] Model discovery failed, observer disabled: ${err}`);+ log(`[hooks:observer] Model discovery failed, observer disabled: ${err}`);cachedModel = null;return null;}@@ -95,7 +98,7 @@ export function resetObserverModelCache(): void {*/export async function observe(digest: ObserverDigest,- config: BehaviorConfig+ config: ObserverConfig): Promise<ObserverVerdict | null> {const mode = config.observer?.mode ?? "suggest";if (config.observer?.enabled !== true || mode === "off") return null;@@ -122,7 +125,7 @@ export async function observe(}),});if (!response.ok) {- log(`[behavior:observer] HTTP ${response.status} — skipping`);+ log(`[hooks:observer] HTTP ${response.status} — skipping`);return null;}@@ -136,7 +139,7 @@ export async function observe(// An id outside the vocabulary is a hallucination. Drop it rather than let// an invented rule name reach the engine or the divergence log.if (ruleId && !digest.ruleVocabulary.includes(ruleId)) {- log(`[behavior:observer] Discarding unknown ruleId "${ruleId}"`);+ log(`[hooks:observer] Discarding unknown ruleId "${ruleId}"`);return null;}@@ -147,7 +150,7 @@ export async function observe(};} catch (err) {// Timeouts are the expected failure here, not an exceptional one.- log(`[behavior:observer] Skipped: ${err instanceof Error ? err.message : err}`);+ log(`[hooks:observer] Skipped: ${err instanceof Error ? err.message : err}`);return null;}}diff --git a/packages/cli/src/behavior/observer/corpus.test.ts b/packages/cli/src/hooks/observer/corpus.test.tssimilarity index 100%rename from packages/cli/src/behavior/observer/corpus.test.tsrename to packages/cli/src/hooks/observer/corpus.test.tsdiff --git a/packages/cli/src/behavior/observer/corpus.ts b/packages/cli/src/hooks/observer/corpus.tssimilarity index 100%rename from packages/cli/src/behavior/observer/corpus.tsrename to packages/cli/src/hooks/observer/corpus.tsdiff --git a/packages/cli/src/behavior/observer/digest.ts b/packages/cli/src/hooks/observer/digest.tssimilarity index 97%rename from packages/cli/src/behavior/observer/digest.tsrename to packages/cli/src/hooks/observer/digest.tsindex ecc93ae7..22cac135 100644--- a/packages/cli/src/behavior/observer/digest.ts+++ b/packages/cli/src/hooks/observer/digest.ts@@ -15,7 +15,7 @@* model). Everything else is reduced to key names.*/-import type { HarnessFacts } from "../types.js";+import type { HarnessFacts } from "../public.js";export interface ObserverDigest {model: string;diff --git a/packages/cli/src/behavior/observer/live-log.ts b/packages/cli/src/hooks/observer/live-log.tssimilarity index 95%rename from packages/cli/src/behavior/observer/live-log.tsrename to packages/cli/src/hooks/observer/live-log.tsindex f3e4964e..66159755 100644--- a/packages/cli/src/behavior/observer/live-log.ts+++ b/packages/cli/src/hooks/observer/live-log.ts@@ -42,6 +42,6 @@ export async function recordLiveDivergence(await appendFile(path, `${JSON.stringify(entry)}\n`);} catch (err) {// Directory missing, disk full, read-only home — all non-events here.- log(`[behavior:observer] could not append divergence: ${err}`);+ log(`[hooks:observer] could not append divergence: ${err}`);}}diff --git a/packages/cli/src/hooks/request-stage.ts b/packages/cli/src/hooks/request-stage.tsindex a59105bc..952054ae 100644--- a/packages/cli/src/hooks/request-stage.ts+++ b/packages/cli/src/hooks/request-stage.ts@@ -35,6 +35,7 @@ import {} from "./actions.js";import { type HookEngine, type JournalMeta, PENDING_NOTE_ID } from "./engine.js";import { detectHarnessFacts, extractAvailableSkills, extractSessionId } from "./harness.js";+import { type InjectionSink, sinkFromEnv } from "./injection/sinks.js";import type {ClaudeMessage,ClaudeTool,@@ -162,7 +163,9 @@ export class RequestHooks {constructor(readonly engine: HookEngine,/** Which session this process's proxy events belong to; `CLAUDISH_HOOK_SESSION` by default. */- readonly session: ProxySessionRef | null = proxySessionFromEnv()+ readonly session: ProxySessionRef | null = proxySessionFromEnv(),+ /** Where `responseEnd` injections, annotations and the inbox `stop`/`end` lines go. */+ readonly sink: InjectionSink = sinkFromEnv()) {}/**@@ -179,18 +182,46 @@ export class RequestHooks {type ScopeState = "open" | "committed" | "abandoned";+/** A `toolCall` hook armed for one request, with the tool names it sees. */+export interface ArmedToolHook {+ applicable: ApplicableHook;+ /** The names it listed; `"*"` matches every tool. */+ tools: ReadonlySet<string>;+}++/** True when an armed hook's tool list covers `name`. */+export function armedFor(hook: ArmedToolHook, name: string): boolean {+ return hook.tools.has("*") || hook.tools.has(name);+}++/** What `begin` decided about the response, before it starts. */+interface ResponsePlan {+ /** Fix-severity, non-observe `toolCall` hooks whose `armed` was true: they hold blocks. */+ interceptHooks: ArmedToolHook[];+ /** Observe-mode or warn-severity `toolCall` hooks whose `armed` was true: they run at the tap. */+ observeToolHooks: ArmedToolHook[];+ /** Fix-severity `responseRewrite` hooks whose `claims` was true: they buffer the response. */+ rewriteHooks: ApplicableHook[];+ /** Warn-severity `responseRewrite` hooks whose `claims` was true: evaluated at the tap. */+ observeRewriteHooks: ApplicableHook[];+ /** Applicable `responseEnd` hooks. */+ endHooks: ApplicableHook[];+}+/** One upstream attempt's hook state. */export class HookRequestScope {/** Tool names a fix-severity `toolCall` hook armed for this request. Consumed by the response seam. */readonly armedTools: ReadonlySet<string>;/** Ids of fix-severity `responseRewrite` hooks whose `claims` was true. Consumed by the response seam. */readonly rewriteClaimants: ReadonlyArray<string>;+ /** The response-side hooks this request armed (§5.3). */+ readonly response: Readonly<ResponsePlan>;private held: PlannedAction<RequestAction>[];private state: ScopeState = "open";private constructor(- private readonly engine: HookEngine,+ readonly engine: HookEngine,readonly route: RouteInfo,readonly harness: HarnessFacts,readonly sessionId: string | undefined,@@ -198,12 +229,31 @@ export class HookRequestScope {held: PlannedAction<RequestAction>[],private readonly removedTools: ReadonlySet<string>,private readonly pendingSeqs: ReadonlyArray<number>,- armedTools: ReadonlySet<string>,- rewriteClaimants: ReadonlyArray<string>+ /** The request as the response-side hooks see it (post stage A). */+ readonly facts: RequestFacts,+ readonly session: ProxySessionRef | null,+ response: ResponsePlan) {this.held = held;- this.armedTools = armedTools;- this.rewriteClaimants = rewriteClaimants;+ this.response = response;+ const armed = new Set<string>();+ for (const h of response.interceptHooks) for (const t of h.tools) armed.add(t);+ this.armedTools = armed;+ this.rewriteClaimants = response.rewriteHooks.map((a) => a.hook.id);+ }++ /** A proxy-event context for a response-side hook (the request facts are post stage A). */+ proxyContext<T extends object>(base: object, event: string, extra: T): object {+ return {+ ...base,+ event,+ host: { mode: this.engine.hostMode },+ route: this.route,+ request: this.facts,+ harness: this.harness,+ session: this.session,+ ...extra,+ };}/** Steps 1–7 of §5.1, in order. */@@ -272,24 +322,44 @@ export class HookRequestScope {if (stageA.results.length > 0) engine.recordResults("request", stageA.results, meta);// 6. Armed tools and rewrite claims, evaluated once, before any response.- const armedTools = new Set<string>();+ // The request facts the response-side hooks see are the post-stage-A+ // request: what the provider actually received.+ const postFacts: RequestFacts = {+ ...facts,+ systemText: systemTextOf(claudeRequest.system),+ messages: (claudeRequest.messages ?? []) as ReadonlyArray<ClaudeMessage>,+ tools: (claudeRequest.tools ?? []) as ReadonlyArray<ClaudeTool>,+ };+ const predicateContext = (applicable: ApplicableHook): RequestContext =>+ ({+ ...requestContext(predicateBase(applicable)),+ request: postFacts,+ }) as RequestContext;+ const plan: ResponsePlan = {+ interceptHooks: [],+ observeToolHooks: [],+ rewriteHooks: [],+ observeRewriteHooks: [],+ endHooks: engine.select("responseEnd", { route }),+ };for (const applicable of toolCallHooks) {- if (applicable.severity !== "fix") continue;const tc = applicable.hook.def.on?.toolCall;- if (!tc || tc.observe === true) continue;- const ctx = requestContext(predicateBase(applicable));+ if (!tc) continue;+ const ctx = predicateContext(applicable);if (!engine.callPredicate(applicable.hook.id, tc.armed, tc, ctx, true)) continue;- for (const tool of tc.tools) armedTools.add(tool);+ const armed: ArmedToolHook = { applicable, tools: new Set(tc.tools) };+ // A warn-severity or observe-mode hook never holds the stream: it sees the+ // call as delivered, at the tap.+ if (applicable.severity === "fix" && tc.observe !== true) plan.interceptHooks.push(armed);+ else plan.observeToolHooks.push(armed);}- const rewriteClaimants: string[] = [];for (const applicable of rewriteHooks) {- if (applicable.severity !== "fix") continue;const rr = applicable.hook.def.on?.responseRewrite;if (!rr) continue;- const ctx = requestContext(predicateBase(applicable));- if (engine.callPredicate(applicable.hook.id, rr.claims, rr, ctx, true)) {- rewriteClaimants.push(applicable.hook.id);- }+ const ctx = predicateContext(applicable);+ if (!engine.callPredicate(applicable.hook.id, rr.claims, rr, ctx, true)) continue;+ if (applicable.severity === "fix") plan.rewriteHooks.push(applicable);+ else plan.observeRewriteHooks.push(applicable);}const applied = stageA.results.filter((r) => r.decision === "matched").length;@@ -310,8 +380,9 @@ export class HookRequestScope {[...stageA.held],stageA.removedTools,notes.map((n) => n.seq),- armedTools,- rewriteClaimants+ postFacts,+ session,+ plan);}diff --git a/packages/cli/src/hooks/response-blocks.ts b/packages/cli/src/hooks/response-blocks.tsnew file mode 100644index 00000000..d0faecd6--- /dev/null+++ b/packages/cli/src/hooks/response-blocks.ts@@ -0,0 +1,210 @@+/**+ * Content blocks of one Claude-format response, as the response-side hooks see+ * them: assembled from parsed SSE events (the seam's `buffer` mode and its+ * observe tap) or read off a non-streaming message (the JSON branch).+ *+ * The view is normalized on purpose. Every route converges on Claude SSE before+ * the seam, so a hook reads one shape, whichever parser produced the bytes.+ */++import type { ResponseBlock, ResponseView } from "./public.js";++/** One block as the collector assembled it. */+export interface CollectedBlock {+ /** The block's index as it arrived. */+ index: number;+ /** `text`, `thinking`, `redacted_thinking`, `tool_use`, or anything else. */+ type: string;+ /** Text of a text block, or thinking of a thinking block. */+ text: string;+ /** A tool block's accumulated `input_json_delta` fragments. */+ args: string;+ /** A tool block's id and name. */+ id?: string;+ name?: string;+ /** A tool block's `input` from its start event (a JSON message carries it whole). */+ startInput?: unknown;+ /** A text block that carried a non-`text_delta` delta (e.g. `citations_delta`). */+ locked: boolean;+ complete: boolean;+}++const THINKING_TYPES = new Set(["thinking", "redacted_thinking"]);++export function isThinkingType(type: string | undefined): boolean {+ return THINKING_TYPES.has(type ?? "");+}++// biome-ignore lint/suspicious/noExplicitAny: parsed SSE payloads are untyped+type Json = any;++/** Assembles blocks from Claude SSE events, in arrival order. */+export class BlockCollector {+ readonly blocks: CollectedBlock[] = [];+ private readonly open = new Map<number, CollectedBlock>();+ stopReason: string | null = null;+ sawMessageStop = false;++ /**+ * Feed one parsed event. Returns the block it completed, if it was a+ * `content_block_stop`.+ */+ onEvent(data: Json): CollectedBlock | undefined {+ switch (data?.type) {+ case "content_block_start": {+ const cb = data.content_block ?? {};+ const block: CollectedBlock = {+ index: data.index,+ type: typeof cb.type === "string" ? cb.type : "unknown",+ text:+ typeof cb.text === "string"+ ? cb.text+ : typeof cb.thinking === "string"+ ? cb.thinking+ : "",+ args: "",+ locked: false,+ complete: false,+ };+ if (block.type === "tool_use") {+ block.id = typeof cb.id === "string" ? cb.id : undefined;+ block.name = typeof cb.name === "string" ? cb.name : undefined;+ block.startInput = cb.input;+ }+ this.blocks.push(block);+ this.open.set(data.index, block);+ return undefined;+ }+ case "content_block_delta": {+ const block = this.open.get(data.index);+ const delta = data.delta ?? {};+ if (!block) return undefined;+ if (delta.type === "text_delta" && typeof delta.text === "string") block.text += delta.text;+ else if (delta.type === "thinking_delta" && typeof delta.thinking === "string") {+ block.text += delta.thinking;+ } else if (delta.type === "input_json_delta" && typeof delta.partial_json === "string") {+ block.args += delta.partial_json;+ } else if (block.type === "text") {+ block.locked = true;+ }+ return undefined;+ }+ case "content_block_stop": {+ const block = this.open.get(data.index);+ if (!block) return undefined;+ this.open.delete(data.index);+ block.complete = true;+ return block;+ }+ case "message_delta":+ if (typeof data.delta?.stop_reason === "string") this.stopReason = data.delta.stop_reason;+ return undefined;+ case "message_stop":+ this.sawMessageStop = true;+ return undefined;+ default:+ return undefined;+ }+ }+}++/** A tool block's arguments: the parsed object, or null when they are malformed. */+export function parseToolArgs(raw: string): Record<string, unknown> | null {+ if (raw.trim() === "") return {};+ try {+ const parsed = JSON.parse(raw);+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)+ ? (parsed as Record<string, unknown>)+ : null;+ } catch {+ return null;+ }+}++/** The input a view reports for a collected tool block. */+function toolInput(block: CollectedBlock, override?: Record<string, unknown>): unknown {+ if (override) return override;+ if (block.args === "" && block.startInput !== undefined) return block.startInput;+ return parseToolArgs(block.args) ?? block.args;+}++/** One collected block as a hook sees it. */+export function viewBlock(+ block: CollectedBlock,+ override?: Record<string, unknown>+): ResponseBlock {+ switch (block.type) {+ case "text":+ return { type: "text", text: block.text };+ case "thinking":+ return { type: "thinking", thinking: block.text };+ case "tool_use":+ return {+ type: "tool_use",+ id: block.id ?? "",+ name: block.name ?? "",+ input: toolInput(block, override),+ };+ default:+ return { type: "other", blockType: block.type };+ }+}++/** Assemble a view from normalized blocks. */+export function responseView(+ blocks: ReadonlyArray<ResponseBlock>,+ stopReason: string | null+): ResponseView {+ const text: string[] = [];+ const reasoning: string[] = [];+ const toolNames: string[] = [];+ for (const b of blocks) {+ if (b.type === "text") text.push(b.text);+ else if (b.type === "thinking") reasoning.push(b.thinking);+ else if (b.type === "tool_use") toolNames.push(b.name);+ }+ return {+ blocks,+ text: text.join("\n\n"),+ reasoning: reasoning.join("\n\n"),+ toolNames,+ stopReason,+ };+}++/** A view over every block a collector saw. */+export function collectorView(+ collector: BlockCollector,+ overrides?: ReadonlyMap<number, Record<string, unknown>>+): ResponseView {+ return responseView(+ collector.blocks.map((b) => viewBlock(b, overrides?.get(b.index))),+ collector.stopReason+ );+}++/** A view over a non-streaming message's `content[]`. */+export function messageView(message: Json): ResponseView {+ const content: Json[] = Array.isArray(message?.content) ? message.content : [];+ const blocks: ResponseBlock[] = content.map((b: Json): ResponseBlock => {+ switch (b?.type) {+ case "text":+ return { type: "text", text: typeof b.text === "string" ? b.text : "" };+ case "thinking":+ return { type: "thinking", thinking: typeof b.thinking === "string" ? b.thinking : "" };+ case "tool_use":+ return {+ type: "tool_use",+ id: String(b.id ?? ""),+ name: String(b.name ?? ""),+ input: b.input,+ };+ default:+ return { type: "other", blockType: typeof b?.type === "string" ? b.type : "unknown" };+ }+ });+ return responseView(+ blocks,+ typeof message?.stop_reason === "string" ? message.stop_reason : null+ );+}diff --git a/packages/cli/src/hooks/response-seam.ts b/packages/cli/src/hooks/response-seam.tsindex cca6b3f2..201a5a93 100644--- a/packages/cli/src/hooks/response-seam.ts+++ b/packages/cli/src/hooks/response-seam.ts@@ -14,21 +14,36 @@* handler returns: no scope or a non-2xx response → `abandon()` and the response* unchanged; otherwise `commit()` and `applyResponseSeam`.*- * This revision implements closed mode `none` only: the seam returns the inner- * `Response` object itself. The `intercept` and `buffer` modes, the raw- * `response` stage and the observe tap come with the response half.+ * Every route's output converges here as Claude SSE (or the JSON message a+ * `stream:false` request gets), so one seam covers every parser. Three stages,+ * in a fixed order, each present only when an applicable hook needs it:+ *+ * 1. the closed transform (`intercept` or `buffer`, seam-transform.ts);+ * 2. the raw `response` hooks (the unsafe tier; none until it is built);+ * 3. the observe tap (seam-tap.ts), which writes the inbox `stop` before the+ * `message_stop` chunk is enqueued and runs every observe-type consumer —+ * `responseEnd` included — on exactly the bytes the client received.+ *+ * When no stage is needed the seam returns the SAME `Response` object, so a+ * request no hook claimed streams exactly as it did before hooks existed.*/import type { Context } from "hono";import type { ModelHandler } from "../handlers/types.js";import { log } from "../logger.js";import type { HookEngine } from "./engine.js";+import { type InjectionSink, UnavailableSink } from "./injection/sinks.js";import {type HookRequestScope,RequestHooks,attachRequestHooks,hookScopeOf,} from "./request-stage.js";+import { messageView } from "./response-blocks.js";+import { SeamHooks } from "./seam-hooks.js";+import { EndLine, newRequestId, observeTap } from "./seam-tap.js";+import { type ClosedMode, closedTransform } from "./seam-transform.js";+import { type RewriteBlock, applyTextActions } from "./text-rewrite.js";/** The decorator `withHooks` returns. Exported for `instanceof` checks. */export class HooksHandler implements ModelHandler {@@ -54,7 +69,7 @@ export class HooksHandler implements ModelHandler {return response;}scope.commit();- return applyResponseSeam(response, scope);+ return applyResponseSeam(response, scope, { sink: this.hooks.sink });}/** Forwarded: `AdvisorSwapHandler.shutdown()` calls it on whatever it wraps. */@@ -69,12 +84,204 @@ export function withHooks(inner: ModelHandler, engine: HookEngine): ModelHandlerreturn new HooksHandler(inner, new RequestHooks(engine));}+export interface SeamOptions {+ /** Where `responseEnd` injections and the inbox lines go. Default: none available. */+ sink?: InjectionSink;+ /** The id this response's inbox lines carry. Default: a fresh UUID. */+ req?: string;+ /** Test seams for the closed transform's keepalive and hold cap. */+ pingIntervalMs?: number;+ holdCapBytes?: number;+}++/** The seam's stages for one request, decided before the response starts. */+export interface SeamPlan {+ mode: "none" | ClosedMode;+ tap: boolean;+}++/** The strictest closed mode an armed hook needs, and whether the tap is needed. */+export function planSeam(scope: HookRequestScope): SeamPlan {+ const p = scope.response;+ const mode =+ p.rewriteHooks.length > 0 ? "buffer" : p.interceptHooks.length > 0 ? "intercept" : "none";+ const tap =+ p.endHooks.length > 0 || p.observeToolHooks.length > 0 || p.observeRewriteHooks.length > 0;+ return { mode, tap };+}++/**+ * Assemble the response stages for an accepted (2xx) response. With no stage+ * needed it returns the SAME object. Fails open: a seam that cannot be built+ * returns the response as the handler produced it.+ */+export async function applyResponseSeam(+ response: Response,+ scope: HookRequestScope,+ opts: SeamOptions = {}+): Promise<Response> {+ const plan = planSeam(scope);+ log(`[hooks] seam mode=${plan.mode} raw=0 tap=${plan.tap ? 1 : 0}`);+ if ((plan.mode === "none" && !plan.tap) || !response.body) return response;++ const hooks = new SeamHooks(scope, opts.sink ?? new UnavailableSink());+ const req = opts.req ?? newRequestId();+ if (isJson(response)) return jsonBranch(response, hooks, plan, req);++ try {+ let body: ReadableStream<Uint8Array> = response.body;+ if (plan.mode !== "none") {+ body = closedTransform(body, {+ mode: plan.mode,+ hooks,+ pingIntervalMs: opts.pingIntervalMs,+ holdCapBytes: opts.holdCapBytes,+ });+ }+ if (plan.tap) body = observeTap(body, hooks, req);+ return new Response(body, {+ status: response.status,+ statusText: response.statusText,+ headers: withoutLength(response.headers),+ });+ } catch (err) {+ log(`[hooks] seam not applied: ${err instanceof Error ? err.message : err}`);+ return response;+ }+}++function isJson(response: Response): boolean {+ const type = response.headers.get("content-type") ?? "";+ return type.includes("application/json");+}++function withoutLength(headers: Headers): Headers {+ const out = new Headers(headers);+ out.delete("content-length");+ return out;+}++// biome-ignore lint/suspicious/noExplicitAny: a Messages API message is untyped at this layer+type Json = any;++/** A text block carrying citations is never rewritten (it is re-emitted as is). */+function isCitedText(block: Json): boolean {+ return Array.isArray(block?.citations) && block.citations.length > 0;+}+/**- * Assemble the response stages for an accepted response. With no stage needed- * — the only case this revision builds — it returns the SAME object, so- * streaming takes exactly today's path.+ * The non-streaming branch (§5.4): the message is parsed once, `toolCall`+ * hooks repair `tool_use.input`, `responseRewrite` applies the same text+ * actions over `content[]` (the whole array being the held region), and the body+ * is re-serialised with the original status and headers. The inbox `stop` is+ * written before the Response is returned; `responseEnd` runs after.*/-export function applyResponseSeam(response: Response, _scope: HookRequestScope): Response {- log("[hooks] seam mode=none raw=0 tap=0");- return response;+async function jsonBranch(+ response: Response,+ hooks: SeamHooks,+ plan: SeamPlan,+ req: string+): Promise<Response> {+ const text = await response.text();+ const rebuild = (body: string) =>+ new Response(body, {+ status: response.status,+ statusText: response.statusText,+ headers: withoutLength(response.headers),+ });++ let message: Json;+ try {+ message = JSON.parse(text);+ } catch {+ return rebuild(text);+ }+ if (!message || !Array.isArray(message.content)) return rebuild(text);++ try {+ let content: Json[] = message.content;+ if (plan.mode !== "none") {+ const repaired: Json[] = [];+ for (const block of content) {+ if (+ block?.type === "tool_use" &&+ typeof block.name === "string" &&+ hooks.intercepts(block.name)+ ) {+ const args = await hooks.interceptToolCall({+ id: String(block.id ?? ""),+ name: block.name,+ rawArgs: JSON.stringify(block.input ?? {}),+ });+ repaired.push(args ? { ...block, input: args } : block);+ } else {+ repaired.push(block);+ }+ }+ content = repaired;+ }+ if (plan.mode === "buffer") {+ const planned = await hooks.rewrite(messageView({ ...message, content }));+ const blocks: RewriteBlock[] = content.map((b) => ({+ type: typeof b?.type === "string" ? b.type : "unknown",+ ...(b?.type === "text" && typeof b.text === "string" ? { text: b.text } : {}),+ ...(isCitedText(b) ? { locked: true } : {}),+ }));+ if (planned.length > 0 && blocks.some((b) => b.locked)) hooks.noteRewriteInvalid("citations");+ const result = applyTextActions(+ blocks,+ planned.map((p) => p.action)+ );+ hooks.recordRewrite(planned, result);+ const original = content;+ content = result.blocks.map((out) => {+ const text = (out.block as { text?: string }).text ?? "";+ if (out.source === null) return { type: "text", text };+ return out.changed ? { ...original[out.source], text } : original[out.source];+ });+ }+ message = { ...message, content };+ } catch (err) {+ log(`[hooks] seam JSON branch failed open: ${err instanceof Error ? err.message : err}`);+ return rebuild(text);+ }++ const out = rebuild(JSON.stringify(message));+ if (!plan.tap) return out;++ const end = new EndLine(hooks, req);+ if (hooks.hasEndHooks) {+ try {+ hooks.sink.stop(req);+ } catch (err) {+ log(`[hooks] inbox stop failed: ${err instanceof Error ? err.message : err}`);+ }+ }+ const view = messageView(message);+ for (const block of message.content as Json[]) {+ if (+ block?.type === "tool_use" &&+ typeof block.name === "string" &&+ hooks.observes(block.name)+ ) {+ void hooks+ .observeToolCall({+ id: String(block.id ?? ""),+ name: block.name,+ rawArgs: JSON.stringify(block.input ?? {}),+ })+ .catch(() => {});+ }+ }+ void (async () => {+ try {+ await hooks.observeRewrite(view);+ await hooks.end(view, req);+ } catch (err) {+ log(`[hooks] tap consumers failed: ${err instanceof Error ? err.message : err}`);+ } finally {+ end.write(false);+ }+ })();+ return out;}diff --git a/packages/cli/src/hooks/seam-hooks.ts b/packages/cli/src/hooks/seam-hooks.tsnew file mode 100644index 00000000..978a36af--- /dev/null+++ b/packages/cli/src/hooks/seam-hooks.ts@@ -0,0 +1,270 @@+/**+ * The response-side hook calls of one request, shared by the seam's three+ * places that run them: the closed transform (`toolCall` on held blocks,+ * `responseRewrite` at `message_delta`), the observe tap (observe-mode+ * `toolCall`, warn-mode `responseRewrite`, `responseEnd`), and the+ * non-streaming JSON branch.+ *+ * Every call fails open: the engine journals a throw, a rejection, a timeout or+ * an invalid return and treats it as "no actions", so a broken hook leaves the+ * response exactly as the model produced it.+ */++import { log } from "../logger.js";+import { type PlannedAction, applyToolCallActions } from "./actions.js";+import type { JournalMeta } from "./engine.js";+import type { InjectionSink } from "./injection/sinks.js";+import type { ResponseView, RewriteAction } from "./public.js";+import { type ArmedToolHook, type HookRequestScope, armedFor } from "./request-stage.js";+import { parseToolArgs } from "./response-blocks.js";+import type { RewriteBlock, TextAction, TextRewriteResult } from "./text-rewrite.js";++/** A completed tool call, as the seam assembled it. */+export interface SeamToolCall {+ id: string;+ name: string;+ /** The argument JSON exactly as the model produced it. */+ rawArgs: string;+}++/** Fix-severity rewrite actions, attributed, in effective order. */+export type PlannedTextAction = PlannedAction<TextAction>;++export class SeamHooks {+ constructor(+ readonly scope: HookRequestScope,+ readonly sink: InjectionSink+ ) {}++ private get engine() {+ return this.scope.engine;+ }++ private get plan() {+ return this.scope.response;+ }++ /** True when a fix-severity `toolCall` hook holds blocks of this tool. */+ intercepts(name: string): boolean {+ return this.plan.interceptHooks.some((h) => armedFor(h, name));+ }++ /** True when an observe-mode or warn-severity `toolCall` hook watches this tool. */+ observes(name: string): boolean {+ return this.plan.observeToolHooks.some((h) => armedFor(h, name));+ }++ /**+ * Run the fix-severity `toolCall` hooks for one held call. Returns the+ * replacement arguments, or undefined to forward the model's own.+ */+ async interceptToolCall(+ call: SeamToolCall,+ signal?: AbortSignal+ ): Promise<Record<string, unknown> | undefined> {+ return this.runToolCall(call, this.plan.interceptHooks, true, signal);+ }++ /** Run the observe-mode and warn-severity `toolCall` hooks for one delivered call. */+ async observeToolCall(call: SeamToolCall, signal?: AbortSignal): Promise<void> {+ await this.runToolCall(call, this.plan.observeToolHooks, false, signal);+ }++ private async runToolCall(+ call: SeamToolCall,+ armed: ReadonlyArray<ArmedToolHook>,+ apply: boolean,+ signal?: AbortSignal+ ): Promise<Record<string, unknown> | undefined> {+ const hooks = armed.filter((h) => armedFor(h, call.name)).map((h) => h.applicable);+ if (hooks.length === 0) return undefined;+ const args = parseToolArgs(call.rawArgs);+ if (!args) {+ // Malformed arguments are the recovery layer's concern; no hook sees them.+ log(`[hooks] toolCall ${call.name}: arguments are not a JSON object, hooks not called`);+ return undefined;+ }++ const meta: JournalMeta = { ...this.scope.meta, toolName: call.name };+ const run = await this.engine.run(+ "toolCall",+ hooks,+ (_applicable, base) =>+ this.scope.proxyContext(base, "toolCall", {+ tool: {+ id: call.id,+ name: call.name,+ args: structuredClone(args),+ rawArgs: call.rawArgs,+ },+ }),+ meta,+ signal ? { signal } : {}+ );+ if (!apply) return undefined;++ // The path facts keep the telemetry's categorical `pathRelation`: the+ // plan-mode measurement keys off where a write landed against where the+ // harness expected it.+ const pathFacts = {+ argKeys: Object.keys(args),+ observedPath: typeof args.file_path === "string" ? args.file_path : undefined,+ expectedPath: this.scope.harness.planFilePath,+ };+ const applied = applyToolCallActions(run.apply);+ this.engine.recordResults("toolCall", applied.results, meta, (r) => ({+ ...pathFacts,+ note: r.action.type === "repairToolArgs" ? r.action.reason : undefined,+ }));+ // A call a hook saw and left alone is a decision too: a hook that never+ // fires looks identical to a hook that is not needed without the negatives.+ if (applied.args === undefined) {+ for (const r of run.runs) {+ if (r.status !== "ok") continue;+ this.engine.journal({+ ...meta,+ ...pathFacts,+ event: "toolCall",+ hookId: r.applicable.hook.id,+ decision: "ignored",+ });+ }+ } else {+ log(`[hooks] toolCall ${call.name}: arguments repaired`);+ }+ return applied.args;+ }++ /** Run the fix-severity `responseRewrite` hooks; returns their text actions. */+ async rewrite(view: ResponseView, signal?: AbortSignal): Promise<PlannedTextAction[]> {+ const hooks = this.plan.rewriteHooks;+ if (hooks.length === 0) return [];+ const run = await this.engine.run(+ "responseRewrite",+ hooks,+ (_applicable, base) => this.scope.proxyContext(base, "responseRewrite", { response: view }),+ this.scope.meta,+ signal ? { signal } : {}+ );+ return run.apply.filter(+ (p): p is PlannedTextAction => (p.action as RewriteAction).type !== "warn"+ );+ }++ /** Journal what `applyTextActions` did with each planned action. */+ recordRewrite(+ planned: ReadonlyArray<PlannedTextAction>,+ result: Pick<TextRewriteResult<RewriteBlock>, "applied" | "rejected">+ ): void {+ const results = [+ ...result.applied.map((a) => ({+ ...(planned[a.index] as PlannedTextAction),+ decision: a.changed ? ("matched" as const) : ("ignored" as const),+ ...(a.changed ? {} : { detail: "no_match" }),+ })),+ ...result.rejected.map((r) => ({+ ...(planned[r.index] as PlannedTextAction),+ decision: "invalid" as const,+ detail: r.reason,+ })),+ ];+ this.engine.recordResults("responseRewrite", results, this.scope.meta);+ }++ /** Journal one rewrite-hook outcome that did not come from an action (cap, citations). */+ noteRewriteInvalid(detail: string): void {+ for (const a of this.plan.rewriteHooks) {+ this.engine.journal({+ ...this.scope.meta,+ event: "responseRewrite",+ hookId: a.hook.id,+ decision: "invalid",+ detail,+ });+ }+ }++ /** Journal one intercept outcome that did not come from an action (the hold cap). */+ noteInterceptInvalid(detail: string): void {+ for (const a of this.plan.interceptHooks) {+ this.engine.journal({+ ...this.scope.meta,+ event: "toolCall",+ hookId: a.applicable.hook.id,+ decision: "invalid",+ detail,+ });+ }+ }++ /** Warn-severity `responseRewrite` hooks, evaluated against the delivered response. */+ async observeRewrite(view: ResponseView): Promise<void> {+ const hooks = this.plan.observeRewriteHooks;+ if (hooks.length === 0) return;+ await this.engine.run(+ "responseRewrite",+ hooks,+ (_applicable, base) => this.scope.proxyContext(base, "responseRewrite", { response: view }),+ this.scope.meta+ );+ }++ /** True when a `responseEnd` hook applies (and so the inbox gets `stop` and `end`). */+ get hasEndHooks(): boolean {+ return this.plan.endHooks.length > 0;+ }++ /**+ * Run `responseEnd` over the final response and route its actions:+ * `injectSystemNote` to this Claude session's next request, `injectUserTurn`+ * and `annotateTurn` to the sink. Never rejects.+ */+ async end(view: ResponseView, req: string): Promise<void> {+ const hooks = this.plan.endHooks;+ if (hooks.length === 0) return;+ const meta = this.scope.meta;+ try {+ const run = await this.engine.run(+ "responseEnd",+ hooks,+ (_applicable, base) => this.scope.proxyContext(base, "responseEnd", { response: view }),+ meta+ );+ for (const { hookId, action } of run.apply) {+ const base = { ...meta, event: "responseEnd" as const, hookId, action: action.type };+ switch (action.type) {+ case "injectSystemNote":+ if (this.scope.sessionId) {+ this.engine.queueNote(this.scope.sessionId, hookId, action.text);+ this.engine.journal({ ...base, decision: "queued", detail: "next request" });+ } else {+ this.engine.journal({ ...base, decision: "dropped", detail: "no_session" });+ }+ break;+ case "injectUserTurn": {+ const outcome = this.sink.inject(req, hookId, action.text);+ this.engine.journal({+ ...base,+ decision: outcome === "queued" ? "queued" : "dropped",+ ...(outcome === "queued" ? {} : { detail: outcome }),+ });+ break;+ }+ case "annotateTurn": {+ const outcome = this.sink.annotate(req, hookId, action.key, action.value);+ this.engine.journal({+ ...base,+ decision: outcome === "queued" ? "queued" : "dropped",+ ...(outcome === "queued" ? {} : { detail: outcome }),+ });+ break;+ }+ default:+ break;+ }+ }+ } catch (err) {+ log(`[hooks] responseEnd failed: ${err instanceof Error ? err.message : err}`);+ }+ }+}diff --git a/packages/cli/src/hooks/seam-tap.ts b/packages/cli/src/hooks/seam-tap.tsnew file mode 100644index 00000000..aaf31892--- /dev/null+++ b/packages/cli/src/hooks/seam-tap.ts@@ -0,0 +1,153 @@+/**+ * Stage 3 of the response seam: the observe tap (§5.3).+ *+ * A synchronous pass-through. Each chunk is parsed incrementally and enqueued+ * unchanged — same bytes, same chunking, nothing awaited between reading a+ * chunk and handing it on. It is pull-driven, so it reads upstream no faster+ * than the client reads it.+ *+ * Two things happen at the chunk that carries `message_stop`:+ *+ * 1. BEFORE it is enqueued, the inbox `stop` line is appended synchronously+ * (when a `responseEnd` hook applies). Claude Code writes a turn's+ * `turn_duration` only after it read the final response's `message_stop`, so+ * the line is on disk first by construction, whatever the earlier stages did.+ * 2. AFTER it is enqueued, the consumers run on what was parsed, off the client+ * path: warn-mode `responseRewrite`, then `responseEnd`, whose `end` line is+ * written in a `finally`.+ *+ * Observe-mode and warn-severity `toolCall` hooks run as each tool block+ * completes. Because the tap is the last stage, every consumer sees exactly+ * what the client received. A throw in the tap's parser stops parsing and the+ * bytes keep flowing (fail open); a client cancel or an upstream error writes+ * `end` with `aborted: true` at once.+ */++import { randomUUID } from "node:crypto";+import { log } from "../logger.js";+import { BlockCollector, collectorView } from "./response-blocks.js";+import type { SeamHooks } from "./seam-hooks.js";+import { SseSplitter, eventJson } from "./sse-codec.js";++/** A fresh id for one response's inbox lines. */+export function newRequestId(): string {+ return randomUUID();+}++/**+ * Writes one response's `end` line exactly once. `stop` is written by the+ * tap or the JSON branch; `end` by whichever finishes first: the `responseEnd`+ * dispatch, or an abort.+ */+export class EndLine {+ private written = false;++ constructor(+ private readonly hooks: SeamHooks,+ readonly req: string+ ) {}++ write(aborted: boolean): void {+ if (this.written || !this.hooks.hasEndHooks) return;+ this.written = true;+ try {+ this.hooks.sink.end(this.req, aborted);+ } catch (err) {+ log(`[hooks] inbox end failed: ${err instanceof Error ? err.message : err}`);+ }+ }+}++export function observeTap(+ source: ReadableStream<Uint8Array>,+ hooks: SeamHooks,+ req: string = newRequestId()+): ReadableStream<Uint8Array> {+ const reader = source.getReader();+ const splitter = new SseSplitter();+ const collector = new BlockCollector();+ const end = new EndLine(hooks, req);+ let parsing = true;+ let stopped = false;++ const observeTool = (name: string, id: string, rawArgs: string) => {+ if (!hooks.observes(name)) return;+ void hooks.observeToolCall({ id, name, rawArgs }).catch(() => {});+ };++ const onMessageStop = () => {+ const view = collectorView(collector);+ void (async () => {+ try {+ await hooks.observeRewrite(view);+ await hooks.end(view, req);+ } catch (err) {+ log(`[hooks] tap consumers failed: ${err instanceof Error ? err.message : err}`);+ } finally {+ end.write(false);+ }+ })();+ };++ return new ReadableStream<Uint8Array>(+ {+ async pull(controller) {+ let result: Awaited<ReturnType<typeof reader.read>>;+ try {+ result = await reader.read();+ } catch (err) {+ end.write(true);+ controller.error(err);+ return;+ }+ if (result.done) {+ controller.close();+ // A response that ended before `message_stop` writes only its `end`.+ if (!stopped) end.write(true);+ return;+ }++ const chunk = result.value;+ let carriesStop = false;+ const completed: Array<{ name: string; id: string; args: string }> = [];+ if (parsing) {+ try {+ for (const ev of splitter.push(chunk)) {+ const json = eventJson(ev) as { type?: string } | undefined;+ if (!json) continue;+ const block = collector.onEvent(json);+ if (block?.type === "tool_use" && block.name) {+ completed.push({ name: block.name, id: block.id ?? "", args: block.args });+ }+ if (json.type === "message_stop" && !stopped) carriesStop = true;+ }+ } catch (err) {+ parsing = false;+ log(+ `[hooks] tap parser failed, observing stopped: ${err instanceof Error ? err.message : err}`+ );+ }+ }++ if (carriesStop) {+ stopped = true;+ if (hooks.hasEndHooks) {+ try {+ hooks.sink.stop(req);+ } catch (err) {+ log(`[hooks] inbox stop failed: ${err instanceof Error ? err.message : err}`);+ }+ }+ }+ controller.enqueue(chunk);+ for (const c of completed) observeTool(c.name, c.id, c.args);+ if (carriesStop) onMessageStop();+ },+ cancel(reason) {+ end.write(true);+ return reader.cancel(reason).catch(() => {});+ },+ },+ { highWaterMark: 0 }+ );+}diff --git a/packages/cli/src/hooks/seam-transform.ts b/packages/cli/src/hooks/seam-transform.tsnew file mode 100644index 00000000..4fb13d56--- /dev/null+++ b/packages/cli/src/hooks/seam-transform.ts@@ -0,0 +1,590 @@+/**+ * Stage 1 of the response seam: the closed transform (§5.3).+ *+ * - `intercept`: complete events are forwarded as soon as their terminator+ * arrives, re-encoded from the decoded text (byte-identical for valid UTF-8).+ * Only a `tool_use` block of an armed tool is held: its `content_block_start`+ * goes out at once, its `input_json_delta` events are swallowed, and at its+ * `content_block_stop` the `toolCall` hooks run and the block is finished with+ * ONE `input_json_delta` carrying the repaired (or original) arguments, then+ * the stop. No block is inserted or dropped, so no index changes.+ * - `buffer`: `message_start` and leading thinking blocks stream live. From the+ * first `content_block_start` of any other type, every event except `ping` is+ * held, in order, until `message_delta`. Then the `toolCall` hooks' repairs+ * (started at each held tool block's stop) are collected, the+ * `responseRewrite` hooks run over the whole response, their text actions are+ * applied to the held blocks, and the held region is re-emitted. Once a block+ * is inserted or dropped, every later block event is re-serialised with its+ * new index, so emitted indices are always 0, 1, 2, … with no gap or repeat.+ *+ * Safety (§5.4): pings are forwarded immediately in every state, and while the+ * transform holds content with no upstream ping to forward it emits its own+ * once a second. Past 8 MiB held it flushes everything unchanged and stops+ * holding. An upstream `event: error` flushes the held events unchanged, then+ * the error. A throw inside the transform flushes what it holds and passes the+ * rest through. A client cancel cancels the upstream and aborts running hooks.+ */++import { log } from "../logger.js";+import {+ BlockCollector,+ type CollectedBlock,+ collectorView,+ isThinkingType,+} from "./response-blocks.js";+import type { SeamHooks } from "./seam-hooks.js";+import {+ type SseEvent,+ SseSplitter,+ chunkText,+ encodeUtf8,+ eventJson,+ serializeSseEvent,+} from "./sse-codec.js";+import { type RewriteBlock, applyTextActions } from "./text-rewrite.js";++export type ClosedMode = "intercept" | "buffer";++/** The exact keepalive frame every parser emits. */+export const PING_FRAME = 'event: ping\ndata: {"type":"ping"}\n\n';++/** Held content past which the seam stops holding (§5.4). */+export const HOLD_CAP_BYTES = 8 * 1024 * 1024;++export interface ClosedTransformOptions {+ mode: ClosedMode;+ hooks: SeamHooks;+ /** Interval of the seam's own pings while it holds content. Default 1,000 ms. */+ pingIntervalMs?: number;+ /** Held bytes past which it flushes and stops holding. Default 8 MiB. */+ holdCapBytes?: number;+}++// biome-ignore lint/suspicious/noExplicitAny: parsed SSE payloads are untyped+type Json = any;++type QueueItem =+ | { kind: "event"; ev: SseEvent }+ | { kind: "end" }+ | { kind: "error"; err: unknown };++/** One armed tool block held in `intercept` mode. */+interface HeldTool {+ index: number;+ id: string;+ name: string;+ args: string;+ /** Its `input_json_delta` events, swallowed. */+ deltas: SseEvent[];+ /** Any other event that arrived while it was held. */+ extras: SseEvent[];+}++/** One block of the `buffer` mode's held region. */+interface HeldBlock {+ index: number;+ events: SseEvent[];+ collected: CollectedBlock;+}++function isPing(ev: SseEvent, json: Json): boolean {+ return ev.event === "ping" || json?.type === "ping";+}++function isError(ev: SseEvent, json: Json): boolean {+ return ev.event === "error" || json?.type === "error";+}++/** Re-serialise a block event with a new index; anything unparseable stays raw. */+function reindexed(ev: SseEvent, index: number): string {+ const json = eventJson(ev);+ if (!json || typeof (json as Json).index !== "number") return ev.raw;+ return serializeSseEvent(ev.event, { ...(json as object), index });+}++function inputDelta(index: number, partialJson: string): string {+ return serializeSseEvent("content_block_delta", {+ type: "content_block_delta",+ index,+ delta: { type: "input_json_delta", partial_json: partialJson },+ });+}++/** A rewritten or inserted text block: start (empty), bounded text deltas, stop. */+function textBlock(index: number, text: string): string[] {+ const out = [+ serializeSseEvent("content_block_start", {+ type: "content_block_start",+ index,+ content_block: { type: "text", text: "" },+ }),+ ];+ for (const piece of chunkText(text)) {+ out.push(+ serializeSseEvent("content_block_delta", {+ type: "content_block_delta",+ index,+ delta: { type: "text_delta", text: piece },+ })+ );+ }+ out.push(serializeSseEvent("content_block_stop", { type: "content_block_stop", index }));+ return out;+}++/**+ * A held block re-emitted at `index`: its original bytes when the index is+ * unchanged, every event re-serialised with the new index otherwise. A+ * repaired tool block loses its fragments and gets one delta before its stop.+ */+function heldBlock(+ held: HeldBlock,+ index: number,+ repaired: Record<string, unknown> | undefined+): string[] {+ const same = index === held.index;+ const raw = (ev: SseEvent) => (same ? ev.raw : reindexed(ev, index));+ if (!repaired) return held.events.map(raw);+ const out: string[] = [];+ let deltaSent = false;+ for (const ev of held.events) {+ const json = eventJson(ev) as Json;+ if (json?.type === "content_block_delta" && json.delta?.type === "input_json_delta") continue;+ if (json?.type === "content_block_stop" && !deltaSent) {+ out.push(inputDelta(index, JSON.stringify(repaired)));+ deltaSent = true;+ }+ out.push(raw(ev));+ }+ return out;+}++export function closedTransform(+ source: ReadableStream<Uint8Array>,+ opts: ClosedTransformOptions+): ReadableStream<Uint8Array> {+ return new ClosedTransform(source, opts).readable;+}++class ClosedTransform {+ readonly readable: ReadableStream<Uint8Array>;++ private controller!: ReadableStreamDefaultController<Uint8Array>;+ private readonly reader: ReadableStreamDefaultReader<Uint8Array>;+ private readonly splitter = new SseSplitter();+ private readonly abort = new AbortController();+ private readonly pingIntervalMs: number;+ private readonly holdCap: number;+ private readonly queue: QueueItem[] = [];+ private timer: ReturnType<typeof setInterval> | null = null;+ private busy = false;+ private done = false;+ private lastPingAt = Date.now();+ /** Once true, every event is forwarded unchanged (cap, error, fail-open). */+ private passthrough = false;+ /**+ * An upstream read error, raised once the client has read what was flushed+ * before it: `controller.error()` discards chunks still queued.+ */+ private pendingError: { err: unknown } | null = null;++ // intercept+ private heldTool: HeldTool | null = null;++ // buffer+ private phase: "live" | "holding" | "after" = "live";+ private readonly collector = new BlockCollector();+ private liveBlocks = 0;+ private heldRaw: SseEvent[] = [];+ private heldBlocks: HeldBlock[] = [];+ private readonly heldByIndex = new Map<number, HeldBlock>();+ private loose: Array<{ ev: SseEvent; ordinal: number }> = [];+ private readonly toolRuns = new Map<number, Promise<Record<string, unknown> | undefined>>();+ private heldBytes = 0;++ constructor(+ source: ReadableStream<Uint8Array>,+ private readonly opts: ClosedTransformOptions+ ) {+ this.reader = source.getReader();+ this.pingIntervalMs = opts.pingIntervalMs ?? 1_000;+ this.holdCap = opts.holdCapBytes ?? HOLD_CAP_BYTES;+ this.readable = new ReadableStream<Uint8Array>({+ start: (controller) => {+ this.controller = controller;+ this.timer = setInterval(() => this.tick(), this.pingIntervalMs);+ (this.timer as { unref?: () => void }).unref?.();+ void this.pump();+ },+ pull: () => this.raisePendingError(),+ cancel: (reason) => {+ this.stop();+ this.abort.abort(reason ?? new Error("client cancelled"));+ return this.reader.cancel(reason).catch(() => {});+ },+ });+ }++ /* ───────────── reading ───────────── */++ private async pump(): Promise<void> {+ try {+ for (;;) {+ const { done, value } = await this.reader.read();+ if (this.done) return;+ if (done) {+ for (const ev of this.splitter.end()) this.push({ kind: "event", ev });+ this.push({ kind: "end" });+ return;+ }+ for (const ev of this.splitter.push(value)) this.push({ kind: "event", ev });+ }+ } catch (err) {+ if (!this.done) this.push({ kind: "error", err });+ }+ }++ /**+ * Queue one item and drain. While a hook is awaited, a ping skips the queue:+ * keepalive must reach the client however long the hold lasts.+ */+ private push(item: QueueItem): void {+ if (item.kind === "event" && this.busy && isPing(item.ev, eventJson(item.ev))) {+ this.emit(item.ev.raw);+ return;+ }+ this.queue.push(item);+ this.drain();+ }++ /** Process queued items in order; synchronous until a handler returns a promise. */+ private drain(): void {+ if (this.busy) return;+ this.busy = true;+ while (this.queue.length > 0 && !this.done) {+ const item = this.queue.shift() as QueueItem;+ let pending: void | Promise<void>;+ try {+ pending = this.handleItem(item);+ } catch (err) {+ this.failOpen(err);+ continue;+ }+ if (pending) {+ pending.then(+ () => {+ this.busy = false;+ this.drain();+ },+ (err) => {+ this.failOpen(err);+ this.busy = false;+ this.drain();+ }+ );+ return;+ }+ }+ this.busy = false;+ }++ private handleItem(item: QueueItem): void | Promise<void> {+ if (item.kind === "end") {+ this.flushHeld();+ this.close();+ return;+ }+ if (item.kind === "error") {+ this.flushHeld();+ this.stop();+ this.pendingError = { err: item.err };+ this.raisePendingError();+ return;+ }+ const ev = item.ev;+ if (this.passthrough) {+ this.emit(ev.raw);+ return;+ }+ const json = eventJson(ev) as Json;+ if (isPing(ev, json)) {+ this.emit(ev.raw);+ return;+ }+ if (isError(ev, json)) {+ this.flushHeld();+ this.passthrough = true;+ this.emit(ev.raw);+ return;+ }+ return this.opts.mode === "intercept" ? this.intercept(ev, json) : this.buffer(ev, json);+ }++ /* ───────────── intercept ───────────── */++ private intercept(ev: SseEvent, json: Json): void | Promise<void> {+ const held = this.heldTool;+ if (held) {+ if (json?.type === "content_block_stop" && json.index === held.index) {+ return this.finishTool(held, ev);+ }+ if (+ json?.type === "content_block_delta" &&+ json.index === held.index &&+ json.delta?.type === "input_json_delta"+ ) {+ held.deltas.push(ev);+ held.args += typeof json.delta.partial_json === "string" ? json.delta.partial_json : "";+ } else {+ held.extras.push(ev);+ }+ this.account(ev, "intercept");+ return;+ }+ const cb = json?.type === "content_block_start" ? json.content_block : undefined;+ if (+ cb?.type === "tool_use" &&+ typeof cb.name === "string" &&+ this.opts.hooks.intercepts(cb.name)+ ) {+ this.heldTool = {+ index: json.index,+ id: typeof cb.id === "string" ? cb.id : "",+ name: cb.name,+ args: "",+ deltas: [],+ extras: [],+ };+ }+ this.emit(ev.raw);+ }++ private async finishTool(held: HeldTool, stop: SseEvent): Promise<void> {+ let repaired: Record<string, unknown> | undefined;+ try {+ repaired = await this.opts.hooks.interceptToolCall(+ { id: held.id, name: held.name, rawArgs: held.args },+ this.abort.signal+ );+ } catch (err) {+ // The block goes out as the model sent it.+ log(`[hooks] seam toolCall failed open: ${err instanceof Error ? err.message : err}`);+ }+ if (this.done || this.heldTool !== held) return;+ this.heldTool = null;+ const args = repaired ? JSON.stringify(repaired) : held.args;+ if (repaired || held.deltas.length > 0) this.emit(inputDelta(held.index, args));+ for (const extra of held.extras) this.emit(extra.raw);+ this.emit(stop.raw);+ }++ /* ───────────── buffer ───────────── */++ private buffer(ev: SseEvent, json: Json): void | Promise<void> {+ if (this.phase === "after") {+ this.emit(ev.raw);+ return;+ }+ if (json) this.collector.onEvent(json);++ if (this.phase === "live") {+ if (json?.type === "message_delta") return this.finishHold(ev);+ if (json?.type === "content_block_start") {+ if (isThinkingType(json.content_block?.type)) {+ this.liveBlocks++;+ this.emit(ev.raw);+ return;+ }+ this.phase = "holding";+ this.hold(ev, json);+ return;+ }+ this.emit(ev.raw);+ return;+ }++ if (json?.type === "message_delta") return this.finishHold(ev);+ this.hold(ev, json);+ }++ private hold(ev: SseEvent, json: Json): void {+ this.heldRaw.push(ev);+ const index = typeof json?.index === "number" ? json.index : undefined;+ if (json?.type === "content_block_start" && index !== undefined) {+ const collected = this.collector.blocks[this.collector.blocks.length - 1] as CollectedBlock;+ const block: HeldBlock = { index, events: [ev], collected };+ this.heldBlocks.push(block);+ this.heldByIndex.set(index, block);+ } else if (index !== undefined && this.heldByIndex.has(index)) {+ const block = this.heldByIndex.get(index) as HeldBlock;+ block.events.push(ev);+ if (json.type === "content_block_stop") this.startToolRun(block);+ } else {+ this.loose.push({ ev, ordinal: this.heldBlocks.length });+ }+ this.account(ev, "buffer");+ }++ /** A held tool block completed: start its `toolCall` hooks now, collect at `message_delta`. */+ private startToolRun(block: HeldBlock): void {+ const c = block.collected;+ if (c.type !== "tool_use" || !c.name || !this.opts.hooks.intercepts(c.name)) return;+ const run = this.opts.hooks+ .interceptToolCall({ id: c.id ?? "", name: c.name, rawArgs: c.args }, this.abort.signal)+ .catch((err: unknown) => {+ log(`[hooks] seam toolCall failed open: ${err instanceof Error ? err.message : err}`);+ return undefined;+ });+ this.toolRuns.set(block.index, run);+ }++ private async finishHold(messageDelta: SseEvent): Promise<void> {+ try {+ await this.rewriteHeld();+ } catch (err) {+ // Fail open: whatever is still held goes out unchanged.+ log(`[hooks] seam rewrite failed open: ${err instanceof Error ? err.message : err}`);+ this.flushHeld();+ this.passthrough = true;+ }+ if (this.done) return;+ this.phase = "after";+ this.emit(messageDelta.raw);+ }++ /** Collect repairs, run `responseRewrite`, and re-emit the held region. */+ private async rewriteHeld(): Promise<void> {+ const repairs = new Map<number, Record<string, unknown>>();+ for (const [index, run] of this.toolRuns) {+ const args = await run;+ if (args) repairs.set(index, args);+ }+ if (this.done) return;+ const hooks = this.opts.hooks;+ const planned = await hooks.rewrite(collectorView(this.collector, repairs), this.abort.signal);+ if (this.done) return;++ const rewriteBlocks: RewriteBlock[] = this.heldBlocks.map((b) => ({+ type: b.collected.type,+ ...(b.collected.type === "text" ? { text: b.collected.text } : {}),+ ...(b.collected.locked ? { locked: true } : {}),+ }));+ if (planned.length > 0 && rewriteBlocks.some((b) => b.locked)) {+ hooks.noteRewriteInvalid("citations");+ }+ const result = applyTextActions(+ rewriteBlocks,+ planned.map((p) => p.action)+ );+ hooks.recordRewrite(planned, result);++ // Build the whole region first, so a throw half way emits nothing twice.+ const out: string[] = [];+ let k = 0;+ let looseAt = 0;+ const flushLoose = (upTo: number) => {+ while (looseAt < this.loose.length && (this.loose[looseAt]?.ordinal ?? 0) <= upTo) {+ out.push((this.loose[looseAt] as { ev: SseEvent }).ev.raw);+ looseAt++;+ }+ };+ for (const block of result.blocks) {+ const index = this.liveBlocks + k++;+ if (block.source !== null) flushLoose(block.source);+ if (block.source === null || block.changed) {+ out.push(...textBlock(index, (block.block as { text?: string }).text ?? ""));+ continue;+ }+ const held = this.heldBlocks[block.source] as HeldBlock;+ out.push(...heldBlock(held, index, repairs.get(held.index)));+ }+ flushLoose(Number.POSITIVE_INFINITY);+ this.resetHeld();+ for (const text of out) this.emit(text);+ }++ /* ───────────── holding bookkeeping ───────────── */++ /** Count held bytes; past the cap, flush everything unchanged and stop holding. */+ private account(ev: SseEvent, mode: ClosedMode): void {+ this.heldBytes += Buffer.byteLength(ev.raw);+ if (this.heldBytes <= this.holdCap) return;+ log(`[hooks] seam held more than ${this.holdCap} bytes: flushed unchanged, holding stopped`);+ if (mode === "buffer") this.opts.hooks.noteRewriteInvalid("buffer_cap");+ else this.opts.hooks.noteInterceptInvalid("buffer_cap");+ this.flushHeld();+ this.passthrough = true;+ }++ /** Forward everything held, unchanged, in arrival order. */+ private flushHeld(): void {+ const tool = this.heldTool;+ if (tool) {+ this.heldTool = null;+ for (const ev of tool.deltas) this.emit(ev.raw);+ for (const ev of tool.extras) this.emit(ev.raw);+ }+ if (this.heldRaw.length > 0) {+ for (const ev of this.heldRaw) this.emit(ev.raw);+ }+ this.resetHeld();+ if (this.phase === "holding") this.phase = "after";+ }++ private resetHeld(): void {+ this.heldRaw = [];+ this.heldBlocks = [];+ this.heldByIndex.clear();+ this.loose = [];+ this.toolRuns.clear();+ this.heldBytes = 0;+ }++ private get holding(): boolean {+ return this.busy || this.heldTool !== null || this.phase === "holding";+ }++ /** The seam's own keepalive, while it holds content and upstream sends none. */+ private tick(): void {+ if (this.done || !this.holding) return;+ if (Date.now() - this.lastPingAt < this.pingIntervalMs) return;+ this.emit(PING_FRAME);+ }++ /** A throw inside the transform: flush what is held and pass the rest through. */+ private failOpen(err: unknown): void {+ log(`[hooks] seam transform failed open: ${err instanceof Error ? err.message : err}`);+ try {+ this.flushHeld();+ } catch {}+ this.passthrough = true;+ }++ /* ───────────── output ───────────── */++ /** Error the stream once the client has drained what was queued before the error. */+ private raisePendingError(): void {+ const pending = this.pendingError;+ if (!pending || (this.controller.desiredSize ?? 0) <= 0) return;+ this.pendingError = null;+ this.controller.error(pending.err);+ }++ private emit(text: string): void {+ if (this.done) return;+ if (text === PING_FRAME || text.startsWith("event: ping")) this.lastPingAt = Date.now();+ this.controller.enqueue(encodeUtf8(text));+ }++ private close(): void {+ if (this.done) return;+ this.stop();+ this.controller.close();+ }++ private stop(): void {+ this.done = true;+ if (this.timer) clearInterval(this.timer);+ this.timer = null;+ }+}diff --git a/packages/cli/src/hooks/seam.test.ts b/packages/cli/src/hooks/seam.test.tsnew file mode 100644index 00000000..d4967f26--- /dev/null+++ b/packages/cli/src/hooks/seam.test.ts@@ -0,0 +1,1078 @@+/**+ * The response seam over synthetic Claude SSE streams (§5.3, §5.4, §11.3+ * "Seam"): the closed modes `intercept` and `buffer`, block re-indexing,+ * keepalive pings, the hold cap, upstream errors, client cancel, fail-open, the+ * observe tap and its inbox `stop`/`end` lines, `responseEnd`, and the+ * non-streaming JSON branch.+ */++import { afterEach, describe, expect, it } from "bun:test";+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { HookEngine } from "./engine.js";+import { InboxFileSink, type InjectionSink, UnavailableSink } from "./injection/sinks.js";+import type { JournalEntry } from "./journal.js";+import { type HookDefinition, type ResponseView, type Severity, act } from "./public.js";+import { HookRegistry, type UserHookInput } from "./registry.js";+import { RequestHooks } from "./request-stage.js";+import { applyResponseSeam, planSeam, withHooks } from "./response-seam.js";+import type { SeamHooks } from "./seam-hooks.js";+import { PING_FRAME, closedTransform } from "./seam-transform.js";++const SESSION = "5b0c8f7e-2f7a-4d55-9d7e-2f2a1c7e9a10";++/* ───────────── fixtures ───────────── */++const frame = (event: string, data: object) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;++const messageStart = () =>+ frame("message_start", {+ type: "message_start",+ message: { id: "msg_1", type: "message", role: "assistant", content: [], model: "m" },+ });+const start = (index: number, block: object) =>+ frame("content_block_start", { type: "content_block_start", index, content_block: block });+const textDelta = (index: number, text: string) =>+ frame("content_block_delta", {+ type: "content_block_delta",+ index,+ delta: { type: "text_delta", text },+ });+const jsonDelta = (index: number, partial_json: string) =>+ frame("content_block_delta", {+ type: "content_block_delta",+ index,+ delta: { type: "input_json_delta", partial_json },+ });+const thinkingDelta = (index: number, thinking: string) =>+ frame("content_block_delta", {+ type: "content_block_delta",+ index,+ delta: { type: "thinking_delta", thinking },+ });+const signatureDelta = (index: number, signature: string) =>+ frame("content_block_delta", {+ type: "content_block_delta",+ index,+ delta: { type: "signature_delta", signature },+ });+const stop = (index: number) => frame("content_block_stop", { type: "content_block_stop", index });+const messageDelta = (stop_reason = "end_turn") =>+ frame("message_delta", { type: "message_delta", delta: { stop_reason, stop_sequence: null } });+const messageStop = () => frame("message_stop", { type: "message_stop" });++const textBlock = (index: number, text: string) => [+ start(index, { type: "text", text: "" }),+ textDelta(index, text),+ stop(index),+];+const toolBlock = (index: number, name: string, fragments: string[], id = `toolu_${index}`) => [+ start(index, { type: "tool_use", id, name, input: {} }),+ ...fragments.map((f) => jsonDelta(index, f)),+ stop(index),+];++const encoder = new TextEncoder();++/** A Claude SSE Response that yields `chunks` one per read, optionally waiting before some. */+function sse(+ chunks: string[],+ opts: { gates?: Map<number, Promise<void>>; onCancel?: () => void; errorAfter?: number } = {}+): Response {+ let i = 0;+ const body = new ReadableStream<Uint8Array>({+ async pull(controller) {+ if (opts.errorAfter !== undefined && i === opts.errorAfter) {+ controller.error(new Error("upstream socket dropped"));+ return;+ }+ if (i >= chunks.length) {+ controller.close();+ return;+ }+ await opts.gates?.get(i);+ controller.enqueue(encoder.encode(chunks[i] as string));+ i++;+ },+ cancel() {+ opts.onCancel?.();+ },+ });+ return new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } });+}++let n = 0;+function userHook(def: Omit<HookDefinition, "apiVersion">): UserHookInput {+ const full = { apiVersion: 1, ...def } as HookDefinition;+ return { id: `hook:t/${def.id}`, module: "/t.ts", moduleIndex: 0, exportIndex: n++, def: full };+}++function engineWith(hooks: UserHookInput[], severity?: Record<string, Severity>) {+ const journal: JournalEntry[] = [];+ const engine = new HookEngine({+ registry: new HookRegistry([], hooks, severity),+ config: {},+ hostMode: "pane-child",+ journalSink: (e) => journal.push(e),+ warn: () => {},+ drainTelemetryOutbox: false,+ });+ return { engine, journal };+}++function fakeContext(): any {+ const vars = new Map<string, unknown>();+ return { get: (k: string) => vars.get(k), set: (k: string, v: unknown) => vars.set(k, v) };+}++async function scopeOf(engine: HookEngine, sink: InjectionSink = new UnavailableSink(() => {})) {+ return new RequestHooks(engine, null, sink).beginAttempt(fakeContext(), {+ claudeRequest: {+ system: "base",+ messages: [{ role: "user", content: "hi" }],+ metadata: {+ user_id: JSON.stringify({ device_id: "d", account_uuid: "", session_id: SESSION }),+ },+ },+ route: { modelId: "glm-5", provider: "zai", native: false },+ model: "glm-5",+ stream: true,+ });+}++async function readAll(res: Response): Promise<string> {+ return await res.text();+}++/** Every `data:` payload, pings excluded. */+function payloads(wire: string): any[] {+ return wire+ .split("\n")+ .filter((l) => l.startsWith("data: "))+ .map((l) => JSON.parse(l.slice(6)))+ .filter((p) => p.type !== "ping");+}++function indicesOf(wire: string, type: string): number[] {+ return payloads(wire)+ .filter((p) => p.type === type)+ .map((p) => p.index);+}++function blockStarts(wire: string): Array<{ index: number; type: string }> {+ return payloads(wire)+ .filter((p) => p.type === "content_block_start")+ .map((p) => ({ index: p.index, type: p.content_block.type }));+}++const tmpDirs: string[] = [];+function inboxPath(): string {+ const dir = mkdtempSync(join(tmpdir(), "claudish-seam-"));+ tmpDirs.push(dir);+ return join(dir, "hook-inbox.jsonl");+}+function inboxLines(path: string): any[] {+ if (!existsSync(path)) return [];+ return readFileSync(path, "utf8")+ .split("\n")+ .filter(Boolean)+ .map((l) => JSON.parse(l));+}+afterEach(() => {+ for (const d of tmpDirs.splice(0)) rmSync(d, { recursive: true, force: true });+});++async function until(cond: () => boolean, ms = 2_000): Promise<void> {+ const deadline = Date.now() + ms;+ while (!cond()) {+ if (Date.now() > deadline) throw new Error("condition not met in time");+ await Bun.sleep(5);+ }+}++const repairHook = (tool: string, args: Record<string, unknown>) =>+ userHook({+ id: `repair-${tool}`,+ on: { toolCall: { tools: [tool], handle: () => [act.repairToolArgs(args, "test")] } },+ });++const rewriteHook = (id: string, handle: (view: ResponseView) => unknown) =>+ userHook({+ id,+ on: { responseRewrite: { handle: (ctx) => handle(ctx.response) as never } },+ });++/* ───────────── plan and identity ───────────── */++describe("seam plan", () => {+ it("is mode none with no tap when nothing claims the request, and returns the same object", async () => {+ const { engine } = engineWith([]);+ const scope = await scopeOf(engine);+ expect(planSeam(scope)).toEqual({ mode: "none", tap: false });+ const res = sse([messageStart()]);+ expect(await applyResponseSeam(res, scope)).toBe(res);+ });++ it("picks the strictest closed mode: buffer over intercept over none", async () => {+ const tool = repairHook("Write", {});+ const rewrite = rewriteHook("rw", () => []);+ expect(planSeam(await scopeOf(engineWith([tool]).engine)).mode).toBe("intercept");+ expect(planSeam(await scopeOf(engineWith([tool, rewrite]).engine)).mode).toBe("buffer");+ });++ it("a warn-severity toolCall or rewrite hook never holds: it goes to the tap", async () => {+ const tool = repairHook("Write", {});+ const rewrite = rewriteHook("rw", () => []);+ const { engine } = engineWith([tool, rewrite], { "hook:t/*": "warn" });+ expect(planSeam(await scopeOf(engine))).toEqual({ mode: "none", tap: true });+ });++ it("an unarmed toolCall hook and a declining rewrite hook leave the identity case", async () => {+ const tool = userHook({+ id: "unarmed",+ on: { toolCall: { tools: ["Write"], armed: () => false, handle: () => [] } },+ });+ const rewrite = userHook({+ id: "declines",+ on: { responseRewrite: { claims: () => false, handle: () => [] } },+ });+ const { engine } = engineWith([tool, rewrite]);+ const scope = await scopeOf(engine);+ expect(planSeam(scope)).toEqual({ mode: "none", tap: false });+ });+});++/* ───────────── intercept ───────────── */++describe("intercept mode", () => {+ it("repairs one named tool and leaves another tool and all text byte-identical", async () => {+ const { engine, journal } = engineWith([repairHook("Write", { file_path: "/fixed" })]);+ const scope = await scopeOf(engine);+ const before = [+ messageStart(),+ PING_FRAME,+ ...textBlock(0, "héllo wörld"),+ ...toolBlock(1, "Read", ['{"file_path":', '"/a"}']),+ ...toolBlock(2, "Write", ['{"file_path":"/wr', 'ong"}']),+ messageDelta("tool_use"),+ messageStop(),+ ];+ const out = await readAll(await applyResponseSeam(sse(before), scope));++ const expected = [+ ...before.slice(0, 9),+ start(2, { type: "tool_use", id: "toolu_2", name: "Write", input: {} }),+ jsonDelta(2, '{"file_path":"/fixed"}'),+ stop(2),+ messageDelta("tool_use"),+ messageStop(),+ ].join("");+ expect(out).toBe(expected);+ expect(+ journal.some(+ (e) => e.event === "toolCall" && e.decision === "repaired" && e.toolName === "Write"+ )+ ).toBe(true);+ });++ it("a hook that changes nothing still finishes the block with one delta of the model's arguments", async () => {+ const hook = userHook({ id: "noop", on: { toolCall: { tools: ["Write"], handle: () => [] } } });+ const { engine, journal } = engineWith([hook]);+ const out = await readAll(+ await applyResponseSeam(+ sse([...toolBlock(0, "Write", ['{"a":', "1}"]), messageStop()]),+ await scopeOf(engine)+ )+ );+ expect(payloads(out).filter((p) => p.type === "content_block_delta")).toEqual([+ {+ type: "content_block_delta",+ index: 0,+ delta: { type: "input_json_delta", partial_json: '{"a":1}' },+ },+ ]);+ expect(journal.some((e) => e.hookId === "hook:t/noop" && e.decision === "ignored")).toBe(true);+ });++ it("does not call the hook for malformed arguments, and forwards them unchanged", async () => {+ let called = 0;+ const hook = userHook({+ id: "count",+ on: {+ toolCall: {+ tools: ["Write"],+ handle: () => {+ called++;+ return [];+ },+ },+ },+ });+ const { engine } = engineWith([hook]);+ const out = await readAll(+ await applyResponseSeam(sse(toolBlock(0, "Write", ['{"a":'])), await scopeOf(engine))+ );+ expect(called).toBe(0);+ expect(payloads(out)[1].delta.partial_json).toBe('{"a":');+ });++ it("a throwing hook fails open: the model's arguments go out", async () => {+ const hook = userHook({+ id: "boom",+ on: {+ toolCall: {+ tools: ["Write"],+ handle: () => {+ throw new Error("boom");+ },+ },+ },+ });+ const { engine, journal } = engineWith([hook]);+ const out = await readAll(+ await applyResponseSeam(sse(toolBlock(0, "Write", ['{"a":1}'])), await scopeOf(engine))+ );+ expect(payloads(out)[1].delta.partial_json).toBe('{"a":1}');+ expect(journal.some((e) => e.hookId === "hook:t/boom" && e.decision === "error")).toBe(true);+ });++ it('"*" holds every tool', async () => {+ const hook = userHook({+ id: "all",+ on: { toolCall: { tools: ["*"], handle: () => [act.repairToolArgs({ x: 1 }, "all")] } },+ });+ const { engine } = engineWith([hook]);+ const out = await readAll(+ await applyResponseSeam(sse(toolBlock(0, "Anything", ['{"y":2}'])), await scopeOf(engine))+ );+ expect(payloads(out)[1].delta.partial_json).toBe('{"x":1}');+ });++ it("forwards upstream pings while a hook is awaited", async () => {+ let release!: () => void;+ const gate = new Promise<void>((r) => {+ release = r;+ });+ const hook = userHook({+ id: "slow",+ on: {+ toolCall: {+ tools: ["Write"],+ handle: async () => {+ await gate;+ return [];+ },+ },+ },+ });+ const { engine } = engineWith([hook]);+ const res = await applyResponseSeam(+ sse([...toolBlock(0, "Write", ['{"a":1}']), PING_FRAME, messageStop()]),+ await scopeOf(engine),+ { pingIntervalMs: 10_000 }+ );+ const reader = res.body!.getReader();+ const decoder = new TextDecoder();+ let seen = "";+ while (!seen.includes(PING_FRAME)) seen += decoder.decode((await reader.read()).value);+ // The ping arrived while the Write block was still held.+ expect(seen).not.toContain("content_block_stop");+ release();+ for (;;) {+ const r = await reader.read();+ if (r.done) break;+ seen += decoder.decode(r.value);+ }+ expect(seen.indexOf(PING_FRAME)).toBeLessThan(seen.indexOf("content_block_stop"));+ });+});++/* ───────────── buffer ───────────── */++describe("buffer mode", () => {+ it("appendText on a tool-only response yields a text block BEFORE the tool_use", async () => {+ const { engine } = engineWith([rewriteHook("add", () => [act.appendText("ADDED")])]);+ const out = await readAll(+ await applyResponseSeam(+ sse([+ messageStart(),+ ...toolBlock(0, "Read", ['{"a":1}']),+ messageDelta("tool_use"),+ messageStop(),+ ]),+ await scopeOf(engine)+ )+ );+ expect(blockStarts(out)).toEqual([+ { index: 0, type: "text" },+ { index: 1, type: "tool_use" },+ ]);+ expect(payloads(out).find((p) => p.delta?.type === "text_delta")?.delta.text).toBe("ADDED");+ });++ it("re-index: appendText on [thinking, tool_use, tool_use] emits 0,1,2,3 with the text at 1", async () => {+ const { engine } = engineWith([rewriteHook("add", () => [act.appendText("T")])]);+ const out = await readAll(+ await applyResponseSeam(+ sse([+ messageStart(),+ start(0, { type: "thinking", thinking: "" }),+ thinkingDelta(0, "hmm"),+ signatureDelta(0, "SIG+/=="),+ stop(0),+ ...toolBlock(1, "A", ['{"q":"\\"x\\""}']),+ ...toolBlock(2, "B", ["{}"]),+ messageDelta("tool_use"),+ messageStop(),+ ]),+ await scopeOf(engine)+ )+ );+ expect(blockStarts(out)).toEqual([+ { index: 0, type: "thinking" },+ { index: 1, type: "text" },+ { index: 2, type: "tool_use" },+ { index: 3, type: "tool_use" },+ ]);+ expect(indicesOf(out, "content_block_stop")).toEqual([0, 1, 2, 3]);+ // Every other field is carried unchanged.+ const deltas = payloads(out).filter((p) => p.type === "content_block_delta");+ expect(deltas.find((d) => d.delta.type === "signature_delta")?.delta.signature).toBe("SIG+/==");+ expect(deltas.find((d) => d.index === 2)?.delta.partial_json).toBe('{"q":"\\"x\\""}');+ });++ it("re-index: removeText emptying block 0 of [text, tool_use] emits the tool at index 0", async () => {+ const { engine } = engineWith([rewriteHook("rm", () => [act.removeText("DROP")])]);+ const out = await readAll(+ await applyResponseSeam(+ sse([+ messageStart(),+ ...textBlock(0, "DROP"),+ ...toolBlock(1, "A", ['{"k":"v"}']),+ messageDelta(),+ messageStop(),+ ]),+ await scopeOf(engine)+ )+ );+ expect(blockStarts(out)).toEqual([{ index: 0, type: "tool_use" }]);+ expect(indicesOf(out, "content_block_delta")).toEqual([0]);+ expect(indicesOf(out, "content_block_stop")).toEqual([0]);+ expect(payloads(out).find((p) => p.type === "content_block_delta").delta.partial_json).toBe(+ '{"k":"v"}'+ );+ });++ it("replaceText and prependText rewrite the text, chunked into deltas of at most 1,024 units", async () => {+ const long = "a".repeat(3000);+ const { engine } = engineWith([+ rewriteHook("rw", () => [act.prependText("P:"), act.replaceText("KEEP REMOVE-ME", "KEEP")]),+ ]);+ const out = await readAll(+ await applyResponseSeam(+ sse([+ messageStart(),+ ...textBlock(0, `KEEP REMOVE-ME KEEP${long}`),+ messageDelta(),+ messageStop(),+ ]),+ await scopeOf(engine)+ )+ );+ const texts = payloads(out)+ .filter((p) => p.delta?.type === "text_delta")+ .map((p) => p.delta.text);+ expect(texts.join("")).toBe(`P:KEEP KEEP${long}`);+ expect(Math.max(...texts.map((t) => t.length))).toBeLessThanOrEqual(1024);+ });++ it("a leading thinking block streams live, before the rewrite hook has run", async () => {+ let release!: () => void;+ const gate = new Promise<void>((r) => {+ release = r;+ });+ const { engine } = engineWith([+ rewriteHook("slow", async () => {+ await gate;+ return [act.appendText("!")];+ }),+ ]);+ const res = await applyResponseSeam(+ sse([+ messageStart(),+ start(0, { type: "thinking", thinking: "" }),+ thinkingDelta(0, "think"),+ stop(0),+ ...textBlock(1, "answer"),+ messageDelta(),+ messageStop(),+ ]),+ await scopeOf(engine)+ );+ const reader = res.body!.getReader();+ const decoder = new TextDecoder();+ let seen = "";+ while (!seen.includes('"type":"content_block_stop","index":0')) {+ seen += decoder.decode((await reader.read()).value);+ }+ expect(seen).not.toContain("answer");+ release();+ for (;;) {+ const r = await reader.read();+ if (r.done) break;+ seen += decoder.decode(r.value);+ }+ expect(seen).toContain('"text":"answer!"');+ });++ it("forwards upstream pings during the hold, ahead of the held events", async () => {+ const { engine } = engineWith([rewriteHook("rw", () => [act.appendText("!")])]);+ const out = await readAll(+ await applyResponseSeam(+ sse([+ messageStart(),+ start(0, { type: "text", text: "" }),+ PING_FRAME,+ textDelta(0, "x"),+ stop(0),+ messageDelta(),+ messageStop(),+ ]),+ await scopeOf(engine)+ )+ );+ expect(out.indexOf(PING_FRAME)).toBeLessThan(out.indexOf("content_block_start"));+ });++ it("emits its own ping each interval while awaiting responseRewrite after upstream close", async () => {+ const { engine } = engineWith([+ rewriteHook("slow", async () => {+ await Bun.sleep(260);+ return [];+ }),+ ]);+ const out = await readAll(+ await applyResponseSeam(+ sse([messageStart(), ...textBlock(0, "x"), messageDelta(), messageStop()]),+ await scopeOf(engine),+ { pingIntervalMs: 50 }+ )+ );+ const pings = out.split(PING_FRAME).length - 1;+ expect(pings).toBeGreaterThanOrEqual(2);+ expect(out.indexOf(PING_FRAME)).toBeLessThan(out.indexOf("content_block_start"));+ });++ it("repairs a held tool block's arguments before the rewrite hooks see the response", async () => {+ let seen: ResponseView | undefined;+ const { engine } = engineWith([+ repairHook("Write", { file_path: "/fixed" }),+ rewriteHook("look", (view) => {+ seen = view;+ return [];+ }),+ ]);+ const out = await readAll(+ await applyResponseSeam(+ sse([+ messageStart(),+ ...toolBlock(0, "Write", ['{"file_path":"/x"}']),+ messageDelta("tool_use"),+ messageStop(),+ ]),+ await scopeOf(engine)+ )+ );+ expect(payloads(out).find((p) => p.type === "content_block_delta").delta.partial_json).toBe(+ '{"file_path":"/fixed"}'+ );+ expect(seen?.blocks).toEqual([+ { type: "tool_use", id: "toolu_0", name: "Write", input: { file_path: "/fixed" } },+ ]);+ expect(seen?.stopReason).toBe("tool_use");+ });++ it("past the hold cap it flushes everything unchanged and stops holding", async () => {+ const { engine, journal } = engineWith([rewriteHook("rw", () => [act.appendText("!")])]);+ const input = [messageStart(), ...textBlock(0, "x".repeat(500)), messageDelta(), messageStop()];+ const out = await readAll(+ await applyResponseSeam(sse(input), await scopeOf(engine), { holdCapBytes: 200 })+ );+ expect(out).toBe(input.join(""));+ expect(journal.some((e) => e.decision === "invalid" && e.detail === "buffer_cap")).toBe(true);+ });++ it("an upstream error event while holding flushes the held events unchanged, then the error", async () => {+ const { engine } = engineWith([rewriteHook("rw", () => [act.appendText("!")])]);+ const error = frame("error", {+ type: "error",+ error: { type: "overloaded_error", message: "x" },+ });+ const input = [+ messageStart(),+ start(0, { type: "text", text: "" }),+ textDelta(0, "partial"),+ error,+ ];+ const out = await readAll(await applyResponseSeam(sse(input), await scopeOf(engine)));+ expect(out).toBe(input.join(""));+ });++ it("a stream that ends while holding forwards what it held", async () => {+ const { engine } = engineWith([rewriteHook("rw", () => [act.appendText("!")])]);+ const input = [messageStart(), start(0, { type: "text", text: "" }), textDelta(0, "partial")];+ const out = await readAll(await applyResponseSeam(sse(input), await scopeOf(engine)));+ expect(out).toBe(input.join(""));+ });++ it("a citations text block is never rewritten, and the skip is journaled", async () => {+ const { engine, journal } = engineWith([+ rewriteHook("rw", () => [act.replaceText("cite", "X")]),+ ]);+ const input = [+ messageStart(),+ start(0, { type: "text", text: "" }),+ textDelta(0, "cite me"),+ frame("content_block_delta", {+ type: "content_block_delta",+ index: 0,+ delta: { type: "citations_delta", citation: { cited_text: "c" } },+ }),+ stop(0),+ messageDelta(),+ messageStop(),+ ];+ const out = await readAll(await applyResponseSeam(sse(input), await scopeOf(engine)));+ expect(out).toBe(input.join(""));+ expect(journal.some((e) => e.decision === "invalid" && e.detail === "citations")).toBe(true);+ });++ it("splits a multi-byte character across chunks without corrupting it", async () => {+ const { engine } = engineWith([rewriteHook("rw", () => [act.appendText("!")])]);+ const whole = [+ messageStart(),+ ...textBlock(0, "snow ☃ man"),+ messageDelta(),+ messageStop(),+ ].join("");+ const bytes = encoder.encode(whole);+ const cut = bytes.indexOf(0xe2) + 1; // inside the 3-byte snowman+ const body = new ReadableStream<Uint8Array>({+ start(c) {+ c.enqueue(bytes.slice(0, cut));+ c.enqueue(bytes.slice(cut));+ c.close();+ },+ });+ const res = new Response(body, { headers: { "content-type": "text/event-stream" } });+ const out = await readAll(await applyResponseSeam(res, await scopeOf(engine)));+ expect(payloads(out).find((p) => p.delta?.type === "text_delta").delta.text).toBe(+ "snow ☃ man!"+ );+ });+});++/* ───────────── fail open ───────────── */++describe("fail open", () => {+ it("a throw inside the transform forwards what it held, and the rest, unchanged", async () => {+ const throwing = {+ intercepts: () => false,+ rewrite: () => {+ throw new Error("seam bug");+ },+ noteRewriteInvalid: () => {},+ recordRewrite: () => {},+ } as unknown as SeamHooks;+ const input = [messageStart(), ...textBlock(0, "keep"), messageDelta(), messageStop()];+ const out = await readAll(+ new Response(closedTransform(sse(input).body!, { mode: "buffer", hooks: throwing }))+ );+ expect(out).toBe(input.join(""));+ });++ it("an upstream read error forwards what was held, then errors the stream", async () => {+ const { engine } = engineWith([rewriteHook("rw", () => [])]);+ const res = await applyResponseSeam(+ sse([messageStart(), start(0, { type: "text", text: "" }), textDelta(0, "partial")], {+ errorAfter: 3,+ }),+ await scopeOf(engine)+ );+ const reader = res.body!.getReader();+ const decoder = new TextDecoder();+ let seen = "";+ let error: unknown;+ try {+ for (;;) {+ const r = await reader.read();+ if (r.done) break;+ seen += decoder.decode(r.value);+ }+ } catch (err) {+ error = err;+ }+ expect(String(error)).toContain("upstream socket dropped");+ expect(seen).toContain('"text":"partial"');+ });+});++/* ───────────── tap, inbox and responseEnd ───────────── */++describe("observe tap", () => {+ const endHook = (onEnd: (view: ResponseView) => unknown = () => []) =>+ userHook({ id: "end", on: { responseEnd: (ctx) => onEnd(ctx.response) as never } });++ it("passes every chunk through unchanged and delivers chunk 1 before chunk 2 exists", async () => {+ const { engine } = engineWith([endHook()]);+ let release!: () => void;+ const gate = new Promise<void>((r) => {+ release = r;+ });+ const chunks = [messageStart(), ...textBlock(0, "x"), messageDelta(), messageStop()];+ const res = await applyResponseSeam(+ sse(chunks, { gates: new Map([[1, gate]]) }),+ await scopeOf(engine)+ );+ const reader = res.body!.getReader();+ const first = await Promise.race([+ reader.read(),+ Bun.sleep(500).then(() => "timeout" as const),+ ]);+ expect(first).not.toBe("timeout");+ expect(new TextDecoder().decode((first as ReadableStreamReadResult<Uint8Array>).value)).toBe(+ chunks[0]+ );+ release();+ const rest: string[] = [];+ for (;;) {+ const r = await reader.read();+ if (r.done) break;+ rest.push(new TextDecoder().decode(r.value));+ }+ // Same bytes, same chunking.+ expect(rest).toEqual(chunks.slice(1));+ });++ for (const mode of ["none", "intercept", "buffer"] as const) {+ it(`inbox stop is on disk when the client reads the message_stop chunk (mode ${mode})`, async () => {+ const path = inboxPath();+ const hooks = [endHook()];+ if (mode === "intercept") hooks.push(repairHook("Write", { a: 1 }));+ if (mode === "buffer") hooks.push(rewriteHook("rw", () => [act.appendText("!")]));+ const { engine } = engineWith(hooks);+ const scope = await scopeOf(engine);+ expect(planSeam(scope).mode).toBe(mode);+ const res = await applyResponseSeam(+ sse([+ messageStart(),+ ...textBlock(0, "x"),+ ...toolBlock(1, "Write", ["{}"]),+ messageDelta(),+ messageStop(),+ ]),+ scope,+ { sink: new InboxFileSink(path), req: "r1" }+ );+ const reader = res.body!.getReader();+ const decoder = new TextDecoder();+ let atStop: any[] | null = null;+ for (;;) {+ const r = await reader.read();+ if (r.done) break;+ if (decoder.decode(r.value).includes('"type":"message_stop"')) {+ atStop = inboxLines(path);+ }+ }+ expect(atStop).toEqual([{ v: 1, kind: "stop", req: "r1" }]);+ await until(() => inboxLines(path).length === 2);+ expect(inboxLines(path)[1]).toEqual({ v: 1, kind: "end", req: "r1" });+ });+ }++ it("responseEnd sees the bytes the client received (the rewrite included)", async () => {+ let seen: ResponseView | undefined;+ const { engine } = engineWith([+ rewriteHook("rw", () => [act.appendText(" HOOK-ADDED")]),+ endHook((view) => {+ seen = view;+ return [];+ }),+ ]);+ await readAll(+ await applyResponseSeam(+ sse([messageStart(), ...textBlock(0, "answer"), messageDelta(), messageStop()]),+ await scopeOf(engine)+ )+ );+ await until(() => seen !== undefined);+ expect(seen?.text).toBe("answer HOOK-ADDED");+ expect(seen?.stopReason).toBe("end_turn");+ });++ it("routes responseEnd actions: inject and annotate to the inbox, a system note to the next request", async () => {+ const path = inboxPath();+ const { engine, journal } = engineWith([+ endHook(() => [+ act.injectUserTurn("HOOK-PING"),+ act.annotateTurn("k", { n: 1 }),+ act.injectSystemNote("NEXT"),+ ]),+ ]);+ await readAll(+ await applyResponseSeam(+ sse([messageStart(), ...textBlock(0, "x"), messageDelta(), messageStop()]),+ await scopeOf(engine),+ { sink: new InboxFileSink(path, undefined, () => new Date(0)), req: "r9" }+ )+ );+ await until(() => inboxLines(path).some((l) => l.kind === "end"));+ expect(inboxLines(path)).toEqual([+ { v: 1, kind: "stop", req: "r9" },+ {+ v: 1,+ kind: "inject",+ req: "r9",+ hookId: "hook:t/end",+ text: "HOOK-PING",+ at: "1970-01-01T00:00:00.000Z",+ },+ {+ v: 1,+ kind: "annotate",+ req: "r9",+ hookId: "hook:t/end",+ key: "k",+ value: { n: 1 },+ at: "1970-01-01T00:00:00.000Z",+ },+ { v: 1, kind: "end", req: "r9" },+ ]);+ expect(engine.peekNotes(SESSION).map((n) => n.text)).toEqual(["NEXT"]);+ expect(+ journal.filter((e) => e.event === "responseEnd" && e.decision === "queued")+ ).toHaveLength(3);+ });++ it("with no session driver an injection is dropped `unavailable`, with one stderr line per process", async () => {+ const lines: string[] = [];+ const { engine, journal } = engineWith([endHook(() => [act.injectUserTurn("X")])]);+ const { resetUnavailableSinkReportForTests } = await import("./injection/sinks.js");+ resetUnavailableSinkReportForTests();+ for (let i = 0; i < 2; i++) {+ await readAll(+ await applyResponseSeam(+ sse([messageStart(), ...textBlock(0, "x"), messageDelta(), messageStop()]),+ await scopeOf(engine),+ { sink: new UnavailableSink((l) => lines.push(l)) }+ )+ );+ }+ await until(() => journal.filter((e) => e.decision === "dropped").length === 2);+ expect(journal.filter((e) => e.detail === "unavailable")).toHaveLength(2);+ expect(lines).toHaveLength(1);+ });++ it("a warn-severity responseEnd hook writes nothing but stop/end, and journals warned", async () => {+ const path = inboxPath();+ const { engine, journal } = engineWith([endHook(() => [act.injectUserTurn("X")])], {+ "hook:t/end": "warn",+ });+ await readAll(+ await applyResponseSeam(+ sse([messageStart(), ...textBlock(0, "x"), messageDelta(), messageStop()]),+ await scopeOf(engine),+ { sink: new InboxFileSink(path), req: "w" }+ )+ );+ await until(() => inboxLines(path).some((l) => l.kind === "end"));+ expect(inboxLines(path).map((l) => l.kind)).toEqual(["stop", "end"]);+ expect(journal.some((e) => e.event === "responseEnd" && e.decision === "warned")).toBe(true);+ });++ it("a client cancel writes end with aborted at once, and cancels the upstream", async () => {+ const path = inboxPath();+ let cancelled = false;+ const { engine } = engineWith([endHook()]);+ const res = await applyResponseSeam(+ sse([messageStart(), ...textBlock(0, "x"), messageDelta(), messageStop()], {+ gates: new Map([[2, new Promise<void>(() => {})]]),+ onCancel: () => {+ cancelled = true;+ },+ }),+ await scopeOf(engine),+ { sink: new InboxFileSink(path), req: "c" }+ );+ const reader = res.body!.getReader();+ await reader.read();+ await reader.cancel("client went away");+ expect(inboxLines(path)).toEqual([{ v: 1, kind: "end", req: "c", aborted: true }]);+ expect(cancelled).toBe(true);+ });++ it("a response that ends before message_stop writes only its end", async () => {+ const path = inboxPath();+ const { engine } = engineWith([endHook()]);+ await readAll(+ await applyResponseSeam(sse([messageStart(), ...textBlock(0, "x")]), await scopeOf(engine), {+ sink: new InboxFileSink(path),+ req: "t",+ })+ );+ expect(inboxLines(path)).toEqual([{ v: 1, kind: "end", req: "t", aborted: true }]);+ });++ it("observe-mode and warn-severity toolCall hooks see the delivered call and hold nothing", async () => {+ const seen: string[] = [];+ const observe = userHook({+ id: "obs",+ on: {+ toolCall: {+ tools: ["Write"],+ observe: true,+ handle: (ctx) => {+ seen.push(`obs:${JSON.stringify(ctx.tool.args)}`);+ return [act.warn("seen")];+ },+ },+ },+ });+ const warnRepair = userHook({+ id: "warned",+ on: {+ toolCall: {+ tools: ["Write"],+ handle: (ctx) => {+ seen.push(`warn:${ctx.tool.rawArgs}`);+ return [act.repairToolArgs({ changed: true }, "would repair")];+ },+ },+ },+ });+ const { engine, journal } = engineWith([observe, warnRepair], { "hook:t/warned": "warn" });+ const scope = await scopeOf(engine);+ expect(planSeam(scope)).toEqual({ mode: "none", tap: true });+ const input = [+ messageStart(),+ ...toolBlock(0, "Write", ['{"a":', "1}"]),+ messageDelta(),+ messageStop(),+ ];+ const out = await readAll(await applyResponseSeam(sse(input), scope));+ expect(out).toBe(input.join(""));+ await until(() => seen.length === 2);+ expect(seen.sort()).toEqual(['obs:{"a":1}', 'warn:{"a":1}']);+ await until(() => journal.some((e) => e.hookId === "hook:t/warned" && e.decision === "warned"));+ });+});++/* ───────────── JSON branch ───────────── */++describe("non-streaming JSON branch", () => {+ const jsonResponse = (message: object) =>+ new Response(JSON.stringify(message), {+ status: 200,+ headers: { "content-type": "application/json", "x-upstream": "kept" },+ });++ it("repairs tool_use.input, rewrites text, keeps status and headers, and writes stop before returning", async () => {+ const path = inboxPath();+ let seen: ResponseView | undefined;+ const { engine } = engineWith([+ repairHook("Write", { file_path: "/fixed" }),+ rewriteHook("rm", () => [act.removeText("\\s*REMOVE-ME", { regex: true })]),+ userHook({+ id: "end",+ on: {+ responseEnd: (ctx) => {+ seen = ctx.response;+ },+ },+ }),+ ]);+ const res = await applyResponseSeam(+ jsonResponse({+ id: "msg_1",+ type: "message",+ role: "assistant",+ content: [+ { type: "text", text: "KEEP REMOVE-ME KEEP" },+ { type: "tool_use", id: "t1", name: "Write", input: { file_path: "/wrong" } },+ ],+ stop_reason: "tool_use",+ }),+ await scopeOf(engine),+ { sink: new InboxFileSink(path), req: "j" }+ );+ expect(inboxLines(path)).toEqual([{ v: 1, kind: "stop", req: "j" }]);+ expect(res.status).toBe(200);+ expect(res.headers.get("x-upstream")).toBe("kept");+ const body = await res.json();+ expect(body.content).toEqual([+ { type: "text", text: "KEEP KEEP" },+ { type: "tool_use", id: "t1", name: "Write", input: { file_path: "/fixed" } },+ ]);+ await until(() => inboxLines(path).length === 2);+ expect(seen?.text).toBe("KEEP KEEP");+ });++ it("inserts a text block before the first tool_use when the message has no text", async () => {+ const { engine } = engineWith([rewriteHook("add", () => [act.appendText("A")])]);+ const res = await applyResponseSeam(+ jsonResponse({+ content: [+ { type: "thinking", thinking: "t", signature: "s" },+ { type: "tool_use", id: "t1", name: "R", input: {} },+ ],+ }),+ await scopeOf(engine)+ );+ expect((await res.json()).content.map((b: any) => b.type)).toEqual([+ "thinking",+ "text",+ "tool_use",+ ]);+ });++ it("passes a body that is not a message through unchanged", async () => {+ const { engine } = engineWith([rewriteHook("add", () => [act.appendText("A")])]);+ const res = await applyResponseSeam(+ new Response("not json", { headers: { "content-type": "application/json" } }),+ await scopeOf(engine)+ );+ expect(await res.text()).toBe("not json");+ });+});++/* ───────────── through withHooks ───────────── */++describe("withHooks applies the seam", () => {+ it("an accepted response with a claiming hook is rewritten; a non-2xx one is not", async () => {+ const { engine } = engineWith([rewriteHook("add", () => [act.appendText("!")])]);+ const terminal = (status: number) => ({+ async handle(c: any, body: any) {+ const hooks = (await import("./request-stage.js")).requestHooksOf(c);+ await hooks?.beginAttempt(c, {+ claudeRequest: structuredClone(body),+ route: { modelId: "m", provider: "p", native: false },+ model: "m",+ stream: true,+ });+ return status === 200+ ? sse([messageStart(), ...textBlock(0, "hi"), messageDelta(), messageStop()])+ : new Response("{}", { status });+ },+ shutdown: async () => {},+ });+ const ok = await withHooks(terminal(200), engine).handle(fakeContext(), {+ messages: [{ role: "user", content: "x" }],+ });+ expect(await ok.text()).toContain('"text":"hi!"');+ const failed = await withHooks(terminal(500), engine).handle(fakeContext(), {+ messages: [{ role: "user", content: "x" }],+ });+ expect(await failed.text()).toBe("{}");+ });+});diff --git a/packages/cli/src/test-fixtures/parser-goldens/capture.ts b/packages/cli/src/test-fixtures/parser-goldens/capture.tsdeleted file mode 100644index 9d9b3494..00000000--- a/packages/cli/src/test-fixtures/parser-goldens/capture.ts+++ /dev/null@@ -1,77 +0,0 @@-/**- * Capture the parser goldens from the CURRENT code.- *- * bun run src/test-fixtures/parser-goldens/capture.ts (from packages/cli)- *- * Writes one `<id>.golden.json` per case in `cases.ts`. It refuses to overwrite- * an existing golden: the goldens are the pre-rewrite contract, and capturing- * them again from rewritten code would make every parity check vacuous. To- * re-capture deliberately (only ever from the pre-hook parsers), delete the file- * first and say why in the commit.- *- * Every case is captured twice, 25 ms apart, so a clock- or random-derived value- * that `normalizeWire` misses shows up as a mismatch and nothing is written.- */--import { existsSync, writeFileSync } from "node:fs";--import {- GEMINI_APPLICABILITY_MODELS,- GEMINI_GOLDEN_ID,- GEMINI_MODEL,- GEMINI_SCENARIOS,- GEMINI_TOOL_SCHEMAS,- PARSER_CASES,-} from "./cases.js";-import { runGeminiCapture, runParserCase } from "./drive-current.js";-import { type Golden, goldenPath } from "./golden-format.js";--const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));--async function twice<T>(label: string, run: () => Promise<T>): Promise<T> {- const first = await run();- await pause(25);- const second = await run();- const a = JSON.stringify(first);- const b = JSON.stringify(second);- if (a !== b) {- throw new Error(`${label}: two captures differ — a nondeterministic value is not normalized`);- }- return first;-}--async function main(): Promise<void> {- const goldens: Golden[] = [];-- for (const c of PARSER_CASES) {- const output = await twice(c.id, () => runParserCase(c));- goldens.push({ kind: "parser", ...c, output });- }-- goldens.push(- await twice(GEMINI_GOLDEN_ID, () =>- runGeminiCapture(- GEMINI_GOLDEN_ID,- GEMINI_MODEL,- GEMINI_TOOL_SCHEMAS,- GEMINI_APPLICABILITY_MODELS,- GEMINI_SCENARIOS- )- )- );-- const existing = goldens.filter((g) => existsSync(goldenPath(g.id)));- if (existing.length > 0) {- console.error(- `refusing to overwrite ${existing.length} existing golden(s): ${existing.map((g) => g.id).join(", ")}`- );- process.exit(1);- }-- for (const golden of goldens) {- writeFileSync(goldenPath(golden.id), `${JSON.stringify(golden, null, 2)}\n`);- console.log(`wrote ${golden.id}`);- }-}--await main();diff --git a/packages/cli/src/test-fixtures/parser-goldens/cases.ts b/packages/cli/src/test-fixtures/parser-goldens/cases.tsindex 63c4350b..606628c1 100644--- a/packages/cli/src/test-fixtures/parser-goldens/cases.ts+++ b/packages/cli/src/test-fixtures/parser-goldens/cases.ts@@ -1,11 +1,11 @@/*** The cases captured into the parser goldens.*- * Every case of `handlers/shared/stream-parsers/behavior-repair.test.ts`, with+ * Every case of the (deleted) parser repair test `behavior-repair.test.ts`, with* its exact input frames and repair rule, plus the Devin parser (which carried* the same plumbing but had no repair test) and the Gemini thought-signature- * middleware. Only `capture.ts` and the drift check in `parser-goldens.test.ts`- * read this file; replays read the self-contained golden files.+ * middleware. Only the drift check in `parser-goldens.test.ts` reads this file;+ * replays read the self-contained golden files.*/import { readFileSync } from "node:fs";diff --git a/packages/cli/src/test-fixtures/parser-goldens/drive-current.ts b/packages/cli/src/test-fixtures/parser-goldens/drive-current.tsdeleted file mode 100644index d61a4412..00000000--- a/packages/cli/src/test-fixtures/parser-goldens/drive-current.ts+++ /dev/null@@ -1,217 +0,0 @@-/**- * Drives the CURRENT parsers — the pre-hook API, with repair plumbing on each- * parser and the Gemini middleware on `MiddlewareManager` — over golden inputs.- *- * This file is bound to the API the hook system deletes. When P4 removes the- * parser repair options and P5 removes `middleware/`, this driver goes with- * them, and the parity test drives the new parser + seam over the same golden- * files instead. The goldens themselves never change.- */--import { DefaultAPIFormat } from "../../adapters/base-api-format.js";-import { createAnthropicPassthroughStream } from "../../handlers/shared/stream-parsers/anthropic-sse.js";-import { createDevinConnectStream } from "../../handlers/shared/stream-parsers/devin-connect.js";-import { createGeminiSseStream } from "../../handlers/shared/stream-parsers/gemini-sse.js";-import { createResponsesStreamHandler } from "../../handlers/shared/stream-parsers/openai-responses-sse.js";-import { createStreamingResponseHandler } from "../../handlers/shared/stream-parsers/openai-sse.js";-import { GeminiThoughtSignatureMiddleware, MiddlewareManager } from "../../middleware/index.js";-import {- type GeminiMiddlewareGolden,- type GoldenInput,- type GoldenRepair,- type GoldenToolSchema,- type ParserGolden,- inputResponse,- normalizeWire,-} from "./golden-format.js";--/**- * The minimal Hono context the parsers touch (same stub as behavior-repair.test.ts).- *- * openai-sse also takes an adapter. behavior-repair.test.ts passed `{}`, which- * works only because its inputs carry no text: `{}` has no `processTextContent`,- * so the parser's per-chunk catch silently drops every text chunk. The goldens- * use the real `DefaultAPIFormat`, as format-translation.test.ts does; for the- * tool-only repair inputs the output is byte-identical either way.- */-const ctx: any = {- body: (stream: any, init: any) => new Response(stream, init),- json: () => {- throw new Error("Unexpected no-body error path");- },-};--interface RepairFns {- shouldBufferTool: (name: string) => boolean;- repair: (name: string, argsJson: string) => string | undefined;-}--/** The repair rule as the callbacks the old plumbing took (mirrors `fakeSession()`). */-function repairFns(repair: GoldenRepair): RepairFns | undefined {- switch (repair.kind) {- case "none":- return undefined;- case "replace":- return {- shouldBufferTool: (name) => name === repair.tool,- repair: (name) => (name === repair.tool ? repair.args : undefined),- };- case "throws":- return {- shouldBufferTool: (name) => name === repair.tool,- repair: () => {- throw new Error("synthetic repair failure");- },- };- }-}--export type ParserCaseInput = Omit<ParserGolden, "kind" | "output">;--/** Run one parser case and return the client SSE, normalized. */-export async function runParserCase(c: ParserCaseInput): Promise<string> {- const fns = repairFns(c.repair);- const upstream = inputResponse(c.input);- let out: Response;-- switch (c.parser) {- case "openai-sse":- out = createStreamingResponseHandler(- ctx,- upstream,- new DefaultAPIFormat(c.modelName),- c.modelName,- null,- undefined,- c.toolSchemas,- undefined,- undefined,- fns && {- shouldBufferTool: fns.shouldBufferTool,- onToolCall: fns.repair,- }- );- break;- case "openai-responses-sse":- out = createResponsesStreamHandler(ctx, upstream, {- modelName: c.modelName,- ...(fns ? { shouldBufferTool: fns.shouldBufferTool, onToolCall: fns.repair } : {}),- });- break;- case "anthropic-sse":- out = createAnthropicPassthroughStream(ctx, upstream, {- modelName: c.modelName,- ...(fns ? { shouldBufferTool: fns.shouldBufferTool, repairToolArgs: fns.repair } : {}),- });- break;- case "gemini-sse":- // gemini-sse never buffers (a functionCall arrives whole); the old test- // passed `repairToolArgs` alone.- out = createGeminiSseStream(ctx, upstream, {- modelName: c.modelName,- ...(fns ? { repairToolArgs: fns.repair } : {}),- });- break;- case "devin-connect":- out = createDevinConnectStream(ctx, upstream, {- modelName: c.modelName,- ...(fns ? { shouldBufferTool: fns.shouldBufferTool, repairToolArgs: fns.repair } : {}),- });- break;- }-- return normalizeWire(await out.text());-}--function runOpenAiSse(- input: GoldenInput,- modelId: string,- toolSchemas: GoldenToolSchema[],- manager: MiddlewareManager | null-): Promise<string> {- return createStreamingResponseHandler(- ctx,- inputResponse(input),- new DefaultAPIFormat(modelId),- modelId,- manager,- undefined,- toolSchemas- )- .text()- .then(normalizeWire);-}--export interface GeminiScenarioInput {- id: string;- description: string;- streams: GoldenInput[];- nextRequestMessages: unknown[];-}--/**- * Run the Gemini middleware the way ComposedHandler wires it: one middleware- * instance per handler (its cache lives as long as the handler), streams through- * openai-sse with `target = modelId`, then `beforeRequest` on the next request.- */-export async function runGeminiCapture(- id: string,- modelId: string,- toolSchemas: GoldenToolSchema[],- applicabilityModels: string[],- scenarios: GeminiScenarioInput[]-): Promise<GeminiMiddlewareGolden> {- const probe = new GeminiThoughtSignatureMiddleware();- const applicability = applicabilityModels.map((m) => {- const manager = new MiddlewareManager();- manager.register(new GeminiThoughtSignatureMiddleware());- return {- modelId: m,- shouldHandle: probe.shouldHandle(m),- activeNames: manager.getActiveNames(m),- };- });-- const outScenarios: GeminiMiddlewareGolden["scenarios"] = [];- for (const scenario of scenarios) {- const manager = new MiddlewareManager();- manager.register(new GeminiThoughtSignatureMiddleware());- await manager.initialize();-- const streams: GeminiMiddlewareGolden["scenarios"][number]["streams"] = [];- for (const input of scenario.streams) {- const output = await runOpenAiSse(input, modelId, toolSchemas, manager);- const without = await runOpenAiSse(input, modelId, toolSchemas, null);- streams.push({ input, output, outputUnchangedByMiddleware: output === without });- }-- const before = structuredClone(scenario.nextRequestMessages) as any[];- const messages = structuredClone(scenario.nextRequestMessages) as any[];- await manager.beforeRequest({- modelId,- messages,- tools: [],- stream: true,- claudeRequest: {},- claudeTools: [],- });- // Round-trip through JSON: the golden records what reaches the wire.- const after = JSON.parse(JSON.stringify(messages));-- outScenarios.push({- id: scenario.id,- description: scenario.description,- streams,- nextRequest: { before, after },- });- }-- return {- kind: "gemini-middleware",- id,- modelId,- toolSchemas,- applicability,- scenarios: outScenarios,- };-}diff --git a/packages/cli/src/test-fixtures/parser-goldens/drive-gemini-middleware.ts b/packages/cli/src/test-fixtures/parser-goldens/drive-gemini-middleware.tsnew file mode 100644index 00000000..27711ea5--- /dev/null+++ b/packages/cli/src/test-fixtures/parser-goldens/drive-gemini-middleware.ts@@ -0,0 +1,120 @@+/**+ * Drives the Gemini thought-signature middleware the way ComposedHandler wires+ * it today (`MiddlewareManager`, openai-sse), over the Gemini golden.+ *+ * Bound to `middleware/`, which the raw tier replaces; this driver goes with+ * it, and the Gemini built-in's parity test drives the same golden through the+ * hook raw tier instead. The golden itself never changes.+ */++import { DefaultAPIFormat } from "../../adapters/base-api-format.js";+import { createStreamingResponseHandler } from "../../handlers/shared/stream-parsers/openai-sse.js";+import { GeminiThoughtSignatureMiddleware, MiddlewareManager } from "../../middleware/index.js";+import {+ type GeminiMiddlewareGolden,+ type GoldenInput,+ type GoldenToolSchema,+ inputResponse,+ normalizeWire,+} from "./golden-format.js";++/** The minimal Hono context the parser touches. */+const ctx: any = {+ body: (stream: any, init: any) => new Response(stream, init),+ json: () => {+ throw new Error("Unexpected no-body error path");+ },+};++function runOpenAiSse(+ input: GoldenInput,+ modelId: string,+ toolSchemas: GoldenToolSchema[],+ manager: MiddlewareManager | null+): Promise<string> {+ return createStreamingResponseHandler(+ ctx,+ inputResponse(input),+ new DefaultAPIFormat(modelId),+ modelId,+ manager,+ undefined,+ toolSchemas+ )+ .text()+ .then(normalizeWire);+}++export interface GeminiScenarioInput {+ id: string;+ description: string;+ streams: GoldenInput[];+ nextRequestMessages: unknown[];+}++/**+ * Run the Gemini middleware the way ComposedHandler wires it: one middleware+ * instance per handler (its cache lives as long as the handler), streams through+ * openai-sse with `target = modelId`, then `beforeRequest` on the next request.+ */+export async function runGeminiCapture(+ id: string,+ modelId: string,+ toolSchemas: GoldenToolSchema[],+ applicabilityModels: string[],+ scenarios: GeminiScenarioInput[]+): Promise<GeminiMiddlewareGolden> {+ const probe = new GeminiThoughtSignatureMiddleware();+ const applicability = applicabilityModels.map((m) => {+ const manager = new MiddlewareManager();+ manager.register(new GeminiThoughtSignatureMiddleware());+ return {+ modelId: m,+ shouldHandle: probe.shouldHandle(m),+ activeNames: manager.getActiveNames(m),+ };+ });++ const outScenarios: GeminiMiddlewareGolden["scenarios"] = [];+ for (const scenario of scenarios) {+ const manager = new MiddlewareManager();+ manager.register(new GeminiThoughtSignatureMiddleware());+ await manager.initialize();++ const streams: GeminiMiddlewareGolden["scenarios"][number]["streams"] = [];+ for (const input of scenario.streams) {+ const output = await runOpenAiSse(input, modelId, toolSchemas, manager);+ const without = await runOpenAiSse(input, modelId, toolSchemas, null);+ streams.push({ input, output, outputUnchangedByMiddleware: output === without });+ }++ const before = structuredClone(scenario.nextRequestMessages) as any[];+ const messages = structuredClone(scenario.nextRequestMessages) as any[];+ await manager.beforeRequest({+ modelId,+ messages,+ tools: [],+ stream: true,+ claudeRequest: {},+ claudeTools: [],+ });+ // Round-trip through JSON: the golden records what reaches the wire.+ const after = JSON.parse(JSON.stringify(messages));++ outScenarios.push({+ id: scenario.id,+ description: scenario.description,+ streams,+ nextRequest: { before, after },+ });+ }++ return {+ kind: "gemini-middleware",+ id,+ modelId,+ toolSchemas,+ applicability,+ scenarios: outScenarios,+ };+}diff --git a/packages/cli/src/test-fixtures/parser-goldens/drive-seam.ts b/packages/cli/src/test-fixtures/parser-goldens/drive-seam.tsnew file mode 100644index 00000000..32901fcf--- /dev/null+++ b/packages/cli/src/test-fixtures/parser-goldens/drive-seam.ts@@ -0,0 +1,125 @@+/**+ * Drives a golden case through the code that replaced the parsers' repair+ * plumbing: the parser (which no longer repairs anything) and then the hook+ * response seam, with the golden's repair rule expressed as a `toolCall` hook.+ *+ * - `none`: no hook; the seam is the identity, so the parser's own bytes reach+ * the client.+ * - `replace`: a fix-severity hook armed for `tool` returns+ * `repairToolArgs(args)`; the seam holds that tool's block and finishes it+ * with one delta carrying the repaired arguments.+ * - `throws`: the same hook throws on every call; the engine fails open and the+ * seam forwards the model's own arguments.+ */++import { DefaultAPIFormat } from "../../adapters/base-api-format.js";+import { createAnthropicPassthroughStream } from "../../handlers/shared/stream-parsers/anthropic-sse.js";+import { createDevinConnectStream } from "../../handlers/shared/stream-parsers/devin-connect.js";+import { createGeminiSseStream } from "../../handlers/shared/stream-parsers/gemini-sse.js";+import { createResponsesStreamHandler } from "../../handlers/shared/stream-parsers/openai-responses-sse.js";+import { createStreamingResponseHandler } from "../../handlers/shared/stream-parsers/openai-sse.js";+import { HookEngine } from "../../hooks/engine.js";+import { UnavailableSink } from "../../hooks/injection/sinks.js";+import { type HookDefinition, act } from "../../hooks/public.js";+import { HookRegistry } from "../../hooks/registry.js";+import { type HookRequestScope, RequestHooks } from "../../hooks/request-stage.js";+import { applyResponseSeam } from "../../hooks/response-seam.js";+import {+ type GoldenRepair,+ type ParserGolden,+ inputResponse,+ normalizeWire,+} from "./golden-format.js";++/** The minimal Hono context the parsers and the request stage touch. */+function context(): any {+ const vars = new Map<string, unknown>();+ return {+ body: (stream: any, init: any) => new Response(stream, init),+ json: () => {+ throw new Error("Unexpected no-body error path");+ },+ get: (k: string) => vars.get(k),+ set: (k: string, v: unknown) => vars.set(k, v),+ };+}++/** The golden's repair rule as a hook definition. */+export function repairHook(repair: Exclude<GoldenRepair, { kind: "none" }>): HookDefinition {+ return {+ apiVersion: 1,+ id: "repair",+ on: {+ toolCall: {+ tools: [repair.tool],+ handle: () => {+ if (repair.kind === "throws") throw new Error("synthetic repair failure");+ return [act.repairToolArgs(JSON.parse(repair.args), "golden repair")];+ },+ },+ },+ };+}++/** A request scope whose only hook is `def`, as `withHooks` + a terminal handler would build it. */+export async function scopeWith(+ def: HookDefinition,+ modelName: string,+ c: any = context()+): Promise<HookRequestScope> {+ const engine = new HookEngine({+ registry: new HookRegistry(+ [],+ [{ id: `hook:golden/${def.id}`, module: "/golden.ts", moduleIndex: 0, exportIndex: 0, def }],+ undefined+ ),+ config: {},+ hostMode: "other",+ journalSink: () => {},+ warn: () => {},+ drainTelemetryOutbox: false,+ });+ return new RequestHooks(engine, null, new UnavailableSink(() => {})).beginAttempt(c, {+ claudeRequest: { messages: [{ role: "user", content: "golden" }] },+ route: { modelId: modelName, provider: "golden", native: false },+ model: modelName,+ stream: true,+ });+}++export type ParserCaseInput = Omit<ParserGolden, "kind" | "output">;++/** The parser's own output for a case: no repair plumbing exists any more. */+export function runParser(c: ParserCaseInput): Response {+ const ctx = context();+ const upstream = inputResponse(c.input);+ switch (c.parser) {+ case "openai-sse":+ return createStreamingResponseHandler(+ ctx,+ upstream,+ new DefaultAPIFormat(c.modelName),+ c.modelName,+ null,+ undefined,+ c.toolSchemas+ );+ case "openai-responses-sse":+ return createResponsesStreamHandler(ctx, upstream, { modelName: c.modelName });+ case "anthropic-sse":+ return createAnthropicPassthroughStream(ctx, upstream, { modelName: c.modelName });+ case "gemini-sse":+ return createGeminiSseStream(ctx, upstream, { modelName: c.modelName });+ case "devin-connect":+ return createDevinConnectStream(ctx, upstream, { modelName: c.modelName });+ }+}++/** Run one case through parser + seam and return the client SSE, normalized. */+export async function runParserCase(c: ParserCaseInput): Promise<string> {+ let out = runParser(c);+ if (c.repair.kind !== "none") {+ out = await applyResponseSeam(out, await scopeWith(repairHook(c.repair), c.modelName));+ }+ return normalizeWire(await out.text());+}diff --git a/packages/cli/src/test-fixtures/parser-goldens/golden-format.ts b/packages/cli/src/test-fixtures/parser-goldens/golden-format.tsindex 016730a6..367169ca 100644--- a/packages/cli/src/test-fixtures/parser-goldens/golden-format.ts+++ b/packages/cli/src/test-fixtures/parser-goldens/golden-format.ts@@ -1,5 +1,5 @@/**- * Parser goldens — the format shared by the capture script and every test that+ * Parser goldens — the format shared by every test that* replays them.** A golden is a snapshot of what the stream parsers emitted BEFORE the hook@@ -10,7 +10,8 @@* repair rule as data, and the Claude SSE that reached the client.** Never re-capture to make a parity test pass. A golden captured from the new- * code proves the new code equals itself. `capture.ts` refuses to overwrite.+ * code proves the new code equals itself. The capture script was deleted with+ * the pre-hook parser API it drove (P4); the files are now read-only fixtures.*/import { readFileSync, readdirSync } from "node:fs";@@ -164,14 +165,12 @@ export function inputResponse(input: GoldenInput): Response {/*** Replace the only clock- and random-derived values the parsers emit, so a- * capture is reproducible:+ * replay is comparable:** - message ids: `msg_<ms>` and `msg_<ms>_<random>`* - synthesized tool ids: `tool_<ms>_<n>`, `toolu_<ms>_<n>`, `tool_repaired_<ms>_<n>`** Everything else, keep-alive `ping` events included, is kept byte for byte.- * The capture script runs every case twice, apart in time, and refuses to write- * a golden whose two normalized captures differ.*/export function normalizeWire(wire: string): string {return wirediff --git a/packages/cli/src/test-fixtures/parser-goldens/parser-goldens.test.ts b/packages/cli/src/test-fixtures/parser-goldens/parser-goldens.test.tsindex a8c61599..07ad77fb 100644--- a/packages/cli/src/test-fixtures/parser-goldens/parser-goldens.test.ts+++ b/packages/cli/src/test-fixtures/parser-goldens/parser-goldens.test.ts@@ -1,13 +1,13 @@/**- * P0 — the current parsers reproduce the parser goldens.+ * Parser parity: the parsers plus the hook response seam reproduce the goldens+ * captured from the pre-hook parsers (P0, base 2e4ac246).*- * The goldens are the pre-hook contract that the response seam (P4) and the- * Gemini built-in (P5) must keep. This file proves they were captured from, and- * still describe, the code at the capture base: every golden replays to its- * recorded output through the CURRENT parser API (`drive-current.ts`).- *- * When P4/P5 delete that API, the replay half moves to a driver over the new- * parser + seam; the coverage, drift and meaning checks stay as they are.+ * Tool-argument repair moved out of five parsers into one seam above them.+ * Every parser golden replays through the new parser + seam (`drive-seam.ts`)+ * to its recorded output, byte for byte after normalization, except the one+ * golden that recorded a defect of the old code, which is compared by its data+ * payloads. The Gemini middleware golden still replays through `middleware/`+ * (`drive-gemini-middleware.ts`) until the raw tier replaces it.*/import { describe, expect, it } from "bun:test";@@ -23,7 +23,8 @@ import {REPAIRED_ARGS,REPAIRED_VALUE,} from "./cases.js";-import { runGeminiCapture, runParserCase } from "./drive-current.js";+import { runGeminiCapture } from "./drive-gemini-middleware.js";+import { runParserCase } from "./drive-seam.js";import {type GeminiMiddlewareGolden,type ParserGolden,@@ -69,11 +70,22 @@ describe("parser goldens: coverage and drift", () => {});});-describe("parser goldens: the current parsers reproduce them", () => {+describe("parser goldens: parser + response seam reproduce them", () => {for (const c of PARSER_CASES) {it(c.id, async () => {const golden = parserGolden(c.id);- expect(await runParserCase(golden)).toBe(golden.output);+ const replay = await runParserCase(golden);+ if (golden.defect) {+ // The old wire framed the repaired delta and the stop wrongly; the seam+ // must send the same payloads, in order, each under its own event name.+ expect(dataPayloads(replay)).toEqual(dataPayloads(golden.output));+ expect(replay).not.toContain("event: content_block_stop\nevent: content_block_delta\n");+ expect(replay).toContain(+ 'event: content_block_stop\ndata: {"type":"content_block_stop","index":0}'+ );+ } else {+ expect(replay).toBe(golden.output);+ }});}