Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(hooks): replace MiddlewareManager with the raw hook tier
Jack Rudenko6057c0c6a00b
diff --git a/packages/cli/src/adapters/devin-api-format.ts b/packages/cli/src/adapters/devin-api-format.tsindex 05e3c984..3c330e2d 100644--- a/packages/cli/src/adapters/devin-api-format.ts+++ b/packages/cli/src/adapters/devin-api-format.ts@@ -8,14 +8,13 @@* inherited `convertMessagesToOpenAI` / `convertToolsToOpenAI` already handle* the hard parts of Claude Messages (block arrays, `tool_use`/`tool_result`* pairing, system extraction, identity filtering) — and, decisively, they- * produce the shape that every middleware and every Layer 4 rule already+ * produce the shape that every raw hook and every built-in hook already* understands:*- * - `middlewareManager.beforeRequest({ messages, tools, … })` mutates- * OpenAI-shaped objects at ComposedHandler step 3b.- * - `behaviorSession.applyRequest(claudeRequest, claudeTools, tools, messages)`- * reads OpenAI-shaped tools for `rewriteToolDescription` — the mechanism the- * `plan-mode/plan-file-path` rule depends on.+ * - raw `providerRequest` hooks edit OpenAI-shaped `messages` and `tools` at+ * ComposedHandler step 3b.+ * - request stage B reads OpenAI-shaped tools for `rewriteToolDescription` —+ * the mechanism the `plan-mode/plan-file-path` hook depends on.** Inventing a bespoke Devin message shape here would silently disable both for* this provider. {@link buildPayload} therefore does the Devin-specific mappingdiff --git a/packages/cli/src/handlers/composed-handler-raw.test.ts b/packages/cli/src/handlers/composed-handler-raw.test.tsnew file mode 100644index 00000000..b750d2a8--- /dev/null+++ b/packages/cli/src/handlers/composed-handler-raw.test.ts@@ -0,0 +1,872 @@+/**+ * The raw (unsafe) tier end to end: a ComposedHandler through `withHooks`, a+ * stubbed upstream replaying scripted provider events, and hook modules written+ * to a temp dir and loaded by the real loader. Assertions are on what the+ * client reads and what the transport receives.+ *+ * X-1 … X-8 are the architecture's §11.5 rows for transactional containment+ * and the parser commit; the rest cover `providerRequest` containment, warn+ * severity, and a replacement that succeeds or fails.+ */++import { afterAll, afterEach, describe, expect, it } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { AnthropicAPIFormat } from "../adapters/anthropic-api-format.js";+import { OpenAIAPIFormat } from "../adapters/openai-api-format.js";+import { HookEngine } from "../hooks/engine.js";+import type { JournalEntry } from "../hooks/journal.js";+import { loadUserHooks } from "../hooks/loader.js";+import { HookRegistry } from "../hooks/registry.js";+import { withHooks } from "../hooks/response-seam.js";+import type { ProviderTransport } from "../providers/transport/types.js";+import { stripPings } from "../test-fixtures/parser-goldens/golden-format.js";+import { ComposedHandler } from "./composed-handler.js";++const realFetch = globalThis.fetch;+const dir = mkdtempSync(join(tmpdir(), "claudish-raw-"));+const g = globalThis as Record<string, any>;++afterEach(() => {+ globalThis.fetch = realFetch;+});+afterAll(() => rmSync(dir, { recursive: true, force: true }));++const encoder = new TextEncoder();++/* ───────────── upstream ───────────── */++interface Source {+ /** Chunks the source has handed out. */+ released: number;+ closed: boolean;+}++/** Stub fetch: answer with `chunks`, optionally one per `delayMs`, recording the request body. */+function stubUpstream(+ chunks: string[],+ opts: { delayMs?: number; json?: boolean } = {}+): { source: Source; bodies: any[] } {+ const source: Source = { released: 0, closed: false };+ const bodies: any[] = [];+ globalThis.fetch = (async (_url: unknown, init?: RequestInit) => {+ if (typeof init?.body === "string") bodies.push(JSON.parse(init.body));+ let i = 0;+ return new Response(+ new ReadableStream<Uint8Array>({+ async pull(controller) {+ if (opts.delayMs) await Bun.sleep(opts.delayMs);+ if (i >= chunks.length) {+ source.closed = true;+ controller.close();+ return;+ }+ controller.enqueue(encoder.encode(chunks[i++] as string));+ source.released = i;+ },+ }),+ {+ status: 200,+ headers: { "content-type": opts.json ? "application/json" : "text/event-stream" },+ }+ );+ }) as unknown as typeof fetch;+ return { source, bodies };+}++function transport(streamFormat: string): ProviderTransport {+ return {+ name: "test-provider",+ displayName: "Test",+ streamFormat,+ overrideStreamFormat: () => 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),+ };+}++const MODEL = "test-model";++function handler(format: "openai-sse" | "openai-responses-sse" | "anthropic-sse") {+ const adapter =+ format === "anthropic-sse" ? new AnthropicAPIFormat(MODEL) : new OpenAIAPIFormat(MODEL);+ return new ComposedHandler(transport(format), MODEL, MODEL, 8080, { adapter });+}++function payload(stream = true): any {+ return {+ model: MODEL,+ max_tokens: 64,+ stream,+ system: "You are a test.",+ messages: [{ role: "user", content: "Say something." }],+ tools: [+ {+ name: "Read",+ description: "Read a file",+ input_schema: { type: "object", properties: { file_path: { type: "string" } } },+ },+ ],+ };+}++/* ───────────── hooks ───────────── */++let moduleSeq = 0;++/** Write `source` as a hook module, load it with the real loader, build an engine over it. */+async function loadHook(source: string, severity?: Record<string, "off" | "warn" | "fix">) {+ const name = `rawhook${++moduleSeq}`;+ // One directory per module: Bun's resolver caches a directory's entries on+ // first import, so a file written later into the same directory is not found.+ const moduleDir = mkdtempSync(join(dir, "m-"));+ const path = join(moduleDir, `${name}.ts`);+ writeFileSync(path, source);+ const loadWarnings: string[] = [];+ const loaded = await loadUserHooks({+ modules: [path],+ configDir: moduleDir,+ hostMode: "other",+ warn: (l) => loadWarnings.push(l),+ });+ const journal: JournalEntry[] = [];+ const engineWarnings: string[] = [];+ const engine = new HookEngine({+ registry: new HookRegistry([], loaded.hooks, severity),+ config: {},+ hostMode: "other",+ journalSink: (e) => journal.push(e),+ warn: (l) => engineWarnings.push(l),+ drainTelemetryOutbox: false,+ });+ return { name, engine, journal, loadWarnings, engineWarnings, loaded };+}++/* ───────────── wire ───────────── */++const openAiFrame = (data: unknown) => `data: ${JSON.stringify(data)}\n\n`;+const anthropicFrame = (event: string, data: unknown) =>+ `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;++function payloads(wire: string): any[] {+ const out: any[] = [];+ for (const line of wire.split("\n")) {+ if (!line.startsWith("data: ") || line === "data: [DONE]") continue;+ try {+ out.push(JSON.parse(line.slice(6)));+ } catch {+ // not JSON+ }+ }+ return out;+}++function textOf(wire: string): string {+ return payloads(wire)+ .filter((p) => p.type === "content_block_delta" && p.delta?.type === "text_delta")+ .map((p) => p.delta.text)+ .join("");+}++function thinkingOf(wire: string): string {+ return payloads(wire)+ .filter((p) => p.type === "content_block_delta" && p.delta?.type === "thinking_delta")+ .map((p) => p.delta.thinking)+ .join("");+}++function stopReasonOf(wire: string): string | undefined {+ return payloads(wire).find((p) => p.type === "message_delta")?.delta?.stop_reason;+}++const responsesEvent = (data: Record<string, unknown>) =>+ `event: ${data.type}\ndata: ${JSON.stringify(data)}\n\n`;++function responsesStream(deltas: string[]): string[] {+ return [+ responsesEvent({ type: "response.created", response: { id: "resp_1" } }),+ ...deltas.map((d) => responsesEvent({ type: "response.output_text.delta", delta: d })),+ responsesEvent({+ type: "response.completed",+ response: { id: "resp_1", usage: { input_tokens: 5, output_tokens: 3 } },+ }),+ ];+}++/** An 8-event Claude SSE message (anthropic-sse passthrough). */+function claudeMessage(text = "original answer"): string[] {+ const half = Math.floor(text.length / 2);+ return [+ anthropicFrame("message_start", {+ type: "message_start",+ message: {+ id: "msg_raw",+ type: "message",+ role: "assistant",+ content: [],+ model: MODEL,+ usage: { input_tokens: 5, output_tokens: 1 },+ },+ }),+ anthropicFrame("content_block_start", {+ type: "content_block_start",+ index: 0,+ content_block: { type: "text", text: "" },+ }),+ anthropicFrame("content_block_delta", {+ type: "content_block_delta",+ index: 0,+ delta: { type: "text_delta", text: text.slice(0, half) },+ }),+ anthropicFrame("content_block_delta", {+ type: "content_block_delta",+ index: 0,+ delta: { type: "text_delta", text: text.slice(half) },+ }),+ anthropicFrame("content_block_stop", { type: "content_block_stop", index: 0 }),+ anthropicFrame("message_delta", {+ type: "message_delta",+ delta: { stop_reason: "end_turn", stop_sequence: null },+ usage: { output_tokens: 4 },+ }),+ anthropicFrame("message_stop", { type: "message_stop" }),+ anthropicFrame("ping", { type: "ping" }),+ ];+}++/** The same upstream through the same route with no hooks: what "the original" is. */+async function originalWire(format: "anthropic-sse", chunks: string[]): Promise<string> {+ stubUpstream(chunks);+ return stripPings(await (await handler(format).handle(context(), payload())).text());+}++async function settle(ms = 20): Promise<void> {+ await Bun.sleep(ms);+}++/* ───────────── X-1 … X-5: providerChunk ───────────── */++describe("X-1: a providerChunk that mutates and then returns a rejecting promise", () => {+ it("openai-sse: the client gets the original text; invalid + error journaled; no unhandledRejection", async () => {+ const unhandled: unknown[] = [];+ const onUnhandled = (r: unknown) => unhandled.push(r);+ process.on("unhandledRejection", onUnhandled);+ try {+ const h = await loadHook(`+ export default {+ apiVersion: 1, id: "x1", unsafe: true,+ raw: {+ providerChunk(ctx) {+ if (ctx.delta && "content" in ctx.delta) ctx.delta.content = "CORRUPTED";+ return Promise.reject(new Error("x"));+ },+ },+ };`);+ stubUpstream([+ openAiFrame({ choices: [{ delta: { role: "assistant", content: "original" } }] }),+ openAiFrame({ choices: [{ delta: {}, finish_reason: "stop" }] }),+ "data: [DONE]\n\n",+ ]);+ const wire = await (+ await withHooks(handler("openai-sse"), h.engine).handle(context(), payload())+ ).text();+ await settle();++ expect(textOf(wire)).toBe("original");+ expect(wire).not.toContain("CORRUPTED");+ const lines = h.journal.filter((e) => e.hookId === `hook:${h.name}/x1`);+ expect(+ lines.some((e) => e.decision === "invalid" && e.detail?.includes("async_return"))+ ).toBe(true);+ expect(lines.some((e) => e.decision === "error" && e.detail?.includes("x"))).toBe(true);+ expect(unhandled).toEqual([]);+ } finally {+ process.off("unhandledRejection", onUnhandled);+ }+ });++ it("openai-responses-sse: ctx.delta.delta = CORRUPTED never reaches the client", async () => {+ const h = await loadHook(`+ export default {+ apiVersion: 1, id: "x1r", unsafe: true,+ raw: {+ providerChunk(ctx) {+ if (typeof ctx.delta?.delta === "string") ctx.delta.delta = "CORRUPTED";+ return Promise.reject(new Error("x"));+ },+ },+ };`);+ stubUpstream(responsesStream(["original"]));+ const wire = await (+ await withHooks(handler("openai-responses-sse"), h.engine).handle(context(), payload())+ ).text();+ await settle();+ expect(textOf(wire)).toBe("original");+ expect(wire).not.toContain("CORRUPTED");+ });+});++describe("X-2: any thenable return is invalid, and five trip the breaker", () => {+ it("8 chunks: the client text is the original's; 5 invalid, then disabled with one stderr line", async () => {+ g.__x2calls = 0;+ const h = await loadHook(`+ export default {+ apiVersion: 1, id: "x2", unsafe: true,+ raw: {+ providerChunk(ctx) {+ globalThis.__x2calls++;+ if (ctx.delta && "content" in ctx.delta) ctx.delta.content = "CORRUPTED";+ return Promise.resolve();+ },+ },+ };`);+ const parts = ["c1 ", "c2 ", "c3 ", "c4 ", "c5 ", "c6 ", "c7 ", "c8"];+ stubUpstream([+ ...parts.map((p) => openAiFrame({ choices: [{ delta: { content: p } }] })),+ openAiFrame({ choices: [{ finish_reason: "stop" }] }),+ "data: [DONE]\n\n",+ ]);+ const wire = await (+ await withHooks(handler("openai-sse"), h.engine).handle(context(), payload())+ ).text();+ await settle();++ expect(textOf(wire)).toBe(parts.join(""));+ const lines = h.journal.filter((e) => e.hookId === `hook:${h.name}/x2`);+ expect(lines.filter((e) => e.decision === "invalid")).toHaveLength(5);+ expect(lines.filter((e) => e.decision === "disabled")).toHaveLength(1);+ expect(h.engineWarnings).toHaveLength(1);+ expect(h.engineWarnings[0]).toContain("disabled");+ // Chunks 6 to 8 passed without a hook call.+ expect(g.__x2calls).toBe(5);+ });+});++describe("X-3: a declared async providerChunk is rejected at load", () => {+ it("the load warns once, registers the other hook, and never calls the async one", async () => {+ g.__x3calls = { sync: 0, async: 0 };+ const h = await loadHook(`+ export default [+ { apiVersion: 1, id: "async-one", unsafe: true,+ raw: { async providerChunk() { globalThis.__x3calls.async++; } } },+ { apiVersion: 1, id: "sync-one", unsafe: true,+ raw: { providerChunk() { globalThis.__x3calls.sync++; } } },+ ];`);+ const mustBeSync = h.loadWarnings.filter((l) =>+ l.includes("raw.providerChunk must be synchronous")+ );+ expect(mustBeSync).toHaveLength(1);+ expect(h.loaded.hooks.map((u) => u.id)).toEqual([`hook:${h.name}/sync-one`]);++ stubUpstream([+ openAiFrame({ choices: [{ delta: { content: "hi" } }] }),+ openAiFrame({ choices: [{ delta: {}, finish_reason: "stop" }] }),+ "data: [DONE]\n\n",+ ]);+ await (await withHooks(handler("openai-sse"), h.engine).handle(context(), payload())).text();+ expect(g.__x3calls.async).toBe(0);+ expect(g.__x3calls.sync).toBeGreaterThan(0);+ });+});++const X4_HOOK = `+ export default {+ apiVersion: 1, id: "x4", unsafe: true,+ raw: {+ providerChunk(ctx) {+ delete ctx.delta.reasoning_content;+ if ("content" in ctx.delta) ctx.delta.content = "rewritten";+ if (ctx.chunk.choices[0].finish_reason === "length") ctx.chunk.choices[0].finish_reason = "stop";+ },+ },+ };`;++function x4Upstream() {+ return stubUpstream([+ openAiFrame({ choices: [{ delta: { reasoning_content: "R" } }] }),+ openAiFrame({ choices: [{ delta: { content: "original" } }] }),+ openAiFrame({ choices: [{ delta: {}, finish_reason: "length" }] }),+ "data: [DONE]\n\n",+ ]);+}++describe("X-4: the parser reads the committed chunk (openai-sse)", () => {+ it("a deletion, a delta edit and a finish_reason change all reach the client", async () => {+ const h = await loadHook(X4_HOOK);+ x4Upstream();+ const wire = await (+ await withHooks(handler("openai-sse"), h.engine).handle(context(), payload())+ ).text();+ expect(thinkingOf(wire)).toBe("");+ expect(textOf(wire)).toBe("rewritten");+ expect(stopReasonOf(wire)).toBe("end_turn");+ expect(h.journal.some((e) => e.hookId === `hook:${h.name}/x4` && e.decision === "raw")).toBe(+ true+ );+ });++ it("control: the same hook at warn commits nothing", async () => {+ const h = await loadHook(X4_HOOK, { "hook:*": "warn" });+ x4Upstream();+ const wire = await (+ await withHooks(handler("openai-sse"), h.engine).handle(context(), payload())+ ).text();+ expect(thinkingOf(wire)).toBe("R");+ expect(textOf(wire)).toBe("original");+ expect(stopReasonOf(wire)).toBe("max_tokens");+ const warned = h.journal.filter((e) => e.decision === "warned");+ // Once per hook and stage, not once per chunk.+ expect(warned).toHaveLength(1);+ });+});++describe("X-5: the parser reads the committed event (openai-responses-sse)", () => {+ it("upper-casing ctx.delta.delta reaches the client", async () => {+ const h = await loadHook(`+ export default {+ apiVersion: 1, id: "x5", unsafe: true,+ raw: {+ providerChunk(ctx) {+ if (typeof ctx.delta.delta === "string") ctx.delta.delta = ctx.delta.delta.toUpperCase();+ },+ },+ };`);+ stubUpstream(responsesStream(["orig", "inal"]));+ const wire = await (+ await withHooks(handler("openai-responses-sse"), h.engine).handle(context(), payload())+ ).text();+ expect(textOf(wire)).toBe("ORIGINAL");+ });+});++/* ───────────── X-6 … X-8: response ───────────── */++// Starts on the same line as the expression it is spliced after: a line break+// right after \`return\` would return undefined.+const NEVER_CLOSING = `new Response(new ReadableStream({+ pull() { return new Promise(() => {}); },+ cancel() { globalThis.__replacementCancels++; },+ }), { headers: { "content-type": "text/event-stream" } })`;++describe("X-6: an ignored view and a never-closing replacement", () => {+ it("the original is drained by claudish and forwarded from its first byte after the deadline", async () => {+ const chunks = claudeMessage();+ const expected = await originalWire("anthropic-sse", chunks);++ g.__replacementCancels = 0;+ const h = await loadHook(`+ export default {+ apiVersion: 1, id: "x6", unsafe: true, timeoutMs: 300,+ raw: { response() { return ${NEVER_CLOSING}; } },+ };`);+ const { source } = stubUpstream(chunks);+ const res = await withHooks(handler("anthropic-sse"), h.engine).handle(context(), payload());++ const started = Date.now();+ const reader = res.body!.getReader();+ const decoder = new TextDecoder();+ let wire = "";+ let firstOriginalAt = 0;+ for (;;) {+ const r = await reader.read();+ if (r.done) break;+ const text = decoder.decode(r.value);+ if (!firstOriginalAt && stripPings(text).length > 0) firstOriginalAt = Date.now() - started;+ wire += text;+ }++ // The source was drained to its end with nobody reading the hook's view.+ expect(source.released).toBe(chunks.length);+ expect(source.closed).toBe(true);+ // Pings while the replacement was held, then the original from its first byte.+ expect(wire.startsWith("event: ping\n")).toBe(true);+ expect(stripPings(wire)).toBe(expected);+ expect(firstOriginalAt).toBeGreaterThanOrEqual(250);+ expect(wire).not.toContain("event: error");+ await settle();+ expect(g.__replacementCancels).toBe(1);+ expect(+ h.journal.some(+ (e) => e.hookId === `hook:${h.name}/x6` && e.decision === "timeout" && e.event === "raw"+ )+ ).toBe(true);+ });+});++describe("X-7: a partly read view, then a never-closing replacement", () => {+ it("behaves as X-6", async () => {+ const chunks = claudeMessage();+ const expected = await originalWire("anthropic-sse", chunks);++ g.__replacementCancels = 0;+ const h = await loadHook(`+ export default {+ apiVersion: 1, id: "x7", unsafe: true, timeoutMs: 300,+ raw: {+ async response(ctx) {+ const reader = ctx.response.body.getReader();+ await reader.read();+ await reader.read();+ return ${NEVER_CLOSING};+ },+ },+ };`);+ const { source } = stubUpstream(chunks);+ const res = await withHooks(handler("anthropic-sse"), h.engine).handle(context(), payload());+ const wire = await res.text();++ expect(source.released).toBe(chunks.length);+ expect(source.closed).toBe(true);+ expect(wire.startsWith("event: ping\n")).toBe(true);+ expect(stripPings(wire)).toBe(expected);+ expect(wire).not.toContain("event: error");+ await settle();+ expect(g.__replacementCancels).toBe(1);+ expect(h.journal.some((e) => e.decision === "timeout" && e.event === "raw")).toBe(true);+ });+});++describe("X-8: nothing returned", () => {+ it("the original streams as it arrives, byte for byte, with no failure journaled", async () => {+ const chunks = claudeMessage();+ const expected = await originalWire("anthropic-sse", chunks);++ const h = await loadHook(`+ export default {+ apiVersion: 1, id: "x8", unsafe: true,+ raw: { response() { return undefined; } },+ };`);+ const { source } = stubUpstream(chunks, { delayMs: 50 });+ const res = await withHooks(handler("anthropic-sse"), h.engine).handle(context(), payload());++ const reader = res.body!.getReader();+ const decoder = new TextDecoder();+ let wire = "";+ let releasedAtFirstChunk = -1;+ for (;;) {+ const r = await reader.read();+ if (r.done) break;+ const text = decoder.decode(r.value);+ if (releasedAtFirstChunk < 0 && stripPings(text).length > 0) {+ releasedAtFirstChunk = source.released;+ }+ wire += text;+ }++ expect(releasedAtFirstChunk).toBeGreaterThan(0);+ expect(releasedAtFirstChunk).toBeLessThan(3);+ expect(stripPings(wire)).toBe(expected);+ expect(h.journal.some((e) => ["error", "timeout", "invalid"].includes(e.decision))).toBe(false);+ });+});++/* ───────────── the hook's view never shares bytes with the fallback ───────────── */++describe("a raw response hook that edits the bytes it read in place", () => {+ /** Reads the first chunk of ctx.response, overwrites it in place, then ends with `tail`. */+ const editor = (id: string, tail: string, async = true) => `+ export default {+ apiVersion: 1, id: "${id}", unsafe: true,+ raw: {+ ${async ? "async " : ""}response(ctx) {+ const reader = ctx.response.body.getReader();+ return reader.read().then((r) => {+ if (r.value) r.value.fill(0x58);+ ${tail}+ });+ },+ },+ };`;++ for (const [name, tail, severity] of [+ ["throws (fix)", `throw new Error("edited, then failed");`, "fix"],+ ["returns nothing (fix)", "return undefined;", "fix"],+ ["returns a replacement (warn)", `return new Response("event: ping\\n\\n");`, "warn"],+ ] as const) {+ it(`${name}: the client receives the original bytes`, async () => {+ const chunks = claudeMessage();+ const expected = await originalWire("anthropic-sse", chunks);+ const h = await loadHook(editor(`cr3${name.length}`, tail), { "hook:*": severity });+ stubUpstream(chunks, { delayMs: 20 });+ const wire = await (+ await withHooks(handler("anthropic-sse"), h.engine).handle(context(), payload())+ ).text();+ expect(wire).not.toContain("XXXX");+ expect(stripPings(wire)).toBe(expected);+ });+ }+});++describe("a raw response hook that edits Buffer chunks it read in place", () => {+ // The first hook re-emits the response as Node Buffers, which is what the second+ // hook's recorder then retains. `Buffer#slice` is a view, so a copy taken with it+ // would let the second hook's in-place edit reach the fallback bytes.+ // The editor overwrites EVERY chunk it reads: the first one or more are the keepalive+ // pings "buffers" emits while it holds its replacement, and only later ones are copies+ // of the Buffers the editor's recorder retains.+ const pair = (tail: string) => `+ export default [+ {+ apiVersion: 1, id: "buffers", unsafe: true,+ raw: {+ response(ctx) {+ const toBuffers = new TransformStream({+ transform(chunk, c) { c.enqueue(Buffer.from(chunk)); },+ });+ return new Response(ctx.response.body.pipeThrough(toBuffers), ctx.response);+ },+ },+ },+ {+ apiVersion: 1, id: "editor", unsafe: true,+ raw: {+ async response(ctx) {+ const reader = ctx.response.body.getReader();+ for (;;) {+ const r = await reader.read();+ if (r.done) break;+ r.value.fill(0x58);+ }+ ${tail}+ },+ },+ },+ ];`;++ for (const [name, tail] of [+ ["throws", `throw new Error("edited, then failed");`],+ ["returns nothing", "return undefined;"],+ ] as const) {+ it(`${name}: the client receives the original bytes`, async () => {+ const chunks = claudeMessage();+ const expected = await originalWire("anthropic-sse", chunks);+ const h = await loadHook(pair(tail), { "hook:*": "fix" });+ stubUpstream(chunks, { delayMs: 20 });+ const wire = await (+ await withHooks(handler("anthropic-sse"), h.engine).handle(context(), payload())+ ).text();+ expect(wire).not.toContain("XXXX");+ expect(stripPings(wire)).toBe(expected);+ });+ }+});++/* ───────────── a warn replacement built from ctx.response ───────────── */++describe("at warn, a replacement that streams ctx.response is read to the original's end", () => {+ it("the replacement sees every byte of the original, and the client the original", async () => {+ const chunks = claudeMessage();+ const expected = await originalWire("anthropic-sse", chunks);+ g.__cr20bytes = -1;+ const h = await loadHook(+ `export default {+ apiVersion: 1, id: "tee", unsafe: true,+ raw: {+ response(ctx) {+ let n = 0;+ const count = new TransformStream({+ transform(chunk, c) { n += chunk.byteLength; c.enqueue(chunk); },+ flush() { globalThis.__cr20bytes = n; },+ });+ return new Response(ctx.response.body.pipeThrough(count));+ },+ },+ };`,+ { "hook:*": "warn" }+ );+ stubUpstream(chunks, { delayMs: 20 });+ const wire = await (+ await withHooks(handler("anthropic-sse"), h.engine).handle(context(), payload())+ ).text();+ expect(stripPings(wire)).toBe(expected);+ await settle(100);+ // the client got the original whole at warn, so its wire is exactly what the view held+ expect(g.__cr20bytes).toBe(new TextEncoder().encode(wire).byteLength);+ });+});++/* ───────────── response: replacement outcomes ───────────── */++describe("raw response replacements", () => {+ it("a replacement that closes cleanly is what the client receives, and responseEnd sees it", async () => {+ const replacement = claudeMessage("REPLACED");+ g.__x9seen = null;+ const h = await loadHook(`+ const frames = ${JSON.stringify(replacement)};+ export default [+ { apiVersion: 1, id: "swap", unsafe: true,+ raw: { response() { return new Response(frames.join("")); } } },+ { apiVersion: 1, id: "end",+ on: { responseEnd(ctx) { globalThis.__x9seen = ctx.response.text; } } },+ ];`);+ stubUpstream(claudeMessage("original answer"));+ const res = await withHooks(handler("anthropic-sse"), h.engine).handle(context(), payload());+ const wire = await res.text();+ expect(textOf(wire)).toBe("REPLACED");+ expect(stripPings(wire)).toBe(stripPings(replacement.join("")));+ await settle(50);+ expect(g.__x9seen).toBe("REPLACED");+ });++ it("a replacement that errors after its first chunk: the client gets the original, no event: error", async () => {+ const chunks = claudeMessage();+ const expected = await originalWire("anthropic-sse", chunks);+ const h = await loadHook(`+ export default {+ apiVersion: 1, id: "broken", unsafe: true,+ raw: {+ response() {+ let n = 0;+ return new Response(new ReadableStream({+ pull(c) {+ if (n++ === 0) c.enqueue(new TextEncoder().encode("event: ping\\n\\n"));+ else c.error(new Error("replacement broke"));+ },+ }));+ },+ },+ };`);+ stubUpstream(chunks);+ const wire = await (+ await withHooks(handler("anthropic-sse"), h.engine).handle(context(), payload())+ ).text();+ expect(stripPings(wire)).toBe(expected);+ expect(wire).not.toContain("event: error");+ expect(h.journal.some((e) => e.decision === "error" && e.event === "raw")).toBe(true);+ });++ it("at warn a replacement is read and discarded, and the original is forwarded", async () => {+ const chunks = claudeMessage();+ const expected = await originalWire("anthropic-sse", chunks);+ const h = await loadHook(+ `export default {+ apiVersion: 1, id: "warned", unsafe: true,+ raw: { response() { return new Response("event: ping\\n\\n"); } },+ };`,+ { "hook:*": "warn" }+ );+ stubUpstream(chunks);+ const wire = await (+ await withHooks(handler("anthropic-sse"), h.engine).handle(context(), payload())+ ).text();+ expect(stripPings(wire)).toBe(expected);+ await settle();+ expect(h.journal.some((e) => e.decision === "warned" && e.event === "raw")).toBe(true);+ });++ it("stream:false: a replacement JSON message is what the client receives", async () => {+ const h = await loadHook(`+ export default {+ apiVersion: 1, id: "jsonswap", unsafe: true,+ raw: {+ async response(ctx) {+ const message = await ctx.response.json();+ message.content = [{ type: "text", text: "FROM HOOK" }];+ return new Response(JSON.stringify(message), { headers: { "content-type": "application/json" } });+ },+ },+ };`);+ stubUpstream(claudeMessage("original answer"));+ const res = await withHooks(handler("anthropic-sse"), h.engine).handle(+ context(),+ payload(false)+ );+ const message = await res.json();+ expect(message.content).toEqual([{ type: "text", text: "FROM HOOK" }]);+ });+});++/* ───────────── providerRequest ───────────── */++describe("raw providerRequest containment", () => {+ const upstream = () =>+ stubUpstream([+ openAiFrame({ choices: [{ delta: { content: "ok" } }] }),+ openAiFrame({ choices: [{ delta: {}, finish_reason: "stop" }] }),+ "data: [DONE]\n\n",+ ]);++ it("a committed edit reaches the transport, after stage B's tool description", async () => {+ const h = await loadHook(`+ export default [+ { apiVersion: 1, id: "desc",+ on: { request: () => [{ type: "rewriteToolDescription", tool: "Read", append: " STAGE-B" }] } },+ { apiVersion: 1, id: "edit", unsafe: true,+ raw: {+ providerRequest(ctx) {+ const fn = ctx.tools.find((t) => (t.function?.name ?? t.name) === "Read");+ globalThis.__sawStageB = (fn.function?.description ?? fn.description).includes("STAGE-B");+ ctx.messages.push({ role: "user", content: "RAW-ADDED" });+ },+ } },+ ];`);+ const { bodies } = upstream();+ await (await withHooks(handler("openai-sse"), h.engine).handle(context(), payload())).text();+ expect(g.__sawStageB).toBe(true);+ expect(JSON.stringify(bodies[0].messages)).toContain("RAW-ADDED");+ });++ it("a hook that empties messages and then throws changes nothing", async () => {+ const h = await loadHook(`+ export default {+ apiVersion: 1, id: "empties", unsafe: true,+ raw: { providerRequest(ctx) { ctx.messages.length = 0; ctx.tools.length = 0; throw new Error("boom"); } },+ };`);+ const { bodies } = upstream();+ await (await withHooks(handler("openai-sse"), h.engine).handle(context(), payload())).text();+ expect(JSON.stringify(bodies[0].messages)).toContain("Say something.");+ expect(bodies[0].tools).toHaveLength(1);+ expect(h.journal.some((e) => e.decision === "error" && e.event === "raw")).toBe(true);+ });++ it("a hook that times out and mutates afterwards changes nothing", async () => {+ const h = await loadHook(`+ export default {+ apiVersion: 1, id: "late", unsafe: true, timeoutMs: 50,+ raw: {+ async providerRequest(ctx) {+ await new Promise((r) => setTimeout(r, 150));+ ctx.messages.push({ role: "user", content: "LATE" });+ },+ },+ };`);+ const { bodies } = upstream();+ await (await withHooks(handler("openai-sse"), h.engine).handle(context(), payload())).text();+ await settle(200);+ expect(JSON.stringify(bodies[0].messages)).not.toContain("LATE");+ expect(h.journal.some((e) => e.decision === "timeout" && e.event === "raw")).toBe(true);+ });++ it("at warn the hook runs on copies that never reach the transport", async () => {+ g.__warnRan = false;+ const h = await loadHook(+ `export default {+ apiVersion: 1, id: "warnreq", unsafe: true,+ raw: { providerRequest(ctx) { globalThis.__warnRan = true; ctx.messages.push({ role: "user", content: "WARN-ONLY" }); } },+ };`,+ { "hook:*": "warn" }+ );+ const { bodies } = upstream();+ await (await withHooks(handler("openai-sse"), h.engine).handle(context(), payload())).text();+ expect(g.__warnRan).toBe(true);+ expect(JSON.stringify(bodies[0].messages)).not.toContain("WARN-ONLY");+ expect(h.journal.some((e) => e.decision === "warned" && e.event === "raw")).toBe(true);+ });+});diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.tsindex 9d7e4f94..38c2db07 100644--- a/packages/cli/src/handlers/composed-handler.ts+++ b/packages/cli/src/handlers/composed-handler.ts@@ -11,7 +11,7 @@* 2. adapter.convertMessages(claudeRequest) — Claude → target format* 3. adapter.convertTools(claudeRequest) — tool schema conversion* 3a. hook request stage B — tool descriptions, both representations- * 3b. middleware.beforeRequest(...) — pre-flight hooks+ * 3b. raw providerRequest hooks — unsafe tier, on committed clones* 4. adapter.buildPayload(...) — assemble full request body* 5. adapter.prepareRequest(payload, original) — tool name truncation, etc.* 6. fetch via provider (with optional queue) — HTTP request@@ -41,6 +41,8 @@ import { lookupModelAcceptsImages, lookupModelForProvider } from "../adapters/moimport type { QuotaAdapter } from "../auth/quota/adapter.js";import { resolveQuotaAdapter } from "../auth/quota/registry.js";import { PLAN_POLL_INTERVAL_MS } from "../auth/quota/types.js";+import { getHookEngine } from "../hooks/index.js";+import { type RawStreamTap, statsNames } from "../hooks/raw.js";import { type HookRequestScope, isNativeRoute, requestHooksOf } from "../hooks/request-stage.js";import {getLogLevel,@@ -50,7 +52,6 @@ import {logStructured,truncateContent,} from "../logger.js";-import { GeminiThoughtSignatureMiddleware, MiddlewareManager } from "../middleware/index.js";import { deepMergeParams } from "../model-params.js";import type { ResolvedConnection } from "../providers/connection-resolver.js";import type { WireHeader } from "../providers/connection-wire.js";@@ -252,13 +253,12 @@ export class ComposedHandler implements ModelHandler {private explicitAdapter?: BaseModelAdapter;/** Model-specific adapter (GLM, Grok, etc.) — handles model quirks independent of provider */private modelAdapter?: BaseModelAdapter;- private middlewareManager: MiddlewareManager;private tokenTracker: TokenTracker;/** Full routed model string (e.g. "[email protected]"). Used for provider routing and display echo. */private targetModel: string;/*** Bare model name (e.g. "glm-4.7"), provider prefix stripped. Used for model identity:- * dialect selection, catalog lookup, middleware routing, context tracking. Never contains '@'.+ * dialect selection, catalog lookup, raw-hook routing, context tracking. Never contains '@'.* @invariant !bareModelName.includes("@")*/private readonly bareModelName: string;@@ -351,29 +351,6 @@ export class ComposedHandler implements ModelHandler {this.resolvedDialect.setResponseWireFormat(responseWire);this.explicitAdapter?.setResponseWireFormat(responseWire);- // Initialize middleware (only register model-specific middleware when applicable).- // Use bareModelName for the middleware gate — .includes() works identically for- // "[email protected]" and "gemini-2.5-flash", and bare form is the invariant.- this.middlewareManager = new MiddlewareManager();- // With a connection, from data: a Gemini-API wire, or a Google model behind- // a gateway (OpenRouter carries its thought signatures in reasoning_details).- const connectionWire = options.connection?.wire;- if (- options.connection- ? (connectionWire?.status === "known" && connectionWire.api === "gemini") ||- options.connection.vendor === "google"- : this.bareModelName.includes("gemini") || this.bareModelName.includes("google/")- ) {- // Selected from data when there is a connection: the middleware's own- // name gate must not re-filter an opaque gateway id out again.- this.middlewareManager.register(- new GeminiThoughtSignatureMiddleware({ alwaysHandle: !!options.connection })- );- }- this.middlewareManager- .initialize()- .catch((err) => log(`[ComposedHandler:${this.bareModelName}] Middleware init error: ${err}`));-// `--effort`: install the pin on EVERY dialect this handler can route// through. getAdapter() picks explicitAdapter or resolvedDialect at request// time and modelAdapter runs in addition to it, so pinning only one leaves@@ -413,6 +390,15 @@ export class ComposedHandler implements ModelHandler {};}+ /**+ * `middleware_names` for stats: the built-in raw hooks (the Gemini+ * thought-signature hook, today) that apply to this route. User hooks never+ * appear, so the OTLP `llm.middleware` attribute is unchanged for them.+ */+ private rawStatsNames(): string[] {+ return statsNames(getHookEngine(), this.routeInfo());+ }+/** Provider adapter — handles transport format (messages, tools, payload) */private getAdapter(): BaseModelAdapter {return this.explicitAdapter || this.resolvedDialect;@@ -593,7 +579,7 @@ export class ComposedHandler implements ModelHandler {error_code,token_strategy: this.options.tokenStrategy ?? "standard",adapter_name: this.getActiveAdapterName(),- middleware_names: this.middlewareManager.getActiveNames(this.bareModelName),+ middleware_names: this.rawStatsNames(),fallback_used: ctx.fallbackMeta !== undefined,fallback_chain: ctx.fallbackMeta?.chain,fallback_attempts: ctx.fallbackMeta?.attempts,@@ -693,7 +679,7 @@ export class ComposedHandler implements ModelHandler {error_code,token_strategy: this.options.tokenStrategy ?? "standard",adapter_name: this.getActiveAdapterName(),- middleware_names: this.middlewareManager.getActiveNames(this.bareModelName),+ middleware_names: this.rawStatsNames(),fallback_used: ctx.fallbackMeta !== undefined,fallback_chain: ctx.fallbackMeta?.chain,fallback_attempts: ctx.fallbackMeta?.attempts,@@ -994,7 +980,7 @@ export class ComposedHandler implements ModelHandler {error_code: "client_disconnected",token_strategy: this.options.tokenStrategy ?? "standard",adapter_name: this.getActiveAdapterName(),- middleware_names: this.middlewareManager.getActiveNames(this.bareModelName),+ middleware_names: this.rawStatsNames(),fallback_used: fallbackMeta !== undefined,fallback_chain: fallbackMeta?.chain,fallback_attempts: fallbackMeta?.attempts,@@ -1056,7 +1042,10 @@ export class ComposedHandler implements ModelHandler {// record unless a classified connection failure actually occurs.const recoveryTally = ComposedHandler.newRecoveryTally();// 1. Transform incoming Claude-format request- const { claudeRequest, droppedParams } = transformOpenAIToClaude(payload);+ const transformed = transformOpenAIToClaude(payload);+ const { droppedParams } = transformed;+ // `let`: a raw `providerRequest` hook's committed copies replace it (3b).+ let claudeRequest = transformed.claudeRequest;// 1a. Hook request stage A, on this attempt's own deep copy (each// FallbackHandler candidate gets a fresh one, so nothing leaks between@@ -1078,7 +1067,7 @@ export class ComposedHandler implements ModelHandler {if (typeof adapter.reset === "function") adapter.reset();// 3. Convert messages and tools- const messages = adapter.convertMessages(claudeRequest, filterIdentity);+ let messages = adapter.convertMessages(claudeRequest, filterIdentity);let tools = adapter.convertTools(claudeRequest, this.options.summarizeTools);// Per-API tool-count cap (e.g. OpenAI Chat Completions hard-caps `tools` at@@ -1205,30 +1194,30 @@ export class ComposedHandler implements ModelHandler {// which keeps only a description's first sentence, cannot cut an append)// and after the tool-count cap (a description action on a capped tool// changes the Claude-format copy only, journaled `capped`). It runs before- // the middleware step on purpose: a pre-flight hook sees the request the+ // the raw tier on purpose: a raw `providerRequest` hook sees the request the// closed actions produced.hookScope?.applyToolDescriptions(claudeRequest.tools ?? [], tools);- // 3b. Middleware before request.+ // 3b. Raw `providerRequest` hooks (the unsafe tier; the Gemini+ // thought-signature built-in lives here), after stage B so they see the+ // request the closed actions produced.//// MUST run before buildPayload. buildPayload is not guaranteed to keep a// reference to `messages`/`tools`: the Chat Completions adapter assigns them- // straight onto the payload (so in-place edits happened to survive), but the- // Codex/Responses adapter deep-copies both (convertMessagesToResponsesAPI +- // .map()) and lifts the system prompt out of `claudeRequest.system` into- // `payload.instructions`. Running this hook after buildPayload therefore- // discarded every mutation on exactly the path gpt-5.x uses, silently.+ // straight onto the payload, but the Codex/Responses adapter deep-copies+ // both and lifts the system prompt out of `claudeRequest.system` into+ // `payload.instructions`. A hook run after buildPayload would lose every+ // change on exactly the path gpt-5.x uses.//- // Use bareModelName — must match the key used by getActiveNames() and- // afterStreamComplete() so the same set of middlewares is selected at both ends.- await this.middlewareManager.beforeRequest({- modelId: this.bareModelName,- messages,- tools,- stream: true,- claudeRequest,- claudeTools: claudeRequest.tools ?? [],- });+ // Each hook works on clones, committed only when its call succeeds within+ // its timeout; a throw, rejection or timeout leaves the request as it was.+ if (hookScope) {+ ({ claudeRequest, messages, tools } = await hookScope.raw.providerRequest({+ claudeRequest,+ messages,+ tools,+ }));+ }// 4. Build request payloadlet requestPayload = adapter.buildPayload(claudeRequest, messages, tools);@@ -1463,8 +1452,8 @@ export class ComposedHandler implements ModelHandler {requestPayload = this.provider.transformPayload(requestPayload, claudeRequest);}- // (Middleware beforeRequest ran at step 3b, before buildPayload — see the- // note there for why it cannot run at this point.)+ // (Raw providerRequest hooks ran at step 3b, before buildPayload — see the+ // note there for why they cannot run at this point.)const endpoint = this.provider.getEndpoint(this.targetModel);// The ORIGINAL inbound body, not the normalized `claudeRequest` clone: a@@ -1925,7 +1914,7 @@ export class ComposedHandler implements ModelHandler {error_code,token_strategy: this.options.tokenStrategy ?? "standard",adapter_name: this.getActiveAdapterName(),- middleware_names: this.middlewareManager.getActiveNames(this.bareModelName),+ middleware_names: this.rawStatsNames(),fallback_used: fallbackMeta !== undefined,fallback_chain: fallbackMeta?.chain,fallback_attempts: fallbackMeta?.attempts,@@ -2056,7 +2045,7 @@ export class ComposedHandler implements ModelHandler {error_code,token_strategy: this.options.tokenStrategy ?? "standard",adapter_name: this.getActiveAdapterName(),- middleware_names: this.middlewareManager.getActiveNames(this.bareModelName),+ middleware_names: this.rawStatsNames(),fallback_used: fallbackMeta !== undefined,fallback_chain: fallbackMeta?.chain,fallback_attempts: fallbackMeta?.attempts,@@ -2175,7 +2164,7 @@ export class ComposedHandler implements ModelHandler {error_code,token_strategy: this.options.tokenStrategy ?? "standard",adapter_name: this.getActiveAdapterName(),- middleware_names: this.middlewareManager.getActiveNames(this.bareModelName),+ middleware_names: this.rawStatsNames(),fallback_used: fallbackMeta !== undefined,fallback_chain: fallbackMeta?.chain,fallback_attempts: fallbackMeta?.attempts,@@ -2284,7 +2273,7 @@ export class ComposedHandler implements ModelHandler {error_code: settled.code,token_strategy: this.options.tokenStrategy ?? "standard",adapter_name: this.getActiveAdapterName(),- middleware_names: this.middlewareManager.getActiveNames(this.bareModelName),+ middleware_names: this.rawStatsNames(),fallback_used: fallbackMeta !== undefined,fallback_chain: fallbackMeta?.chain,fallback_attempts: fallbackMeta?.attempts,@@ -2350,7 +2339,7 @@ export class ComposedHandler implements ModelHandler {error_code: settled.code,token_strategy: this.options.tokenStrategy ?? "standard",adapter_name: this.getActiveAdapterName(),- middleware_names: this.middlewareManager.getActiveNames(this.bareModelName),+ middleware_names: this.rawStatsNames(),fallback_used: fallbackMeta !== undefined,fallback_chain: fallbackMeta?.chain,fallback_attempts: fallbackMeta?.attempts,@@ -2420,7 +2409,7 @@ export class ComposedHandler implements ModelHandler {is_free_model: isFreeModel,token_strategy: this.options.tokenStrategy ?? "standard",adapter_name: this.getActiveAdapterName(),- middleware_names: this.middlewareManager.getActiveNames(this.bareModelName),+ middleware_names: this.rawStatsNames(),fallback_used: fallbackMeta !== undefined,fallback_chain: fallbackMeta?.chain,fallback_attempts: fallbackMeta?.attempts,@@ -2451,7 +2440,8 @@ export class ComposedHandler implements ModelHandler {onStreamComplete,(code, message) => {streamApiError = { code, message };- }+ },+ hookScope?.raw.streamTap());// A client that did not ask for a stream gets the single JSON message the@@ -2697,7 +2687,9 @@ export class ComposedHandler implements ModelHandler {claudeRequest: any,toolNameMap?: Map<string, string>,onComplete?: () => void,- onApiError?: (code: string, message: string) => void+ onApiError?: (code: string, message: string) => void,+ /** The raw `providerChunk`/`providerStreamEnd` tap for this stream, when one applies. */+ raw?: RawStreamTap): Response {// Local mutable copy so we can null it out after firing (prevents double-firing)// without reassigning the function parameter.@@ -2736,8 +2728,7 @@ export class ComposedHandler implements ModelHandler {};const streamFormat = this.resolveStreamFormat();- // Stream parsers receive bareModelName: it is used both as the middleware-identity- // key (must match beforeRequest() / getActiveNames()) AND as the value echoed in+ // Stream parsers receive bareModelName: it is the value echoed in// `message_start.message.model` for display. Passing the routed form here was the// latent second part of #102 — the parameter was named `modelName` but received// the full routed string.@@ -2766,7 +2757,7 @@ export class ComposedHandler implements ModelHandler {response,adapter,this.bareModelName,- this.middlewareManager,+ raw,onTokenUpdate,claudeRequest.tools,toolNameMap,@@ -2789,7 +2780,7 @@ export class ComposedHandler implements ModelHandler {contextWindow: lookupModelForProvider(this.bareModelName, this.provider.name),onApiError,priorInputTokens,- middlewareManager: this.middlewareManager,+ raw,onToolCallObserved: observeToolCall,});@@ -2821,7 +2812,7 @@ export class ComposedHandler implements ModelHandler {return createGeminiSseStream(c, response, {modelName: this.bareModelName,adapter,- middlewareManager: this.middlewareManager,+ raw,onTokenUpdate,onToolCall,onToolCallObserved: observeToolCall,diff --git a/packages/cli/src/handlers/shared/stream-parsers/gemini-sse.ts b/packages/cli/src/handlers/shared/stream-parsers/gemini-sse.tsindex 05a745b8..6a1dbd41 100644--- a/packages/cli/src/handlers/shared/stream-parsers/gemini-sse.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/gemini-sse.ts@@ -8,15 +8,16 @@import type { Context } from "hono";import type { BaseAPIFormat } from "../../../adapters/base-api-format.js";+import type { RawStreamTap } from "../../../hooks/raw.js";import { log } from "../../../logger.js";-import type { MiddlewareManager } from "../../../middleware/manager.js";import { messageStartUsage } from "./message-start-usage.js";import { sseDataPayload } from "./sse-line.js";export interface GeminiSseOptions {modelName: string;adapter?: BaseAPIFormat;- middlewareManager?: MiddlewareManager;+ /** The raw-tier tap; this wire calls only its `providerStreamEnd`. */+ raw?: RawStreamTap | null;onTokenUpdate?: (input: number, output: number) => void;/** Store tool call info (id, name, thoughtSignature) for future request context */onToolCall?: (toolId: string, name: string, thoughtSignature?: string) => void;@@ -87,8 +88,8 @@ export function createGeminiSseStream(}, 1000);// Kept out of finalize() so it can run from a `finally`. finalize() guards- // re-entry on `finalized`, so a throw part-way through (afterStreamComplete- // is an await on user middleware) used to leave the controller open and the+ // re-entry on `finalized`, so a throw part-way through (the raw tap's+ // streamEnd is an await on hook code) used to leave the controller open and the// ping interval running forever — the outer catch re-called finalize() and// it returned at the guard. Safe to call more than once.const teardown = () => {@@ -127,9 +128,7 @@ export function createGeminiSseStream(}}- if (opts.middlewareManager) {- await opts.middlewareManager.afterStreamComplete(opts.modelName, new Map());- }+ if (opts.raw) await opts.raw.streamEnd();const inputTokens = usage?.promptTokenCount || 0;const outputTokens = usage?.candidatesTokenCount || 0;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 379b956b..7cf595d3 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@@ -16,6 +16,7 @@ import {type CachedReasoningItem,rememberReasoningForCall,} from "../../../adapters/reasoning-cache.js";+import type { RawStreamTap } from "../../../hooks/raw.js";import { getLogLevel, log } from "../../../logger.js";import { wrapAnthropicError } from "../anthropic-error.js";import { messageStartUsage } from "./message-start-usage.js";@@ -49,11 +50,12 @@ export function createResponsesStreamHandler(*/priorInputTokens?: number;/**- * Middleware chain, so the Responses path gets the same response-side hooks- * the Chat Completions path has had. Previously absent, which left the Codex- * models with no observation point at all.+ * The raw-tier tap (`providerChunk` / `providerStreamEnd`), so the Responses+ * path has the same raw hook points as the Chat Completions path. The+ * Responses API has no `delta` object of its own, so the event stands in for+ * both.*/- middlewareManager?: any;+ raw?: RawStreamTap | null;/*** 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@@ -106,9 +108,6 @@ export function createResponsesStreamHandler(claudeId?: string;};- /** Shared across every chunk hook in this stream; handed to afterStreamComplete. */- const streamMetadata = new Map<string, any>();-// Track function calls being streamed. Keyed by BOTH call_id and item_id, so// the same FnCall object appears under two keys — never derive a count from// this map's size; use openToolBlocks / hasToolUse instead.@@ -240,19 +239,13 @@ export function createResponsesStreamHandler(}try {- const event = JSON.parse(data);-- // Response-side observation point. The Responses API has no- // `delta` object of its own, so the event stands in for both —- // observers here key off `event.type`.- if (opts.middlewareManager) {- await opts.middlewareManager.afterStreamChunk({- modelId: opts.modelName,- chunk: event,- delta: event,- metadata: streamMetadata,- });- }+ let event = JSON.parse(data);++ // Raw-tier tap, before anything reads the event: what it returns+ // is the committed object, and every read below is of it. The+ // Responses API has no `delta` object of its own, so the event+ // stands in for both.+ if (opts.raw) event = opts.raw.chunk(event, (e: any) => e);if (getLogLevel() === "debug" && event.type) {log(`[ResponsesSSE] Event: ${event.type}`);@@ -497,9 +490,7 @@ export function createResponsesStreamHandler(isClosed = true;if (opts.onTokenUpdate) opts.onTokenUpdate(inputTokens, outputTokens);- if (opts.middlewareManager) {- await opts.middlewareManager.afterStreamComplete(opts.modelName, streamMetadata);- }+ if (opts.raw) await opts.raw.streamEnd();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 e46cce94..88c5cde5 100644--- a/packages/cli/src/handlers/shared/stream-parsers/openai-sse.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/openai-sse.ts@@ -8,6 +8,7 @@*/import type { Context } from "hono";+import type { RawStreamTap } from "../../../hooks/raw.js";import { log } from "../../../logger.js";import {type ToolSchema,@@ -239,7 +240,11 @@ export function createStreamingResponseHandler(response: Response,adapter: any,target: string,- middlewareManager: any,+ /**+ * The raw-tier tap (`providerChunk` / `providerStreamEnd`), when a raw hook+ * applies to this route. `chunk()` returns the object to read from then on.+ */+ raw: RawStreamTap | null | undefined,/*** `input` is ALWAYS `prompt_tokens` — the full context size. The cached* breakdown rides in the third argument and is for COST ONLY; handing the@@ -270,7 +275,6 @@ export function createStreamingResponseHandler(let ping: NodeJS.Timeout | null = null;const encoder = new TextEncoder();const decoder = new TextDecoder();- const streamMetadata = new Map<string, any>();return c.body(new ReadableStream({@@ -622,9 +626,7 @@ export function createStreamingResponseHandler(}}- if (middlewareManager) {- await middlewareManager.afterStreamComplete(target, streamMetadata);- }+ if (raw) await raw.streamEnd();if (ending === "failure") {// An SSE `error` event is the ONE ending Claude Code honours by@@ -811,7 +813,7 @@ export function createStreamingResponseHandler(}try {- const chunk = JSON.parse(dataStr);+ let chunk = JSON.parse(dataStr);if (chunk.usage) {state.usage = chunk.usage;log(@@ -836,6 +838,14 @@ export function createStreamingResponseHandler(return;}+ // The raw tap runs BEFORE anything is derived from the chunk:+ // what it returns is the committed object (a hook's clone, or+ // the chunk itself), and every read below is of it, deletions+ // and a changed finish_reason included.+ if (raw && chunk.choices?.[0]?.delta) {+ chunk = raw.chunk(chunk, (c: any) => c.choices?.[0]?.delta);+ }+const delta = chunk.choices?.[0]?.delta;const finishReason = chunk.choices?.[0]?.finish_reason;if (finishReason) state.finishReason = finishReason;@@ -848,15 +858,6 @@ export function createStreamingResponseHandler(}if (delta) {- if (middlewareManager) {- await middlewareManager.afterStreamChunk({- modelId: target,- chunk,- delta,- metadata: streamMetadata,- });- }-// Reasoning arrives under two different field names on this one// wire format: `reasoning_content` (Kimi, DeepSeek via LiteLLM)// and `reasoning` (OpenRouter). Reading only the former silentlydiff --git a/packages/cli/src/hooks/builtins/gemini-thought-signature.ts b/packages/cli/src/hooks/builtins/gemini-thought-signature.tsnew file mode 100644index 00000000..3ffbf95c--- /dev/null+++ b/packages/cli/src/hooks/builtins/gemini-thought-signature.ts@@ -0,0 +1,167 @@+/**+ * Built-in raw hook `gemini/thought-signature`.+ *+ * Gemini 3 requires the reasoning of an assistant turn that called tools to be+ * sent back with that turn on every later request. OpenRouter carries it as the+ * message's `reasoning_details` array, and it must be the WHOLE array: a request+ * whose assistant tool call lacks it is rejected with a 400 validation error.+ * References: https://ai.google.dev/gemini-api/docs/thought-signatures and+ * https://openrouter.ai/docs/use-cases/reasoning-tokens#preserving-reasoning-blocks+ *+ * Three raw stages, ported from the `GeminiThoughtSignatureMiddleware` the hook+ * system replaced:+ *+ * - `providerChunk` (was `afterStreamChunk`) accumulates each chunk's+ * `reasoning_details` and tool-call ids into the stream's own `metadata`. It+ * only READS the delta, so the committed clone equals the parsed chunk and the+ * client stream never changes.+ * - `providerStreamEnd` (was `afterStreamComplete`) caches what one response+ * accumulated against its tool-call ids, when it carried both.+ * - `providerRequest` (was `beforeRequest`) puts the cached array back on each+ * assistant message whose tool calls it was recorded for.+ *+ * Active when the bare model name contains `gemini` or `google/`, today's rule.+ * The cache is keyed per route (`<provider>\0<modelId>`): the middleware was+ * constructed once per handler, i.e. per served model, and that scope is kept.+ * Each per-route cache stays unbounded, as before.+ *+ * The middleware's `afterResponse` (non-streaming) had no production caller and+ * is not ported. If non-streaming Gemini is ever wired, it needs a raw stage on+ * the provider-format JSON, which the hook system does not offer.+ */++import { isLoggingEnabled, log, logStructured } from "../../logger.js";+import type {+ RawProviderChunkContext,+ RawProviderRequestContext,+ RawProviderStreamEndContext,+ RouteInfo,+} from "../public.js";+import type { BuiltinHook } from "../registry.js";++export const GEMINI_THOUGHT_SIGNATURE_HOOK_ID = "gemini/thought-signature";++/** The `middleware_names` stats value, unchanged from the middleware it replaced. */+export const GEMINI_THOUGHT_SIGNATURE_STATS_NAME = "GeminiThoughtSignature";++interface CachedReasoning {+ // biome-ignore lint/suspicious/noExplicitAny: provider-format reasoning blocks, forwarded verbatim+ reasoning_details: any[];+ tool_call_ids: Set<string>;+}++type RouteCache = Map<string, CachedReasoning>;++const REASONING_KEY = "reasoning_details";+const TOOL_IDS_KEY = "tool_call_ids";++function routeKey(route: RouteInfo): string {+ return `${route.provider}\0${route.modelId}`;+}++/**+ * A fresh instance of the built-in, with its own caches. One per hook engine:+ * the engine is one per process, as the middleware instances were one per+ * handler.+ */+export function createGeminiThoughtSignatureHook(): BuiltinHook {+ const caches = new Map<string, RouteCache>();+ const cacheFor = (route: RouteInfo): RouteCache => {+ const key = routeKey(route);+ let cache = caches.get(key);+ if (!cache) {+ cache = new Map();+ caches.set(key, cache);+ }+ return cache;+ };++ return {+ apiVersion: 1,+ id: GEMINI_THOUGHT_SIGNATURE_HOOK_ID,+ description:+ "Sends Gemini's reasoning_details back with the assistant tool calls they were produced for",+ order: "pre",+ models: ["*gemini*", "*google/*"],+ routes: "all",+ defaultSeverity: "fix",+ statsName: GEMINI_THOUGHT_SIGNATURE_STATS_NAME,+ unsafe: true,+ raw: {+ providerRequest(ctx: RawProviderRequestContext): void {+ const cache = caches.get(routeKey(ctx.route));+ if (!cache || cache.size === 0) return;+ let injected = 0;+ for (const msg of ctx.messages) {+ if (msg?.role !== "assistant" || !Array.isArray(msg.tool_calls)) continue;+ for (const [messageId, cached] of cache) {+ // biome-ignore lint/suspicious/noExplicitAny: provider-format tool call+ if (!msg.tool_calls.some((tc: any) => cached.tool_call_ids.has(tc?.id))) continue;+ msg.reasoning_details = cached.reasoning_details;+ injected++;+ if (isLoggingEnabled()) {+ logStructured("[Gemini] Reasoning details added to assistant message", {+ message_id: messageId,+ reasoning_blocks: cached.reasoning_details.length,+ tool_calls: msg.tool_calls.length,+ });+ }+ break; // once per message+ }+ if (!msg.reasoning_details && isLoggingEnabled()) {+ log(+ // biome-ignore lint/suspicious/noExplicitAny: provider-format tool call+ `[Gemini] No reasoning_details cached for the assistant tool calls ${msg.tool_calls.map((tc: any) => tc?.id).join(", ")}`+ );+ }+ }+ if (injected > 0 && isLoggingEnabled()) {+ logStructured("[Gemini] Signature injection complete", {+ injected,+ cacheSize: cache.size,+ });+ }+ },++ providerChunk(ctx: RawProviderChunkContext): void {+ const delta = ctx.delta;+ if (!delta) return;+ if (Array.isArray(delta.reasoning_details) && delta.reasoning_details.length > 0) {+ // biome-ignore lint/suspicious/noExplicitAny: provider-format reasoning blocks+ let accumulated = ctx.metadata.get(REASONING_KEY) as any[] | undefined;+ if (!accumulated) {+ accumulated = [];+ ctx.metadata.set(REASONING_KEY, accumulated);+ }+ accumulated.push(...delta.reasoning_details);+ }+ if (Array.isArray(delta.tool_calls)) {+ let ids = ctx.metadata.get(TOOL_IDS_KEY) as Set<string> | undefined;+ if (!ids) {+ ids = new Set();+ ctx.metadata.set(TOOL_IDS_KEY, ids);+ }+ for (const tc of delta.tool_calls) {+ if (typeof tc?.id === "string" && tc.id) ids.add(tc.id);+ }+ }+ },++ providerStreamEnd(ctx: RawProviderStreamEndContext): void {+ // biome-ignore lint/suspicious/noExplicitAny: provider-format reasoning blocks+ const reasoning = (ctx.metadata.get(REASONING_KEY) as any[] | undefined) ?? [];+ const ids = (ctx.metadata.get(TOOL_IDS_KEY) as Set<string> | undefined) ?? new Set();+ if (reasoning.length === 0 || ids.size === 0) return;+ const cache = cacheFor(ctx.route);+ const messageId = `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`;+ cache.set(messageId, { reasoning_details: reasoning, tool_call_ids: ids });+ logStructured("[Gemini] Streaming complete - reasoning details saved", {+ message_id: messageId,+ reasoning_blocks: reasoning.length,+ tool_calls: ids.size,+ total_cached_messages: cache.size,+ });+ },+ },+ } as BuiltinHook;+}diff --git a/packages/cli/src/hooks/builtins/index.ts b/packages/cli/src/hooks/builtins/index.tsindex f856907d..5e85fde6 100644--- a/packages/cli/src/hooks/builtins/index.ts+++ b/packages/cli/src/hooks/builtins/index.ts@@ -9,6 +9,7 @@import type { HooksConfig } from "../config.js";import type { BuiltinHook } from "../registry.js";+import { createGeminiThoughtSignatureHook } from "./gemini-thought-signature.js";import { createObserverHook } from "./observer.js";import { planModeHook } from "./plan-mode.js";import { sessionContextHook } from "./session-context.js";@@ -16,10 +17,16 @@ 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. */+/**+ * Every built-in for one config: the fixed ones, the Gemini thought-signature+ * raw hook (a fresh instance, so its per-route caches belong to one engine), then+ * the observer it configures. The observer's rule vocabulary is the closed+ * conformance rules only.+ */export function builtinHooks(config: HooksConfig): ReadonlyArray<BuiltinHook> {return [...BUILTIN_HOOKS,+ createGeminiThoughtSignatureHook(),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.tsindex 0983d5db..44b21a2b 100644--- a/packages/cli/src/hooks/builtins/observer.test.ts+++ b/packages/cli/src/hooks/builtins/observer.test.ts@@ -68,6 +68,7 @@ describe("observer built-in definition", () => {expect(ids).toEqual(["plan-mode/plan-file-path","session-context/no-harness-echo",+ "gemini/thought-signature",OBSERVER_HOOK_ID,]);});@@ -107,7 +108,7 @@ describe("observer through the seam", () => {stream: true,});- expect(planSeam(scope)).toEqual({ mode: "none", tap: true });+ expect(planSeam(scope)).toEqual({ mode: "none", raw: 0, 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',diff --git a/packages/cli/src/hooks/engine.ts b/packages/cli/src/hooks/engine.tsindex 4cb9bfa4..30db04a7 100644--- a/packages/cli/src/hooks/engine.ts+++ b/packages/cli/src/hooks/engine.ts@@ -1,20 +1,29 @@/**- * The hook engine: runs one event's hooks and turns what they return into- * attributed, severity-gated, validated actions.+ * The hook engine: runs one dispatch's hooks as a hook chain and turns what+ * they return into attributed, severity-gated, validated, applied actions.*- * Execution: every applicable hook's handler is invoked CONCURRENTLY, each with- * its own timeout and `AbortSignal`, against a shallow-frozen context, inside- * the hook output scope. Results are collected and returned in EFFECTIVE ORDER;- * the appliers (actions.ts, text-rewrite.ts) then apply them sequentially.- * Closed handlers cannot see each other's results, so concurrency changes no- * outcome — it only bounds latency to the slowest hook.+ * Execution (§4.4.1): a dispatch is one firing of one event. Its applicable+ * hooks run one at a time, in effective order — a left fold the engine drives,+ * never `next()` middleware, so no hook can stall or stop the chain. Each step+ * builds a fresh shallow-frozen context from the dispatch's WORKING STATE (the+ * event's input plus every action earlier steps applied), calls the handler+ * inside the hook output scope with its own timeout and `AbortSignal`, then+ * severity-gates and validates what it returned and hands the step's fix+ * actions to the event's applier, in the order the hook returned them, before+ * the next hook is called. `ctx.prior` lists what earlier steps applied.+ *+ * Latency is the sum of the steps, bounded by an event budget (§4.5): a step's+ * timeout is its own or the budget left, whichever is shorter, and a hook whose+ * step would start with no budget left is journaled `skipped`. Separate+ * dispatches (two requests, two tool calls, two sessions) are independent.** Failure posture: fail open, always. A throw, a rejection, a timeout or an- * invalid return value is journaled and treated as "no actions"; an invalid- * action is journaled and ignored. Five consecutive failures of one hook disable- * it for the process (journal `disabled`, one stderr line); any success resets- * the count. There is no fail-closed option: a throwing hook never breaks a- * request or a session.+ * invalid return value is journaled and treated as "no actions", and the next+ * step sees what the failed one saw; an invalid action is journaled and+ * ignored. Five consecutive failures of one hook disable it for the process+ * (journal `disabled`, one stderr line); any success resets the count. A+ * timeout the event budget caused, and a skipped step, do not count. There is+ * no fail-closed option: a throwing hook never breaks a request or a session.** Observability: one private `journal()` fans out to the local journal and —* for the surfaces and decision values the telemetry backend accepts — to@@ -33,6 +42,7 @@ import {validateAction,} from "./actions.js";import type { HooksConfig, WarnSink } from "./config.js";+import { deepFreeze } from "./freeze.js";import {type Decision,JOURNAL_SCHEMA_VERSION,@@ -51,6 +61,7 @@ import type {HookDefinition,HostMode,ObserveAction,+ PriorAction,RequestAction,ResponseEndAction,RewriteAction,@@ -77,8 +88,6 @@ export const EVENT_TIMEOUTS: Readonly<Record<HookEventName, { default: number; msessionStart: { default: 5_000, max: 30_000 },sessionIdle: { default: 5_000, max: 30_000 },sessionBlocked: { default: 5_000, max: 30_000 },- // Shared across hooks: they run concurrently from one start, so a per-hook- // bound of 1,500 ms bounds the whole dispatch to 1,500 ms.sessionEnd: { default: 1_500, max: 1_500 },"raw.providerRequest": { default: 1_000, max: 5_000 },// Synchronous; no timeout applies.@@ -87,6 +96,28 @@ export const EVENT_TIMEOUTS: Readonly<Record<HookEventName, { default: number; m"raw.response": { default: 1_000, max: 5_000 },};+/**+ * The event budget (§4.5): the time the whole hook chain of one dispatch may+ * take, in ms. Each equals the event's per-hook maximum, so no dispatch's+ * worst case is longer than one hook at its maximum. `null` = no budget: raw+ * `providerChunk` is synchronous, and each raw `response` step keeps its own+ * call and close deadlines (a budget would cut a replacement mid-decision).+ */+export const EVENT_BUDGETS: Readonly<Record<HookEventName, number | null>> = {+ request: 5_000,+ toolCall: 5_000,+ responseRewrite: 10_000,+ responseEnd: 30_000,+ sessionStart: 30_000,+ sessionIdle: 30_000,+ sessionBlocked: 30_000,+ sessionEnd: 1_500,+ "raw.providerRequest": 5_000,+ "raw.providerChunk": null,+ "raw.providerStreamEnd": 5_000,+ "raw.response": null,+};+/** A hook's timeout for an event: its own `timeoutMs` clamped to the event's maximum. */export function timeoutFor(def: HookDefinition, event: HookEventName): number {const bounds = EVENT_TIMEOUTS[event];@@ -95,9 +126,93 @@ export function timeoutFor(def: HookDefinition, event: HookEventName): number {return Math.min(own, bounds.max);}+/**+ * The dispatch bound of an event (§4.5): the smaller of its budget and the sum+ * of its applicable hooks' step timeouts. With no budget, the sum.+ */+export function dispatchBoundMs(+ event: HookEventName,+ hooks: ReadonlyArray<{ hook: { def: HookDefinition } }>+): number {+ let sum = 0;+ for (const a of hooks) sum += timeoutFor(a.hook.def, event);+ const budget = EVENT_BUDGETS[event];+ return budget === null ? sum : Math.min(budget, sum);+}++/** One step's timeout: its own, or the budget left, whichever is shorter. */+export interface StepTimeout {+ ms: number;+ /**+ * true when the earlier steps cut this step's time by MORE than `clipMarginMs`, so a+ * timeout is theirs: journaled `event_budget`, not counted toward the breaker. A cut+ * within the margin leaves this false even though `ms` may be a little under the+ * hook's own timeout: that timeout is the hook's own and counts.+ */+ clipped: boolean;+}++/** The smallest cut, in ms, that makes a budget-shortened step's timeout the budget's fault. */+export const CLIP_MARGIN_MIN_MS = 250;+/** The same margin as a share of the hook's own timeout, when that is larger. */+export const CLIP_MARGIN_SHARE = 0.1;+/** The margin never exceeds this share of the hook's own timeout (short hooks). */+export const CLIP_MARGIN_MAX_SHARE = 0.5;++/**+ * How much shorter than its own timeout a step must be before a timeout is not counted:+ * max(250 ms, 10 % of its own timeout), capped at half its own timeout. Without the cap a+ * hook whose own timeout is 250 ms or less could never be clipped by more than the+ * margin, so a slow hook before it would get it disabled.+ */+export function clipMarginMs(ownMs: number): number {+ return Math.min(+ ownMs * CLIP_MARGIN_MAX_SHARE,+ Math.max(CLIP_MARGIN_MIN_MS, ownMs * CLIP_MARGIN_SHARE)+ );+}++/**+ * The step timeout of a hook whose step starts with `remaining` ms of budget+ * left (`null` = no budget), or null when nothing is left: the hook is skipped.+ *+ * The breaker rule (§2.4): a step timeout counts toward the hook's breaker unless the+ * step was clipped by MORE than `clipMarginMs(own)` — max(250 ms, 10 % of the hook's own+ * timeout), capped at half its own timeout — and therefore the hook did not get its own+ * full timeout. A clip within the+ * margin is what the earlier steps' ordinary run time costs (the built-ins before every+ * `request` hook, a 1 ms boundary between deadline and `Date.now()`); exempting it let a+ * hook that hangs at its own maximum escape the breaker forever whenever any step ran+ * before it. A larger clip means an earlier hook really spent the budget, and a slow hook+ * A must not disable a healthy hook B.+ */+export function stepTimeout(+ def: HookDefinition,+ event: HookEventName,+ remaining: number | null+): StepTimeout | null {+ const own = timeoutFor(def, event);+ if (remaining === null) return { ms: own, clipped: false };+ if (remaining <= 0) return null;+ if (remaining >= own) return { ms: own, clipped: false };+ return { ms: remaining, clipped: own - remaining > clipMarginMs(own) };+}++/** The journal detail of a timeout or a skip the event budget caused. */+export const EVENT_BUDGET_DETAIL = "event_budget";+/** Consecutive failures that disable a hook for the process. */export const BREAKER_THRESHOLD = 5;+/**+ * Actions one hook may return from one step; the rest are journaled `invalid`+ * (`too_many_actions`) and not applied. Applying a step is synchronous and runs+ * outside the step's timeout, and a `responseRewrite` step re-applies every text+ * action so far over a held response of up to 8 MiB, so an unbounded list could+ * hold the response (and its keepalive) far past the event's budget.+ */+export const MAX_ACTIONS_PER_STEP = 64;+/** The synthetic hook id carried by a pending note on the request it is applied to. */export const PENDING_NOTE_ID = "behavior/pending-correction";@@ -137,7 +252,10 @@ export interface BaseContextParts {hookId: string;severity: Exclude<Severity, "off">;log(message: string): void;+ /** this step's own signal: its step timeout, or the dispatch's abort */signal: AbortSignal;+ /** what earlier steps of this dispatch applied or handed on, in order (§4.4.1 rule 5) */+ prior: ReadonlyArray<PriorAction>;}/** Facts every journal line of one dispatch shares. */@@ -160,27 +278,73 @@ export interface JournalInput extends JournalMeta {expectedPath?: string;note?: string;detail?: string;+ /** Never sent to the telemetry aggregate, whatever the surface and decision (raw-tier rows). */+ localOnly?: boolean;}-export type HookRunStatus = "ok" | "timeout" | "error" | "invalid" | "aborted";+export type HookRunStatus = "ok" | "timeout" | "error" | "invalid" | "aborted" | "skipped";-/** One hook's run within a dispatch. */+/** One hook's step within a dispatch. */export interface HookRun<A extends HookAction> {applicable: ApplicableHook;status: HookRunStatus;/** Every valid action the hook returned, `warn` included, before the severity gate. */returned: A[];+ /** The actions this step applied (or handed on): what it added to `ctx.prior`. */+ applied: Array<PlannedAction<A>>;}-export interface RunResult<A extends HookAction> {- runs: Array<HookRun<A>>;- /** Valid, non-`warn` actions of fix-severity hooks, in effective order: what to apply. */- apply: Array<PlannedAction<A>>;+/** What one step's applier did with that step's fix actions. */+export interface StepApplied<A extends HookAction, S> {+ /** The working state the next step starts from. */+ state: S;+ /** Outcomes the engine journals at this step (an applier may journal itself and return none). */+ results: ReadonlyArray<ActionResult<A>>;+ /** The actions that took effect, in order: appended to `ctx.prior`. */+ applied: ReadonlyArray<PlannedAction<A>>;+}++/**+ * One event's step functions (§4.4.1). `context` builds a step's context from+ * the working state; `apply` applies one step's fix actions — valid, non-`warn`,+ * in the order the hook returned them — and must not mutate `state`: the+ * engine replaces the working state only when it returns, so a step is atomic.+ * The one exception is `responseEnd`, whose applier delivers each action as it+ * routes it; it contains a throw per action instead (`SeamHooks.end`).+ * An observe-only chain passes no `apply`: nothing it returns can be applied.+ */+export interface ChainStep<A extends HookAction, S> {+ context(applicable: ApplicableHook, base: BaseContextParts, state: S): object;+ apply?(state: S, items: ReadonlyArray<PlannedAction<A>>): StepApplied<A, S>;+ /** Extra fields for the journal line of one result this step's applier returned. */+ journalExtra?(result: ActionResult<A>, before: S): Partial<JournalInput>;+ /**+ * Called once a hook's step ended (not for a skipped or aborted one, nor for one+ * whose applier threw: that step's lines are its `apply_failed` errors), with+ * the state the step saw: for journal lines that are not action outcomes.+ */+ afterStep?(run: HookRun<A>, before: S): void;}-export interface RunOptions {- /** Aborting it aborts every hook's signal; unfinished hooks end `aborted`, unjournaled. */+export interface ChainOptions<S> {+ /** The working state step 1 starts from. */+ initial: S;+ /**+ * Aborting it aborts the running step's signal and starts no later step;+ * the running hook ends `aborted`, unjournaled.+ */signal?: AbortSignal;+ /** `ctx.prior` of step 1: actions applied before the chain (the request's pending notes). */+ prior?: ReadonlyArray<PriorAction>;+}++export interface ChainResult<A extends HookAction, S> {+ /** One entry per hook the chain reached, in effective order. */+ runs: Array<HookRun<A>>;+ /** The working state after the last step. */+ state: S;+ /** Every action the chain's steps applied (or handed on), in order. */+ applied: Array<PlannedAction<A>>;}function isUserHook(hookId: string): boolean {@@ -277,28 +441,75 @@ export class HookEngine {return this.disabled.has(hookId);}- /* ───────────── dispatch ───────────── */+ /* ───────────── dispatch: the hook chain (§4.4.1) ───────────── *//**- * Run one closed event's handlers concurrently and collect their actions.+ * Run one dispatch's hooks as a hook chain: one at a time, in the order of+ * `hooks` (effective order), each step's fix actions applied by `step.apply`+ * before the next hook is called.*- * `context` builds the event's full context from the engine's base parts;- * the result is shallow-frozen before the handler sees it.+ * Per step: a hook the breaker disabled since selection is passed over with+ * no journal line; a hook whose step would start with no budget left is+ * journaled `skipped`; otherwise its context is built from the working state+ * (shallow-frozen, with `prior`), it is called with its step timeout and its+ * own signal, its return value is validated, `warn` actions and everything a+ * warn-severity hook returned are journaled `warned`, and its remaining+ * actions are applied atomically. An applier that throws (a claudish bug)+ * leaves the working state as it was and journals each action of the step+ * `error` with detail `apply_failed:<message>`.*/- async run<E extends ClosedEvent>(+ async runChain<E extends ClosedEvent, S>(event: E,hooks: ReadonlyArray<ApplicableHook>,- context: (applicable: ApplicableHook, base: BaseContextParts) => object,+ step: ChainStep<EventActions[E], S>,meta: JournalMeta,- opts: RunOptions = {}- ): Promise<RunResult<EventActions[E]>> {- const runs = await Promise.all(- hooks.map((applicable) => this.runOne(event, applicable, context, meta, opts.signal))- );+ opts: ChainOptions<S>+ ): Promise<ChainResult<EventActions[E], S>> {+ type A = EventActions[E];+ const budget = EVENT_BUDGETS[event];+ const deadline = budget === null ? null : Date.now() + budget;+ const prior: PriorAction[] = [...(opts.prior ?? [])];+ const runs: Array<HookRun<A>> = [];+ const appliedAll: Array<PlannedAction<A>> = [];+ let state = opts.initial;++ for (const applicable of hooks) {+ if (opts.signal?.aborted) break;+ const { hook, severity } = applicable;+ if (this.disabled.has(hook.id)) continue;++ const timeout = stepTimeout(+ hook.def,+ event,+ deadline === null ? null : deadline - Date.now()+ );+ if (timeout === null) {+ this.journal({+ ...meta,+ event,+ hookId: hook.id,+ decision: "skipped",+ detail: EVENT_BUDGET_DETAIL,+ });+ runs.push({ applicable, status: "skipped", returned: [], applied: [] });+ continue;+ }++ const seen = state;+ const frozenPrior = Object.freeze([...prior]);+ const run = await this.runStep<E>(+ event,+ applicable,+ (base) => step.context(applicable, { ...base, prior: frozenPrior }, seen),+ meta,+ opts.signal,+ timeout+ );+ runs.push(run);+ if (run.status === "aborted") break;- const apply: Array<PlannedAction<EventActions[E]>> = [];- for (const run of runs) {- const { hook, severity } = run.applicable;+ // Severity gate: warn actions journal at the step; a warn hook applies nothing.+ const items: Array<PlannedAction<A>> = [];for (const action of run.returned) {if (action.type === "warn") {log(`[hooks] ${hook.id} warn: ${action.message}`);@@ -323,24 +534,70 @@ export class HookEngine {});continue;}- apply.push({ hookId: hook.id, action });+ items.push({ hookId: hook.id, action });+ }+ if (items.length === 0 || !step.apply) {+ step.afterStep?.(run, seen);+ continue;}++ let outcome: StepApplied<A, S>;+ try {+ outcome = step.apply(seen, items);+ } catch (err) {+ log(`[hooks] ${hook.id}: applying its actions failed: ${errorText(err)}`);+ for (const item of items) {+ this.journal({+ ...meta,+ event,+ hookId: hook.id,+ action: item.action.type,+ decision: "error",+ detail: `apply_failed:${errorText(err)}`,+ });+ }+ // No afterStep: the step's lines are the `error` ones above. An `ignored` line+ // from afterStep (no repair applied) would contradict them.+ continue;+ }+ state = outcome.state;+ if (outcome.results.length > 0) {+ this.recordResults(+ event,+ outcome.results,+ meta,+ step.journalExtra+ ? (r) => step.journalExtra?.(r as ActionResult<A>, seen) ?? {}+ : undefined+ );+ }+ for (const p of outcome.applied) {+ run.applied.push(p);+ appliedAll.push(p);+ // Already a deep-frozen copy (`collect`): the same object the working state+ // holds, so a later hook cannot write into it through ctx.prior.+ prior.push(Object.freeze({ hookId: p.hookId, action: p.action }));+ }+ step.afterStep?.(run, seen);}- return { runs, apply };+ return { runs, state, applied: appliedAll };}- private runOne<E extends ClosedEvent>(+ /** One step: call the handler within `timeout`, validate what it returned. */+ private runStep<E extends ClosedEvent>(event: E,applicable: ApplicableHook,- context: (applicable: ApplicableHook, base: BaseContextParts) => object,+ context: (base: BaseContextParts) => object,meta: JournalMeta,- parent: AbortSignal | undefined+ parent: AbortSignal | undefined,+ timeout: StepTimeout): Promise<HookRun<EventActions[E]>> {const { hook, severity } = applicable;const done = (status: HookRunStatus, returned: Array<EventActions[E]> = []) => ({applicable,status,returned,+ applied: [],});const handler = handlerOf(hook.def, event);@@ -348,7 +605,7 @@ export class HookEngine {if (parent?.aborted) return Promise.resolve(done("aborted"));const controller = new AbortController();- const timeoutMs = timeoutFor(hook.def, event);+ const timeoutMs = timeout.ms;const observe =event === "toolCall" &&(hook.def.on?.toolCall as { observe?: boolean } | undefined)?.observe === true;@@ -369,6 +626,7 @@ export class HookEngine {};parent?.addEventListener("abort", onParentAbort, { once: true });+ // A late result is discarded: once the timer fired, `settled` is true.const timer = setTimeout(() => {controller.abort(new Error(`hook ${hook.id} timed out after ${timeoutMs} ms`));this.journal({@@ -376,9 +634,11 @@ export class HookEngine {event,hookId: hook.id,decision: "timeout",- detail: `${timeoutMs} ms`,+ detail: timeout.clipped ? EVENT_BUDGET_DETAIL : `${timeoutMs} ms`,});- this.noteFailure(hook.id, meta, event);+ // Clipped beyond the margin: the steps before this one spent the budget, so it is+ // not this hook's failure. Within the margin it is the hook's own (stepTimeout).+ if (!timeout.clipped) this.noteFailure(hook.id, meta, event);finish(done("timeout"));}, timeoutMs);@@ -387,11 +647,12 @@ export class HookEngine {severity,log: (message: string) => log(`[hook ${hook.id}] ${message}`),signal: controller.signal,+ prior: [],};let value: unknown;try {- const ctx = Object.freeze(context(applicable, base));+ const ctx = Object.freeze(context(base));value = runInHookScope(hook.id, () => handler.fn.call(handler.self, ctx));} catch (err) {this.journal({@@ -415,8 +676,16 @@ export class HookEngine {finish(done("invalid"));return;}+ const actions = result.actions as Array<EventActions[E]>;+ if (result.notPlainData) {+ // Its other, valid actions still apply, as with any invalid action; but a+ // value claudish cannot copy is a broken return, so the step counts.+ this.noteFailure(hook.id, meta, event);+ finish(done("invalid", actions));+ return;+ }this.noteSuccess(hook.id);- finish(done("ok", result as Array<EventActions[E]>));+ finish(done("ok", actions));},(err: unknown) => {if (settled) return;@@ -437,6 +706,15 @@ export class HookEngine {/*** Validate a handler's return value. Returns the valid actions, or null when* the value itself is invalid (not an array, not undefined).+ *+ * Each action is COPIED before it is validated, and the deep-frozen copy is the+ * only object claudish uses from then on: the applier, stage B's held list, the+ * rewrite plan and `ctx.prior` all share it. So a hook cannot change an action+ * after returning it (from a timer, say) to slip past the limits checked here,+ * and a getter or a Proxy cannot show validation one value and the applier+ * another. A value that cannot be copied as plain data (a method, a Symbol, a+ * Proxy) is journaled `invalid` (`not_plain_data`) and sets `notPlainData`,+ * which counts the step toward the breaker.*/private collect(event: ClosedEvent,@@ -444,8 +722,8 @@ export class HookEngine {returned: unknown,meta: JournalMeta,observe: boolean- ): HookAction[] | null {- if (returned === undefined || returned === null) return [];+ ): { actions: HookAction[]; notPlainData: boolean } | null {+ if (returned === undefined || returned === null) return { actions: [], notPlainData: false };if (!Array.isArray(returned)) {this.journal({...meta,@@ -457,13 +735,45 @@ export class HookEngine {return null;}const valid: HookAction[] = [];- for (const value of returned) {- const checked = validateAction(event, value, { observe });+ if (returned.length > MAX_ACTIONS_PER_STEP) {+ // One line for the excess, not one per action: the array is unbounded.+ this.journal({+ ...meta,+ event,+ hookId,+ decision: "invalid",+ detail: `too_many_actions:${returned.length - MAX_ACTIONS_PER_STEP} over ${MAX_ACTIONS_PER_STEP}`,+ });+ }+ let notPlainData = false;+ for (const value of returned.slice(0, MAX_ACTIONS_PER_STEP)) {+ let copy: unknown;+ try {+ copy = structuredClone(value);+ } catch {+ notPlainData = true;+ let type: unknown;+ try {+ type = (value as { type?: unknown } | null)?.type;+ } catch {+ // a Proxy may throw on any read+ }+ this.journal({+ ...meta,+ event,+ hookId,+ action: typeof type === "string" ? type : undefined,+ decision: "invalid",+ detail: "not_plain_data",+ });+ continue;+ }+ const checked = validateAction(event, copy, { observe });if (checked.ok) {- valid.push(checked.action);+ valid.push(deepFreeze(checked.action));continue;}- const type = (value as { type?: unknown } | null)?.type;+ const type = (copy as { type?: unknown } | null)?.type;this.journal({...meta,event,@@ -473,7 +783,7 @@ export class HookEngine {detail: checked.reason,});}- return valid;+ return { actions: valid, notPlainData };}/**@@ -538,7 +848,7 @@ export class HookEngine {const upload = isUploadSurface(surface);const pathRelation = upload ? classifyPath(input.observedPath, input.expectedPath) : undefined;- if (upload && isUploadDecision(input.decision)) {+ if (upload && input.localOnly !== true && isUploadDecision(input.decision)) {const user = isUserHook(input.hookId);recordTelemetryDecision({sessionId: input.sessionId,diff --git a/packages/cli/src/hooks/raw.test.ts b/packages/cli/src/hooks/raw.test.tsnew file mode 100644index 00000000..24977221--- /dev/null+++ b/packages/cli/src/hooks/raw.test.ts@@ -0,0 +1,336 @@+/**+ * Raw tier units: the ResponseRecorder, `statsNames`, the Gemini built-in's+ * per-route cache, and the seam plan for a raw-only request. The end-to-end+ * containment rows (X-1 … X-8) are in handlers/composed-handler-raw.test.ts.+ */++import { describe, expect, it } from "bun:test";+import { createGeminiThoughtSignatureHook } from "./builtins/gemini-thought-signature.js";+import { builtinHooks } from "./builtins/index.js";+import { HookEngine } from "./engine.js";+import type { JournalEntry } from "./journal.js";+import type { HookDefinition, RouteInfo } from "./public.js";+import { RawRequest, ResponseRecorder, statsNames } from "./raw.js";+import { HookRegistry, type UserHookInput } from "./registry.js";+import { HookRequestScope } from "./request-stage.js";+import { planSeam } from "./response-seam.js";++const encoder = new TextEncoder();+const decoder = new TextDecoder();++function engineOf(+ builtins: ReturnType<typeof builtinHooks>,+ users: UserHookInput[] = [],+ journal: JournalEntry[] = []+): HookEngine {+ return new HookEngine({+ registry: new HookRegistry(builtins, users, undefined),+ config: {},+ hostMode: "other",+ journalSink: (e) => journal.push(e),+ warn: () => {},+ drainTelemetryOutbox: false,+ });+}++const route = (modelId: string, provider = "openrouter"): RouteInfo => ({+ modelId,+ provider,+ native: false,+});++function rawFor(engine: HookEngine, r: RouteInfo): RawRequest {+ return new RawRequest(+ engine,+ r,+ { model: r.modelId, provider: r.provider },+ { model: r.modelId, stream: true, systemText: "", messages: [], tools: [] }+ );+}++/** A source that hands out `n` chunks, counting pulls. */+function countingSource(n: number) {+ const state = { pulls: 0 };+ let i = 0;+ const stream = new ReadableStream<Uint8Array>(+ {+ pull(c) {+ state.pulls++;+ if (i >= n) c.close();+ else c.enqueue(encoder.encode(`chunk-${i++};`));+ },+ },+ { highWaterMark: 0 }+ );+ return { stream, state };+}++async function readAll(stream: ReadableStream<Uint8Array>): Promise<string> {+ let out = "";+ const reader = stream.getReader();+ for (;;) {+ const r = await reader.read();+ if (r.done) return out;+ out += decoder.decode(r.value);+ }+}++describe("ResponseRecorder", () => {+ it("drains its input to the end with no reader at all", async () => {+ const { stream, state } = countingSource(8);+ const recorder = new ResponseRecorder(stream);+ recorder.replay(); // a replay nobody reads+ await recorder.ended;+ expect(state.pulls).toBe(9); // 8 chunks + the pull that closed it+ expect(recorder.done).toBe(true);+ });++ it("serves independent replays from byte 0; cancelling one leaves the other", async () => {+ const { stream } = countingSource(4);+ const recorder = new ResponseRecorder(stream);+ const a = recorder.replay();+ const b = recorder.replay();+ const readerA = a.stream.getReader();+ await readerA.read();+ await readerA.cancel();+ expect(await readAll(b.stream)).toBe("chunk-0;chunk-1;chunk-2;chunk-3;");+ });++ it("a replay created later still starts at byte 0 while retaining", async () => {+ const { stream } = countingSource(3);+ const recorder = new ResponseRecorder(stream);+ await recorder.ended;+ expect(await readAll(recorder.replay().stream)).toBe("chunk-0;chunk-1;chunk-2;");+ });++ it("a replay of an errored input errors after the bytes it had", async () => {+ let n = 0;+ const stream = new ReadableStream<Uint8Array>({+ pull(c) {+ if (n++ === 0) c.enqueue(encoder.encode("first"));+ else c.error(new Error("upstream broke"));+ },+ });+ const recorder = new ResponseRecorder(stream);+ const reader = recorder.replay().stream.getReader();+ expect(decoder.decode((await reader.read()).value)).toBe("first");+ await expect(reader.read()).rejects.toThrow("upstream broke");+ });+});++describe("statsNames", () => {+ it("names the Gemini built-in on gemini and google/ models only", () => {+ const engine = engineOf(builtinHooks({}));+ expect(statsNames(engine, route("google/gemini-3.1-pro-preview"))).toEqual([+ "GeminiThoughtSignature",+ ]);+ expect(statsNames(engine, route("gemini-2.5-flash", "google"))).toEqual([+ "GeminiThoughtSignature",+ ]);+ expect(statsNames(engine, route("gpt-5.6-sol"))).toEqual([]);+ expect(statsNames(null, route("gemini-2.5-flash"))).toEqual([]);+ });++ it("never names a user hook, and an off built-in is not active", () => {+ const user: UserHookInput = {+ id: "hook:u/raw",+ module: "/u.ts",+ moduleIndex: 0,+ exportIndex: 0,+ def: {+ apiVersion: 1,+ id: "raw",+ unsafe: true,+ raw: { providerChunk() {} },+ } as HookDefinition,+ };+ const engine = engineOf([], [user]);+ expect(statsNames(engine, route("gemini-2.5-flash"))).toEqual([]);++ const off = new HookEngine({+ registry: new HookRegistry(builtinHooks({}), [], { "gemini/*": "off" }),+ config: {},+ hostMode: "other",+ journalSink: () => {},+ warn: () => {},+ drainTelemetryOutbox: false,+ });+ expect(statsNames(off, route("gemini-2.5-flash"))).toEqual([]);+ });+});++describe("Gemini built-in: the cache is per route", () => {+ const reasoningChunk = (sig: string, callId: string) => ({+ choices: [+ {+ delta: {+ reasoning_details: [{ type: "reasoning.text", signature: sig }],+ tool_calls: [{ index: 0, id: callId, function: { name: "Read", arguments: "" } }],+ },+ },+ ],+ });+ const assistantCall = (callId: string) => ({+ role: "assistant",+ content: "",+ tool_calls: [{ id: callId, type: "function", function: { name: "Read", arguments: "{}" } }],+ });++ async function streamThrough(engine: HookEngine, r: RouteInfo, chunk: unknown): Promise<void> {+ const tap = rawFor(engine, r).streamTap();+ expect(tap).toBeDefined();+ tap?.chunk(chunk, (c: any) => c.choices?.[0]?.delta);+ await tap?.streamEnd();+ }++ it("two models' signatures never mix, and each lands on its own call", async () => {+ const engine = engineOf([createGeminiThoughtSignatureHook()]);+ const a = route("google/gemini-3.1-pro-preview");+ const b = route("gemini-2.5-flash", "google");+ await streamThrough(engine, a, reasoningChunk("SIG-A", "call_a"));+ await streamThrough(engine, b, reasoningChunk("SIG-B", "call_b"));++ const messages = [assistantCall("call_a"), assistantCall("call_b")];+ const forA = await rawFor(engine, a).providerRequest({+ claudeRequest: {},+ messages: structuredClone(messages),+ tools: [],+ });+ const forB = await rawFor(engine, b).providerRequest({+ claudeRequest: {},+ messages: structuredClone(messages),+ tools: [],+ });+ const sigs = (m: any) => m.reasoning_details?.map((d: any) => d.signature) ?? null;+ expect(forA.messages.map(sigs)).toEqual([["SIG-A"], null]);+ expect(forB.messages.map(sigs)).toEqual([null, ["SIG-B"]]);+ });++ it("the client stream is not changed: a committed chunk equals the parsed one", () => {+ const engine = engineOf([createGeminiThoughtSignatureHook()]);+ const tap = rawFor(engine, route("gemini-2.5-flash")).streamTap();+ const chunk = reasoningChunk("SIG", "call_x");+ const out = tap?.chunk(chunk, (c: any) => c.choices?.[0]?.delta);+ expect(out).toEqual(chunk);+ });++ it("at warn it computes but never sends: the request stays as it is at off", async () => {+ const journal: JournalEntry[] = [];+ const engine = new HookEngine({+ registry: new HookRegistry([createGeminiThoughtSignatureHook()], [], { "gemini/*": "warn" }),+ config: {},+ hostMode: "other",+ journalSink: (e) => journal.push(e),+ warn: () => {},+ drainTelemetryOutbox: false,+ });+ const r = route("gemini-2.5-flash");+ await streamThrough(engine, r, reasoningChunk("SIG", "call_w"));+ const out = await rawFor(engine, r).providerRequest({+ claudeRequest: {},+ messages: [assistantCall("call_w")],+ tools: [],+ });+ expect((out.messages[0] as any).reasoning_details).toBeUndefined();+ expect(journal.some((e) => e.decision === "warned" && e.event === "raw")).toBe(true);+ expect(journal.some((e) => e.decision === "raw")).toBe(false);+ });+});++describe("seam plan", () => {+ it("a request whose only consumer is a raw response hook plans mode=none raw=1 tap=0", async () => {+ const user: UserHookInput = {+ id: "hook:u/resp",+ module: "/u.ts",+ moduleIndex: 0,+ exportIndex: 0,+ def: {+ apiVersion: 1,+ id: "resp",+ unsafe: true,+ raw: { response() {} },+ } as HookDefinition,+ };+ const engine = engineOf([], [user]);+ const scope = await HookRequestScope.begin(engine, null, {+ claudeRequest: { messages: [{ role: "user", content: "hi" }] },+ route: route("glm-5"),+ model: "glm-5",+ stream: true,+ });+ expect(planSeam(scope)).toEqual({ mode: "none", raw: 1, tap: false });+ });+});++describe("a client cancel while a raw response hook fails", () => {+ /** Every `controller.error()` any ReadableStream in this process makes, while installed. */+ function spyControllerErrors() {+ let ctor: { prototype: { error(e?: unknown): void } } | null = null;+ new ReadableStream({+ start(c) {+ ctor = (c as unknown as { constructor: typeof ctor }).constructor;+ },+ });+ const proto = (ctor as unknown as { prototype: { error(e?: unknown): void } }).prototype;+ const original = proto.error;+ const seen: unknown[] = [];+ proto.error = function (this: unknown, e?: unknown) {+ seen.push(e);+ return original.call(this, e);+ };+ const restore = () => {+ proto.error = original;+ };+ return { seen, restore };+ }++ for (const [name, fail] of [+ ["throws", "throw"],+ ["times out", "timeout"],+ ] as const) {+ it(`the hook ${name} after the cancel: no fallback is read, no controller.error is raised`, async () => {+ let release!: () => void;+ const gate = new Promise<void>((r) => {+ release = r;+ });+ const user: UserHookInput = {+ id: "hook:u/cr5",+ module: "/u.ts",+ moduleIndex: 0,+ exportIndex: 0,+ def: {+ apiVersion: 1,+ id: "cr5",+ unsafe: true,+ timeoutMs: 200,+ raw: {+ response: () =>+ fail === "throw"+ ? gate.then(() => {+ throw new Error("failed after the cancel");+ })+ : new Promise(() => {}),+ },+ } as HookDefinition,+ };+ const engine = engineOf([], [user]);+ const raw = rawFor(engine, route("glm-5"));+ const input = new Response(countingSource(4).stream, {+ headers: { "content-type": "application/json" },+ });+ const spy = spyControllerErrors();+ try {+ const reader = (raw.responseStages(input).body as ReadableStream<Uint8Array>).getReader();+ const pending = reader.read(); // a pull waiting for the decision+ await Bun.sleep(30); // the pull is running, parked on the undecided stage+ await reader.cancel("client went away");+ await pending.catch(() => undefined);+ release();+ await Bun.sleep(fail === "timeout" ? 400 : 50);+ expect(spy.seen).toEqual([]);+ } finally {+ spy.restore();+ }+ });+ }+});diff --git a/packages/cli/src/hooks/raw.ts b/packages/cli/src/hooks/raw.tsnew file mode 100644index 00000000..1714eade--- /dev/null+++ b/packages/cli/src/hooks/raw.ts@@ -0,0 +1,1004 @@+/**+ * The raw (unsafe) tier: hooks that receive provider-format objects and the+ * response itself, at the points the old `MiddlewareManager` had.+ *+ * Containment is TRANSACTIONAL (FR-8: a raw hook's failure is contained the+ * same way a throwing closed hook's is). A raw hook works on copies, and its+ * work reaches the request or the client only when its call succeeds:+ *+ * - `providerRequest` runs on `structuredClone` copies of `claudeRequest`,+ * `messages` and `tools`. They replace the pipeline's objects only when the+ * call returns, or its promise resolves, within its timeout. A throw, a+ * rejection or a timeout discards them, so a late mutation from an abandoned+ * call lands on copies nobody reads.+ * - `providerChunk` is synchronous by contract and runs on a clone of the+ * parsed provider event. A normal, non-thenable return COMMITS the clone by+ * identity: `RawStreamTap.chunk()` returns it and the parser reads that+ * object from then on, deletions included. A thenable return is an invalid+ * invocation — an `async` body that throws after mutating still returns a+ * promise, so committing on return would apply the mutation — and discards+ * the clone; a rejection handler is attached so a rejection is journaled and+ * never becomes an `unhandledRejection`.+ * - `providerStreamEnd` sees only the hook's own per-stream `metadata`, so+ * there is nothing to undo; it is bounded by its timeout.+ * - `response`: claudish drains the stage's input itself into a+ * `ResponseRecorder`. The hook's `ctx.response` is a replay of it, read at+ * the hook's own pace, and the fallback is a second replay, so a hook that+ * ignores its view stalls nothing. A replacement is read WHOLE and forwarded+ * only once it closes cleanly within its deadline; in every other case the+ * original goes, from its first byte. The client never sees a partial+ * replacement or an error the hook caused.+ *+ * Each raw stage is a hook chain (§4.4.1), the same execution model as the+ * closed tier: its hooks run one at a time in effective order, each on what the+ * previous committed, and a stage runs after the closed chain of its point+ * (`providerRequest` after the closed `request` chain and stage B; `response`+ * after the closed transform). `providerRequest` and `providerStreamEnd` share+ * an event budget: a step's timeout is its own or the budget left, whichever is+ * shorter, and a hook reached with none left is journaled `skipped`.+ * `providerChunk` is synchronous and `response` keeps per-step deadlines, so+ * neither has a budget.+ *+ * At `warn` severity a raw hook runs on copies that are never committed, so the+ * next raw step starts from the uncommitted state, and a returned replacement is+ * read to its end and discarded.+ *+ * Containment isolates failure; it does not validate what an unsafe hook+ * deliberately produces. That is what the `unsafe` label means.+ */++import { log } from "../logger.js";+import {+ EVENT_BUDGETS,+ EVENT_BUDGET_DETAIL,+ type HookEngine,+ type JournalInput,+ type JournalMeta,+ type StepTimeout,+ stepTimeout,+ timeoutFor,+} from "./engine.js";+import { runInHookScope } from "./output-capture.js";+import type {+ RawMiddleware,+ RawProviderChunkContext,+ RawProviderRequestContext,+ RawProviderStreamEndContext,+ RawResponseContext,+ RequestFacts,+ RouteInfo,+} from "./public.js";+import type { ApplicableHook, HookEventName } from "./registry.js";+import { HOLD_CAP_BYTES, PING_FRAME } from "./seam-transform.js";++export type RawStage = "providerRequest" | "providerChunk" | "providerStreamEnd" | "response";++const RAW_STAGES: ReadonlyArray<RawStage> = [+ "providerRequest",+ "providerChunk",+ "providerStreamEnd",+ "response",+];++/** What the parsers call at the old middleware sites. */+export interface RawStreamTap {+ /**+ * Runs the applicable `providerChunk` hooks synchronously in effective order,+ * each on a `structuredClone` of the previous result. Returns the object the+ * parser must read from now on: the last committed clone, or `chunk` itself+ * when nothing was committed. Never throws.+ */+ chunk<T>(chunk: T, deltaOf: (c: T) => unknown): T;+ /** `providerStreamEnd`, in effective order, each bounded by its timeout. Never rejects. */+ streamEnd(): Promise<void>;+}++/** The provider-format request `providerRequest` hooks see and may replace. */+export interface ProviderRequestState {+ // biome-ignore lint/suspicious/noExplicitAny: the Claude-format request is untyped at this layer+ claudeRequest: any;+ // biome-ignore lint/suspicious/noExplicitAny: provider format+ messages: any[];+ // biome-ignore lint/suspicious/noExplicitAny: provider format+ tools: any[];+}++export interface ResponseStageOptions {+ /** Interval of the stage's own pings while it holds a replacement. Default 1,000 ms. */+ pingIntervalMs?: number;+ /** Recorded original plus held replacement above this falls back to the original. Default 8 MiB. */+ capBytes?: number;+}++/* ───────────── helpers ───────────── */++/**+ * The reader surface this module uses. Annotated structurally, not as+ * `ReadableStreamDefaultReader`: bun-types and node:stream/web declare that+ * global differently (`readMany`), and a package that typechecks this file+ * under node's stream types (macos-bridge) rejects the bun one.+ */+type ByteReader = {+ read(): Promise<{ done: true; value?: unknown } | { done: false; value: Uint8Array }>;+ cancel(reason?: unknown): Promise<void>;+};++function errorText(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++function isThenable(value: unknown): value is PromiseLike<unknown> {+ return (+ value !== null &&+ (typeof value === "object" || typeof value === "function") &&+ typeof (value as { then?: unknown }).then === "function"+ );+}++type Bounded =+ | { status: "ok"; value: unknown }+ | { status: "error"; err: unknown }+ | { status: "timeout" };++/** Call `fn` and settle within `ms`. A synchronous throw is an `error`, never a rejection. */+function callBounded(fn: () => unknown, ms: number): Promise<Bounded> {+ let value: unknown;+ try {+ value = fn();+ } catch (err) {+ return Promise.resolve({ status: "error", err });+ }+ if (!isThenable(value)) return Promise.resolve({ status: "ok", value });+ return new Promise<Bounded>((resolveCall) => {+ const timer = setTimeout(() => resolveCall({ status: "timeout" }), ms);+ Promise.resolve(value).then(+ (v) => {+ clearTimeout(timer);+ resolveCall({ status: "ok", value: v });+ },+ (err: unknown) => {+ clearTimeout(timer);+ resolveCall({ status: "error", err });+ }+ );+ });+}++function rawOf(applicable: ApplicableHook): RawMiddleware {+ return ((applicable.hook.def as { raw?: RawMiddleware }).raw ?? {}) as RawMiddleware;+}++/* ───────────── stats ───────────── */++/**+ * `middleware_names` for stats: the `statsName` of every BUILT-IN raw hook that+ * applies to the route. User hooks never appear, so the OTLP `llm.middleware`+ * attribute does not change for users with hooks. Empty when no engine is+ * loaded in this process.+ */+export function statsNames(engine: HookEngine | null | undefined, route: RouteInfo): string[] {+ if (!engine) return [];+ const names: string[] = [];+ for (const stage of RAW_STAGES) {+ for (const { hook } of engine.registry.applicable(`raw.${stage}`, { route })) {+ if (hook.source === "builtin" && hook.statsName && !names.includes(hook.statsName)) {+ names.push(hook.statsName);+ }+ }+ }+ return names;+}++/* ───────────── one request's raw tier ───────────── */++/**+ * The raw tier for one upstream attempt. Owned by the attempt's+ * `HookRequestScope`; the terminal handler runs `providerRequest` and opens a+ * stream tap per parser, and the response seam runs the `response` stage.+ *+ * Every request a raw hook touches journals ONE line per hook (`decision:+ * "raw"`, its stages listed) and a debug-log line. A warn-severity run is+ * journaled `warned` once per hook and stage.+ */+export class RawRequest {+ private readonly touched = new Set<string>();+ private readonly warnedStages = new Set<string>();++ constructor(+ readonly engine: HookEngine,+ readonly route: RouteInfo,+ readonly meta: JournalMeta,+ /** The request as response-side hooks see it. */+ readonly facts: RequestFacts+ ) {}++ /** Applicable hooks for one stage, in effective order, minus breaker-disabled ones. */+ hooks(stage: RawStage): ApplicableHook[] {+ return this.engine.select(`raw.${stage}`, { route: this.route });+ }++ /** How many raw `response` hooks apply (the seam log's `raw=<n>`). */+ get responseHookCount(): number {+ return this.hooks("response").length;+ }++ /* ───────────── journaling ───────────── */++ journal(input: Omit<JournalInput, keyof JournalMeta | "localOnly">): void {+ this.engine.journal({ ...this.meta, ...input, localOnly: true });+ }++ private fail(+ applicable: ApplicableHook,+ stage: RawStage,+ decision: "error" | "timeout" | "invalid",+ detail: string,+ countsFailure = true+ ): void {+ const event: HookEventName = `raw.${stage}`;+ this.journal({ event, hookId: applicable.hook.id, decision, detail: `${stage}: ${detail}` });+ log(`[hooks] raw ${applicable.hook.id} ${stage} ${decision}: ${detail}`);+ if (countsFailure) this.engine.noteFailure(applicable.hook.id, this.meta, event);+ }++ /**+ * A step timed out: on its own timeout (counts), or on a budget clipped beyond the+ * margin (does not; `stepTimeout` in engine.ts holds the rule).+ */+ private timedOut(applicable: ApplicableHook, stage: RawStage, timeout: StepTimeout): void {+ if (timeout.clipped) this.fail(applicable, stage, "timeout", EVENT_BUDGET_DETAIL, false);+ else this.fail(applicable, stage, "timeout", `${timeout.ms} ms`);+ }++ /** The stage's budget was spent before this hook's step: not called, not counted. */+ private skip(applicable: ApplicableHook, stage: RawStage): void {+ this.journal({+ event: `raw.${stage}`,+ hookId: applicable.hook.id,+ decision: "skipped",+ detail: `${stage}: ${EVENT_BUDGET_DETAIL}`,+ });+ log(`[hooks] raw ${applicable.hook.id} ${stage} skipped: ${EVENT_BUDGET_DETAIL}`);+ }++ /** The step timeout of a budgeted stage whose chain started at `startedAt`; null = skip. */+ stepTimeoutFor(+ applicable: ApplicableHook,+ stage: "providerRequest" | "providerStreamEnd",+ startedAt: number+ ): StepTimeout | null {+ const event: HookEventName = `raw.${stage}`;+ const budget = EVENT_BUDGETS[event];+ const remaining = budget === null ? null : startedAt + budget - Date.now();+ return stepTimeout(applicable.hook.def, event, remaining);+ }++ private succeed(applicable: ApplicableHook, stage: RawStage): void {+ this.engine.noteSuccess(applicable.hook.id);+ const id = applicable.hook.id;+ if (applicable.severity === "warn") {+ const key = `${id}\0${stage}`;+ if (this.warnedStages.has(key)) return;+ this.warnedStages.add(key);+ this.journal({+ event: `raw.${stage}`,+ hookId: id,+ decision: "warned",+ detail: `${stage}: severity warn, not committed`,+ });+ return;+ }+ if (this.touched.has(id)) return;+ this.touched.add(id);+ const stages = applicable.hook.events+ .filter((e) => e.startsWith("raw."))+ .map((e) => e.slice(4))+ .join(",");+ this.journal({+ event: `raw.${stage}`,+ hookId: id,+ decision: "raw",+ detail: `stages: ${stages}`,+ });+ log(+ `[hooks] raw ${id} touched ${this.route.provider}/${this.route.modelId} (stages ${stages})`+ );+ }++ /* ───────────── providerRequest ───────────── */++ /**+ * Run the `providerRequest` chain: the hooks in effective order, each on+ * clones of the previous result, within the stage's budget. Returns the state+ * the pipeline continues with: the input itself when nothing was committed.+ * Never rejects.+ */+ async providerRequest(input: ProviderRequestState): Promise<ProviderRequestState> {+ let current = input;+ const startedAt = Date.now();+ for (const applicable of this.hooks("providerRequest")) {+ if (this.engine.isDisabled(applicable.hook.id)) continue;+ const fn = rawOf(applicable).providerRequest;+ if (typeof fn !== "function") continue;+ const timeout = this.stepTimeoutFor(applicable, "providerRequest", startedAt);+ if (!timeout) {+ this.skip(applicable, "providerRequest");+ continue;+ }++ let ctx: RawProviderRequestContext;+ try {+ ctx = {+ hookId: applicable.hook.id,+ route: this.route,+ claudeRequest: structuredClone(current.claudeRequest),+ messages: structuredClone(current.messages),+ tools: structuredClone(current.tools),+ };+ } catch (err) {+ this.fail(+ applicable,+ "providerRequest",+ "error",+ `request not cloneable: ${errorText(err)}`+ );+ continue;+ }++ const raw = rawOf(applicable);+ const outcome = await callBounded(+ () => runInHookScope(applicable.hook.id, () => fn.call(raw, ctx)),+ timeout.ms+ );+ if (outcome.status === "timeout") {+ this.timedOut(applicable, "providerRequest", timeout);+ continue;+ }+ if (outcome.status === "error") {+ this.fail(applicable, "providerRequest", "error", errorText(outcome.err));+ continue;+ }+ // A hook may replace the fields, not only edit them; it may not replace+ // them with something the pipeline cannot carry on with.+ if (+ !ctx.claudeRequest ||+ typeof ctx.claudeRequest !== "object" ||+ !Array.isArray(ctx.messages) ||+ !Array.isArray(ctx.tools)+ ) {+ this.fail(+ applicable,+ "providerRequest",+ "invalid",+ "claudeRequest, messages or tools replaced by a non-object"+ );+ continue;+ }+ this.succeed(applicable, "providerRequest");+ if (applicable.severity !== "fix") continue;+ current = { claudeRequest: ctx.claudeRequest, messages: ctx.messages, tools: ctx.tools };+ }+ return current;+ }++ /* ───────────── stream tap ───────────── */++ /**+ * A tap for one parser stream, or undefined when no `providerChunk` or+ * `providerStreamEnd` hook applies (the parser then does nothing extra).+ */+ streamTap(): RawStreamTap | undefined {+ const chunkHooks = this.hooks("providerChunk");+ const endHooks = this.hooks("providerStreamEnd");+ if (chunkHooks.length === 0 && endHooks.length === 0) return undefined;+ return new StreamTap(this, chunkHooks, endHooks);+ }++ /** @internal the tap reports through these. */+ reportFail(+ applicable: ApplicableHook,+ stage: RawStage,+ decision: "error" | "timeout" | "invalid",+ detail: string+ ): void {+ this.fail(applicable, stage, decision, detail);+ }++ /** @internal */+ reportSuccess(applicable: ApplicableHook, stage: RawStage): void {+ this.succeed(applicable, stage);+ }++ /** @internal */+ reportTimeout(applicable: ApplicableHook, stage: RawStage, timeout: StepTimeout): void {+ this.timedOut(applicable, stage, timeout);+ }++ /** @internal */+ reportSkip(applicable: ApplicableHook, stage: RawStage): void {+ this.skip(applicable, stage);+ }++ /* ───────────── response ───────────── */++ /**+ * Run the `response` stage: each applicable hook in effective order, each+ * over the previous stage's output. Returns `response` itself when no hook+ * applies.+ */+ responseStages(response: Response, opts: ResponseStageOptions = {}): Response {+ let current = response;+ for (const applicable of this.hooks("response")) {+ if (this.engine.isDisabled(applicable.hook.id)) continue;+ current = responseStage(current, applicable, this, opts);+ }+ return current;+ }+}++/* ───────────── RawStreamTap ───────────── */++class StreamTap implements RawStreamTap {+ /** Per hook, per stream; shared across that hook's calls; never cloned. */+ private readonly metadata = new Map<string, Map<string, unknown>>();+ private ended = false;++ constructor(+ private readonly raw: RawRequest,+ private readonly chunkHooks: ApplicableHook[],+ private readonly endHooks: ApplicableHook[]+ ) {}++ private metadataFor(hookId: string): Map<string, unknown> {+ let m = this.metadata.get(hookId);+ if (!m) {+ m = new Map();+ this.metadata.set(hookId, m);+ }+ return m;+ }++ chunk<T>(chunk: T, deltaOf: (c: T) => unknown): T {+ let current = chunk;+ for (const applicable of this.chunkHooks) {+ const id = applicable.hook.id;+ if (this.raw.engine.isDisabled(id)) continue;+ const raw = rawOf(applicable);+ const fn = raw.providerChunk;+ if (typeof fn !== "function") continue;++ let ctx: RawProviderChunkContext;+ try {+ const clone = structuredClone(current);+ ctx = {+ hookId: id,+ route: this.raw.route,+ chunk: clone,+ delta: deltaOf(clone),+ metadata: this.metadataFor(id),+ };+ } catch (err) {+ this.raw.reportFail(+ applicable,+ "providerChunk",+ "error",+ `chunk not cloneable: ${errorText(err)}`+ );+ continue;+ }++ let returned: unknown;+ try {+ returned = runInHookScope(id, () => fn.call(raw, ctx));+ } catch (err) {+ this.raw.reportFail(applicable, "providerChunk", "error", errorText(err));+ continue;+ }+ if (isThenable(returned)) {+ // Whatever the promise later does, this clone is never committed.+ this.raw.reportFail(applicable, "providerChunk", "invalid", "async_return");+ try {+ Promise.resolve(returned).then(undefined, (err: unknown) => {+ this.raw.journal({+ event: "raw.providerChunk",+ hookId: id,+ decision: "error",+ detail: `providerChunk: ${errorText(err)}`,+ });+ });+ } catch {+ // A hostile thenable whose `then` throws: nothing left to attach to.+ }+ continue;+ }+ this.raw.reportSuccess(applicable, "providerChunk");+ if (applicable.severity !== "fix") continue;+ current = ctx.chunk as T;+ }+ return current;+ }++ async streamEnd(): Promise<void> {+ if (this.ended) return;+ this.ended = true;+ const startedAt = Date.now();+ for (const applicable of this.endHooks) {+ const id = applicable.hook.id;+ if (this.raw.engine.isDisabled(id)) continue;+ const raw = rawOf(applicable);+ const fn = raw.providerStreamEnd;+ if (typeof fn !== "function") continue;+ const timeout = this.raw.stepTimeoutFor(applicable, "providerStreamEnd", startedAt);+ if (!timeout) {+ this.raw.reportSkip(applicable, "providerStreamEnd");+ continue;+ }+ const ctx: RawProviderStreamEndContext = {+ hookId: id,+ route: this.raw.route,+ metadata: this.metadataFor(id),+ };+ const outcome = await callBounded(+ () => runInHookScope(id, () => fn.call(raw, ctx)),+ timeout.ms+ );+ if (outcome.status === "timeout") {+ this.raw.reportTimeout(applicable, "providerStreamEnd", timeout);+ } else if (outcome.status === "error") {+ this.raw.reportFail(applicable, "providerStreamEnd", "error", errorText(outcome.err));+ } else {+ this.raw.reportSuccess(applicable, "providerStreamEnd");+ }+ }+ }+}++/* ───────────── ResponseRecorder ───────────── */++interface Cursor {+ pos: number;+ detached: boolean;+}++/** A replay of the recorder from byte 0, and the way to let go of it. */+export interface Replay {+ stream: ReadableStream<Uint8Array>;+ /** Stop reading: the replay closes and its chunks may be freed. Idempotent. */+ detach(): void;+}++/**+ * Reads a body to its end at upstream speed, whatever its readers do, and+ * serves any number of replays from byte 0. A replay never slows the recorder,+ * and cancelling one cancels neither the recorder nor another replay.+ *+ * Every chunk is retained until `stopRetaining()`; after that a chunk is freed+ * once every live replay has read past it.+ */+export class ResponseRecorder {+ private chunks: Uint8Array[] = [];+ /** Index (in the whole recording) of `chunks[0]`. */+ private base = 0;+ private retainAll = true;+ private readonly cursors = new Set<Cursor>();+ private wake: Array<() => void> = [];+ private readonly reader: ByteReader;++ /** Bytes read so far. */+ totalBytes = 0;+ done = false;+ failed = false;+ failure: unknown = undefined;+ /** Resolves when the input ends, errors or is cancelled. Never rejects. */+ readonly ended: Promise<void>;++ constructor(+ body: ReadableStream<Uint8Array>,+ private readonly onChunk: () => void = () => {}+ ) {+ this.reader = body.getReader();+ this.ended = this.pump();+ }++ private async pump(): Promise<void> {+ try {+ for (;;) {+ const r = await this.reader.read();+ if (r.done) break;+ this.chunks.push(r.value);+ this.totalBytes += r.value.byteLength;+ this.release();+ this.notify();+ this.onChunk();+ }+ } catch (err) {+ this.failed = true;+ this.failure = err;+ } finally {+ this.done = true;+ this.notify();+ }+ }++ private notify(): void {+ const waiting = this.wake;+ this.wake = [];+ for (const w of waiting) w();+ }++ private next(): Promise<void> {+ return new Promise((r) => this.wake.push(r));+ }++ /**+ * A new replay from byte 0. Must be created before `stopRetaining()`. `copy` hands+ * out a copy of each chunk instead of the retained bytes: a hook's view must, since a+ * hook may edit what it reads in place, and the retained bytes are the fallback the+ * client gets when that hook fails or is not committed.+ */+ replay(opts: { copy?: boolean } = {}): Replay {+ const cursor: Cursor = { pos: this.base, detached: false };+ this.cursors.add(cursor);+ const detach = () => {+ if (cursor.detached) return;+ cursor.detached = true;+ this.cursors.delete(cursor);+ this.release();+ this.notify();+ };+ const stream = new ReadableStream<Uint8Array>(+ {+ pull: async (controller) => {+ for (;;) {+ if (cursor.detached) {+ controller.close();+ return;+ }+ const idx = cursor.pos - this.base;+ if (idx < this.chunks.length) {+ const chunk = this.chunks[idx] as Uint8Array;+ cursor.pos++;+ this.release();+ // `new Uint8Array(chunk)` allocates: `chunk.slice()` would not on a Node+ // Buffer (a hook may return one), whose `slice` is a view of the same bytes.+ controller.enqueue(opts.copy ? new Uint8Array(chunk) : chunk);+ return;+ }+ if (this.done) {+ detach();+ if (this.failed) controller.error(this.failure);+ else controller.close();+ return;+ }+ await this.next();+ }+ },+ cancel: () => detach(),+ },+ { highWaterMark: 0 }+ );+ return { stream, detach };+ }++ /** From now on, free each chunk once every live replay has read past it. */+ stopRetaining(): void {+ this.retainAll = false;+ this.release();+ }++ private release(): void {+ if (this.retainAll) return;+ let min = this.base + this.chunks.length;+ for (const c of this.cursors) min = Math.min(min, c.pos);+ const drop = min - this.base;+ if (drop <= 0) return;+ this.chunks = this.chunks.slice(drop);+ this.base = min;+ }++ /** Cancel the input (and so the upstream). */+ cancel(reason?: unknown): void {+ this.reader.cancel(reason).catch(() => {});+ }+}++/* ───────────── one response hook ───────────── */++function isJsonResponse(response: Response): boolean {+ return (response.headers.get("content-type") ?? "").includes("application/json");+}++function sleep(ms: number): { promise: Promise<void>; clear(): void } {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const promise = new Promise<void>((r) => {+ timer = setTimeout(r, Math.max(0, ms));+ });+ return { promise, clear: () => clearTimeout(timer) };+}++type StageDecision = { kind: "original" } | { kind: "replacement"; chunks: Uint8Array[] };++/**+ * One raw `response` hook over one input Response (§6). The returned Response+ * streams the original as soon as the hook returns nothing, holds a returned+ * replacement whole (emitting pings meanwhile on an SSE response) and forwards+ * it only once it closed cleanly within its deadline, and otherwise forwards+ * the original from its first byte.+ */+function responseStage(+ input: Response,+ applicable: ApplicableHook,+ raw: RawRequest,+ opts: ResponseStageOptions+): Response {+ if (!input.body) return input;+ const id = applicable.hook.id;+ const json = isJsonResponse(input);+ const pingIntervalMs = opts.pingIntervalMs ?? 1_000;+ const capBytes = opts.capBytes ?? HOLD_CAP_BYTES;+ const timeoutMs = timeoutFor(applicable.hook.def, "raw.response");+ const encoder = new TextEncoder();+ const ping = encoder.encode(PING_FRAME);++ let decision: StageDecision | null = null;+ let holding = false;+ let heldBytes = 0;+ let cancelled = false;+ let fallback: Replay | null = null;+ let fallbackReader: ByteReader | null = null;+ let replacementReader: ByteReader | null = null;++ // Wakes the client-side pull when the state changes.+ let changed: () => void = () => {};+ let changedPromise = new Promise<void>((r) => {+ changed = r;+ });+ const signal = () => {+ const fire = changed;+ changedPromise = new Promise<void>((r) => {+ changed = r;+ });+ fire();+ };++ const recorder = new ResponseRecorder(input.body, () => {+ if (decision === null && recorder.totalBytes + heldBytes > capBytes) {+ raw.reportFail(applicable, "response", "invalid", "buffer_cap");+ decideOriginal();+ }+ });+ const view = recorder.replay({ copy: true });++ function cancelReplacement(): void {+ const reader = replacementReader;+ replacementReader = null;+ reader?.cancel().catch(() => {});+ }++ /**+ * The client gets the original. The hook's view ends here too, unless `keepView`: a+ * warn replacement may be built from `ctx.response`, and it is read against the view+ * to its end before `run()` detaches it.+ */+ function decideOriginal(keepView = false): void {+ if (decision !== null) return;+ if (!cancelled) {+ fallback = recorder.replay();+ fallbackReader = fallback.stream.getReader();+ }+ if (!keepView) view.detach();+ cancelReplacement();+ recorder.stopRetaining();+ decision = { kind: "original" };+ signal();+ }++ function decideReplacement(chunks: Uint8Array[]): void {+ if (decision !== null) return;+ view.detach();+ recorder.stopRetaining();+ decision = { kind: "replacement", chunks };+ signal();+ }++ /**+ * Read a replacement to its end within the deadline: this hook's timeout+ * after the LATER of the call's return (now) and the end of the original,+ * which claudish reads itself, so that end never waits on a reader. `keep`+ * holds the bytes for the client (fix); otherwise they are discarded (warn).+ */+ async function readWhole(+ replacement: Response,+ keep: boolean+ ): Promise<+ | { ok: true; chunks: Uint8Array[] }+ | { ok: false; decision: "timeout" | "error" | "invalid"; detail: string }+ > {+ const chunks: Uint8Array[] = [];+ if (!replacement.body) return { ok: true, chunks };+ const reader = replacement.body.getReader();+ replacementReader = reader;+ let finished = false;+ let deadlineTimer: { promise: Promise<void>; clear(): void } | null = null;+ const timedOut = recorder.ended.then(() => {+ if (finished) return new Promise<never>(() => {});+ deadlineTimer = sleep(timeoutMs);+ return deadlineTimer.promise.then(() => "timeout" as const);+ });+ try {+ for (;;) {+ if (cancelled || (keep && decision !== null)) {+ return { ok: false, decision: "invalid", detail: "superseded" };+ }+ const r = await Promise.race([reader.read(), timedOut]);+ if (r === "timeout") {+ return {+ ok: false,+ decision: "timeout",+ detail: `replacement did not close within ${timeoutMs} ms`,+ };+ }+ if (r.done) return { ok: true, chunks };+ if (!keep) continue;+ chunks.push(r.value);+ heldBytes += r.value.byteLength;+ if (recorder.totalBytes + heldBytes > capBytes) {+ return { ok: false, decision: "invalid", detail: "buffer_cap" };+ }+ }+ } catch (err) {+ return { ok: false, decision: "error", detail: `replacement errored: ${errorText(err)}` };+ } finally {+ finished = true;+ (deadlineTimer as { clear(): void } | null)?.clear();+ }+ }++ async function run(): Promise<void> {+ const ctx: RawResponseContext = {+ hookId: id,+ route: raw.route,+ request: raw.facts,+ response: new Response(view.stream, {+ status: input.status,+ statusText: input.statusText,+ headers: input.headers,+ }),+ };+ const rawHook = rawOf(applicable);+ const fn = rawHook.response;+ const outcome =+ typeof fn === "function"+ ? await callBounded(() => runInHookScope(id, () => fn.call(rawHook, ctx)), timeoutMs)+ : ({ status: "ok", value: undefined } as Bounded);++ const returned = outcome.status === "ok" ? outcome.value : undefined;+ const isResponse = returned instanceof Response;++ if (decision !== null || cancelled) {+ // Decided while the call ran (the hold cap, or the client went away).+ if (isResponse) (returned as Response).body?.cancel().catch(() => {});+ return;+ }+ if (outcome.status === "timeout") {+ raw.reportFail(applicable, "response", "timeout", `${timeoutMs} ms`);+ decideOriginal();+ return;+ }+ if (outcome.status === "error") {+ raw.reportFail(applicable, "response", "error", errorText(outcome.err));+ decideOriginal();+ return;+ }+ if (returned === undefined || returned === null) {+ raw.reportSuccess(applicable, "response");+ decideOriginal();+ return;+ }+ if (!isResponse) {+ raw.reportFail(applicable, "response", "invalid", "returned a value that is not a Response");+ decideOriginal();+ return;+ }++ if (applicable.severity !== "fix") {+ // Read to its end and discarded; the original goes at once. The view stays+ // readable until then: the replacement may stream it.+ decideOriginal(true);+ const read = await readWhole(returned as Response, false).finally(() => view.detach());+ if (read.ok) raw.reportSuccess(applicable, "response");+ else {+ cancelReplacement();+ raw.reportFail(applicable, "response", read.decision, read.detail);+ }+ return;+ }++ holding = true;+ signal();+ const read = await readWhole(returned as Response, true);+ if (decision !== null || cancelled) {+ cancelReplacement();+ return;+ }+ if (read.ok) {+ raw.reportSuccess(applicable, "response");+ decideReplacement(read.chunks);+ return;+ }+ cancelReplacement();+ raw.reportFail(applicable, "response", read.decision, read.detail);+ decideOriginal();+ }++ let replacementIndex = 0;+ let lastPingAt = Date.now();+ let pingedSinceHold = false;++ const out = new ReadableStream<Uint8Array>(+ {+ pull: async (controller) => {+ for (;;) {+ const d = decision as StageDecision | null;+ if (d?.kind === "replacement") {+ if (replacementIndex < d.chunks.length) {+ controller.enqueue(d.chunks[replacementIndex++] as Uint8Array);+ return;+ }+ controller.close();+ return;+ }+ if (d?.kind === "original") {+ try {+ const r = await (fallbackReader as ByteReader).read();+ if (r.done) controller.close();+ else controller.enqueue(r.value);+ } catch (err) {+ controller.error(err);+ }+ return;+ }+ // Undecided: wait for a decision, emitting keepalive pings on SSE.+ const wait = changedPromise;+ if (json) {+ await wait;+ continue;+ }+ const due = holding && !pingedSinceHold ? 0 : lastPingAt + pingIntervalMs - Date.now();+ const timer = sleep(due);+ const which = await Promise.race([+ wait.then(() => "changed" as const),+ timer.promise.then(() => "ping" as const),+ ]);+ timer.clear();+ if (which === "ping" && decision === null) {+ lastPingAt = Date.now();+ if (holding) pingedSinceHold = true;+ controller.enqueue(ping);+ return;+ }+ }+ },+ cancel: (reason) => {+ cancelled = true;+ recorder.cancel(reason);+ view.detach();+ cancelReplacement();+ (fallbackReader as ByteReader | null)?.cancel(reason).catch(() => {});+ (fallback as Replay | null)?.detach();+ signal();+ },+ },+ { highWaterMark: 0 }+ );++ void run().catch((err) => {+ // run() isolates every hook failure itself; this guards the stage.+ log(`[hooks] raw ${id} response stage failed open: ${errorText(err)}`);+ decideOriginal();+ });++ const headers = new Headers(input.headers);+ headers.delete("content-length");+ return new Response(out, { status: input.status, statusText: input.statusText, headers });+}diff --git a/packages/cli/src/hooks/request-stage.ts b/packages/cli/src/hooks/request-stage.tsindex 952054ae..eee6eae8 100644--- a/packages/cli/src/hooks/request-stage.ts+++ b/packages/cli/src/hooks/request-stage.ts@@ -1,17 +1,26 @@/**- * The request stage: `request` hooks run once per upstream attempt, and their- * actions are applied at two points of the terminal handler.+ * The request stage: `request` hooks run once per upstream attempt, as a hook+ * chain (§4.4.1), and their actions are applied at two points of the terminal+ * handler.*- * - **Stage A, before conversion**: `injectSystemNote` (pending notes- * included), the message actions, `replaceToolSchema`, `removeTool`. Applied- * to the Claude-format request before the adapter converts it, so a system- * note reaches every route — chat-completions adapters build their payload- * from the converted `messages` alone.+ * - **Stage A, before conversion, at each step**: `injectSystemNote`, the+ * message actions, `replaceToolSchema`, `removeTool`, applied to the chain's+ * working state after the hook that returned them and before the next hook+ * is called. Step 0 is the pending notes `responseEnd` stored, so every+ * request hook sees them. The final state becomes the attempt's Claude-format+ * request before the adapter converts it, so a system note reaches every+ * route — chat-completions adapters build their payload from the converted+ * `messages` alone.* - **Stage B, after conversion**: `rewriteToolDescription` and- * `replaceToolDescription`, applied to the Claude-format tools AND the- * converted tools. Stage B is why plan mode keeps working under- * `--summarize-tools`, which cuts a converted description to its first- * sentence: the append lands after that cut.+ * `replaceToolDescription`, replayed in chain order on the Claude-format tools+ * AND the converted tools. During the chain they are an overlay: later hooks+ * see the resulting description in `ctx.request.tools`, but the Claude-format+ * tools `convertTools` summarises stay unedited. Stage B is why plan mode+ * keeps working under `--summarize-tools`, which cuts a converted description+ * to its first sentence: the append lands after that cut.+ *+ * `ctx.harness` is detected once, from the request as Claude Code sent it, and+ * is the same for every step.** The stage runs only when `withHooks` put the per-request `RequestHooks` on the* Hono context. The classifier passthrough, monitor mode, `--probe` and direct@@ -30,22 +39,28 @@ import { log } from "../logger.js";import {type MutableClaudeRequest,type PlannedAction,+ type RequestChainState,applyStageA,applyStageB,+ overlayToolDescriptions,+ requestChainState,} from "./actions.js";import { type HookEngine, type JournalMeta, PENDING_NOTE_ID } from "./engine.js";+import { deepFreeze, frozenClone } from "./freeze.js";import { detectHarnessFacts, extractAvailableSkills, extractSessionId } from "./harness.js";import { type InjectionSink, sinkFromEnv } from "./injection/sinks.js";import type {ClaudeMessage,ClaudeTool,HarnessFacts,+ PriorAction,ProxySessionRef,RequestAction,RequestContext,RequestFacts,RouteInfo,} from "./public.js";+import { RawRequest } from "./raw.js";import type { ApplicableHook } from "./registry.js";import { recordTelemetryTurn } from "./telemetry/aggregate.js";@@ -176,6 +191,8 @@ export class RequestHooks {hookScopeOf(c)?.abandon();const scope = await HookRequestScope.begin(this.engine, this.session, input);contextSet(c, HOOK_SCOPE_CONTEXT_KEY, scope);+ // The interactive launcher's driver follows the session the requests name (§7.5).+ if (scope.sessionId) this.sink.noteSessionId?.(scope.sessionId);return scope;}}@@ -216,6 +233,8 @@ export class HookRequestScope {readonly rewriteClaimants: ReadonlyArray<string>;/** The response-side hooks this request armed (§5.3). */readonly response: Readonly<ResponsePlan>;+ /** This attempt's raw (unsafe) tier: `providerRequest`, the parser taps, the `response` stage. */+ readonly raw: RawRequest;private held: PlannedAction<RequestAction>[];private state: ScopeState = "open";@@ -227,9 +246,9 @@ export class HookRequestScope {readonly sessionId: string | undefined,readonly meta: JournalMeta,held: PlannedAction<RequestAction>[],- private readonly removedTools: ReadonlySet<string>,+ private readonly removedTools: ReadonlyMap<string, number>,private readonly pendingSeqs: ReadonlyArray<number>,- /** The request as the response-side hooks see it (post stage A). */+ /** The request as the response-side hooks see it: the request chain's final view. */readonly facts: RequestFacts,readonly session: ProxySessionRef | null,response: ResponsePlan@@ -240,19 +259,24 @@ export class HookRequestScope {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);+ this.raw = new RawRequest(engine, route, meta, facts);}- /** A proxy-event context for a response-side hook (the request facts are post stage A). */+ /**+ * A proxy-event context for a response-side hook (the request chain's final view).+ * `extra` (the tool call, the response view) is given to the hook as a deep-frozen+ * copy: its objects are what the seam serialises to the client afterwards.+ */proxyContext<T extends object>(base: object, event: string, extra: T): object {return {...base,event,- host: { mode: this.engine.hostMode },+ host: Object.freeze({ mode: this.engine.hostMode }),route: this.route,request: this.facts,harness: this.harness,session: this.session,- ...extra,+ ...frozenClone(extra),};}@@ -274,73 +298,122 @@ export class HookRequestScope {const requestHooks = engine.select("request", { route });const toolCallHooks = engine.select("toolCall", { route });const rewriteHooks = engine.select("responseRewrite", { route });- const anyHook = requestHooks.length + toolCallHooks.length + rewriteHooks.length > 0;-- // 1. Harness facts.- const harness: HarnessFacts = anyHook- ? harnessOf(claudeRequest, sessionId)- : sessionId- ? { planModeActive: false, sessionId }- : { planModeActive: false };-- const facts: RequestFacts = {- model: input.model,- stream: input.stream,- systemText: systemTextOf(claudeRequest.system),- messages: (claudeRequest.messages ?? []) as ReadonlyArray<ClaudeMessage>,- tools: (claudeRequest.tools ?? []) as ReadonlyArray<ClaudeTool>,+ // responseEnd reads ctx.harness too: selected once, here, for the plan below+ const endHooks = engine.select("responseEnd", { route });+ const anyHook =+ requestHooks.length + toolCallHooks.length + rewriteHooks.length + endHooks.length > 0;++ // 1. Harness facts, ONCE, from the request as Claude Code sent it: they+ // describe the client, so no hook's edit can change another hook's idea+ // of whether plan mode is on.+ // Deep-frozen: every hook, `claims()`, `armed()` and the observer read the same+ // object, so a write by one hook would change what all the others see.+ const harness: HarnessFacts = deepFreeze(+ anyHook+ ? harnessOf(claudeRequest, sessionId)+ : sessionId+ ? { planModeActive: false, sessionId }+ : { planModeActive: false }+ );+ // Hook-visible copies: the route and session objects belong to the caller.+ const hookRoute: RouteInfo = Object.freeze({ ...route });+ const hookSession: ProxySessionRef | null = session ? Object.freeze({ ...session }) : null;++ // The request view of one working state, built once per state and frozen: every+ // later step and the response-side hooks read it. `messages` and `tools` are+ // deep-frozen copies made on first read, because their elements are the objects+ // the provider payload is built from; a hook that never reads them pays nothing.+ let viewed: RequestChainState | null = null;+ let view: RequestFacts | null = null;+ const factsOf = (state: RequestChainState): RequestFacts => {+ if (state === viewed && view) return view;+ viewed = state;+ let messages: ReadonlyArray<ClaudeMessage> | undefined;+ let tools: ReadonlyArray<ClaudeTool> | undefined;+ view = Object.freeze({+ model: input.model,+ stream: input.stream,+ systemText: systemTextOf(state.system),+ get messages() {+ messages ??= frozenArrayCopy<ClaudeMessage>(state.messages);+ return messages;+ },+ get tools() {+ tools ??= frozenArrayCopy<ClaudeTool>(overlayToolDescriptions(state.tools, state.held));+ return tools;+ },+ });+ return view;};- const requestContext = (base: object): RequestContext =>+ const requestContext = (base: object, facts: RequestFacts): RequestContext =>({...base,event: "request",- host: { mode: engine.hostMode },- route,+ host: Object.freeze({ mode: engine.hostMode }),+ route: hookRoute,request: facts,harness,- session,+ session: hookSession,}) as RequestContext;- const run =- requestHooks.length > 0- ? await engine.run("request", requestHooks, (_a, base) => requestContext(base), meta)- : { runs: [], apply: [] };-- // 3 + 4. Stage A, with the pending notes peeked (removed only on commit),- // in one pass so an identical note from a hook and from the store is- // applied once.+ // 3. Step 0: the pending notes, peeked (removed only on commit), so every+ // request hook sees them in systemText and in ctx.prior.+ let state = requestChainState(claudeRequest);const notes = engine.peekNotes(sessionId);- const noteItems: PlannedAction<RequestAction>[] = notes.map((n) => ({- hookId: PENDING_NOTE_ID,- action: { type: "injectSystemNote", text: n.text },- }));- const items = [...run.apply, ...noteItems];- const stageA =- items.length > 0- ? applyStageA(claudeRequest, items)- : { results: [], held: [], removedTools: new Set<string>() };- if (stageA.results.length > 0) engine.recordResults("request", stageA.results, meta);+ let prior: PriorAction[] = [];+ let applied = 0;+ if (notes.length > 0) {+ const step0 = applyStageA(+ state,+ notes.map((n) => ({+ hookId: PENDING_NOTE_ID,+ action: { type: "injectSystemNote", text: n.text },+ }))+ );+ state = step0.state;+ engine.recordResults("request", step0.results, meta);+ prior = step0.applied.map((p) =>+ Object.freeze({ hookId: p.hookId, action: frozenClone(p.action) })+ );+ applied += step0.applied.length;+ }++ // 4. The request hook chain: each step's stage-A actions applied to the+ // working state before the next hook, description actions added to the+ // overlay its successors see in ctx.request.tools.+ if (requestHooks.length > 0) {+ const chain = await engine.runChain(+ "request",+ requestHooks,+ {+ context: (_a, base, s) => requestContext(base, factsOf(s)),+ apply: (s, items) => applyStageA(s, items),+ },+ meta,+ { initial: state, prior }+ );+ state = chain.state;+ applied += chain.applied.length;+ }++ // The attempt's own request takes the final working state; a field no step+ // changed keeps its object (and its absence).+ if (state.system !== claudeRequest.system) claudeRequest.system = state.system;+ if (state.messages !== claudeRequest.messages) claudeRequest.messages = state.messages;+ if (state.tools !== claudeRequest.tools) claudeRequest.tools = state.tools;// 6. Armed tools and rewrite claims, evaluated once, before any response.- // 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>,- };+ // The request facts the response-side hooks see are the request chain's+ // final view: what the provider actually receives.+ const postFacts = factsOf(state);const predicateContext = (applicable: ApplicableHook): RequestContext =>- ({- ...requestContext(predicateBase(applicable)),- request: postFacts,- }) as RequestContext;+ requestContext(predicateBase(applicable), postFacts);const plan: ResponsePlan = {interceptHooks: [],observeToolHooks: [],rewriteHooks: [],observeRewriteHooks: [],- endHooks: engine.select("responseEnd", { route }),+ endHooks,};for (const applicable of toolCallHooks) {const tc = applicable.hook.def.on?.toolCall;@@ -362,26 +435,25 @@ export class HookRequestScope {else plan.observeRewriteHooks.push(applicable);}- const applied = stageA.results.filter((r) => r.decision === "matched").length;- if (applied > 0 || stageA.held.length > 0) {+ if (applied > 0 || state.held.length > 0) {log(`[hooks] request ${route.provider}/${route.modelId}: ${requestHooks.length} hook(s), ` +- `${applied} stage-A action(s) applied, ${stageA.held.length} held for stage B`+ `${applied} action(s) applied, ${state.held.length} description action(s) for stage B`);}- // 5. Stage-B actions are held until the converted tools exist.+ // 5. Description actions are replayed, in chain order, once the converted tools exist.return new HookRequestScope(engine,- route,+ hookRoute,harness,sessionId,meta,- [...stageA.held],- stageA.removedTools,+ [...state.held],+ state.removedTools,notes.map((n) => n.seq),postFacts,- session,+ hookSession,plan);}@@ -392,7 +464,8 @@ export class HookRequestScope {}/**- * Stage B: apply the held description actions to both tool representations.+ * Stage B: replay the held description actions, in chain order, on both tool+ * representations, each over the description the earlier ones produced.* `convertedTools` is null on a route with one representation (native). Both* arrays have ELEMENTS replaced, never their tool objects mutated, so the* converted array the provider payload aliases sees the change. Runs once;@@ -452,15 +525,28 @@ function predicateBase(applicable: ApplicableHook): object {severity: applicable.severity,log: (message: string) => log(`[hook ${applicable.hook.id}] ${message}`),signal: new AbortController().signal,+ prior: [],};}+/**+ * The arrays a hook reads as `ctx.request.messages` / `.tools` are deep-frozen+ * copies: the provider payload is built from the originals, and an in-place+ * `reverse()` in a `.js` hook (no types to stop it), or a write into a message or a+ * tool schema, would change the outgoing request with no journal line. A frozen+ * value turns that into a throw the engine contains.+ */+function frozenArrayCopy<T>(items: unknown): ReadonlyArray<T> {+ return frozenClone(Array.isArray(items) ? (items as T[]) : []);+}+function harnessOf(claudeRequest: AttemptInput["claudeRequest"],sessionId: string | undefined): HarnessFacts {- const facts = detectHarnessFacts(claudeRequest);- if (sessionId) facts.sessionId = sessionId;- facts.skills = extractAvailableSkills(systemTextOf(claudeRequest.system));- return facts;+ return {+ ...detectHarnessFacts(claudeRequest),+ ...(sessionId ? { sessionId } : {}),+ skills: extractAvailableSkills(systemTextOf(claudeRequest.system)),+ };}diff --git a/packages/cli/src/hooks/response-seam.ts b/packages/cli/src/hooks/response-seam.tsindex 201a5a93..5ad0f281 100644--- a/packages/cli/src/hooks/response-seam.ts+++ b/packages/cli/src/hooks/response-seam.ts@@ -19,7 +19,9 @@* 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);+ * 2. the raw `response` hooks (the unsafe tier, raw.ts): each drains its input+ * into a recorder, so no hook can stall the stream before it, and a+ * replacement is held whole and forwarded only once it completed;* 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.@@ -39,9 +41,9 @@ import {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 { messageBlock, messageView, rewrittenView } from "./response-blocks.js";+import { SeamHooks, type ToolCallOutcome } from "./seam-hooks.js";+import { EndLine, newRequestId, observeTap, runResponseConsumers } from "./seam-tap.js";import { type ClosedMode, closedTransform } from "./seam-transform.js";import { type RewriteBlock, applyTextActions } from "./text-rewrite.js";@@ -97,6 +99,8 @@ export interface SeamOptions {/** The seam's stages for one request, decided before the response starts. */export interface SeamPlan {mode: "none" | ClosedMode;+ /** Applicable raw `response` hooks. */+ raw: number;tap: boolean;}@@ -107,7 +111,7 @@ export function planSeam(scope: HookRequestScope): SeamPlan {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 };+ return { mode, raw: scope.raw.responseHookCount, tap };}/**@@ -121,12 +125,26 @@ export async function applyResponseSeam(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;+ log(`[hooks] seam mode=${plan.mode} raw=${plan.raw} tap=${plan.tap ? 1 : 0}`);+ if ((plan.mode === "none" && plan.raw === 0 && !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);+ const rawOpts = { pingIntervalMs: opts.pingIntervalMs, capBytes: opts.holdCapBytes };+ if (isJson(response)) {+ // fail open here too. The branch reads the body; the untouched copy is what+ // the client gets when that read or a stage throws, so an upstream body error+ // reaches the reader as it would with no hook, and never rejects out of the seam.+ const original = response.clone();+ try {+ return await jsonBranch(response, hooks, plan, req, (r) =>+ scope.raw.responseStages(r, rawOpts)+ );+ } catch (err) {+ log(`[hooks] seam not applied: ${err instanceof Error ? err.message : err}`);+ return original;+ }+ }try {let body: ReadableStream<Uint8Array> = response.body;@@ -138,6 +156,17 @@ export async function applyResponseSeam(holdCapBytes: opts.holdCapBytes,});}+ if (plan.raw > 0) {+ const staged = scope.raw.responseStages(+ new Response(body, {+ status: response.status,+ statusText: response.statusText,+ headers: response.headers,+ }),+ rawOpts+ );+ body = staged.body ?? body;+ }if (plan.tap) body = observeTap(body, hooks, req);return new Response(body, {status: response.status,@@ -170,68 +199,66 @@ function isCitedText(block: Json): boolean {}/**- * 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.+ * The closed part of the JSON branch. Returns the body to forward and the+ * message it holds (null when the body is not a Messages API message, which+ * passes unchanged). Fails open: on a throw the original text goes.*/-async function jsonBranch(- response: Response,+async function closedJson(+ text: string,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),- });-+ plan: SeamPlan+): Promise<{ text: string; message: Json }> {let message: Json;try {message = JSON.parse(text);} catch {- return rebuild(text);+ return { text, message: null };}- if (!message || !Array.isArray(message.content)) return rebuild(text);+ if (!message || !Array.isArray(message.content)) return { text, message: null };+ if (plan.mode === "none") return { text, message };+ // Repairs are journaled once it is known whether the rebuilt body goes out.+ const outcomes: ToolCallOutcome[] = [];try {- let content: Json[] = message.content;- if (plan.mode !== "none") {- const repaired: Json[] = [];- for (const block of content) {+ // Each tool call is its own dispatch (§4.4.1 rule 9): their chains run+ // side by side, and the blocks keep their order.+ let content: Json[] = await Promise.all(+ (message.content as Json[]).map(async (block) => {if (- block?.type === "tool_use" &&- typeof block.name === "string" &&- hooks.intercepts(block.name)+ 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);+ return block;}- }- content = repaired;- }+ const outcome = await hooks.interceptToolCall({+ id: String(block.id ?? ""),+ name: block.name,+ rawArgs: JSON.stringify(block.input ?? {}),+ });+ outcomes.push(outcome);+ return outcome.args ? { ...block, input: outcome.args } : block;+ })+ );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 } : {}),}));+ // The whole content[] is the held region: each rewrite step sees it as the+ // earlier steps' text actions left it.+ const repaired = content;+ const stopReason = typeof message.stop_reason === "string" ? message.stop_reason : null;+ const { planned, final } = await hooks.rewrite((actions) => {+ const result = applyTextActions(blocks, actions);+ return {+ view: rewrittenView([], result.blocks, (i) => messageBlock(repaired[i]), stopReason),+ result,+ };+ });if (planned.length > 0 && blocks.some((b) => b.locked)) hooks.noteRewriteInvalid("citations");- const result = applyTextActions(- blocks,- planned.map((p) => p.action)- );+ const result = final.result;hooks.recordRewrite(planned, result);const original = content;content = result.blocks.map((out) => {@@ -240,15 +267,58 @@ async function jsonBranch(return out.changed ? { ...original[out.source], text } : original[out.source];});}- message = { ...message, content };+ const next = { ...message, content };+ const body = JSON.stringify(next);+ for (const o of outcomes) o.delivered();+ return { text: body, message: next };} catch (err) {log(`[hooks] seam JSON branch failed open: ${err instanceof Error ? err.message : err}`);- return rebuild(text);+ for (const o of outcomes) o.notDelivered("failed_open");+ return { text, message };}+}++/**+ * The non-streaming branch (§5.4): the message is parsed once, the `toolCall`+ * hook chain repairs `tool_use.input`, the `responseRewrite` chain 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 raw `response`+ * stage then sees that body as one unit. The inbox `stop` is written before the+ * Response is returned; `responseEnd` runs after, on the final message.+ */+async function jsonBranch(+ response: Response,+ hooks: SeamHooks,+ plan: SeamPlan,+ req: string,+ rawStages: (r: Response) => Response+): Promise<Response> {+ const text = await response.text();+ const rebuild = (body: string) =>+ new Response(body, {+ status: response.status,+ statusText: response.statusText,+ headers: withoutLength(response.headers),+ });- const out = rebuild(JSON.stringify(message));+ const closed = await closedJson(text, hooks, plan);+ let out = rebuild(closed.text);+ if (plan.raw > 0) out = rawStages(out);if (!plan.tap) return out;+ // The tap needs the final bytes: a raw replacement is what the client gets.+ const finalText = plan.raw > 0 ? await out.text() : closed.text;+ let message: Json = closed.message;+ if (plan.raw > 0) {+ try {+ message = JSON.parse(finalText);+ } catch {+ // A replacement that is not a message: the consumers see what they can.+ }+ }+ if (!message || !Array.isArray(message.content)) return rebuild(finalText);+ out = rebuild(finalText);+const end = new EndLine(hooks, req);if (hooks.hasEndHooks) {try {@@ -273,15 +343,6 @@ async function jsonBranch(.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);- }- })();+ runResponseConsumers(hooks, view, req, end);return out;}diff --git a/packages/cli/src/hooks/seam-transform.ts b/packages/cli/src/hooks/seam-transform.tsindex 4fb13d56..cfd4dcdb 100644--- a/packages/cli/src/hooks/seam-transform.ts+++ b/packages/cli/src/hooks/seam-transform.ts@@ -5,15 +5,22 @@* 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.+ * `content_block_stop` its `toolCall` hook chain STARTS and the block is+ * finished, once the chain ends, with ONE `input_json_delta` carrying the+ * repaired (or original) arguments, then the stop. Reading goes on while a+ * chain runs: each tool call is its own dispatch (§4.4.1 rule 9), so a later+ * block's chain starts at that block's stop without waiting for an earlier+ * one. Output keeps block order: what arrives behind an unfinished block is+ * queued (`out`) and forwarded once every block ahead of it is finished. 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+ * `responseRewrite` hook chain runs over the whole response — each hook+ * seeing the held blocks as the earlier hooks' text actions left them — the+ * chain's 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.*@@ -29,10 +36,11 @@ import { log } from "../logger.js";import {BlockCollector,type CollectedBlock,- collectorView,isThinkingType,+ rewrittenView,+ viewBlock,} from "./response-blocks.js";-import type { SeamHooks } from "./seam-hooks.js";+import type { SeamHooks, ToolCallOutcome } from "./seam-hooks.js";import {type SseEvent,SseSplitter,@@ -43,6 +51,17 @@ import {} from "./sse-codec.js";import { type RewriteBlock, applyTextActions } from "./text-rewrite.js";+/**+ * The reader surface this module uses. Annotated structurally, not as+ * `ReadableStreamDefaultReader`: bun-types and node:stream/web declare that+ * global differently (`readMany`), and a package that typechecks this file+ * under node's stream types (macos-bridge) rejects the bun one.+ */+type ByteReader = {+ read(): Promise<{ done: true; value?: unknown } | { done: false; value: Uint8Array }>;+ cancel(reason?: unknown): Promise<void>;+};+export type ClosedMode = "intercept" | "buffer";/** The exact keepalive frame every parser emits. */@@ -68,6 +87,35 @@ type QueueItem =| { kind: "end" }| { kind: "error"; err: unknown };+/**+ * One piece of `intercept` output in block order: text ready to go, or a tool+ * block whose `toolCall` chain is running. `lines` is set when the chain ended;+ * `fallback` is the block as the model sent it, forwarded instead whenever the+ * transform must flush first (cap, upstream error, fail-open). `abort` ends this+ * block's chain alone; `outcome` journals its repairs once delivery is known.+ */+type OutSegment =+ | { kind: "ready"; text: string }+ | {+ kind: "tool";+ fallback: string[];+ lines: string[] | null;+ settled: Promise<void>;+ abort: AbortController;+ outcome: ToolCallOutcome | null;+ /** Set when a flush sent `fallback` while the chain still ran. */+ flushedFor: FlushReason | null;+ };++/** One `buffer`-mode tool block's running chain. */+interface ToolRun {+ outcome: Promise<ToolCallOutcome | null>;+ abort: AbortController;+}++/** Why held content went out unchanged; the journal detail of a repair it discarded. */+type FlushReason = "hold_cap" | "upstream_error" | "failed_open" | "stream_end";+/** One armed tool block held in `intercept` mode. */interface HeldTool {index: number;@@ -170,7 +218,7 @@ class ClosedTransform {readonly readable: ReadableStream<Uint8Array>;private controller!: ReadableStreamDefaultController<Uint8Array>;- private readonly reader: ReadableStreamDefaultReader<Uint8Array>;+ private readonly reader: ByteReader;private readonly splitter = new SseSplitter();private readonly abort = new AbortController();private readonly pingIntervalMs: number;@@ -190,6 +238,11 @@ class ClosedTransform {// interceptprivate heldTool: HeldTool | null = null;+ /**+ * Output waiting behind a tool block whose chain has not ended, in arrival+ * order. Empty while nothing is pending: events are then emitted directly.+ */+ private out: OutSegment[] = [];// bufferprivate phase: "live" | "holding" | "after" = "live";@@ -199,7 +252,7 @@ class ClosedTransform {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 readonly toolRuns = new Map<number, ToolRun>();private heldBytes = 0;constructor(@@ -290,12 +343,21 @@ class ClosedTransform {private handleItem(item: QueueItem): void | Promise<void> {if (item.kind === "end") {- this.flushHeld();+ // A tool chain still running finishes its block before the stream closes.+ const running = this.out.flatMap((seg) => (seg.kind === "tool" ? [seg.settled] : []));+ if (running.length > 0) {+ return Promise.all(running).then(() => {+ this.flushOut();+ this.flushHeld("stream_end");+ this.close();+ });+ }+ this.flushHeld("stream_end");this.close();return;}if (item.kind === "error") {- this.flushHeld();+ this.flushHeld("upstream_error");this.stop();this.pendingError = { err: item.err };this.raisePendingError();@@ -312,7 +374,7 @@ class ClosedTransform {return;}if (isError(ev, json)) {- this.flushHeld();+ this.flushHeld("upstream_error");this.passthrough = true;this.emit(ev.raw);return;@@ -322,11 +384,12 @@ class ClosedTransform {/* ───────────── intercept ───────────── */- private intercept(ev: SseEvent, json: Json): void | Promise<void> {+ private intercept(ev: SseEvent, json: Json): void {const held = this.heldTool;if (held) {if (json?.type === "content_block_stop" && json.index === held.index) {- return this.finishTool(held, ev);+ this.finishTool(held, ev);+ return;}if (json?.type === "content_block_delta" &&@@ -356,26 +419,93 @@ class ClosedTransform {extras: [],};}- this.emit(ev.raw);+ this.forward(ev);}- 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;+ /**+ * Emit now, or queue behind a tool block whose chain is still running. Queued+ * output is not counted toward the hold cap: the cap bounds one held block,+ * and this is what a reader blocked on that chain would have left unread.+ */+ private forward(ev: SseEvent): void {+ if (this.out.length === 0) this.emit(ev.raw);+ else this.out.push({ kind: "ready", text: ev.raw });+ }++ /**+ * A held block's arguments are complete: start its `toolCall` chain and go on+ * reading. The block is finished, in order, once the chain ends.+ */+ private finishTool(held: HeldTool, stop: SseEvent): void {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);+ // the cap bounds one held block: this one is complete+ this.heldBytes = 0;+ const segment: Extract<OutSegment, { kind: "tool" }> = {+ kind: "tool",+ fallback: [...held.deltas.map((e) => e.raw), ...held.extras.map((e) => e.raw), stop.raw],+ lines: null,+ settled: Promise.resolve(),+ abort: this.childAbort(),+ outcome: null,+ flushedFor: null,+ };+ this.out.push(segment);+ segment.settled = this.opts.hooks+ .interceptToolCall({ id: held.id, name: held.name, rawArgs: held.args }, segment.abort.signal)+ .catch((err: unknown): ToolCallOutcome | null => {+ // The block goes out as the model sent it.+ log(`[hooks] seam toolCall failed open: ${err instanceof Error ? err.message : err}`);+ return null;+ })+ .then((outcome) => {+ // Flushed meanwhile (cap, error, fail-open) or cancelled: the model's own+ // arguments went out, or nothing did.+ if (this.done || !this.out.includes(segment)) {+ outcome?.notDelivered(segment.flushedFor ?? "client_cancelled");+ return;+ }+ try {+ const repaired = outcome?.args;+ const args = repaired ? JSON.stringify(repaired) : held.args;+ segment.outcome = outcome;+ segment.lines = [+ ...(repaired || held.deltas.length > 0 ? [inputDelta(held.index, args)] : []),+ ...held.extras.map((e) => e.raw),+ stop.raw,+ ];+ } catch (err) {+ // Unserialisable arguments, say: the block goes out as the model sent it.+ log(`[hooks] seam toolCall failed open: ${err instanceof Error ? err.message : err}`);+ outcome?.notDelivered("failed_open");+ segment.outcome = null;+ segment.lines = segment.fallback;+ }+ this.flushOut();+ });+ }++ /** An AbortController that also aborts when the transform's own does (a client cancel). */+ private childAbort(): AbortController {+ const child = new AbortController();+ const parent = this.abort.signal;+ if (parent.aborted) child.abort(parent.reason);+ else parent.addEventListener("abort", () => child.abort(parent.reason), { once: true });+ return child;+ }++ /** Emit every leading segment that is ready; stop at the first running chain. */+ private flushOut(): void {+ while (this.out.length > 0) {+ const head = this.out[0] as OutSegment;+ if (head.kind === "tool" && head.lines === null) return;+ this.out.shift();+ if (head.kind === "ready") {+ this.emit(head.text);+ continue;+ }+ for (const line of head.lines ?? []) this.emit(line);+ head.outcome?.delivered();+ }}/* ───────────── buffer ───────────── */@@ -429,13 +559,14 @@ class ClosedTransform {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) => {+ const abort = this.childAbort();+ const outcome = this.opts.hooks+ .interceptToolCall({ id: c.id ?? "", name: c.name, rawArgs: c.args }, abort.signal)+ .catch((err: unknown): ToolCallOutcome | null => {log(`[hooks] seam toolCall failed open: ${err instanceof Error ? err.message : err}`);- return undefined;+ return null;});- this.toolRuns.set(block.index, run);+ this.toolRuns.set(block.index, { outcome, abort });}private async finishHold(messageDelta: SseEvent): Promise<void> {@@ -444,7 +575,7 @@ class ClosedTransform {} 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.flushHeld("failed_open");this.passthrough = true;}if (this.done) return;@@ -452,30 +583,63 @@ class ClosedTransform {this.emit(messageDelta.raw);}- /** Collect repairs, run `responseRewrite`, and re-emit the held region. */- private async rewriteHeld(): Promise<void> {+ /** Wait for every held tool block's chain: the repaired arguments by block index. */+ private async collectRepairs(): Promise<{+ repairs: Map<number, Record<string, unknown>>;+ outcomes: ToolCallOutcome[];+ }> {const repairs = new Map<number, Record<string, unknown>>();+ const outcomes: ToolCallOutcome[] = [];for (const [index, run] of this.toolRuns) {- const args = await run;- if (args) repairs.set(index, args);+ const outcome = await run.outcome;+ if (!outcome) continue;+ outcomes.push(outcome);+ if (outcome.args) repairs.set(index, outcome.args);}- if (this.done) return;+ return { repairs, outcomes };+ }++ /** True when the client cancelled: the repairs never reach it. */+ private cancelledWith(outcomes: ReadonlyArray<ToolCallOutcome>): boolean {+ if (!this.done) return false;+ for (const o of outcomes) o.notDelivered("client_cancelled");+ return true;+ }++ /** Collect repairs, run the `responseRewrite` chain, and re-emit the held region. */+ private async rewriteHeld(): Promise<void> {+ const { repairs, outcomes } = await this.collectRepairs();+ if (this.cancelledWith(outcomes)) 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 } : {}),}));+ // What a rewrite step sees: the blocks that streamed live, then the held+ // region with the earlier steps' text actions applied, repairs included.+ const held = new Set(this.heldBlocks.map((b) => b.collected));+ const lead = this.collector.blocks.filter((b) => !held.has(b)).map((b) => viewBlock(b));+ const original = (source: number) => {+ const b = this.heldBlocks[source] as HeldBlock;+ return viewBlock(b.collected, repairs.get(b.index));+ };+ const { planned, final } = await hooks.rewrite((actions) => {+ const result = applyTextActions(rewriteBlocks, actions);+ return {+ view: rewrittenView(lead, result.blocks, original, this.collector.stopReason),+ result,+ };+ }, this.abort.signal);+ if (this.cancelledWith(outcomes)) return;+if (planned.length > 0 && rewriteBlocks.some((b) => b.locked)) {hooks.noteRewriteInvalid("citations");}- const result = applyTextActions(- rewriteBlocks,- planned.map((p) => p.action)- );+ // The last step's application, reused: applying every action again is the+ // O(steps × actions) cost the event budget does not cover.+ const result = final.result;hooks.recordRewrite(planned, result);// Build the whole region first, so a throw half way emits nothing twice.@@ -499,8 +663,12 @@ class ClosedTransform {out.push(...heldBlock(held, index, repairs.get(held.index)));}flushLoose(Number.POSITIVE_INFINITY);- this.resetHeld();+ // Emit, then forget the held region: if an emit throws part way, `finishHold`'s+ // fail-open still has the held events to flush (a repeat beats a truncated+ // response), and the repairs count as not delivered.for (const text of out) this.emit(text);+ for (const o of outcomes) o.delivered();+ this.resetHeld();}/* ───────────── holding bookkeeping ───────────── */@@ -511,13 +679,35 @@ class ClosedTransform {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();+ else this.opts.hooks.noteInterceptInvalid("hold_cap");+ this.flushHeld("hold_cap");this.passthrough = true;}- /** Forward everything held, unchanged, in arrival order. */- private flushHeld(): void {+ /**+ * Forward everything held, UNCHANGED, in arrival order: every tool block goes out+ * as the model sent it, even one whose chain already finished, and every chain+ * still running is aborted. Their repairs are journaled `dropped` with `reason`+ * (a running chain's when it settles), never `repaired`.+ */+ private flushHeld(reason: FlushReason): void {+ // Queued intercept output first: it arrived before the block held now.+ const out = this.out;+ this.out = [];+ for (const seg of out) {+ if (seg.kind === "ready") {+ this.emit(seg.text);+ continue;+ }+ for (const line of seg.fallback) this.emit(line);+ seg.flushedFor = reason;+ seg.abort.abort(new Error(`seam flushed: ${reason}`));+ seg.outcome?.notDelivered(reason);+ }+ for (const run of this.toolRuns.values()) {+ run.abort.abort(new Error(`seam flushed: ${reason}`));+ void run.outcome.then((o) => o?.notDelivered(reason));+ }const tool = this.heldTool;if (tool) {this.heldTool = null;@@ -541,7 +731,7 @@ class ClosedTransform {}private get holding(): boolean {- return this.busy || this.heldTool !== null || this.phase === "holding";+ return this.busy || this.heldTool !== null || this.out.length > 0 || this.phase === "holding";}/** The seam's own keepalive, while it holds content and upstream sends none. */@@ -555,7 +745,7 @@ class ClosedTransform {private failOpen(err: unknown): void {log(`[hooks] seam transform failed open: ${err instanceof Error ? err.message : err}`);try {- this.flushHeld();+ this.flushHeld("failed_open");} catch {}this.passthrough = true;}diff --git a/packages/cli/src/hooks/seam.test.ts b/packages/cli/src/hooks/seam.test.tsindex d4967f26..10c87893 100644--- a/packages/cli/src/hooks/seam.test.ts+++ b/packages/cli/src/hooks/seam.test.ts@@ -209,7 +209,7 @@ 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 });+ expect(planSeam(scope)).toEqual({ mode: "none", raw: 0, tap: false });const res = sse([messageStart()]);expect(await applyResponseSeam(res, scope)).toBe(res);});@@ -225,7 +225,7 @@ describe("seam plan", () => {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 });+ expect(planSeam(await scopeOf(engine))).toEqual({ mode: "none", raw: 0, tap: true });});it("an unarmed toolCall hook and a declining rewrite hook leave the identity case", async () => {@@ -239,7 +239,7 @@ describe("seam plan", () => {});const { engine } = engineWith([tool, rewrite]);const scope = await scopeOf(engine);- expect(planSeam(scope)).toEqual({ mode: "none", tap: false });+ expect(planSeam(scope)).toEqual({ mode: "none", raw: 0, tap: false });});});@@ -276,6 +276,23 @@ describe("intercept mode", () => {).toBe(true);});+ it("the hold cap counts one tool block, not every block of the response", async () => {+ const { engine, journal } = engineWith([repairHook("Write", { file_path: "/fixed" })]);+ const args = ['{"file_path":"/wr', `ong","pad":"${"x".repeat(60)}"}`];+ const blocks = [0, 1, 2, 3].flatMap((i) => toolBlock(i, "Write", args));+ const perBlock = new TextEncoder().encode(toolBlock(0, "Write", args).slice(1).join("")).length;+ const out = await readAll(+ await applyResponseSeam(+ sse([messageStart(), ...blocks, messageDelta("tool_use"), messageStop()]),+ await scopeOf(engine),+ // room for one block's held events, not for four+ { holdCapBytes: perBlock + 50 }+ )+ );+ expect(out.split('{\\"file_path\\":\\"/fixed\\"}').length - 1).toBe(4);+ expect(journal.some((e) => e.detail === "buffer_cap")).toBe(false);+ });+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]);@@ -912,6 +929,83 @@ describe("observe tap", () => {expect(cancelled).toBe(true);});+ it("a slow warn-mode rewrite never delays responseEnd or its end line", async () => {+ const path = inboxPath();+ const slowRewrite = userHook({+ id: "slowrw",+ timeoutMs: 5_000,+ on: {+ responseRewrite: {+ handle: () => Bun.sleep(1_500).then(() => [act.appendText("!")]) as never,+ },+ },+ });+ const { engine } = engineWith([slowRewrite, endHook(() => [act.injectUserTurn("ON-TIME")])], {+ "hook:t/slowrw": "warn",+ });+ await readAll(+ await applyResponseSeam(+ sse([messageStart(), ...textBlock(0, "x"), messageDelta(), messageStop()]),+ await scopeOf(engine),+ { sink: new InboxFileSink(path), req: "r4" }+ )+ );+ const readAt = Date.now();+ await until(() => inboxLines(path).some((l) => l.kind === "end"), 5_000);+ // responseEnd's own time only: the 1.5 s warn rewrite is not in front of it+ expect(Date.now() - readAt).toBeLessThan(700);+ expect(inboxLines(path).map((l) => l.kind)).toEqual(["stop", "inject", "end"]);+ });++ it("a client cancel after message_stop leaves end to responseEnd, after its payload", async () => {+ const path = inboxPath();+ const { engine } = engineWith([+ endHook(() => Bun.sleep(200).then(() => [act.injectUserTurn("LATE-BUT-KEPT")])),+ ]);+ const res = await applyResponseSeam(+ sse([messageStart(), ...textBlock(0, "x"), messageDelta(), messageStop()], {+ gates: new Map([[6, new Promise<void>(() => {})]]),+ }),+ await scopeOf(engine),+ { sink: new InboxFileSink(path), req: "c8" }+ );+ const reader = res.body!.getReader();+ const decoder = new TextDecoder();+ for (;;) {+ const r = await reader.read();+ if (r.done || decoder.decode(r.value).includes('"type":"message_stop"')) break;+ }+ await reader.cancel("client closed after message_stop");+ await until(() => inboxLines(path).some((l) => l.kind === "end"), 3_000);+ await Bun.sleep(300);+ expect(inboxLines(path)).toEqual([+ { v: 1, kind: "stop", req: "c8" },+ expect.objectContaining({ kind: "inject", req: "c8", text: "LATE-BUT-KEPT" }),+ { v: 1, kind: "end", req: "c8" },+ ]);+ });++ it("an upstream read error after message_stop leaves end to responseEnd, after its payload", async () => {+ const path = inboxPath();+ const { engine } = engineWith([+ endHook(() => Bun.sleep(200).then(() => [act.injectUserTurn("LATE-BUT-KEPT")])),+ ]);+ const chunks = [messageStart(), ...textBlock(0, "x"), messageDelta(), messageStop()];+ const res = await applyResponseSeam(+ sse(chunks, { errorAfter: chunks.length }),+ await scopeOf(engine),+ { sink: new InboxFileSink(path), req: "e8" }+ );+ await expect(readAll(res)).rejects.toThrow("upstream socket dropped");+ await until(() => inboxLines(path).some((l) => l.kind === "end"), 3_000);+ await Bun.sleep(300);+ expect(inboxLines(path)).toEqual([+ { v: 1, kind: "stop", req: "e8" },+ expect.objectContaining({ kind: "inject", req: "e8", text: "LATE-BUT-KEPT" }),+ { v: 1, kind: "end", req: "e8" },+ ]);+ });+it("a response that ends before message_stop writes only its end", async () => {const path = inboxPath();const { engine } = engineWith([endHook()]);@@ -953,7 +1047,7 @@ describe("observe tap", () => {});const { engine, journal } = engineWith([observe, warnRepair], { "hook:t/warned": "warn" });const scope = await scopeOf(engine);- expect(planSeam(scope)).toEqual({ mode: "none", tap: true });+ expect(planSeam(scope)).toEqual({ mode: "none", raw: 0, tap: true });const input = [messageStart(),...toolBlock(0, "Write", ['{"a":', "1}"]),@@ -1036,6 +1130,25 @@ describe("non-streaming JSON branch", () => {]);});+ it("a body that errors on read fails open: the seam returns, the error reaches the reader", async () => {+ const { engine } = engineWith([rewriteHook("rw", () => [act.appendText("!")])]);+ let sent = false;+ const broken = new Response(+ new ReadableStream<Uint8Array>({+ pull(c) {+ if (!sent) {+ sent = true;+ c.enqueue(encoder.encode('{"type":"message","content":['));+ } else c.error(new Error("upstream body dropped"));+ },+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );+ const out = await applyResponseSeam(broken, await scopeOf(engine));+ expect(out.status).toBe(200);+ await expect(out.text()).rejects.toThrow("upstream body dropped");+ });+it("passes a body that is not a message through unchanged", async () => {const { engine } = engineWith([rewriteHook("add", () => [act.appendText("A")])]);const res = await applyResponseSeam(diff --git a/packages/cli/src/middleware/gemini-thought-signature.ts b/packages/cli/src/middleware/gemini-thought-signature.tsdeleted file mode 100644index f99ccca1..00000000--- a/packages/cli/src/middleware/gemini-thought-signature.ts+++ /dev/null@@ -1,263 +0,0 @@-/**- * Gemini Thought Signature Middleware- *- * Handles thought_signature persistence for Gemini 3 Pro models.- *- * Gemini 3 Pro requires thought_signatures to be preserved across requests:- * 1. When Gemini responds with tool_calls, it includes thought_signatures- * 2. These signatures MUST be included in subsequent requests when sending conversation history- * 3. Missing signatures result in 400 validation errors- *- * This middleware:- * - Extracts thought_signatures from Gemini responses (both streaming and non-streaming)- * - Stores them in persistent in-memory cache- * - Injects signatures into assistant tool_calls when building requests- * - Injects signatures into tool result messages- *- * References:- * - https://ai.google.dev/gemini-api/docs/thought-signatures- * - https://openrouter.ai/docs/use-cases/reasoning-tokens#preserving-reasoning-blocks- */--import { isLoggingEnabled, log, logStructured } from "../logger.js";-import type {- ModelMiddleware,- NonStreamingResponseContext,- RequestContext,- StreamChunkContext,-} from "./types.js";--export class GeminiThoughtSignatureMiddleware implements ModelMiddleware {- readonly name = "GeminiThoughtSignature";-- /**- * Persistent cache for Gemini reasoning details- *- * CRITICAL: Gemini 3 Pro requires the ENTIRE reasoning_details array to be preserved- * and sent back in subsequent requests. Storing just thought_signatures is insufficient.- *- * Maps: assistant_message_id -> { reasoning_details: array, tool_call_ids: Set }- */- private persistentReasoningDetails = new Map<- string,- {- reasoning_details: any[];- tool_call_ids: Set<string>;- }- >();-- /**- * `alwaysHandle`: the handler selected this middleware from catalog data- * (a Gemini-API wire, or a Google model behind a gateway), so the model name- * — possibly an opaque gateway id — is not asked again.- */- constructor(private readonly options: { alwaysHandle?: boolean } = {}) {}-- shouldHandle(modelId: string): boolean {- if (this.options.alwaysHandle) return true;- return modelId.includes("gemini") || modelId.includes("google/");- }-- onInit(): void {- log("[Gemini] Thought signature middleware initialized");- }-- /**- * Before Request: Inject reasoning_details into assistant messages- *- * CRITICAL: Gemini 3 Pro requires the ENTIRE reasoning_details array to be preserved- * in assistant messages. This is how OpenRouter communicates thought_signatures to Gemini.- *- * Modifies:- * - Assistant messages with tool_calls: Add reasoning_details array- */- beforeRequest(context: RequestContext): void {- if (this.persistentReasoningDetails.size === 0) {- return; // No reasoning details to inject- }-- if (isLoggingEnabled()) {- logStructured("[Gemini] Injecting reasoning_details", {- cacheSize: this.persistentReasoningDetails.size,- messageCount: context.messages.length,- });- }-- let injected = 0;-- for (const msg of context.messages) {- // Inject reasoning_details into assistant messages with tool_calls- if (msg.role === "assistant" && msg.tool_calls) {- // Find matching reasoning_details by checking tool_call_ids- for (const [msgId, cached] of this.persistentReasoningDetails.entries()) {- // Check if any tool_call_id matches- const hasMatchingToolCall = msg.tool_calls.some((tc: any) =>- cached.tool_call_ids.has(tc.id)- );-- if (hasMatchingToolCall) {- msg.reasoning_details = cached.reasoning_details;- injected++;-- if (isLoggingEnabled()) {- logStructured("[Gemini] Reasoning details added to assistant message", {- message_id: msgId,- reasoning_blocks: cached.reasoning_details.length,- tool_calls: msg.tool_calls.length,- });- }- break; // Only inject once per message- }- }-- if (!msg.reasoning_details && isLoggingEnabled()) {- log("[Gemini] WARNING: No reasoning_details found for assistant message with tool_calls");- log(`[Gemini] Tool call IDs: ${msg.tool_calls.map((tc: any) => tc.id).join(", ")}`);- }- }- }-- if (isLoggingEnabled() && injected > 0) {- logStructured("[Gemini] Signature injection complete", {- injected,- cacheSize: this.persistentReasoningDetails.size,- });-- // DEBUG: Log the actual messages being sent to understand structure- log("[Gemini] DEBUG: Messages after injection:");- for (let i = 0; i < context.messages.length; i++) {- const msg = context.messages[i];- log(- `[Gemini] Message ${i}: role=${msg.role}, has_content=${!!msg.content}, has_tool_calls=${!!msg.tool_calls}, tool_call_id=${msg.tool_call_id || "N/A"}`- );- if (msg.role === "assistant" && msg.tool_calls) {- log(` - Assistant has ${msg.tool_calls.length} tool call(s), content="${msg.content}"`);- for (const tc of msg.tool_calls) {- log(- ` * Tool call: ${tc.id}, function=${tc.function?.name}, has extra_content: ${!!tc.extra_content}, has thought_signature: ${!!tc.extra_content?.google?.thought_signature}`- );- if (tc.extra_content) {- log(` extra_content keys: ${Object.keys(tc.extra_content).join(", ")}`);- if (tc.extra_content.google) {- log(` google keys: ${Object.keys(tc.extra_content.google).join(", ")}`);- log(- ` thought_signature length: ${tc.extra_content.google.thought_signature?.length || 0}`- );- }- }- }- } else if (msg.role === "tool") {- log(- ` - Tool result: tool_call_id=${msg.tool_call_id}, has extra_content: ${!!msg.extra_content}`- );- }- }- }- }-- /**- * After Non-Streaming Response: Extract reasoning_details from response- */- afterResponse(context: NonStreamingResponseContext): void {- const response = context.response;- const message = response?.choices?.[0]?.message;-- if (!message) {- return;- }-- const reasoningDetails = message.reasoning_details || [];- const toolCalls = message.tool_calls || [];-- if (reasoningDetails.length > 0 && toolCalls.length > 0) {- // Generate a unique ID for this assistant message- const messageId = `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`;-- // Extract tool_call_ids- const toolCallIds = new Set<string>(- toolCalls- .map((tc: any) => tc.id)- .filter((id: unknown): id is string => typeof id === "string")- );-- // Store the full reasoning_details array- this.persistentReasoningDetails.set(messageId, {- reasoning_details: reasoningDetails,- tool_call_ids: toolCallIds,- });-- logStructured("[Gemini] Reasoning details saved (non-streaming)", {- message_id: messageId,- reasoning_blocks: reasoningDetails.length,- tool_calls: toolCallIds.size,- total_cached_messages: this.persistentReasoningDetails.size,- });- }- }-- /**- * After Stream Chunk: Accumulate reasoning_details from deltas- *- * CRITICAL: Gemini sends reasoning_details across multiple chunks.- * We need to accumulate the FULL array to preserve for the next request.- */- afterStreamChunk(context: StreamChunkContext): void {- const delta = context.delta;- if (!delta) return;-- // Accumulate reasoning_details from this chunk- if (delta.reasoning_details && delta.reasoning_details.length > 0) {- if (!context.metadata.has("reasoning_details")) {- context.metadata.set("reasoning_details", []);- }- const accumulated = context.metadata.get("reasoning_details");- accumulated.push(...delta.reasoning_details);-- if (isLoggingEnabled()) {- logStructured("[Gemini] Reasoning details accumulated", {- chunk_blocks: delta.reasoning_details.length,- total_blocks: accumulated.length,- });- }- }-- // Track tool_call_ids for associating with reasoning_details- if (delta.tool_calls) {- if (!context.metadata.has("tool_call_ids")) {- context.metadata.set("tool_call_ids", new Set());- }- const toolCallIds = context.metadata.get("tool_call_ids");- for (const tc of delta.tool_calls) {- if (tc.id) {- toolCallIds.add(tc.id);- }- }- }- }-- /**- * After Stream Complete: Save accumulated reasoning_details to persistent cache- */- afterStreamComplete(metadata: Map<string, any>): void {- const reasoningDetails = metadata.get("reasoning_details") || [];- const toolCallIds = metadata.get("tool_call_ids") || new Set();-- if (reasoningDetails.length > 0 && toolCallIds.size > 0) {- // Generate a unique ID for this assistant message- const messageId = `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`;-- // Store the full reasoning_details array with associated tool_call_ids- this.persistentReasoningDetails.set(messageId, {- reasoning_details: reasoningDetails,- tool_call_ids: toolCallIds,- });-- logStructured("[Gemini] Streaming complete - reasoning details saved", {- message_id: messageId,- reasoning_blocks: reasoningDetails.length,- tool_calls: toolCallIds.size,- total_cached_messages: this.persistentReasoningDetails.size,- });- }- }-}diff --git a/packages/cli/src/middleware/index.ts b/packages/cli/src/middleware/index.tsdeleted file mode 100644index c717aacd..00000000--- a/packages/cli/src/middleware/index.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Middleware System Exports- *- * Provides a clean middleware system for handling model-specific behavior.- */--export { MiddlewareManager } from "./manager.js";-export { GeminiThoughtSignatureMiddleware } from "./gemini-thought-signature.js";-export type {- ModelMiddleware,- RequestContext,- NonStreamingResponseContext,- StreamChunkContext,-} from "./types.js";diff --git a/packages/cli/src/middleware/manager.ts b/packages/cli/src/middleware/manager.tsdeleted file mode 100644index e2c3f975..00000000--- a/packages/cli/src/middleware/manager.ts+++ /dev/null@@ -1,187 +0,0 @@-/**- * MiddlewareManager - Orchestrates model-specific middlewares- *- * Responsibilities:- * - Register middlewares- * - Filter active middlewares by model ID- * - Execute middleware chain in order- * - Handle errors gracefully (log and continue)- */--import { isLoggingEnabled, log, logStructured } from "../logger.js";-import type {- ModelMiddleware,- NonStreamingResponseContext,- RequestContext,- StreamChunkContext,-} from "./types.js";--export class MiddlewareManager {- private middlewares: ModelMiddleware[] = [];- private initialized = false;-- /**- * Register a middleware- * Middlewares execute in registration order- */- register(middleware: ModelMiddleware): void {- this.middlewares.push(middleware);-- if (isLoggingEnabled()) {- logStructured("Middleware Registered", {- name: middleware.name,- total: this.middlewares.length,- });- }- }-- /**- * Initialize all middlewares (call onInit hooks)- * Should be called once when server starts- */- async initialize(): Promise<void> {- if (this.initialized) {- log("[Middleware] Already initialized, skipping");- return;- }-- log(`[Middleware] Initializing ${this.middlewares.length} middleware(s)...`);-- for (const middleware of this.middlewares) {- if (middleware.onInit) {- try {- await middleware.onInit();- log(`[Middleware] ${middleware.name} initialized`);- } catch (error) {- log(`[Middleware] ERROR: ${middleware.name} initialization failed: ${error}`);- // Continue with other middlewares even if one fails- }- }- }-- this.initialized = true;- log("[Middleware] Initialization complete");- }-- /**- * Get active middlewares for a specific model- */- private getActiveMiddlewares(modelId: string): ModelMiddleware[] {- return this.middlewares.filter((m) => m.shouldHandle(modelId));- }-- /**- * Get names of active middlewares for a specific model.- * Used by stats recording to capture middleware names without details.- */- getActiveNames(modelId: string): string[] {- return this.getActiveMiddlewares(modelId).map((m) => m.name);- }-- /**- * Execute beforeRequest hooks for all active middlewares- */- async beforeRequest(context: RequestContext): Promise<void> {- const active = this.getActiveMiddlewares(context.modelId);-- if (active.length === 0) {- return; // No middlewares for this model- }-- if (isLoggingEnabled()) {- logStructured("Middleware Chain (beforeRequest)", {- modelId: context.modelId,- middlewares: active.map((m) => m.name),- messageCount: context.messages.length,- });- }-- for (const middleware of active) {- try {- await middleware.beforeRequest(context);- } catch (error) {- log(`[Middleware] ERROR in ${middleware.name}.beforeRequest: ${error}`);- // Continue with next middleware - don't let one failure break the chain- }- }- }-- /**- * Execute afterResponse hooks for non-streaming responses- */- async afterResponse(context: NonStreamingResponseContext): Promise<void> {- const active = this.getActiveMiddlewares(context.modelId);-- if (active.length === 0) {- return;- }-- if (isLoggingEnabled()) {- logStructured("Middleware Chain (afterResponse)", {- modelId: context.modelId,- middlewares: active.map((m) => m.name),- });- }-- for (const middleware of active) {- if (middleware.afterResponse) {- try {- await middleware.afterResponse(context);- } catch (error) {- log(`[Middleware] ERROR in ${middleware.name}.afterResponse: ${error}`);- }- }- }- }-- /**- * Execute afterStreamChunk hooks for each streaming chunk- */- async afterStreamChunk(context: StreamChunkContext): Promise<void> {- const active = this.getActiveMiddlewares(context.modelId);-- if (active.length === 0) {- return;- }-- // Only log on first chunk to avoid spam- if (isLoggingEnabled() && !context.metadata.has("_middlewareLogged")) {- logStructured("Middleware Chain (afterStreamChunk)", {- modelId: context.modelId,- middlewares: active.map((m) => m.name),- });- context.metadata.set("_middlewareLogged", true);- }-- for (const middleware of active) {- if (middleware.afterStreamChunk) {- try {- await middleware.afterStreamChunk(context);- } catch (error) {- log(`[Middleware] ERROR in ${middleware.name}.afterStreamChunk: ${error}`);- }- }- }- }-- /**- * Execute afterStreamComplete hooks after streaming finishes- */- async afterStreamComplete(modelId: string, metadata: Map<string, any>): Promise<void> {- const active = this.getActiveMiddlewares(modelId);-- if (active.length === 0) {- return;- }-- for (const middleware of active) {- if (middleware.afterStreamComplete) {- try {- await middleware.afterStreamComplete(metadata);- } catch (error) {- log(`[Middleware] ERROR in ${middleware.name}.afterStreamComplete: ${error}`);- }- }- }- }-}diff --git a/packages/cli/src/middleware/types.ts b/packages/cli/src/middleware/types.tsdeleted file mode 100644index 9f85b4c2..00000000--- a/packages/cli/src/middleware/types.ts+++ /dev/null@@ -1,129 +0,0 @@-/**- * Middleware System for Model-Specific Behavior- *- * This system allows clean separation of model-specific logic (Gemini thought signatures,- * Grok XML handling, etc.) from the core proxy server.- */--/**- * Context passed to middleware before sending request to OpenRouter- */-export interface RequestContext {- /** Model ID being used (e.g., "google/gemini-3-pro-preview") */- modelId: string;-- /** Messages array (mutable - middlewares can modify in place) */- messages: any[];-- /** Tools array (if any) */- tools?: any[];-- /** Whether this is a streaming request */- stream: boolean;-- /**- * The normalized Claude-format request.- *- * This is the ONLY place the system prompt is reachable: the Codex/Responses- * adapter reads `claudeRequest.system` into `payload.instructions` rather than- * taking it from `messages`, so a middleware that wants to inject a system-level- * note must edit this. Mutable.- */- claudeRequest: any;-- /**- * Claude-format tool definitions (`{name, description, input_schema}`),- * BEFORE conversion to the target wire format.- *- * Rewrite descriptions here rather than on `tools`: conversion runs- * `sanitizeSchemaForOpenAI` and, on Codex, rebuilds every tool object, so edits- * made to the converted array are the ones most likely to be dropped. Mutable.- */- claudeTools: any[];-}--/**- * Context passed to middleware after receiving non-streaming response- */-export interface NonStreamingResponseContext {- /** Model ID being used */- modelId: string;-- /** OpenAI format response from OpenRouter */- response: any;-}--/**- * Context passed to middleware for each streaming chunk- */-export interface StreamChunkContext {- /** Model ID being used */- modelId: string;-- /** Raw SSE chunk from OpenRouter */- chunk: any;-- /** Delta object (chunk.choices[0].delta) - mutable */- delta: any;-- /**- * Shared metadata across all chunks in this streaming response- * Useful for accumulating state (e.g., thought signatures)- * Auto-cleaned after stream completes- */- metadata: Map<string, any>;-}--/**- * Base middleware interface- *- * Middlewares handle model-specific behavior by hooking into the request/response lifecycle.- */-export interface ModelMiddleware {- /** Unique name for this middleware (for logging) */- readonly name: string;-- /**- * Determines if this middleware should handle the given model- * Called once per request to filter active middlewares- */- shouldHandle(modelId: string): boolean;-- /**- * Called once when the proxy server starts (optional)- * Use for initialization, loading config, etc.- */- onInit?(): void | Promise<void>;-- /**- * Called before sending request to OpenRouter- * Can modify messages, add extra_content, inject system messages, etc.- *- * @param context - Mutable context (can modify messages array)- */- beforeRequest(context: RequestContext): void | Promise<void>;-- /**- * Called after receiving complete non-streaming response (optional)- * Can extract data, transform response, update cache, etc.- *- * @param context - Response context (read-only)- */- afterResponse?(context: NonStreamingResponseContext): void | Promise<void>;-- /**- * Called for each chunk in a streaming response (optional)- * Can extract data from delta, transform content, etc.- *- * @param context - Chunk context (delta is mutable)- */- afterStreamChunk?(context: StreamChunkContext): void | Promise<void>;-- /**- * Called once after a streaming response completes (optional)- * Use for cleanup, final processing of accumulated metadata, etc.- *- * @param metadata - Metadata map that was shared across all chunks- */- afterStreamComplete?(metadata: Map<string, any>): void | Promise<void>;-}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.tsdeleted file mode 100644index 27711ea5..00000000--- a/packages/cli/src/test-fixtures/parser-goldens/drive-gemini-middleware.ts+++ /dev/null@@ -1,120 +0,0 @@-/**- * 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-gemini-raw.ts b/packages/cli/src/test-fixtures/parser-goldens/drive-gemini-raw.tsnew file mode 100644index 00000000..fae85c24--- /dev/null+++ b/packages/cli/src/test-fixtures/parser-goldens/drive-gemini-raw.ts@@ -0,0 +1,136 @@+/**+ * Drives the Gemini thought-signature built-in through the hook raw tier, the+ * way ComposedHandler wires it: a `RawStreamTap` on openai-sse per stream, then+ * `providerRequest` on the next request, over the Gemini golden captured from+ * the pre-hook `MiddlewareManager` (P0). The golden itself never changes.+ *+ * `shouldHandle` is whether the built-in applies to a route for that model, and+ * `activeNames` is the `middleware_names` stats value (`statsNames`).+ */++import { DefaultAPIFormat } from "../../adapters/base-api-format.js";+import { createStreamingResponseHandler } from "../../handlers/shared/stream-parsers/openai-sse.js";+import { createGeminiThoughtSignatureHook } from "../../hooks/builtins/gemini-thought-signature.js";+import { HookEngine } from "../../hooks/engine.js";+import type { JournalEntry } from "../../hooks/journal.js";+import type { RouteInfo } from "../../hooks/public.js";+import { RawRequest, type RawStreamTap, statsNames } from "../../hooks/raw.js";+import { HookRegistry } from "../../hooks/registry.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");+ },+};++const route = (modelId: string): RouteInfo => ({ modelId, provider: "openrouter", native: false });++/** One engine, as one process has: the built-in's caches live as long as it does. */+export function geminiEngine(journal: JournalEntry[] = []): HookEngine {+ return new HookEngine({+ registry: new HookRegistry([createGeminiThoughtSignatureHook()], [], undefined),+ config: {},+ hostMode: "other",+ journalSink: (e) => journal.push(e),+ warn: () => {},+ drainTelemetryOutbox: false,+ });+}++function rawRequest(engine: HookEngine, modelId: string): RawRequest {+ return new RawRequest(+ engine,+ route(modelId),+ { model: modelId, provider: "openrouter" },+ { model: modelId, stream: true, systemText: "", messages: [], tools: [] }+ );+}++function runOpenAiSse(+ input: GoldenInput,+ modelId: string,+ toolSchemas: GoldenToolSchema[],+ tap: RawStreamTap | undefined+): Promise<string> {+ return createStreamingResponseHandler(+ ctx,+ inputResponse(input),+ new DefaultAPIFormat(modelId),+ modelId,+ tap,+ undefined,+ toolSchemas+ )+ .text()+ .then(normalizeWire);+}++export interface GeminiScenarioInput {+ id: string;+ description: string;+ streams: GoldenInput[];+ nextRequestMessages: unknown[];+}++/** Replay the Gemini golden's scenarios through the raw tier. */+export async function runGeminiCapture(+ id: string,+ modelId: string,+ toolSchemas: GoldenToolSchema[],+ applicabilityModels: string[],+ scenarios: GeminiScenarioInput[]+): Promise<GeminiMiddlewareGolden> {+ const probe = geminiEngine();+ const applicability = applicabilityModels.map((m) => ({+ modelId: m,+ shouldHandle: probe.registry.applicable("raw.providerChunk", { route: route(m) }).length > 0,+ activeNames: statsNames(probe, route(m)),+ }));++ const outScenarios: GeminiMiddlewareGolden["scenarios"] = [];+ for (const scenario of scenarios) {+ const engine = geminiEngine();++ const streams: GeminiMiddlewareGolden["scenarios"][number]["streams"] = [];+ for (const input of scenario.streams) {+ const tap = rawRequest(engine, modelId).streamTap();+ const output = await runOpenAiSse(input, modelId, toolSchemas, tap);+ const without = await runOpenAiSse(input, modelId, toolSchemas, undefined);+ streams.push({ input, output, outputUnchangedByMiddleware: output === without });+ }++ const before = structuredClone(scenario.nextRequestMessages) as any[];+ const next = await rawRequest(engine, modelId).providerRequest({+ claudeRequest: {},+ messages: structuredClone(scenario.nextRequestMessages) as any[],+ tools: [],+ });+ // Round-trip through JSON: the golden records what reaches the wire.+ const after = JSON.parse(JSON.stringify(next.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/parser-goldens.test.ts b/packages/cli/src/test-fixtures/parser-goldens/parser-goldens.test.tsindex 07ad77fb..568341eb 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@@ -6,8 +6,8 @@* 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.+ * payloads. The Gemini middleware golden replays through the hook raw tier+ * (`drive-gemini-raw.ts`), against the output the middleware recorded.*/import { describe, expect, it } from "bun:test";@@ -23,7 +23,7 @@ import {REPAIRED_ARGS,REPAIRED_VALUE,} from "./cases.js";-import { runGeminiCapture } from "./drive-gemini-middleware.js";+import { runGeminiCapture } from "./drive-gemini-raw.js";import { runParserCase } from "./drive-seam.js";import {type GeminiMiddlewareGolden,@@ -89,7 +89,7 @@ describe("parser goldens: parser + response seam reproduce them", () => {});}- it("Gemini thought-signature middleware", async () => {+ it("Gemini thought-signature built-in (raw tier)", async () => {const golden = geminiGolden();const replay = await runGeminiCapture(golden.id,