Skip to content

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

feat(hooks)!: run an event's hooks in turn, each seeing earlier edits

Jack Rudenko1d2a2a7895fa
diff --git a/packages/cli/src/hooks/actions.test.ts b/packages/cli/src/hooks/actions.test.ts
index a7c53fcd..2bc73580 100644
--- a/packages/cli/src/hooks/actions.test.ts
+++ b/packages/cli/src/hooks/actions.test.ts
@@ -5,6 +5,7 @@ import {
applyStageA,
applyStageB,
applyToolCallActions,
+ requestChainState,
validateAction,
} from "./actions.js";
import { type RequestAction, type ToolCallAction, act } from "./public.js";
@@ -41,6 +42,18 @@ function request(overrides: Partial<MutableClaudeRequest> = {}): MutableClaudeRe
};
}
+/**
+ * One stage-A step over `req` as a chain's first step: the step's state is
+ * written back onto `req`, so the assertions read the request as it would be sent.
+ */
+function stageA(req: MutableClaudeRequest, items: ReadonlyArray<PlannedAction<RequestAction>>) {
+ const step = applyStageA(requestChainState(req), items);
+ req.system = step.state.system;
+ req.messages = step.state.messages;
+ req.tools = step.state.tools;
+ return { ...step, held: step.state.held, removedTools: step.state.removedTools };
+}
+
describe("validateAction", () => {
it("allows only the event's actions", () => {
expect(validateAction("request", act.injectSystemNote("x")).ok).toBe(true);
@@ -148,7 +161,7 @@ describe("validateAction", () => {
describe("applyStageA — system notes", () => {
it("appends to a string system as a new paragraph, once per identical text", () => {
const req = request();
- const { results } = applyStageA(req, [
+ const { results } = stageA(req, [
plan("a", act.injectSystemNote("NOTE")),
plan("b", act.injectSystemNote("NOTE")),
]);
@@ -162,7 +175,7 @@ describe("applyStageA — system notes", () => {
it("appends a text block to an array system without mutating the original array", () => {
const original = [{ type: "text", text: "base" }];
const req = request({ system: original });
- applyStageA(req, [plan("a", act.injectSystemNote("NOTE"))]);
+ stageA(req, [plan("a", act.injectSystemNote("NOTE"))]);
expect(req.system).toEqual([
{ type: "text", text: "base" },
{ type: "text", text: "NOTE" },
@@ -172,7 +185,7 @@ describe("applyStageA — system notes", () => {
it("sets the system prompt when the request has none", () => {
const req = request({ system: undefined });
- applyStageA(req, [plan("a", act.injectSystemNote("NOTE"))]);
+ stageA(req, [plan("a", act.injectSystemNote("NOTE"))]);
expect(req.system).toBe("NOTE");
});
});
@@ -180,7 +193,7 @@ describe("applyStageA — system notes", () => {
describe("applyStageA — message text", () => {
it("appendUserText lands at the end of the last user message, after tool_result", () => {
const req = request();
- applyStageA(req, [plan("a", act.appendUserText("REMINDER"))]);
+ stageA(req, [plan("a", act.appendUserText("REMINDER"))]);
const last = req.messages?.[2];
expect(last.content).toEqual([
{ type: "tool_result", tool_use_id: "toolu_1", content: "plan contents" },
@@ -190,7 +203,7 @@ describe("applyStageA — message text", () => {
it("appendUserText normalises a string content to blocks first", () => {
const req = request({ messages: [{ role: "user", content: "hi" }] });
- applyStageA(req, [plan("a", act.appendUserText("there"))]);
+ stageA(req, [plan("a", act.appendUserText("there"))]);
expect(req.messages?.[0].content).toEqual([
{ type: "text", text: "hi" },
{ type: "text", text: "there" },
@@ -199,13 +212,13 @@ describe("applyStageA — message text", () => {
it("appendUserText with no user message is invalid", () => {
const req = request({ messages: [{ role: "assistant", content: "x" }] });
- const { results } = applyStageA(req, [plan("a", act.appendUserText("x"))]);
+ const { results } = stageA(req, [plan("a", act.appendUserText("x"))]);
expect(results[0]).toMatchObject({ decision: "invalid", detail: "no_user_message" });
});
it("identical appended texts are applied once", () => {
const req = request({ messages: [{ role: "user", content: "q" }] });
- const { results } = applyStageA(req, [
+ const { results } = stageA(req, [
plan("a", act.appendUserText("same")),
plan("b", act.appendUserText("same")),
]);
@@ -213,19 +226,38 @@ describe("applyStageA — message text", () => {
expect(results.map((r) => r.decision)).toEqual(["matched", "superseded"]);
});
+ it("a duplicate in a later step's list is superseded too", () => {
+ const req = request({ messages: [{ role: "user", content: "q" }] });
+ const first = applyStageA(requestChainState(req), [
+ plan("a", act.appendUserText("same")),
+ plan("a", act.injectSystemNote("NOTE")),
+ ]);
+ const second = applyStageA(first.state, [
+ plan("b", act.appendUserText("same")),
+ plan("b", act.injectSystemNote("NOTE")),
+ ]);
+ expect(second.state.messages?.[0].content.length).toBe(2);
+ expect(second.state.system).toBe("base\n\nNOTE");
+ expect(second.results.map((r) => [r.hookId, r.decision, r.detail])).toEqual([
+ ["b", "superseded", "duplicate"],
+ ["b", "superseded", "duplicate"],
+ ]);
+ // A step never mutates the state it was given.
+ expect(first.state.messages?.[0].content.length).toBe(2);
+ expect(req.messages?.[0].content).toBe("q");
+ });
+
it("never touches tool_use, tool_result or thinking, and defaults roles to user", () => {
const req = request();
const before = structuredClone(req.messages);
- applyStageA(req, [plan("a", act.replaceMessageText("plan", "PLAN"))]);
+ stageA(req, [plan("a", act.replaceMessageText("plan", "PLAN"))]);
// User string content was edited; the assistant turn (default roles) was not.
expect(req.messages?.[0].content).toBe("first question");
expect(req.messages?.[1]).toEqual(before?.[1]);
// tool_result content is never edited even though it contains "plan".
expect(req.messages?.[2]).toEqual(before?.[2]);
- applyStageA(req, [
- plan("a", act.replaceMessageText("check", "verify", { roles: ["assistant"] })),
- ]);
+ stageA(req, [plan("a", act.replaceMessageText("check", "verify", { roles: ["assistant"] }))]);
const blocks = req.messages?.[1].content;
expect(blocks[0]).toEqual({ type: "thinking", thinking: "secret plan", signature: "sig" });
expect(blocks[1]).toEqual({ type: "text", text: "let me verify" });
@@ -234,7 +266,7 @@ describe("applyStageA — message text", () => {
it("inserts a literal $500 verbatim and expands $1 in regex mode", () => {
const req = request({ messages: [{ role: "user", content: "cost N, name: Ada Lovelace" }] });
- applyStageA(req, [
+ stageA(req, [
plan("a", act.replaceMessageText("N", "$500")),
plan("b", act.replaceMessageText("(\\w+) (\\w+)$", "$2 $1", { regex: true })),
]);
@@ -255,7 +287,7 @@ describe("applyStageA — message text", () => {
{ role: "user", content: "DROP" },
],
});
- const { results } = applyStageA(req, [plan("a", act.removeMessageText("DROP"))]);
+ const { results } = stageA(req, [plan("a", act.removeMessageText("DROP"))]);
expect(req.messages?.[0].content).toEqual([{ type: "text", text: "keep" }]);
expect(req.messages?.[2].content).toBe("DROP");
expect(results[0]).toMatchObject({ decision: "matched", detail: "empty_message_reverted:1" });
@@ -263,14 +295,14 @@ describe("applyStageA — message text", () => {
it("reports invalid empty_message when every changed message was reverted", () => {
const req = request({ messages: [{ role: "user", content: "only" }] });
- const { results } = applyStageA(req, [plan("a", act.removeMessageText("only"))]);
+ const { results } = stageA(req, [plan("a", act.removeMessageText("only"))]);
expect(req.messages?.[0].content).toBe("only");
expect(results[0]).toMatchObject({ decision: "invalid", detail: "empty_message" });
});
it("applies message edits sequentially in effective order", () => {
const req = request({ messages: [{ role: "user", content: "a" }] });
- applyStageA(req, [
+ stageA(req, [
plan("a", act.replaceMessageText("a", "b")),
plan("b", act.replaceMessageText("b", "c")),
plan("c", act.appendUserText("d")),
@@ -284,7 +316,7 @@ describe("applyStageA — message text", () => {
it("does not mutate the original message objects", () => {
const original = { role: "user", content: [{ type: "text", text: "x" }] };
const req = request({ messages: [original] });
- applyStageA(req, [plan("a", act.replaceMessageText("x", "y"))]);
+ stageA(req, [plan("a", act.replaceMessageText("x", "y"))]);
expect(original.content[0]?.text).toBe("x");
expect(req.messages?.[0]).not.toBe(original);
});
@@ -293,14 +325,14 @@ describe("applyStageA — message text", () => {
describe("applyStageA — tools", () => {
it("removeTool is refused while a message holds a tool_use of that tool", () => {
const req = request();
- const { results } = applyStageA(req, [plan("a", act.removeTool("Read"))]);
+ const { results } = stageA(req, [plan("a", act.removeTool("Read"))]);
expect(results[0]).toMatchObject({ decision: "invalid", detail: "tool_in_history" });
expect(req.tools?.map((t) => t.name)).toEqual(["Read", "Write", "ExitPlanMode"]);
});
- it("removes a tool, and supersedes every other action on it", () => {
+ it("removes a tool at its place; an action before it stays matched, later ones are superseded", () => {
const req = request();
- const stage = applyStageA(req, [
+ const stage = stageA(req, [
plan("a", act.replaceToolSchema("Write", { type: "object", properties: {} })),
plan("b", act.removeTool("Write")),
plan("c", act.removeTool("Write")),
@@ -308,7 +340,7 @@ describe("applyStageA — tools", () => {
]);
expect(req.tools?.map((t) => t.name)).toEqual(["Read", "ExitPlanMode"]);
expect(stage.results.map((r) => [r.hookId, r.decision, r.detail])).toEqual([
- ["a", "superseded", "tool_removed"],
+ ["a", "matched", undefined],
["b", "matched", undefined],
["c", "superseded", "already_removed"],
]);
@@ -320,30 +352,30 @@ describe("applyStageA — tools", () => {
});
});
- it("replaceToolSchema: first wins per tool; an unknown tool is invalid", () => {
+ it("replaceToolSchema: each replaces the current schema; an unknown tool is invalid", () => {
const original = request().tools?.[1];
const req = request();
- const { results } = applyStageA(req, [
+ const { results } = stageA(req, [
plan("a", act.replaceToolSchema("Write", { type: "object", properties: { a: {} } })),
plan("b", act.replaceToolSchema("Write", { type: "object", properties: { b: {} } })),
plan("c", act.replaceToolSchema("Nope", { type: "object" })),
]);
- expect(req.tools?.[1].input_schema).toEqual({ type: "object", properties: { a: {} } });
+ expect(req.tools?.[1].input_schema).toEqual({ type: "object", properties: { b: {} } });
expect(original?.input_schema).toEqual({ type: "object" });
expect(results.map((r) => [r.hookId, r.decision, r.detail])).toEqual([
["a", "matched", undefined],
- ["b", "superseded", undefined],
+ ["b", "matched", undefined],
["c", "invalid", "unknown_tool"],
]);
});
it("removeTool on an unknown tool is invalid", () => {
- const { results } = applyStageA(request(), [plan("a", act.removeTool("Nope"))]);
+ const { results } = stageA(request(), [plan("a", act.removeTool("Nope"))]);
expect(results[0]).toMatchObject({ decision: "invalid", detail: "unknown_tool" });
});
- it("holds description actions for stage B in effective order", () => {
- const { held } = applyStageA(request(), [
+ it("holds description actions for stage B in chain order", () => {
+ const { held } = stageA(request(), [
plan("a", act.rewriteToolDescription("Write", " A")),
plan("b", act.injectSystemNote("x")),
plan("c", act.replaceToolDescription("Read", "R")),
@@ -384,14 +416,16 @@ describe("applyStageB — tool descriptions", () => {
expect(converted[0]?.description).toBe(`Long.${append}`);
});
- it("first description action per tool wins across append and replace", () => {
+ it("replays description actions in order, each over the description before it", () => {
const claude = claudeTools();
- const results = applyStageB(claude, chatTools(), [
+ const converted = chatTools();
+ const results = applyStageB(claude, converted, [
plan("a", act.replaceToolDescription("Write", "NEW")),
plan("b", act.rewriteToolDescription("Write", " more")),
]);
- expect(claude[1]?.description).toBe("NEW");
- expect(results.map((r) => r.decision)).toEqual(["matched", "superseded"]);
+ expect(claude[1]?.description).toBe("NEW more");
+ expect(converted[1]?.function.description).toBe("NEW more");
+ expect(results.map((r) => r.decision)).toEqual(["matched", "matched"]);
});
it("an unknown tool is invalid; a capped tool changes the Claude copy only", () => {
@@ -427,18 +461,24 @@ describe("applyStageB — tool descriptions", () => {
});
describe("applyToolCallActions", () => {
- it("first repairToolArgs wins; later ones are superseded", () => {
+ it("each repairToolArgs replaces the current arguments; every one is matched", () => {
const items: PlannedAction<ToolCallAction>[] = [
{ hookId: "a", action: act.repairToolArgs({ file_path: "/a" }, "a") },
{ hookId: "b", action: act.repairToolArgs({ file_path: "/b" }, "b") },
];
- const out = applyToolCallActions(items);
- expect(out.args).toEqual({ file_path: "/a" });
- expect(out.results.map((r) => r.decision)).toEqual(["matched", "superseded"]);
- });
-
- it("returns no args when nothing repaired", () => {
- expect(applyToolCallActions([{ hookId: "a", action: act.warn("w") }])).toEqual({
+ const model = { file_path: "/model" };
+ const out = applyToolCallActions(model, items);
+ expect(out.args).toEqual({ file_path: "/b" });
+ expect(out.repaired).toBe(true);
+ expect(out.results.map((r) => r.decision)).toEqual(["matched", "matched"]);
+ expect(model).toEqual({ file_path: "/model" });
+ });
+
+ it("returns the arguments it was given when nothing repaired", () => {
+ const model = { file_path: "/model" };
+ expect(applyToolCallActions(model, [{ hookId: "a", action: act.warn("w") }])).toEqual({
+ args: model,
+ repaired: false,
results: [],
});
});
diff --git a/packages/cli/src/hooks/actions.ts b/packages/cli/src/hooks/actions.ts
index 1d0b7a81..a2f56ef3 100644
--- a/packages/cli/src/hooks/actions.ts
+++ b/packages/cli/src/hooks/actions.ts
@@ -4,25 +4,28 @@
* request and tool-call targets.
*
* Actions are plain data (the Command pattern as a discriminated union), so
- * they can be validated, severity-gated, conflict-checked, journaled and, for
- * `injectUserTurn` / `annotateTurn`, serialised into the hook inbox. Nothing
- * here runs hook code.
+ * they can be validated, severity-gated, applied one hook-chain step at a time,
+ * journaled and, for `injectUserTurn` / `annotateTurn`, serialised into the
+ * hook inbox. Nothing here runs hook code.
*
* The request appliers never mutate a message, block or tool object in place.
- * Stage A replaces `system`, `messages` and `tools` (and every changed message
- * or tool) with new objects on the request object it is given; stage B replaces
- * ELEMENTS of the two tool arrays it is given, so a converted array the provider
- * payload aliases sees the change. That makes them safe on the NativeHandler's
+ * Stage A works on a step's copy of the request chain's working state and
+ * returns a new one (every changed message or tool a new object); stage B
+ * replaces ELEMENTS of the two tool arrays it is given, so a converted array the
+ * provider payload aliases sees the change. That makes them safe on the NativeHandler's
* copy-on-write view as well as on ComposedHandler's deep copy.
*/
+import { sanitizeToolNameForGemini } from "../handlers/shared/gemini-schema.js";
import type {
ClaudeContentBlock,
HookAction,
JsonValue,
RemoveMessageText,
ReplaceMessageText,
+ ReplaceToolDescription,
RequestAction,
+ RewriteToolDescription,
ToolCallAction,
} from "./public.js";
import { compileMatcher } from "./text-rewrite.js";
@@ -253,7 +256,7 @@ export interface PlannedAction<A extends HookAction = HookAction> {
export interface ActionResult<A extends HookAction = HookAction> {
hookId: string;
action: A;
- decision: "matched" | "superseded" | "invalid" | "ignored";
+ decision: "matched" | "superseded" | "invalid" | "ignored" | "queued" | "dropped";
detail?: string;
}
@@ -269,140 +272,227 @@ export interface MutableClaudeRequest {
const STAGE_B: ReadonlySet<string> = new Set(["rewriteToolDescription", "replaceToolDescription"]);
-/** The outcome of stage A, and what stage B still has to do. */
-export interface StageAResult {
+/**
+ * The working state of one request hook chain (§4.4.1): the request as the
+ * steps so far left it, plus what the duplicate and removal rules need to
+ * remember across steps. Never mutated: each step produces a new one.
+ */
+export interface RequestChainState {
+ // biome-ignore lint/suspicious/noExplicitAny: Claude-format system is a string or a block array
+ readonly system: any;
+ // biome-ignore lint/suspicious/noExplicitAny: Claude-format messages
+ readonly messages: any[] | undefined;
+ // biome-ignore lint/suspicious/noExplicitAny: Claude-format tools
+ readonly tools: any[] | undefined;
+ /** Tool-description actions in chain order: the overlay, replayed at stage B. */
+ readonly held: ReadonlyArray<PlannedAction<RequestAction>>;
+ /** System-note texts earlier steps of this dispatch added (pending notes included). */
+ readonly seenNotes: ReadonlySet<string>;
+ /** User texts earlier steps of this dispatch appended. */
+ readonly seenAppends: ReadonlySet<string>;
+ /**
+ * Tools earlier steps removed, each with the number of `held` description actions at
+ * the moment of its removal: the held actions before that index preceded the removal
+ * and stay `matched` at stage B; the ones from it on are `superseded: tool_removed`.
+ */
+ readonly removedTools: ReadonlyMap<string, number>;
+}
+
+/** The working state a request chain starts from: the attempt's request as given. */
+export function requestChainState(req: MutableClaudeRequest): RequestChainState {
+ return {
+ system: req.system,
+ messages: req.messages,
+ tools: req.tools,
+ held: [],
+ seenNotes: new Set(),
+ seenAppends: new Set(),
+ removedTools: new Map(),
+ };
+}
+
+/** One step's stage A: the next working state, the outcomes to journal, what took effect. */
+export interface StageAStep {
+ state: RequestChainState;
+ /** Outcomes of every action but the description actions (those journal at stage B). */
results: ActionResult<RequestAction>[];
- /** Tool-description actions, held for stage B in effective order. */
- held: PlannedAction<RequestAction>[];
- /** Tools stage A removed; description actions on them are `superseded`. */
- removedTools: ReadonlySet<string>;
+ /** What took effect at this step, description actions on a present tool included. */
+ applied: PlannedAction<RequestAction>[];
}
/**
- * Stage A, before conversion: system notes, then message text, then tool
- * schemas, then tool removal. `items` are in effective order and already
- * severity-gated (fix only) and validated; `warn` actions are skipped.
+ * Stage A for one step of the request chain, before conversion. `items` are one
+ * hook's actions (or the pending notes), already severity-gated and validated,
+ * applied in ARRAY ORDER, each over the state every action before it produced:
+ * earlier actions of the same list and every earlier step. `warn` is skipped.
*
- * Conflict rules: identical system notes and identical appended user texts are
- * applied once (later copies `superseded`); message text actions apply
- * sequentially; one schema per tool (first wins); one removal per tool (first
- * wins); every other action on a removed tool is `superseded`.
+ * - `injectSystemNote` / `appendUserText`: a text equal to one an earlier action
+ * of this dispatch added is `superseded` (`duplicate`).
+ * - message text edits: over the current messages.
+ * - `replaceToolSchema`: replaces the current schema; on a removed tool
+ * `superseded: tool_removed`.
+ * - `removeTool`: removes the tool now; a second removal is
+ * `superseded: already_removed`; a tool still used in the history is
+ * `invalid: tool_in_history`.
+ * - description actions join the overlay (`held`), in order, and are journaled
+ * when stage B applies them.
+ *
+ * `state` is never mutated, so a throw leaves the chain's working state intact.
*/
export function applyStageA(
- req: MutableClaudeRequest,
+ state: RequestChainState,
items: ReadonlyArray<PlannedAction<RequestAction>>
-): StageAResult {
+): StageAStep {
+ const req: MutableClaudeRequest = {
+ system: state.system,
+ messages: state.messages,
+ tools: state.tools,
+ };
+ const held = [...state.held];
+ const seenNotes = new Set(state.seenNotes);
+ const seenAppends = new Set(state.seenAppends);
+ const removed = new Map(state.removedTools);
const results: ActionResult<RequestAction>[] = [];
- const held: PlannedAction<RequestAction>[] = [];
+ const applied: PlannedAction<RequestAction>[] = [];
const result = (
item: PlannedAction<RequestAction>,
decision: ActionResult["decision"],
detail?: string
- ) => results.push(detail === undefined ? { ...item, decision } : { ...item, decision, detail });
+ ) => {
+ results.push(detail === undefined ? { ...item, decision } : { ...item, decision, detail });
+ if (decision === "matched") applied.push(item);
+ };
+ const hasTool = (name: string) => (req.tools ?? []).some((t) => t?.name === name);
- const notes: PlannedAction<RequestAction>[] = [];
- const messageEdits: PlannedAction<RequestAction>[] = [];
- const schemas: PlannedAction<RequestAction>[] = [];
- const removals: PlannedAction<RequestAction>[] = [];
for (const item of items) {
- const t = item.action.type;
- if (t === "warn") continue;
- if (t === "injectSystemNote") notes.push(item);
- else if (t === "appendUserText" || t === "replaceMessageText" || t === "removeMessageText") {
- messageEdits.push(item);
- } else if (t === "replaceToolSchema") schemas.push(item);
- else if (t === "removeTool") removals.push(item);
- else if (STAGE_B.has(t)) held.push(item);
- }
-
- // 1. System notes.
- const seenNotes = new Set<string>();
- for (const item of notes) {
- const text = (item.action as { text: string }).text;
- if (seenNotes.has(text)) {
- result(item, "superseded", "duplicate");
- continue;
- }
- seenNotes.add(text);
- req.system = withSystemNote(req.system, text);
- result(item, "matched");
- }
-
- // 2. Message text, sequentially in effective order.
- const seenAppends = new Set<string>();
- for (const item of messageEdits) {
const a = item.action;
- if (a.type === "appendUserText") {
- if (seenAppends.has(a.text)) {
- result(item, "superseded", "duplicate");
- continue;
+ switch (a.type) {
+ case "warn":
+ break;
+ case "injectSystemNote":
+ if (seenNotes.has(a.text)) {
+ result(item, "superseded", "duplicate");
+ break;
+ }
+ seenNotes.add(a.text);
+ req.system = withSystemNote(req.system, a.text);
+ result(item, "matched");
+ break;
+ case "appendUserText": {
+ if (seenAppends.has(a.text)) {
+ result(item, "superseded", "duplicate");
+ break;
+ }
+ const r = appendUserText(req, a.text);
+ if (r) result(item, "invalid", r);
+ else {
+ // Only an append that took effect makes a later identical one a duplicate.
+ seenAppends.add(a.text);
+ result(item, "matched");
+ }
+ break;
+ }
+ case "replaceMessageText":
+ case "removeMessageText": {
+ const edit = editMessageText(req, a);
+ if (edit.invalid) result(item, "invalid", edit.invalid);
+ else if (edit.reverted > 0 && !edit.changed) result(item, "invalid", "empty_message");
+ else if (edit.reverted > 0)
+ result(item, "matched", `empty_message_reverted:${edit.reverted}`);
+ else if (!edit.changed) result(item, "ignored", "no_match");
+ else result(item, "matched");
+ break;
}
- seenAppends.add(a.text);
- const r = appendUserText(req, a.text);
- if (r) result(item, "invalid", r);
- else result(item, "matched");
- continue;
+ case "replaceToolSchema":
+ if (removed.has(a.tool)) result(item, "superseded", "tool_removed");
+ else if (!hasTool(a.tool)) result(item, "invalid", "unknown_tool");
+ else {
+ req.tools = (req.tools ?? []).map((t) =>
+ t?.name === a.tool ? { ...t, input_schema: structuredClone(a.inputSchema) } : t
+ );
+ result(item, "matched");
+ }
+ break;
+ case "removeTool":
+ if (removed.has(a.tool)) result(item, "superseded", "already_removed");
+ else if (!hasTool(a.tool)) result(item, "invalid", "unknown_tool");
+ else if (toolInHistory(req.messages, a.tool)) result(item, "invalid", "tool_in_history");
+ else {
+ removed.set(a.tool, held.length);
+ req.tools = (req.tools ?? []).filter((t) => t?.name !== a.tool);
+ result(item, "matched");
+ }
+ break;
+ default:
+ if (STAGE_B.has(a.type)) {
+ held.push(item);
+ // Visible to later steps through the overlay when the tool is on offer;
+ // stage B journals its outcome either way.
+ const tool = (a as { tool: string }).tool;
+ if (!removed.has(tool) && hasTool(tool)) applied.push(item);
+ }
+ break;
}
- const edit = editMessageText(req, a as ReplaceMessageText | RemoveMessageText);
- if (edit.invalid) result(item, "invalid", edit.invalid);
- else if (edit.reverted > 0 && !edit.changed) result(item, "invalid", "empty_message");
- else if (edit.reverted > 0) result(item, "matched", `empty_message_reverted:${edit.reverted}`);
- else if (!edit.changed) result(item, "ignored", "no_match");
- else result(item, "matched");
}
- // 3. Decide removals first, so a schema action on a removed tool is superseded.
- const toolNames = new Set<string>((req.tools ?? []).map((t) => t?.name));
- const removed = new Set<string>();
- const removalOutcome = new Map<
- PlannedAction<RequestAction>,
- [ActionResult["decision"], string?]
- >();
- for (const item of removals) {
- const name = (item.action as { tool: string }).tool;
- if (removed.has(name)) removalOutcome.set(item, ["superseded", "already_removed"]);
- else if (!toolNames.has(name)) removalOutcome.set(item, ["invalid", "unknown_tool"]);
- else if (toolInHistory(req.messages, name)) {
- removalOutcome.set(item, ["invalid", "tool_in_history"]);
- } else {
- removed.add(name);
- removalOutcome.set(item, ["matched"]);
- }
- }
+ return {
+ state: {
+ system: req.system,
+ messages: req.messages,
+ tools: req.tools,
+ held,
+ seenNotes,
+ seenAppends,
+ removedTools: removed,
+ },
+ results,
+ applied,
+ };
+}
- // 4. Schemas: one per tool, first wins.
- const schemaDone = new Set<string>();
- for (const item of schemas) {
- const a = item.action as { tool: string; inputSchema: Record<string, unknown> };
- if (!toolNames.has(a.tool)) result(item, "invalid", "unknown_tool");
- else if (removed.has(a.tool)) result(item, "superseded", "tool_removed");
- else if (schemaDone.has(a.tool)) result(item, "superseded");
- else {
- schemaDone.add(a.tool);
- req.tools = (req.tools ?? []).map((t) =>
- t?.name === a.tool ? { ...t, input_schema: structuredClone(a.inputSchema) } : t
- );
- result(item, "matched");
- }
- }
+/** One description action over a description. */
+function describeWith(
+ a: RewriteToolDescription | ReplaceToolDescription,
+ current: unknown
+): string {
+ return a.type === "rewriteToolDescription"
+ ? `${typeof current === "string" ? current : ""}${a.append}`
+ : a.description;
+}
- // 5. Removal.
- if (removed.size > 0) req.tools = (req.tools ?? []).filter((t) => !removed.has(t?.name));
- for (const item of removals) {
- const [decision, detail] = removalOutcome.get(item) ?? ["invalid"];
- result(item, decision, detail);
+/**
+ * The description overlay: `tools` with every held description action replayed
+ * in chain order on new tool objects, exactly as stage B will give the
+ * Claude-format tools. `tools` is never mutated; an action on a tool not in it
+ * is passed over.
+ */
+export function overlayToolDescriptions(
+ // biome-ignore lint/suspicious/noExplicitAny: Claude-format tools
+ tools: any[] | undefined,
+ held: ReadonlyArray<PlannedAction<RequestAction>>
+ // biome-ignore lint/suspicious/noExplicitAny: Claude-format tools
+): any[] {
+ const out = [...(tools ?? [])];
+ for (const { action: a } of held) {
+ if (a.type !== "rewriteToolDescription" && a.type !== "replaceToolDescription") continue;
+ out.forEach((t, i) => {
+ if (t?.name === a.tool) out[i] = { ...t, description: describeWith(a, t.description) };
+ });
}
-
- return { results, held, removedTools: removed };
+ return out;
}
/**
- * Stage B, after conversion: tool descriptions on BOTH representations, so
- * `--summarize-tools` (which truncates the converted description to its first
- * sentence) can never cut an appended instruction. One description action per
- * tool (first wins). A tool present in `claudeTools` but not in the converted
- * array (the tool-count cap removed it) gets the Claude-format change only and is
- * `matched` with detail `capped`.
+ * Stage B, after conversion: the held description actions replayed in chain
+ * order on BOTH representations, each over the description the earlier ones
+ * produced, so `--summarize-tools` (which truncates the converted description
+ * to its first sentence) can never cut an appended instruction. An append
+ * extends the current description; a replace replaces it on both copies. A tool
+ * present in `claudeTools` but not in the converted array (the tool-count cap
+ * removed it) gets the Claude-format change only and is `matched` with detail
+ * `capped`. On a tool a step removed, an action held before the removal is `matched`
+ * (it took effect on the view the steps in between saw) and one held after it is
+ * `superseded: tool_removed`.
*
* `convertedTools` is null on a route with one representation (native).
*/
@@ -412,87 +502,134 @@ export function applyStageB(
// biome-ignore lint/suspicious/noExplicitAny: see above
convertedTools: any[] | null,
held: ReadonlyArray<PlannedAction<RequestAction>>,
- removedTools: ReadonlySet<string> = new Set()
+ removedTools: ReadonlyMap<string, number> = new Map()
): ActionResult<RequestAction>[] {
const results: ActionResult<RequestAction>[] = [];
- const done = new Set<string>();
- const sameArray = convertedTools === claudeTools;
-
- for (const item of held) {
+ for (const [index, item] of held.entries()) {
const a = item.action;
if (a.type !== "rewriteToolDescription" && a.type !== "replaceToolDescription") continue;
- if (removedTools.has(a.tool)) {
- results.push({ ...item, decision: "superseded", detail: "tool_removed" });
- continue;
- }
- if (done.has(a.tool)) {
- results.push({ ...item, decision: "superseded" });
- continue;
- }
- const describe = (current: unknown) =>
- a.type === "rewriteToolDescription"
- ? `${typeof current === "string" ? current : ""}${a.append}`
- : a.description;
-
- let claudeHits = 0;
- claudeTools.forEach((t, i) => {
- if (t?.name !== a.tool) return;
- claudeTools[i] = { ...t, description: describe(t.description) };
- claudeHits++;
- });
- if (claudeHits === 0) {
- results.push({ ...item, decision: "invalid", detail: "unknown_tool" });
- continue;
- }
- done.add(a.tool);
-
- let convertedHits = 0;
- if (convertedTools && !sameArray) {
- convertedTools.forEach((t, i) => {
- // Chat Completions wraps the definition in `function`; Responses does not.
- if (t?.function?.name === a.tool) {
- convertedTools[i] = {
- ...t,
- function: { ...t.function, description: describe(t.function.description) },
- };
- convertedHits++;
- } else if (!t?.function && t?.name === a.tool) {
- convertedTools[i] = { ...t, description: describe(t.description) };
- convertedHits++;
- }
- });
- }
- const capped = convertedTools !== null && !sameArray && convertedHits === 0;
- results.push(
- capped ? { ...item, decision: "matched", detail: "capped" } : { ...item, decision: "matched" }
- );
+ const removedAt = removedTools.get(a.tool);
+ // §4-J: an action applied before the removal stays `matched` (it took effect on the
+ // view the hooks between saw); one after it is `superseded: tool_removed`.
+ const outcome: Outcome =
+ removedAt === undefined
+ ? describeOnBoth(claudeTools, convertedTools, a)
+ : index < removedAt
+ ? { decision: "matched" }
+ : { decision: "superseded", detail: "tool_removed" };
+ results.push({ ...item, ...outcome });
}
return results;
}
-/** The outcome of the `repairToolArgs` actions for one call. */
+type Outcome = Pick<ActionResult, "decision" | "detail">;
+
+/** One description action on both tool representations (stage B), and its outcome. */
+function describeOnBoth(
+ // biome-ignore lint/suspicious/noExplicitAny: Claude-format and provider-format tools
+ claudeTools: any[],
+ // biome-ignore lint/suspicious/noExplicitAny: see above
+ convertedTools: any[] | null,
+ a: RewriteToolDescription | ReplaceToolDescription
+): Outcome {
+ const claudeHits = replaceEach(claudeTools, (t) =>
+ t?.name === a.tool
+ ? { tool: { ...t, description: describeWith(a, t.description) }, hits: 1 }
+ : null
+ );
+ if (claudeHits === 0) return { decision: "invalid", detail: "unknown_tool" };
+ // null: a route with one representation (native); the same array: nothing to convert.
+ if (convertedTools === null || convertedTools === claudeTools) return { decision: "matched" };
+ const convertedHits = replaceEach(convertedTools, (t) => describeConverted(t, a));
+ return convertedHits === 0 ? { decision: "matched", detail: "capped" } : { decision: "matched" };
+}
+
+/**
+ * Replace each element `edit` matches with the tool it returns, in place (the
+ * element, never the tool object), and count the definitions matched.
+ */
+function replaceEach(
+ // biome-ignore lint/suspicious/noExplicitAny: Claude-format or provider-format tools
+ tools: any[],
+ // biome-ignore lint/suspicious/noExplicitAny: see above
+ edit: (t: any) => { tool: any; hits: number } | null
+): number {
+ let hits = 0;
+ tools.forEach((t, i) => {
+ const r = edit(t);
+ if (!r || r.hits === 0) return;
+ tools[i] = r.tool;
+ hits += r.hits;
+ });
+ return hits;
+}
+
+/**
+ * One description action on one provider-format tool entry: the new entry and how many
+ * definitions in it matched. Chat Completions wraps the definition in `function`;
+ * Responses does not; Gemini groups every definition under one `functionDeclarations`
+ * entry, by the name `convertToolsToGemini` sanitized.
+ */
+function describeConverted(
+ // biome-ignore lint/suspicious/noExplicitAny: provider-format tool
+ t: any,
+ a: RewriteToolDescription | ReplaceToolDescription
+ // biome-ignore lint/suspicious/noExplicitAny: provider-format tool
+): { tool: any; hits: number } {
+ if (t?.function?.name === a.tool) {
+ return {
+ tool: {
+ ...t,
+ function: { ...t.function, description: describeWith(a, t.function.description) },
+ },
+ hits: 1,
+ };
+ }
+ if (Array.isArray(t?.functionDeclarations)) {
+ const name = sanitizeToolNameForGemini(a.tool);
+ let hits = 0;
+ // biome-ignore lint/suspicious/noExplicitAny: Gemini function declaration
+ const decls = t.functionDeclarations.map((d: any) => {
+ if (d?.name !== name) return d;
+ hits++;
+ return { ...d, description: describeWith(a, d.description) };
+ });
+ return { tool: hits > 0 ? { ...t, functionDeclarations: decls } : t, hits };
+ }
+ if (!t?.function && t?.name === a.tool) {
+ return { tool: { ...t, description: describeWith(a, t.description) }, hits: 1 };
+ }
+ return { tool: t, hits: 0 };
+}
+
+/** The outcome of one step's `repairToolArgs` actions for one call. */
export interface ToolCallApplied {
- /** The replacement arguments, or undefined when nothing was applied. */
- args?: Record<string, unknown>;
+ /** The working arguments after the step: a new object when a repair applied, else `args`. */
+ args: Record<string, unknown>;
+ /** True when at least one repair applied. */
+ repaired: boolean;
results: ActionResult<ToolCallAction>[];
}
-/** One call's arguments: the first `repairToolArgs` in effective order wins. */
+/**
+ * One step's repairs of one call, in order: each `repairToolArgs` replaces the
+ * working arguments, and every one is `matched` (journaled `repaired`). `args`
+ * is never mutated.
+ */
export function applyToolCallActions(
+ args: Record<string, unknown>,
items: ReadonlyArray<PlannedAction<ToolCallAction>>
): ToolCallApplied {
const results: ActionResult<ToolCallAction>[] = [];
- let args: Record<string, unknown> | undefined;
+ let current = args;
+ let repaired = false;
for (const item of items) {
if (item.action.type !== "repairToolArgs") continue;
- if (args !== undefined) {
- results.push({ ...item, decision: "superseded" });
- continue;
- }
- args = structuredClone(item.action.args);
+ current = structuredClone(item.action.args);
+ repaired = true;
results.push({ ...item, decision: "matched" });
}
- return args === undefined ? { results } : { args, results };
+ return { args: current, repaired, results };
}
/* ───────────── request helpers ───────────── */
diff --git a/packages/cli/src/hooks/builtins/plan-mode.test.ts b/packages/cli/src/hooks/builtins/plan-mode.test.ts
index 28033444..a11b0a95 100644
--- a/packages/cli/src/hooks/builtins/plan-mode.test.ts
+++ b/packages/cli/src/hooks/builtins/plan-mode.test.ts
@@ -26,6 +26,7 @@ function requestContext(
severity: "fix",
log: () => {},
signal: new AbortController().signal,
+ prior: [],
event: "request",
host: { mode: "other" },
route: { modelId: "gpt-5.6-codex", provider: "openai-codex", native: false },
diff --git a/packages/cli/src/hooks/builtins/session-context.test.ts b/packages/cli/src/hooks/builtins/session-context.test.ts
index 869ee252..f585ba68 100644
--- a/packages/cli/src/hooks/builtins/session-context.test.ts
+++ b/packages/cli/src/hooks/builtins/session-context.test.ts
@@ -18,6 +18,7 @@ function requestContext(systemText = "", messages: unknown[] = []): RequestConte
severity: "fix",
log: () => {},
signal: new AbortController().signal,
+ prior: [],
event: "request",
host: { mode: "other" },
route: { modelId: "m", provider: "p", native: false },
diff --git a/packages/cli/src/hooks/engine.test.ts b/packages/cli/src/hooks/engine.test.ts
index 8f0ee384..af4f503a 100644
--- a/packages/cli/src/hooks/engine.test.ts
+++ b/packages/cli/src/hooks/engine.test.ts
@@ -3,12 +3,20 @@ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import * as logger from "../logger.js";
-import { applyStageA, applyToolCallActions } from "./actions.js";
+import {
+ type RequestChainState,
+ applyStageA,
+ applyToolCallActions,
+ requestChainState,
+} from "./actions.js";
import {
BREAKER_THRESHOLD,
type BaseContextParts,
+ EVENT_BUDGETS,
HookEngine,
MAX_PENDING_SESSIONS,
+ dispatchBoundMs,
+ stepTimeout,
} from "./engine.js";
import type { JournalEntry } from "./journal.js";
import { type HookDefinition, act } from "./public.js";
@@ -51,29 +59,48 @@ function engineWith(
return { engine, journal, warnings };
}
-/** A minimal RequestContext builder. */
-const requestCtx = (_a: ApplicableHook, base: BaseContextParts) => ({
+/** A minimal RequestContext builder over a request chain's working state. */
+const requestCtx = (_a: ApplicableHook, base: BaseContextParts, state: RequestChainState) => ({
...base,
event: "request",
host: { mode: "other" },
route: ROUTE,
- request: { model: "glm-5", stream: true, systemText: "", messages: [], tools: [] },
+ request: {
+ model: "glm-5",
+ stream: true,
+ systemText: typeof state.system === "string" ? state.system : "",
+ messages: [],
+ tools: [],
+ },
harness: { planModeActive: false },
session: null,
});
+/** One request dispatch: stage A applied at each step, starting from system "base". */
+function runRequest(engine: HookEngine) {
+ return engine.runChain(
+ "request",
+ engine.select("request", { route: ROUTE }),
+ { context: requestCtx, apply: (state, items) => applyStageA(state, items) },
+ META,
+ { initial: requestChainState({ system: "base", messages: [], tools: [] }) }
+ );
+}
+
afterEach(() => resetTelemetryState());
-describe("HookEngine.run", () => {
- it("runs hooks concurrently and returns actions in effective order", async () => {
- const started: string[] = [];
+describe("HookEngine.runChain", () => {
+ it("runs hooks one after another; the second sees the first's applied note", async () => {
+ const events: string[] = [];
+ let fastSaw: { systemText: string; prior: unknown } | undefined;
const slow = userHook(
"slow",
{
on: {
request: async () => {
- started.push("slow");
+ events.push("slow:start");
await Bun.sleep(40);
+ events.push("slow:end");
return [act.injectSystemNote("SLOW")];
},
},
@@ -84,8 +111,9 @@ describe("HookEngine.run", () => {
"fast",
{
on: {
- request: () => {
- started.push("fast");
+ request: (ctx) => {
+ events.push("fast:start");
+ fastSaw = { systemText: ctx.request.systemText, prior: ctx.prior };
return [act.injectSystemNote("FAST")];
},
},
@@ -94,22 +122,19 @@ describe("HookEngine.run", () => {
);
const { engine } = engineWith([slow, fast]);
const t0 = performance.now();
- const result = await engine.run(
- "request",
- engine.select("request", { route: ROUTE }),
- requestCtx,
- META
- );
- // Both started before either finished, and the slow one did not serialise the fast one.
- expect(started).toEqual(["slow", "fast"]);
- expect(performance.now() - t0).toBeLessThan(400);
- expect(result.apply.map((p) => [p.hookId, p.action])).toEqual([
+ const result = await runRequest(engine);
+ // The second step starts only after the first returned, so the total is at least the slow hook's.
+ expect(events).toEqual(["slow:start", "slow:end", "fast:start"]);
+ expect(performance.now() - t0).toBeGreaterThanOrEqual(35);
+ expect(fastSaw?.systemText).toBe("base\n\nSLOW");
+ expect(fastSaw?.prior).toEqual([
+ { hookId: "hook:m/slow", action: act.injectSystemNote("SLOW") },
+ ]);
+ expect(result.applied.map((p) => [p.hookId, p.action])).toEqual([
["hook:m/slow", act.injectSystemNote("SLOW")],
["hook:m/fast", act.injectSystemNote("FAST")],
]);
- const req = { system: "base" };
- applyStageA(req, result.apply);
- expect(req.system).toBe("base\n\nSLOW\n\nFAST");
+ expect(result.state.system).toBe("base\n\nSLOW\n\nFAST");
});
it("times out a hook: its signal aborts, its result is discarded, others still apply", async () => {
@@ -128,19 +153,18 @@ describe("HookEngine.run", () => {
});
const ok = userHook("ok", { on: { request: () => [act.injectSystemNote("OK")] } }, 1);
const { engine, journal } = engineWith([hung, ok]);
- const result = await engine.run(
- "request",
- engine.select("request", { route: ROUTE }),
- requestCtx,
- META
- );
+ const result = await runRequest(engine);
expect(seen?.aborted).toBe(true);
expect(result.runs.map((r) => r.status)).toEqual(["timeout", "ok"]);
- expect(result.apply.map((p) => p.hookId)).toEqual(["hook:m/ok"]);
- expect(journal.find((e) => e.decision === "timeout")?.hookId).toBe("hook:m/hung");
+ expect(result.applied.map((p) => p.hookId)).toEqual(["hook:m/ok"]);
+ expect(journal.find((e) => e.decision === "timeout")).toMatchObject({
+ hookId: "hook:m/hung",
+ detail: "50 ms",
+ });
await Bun.sleep(150);
expect(lateMutation).toBe(true);
- expect(result.apply.length).toBe(1);
+ expect(result.applied.length).toBe(1);
+ expect(result.state.system).toBe("base\n\nOK");
});
it("clamps timeoutMs to the event maximum", async () => {
@@ -152,6 +176,44 @@ describe("HookEngine.run", () => {
expect(timeoutFor({ apiVersion: 1, id: "x" } as HookDefinition, "sessionIdle")).toBe(5_000);
});
+ it("has an event budget equal to each event's per-hook maximum", async () => {
+ const { EVENT_TIMEOUTS } = await import("./engine.js");
+ for (const event of [
+ "request",
+ "toolCall",
+ "responseRewrite",
+ "responseEnd",
+ "sessionStart",
+ "sessionIdle",
+ "sessionBlocked",
+ "sessionEnd",
+ "raw.providerRequest",
+ "raw.providerStreamEnd",
+ ] as const) {
+ expect(EVENT_BUDGETS[event]).toBe(EVENT_TIMEOUTS[event].max);
+ }
+ expect(EVENT_BUDGETS["raw.providerChunk"]).toBeNull();
+ expect(EVENT_BUDGETS["raw.response"]).toBeNull();
+ });
+
+ it("clips a step's timeout to the budget left, and skips a step with none left", () => {
+ const d = { apiVersion: 1, id: "x", timeoutMs: 3_000 } as HookDefinition;
+ expect(stepTimeout(d, "request", 5_000)).toEqual({ ms: 3_000, clipped: false });
+ expect(stepTimeout(d, "request", 1_200)).toEqual({ ms: 1_200, clipped: true });
+ expect(stepTimeout(d, "request", 0)).toBeNull();
+ expect(stepTimeout(d, "raw.response", null)).toEqual({ ms: 3_000, clipped: false });
+ });
+
+ it("bounds a dispatch by the sum of its step timeouts, capped at the budget", () => {
+ const hook = (timeoutMs?: number) => ({
+ hook: { def: { apiVersion: 1, id: "x", timeoutMs } as HookDefinition },
+ });
+ expect(dispatchBoundMs("responseEnd", [hook()])).toBe(5_000);
+ expect(dispatchBoundMs("responseEnd", [hook(), hook(8_000)])).toBe(13_000);
+ expect(dispatchBoundMs("responseEnd", [hook(20_000), hook(20_000)])).toBe(30_000);
+ expect(dispatchBoundMs("sessionIdle", [])).toBe(0);
+ });
+
it("fails open on a throw, a rejection and an invalid return value", async () => {
const thrower = userHook("thrower", {
on: {
@@ -168,14 +230,10 @@ describe("HookEngine.run", () => {
const wrong = userHook("wrong", { on: { request: (() => "nope") as never } }, 2);
const fine = userHook("fine", { on: { request: () => [act.injectSystemNote("F")] } }, 3);
const { engine, journal } = engineWith([thrower, rejecter, wrong, fine]);
- const result = await engine.run(
- "request",
- engine.select("request", { route: ROUTE }),
- requestCtx,
- META
- );
+ const result = await runRequest(engine);
expect(result.runs.map((r) => r.status)).toEqual(["error", "error", "invalid", "ok"]);
- expect(result.apply.map((p) => p.hookId)).toEqual(["hook:m/fine"]);
+ expect(result.applied.map((p) => p.hookId)).toEqual(["hook:m/fine"]);
+ expect(result.state.system).toBe("base\n\nF");
expect(journal.filter((e) => e.decision === "error").map((e) => e.detail)).toEqual([
"boom",
"no",
@@ -189,13 +247,8 @@ describe("HookEngine.run", () => {
},
});
const { engine, journal } = engineWith([mixed]);
- const result = await engine.run(
- "request",
- engine.select("request", { route: ROUTE }),
- requestCtx,
- META
- );
- expect(result.apply.map((p) => p.action.type)).toEqual(["injectSystemNote"]);
+ const result = await runRequest(engine);
+ expect(result.applied.map((p) => p.action.type)).toEqual(["injectSystemNote"]);
expect(journal.find((e) => e.decision === "invalid")).toMatchObject({
action: "appendText",
detail: "not_allowed:appendText",
@@ -209,13 +262,9 @@ describe("HookEngine.run", () => {
on: { request: () => [act.injectSystemNote("N"), act.warn("look out")] },
});
const { engine, journal } = engineWith([h], [], { "hook:m/w": "warn" });
- const result = await engine.run(
- "request",
- engine.select("request", { route: ROUTE }),
- requestCtx,
- META
- );
- expect(result.apply).toEqual([]);
+ const result = await runRequest(engine);
+ expect(result.applied).toEqual([]);
+ expect(result.state.system).toBe("base");
expect(journal.map((e) => [e.action, e.decision])).toEqual([
["injectSystemNote", "warned"],
["warn", "warned"],
@@ -234,11 +283,11 @@ describe("HookEngine.run", () => {
});
const { engine } = engineWith([h], [], { "hook:*": "off" });
expect(engine.select("request", { route: ROUTE })).toEqual([]);
- await engine.run("request", engine.select("request", { route: ROUTE }), requestCtx, META);
+ await runRequest(engine);
expect(called).toBe(false);
});
- it("hands the handler a frozen context with hookId, severity, log and signal", async () => {
+ it("hands the handler a frozen context with hookId, severity, log, signal and prior", async () => {
let captured: Record<string, unknown> | undefined;
const h = userHook("ctx", {
on: {
@@ -249,12 +298,14 @@ describe("HookEngine.run", () => {
},
});
const { engine } = engineWith([h]);
- await engine.run("request", engine.select("request", { route: ROUTE }), requestCtx, META);
+ await runRequest(engine);
expect(Object.isFrozen(captured)).toBe(true);
expect(captured?.hookId).toBe("hook:m/ctx");
expect(captured?.severity).toBe("fix");
expect(typeof captured?.log).toBe("function");
expect(captured?.signal).toBeInstanceOf(AbortSignal);
+ expect(captured?.prior).toEqual([]);
+ expect(Object.isFrozen(captured?.prior)).toBe(true);
});
it("restricts an observe-mode toolCall hook to warn", async () => {
@@ -268,18 +319,20 @@ describe("HookEngine.run", () => {
},
});
const { engine, journal } = engineWith([obs]);
- const result = await engine.run(
+ const result = await engine.runChain(
"toolCall",
engine.select("toolCall", { route: ROUTE }),
- requestCtx,
- { ...META, toolName: "Write" }
+ { context: (_a, base) => ({ ...base, event: "toolCall" }) },
+ { ...META, toolName: "Write" },
+ { initial: undefined }
);
- expect(result.apply).toEqual([]);
+ expect(result.applied).toEqual([]);
expect(journal.map((e) => e.decision)).toContain("invalid");
expect(journal.find((e) => e.decision === "invalid")?.detail).toBe("observe_only");
});
- it("an aborted parent signal ends unfinished hooks as aborted, unjournaled", async () => {
+ it("an aborted dispatch ends the running hook as aborted and starts no later one", async () => {
+ let laterCalled = false;
const h = userHook("idle", {
on: {
sessionIdle: async (ctx) => {
@@ -288,20 +341,33 @@ describe("HookEngine.run", () => {
},
},
});
- const { engine, journal } = engineWith([h]);
+ const later = userHook(
+ "later",
+ {
+ on: {
+ sessionIdle: () => {
+ laterCalled = true;
+ return [];
+ },
+ },
+ },
+ 1
+ );
+ const { engine, journal } = engineWith([h, later]);
const parent = new AbortController();
- const running = engine.run(
+ const running = engine.runChain(
"sessionIdle",
engine.select("sessionIdle", { sessionModel: "glm-5" }),
- (_a, base) => ({ ...base, event: "sessionIdle" }),
+ { context: (_a, base) => ({ ...base, event: "sessionIdle" }) },
META,
- { signal: parent.signal }
+ { initial: undefined, signal: parent.signal }
);
await Bun.sleep(10);
parent.abort("caller");
const result = await running;
- expect(result.runs[0]?.status).toBe("aborted");
- expect(result.apply).toEqual([]);
+ expect(result.runs.map((r) => r.status)).toEqual(["aborted"]);
+ expect(result.applied).toEqual([]);
+ expect(laterCalled).toBe(false);
expect(journal).toEqual([]);
});
});
@@ -319,7 +385,7 @@ describe("circuit breaker", () => {
});
const { engine, journal, warnings } = engineWith([flaky]);
for (let i = 0; i < BREAKER_THRESHOLD + 2; i++) {
- await engine.run("request", engine.select("request", { route: ROUTE }), requestCtx, META);
+ await runRequest(engine);
}
expect(calls).toBe(BREAKER_THRESHOLD);
expect(engine.isDisabled("hook:m/flaky")).toBe(true);
@@ -342,7 +408,7 @@ describe("circuit breaker", () => {
});
const { engine } = engineWith([sometimes]);
for (let i = 0; i < 12; i++) {
- await engine.run("request", engine.select("request", { route: ROUTE }), requestCtx, META);
+ await runRequest(engine);
}
expect(engine.isDisabled("hook:m/sometimes")).toBe(false);
expect(n).toBe(12);
@@ -368,15 +434,19 @@ describe("journal fan-out and the upload projection", () => {
for (const toolName of ["mcp__srv__x", "Write"]) {
const meta = { ...META, toolName };
- const result = await engine.run(
+ await engine.runChain(
"toolCall",
engine.select("toolCall", { route: ROUTE }),
- requestCtx,
- meta
+ {
+ context: (_a, base) => ({ ...base, event: "toolCall" }),
+ apply: (args: Record<string, unknown>, items) => {
+ const out = applyToolCallActions(args, items);
+ return { state: out.args, results: out.results, applied: items };
+ },
+ },
+ meta,
+ { initial: {} as Record<string, unknown> }
);
- for (const planned of result.apply) {
- engine.recordResults("toolCall", applyToolCallActions([planned]).results, meta);
- }
}
const outbox = join(dir, "outbox.jsonl");
diff --git a/packages/cli/src/hooks/journal.ts b/packages/cli/src/hooks/journal.ts
index 95cb260f..4334a47f 100644
--- a/packages/cli/src/hooks/journal.ts
+++ b/packages/cli/src/hooks/journal.ts
@@ -71,7 +71,7 @@ export type Decision =
| "warned" // a rule matched but severity was warn
| "repaired" // arguments were rewritten
| "novel" // nothing matched and the observer was consulted
- | "superseded" // an earlier hook won the same target
+ | "superseded" // a duplicate of an earlier step's text, or an action on a removed tool
| "invalid" // the action was refused (shape, limit, not allowed for the event)
| "timeout" // the handler did not return within its timeout
| "error" // the handler threw or rejected
@@ -79,7 +79,8 @@ export type Decision =
| "dropped" // an injection or annotation was dropped
| "queued" // an injection or note was queued
| "delivered" // an injection was delivered
- | "raw"; // a raw (unsafe) hook touched the request or response
+ | "raw" // a raw (unsafe) hook touched the request or response
+ | "skipped"; // the event budget was spent before the hook's step (local only)
/**
* The decision values the telemetry backend accepts — the `counts.*` keys of
diff --git a/packages/cli/src/hooks/public.ts b/packages/cli/src/hooks/public.ts
index fa3f01c4..2527ecbd 100644
--- a/packages/cli/src/hooks/public.ts
+++ b/packages/cli/src/hooks/public.ts
@@ -19,6 +19,15 @@
* per-turn data from a proxy event to `sessionIdle` with `annotateTurn`, never
* with module variables.
*
+ * ## Execution: a hook chain
+ *
+ * The hooks of one event run one after another, in effective order. Each hook's
+ * actions are applied before the next hook is called, so `ctx.request`,
+ * `ctx.tool.args` and `ctx.response` show what the earlier hooks did, and
+ * `ctx.prior` lists it. A warn-severity or failing hook changes nothing for the
+ * next one. Each event has a budget for all its hooks together; a hook's timeout
+ * is cut to what is left of it.
+ *
* ## Output
*
* Log with `ctx.log`. `console.*` and `process.stdout`/`stderr` writes made by a
@@ -45,20 +54,20 @@ export type JsonValue =
/* ───────────── facts ───────────── */
export interface HarnessFacts {
- planModeActive: boolean;
- planFilePath?: string;
- planDir?: string;
+ readonly planModeActive: boolean;
+ readonly planFilePath?: string;
+ readonly planDir?: string;
/** Claude Code session id from request metadata */
- sessionId?: string;
+ readonly sessionId?: string;
/** empty = no listing found, not "no skills" */
- skills?: ReadonlyArray<{ name: string; description: string }>;
+ readonly skills?: ReadonlyArray<{ name: string; description: string }>;
}
export interface RouteInfo {
/** bare model name the handler serves, e.g. "glm-5" */
- modelId: string;
+ readonly modelId: string;
/** claudish provider name, e.g. "openrouter"; "anthropic" for native */
- provider: string;
+ readonly provider: string;
/**
* true when the request is served by the native Anthropic handler, OR when
* !forceForeignModel && (/^claude[-.]/i.test(modelId) || provider === "anthropic")
@@ -66,7 +75,7 @@ export interface RouteInfo {
* rule the plan-mode built-in has always used (a claude-* uid on an aggregator that sets
* forceForeignModel is foreign).
*/
- native: boolean;
+ readonly native: boolean;
}
export interface ClaudeTool {
@@ -88,23 +97,37 @@ export interface ClaudeMessage {
content: string | ReadonlyArray<ClaudeContentBlock>;
}
+/**
+ * In `request`, the request as the earlier steps of the hook chain left it. On
+ * the response side and in `claims()`, the request chain's final view.
+ */
export interface RequestFacts {
- /** as Claude Code asked for it */
- model: string;
- stream: boolean;
- /** system prompt flattened to text */
- systemText: string;
- /** read-only view; change it through actions */
- messages: ReadonlyArray<ClaudeMessage>;
- /** read-only view; change it through actions */
- tools: ReadonlyArray<ClaudeTool>;
+ /** as Claude Code asked for it; frozen */
+ readonly model: string;
+ /** frozen */
+ readonly stream: boolean;
+ /** system prompt flattened to text, after earlier steps */
+ readonly systemText: string;
+ /** read-only view after earlier steps; change it through actions */
+ readonly messages: ReadonlyArray<ClaudeMessage>;
+ /**
+ * read-only view after earlier steps; `description` includes earlier description actions as
+ * stage B will apply them to the Claude-format tool (the provider copy may be summarised)
+ */
+ readonly tools: ReadonlyArray<ClaudeTool>;
}
/** Which session a proxy event belongs to, when claudish knows. */
export interface ProxySessionRef {
- kind: SessionKind;
- id: string;
- role: "slot" | "judge" | null;
+ readonly kind: SessionKind;
+ readonly id: string;
+ readonly role: "slot" | "judge" | null;
+}
+
+/** One action an earlier step of this hook chain applied or handed on. */
+export interface PriorAction {
+ readonly hookId: string;
+ readonly action: HookAction;
}
interface BaseContext {
@@ -113,8 +136,18 @@ interface BaseContext {
readonly severity: Severity;
/** writes to claudish's debug log; never to the terminal */
log(message: string): void;
- /** aborted when this hook's timeout elapses */
+ /**
+ * this step's own signal: aborted when its step timeout elapses (its own timeout, or the
+ * event budget left, whichever is shorter) or when the dispatch is aborted. Never shared
+ * with another hook's step.
+ */
readonly signal: AbortSignal;
+ /**
+ * actions earlier steps of this hook chain applied (or, for responseEnd/sessionStart/
+ * sessionIdle, handed on), in order. Empty for the first step and in claims()/the toolCall
+ * predicate. Never lists warn actions or anything a warn-severity hook returned.
+ */
+ readonly prior: ReadonlyArray<PriorAction>;
}
export interface ProxyContext extends BaseContext {
@@ -134,7 +167,9 @@ export interface ToolCallContext extends ProxyContext {
readonly tool: {
id: string;
name: string;
+ /** the arguments after every repair earlier hooks in the chain applied */
args: Readonly<Record<string, unknown>>;
+ /** the argument JSON exactly as the model produced it; never rewritten */
rawArgs: string;
};
}
@@ -156,6 +191,7 @@ export interface ResponseView {
stopReason: string | null;
}
+/** response = the held response after every text action earlier hooks in the chain applied */
export interface ResponseRewriteContext extends ProxyContext {
readonly event: "responseRewrite";
readonly response: ResponseView;
@@ -405,7 +441,7 @@ interface HookBase {
models?: string | ReadonlyArray<string>;
/** default "all"; proxy events only */
routes?: RouteScope;
- /** per-handler; clamped to the event's maximum */
+ /** per call; clamped to the event's maximum and to the event budget left when the hook's turn comes */
timeoutMs?: number;
on?: HookHandlers;
}
diff --git a/packages/cli/src/hooks/response-blocks.ts b/packages/cli/src/hooks/response-blocks.ts
index d0faecd6..86de5500 100644
--- a/packages/cli/src/hooks/response-blocks.ts
+++ b/packages/cli/src/hooks/response-blocks.ts
@@ -8,6 +8,7 @@
*/
import type { ResponseBlock, ResponseView } from "./public.js";
+import type { RewriteBlock, RewrittenBlock } from "./text-rewrite.js";
/** One block as the collector assembled it. */
export interface CollectedBlock {
@@ -183,28 +184,52 @@ export function collectorView(
);
}
+/** One block of a non-streaming message's `content[]`, as a hook sees it. */
+export function messageBlock(b: Json): ResponseBlock {
+ switch (b?.type) {
+ case "text":
+ return { type: "text", text: typeof b.text === "string" ? b.text : "" };
+ case "thinking":
+ return { type: "thinking", thinking: typeof b.thinking === "string" ? b.thinking : "" };
+ case "tool_use":
+ return {
+ type: "tool_use",
+ id: String(b.id ?? ""),
+ name: String(b.name ?? ""),
+ input: b.input,
+ };
+ default:
+ return { type: "other", blockType: typeof b?.type === "string" ? b.type : "unknown" };
+ }
+}
+
/** A view over a non-streaming message's `content[]`. */
export function messageView(message: Json): ResponseView {
const content: Json[] = Array.isArray(message?.content) ? message.content : [];
- const blocks: ResponseBlock[] = content.map((b: Json): ResponseBlock => {
- switch (b?.type) {
- case "text":
- return { type: "text", text: typeof b.text === "string" ? b.text : "" };
- case "thinking":
- return { type: "thinking", thinking: typeof b.thinking === "string" ? b.thinking : "" };
- case "tool_use":
- return {
- type: "tool_use",
- id: String(b.id ?? ""),
- name: String(b.name ?? ""),
- input: b.input,
- };
- default:
- return { type: "other", blockType: typeof b?.type === "string" ? b.type : "unknown" };
- }
- });
return responseView(
- blocks,
+ content.map(messageBlock),
typeof message?.stop_reason === "string" ? message.stop_reason : null
);
}
+
+/**
+ * The view a later `responseRewrite` step sees (§4.4.1): `lead` (blocks before
+ * the held region, e.g. thinking that streamed live), then the held region as
+ * `applyTextActions` left it — an edited or inserted text block as its new
+ * text, any other block as `original(source)` gives it. Text actions touch only
+ * text blocks, so `reasoning`, `toolNames` and `stopReason` come out unchanged.
+ */
+export function rewrittenView(
+ lead: ReadonlyArray<ResponseBlock>,
+ rewritten: ReadonlyArray<RewrittenBlock<RewriteBlock>>,
+ original: (source: number) => ResponseBlock,
+ stopReason: string | null
+): ResponseView {
+ const held = rewritten.map(
+ (b): ResponseBlock =>
+ b.source === null || b.changed
+ ? { type: "text", text: (b.block as { text?: string }).text ?? "" }
+ : original(b.source)
+ );
+ return responseView([...lead, ...held], stopReason);
+}
diff --git a/packages/cli/src/hooks/seam-hooks.ts b/packages/cli/src/hooks/seam-hooks.ts
index 978a36af..fdd6659f 100644
--- a/packages/cli/src/hooks/seam-hooks.ts
+++ b/packages/cli/src/hooks/seam-hooks.ts
@@ -5,16 +5,21 @@
* `toolCall`, warn-mode `responseRewrite`, `responseEnd`), and the
* non-streaming JSON branch.
*
+ * Each call is one dispatch, run as a hook chain (§4.4.1): a later hook sees
+ * the arguments, the response text or the hand-offs earlier hooks produced.
+ * Separate dispatches — two tool calls, the tap's `responseEnd` and warn-mode
+ * `responseRewrite` — run independently.
+ *
* Every call fails open: the engine journals a throw, a rejection, a timeout or
* an invalid return and treats it as "no actions", so a broken hook leaves the
- * response exactly as the model produced it.
+ * response as the earlier hooks left it.
*/
import { log } from "../logger.js";
-import { type PlannedAction, applyToolCallActions } from "./actions.js";
+import { type ActionResult, type PlannedAction, applyToolCallActions } from "./actions.js";
import type { JournalMeta } from "./engine.js";
import type { InjectionSink } from "./injection/sinks.js";
-import type { ResponseView, RewriteAction } from "./public.js";
+import type { ResponseEndAction, ResponseView, ToolCallAction } from "./public.js";
import { type ArmedToolHook, type HookRequestScope, armedFor } from "./request-stage.js";
import { parseToolArgs } from "./response-blocks.js";
import type { RewriteBlock, TextAction, TextRewriteResult } from "./text-rewrite.js";
@@ -27,9 +32,43 @@ export interface SeamToolCall {
rawArgs: string;
}
-/** Fix-severity rewrite actions, attributed, in effective order. */
+/** Fix-severity rewrite actions, attributed, in chain order. */
export type PlannedTextAction = PlannedAction<TextAction>;
+/** The held response after some text actions: what the next rewrite step sees. */
+export interface RewrittenResponse {
+ view: ResponseView;
+ /** What `applyTextActions` did: the blocks, and each action's outcome by index. */
+ result: TextRewriteResult<RewriteBlock>;
+}
+
+/** The `responseRewrite` chain's outcome: its actions, and the response they produce. */
+export interface RewriteOutcome {
+ /** Every text action the chain applied, in chain order. */
+ planned: PlannedTextAction[];
+ /** `after(planned)`: the blocks to emit and each action's outcome, computed once. */
+ final: RewrittenResponse;
+}
+
+/**
+ * One tool call's `toolCall` chain outcome. Its repairs are journaled by exactly one
+ * of `delivered()` (journaled `repaired`) and `notDelivered(detail)` (journaled
+ * `dropped`, local only), whichever the seam calls first; later calls do nothing.
+ */
+export interface ToolCallOutcome {
+ /** The repaired arguments, or undefined to forward the model's own. */
+ args: Record<string, unknown> | undefined;
+ delivered(): void;
+ notDelivered(detail: string): void;
+}
+
+/** The outcome of a call no hook could repair: nothing to journal either way. */
+const NO_REPAIR: ToolCallOutcome = Object.freeze({
+ args: undefined,
+ delivered: () => {},
+ notDelivered: () => {},
+});
+
export class SeamHooks {
constructor(
readonly scope: HookRequestScope,
@@ -55,100 +94,198 @@ export class SeamHooks {
}
/**
- * Run the fix-severity `toolCall` hooks for one held call. Returns the
- * replacement arguments, or undefined to forward the model's own.
+ * Run the fix-severity `toolCall` hook chain for one held call. Each repair
+ * replaces the working arguments the next hook sees in `ctx.tool.args`;
+ * `ctx.tool.rawArgs` stays the model's own JSON.
+ *
+ * The repairs are journaled when the caller knows what reached the client, not
+ * at their steps: a flush (hold cap, upstream error, fail-open) or a cancel can
+ * send the model's own arguments after a repair was applied, and a `repaired`
+ * line (an upload decision) for arguments the client never received is a false
+ * negative for the very divergence plan-mode measures. The caller calls exactly
+ * one of `delivered()` / `notDelivered()`; `ignored` lines, which describe what a
+ * hook decided rather than what was sent, are journaled at once.
*/
- async interceptToolCall(
- call: SeamToolCall,
- signal?: AbortSignal
- ): Promise<Record<string, unknown> | undefined> {
- return this.runToolCall(call, this.plan.interceptHooks, true, signal);
- }
-
- /** Run the observe-mode and warn-severity `toolCall` hooks for one delivered call. */
- async observeToolCall(call: SeamToolCall, signal?: AbortSignal): Promise<void> {
- await this.runToolCall(call, this.plan.observeToolHooks, false, signal);
- }
-
- private async runToolCall(
- call: SeamToolCall,
- armed: ReadonlyArray<ArmedToolHook>,
- apply: boolean,
- signal?: AbortSignal
- ): Promise<Record<string, unknown> | undefined> {
- const hooks = armed.filter((h) => armedFor(h, call.name)).map((h) => h.applicable);
- if (hooks.length === 0) return undefined;
+ async interceptToolCall(call: SeamToolCall, signal?: AbortSignal): Promise<ToolCallOutcome> {
+ const hooks = this.hooksFor(this.plan.interceptHooks, call.name);
+ if (hooks.length === 0) return NO_REPAIR;
const args = parseToolArgs(call.rawArgs);
if (!args) {
// Malformed arguments are the recovery layer's concern; no hook sees them.
log(`[hooks] toolCall ${call.name}: arguments are not a JSON object, hooks not called`);
- return undefined;
+ return NO_REPAIR;
}
const meta: JournalMeta = { ...this.scope.meta, toolName: call.name };
- const run = await this.engine.run(
+ // The path facts keep the telemetry's categorical `pathRelation`: the
+ // plan-mode measurement keys off where the MODEL wrote against where the
+ // harness expected it. So `observedPath` is always the model's own path, not
+ // the working arguments an earlier hook's repair produced; `argKeys` is what
+ // the step saw.
+ const modelPath = typeof args.file_path === "string" ? args.file_path : undefined;
+ const pathFacts = (current: Record<string, unknown>) => ({
+ argKeys: Object.keys(current),
+ observedPath: modelPath,
+ expectedPath: this.scope.harness.planFilePath,
+ });
+ const deferred: Array<{
+ results: ActionResult<ToolCallAction>[];
+ before: Record<string, unknown>;
+ }> = [];
+ const chain = await this.engine.runChain(
"toolCall",
hooks,
- (_applicable, base) =>
- this.scope.proxyContext(base, "toolCall", {
- tool: {
- id: call.id,
- name: call.name,
- args: structuredClone(args),
- rawArgs: call.rawArgs,
- },
- }),
+ {
+ context: (_applicable, base, current) => this.toolContext(base, call, current),
+ apply: (current, items) => {
+ const out = applyToolCallActions(current, items);
+ if (out.results.length > 0) deferred.push({ results: out.results, before: current });
+ return {
+ state: out.args,
+ // journaled by delivered() / notDelivered()
+ results: [],
+ applied: out.results.map((r) => ({ hookId: r.hookId, action: r.action })),
+ };
+ },
+ // A call a hook saw and left alone is a decision too: a hook that never
+ // fires looks identical to a hook that is not needed without the negatives.
+ afterStep: (run, before) => {
+ if (run.status !== "ok" || run.applied.some((p) => p.action.type === "repairToolArgs")) {
+ return;
+ }
+ this.engine.journal({
+ ...meta,
+ ...pathFacts(before),
+ event: "toolCall",
+ hookId: run.applicable.hook.id,
+ decision: "ignored",
+ });
+ },
+ },
meta,
- signal ? { signal } : {}
+ signal ? { initial: args, signal } : { initial: args }
);
- if (!apply) return undefined;
+ const repaired = chain.applied.some((p) => p.action.type === "repairToolArgs");
+ if (repaired) log(`[hooks] toolCall ${call.name}: arguments repaired`);
- // The path facts keep the telemetry's categorical `pathRelation`: the
- // plan-mode measurement keys off where a write landed against where the
- // harness expected it.
- const pathFacts = {
- argKeys: Object.keys(args),
- observedPath: typeof args.file_path === "string" ? args.file_path : undefined,
- expectedPath: this.scope.harness.planFilePath,
+ let settled = false;
+ const once = (fn: () => void) => () => {
+ if (settled) return;
+ settled = true;
+ fn();
};
- const applied = applyToolCallActions(run.apply);
- this.engine.recordResults("toolCall", applied.results, meta, (r) => ({
- ...pathFacts,
- note: r.action.type === "repairToolArgs" ? r.action.reason : undefined,
- }));
- // A call a hook saw and left alone is a decision too: a hook that never
- // fires looks identical to a hook that is not needed without the negatives.
- if (applied.args === undefined) {
- for (const r of run.runs) {
- if (r.status !== "ok") continue;
- this.engine.journal({
- ...meta,
- ...pathFacts,
- event: "toolCall",
- hookId: r.applicable.hook.id,
- decision: "ignored",
- });
- }
- } else {
- log(`[hooks] toolCall ${call.name}: arguments repaired`);
+ return {
+ args: repaired ? chain.state : undefined,
+ delivered: once(() => {
+ for (const { results, before } of deferred) {
+ this.engine.recordResults("toolCall", results, meta, (r) => ({
+ ...pathFacts(before),
+ note: r.action.type === "repairToolArgs" ? r.action.reason : undefined,
+ }));
+ }
+ }),
+ notDelivered: (detail: string) =>
+ once(() => {
+ for (const { results, before } of deferred) {
+ for (const r of results) {
+ this.engine.journal({
+ ...meta,
+ ...pathFacts(before),
+ event: "toolCall",
+ hookId: r.hookId,
+ action: r.action.type,
+ decision: "dropped",
+ detail,
+ });
+ }
+ }
+ })(),
+ };
+ }
+
+ /** Run the observe-mode and warn-severity `toolCall` hook chain for one delivered call. */
+ async observeToolCall(call: SeamToolCall, signal?: AbortSignal): Promise<void> {
+ const hooks = this.hooksFor(this.plan.observeToolHooks, call.name);
+ if (hooks.length === 0) return;
+ const args = parseToolArgs(call.rawArgs);
+ if (!args) {
+ log(`[hooks] toolCall ${call.name}: arguments are not a JSON object, hooks not called`);
+ return;
}
- return applied.args;
+ // Only `warn` can come out of an observing chain: nothing is applied.
+ await this.engine.runChain(
+ "toolCall",
+ hooks,
+ { context: (_applicable, base, current) => this.toolContext(base, call, current) },
+ { ...this.scope.meta, toolName: call.name },
+ signal ? { initial: args, signal } : { initial: args }
+ );
+ }
+
+ private hooksFor(armed: ReadonlyArray<ArmedToolHook>, name: string) {
+ return armed.filter((h) => armedFor(h, name)).map((h) => h.applicable);
+ }
+
+ private toolContext(base: object, call: SeamToolCall, args: Record<string, unknown>): object {
+ return this.scope.proxyContext(base, "toolCall", {
+ // proxyContext hands the hook a deep-frozen copy: `args` is the working state.
+ tool: { id: call.id, name: call.name, args, rawArgs: call.rawArgs },
+ });
}
- /** Run the fix-severity `responseRewrite` hooks; returns their text actions. */
- async rewrite(view: ResponseView, signal?: AbortSignal): Promise<PlannedTextAction[]> {
+ /**
+ * Run the fix-severity `responseRewrite` hook chain; returns every text action
+ * it applied, in chain order, for the seam's single `applyTextActions` call.
+ * `after` gives the held response once a list of text actions is applied:
+ * each hook's `ctx.response` is `after` of everything earlier steps returned.
+ */
+ async rewrite(
+ after: (actions: ReadonlyArray<TextAction>) => RewrittenResponse,
+ signal?: AbortSignal
+ ): Promise<RewriteOutcome> {
const hooks = this.plan.rewriteHooks;
- if (hooks.length === 0) return [];
- const run = await this.engine.run(
+ if (hooks.length === 0) return { planned: [], final: after([]) };
+ // One evaluation per working state: the step that applied it and the
+ // context of the next step share it.
+ let memoFor: ReadonlyArray<PlannedTextAction> | null = null;
+ let memo: RewrittenResponse | null = null;
+ const at = (planned: ReadonlyArray<PlannedTextAction>): RewrittenResponse => {
+ if (planned !== memoFor || !memo) {
+ memo = after(planned.map((p) => p.action));
+ memoFor = planned;
+ }
+ return memo;
+ };
+
+ const chain = await this.engine.runChain(
"responseRewrite",
hooks,
- (_applicable, base) => this.scope.proxyContext(base, "responseRewrite", { response: view }),
+ {
+ context: (_applicable, base, planned: ReadonlyArray<PlannedTextAction>) =>
+ this.scope.proxyContext(base, "responseRewrite", { response: at(planned).view }),
+ apply: (planned, items) => {
+ const added = items.filter((p): p is PlannedTextAction => p.action.type !== "warn");
+ const next = [...planned, ...added];
+ // The seam journals the outcomes once, after the final application;
+ // `prior` lists the actions that changed the text at this step.
+ const changed = new Set(
+ at(next)
+ .result.applied.filter((a) => a.changed)
+ .map((a) => a.index)
+ );
+ return {
+ state: next,
+ results: [],
+ applied: added.filter((_, i) => changed.has(planned.length + i)),
+ };
+ },
+ },
this.scope.meta,
- signal ? { signal } : {}
- );
- return run.apply.filter(
- (p): p is PlannedTextAction => (p.action as RewriteAction).type !== "warn"
+ signal ? { initial: [], signal } : { initial: [] }
);
+ // The final application is the one the last step already computed (memoised):
+ // the seam emits it rather than applying every action again.
+ return { planned: [...chain.state], final: at(chain.state) };
}
/** Journal what `applyTextActions` did with each planned action. */
@@ -197,15 +334,19 @@ export class SeamHooks {
}
}
- /** Warn-severity `responseRewrite` hooks, evaluated against the delivered response. */
+ /** Warn-severity `responseRewrite` hooks, as a chain over the delivered response. */
async observeRewrite(view: ResponseView): Promise<void> {
const hooks = this.plan.observeRewriteHooks;
if (hooks.length === 0) return;
- await this.engine.run(
+ await this.engine.runChain(
"responseRewrite",
hooks,
- (_applicable, base) => this.scope.proxyContext(base, "responseRewrite", { response: view }),
- this.scope.meta
+ {
+ context: (_applicable, base) =>
+ this.scope.proxyContext(base, "responseRewrite", { response: view }),
+ },
+ this.scope.meta,
+ { initial: undefined }
);
}
@@ -215,56 +356,83 @@ export class SeamHooks {
}
/**
- * Run `responseEnd` over the final response and route its actions:
- * `injectSystemNote` to this Claude session's next request, `injectUserTurn`
- * and `annotateTurn` to the sink. Never rejects.
+ * Run the `responseEnd` hook chain over the final response, routing each
+ * step's actions at the step, in chain order: `injectSystemNote` to this
+ * Claude session's next request, `injectUserTurn` and `annotateTurn` to the
+ * sink. A later hook sees what the sink accepted in `ctx.prior`. Never rejects.
*/
async end(view: ResponseView, req: string): Promise<void> {
const hooks = this.plan.endHooks;
if (hooks.length === 0) return;
- const meta = this.scope.meta;
try {
- const run = await this.engine.run(
+ await this.engine.runChain(
"responseEnd",
hooks,
- (_applicable, base) => this.scope.proxyContext(base, "responseEnd", { response: view }),
- meta
- );
- for (const { hookId, action } of run.apply) {
- const base = { ...meta, event: "responseEnd" as const, hookId, action: action.type };
- switch (action.type) {
- case "injectSystemNote":
- if (this.scope.sessionId) {
- this.engine.queueNote(this.scope.sessionId, hookId, action.text);
- this.engine.journal({ ...base, decision: "queued", detail: "next request" });
- } else {
- this.engine.journal({ ...base, decision: "dropped", detail: "no_session" });
+ {
+ context: (_applicable, base) =>
+ this.scope.proxyContext(base, "responseEnd", { response: view }),
+ // NOT atomic, unlike the other appliers: routing an action is delivering it
+ // (a queued note, an inbox line), which cannot be taken back. So a throw is
+ // contained per action: that action is journaled `error` (`apply_failed`), the
+ // ones before it stay delivered and listed in `prior`, and the rest still go.
+ apply: (state, items) => {
+ const results: ActionResult<ResponseEndAction>[] = [];
+ const applied: PlannedAction<ResponseEndAction>[] = [];
+ for (const item of items) {
+ let r: ActionResult<ResponseEndAction> | null;
+ try {
+ r = this.route(item, req);
+ } catch (err) {
+ this.engine.journal({
+ ...this.scope.meta,
+ event: "responseEnd",
+ hookId: item.hookId,
+ action: item.action.type,
+ decision: "error",
+ detail: `apply_failed:${err instanceof Error ? err.message : String(err)}`,
+ });
+ continue;
+ }
+ if (!r) continue;
+ results.push(r);
+ if (r.decision === "queued") applied.push(item);
}
- break;
- case "injectUserTurn": {
- const outcome = this.sink.inject(req, hookId, action.text);
- this.engine.journal({
- ...base,
- decision: outcome === "queued" ? "queued" : "dropped",
- ...(outcome === "queued" ? {} : { detail: outcome }),
- });
- break;
- }
- case "annotateTurn": {
- const outcome = this.sink.annotate(req, hookId, action.key, action.value);
- this.engine.journal({
- ...base,
- decision: outcome === "queued" ? "queued" : "dropped",
- ...(outcome === "queued" ? {} : { detail: outcome }),
- });
- break;
- }
- default:
- break;
- }
- }
+ return { state, results, applied };
+ },
+ },
+ this.scope.meta,
+ { initial: undefined }
+ );
} catch (err) {
log(`[hooks] responseEnd failed: ${err instanceof Error ? err.message : err}`);
}
}
+
+ /** Hand one `responseEnd` action on, and say what became of it. */
+ private route(
+ item: PlannedAction<ResponseEndAction>,
+ req: string
+ ): ActionResult<ResponseEndAction> | null {
+ const { hookId, action } = item;
+ switch (action.type) {
+ case "injectSystemNote":
+ if (!this.scope.sessionId) return { ...item, decision: "dropped", detail: "no_session" };
+ this.engine.queueNote(this.scope.sessionId, hookId, action.text);
+ return { ...item, decision: "queued", detail: "next request" };
+ case "injectUserTurn": {
+ const outcome = this.sink.inject(req, hookId, action.text);
+ return outcome === "queued"
+ ? { ...item, decision: "queued" }
+ : { ...item, decision: "dropped", detail: outcome };
+ }
+ case "annotateTurn": {
+ const outcome = this.sink.annotate(req, hookId, action.key, action.value);
+ return outcome === "queued"
+ ? { ...item, decision: "queued" }
+ : { ...item, decision: "dropped", detail: outcome };
+ }
+ default:
+ return null;
+ }
+ }
}
diff --git a/packages/cli/src/hooks/test-helpers/capture-child.ts b/packages/cli/src/hooks/test-helpers/capture-child.ts
index a748fa48..714324a1 100644
--- a/packages/cli/src/hooks/test-helpers/capture-child.ts
+++ b/packages/cli/src/hooks/test-helpers/capture-child.ts
@@ -40,11 +40,12 @@ const engine = new HookEngine({
drainTelemetryOutbox: false,
});
const route = { modelId: "m", provider: "p", native: false };
-const result = await engine.run(
+const result = await engine.runChain(
"request",
engine.select("request", { route }),
- (_a, base) => ({ ...base, event: "request", route }),
- { model: "m", provider: "p" }
+ { context: (_a, base) => ({ ...base, event: "request", route }) },
+ { model: "m", provider: "p" },
+ { initial: undefined }
);
// Let timers the hooks scheduled fire, and the logger's interval flush run.