Skip to content

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

feat(hooks)!: replace applyRequest with the hook request stage

Jack Rudenkodfa70e5f9fbd
diff --git a/packages/cli/src/behavior/engine.ts b/packages/cli/src/behavior/engine.ts
index ccfdbaa1..8790bd6c 100644
--- a/packages/cli/src/behavior/engine.ts
+++ b/packages/cli/src/behavior/engine.ts
@@ -12,6 +12,7 @@
* cannot read each other's plan file path.
*/
+import { detectHarnessFacts, extractAvailableSkills, extractSessionId } from "../hooks/harness.js";
import {
type Decision,
type Surface,
@@ -27,7 +28,6 @@ import {
} from "../hooks/telemetry/aggregate.js";
import { log } from "../logger.js";
import { resolveSeverity } from "./config.js";
-import { detectHarnessFacts, extractAvailableSkills, extractSessionId } from "./harness.js";
import type {
BehaviorConfig,
BehaviorContext,
diff --git a/packages/cli/src/behavior/index.ts b/packages/cli/src/behavior/index.ts
index 70e83260..4931b567 100644
--- a/packages/cli/src/behavior/index.ts
+++ b/packages/cli/src/behavior/index.ts
@@ -13,7 +13,7 @@ import type { BehaviorRule } from "./types.js";
export { BehaviorEngine, BehaviorSession } from "./engine.js";
export { parseBehaviorConfig, resolveSeverity } from "./config.js";
-export { detectHarnessFacts } from "./harness.js";
+export { detectHarnessFacts } from "../hooks/harness.js";
export { loadHookRules } from "./hooks.js";
export { buildDigest } from "./observer/digest.js";
export type { ObserverDigest } from "./observer/digest.js";
diff --git a/packages/cli/src/behavior/types.ts b/packages/cli/src/behavior/types.ts
index bccdbb33..e1c9c1b2 100644
--- a/packages/cli/src/behavior/types.ts
+++ b/packages/cli/src/behavior/types.ts
@@ -55,7 +55,7 @@ export interface HarnessFacts {
* Empty means "no listing found", NOT "the user has no skills" — a rule must
* not conclude anything from an empty list.
*/
- skills?: AvailableSkill[];
+ skills?: ReadonlyArray<AvailableSkill>;
}
/** A skill Claude Code offered the model. */
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index e358d61d..81e9c788 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -1846,7 +1846,8 @@ async function probeModelRouting(
false,
process.env.ANTHROPIC_API_KEY,
undefined,
- { quiet: true }
+ // Hooks never see --probe traffic.
+ { quiet: true, hooks: false }
);
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
@@ -1957,7 +1958,8 @@ async function probeModelRouting(
false,
process.env.ANTHROPIC_API_KEY,
undefined,
- { quiet: true }
+ // Hooks never see --probe traffic.
+ { quiet: true, hooks: false }
);
updateStep("Starting probe proxy", "done");
} catch {
diff --git a/packages/cli/src/handlers/advisor-decorator.ts b/packages/cli/src/handlers/advisor-decorator.ts
index 7aa5c8a5..9568bb0b 100644
--- a/packages/cli/src/handlers/advisor-decorator.ts
+++ b/packages/cli/src/handlers/advisor-decorator.ts
@@ -45,7 +45,7 @@ import type { Context } from "hono";
// The HARNESS extractSessionId: takes the whole request and reads
// `metadata.user_id`'s JSON `session_id`. NOT the same-named function in
// session-events/index.ts, which takes the metadata object instead.
-import { extractSessionId } from "../behavior/harness.js";
+import { extractSessionId } from "../hooks/harness.js";
import { log, logStderr } from "../logger.js";
import {
type AdvisorApiKeys,
diff --git a/packages/cli/src/handlers/composed-handler-behavior-order.test.ts b/packages/cli/src/handlers/composed-handler-behavior-order.test.ts
deleted file mode 100644
index 0b597b1d..00000000
--- a/packages/cli/src/handlers/composed-handler-behavior-order.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { beforeEach, describe, expect, it } from "bun:test";
-import { OpenAIAPIFormat } from "../adapters/openai-api-format.js";
-import { resetBehaviorEngine } from "../behavior/index.js";
-import type { ProviderTransport } from "../providers/transport/types.js";
-import { ComposedHandler } from "./composed-handler.js";
-
-interface CapturedBuildInput {
- messages: any[];
- tools: any[];
- system: any;
-}
-
-class RecordingOpenAIAPIFormat extends OpenAIAPIFormat {
- captured?: CapturedBuildInput;
-
- override buildPayload(claudeRequest: any, messages: any[], tools: any[]): any {
- this.captured = JSON.parse(JSON.stringify({ messages, tools, system: claudeRequest.system }));
- return super.buildPayload(claudeRequest, messages, tools);
- }
-}
-
-function makeFakeTransport(): ProviderTransport {
- return {
- name: "test-provider",
- displayName: "Test",
- streamFormat: "openai-sse",
- getEndpoint: () => "http://127.0.0.1:1/",
- getHeaders: () => ({}),
- } as unknown as ProviderTransport;
-}
-
-function makePayload(model: string): any {
- return {
- model,
- max_tokens: 16,
- messages: [
- {
- role: "user",
- content:
- "No plan file exists yet. You should create your plan at /tmp/behavior-order-test/assigned-plan.md using the Write tool.",
- },
- ],
- tools: [
- {
- name: "ExitPlanMode",
- description: "Exit plan mode after writing the plan.",
- input_schema: { type: "object", properties: {} },
- },
- ],
- };
-}
-
-function exitPlanModeDescription(adapter: RecordingOpenAIAPIFormat): string {
- const tool = adapter.captured?.tools.find(
- (candidate: any) => (candidate.function ?? candidate).name === "ExitPlanMode"
- );
- return (tool?.function ?? tool)?.description ?? "";
-}
-
-async function captureBuildInput(model: string): Promise<RecordingOpenAIAPIFormat> {
- const adapter = new RecordingOpenAIAPIFormat(model);
- const handler = new ComposedHandler(makeFakeTransport(), model, model, 8080, { adapter });
- const context = {
- json: (body: any, status: number) => ({ body, status }),
- body: (...args: any[]) => ({ args }),
- } as any;
-
- try {
- await handler.handle(context, makePayload(model));
- } catch {
- // The fake transport deliberately points at an unroutable local endpoint.
- }
-
- return adapter;
-}
-
-describe("ComposedHandler behavior layer ordering", () => {
- beforeEach(() => {
- resetBehaviorEngine();
- });
-
- it("applies behavior mutations before adapter.buildPayload for foreign models", async () => {
- const adapter = await captureBuildInput("gpt-5.6-sol");
-
- // This can only be captured if behavior ran before buildPayload; moving the
- // call back after buildPayload must fail this regression test.
- expect(exitPlanModeDescription(adapter)).toContain("assigned-plan.md");
- });
-
- it("keeps behavior mutations off for native Claude models", async () => {
- const adapter = await captureBuildInput("claude-opus-4-8");
-
- expect(exitPlanModeDescription(adapter)).not.toContain("assigned-plan.md");
- });
-});
diff --git a/packages/cli/src/handlers/composed-handler-hooks.test.ts b/packages/cli/src/handlers/composed-handler-hooks.test.ts
new file mode 100644
index 00000000..237d46ec
--- /dev/null
+++ b/packages/cli/src/handlers/composed-handler-hooks.test.ts
@@ -0,0 +1,254 @@
+/**
+ * The hook request stage inside ComposedHandler, driven through `withHooks`
+ * with a fake ProviderTransport. Ported from the behavior-layer ordering test
+ * (mutation before `buildPayload` for foreign models, none for `claude-*`),
+ * plus the cases the hook system adds: `summarizeTools`, `forceForeignModel`,
+ * the session-context note reaching a chat-completions payload, and attempt
+ * isolation on one context.
+ */
+
+import { describe, expect, it } from "bun:test";
+import { OpenAIAPIFormat } from "../adapters/openai-api-format.js";
+import { BUILTIN_HOOKS } from "../hooks/builtins/index.js";
+import { planFileInstruction } from "../hooks/builtins/plan-mode.js";
+import { SESSION_CONTEXT_NOTE } from "../hooks/builtins/session-context.js";
+import { HookEngine } from "../hooks/engine.js";
+import type { JournalEntry } from "../hooks/journal.js";
+import { type HookDefinition, act } from "../hooks/public.js";
+import { HookRegistry, type UserHookInput } from "../hooks/registry.js";
+import { withHooks } from "../hooks/response-seam.js";
+import type { ProviderTransport } from "../providers/transport/types.js";
+import { ComposedHandler, type ComposedHandlerOptions } from "./composed-handler.js";
+
+const PLAN_PATH = "/tmp/behavior-order-test/assigned-plan.md";
+
+interface CapturedBuildInput {
+ messages: any[];
+ tools: any[];
+ system: any;
+ built: any;
+}
+
+class RecordingOpenAIAPIFormat extends OpenAIAPIFormat {
+ captured: CapturedBuildInput[] = [];
+
+ override buildPayload(claudeRequest: any, messages: any[], tools: any[]): any {
+ const built = super.buildPayload(claudeRequest, messages, tools);
+ this.captured.push(
+ JSON.parse(JSON.stringify({ messages, tools, system: claudeRequest.system, built }))
+ );
+ return built;
+ }
+
+ get last(): CapturedBuildInput | undefined {
+ return this.captured[this.captured.length - 1];
+ }
+}
+
+function makeFakeTransport(name = "test-provider"): ProviderTransport {
+ return {
+ name,
+ displayName: "Test",
+ streamFormat: "openai-sse",
+ getEndpoint: () => "http://127.0.0.1:1/",
+ getHeaders: () => ({}),
+ } as unknown as ProviderTransport;
+}
+
+const EXIT_PLAN_MODE_DESCRIPTION =
+ "Exit plan mode after writing the plan. This second sentence is what --summarize-tools drops, and it is long enough to matter.";
+
+function makePayload(model: string, overrides: Record<string, unknown> = {}): any {
+ return {
+ model,
+ max_tokens: 16,
+ messages: [
+ {
+ role: "user",
+ content: `No plan file exists yet. You should create your plan at ${PLAN_PATH} using the Write tool.`,
+ },
+ ],
+ tools: [
+ {
+ name: "ExitPlanMode",
+ description: EXIT_PLAN_MODE_DESCRIPTION,
+ input_schema: { type: "object", properties: {} },
+ },
+ ],
+ ...overrides,
+ };
+}
+
+function fakeContext(): any {
+ const vars = new Map<string, unknown>();
+ return {
+ json: (body: any, status: number) => ({ body, status, ok: false }),
+ body: (...args: any[]) => ({ args }),
+ get: (k: string) => vars.get(k),
+ set: (k: string, v: unknown) => vars.set(k, v),
+ };
+}
+
+function engineWith(users: UserHookInput[] = []) {
+ const journal: JournalEntry[] = [];
+ const engine = new HookEngine({
+ registry: new HookRegistry(BUILTIN_HOOKS, users, undefined),
+ config: {},
+ hostMode: "other",
+ journalSink: (e) => journal.push(e),
+ warn: () => {},
+ drainTelemetryOutbox: false,
+ });
+ return { engine, journal };
+}
+
+async function handleOnce(
+ handler: ComposedHandler,
+ engine: HookEngine,
+ payload: any,
+ c: any = fakeContext()
+): Promise<void> {
+ try {
+ await withHooks(handler, engine).handle(c, payload);
+ } catch {
+ // The fake transport deliberately points at an unroutable local endpoint.
+ }
+}
+
+async function captureBuildInput(
+ model: string,
+ opts: {
+ options?: ComposedHandlerOptions;
+ payload?: any;
+ withHooks?: boolean;
+ provider?: string;
+ } = {}
+): Promise<RecordingOpenAIAPIFormat> {
+ const adapter = new RecordingOpenAIAPIFormat(model);
+ const handler = new ComposedHandler(makeFakeTransport(opts.provider), model, model, 8080, {
+ adapter,
+ ...opts.options,
+ });
+ const payload = opts.payload ?? makePayload(model);
+ if (opts.withHooks === false) {
+ try {
+ await handler.handle(fakeContext(), payload);
+ } catch {
+ // unroutable endpoint, as above
+ }
+ } else {
+ await handleOnce(handler, engineWith().engine, payload);
+ }
+ return adapter;
+}
+
+function exitPlanModeDescription(adapter: RecordingOpenAIAPIFormat): string {
+ const tool = adapter.last?.tools.find(
+ (candidate: any) => (candidate.function ?? candidate).name === "ExitPlanMode"
+ );
+ return (tool?.function ?? tool)?.description ?? "";
+}
+
+function userHook(id: string, def: Omit<HookDefinition, "apiVersion" | "id">) {
+ return {
+ id: `hook:m/${id}`,
+ module: "/hooks/m.ts",
+ moduleIndex: 0,
+ exportIndex: 0,
+ def: { apiVersion: 1, id, ...def } as HookDefinition,
+ } satisfies UserHookInput;
+}
+
+describe("ComposedHandler hook request stage ordering", () => {
+ it("applies hook mutations before adapter.buildPayload for foreign models", async () => {
+ const adapter = await captureBuildInput("gpt-5.6-sol");
+
+ // This can only be captured if the request stage ran before buildPayload;
+ // moving it after buildPayload must fail this regression test.
+ expect(exitPlanModeDescription(adapter)).toContain("assigned-plan.md");
+ });
+
+ it("keeps foreign-scoped built-ins off for native Claude models", async () => {
+ const adapter = await captureBuildInput("claude-opus-4-8");
+
+ expect(exitPlanModeDescription(adapter)).not.toContain("assigned-plan.md");
+ });
+
+ it("keeps them off for the anthropic provider whatever the model is called", async () => {
+ const adapter = await captureBuildInput("glm-5", { provider: "anthropic" });
+
+ expect(exitPlanModeDescription(adapter)).not.toContain("assigned-plan.md");
+ });
+
+ it("runs no hooks without withHooks on the context (classifier passthrough, tests)", async () => {
+ const adapter = await captureBuildInput("gpt-5.6-sol", { withHooks: false });
+
+ expect(adapter.last).toBeDefined();
+ expect(exitPlanModeDescription(adapter)).not.toContain("assigned-plan.md");
+ });
+
+ it("forceForeignModel makes a claude-* uid foreign, so plan mode is armed", async () => {
+ const forced = await captureBuildInput("claude-sonnet-5-medium", {
+ options: { forceForeignModel: true },
+ });
+ const control = await captureBuildInput("claude-sonnet-5-medium");
+
+ expect(exitPlanModeDescription(forced)).toContain("assigned-plan.md");
+ expect(exitPlanModeDescription(control)).not.toContain("assigned-plan.md");
+ });
+
+ it("summarizeTools keeps the full plan-mode append on the converted tool", async () => {
+ const adapter = await captureBuildInput("gpt-5.6-sol", { options: { summarizeTools: true } });
+ const description = exitPlanModeDescription(adapter);
+
+ // Summarised to the first sentence…
+ expect(description.startsWith("Exit plan mode after writing the plan.")).toBe(true);
+ expect(description).not.toContain("second sentence");
+ // …and the whole instruction appended after the cut.
+ expect(description.endsWith(planFileInstruction(PLAN_PATH))).toBe(true);
+ });
+
+ it("puts the session-context note inside the system message of the built chat-completions payload", async () => {
+ const adapter = await captureBuildInput("glm-5", {
+ payload: makePayload("glm-5", {
+ system: "Base prompt. SessionStart hook additional context: x",
+ }),
+ });
+ const built = adapter.last?.built;
+ const systemMessage = built?.messages?.find((m: any) => m.role === "system");
+
+ expect(typeof systemMessage?.content).toBe("string");
+ expect(systemMessage.content).toContain(SESSION_CONTEXT_NOTE);
+ expect(JSON.stringify(built)).toContain(SESSION_CONTEXT_NOTE);
+ });
+
+ it("a second attempt on the same context does not carry the first attempt's injected note", async () => {
+ let attempt = 0;
+ const { engine } = engineWith([
+ userHook("count", { on: { request: () => [act.injectSystemNote(`ATTEMPT-${++attempt}`)] } }),
+ ]);
+ const adapter = new RecordingOpenAIAPIFormat("glm-5");
+ const handler = new ComposedHandler(makeFakeTransport(), "glm-5", "glm-5", 8080, { adapter });
+ const c = fakeContext();
+ const payload = makePayload("glm-5", { system: "base" });
+ await handleOnce(handler, engine, payload, c);
+ await handleOnce(handler, engine, payload, c);
+
+ expect(adapter.captured).toHaveLength(2);
+ expect(adapter.captured[0]?.system).toBe("base\n\nATTEMPT-1");
+ expect(adapter.captured[1]?.system).toBe("base\n\nATTEMPT-2");
+ // The inbound payload is never touched.
+ expect(payload.system).toBe("base");
+ });
+
+ it("user stage-A actions reach the converted messages", async () => {
+ const { engine } = engineWith([
+ userHook("append", { on: { request: () => [act.appendUserText("APPENDED-BY-HOOK")] } }),
+ ]);
+ const adapter = new RecordingOpenAIAPIFormat("glm-5");
+ const handler = new ComposedHandler(makeFakeTransport(), "glm-5", "glm-5", 8080, { adapter });
+ await handleOnce(handler, engine, makePayload("glm-5"));
+
+ expect(JSON.stringify(adapter.last?.built.messages)).toContain("APPENDED-BY-HOOK");
+ });
+});
diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.ts
index 427282a4..a9614525 100644
--- a/packages/cli/src/handlers/composed-handler.ts
+++ b/packages/cli/src/handlers/composed-handler.ts
@@ -7,17 +7,23 @@
*
* Flow:
* 1. transformOpenAIToClaude(payload) — normalize incoming request
+ * 1a. hook request stage A — system / message / tool-set actions
* 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
* 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
* 7. stream parser by provider.streamFormat — response → Claude SSE
*
- * Step 3b must stay ahead of step 4: buildPayload does not reliably alias
- * `messages`/`tools`, so hooks that run after it are silently discarded on the
- * Codex/Responses path.
+ * Steps 3a and 3b must stay ahead of step 4: buildPayload does not reliably
+ * alias `messages`/`tools`, so anything that runs after it is silently
+ * discarded on the Codex/Responses path. Stage A runs BEFORE conversion so a
+ * system note reaches chat-completions routes, whose payload is built from the
+ * converted `messages` alone; stage B runs AFTER `convertTools` so
+ * `summarizeTools` can never cut a description append. The hook stages run only
+ * when `withHooks` (hooks/response-seam.ts) put the request hooks on the context.
*/
import type { Context } from "hono";
@@ -35,8 +41,7 @@ import { lookupModelAcceptsImages, lookupModelForProvider } from "../adapters/mo
import 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 type { BehaviorEngine, BehaviorSession } from "../behavior/index.js";
-import { getBehaviorEngine } from "../behavior/index.js";
+import { type HookRequestScope, isNativeRoute, requestHooksOf } from "../hooks/request-stage.js";
import {
getLogLevel,
log,
@@ -181,7 +186,8 @@ export interface ComposedHandlerOptions {
/** Whether the current session is interactive (gates consent prompt). */
isInteractive?: boolean;
/**
- * Force the Layer 4 behavior supervisor ON regardless of the model's name.
+ * Treat this route as FOREIGN for hooks (`RouteInfo.native` false) regardless
+ * of the model's name, so foreign-scoped built-in hooks stay armed.
*
* The default rule reads `claude-*` as "native Claude, already follows these
* conventions" — a naming rule that holds for models reached through
@@ -247,7 +253,6 @@ export class ComposedHandler implements ModelHandler {
/** Model-specific adapter (GLM, Grok, etc.) — handles model quirks independent of provider */
private modelAdapter?: BaseModelAdapter;
private middlewareManager: MiddlewareManager;
- private behaviorEngine: BehaviorEngine;
private tokenTracker: TokenTracker;
/** Full routed model string (e.g. "[email protected]"). Used for provider routing and display echo. */
private targetModel: string;
@@ -369,11 +374,6 @@ export class ComposedHandler implements ModelHandler {
.initialize()
.catch((err) => log(`[ComposedHandler:${this.bareModelName}] Middleware init error: ${err}`));
- // Layer 4: harness-convention conformance. The engine is stateless and
- // process-wide; per-request state lives on the session created in handle(),
- // because this handler is cached per model and can serve overlapping requests.
- this.behaviorEngine = getBehaviorEngine();
-
// `--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
@@ -400,6 +400,19 @@ export class ComposedHandler implements ModelHandler {
});
}
+ /**
+ * The route hooks are scoped by. `native` is the exact rule the plan-mode
+ * supervisor has always used: `claude-*` names and the `anthropic` provider,
+ * unless the provider profile sets `forceForeignModel`.
+ */
+ private routeInfo(): { modelId: string; provider: string; native: boolean } {
+ return {
+ modelId: this.bareModelName,
+ provider: this.provider.name,
+ native: isNativeRoute(this.bareModelName, this.provider.name, this.options.forceForeignModel),
+ };
+ }
+
/** Provider adapter — handles transport format (messages, tools, payload) */
private getAdapter(): BaseModelAdapter {
return this.explicitAdapter || this.resolvedDialect;
@@ -1045,6 +1058,21 @@ export class ComposedHandler implements ModelHandler {
// 1. Transform incoming Claude-format request
const { claudeRequest, droppedParams } = transformOpenAIToClaude(payload);
+ // 1a. Hook request stage A, on this attempt's own deep copy (each
+ // FallbackHandler candidate gets a fresh one, so nothing leaks between
+ // attempts). Before conversion, so a system note reaches every route:
+ // chat-completions adapters copy `system` into messages[0] at step 2 and
+ // build their payload from `messages` alone.
+ const hooks = requestHooksOf(c);
+ const hookScope: HookRequestScope | undefined = hooks
+ ? await hooks.beginAttempt(c, {
+ claudeRequest,
+ route: this.routeInfo(),
+ model: typeof payload?.model === "string" ? payload.model : this.bareModelName,
+ stream: payload?.stream === true,
+ })
+ : undefined;
+
// 2. Get adapter and reset state
const adapter = this.getAdapter();
if (typeof adapter.reset === "function") adapter.reset();
@@ -1172,6 +1200,15 @@ export class ComposedHandler implements ModelHandler {
}
}
+ // 3a. Hook request stage B: tool-description actions, on the Claude-format
+ // tools AND the converted ones, after convertTools (so `summarizeTools`,
+ // 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
+ // closed actions produced.
+ hookScope?.applyToolDescriptions(claudeRequest.tools ?? [], tools);
+
// 3b. Middleware before request.
//
// MUST run before buildPayload. buildPayload is not guaranteed to keep a
@@ -1193,28 +1230,6 @@ export class ComposedHandler implements ModelHandler {
claudeTools: claudeRequest.tools ?? [],
});
- // 3c. Layer 4 — harness-convention conformance. Session is per-request so
- // two concurrent turns on this cached handler cannot share detected state.
- const behaviorSession = this.behaviorEngine.startSession({
- modelId: this.bareModelName,
- providerName: this.provider.name,
- // A naming rule, not a pinned model list: Claude models are `claude-*`, and
- // they already follow these conventions (measured 87/87 on plan mode).
- //
- // `forceForeignModel` is the one escape hatch, and it exists because the
- // name is not always evidence: a subscription aggregator can serve uids
- // like `claude-sonnet-5-medium` that match this test while being reached
- // over a foreign protocol, where the 87/87 measurement says nothing. The
- // flag is opt-in per provider profile, so the global rule — and every
- // other provider's behaviour — is unchanged.
- isNativeAnthropic:
- !this.options.forceForeignModel &&
- (/^claude[-.]/i.test(this.bareModelName) || this.provider.name === "anthropic"),
- });
- if (!behaviorSession.isNoop) {
- behaviorSession.applyRequest(claudeRequest, claudeRequest.tools ?? [], tools, messages);
- }
-
// 4. Build request payload
let requestPayload = adapter.buildPayload(claudeRequest, messages, tools);
@@ -2416,11 +2431,12 @@ export class ComposedHandler implements ModelHandler {
// Stats must never crash claudish
}
try {
- // Layer 4 turn denominator. getInputTokens() is the FULL conversation
- // context for this request (assignment, not accumulation — see the
- // context-tracking note in CLAUDE.md), which is exactly the figure the
- // context bucket wants. No-op unless behaviour telemetry is opted in.
- behaviorSession?.noteTurnComplete(this.tokenTracker.getInputTokens());
+ // Hook telemetry's turn denominator. getInputTokens() is the FULL
+ // conversation context for this request (assignment, not accumulation
+ // — see the context-tracking note in CLAUDE.md), which is exactly the
+ // figure the context bucket wants. No-op unless behaviour telemetry is
+ // opted in.
+ hookScope?.noteTurnComplete(this.tokenTracker.getInputTokens());
} catch {
// Telemetry must never crash claudish
}
@@ -2435,8 +2451,7 @@ export class ComposedHandler implements ModelHandler {
onStreamComplete,
(code, message) => {
streamApiError = { code, message };
- },
- behaviorSession
+ }
);
// A client that did not ask for a stream gets the single JSON message the
@@ -2682,8 +2697,7 @@ export class ComposedHandler implements ModelHandler {
claudeRequest: any,
toolNameMap?: Map<string, string>,
onComplete?: () => void,
- onApiError?: (code: string, message: string) => void,
- behaviorSession?: BehaviorSession
+ onApiError?: (code: string, message: string) => void
): Response {
// Local mutable copy so we can null it out after firing (prevents double-firing)
// without reassigning the function parameter.
@@ -2733,18 +2747,16 @@ export class ComposedHandler implements ModelHandler {
const priorInputTokens = this.tokenTracker.getLastInputTokens();
/**
- * The ONE place a completed tool call is observed, for both consumers.
+ * The ONE place a completed tool call is observed. Tool counting feeds the
+ * end-of-session summary, which must work for every model on every wire, so
+ * every parser below gets it unconditionally.
*
- * It deliberately does NOT depend on `behaviorSession`. Tool counting feeds the
- * end-of-session summary, which must work for every model on every wire — including
- * native Claude and any run with the behaviour layer switched off, where
- * `behaviorSession` is undefined. Gating the count on it (as the four call sites
- * below each used to) would have made the summary silently report zero tools for
- * exactly those sessions.
+ * The parsers' behavior plumbing (tool buffering, argument repair, output
+ * observation) is no longer passed: tool interception moves to the hook
+ * response seam, above every parser.
*/
const observeToolCall = (name: string): void => {
this.tokenTracker.recordToolUse(name);
- behaviorSession?.observeToolCall(name);
};
switch (streamFormat) {
@@ -2759,18 +2771,10 @@ export class ComposedHandler implements ModelHandler {
claudeRequest.tools,
toolNameMap,
priorInputTokens,
- // Always pass the options object, never `behaviorSession && {…}`. The
- // optional-chained hooks below already no-op without a session, and the
- // conditional form meant `onToolCallObserved` was not even installed on the
- // busiest wire in claudish (GLM, Kimi, Grok, DeepSeek, Qwen, OpenRouter,
- // LiteLLM) whenever the behaviour layer was off.
- {
- shouldBufferTool: (name) => behaviorSession?.interceptsTool(name) ?? false,
- onToolCall: (name, argsJson) => behaviorSession?.repairToolCall(name, argsJson) ?? null,
- onAssistantText: (text, kind) => behaviorSession?.observeText(text, kind),
- onToolCallObserved: observeToolCall,
- onTurnEnd: () => behaviorSession?.finishTurn(),
- }
+ // Always pass the options object: without it `onToolCallObserved` is not
+ // installed on the busiest wire in claudish (GLM, Kimi, Grok, DeepSeek,
+ // Qwen, OpenRouter, LiteLLM).
+ { onToolCallObserved: observeToolCall }
);
case "openai-responses-sse":
@@ -2786,11 +2790,7 @@ export class ComposedHandler implements ModelHandler {
onApiError,
priorInputTokens,
middlewareManager: this.middlewareManager,
- shouldBufferTool: (name) => behaviorSession?.interceptsTool(name) ?? false,
- onToolCall: (name, argsJson) => behaviorSession?.repairToolCall(name, argsJson) ?? null,
- onAssistantText: (text, kind) => behaviorSession?.observeText(text, kind),
onToolCallObserved: observeToolCall,
- onTurnEnd: () => behaviorSession?.finishTurn(),
});
case "anthropic-sse":
@@ -2808,12 +2808,7 @@ export class ComposedHandler implements ModelHandler {
// do the same to the base's wire-keyed `true` for every other model
// on this wire (qtoken@'s qwen / glm / deepseek models).
adapter: (this.modelAdapter ?? adapter) as BaseAPIFormat,
- shouldBufferTool: (name) => behaviorSession?.interceptsTool(name) ?? false,
- repairToolArgs: (name, argsJson) =>
- behaviorSession?.repairToolCall(name, argsJson) ?? null,
- onAssistantText: (text, kind) => behaviorSession?.observeText(text, kind),
onToolCallObserved: observeToolCall,
- onTurnEnd: () => behaviorSession?.finishTurn(),
});
case "gemini-sse": {
@@ -2829,11 +2824,7 @@ export class ComposedHandler implements ModelHandler {
middlewareManager: this.middlewareManager,
onTokenUpdate,
onToolCall,
- repairToolArgs: (name, argsJson) =>
- behaviorSession?.repairToolCall(name, argsJson) ?? null,
- onAssistantText: (text, kind) => behaviorSession?.observeText(text, kind),
onToolCallObserved: observeToolCall,
- onTurnEnd: () => behaviorSession?.finishTurn(),
unwrapResponse: this.options.unwrapGeminiResponse,
priorInputTokens,
});
@@ -2852,13 +2843,7 @@ export class ComposedHandler implements ModelHandler {
onServedModel: (uid) => {
if (uid !== this.bareModelName) this.tokenTracker.setActiveModelName(uid);
},
- // Layer 4 — the same hooks the gemini-sse case passes.
- repairToolArgs: (name, argsJson) =>
- behaviorSession?.repairToolCall(name, argsJson) ?? null,
- shouldBufferTool: (name) => behaviorSession?.interceptsTool(name) ?? false,
- onAssistantText: (text, kind) => behaviorSession?.observeText(text, kind),
onToolCallObserved: observeToolCall,
- onTurnEnd: () => behaviorSession?.finishTurn(),
});
case "ollama-jsonl":
diff --git a/packages/cli/src/handlers/native-handler-hooks.test.ts b/packages/cli/src/handlers/native-handler-hooks.test.ts
new file mode 100644
index 00000000..d049e026
--- /dev/null
+++ b/packages/cli/src/handlers/native-handler-hooks.test.ts
@@ -0,0 +1,135 @@
+/**
+ * The hook request stage inside NativeHandler: both stages at the top of
+ * handle(), on a copy-on-write view of the payload, only under `withHooks`.
+ */
+
+import { afterEach, describe, expect, it, spyOn } from "bun:test";
+import { BUILTIN_HOOKS } from "../hooks/builtins/index.js";
+import { HookEngine } from "../hooks/engine.js";
+import { type HookDefinition, type RouteInfo, act } from "../hooks/public.js";
+import { HookRegistry, type UserHookInput } from "../hooks/registry.js";
+import { withHooks } from "../hooks/response-seam.js";
+import { NativeHandler } from "./native-handler.js";
+
+let fetchSpy: ReturnType<typeof spyOn> | undefined;
+afterEach(() => {
+ fetchSpy?.mockRestore();
+ fetchSpy = undefined;
+});
+
+function captureFetch(): { bodies: any[] } {
+ const bodies: any[] = [];
+ fetchSpy = spyOn(globalThis, "fetch").mockImplementation((async (
+ _url: unknown,
+ init?: RequestInit
+ ) => {
+ bodies.push(JSON.parse(String(init?.body)));
+ return new Response(JSON.stringify({ type: "message", content: [] }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }) as typeof fetch);
+ return { bodies };
+}
+
+function fakeContext(): any {
+ const vars = new Map<string, unknown>();
+ return {
+ req: { header: () => ({ "x-api-key": "sk-test" }) },
+ json: (body: unknown, init?: { status?: number } | number) =>
+ new Response(JSON.stringify(body), {
+ status: typeof init === "number" ? init : (init?.status ?? 200),
+ }),
+ body: (stream: unknown, init?: ResponseInit) => new Response(stream as BodyInit, init),
+ get: (k: string) => vars.get(k),
+ set: (k: string, v: unknown) => vars.set(k, v),
+ };
+}
+
+function engineWith(users: UserHookInput[]) {
+ return new HookEngine({
+ registry: new HookRegistry(BUILTIN_HOOKS, users, undefined),
+ config: {},
+ hostMode: "other",
+ journalSink: () => {},
+ warn: () => {},
+ drainTelemetryOutbox: false,
+ });
+}
+
+function userHook(id: string, def: Omit<HookDefinition, "apiVersion" | "id">) {
+ return {
+ id: `hook:m/${id}`,
+ module: "/hooks/m.ts",
+ moduleIndex: 0,
+ exportIndex: 0,
+ def: { apiVersion: 1, id, ...def } as HookDefinition,
+ } satisfies UserHookInput;
+}
+
+function payload(): any {
+ return {
+ model: "claude-opus-4-8",
+ max_tokens: 16,
+ system: [{ type: "text", text: "SessionStart hook additional context: banner" }],
+ messages: [
+ {
+ role: "user",
+ content: "You should create your plan at /tmp/p/assigned.md using the Write tool.",
+ },
+ ],
+ tools: [{ name: "ExitPlanMode", description: "Exit.", input_schema: { type: "object" } }],
+ };
+}
+
+describe("NativeHandler request stage", () => {
+ it("applies native-scoped user actions on a copy-on-write view; the inbound payload is untouched", async () => {
+ const { bodies } = captureFetch();
+ let route: RouteInfo | undefined;
+ const engine = engineWith([
+ userHook("native", {
+ routes: "native",
+ on: {
+ request: (ctx) => {
+ route = ctx.route;
+ return [
+ act.injectSystemNote("NATIVE-NOTE"),
+ act.rewriteToolDescription("ExitPlanMode", " +DESC"),
+ ];
+ },
+ },
+ }),
+ ]);
+ const inbound = payload();
+ const snapshot = structuredClone(inbound);
+ const res = await withHooks(new NativeHandler("sk-x"), engine).handle(fakeContext(), inbound);
+
+ expect(res.status).toBe(200);
+ expect(route).toEqual({ modelId: "claude-opus-4-8", provider: "anthropic", native: true });
+ expect(bodies).toHaveLength(1);
+ expect(bodies[0].system).toEqual([
+ { type: "text", text: "SessionStart hook additional context: banner" },
+ { type: "text", text: "NATIVE-NOTE" },
+ ]);
+ expect(bodies[0].tools[0].description).toBe("Exit. +DESC");
+ // Copy-on-write: the object withAdvisor shares was never mutated.
+ expect(inbound).toEqual(snapshot);
+ });
+
+ it("the foreign-scoped built-ins never touch a native request", async () => {
+ const { bodies } = captureFetch();
+ const inbound = payload();
+ await withHooks(new NativeHandler("sk-x"), engineWith([])).handle(fakeContext(), inbound);
+
+ expect(bodies[0].system).toEqual(inbound.system);
+ expect(bodies[0].tools).toEqual(inbound.tools);
+ });
+
+ it("runs no hooks without withHooks", async () => {
+ const { bodies } = captureFetch();
+ const inbound = payload();
+ await new NativeHandler("sk-x").handle(fakeContext(), inbound);
+
+ expect(bodies[0]).toEqual(inbound);
+ });
+});
diff --git a/packages/cli/src/handlers/native-handler.ts b/packages/cli/src/handlers/native-handler.ts
index 88af45aa..c96f1905 100644
--- a/packages/cli/src/handlers/native-handler.ts
+++ b/packages/cli/src/handlers/native-handler.ts
@@ -1,5 +1,6 @@
import type { Context } from "hono";
import { credentials } from "../auth/credentials/authority.js";
+import { requestHooksOf } from "../hooks/request-stage.js";
import { log, maskCredential } from "../logger.js";
import { ADVISOR_SWAPPED_CONTEXT_KEY } from "./advisor-decorator.js";
import {
@@ -25,7 +26,14 @@ export class NativeHandler implements ModelHandler {
this.advisorCollector = advisorCollector;
}
- async handle(c: Context, payload: any): Promise<Response> {
+ async handle(c: Context, incoming: any): Promise<Response> {
+ // Hook request stages A and B, first, and only when `withHooks` put the
+ // request hooks on the context. A native request is never in a fallback
+ // chain, but its payload object is shared with `withAdvisor`, so the stages
+ // run on a copy-on-write VIEW: `system`, `messages` and `tools` are replaced
+ // on the view, never mutated in place. With no conversion there is one tool
+ // representation, so stage B applies to it alone.
+ const payload = await this.applyRequestHooks(c, incoming);
const originalHeaders = c.req.header();
const target = payload.model;
@@ -192,6 +200,28 @@ export class NativeHandler implements ModelHandler {
}
}
+ // biome-ignore lint/suspicious/noExplicitAny: the Messages API payload is untyped at this layer
+ private async applyRequestHooks(c: Context, payload: any): Promise<any> {
+ const hooks = requestHooksOf(c);
+ if (!hooks || !payload || typeof payload !== "object") return payload;
+ const view = { ...payload };
+ const model = typeof payload.model === "string" ? payload.model : "";
+ const scope = await hooks.beginAttempt(c, {
+ claudeRequest: view,
+ route: { modelId: model, provider: "anthropic", native: true },
+ model,
+ stream: payload.stream === true,
+ });
+ if (scope.hasToolDescriptionWork) {
+ // Stage B replaces ELEMENTS of the array it is given; this one may still
+ // be the shared payload's own. With no tools at all the actions are
+ // journaled `unknown_tool` and the payload keeps having no `tools`.
+ if (Array.isArray(view.tools)) view.tools = [...view.tools];
+ scope.applyToolDescriptions(Array.isArray(view.tools) ? view.tools : [], null);
+ }
+ return view;
+ }
+
async shutdown(): Promise<void> {
// No state to clean up
}
diff --git a/packages/cli/src/hooks/builtins/index.ts b/packages/cli/src/hooks/builtins/index.ts
new file mode 100644
index 00000000..cd09bc76
--- /dev/null
+++ b/packages/cli/src/hooks/builtins/index.ts
@@ -0,0 +1,14 @@
+/**
+ * The hooks claudish ships. Their ids carry no `hook:` prefix, so a user hook
+ * can never shadow one, and they keep the ids the behavior rules had, so
+ * existing severity keys (`plan-mode/*`, …) still address them.
+ *
+ * Order here is their effective order among built-ins of the same `order`
+ * bucket.
+ */
+
+import type { BuiltinHook } from "../registry.js";
+import { planModeHook } from "./plan-mode.js";
+import { sessionContextHook } from "./session-context.js";
+
+export const BUILTIN_HOOKS: ReadonlyArray<BuiltinHook> = [planModeHook, sessionContextHook];
diff --git a/packages/cli/src/hooks/builtins/plan-mode.test.ts b/packages/cli/src/hooks/builtins/plan-mode.test.ts
new file mode 100644
index 00000000..49efea96
--- /dev/null
+++ b/packages/cli/src/hooks/builtins/plan-mode.test.ts
@@ -0,0 +1,70 @@
+/**
+ * Ported from behavior/rules/plan-mode.test.ts (`planFilePathRule.onRequest`).
+ * The tool half (`onToolCall` → `on.toolCall`) is ported with the response seam.
+ */
+
+import { describe, expect, it } from "bun:test";
+import type { HarnessFacts, RequestContext } from "../public.js";
+import { BUILTIN_HOOKS } from "./index.js";
+import { PLAN_MODE_HOOK_ID, planModeHook, planModeRequest } from "./plan-mode.js";
+
+const assignedPath = "/workspace/.custom-plans/assigned-session.md";
+const planDir = "/workspace/.custom-plans";
+
+function requestContext(
+ overrides: { harness?: HarnessFacts; tools?: Array<{ name: string; description?: string }> } = {}
+): RequestContext {
+ return {
+ hookId: PLAN_MODE_HOOK_ID,
+ severity: "fix",
+ log: () => {},
+ signal: new AbortController().signal,
+ event: "request",
+ host: { mode: "other" },
+ route: { modelId: "gpt-5.6-codex", provider: "openai-codex", native: false },
+ request: {
+ model: "gpt-5.6-codex",
+ stream: true,
+ systemText: "",
+ messages: [],
+ tools: overrides.tools ?? [{ name: "ExitPlanMode", description: "Exit plan mode" }],
+ },
+ harness: overrides.harness ?? { planModeActive: true, planFilePath: assignedPath, planDir },
+ session: null,
+ };
+}
+
+describe("plan-mode/plan-file-path request handler", () => {
+ it("returns no actions when plan mode is inactive", () => {
+ expect(planModeRequest(requestContext({ harness: { planModeActive: false } }))).toEqual([]);
+ });
+
+ it("returns no actions when ExitPlanMode is not offered", () => {
+ const ctx = requestContext({ tools: [{ name: "Write", description: "Write a file" }] });
+
+ expect(planModeRequest(ctx)).toEqual([]);
+ });
+
+ it("appends the exact assigned path to the ExitPlanMode description", () => {
+ const actions = planModeRequest(requestContext());
+
+ expect(actions).toHaveLength(1);
+ const [action] = actions;
+ if (action?.type !== "rewriteToolDescription") {
+ throw new Error("expected rewriteToolDescription action");
+ }
+ expect(action.tool).toBe("ExitPlanMode");
+ expect(action.append).toContain(
+ `Your plan MUST be written to exactly this path:\n${assignedPath}`
+ );
+ });
+});
+
+describe("plan-mode built-in definition", () => {
+ it("keeps its id, defaults to fix, and is scoped to foreign routes", () => {
+ expect(planModeHook.id).toBe("plan-mode/plan-file-path");
+ expect(planModeHook.defaultSeverity).toBe("fix");
+ expect(planModeHook.routes).toBe("foreign");
+ expect(BUILTIN_HOOKS).toContain(planModeHook);
+ });
+});
diff --git a/packages/cli/src/hooks/builtins/plan-mode.ts b/packages/cli/src/hooks/builtins/plan-mode.ts
new file mode 100644
index 00000000..976a665d
--- /dev/null
+++ b/packages/cli/src/hooks/builtins/plan-mode.ts
@@ -0,0 +1,74 @@
+/**
+ * Built-in hook `plan-mode/plan-file-path` — the request half.
+ *
+ * Background (measured, not assumed). Claude Code 2.1.220's ExitPlanModeV2 takes
+ * NO plan parameter — its advertised schema is `{allowedPrompts?}` and the tool
+ * description says outright: "This tool does NOT take the plan content as a
+ * parameter - it will read the plan from the file you wrote". CC's
+ * `normalizeToolInput` injects `plan` from disk at the session's assigned path.
+ *
+ * So `ExitPlanMode({})` is CORRECT, and the real failure is upstream: the model
+ * writes its plan somewhere else. gpt-5.6-sol produced a complete 12.9 KB plan
+ * under a filename it invented; CC read the assigned path, found nothing, and
+ * returned `plan: null`. That downgrades the approval dialog from the rich form
+ * ("Here is Claude's plan" + `Yes, and bypass permissions` / `Yes, auto-accept
+ * edits` / `Yes, manually approve edits`) to a bare "Exit plan mode?" yes/no —
+ * and since the rich dialog is the only surface that offers permission
+ * elevation on exit, the session always falls back to manual approval.
+ *
+ * Across 115 recorded ExitPlanMode calls the discriminator was exact: sessions
+ * that wrote to the assigned path got the rich dialog 7/7, sessions that did not
+ * got the degraded one 17/17. Native Claude models were 87/87 correct, so this
+ * hook is scoped to foreign routes (`routes: "foreign"`, where nativeness is
+ * `RouteInfo.native`: `claude-*` names and the `anthropic` provider, unless the
+ * provider profile sets `forceForeignModel`).
+ *
+ * The request half rewrites the ExitPlanMode tool DESCRIPTION, because a tool
+ * description is re-read at the instant the model decides to call the tool,
+ * while the plan-mode reminder can sit ~180K tokens behind the current turn. The
+ * action is applied at stage B, after tool conversion, so `--summarize-tools`
+ * (first sentence, 150 characters) can never cut it.
+ *
+ * The tool half (redirecting a Write/Edit aimed at the plan directory onto the
+ * assigned path) needs the response seam's tool interception and is ported
+ * with it.
+ */
+
+import { type RequestAction, type RequestContext, act } from "../public.js";
+import type { BuiltinHook } from "../registry.js";
+
+export const PLAN_MODE_HOOK_ID = "plan-mode/plan-file-path";
+
+/** The text appended to the ExitPlanMode description. Unchanged from the behavior rule. */
+export function planFileInstruction(planFilePath: string): string {
+ return `
+
+## Plan file for THIS session
+Your plan MUST be written to exactly this path:
+${planFilePath}
+Do not invent a different filename, and do not derive one from the task. Claude Code reads only that exact path; a plan written anywhere else is invisible to it and the approval will show "No plan found".`;
+}
+
+/** The request handler, exported for unit tests. */
+export function planModeRequest(ctx: RequestContext): RequestAction[] {
+ const { planModeActive, planFilePath } = ctx.harness;
+ if (!planModeActive || !planFilePath) return [];
+
+ // Only speak up if the tool is actually on offer this turn.
+ if (!ctx.request.tools.some((t) => t?.name === "ExitPlanMode")) return [];
+
+ return [act.rewriteToolDescription("ExitPlanMode", planFileInstruction(planFilePath))];
+}
+
+export const planModeHook: BuiltinHook = {
+ apiVersion: 1,
+ id: PLAN_MODE_HOOK_ID,
+ description:
+ "Keep plan-mode writes on the plan file Claude Code assigned, and name that " +
+ "path in the ExitPlanMode description.",
+ defaultSeverity: "fix",
+ // Native Claude models are already 87/87 on this; running the hook for them
+ // would be pure risk with no upside.
+ routes: "foreign",
+ on: { request: planModeRequest },
+};
diff --git a/packages/cli/src/hooks/builtins/session-context.test.ts b/packages/cli/src/hooks/builtins/session-context.test.ts
new file mode 100644
index 00000000..869ee252
--- /dev/null
+++ b/packages/cli/src/hooks/builtins/session-context.test.ts
@@ -0,0 +1,94 @@
+/** Ported 1:1 from behavior/rules/session-context.test.ts. */
+
+import { describe, expect, it } from "bun:test";
+import type { RequestContext } from "../public.js";
+import { BUILTIN_HOOKS } from "./index.js";
+import {
+ SESSION_CONTEXT_HOOK_ID,
+ hasInjectedSessionContext,
+ sessionContextHook,
+ sessionContextRequest,
+} from "./session-context.js";
+
+const MARKER = "SessionStart hook additional context";
+
+function requestContext(systemText = "", messages: unknown[] = []): RequestContext {
+ return {
+ hookId: SESSION_CONTEXT_HOOK_ID,
+ severity: "fix",
+ log: () => {},
+ signal: new AbortController().signal,
+ event: "request",
+ host: { mode: "other" },
+ route: { modelId: "m", provider: "p", native: false },
+ request: {
+ model: "m",
+ stream: true,
+ systemText,
+ messages: messages as RequestContext["request"]["messages"],
+ tools: [],
+ },
+ harness: { planModeActive: false },
+ session: null,
+ };
+}
+
+describe("hasInjectedSessionContext", () => {
+ it("detects the marker in system text", () => {
+ expect(hasInjectedSessionContext(MARKER, [])).toBe(true);
+ });
+
+ it("detects the marker in the first message's string content", () => {
+ expect(hasInjectedSessionContext("", [{ content: MARKER }])).toBe(true);
+ });
+
+ it("detects the marker in a text content block in the first message", () => {
+ const messages = [{ content: [{ type: "text", text: MARKER }] }];
+
+ expect(hasInjectedSessionContext("", messages)).toBe(true);
+ });
+
+ it("returns false for ordinary and empty input", () => {
+ expect(hasInjectedSessionContext("You are a helpful assistant.", [])).toBe(false);
+ expect(hasInjectedSessionContext("", [])).toBe(false);
+ });
+
+ it("does not scan later messages", () => {
+ // Only messages[0] is scanned so the model's own earlier echo cannot re-arm the hook.
+ expect(
+ hasInjectedSessionContext("", [
+ { content: "An ordinary first message." },
+ { content: MARKER },
+ ])
+ ).toBe(false);
+ });
+
+ it("matches upper- and lower-case marker variants", () => {
+ expect(hasInjectedSessionContext("SESSIONSTART HOOK ADDITIONAL CONTEXT", [])).toBe(true);
+ expect(hasInjectedSessionContext("sessionstart hook additional context", [])).toBe(true);
+ });
+});
+
+describe("session-context/no-harness-echo", () => {
+ it("is scoped to foreign routes (was appliesTo: !isNativeAnthropic)", () => {
+ expect(sessionContextHook.routes).toBe("foreign");
+ expect(sessionContextHook.defaultSeverity).toBe("fix");
+ });
+
+ it("injects exactly one system note when context is present", () => {
+ const actions = sessionContextRequest(requestContext(MARKER));
+
+ expect(actions).toEqual([{ type: "injectSystemNote", text: expect.any(String) }]);
+ });
+
+ it("returns no actions when context is absent", () => {
+ expect(sessionContextRequest(requestContext("An ordinary system prompt."))).toEqual([]);
+ });
+});
+
+describe("BUILTIN_HOOKS", () => {
+ it("contains the session-context hook under its unchanged id", () => {
+ expect(BUILTIN_HOOKS).toContain(sessionContextHook);
+ expect(sessionContextHook.id).toBe("session-context/no-harness-echo");
+ });
+});
diff --git a/packages/cli/src/hooks/builtins/session-context.ts b/packages/cli/src/hooks/builtins/session-context.ts
new file mode 100644
index 00000000..a28f706e
--- /dev/null
+++ b/packages/cli/src/hooks/builtins/session-context.ts
@@ -0,0 +1,116 @@
+/**
+ * Built-in hook `session-context/no-harness-echo`: keep Claude Code's own
+ * session context OUT of the model's answer.
+ *
+ * Background (measured, not assumed). A `SessionStart` hook's stdout is NOT
+ * written to `claude -p`'s stdout — probed 2026-08-18 against CC 2.1.233 with a
+ * hook emitting a sentinel and a one-word prompt: stdout came back as exactly
+ * `"banana\n"`, sentinel absent from both stdout and stderr. So hook output
+ * reaches the model the only other way it can: as injected context the model
+ * READS.
+ *
+ * Which means a foreign model can decide it is content to reproduce. In team
+ * session team-20260815-115227, `response-01.md` (minimax-m3) and
+ * `response-04.md` (kimi-k3) both OPEN with the host session's SessionStart
+ * output — a "Coaching" block recommending `npx claudeup`, and an "Insight"
+ * block — instead of the requested deliverable. The blind judges penalised both
+ * in those words: "leaked harness boilerplate in deliverable", "irrelevant
+ * coaching preamble violates the requested structure". Two of six models, and
+ * it moved their scores.
+ *
+ * ## Why this is a hook and not a hermeticity fix
+ *
+ * The obvious fix — don't give children the host's hooks — has no lever:
+ *
+ * · Hooks MERGE across settings tiers. Probed 2026-08-18: a project-tier
+ * `SessionStart` hook still fired with `--settings '{"hooks":{}}'` layered
+ * above it, which is the highest (CLI-args) tier. A settings overlay cannot
+ * clear an inherited hook.
+ * · `--bare` does skip hooks, but also skips CLAUDE.md auto-discovery, plugin
+ * sync and auto-memory, and defers the MCP connection past `system/init`.
+ * Team children need their project context and MCP tools.
+ * · A clean `CLAUDE_CONFIG_DIR` loses the user's MCP servers and plugins for
+ * the same reason.
+ *
+ * So the context is going to arrive. What claudish can change is what the model
+ * DOES with it. Following the supervisor's design rule ("put the fact where the
+ * decision is made"), this states the convention in the system prompt, where
+ * the model decides how to open its answer. It is deliberately NOT a post-hoc
+ * filter on the response: there is no reliable way to tell "boilerplate the
+ * model echoed" from "the user's own words quoted legitimately", and a wrong
+ * strip would delete real content from a deliverable.
+ *
+ * The note is applied at stage A, BEFORE message conversion, so it reaches every
+ * route. The behavior rule appended it after `convertMessagesToOpenAI` had
+ * already copied the system prompt into `messages[0]`, and chat-completions
+ * adapters build their payload from `messages` alone, so on OpenRouter and the
+ * OpenAI chat wire it was silently dropped (decisions.md, 2026-10-09).
+ */
+
+import { type RequestAction, type RequestContext, act } from "../public.js";
+import type { BuiltinHook } from "../registry.js";
+
+export const SESSION_CONTEXT_HOOK_ID = "session-context/no-harness-echo";
+
+/**
+ * How Claude Code labels hook-injected context. Taken from CC 2.1.233's own
+ * wording; matched case-insensitively and loosely so a phrasing tweak degrades
+ * to "hook stands down", never to a false positive on user prose.
+ */
+const SESSION_CONTEXT_MARKERS = ["sessionstart hook additional context", "hook additional context"];
+
+/** Does this request actually carry injected session context? */
+export function hasInjectedSessionContext(
+ systemText: string,
+ messages: ReadonlyArray<unknown>
+): boolean {
+ const haystacks: string[] = [systemText ?? ""];
+
+ // CC may place the hook context in the first user turn rather than the system
+ // prompt, so check both — but only the FIRST message, because scanning a long
+ // conversation would match the model's own earlier echo and re-arm forever.
+ const first = Array.isArray(messages) ? messages[0] : undefined;
+ if (first && typeof first === "object") {
+ const content = (first as { content?: unknown }).content;
+ if (typeof content === "string") {
+ haystacks.push(content);
+ } else if (Array.isArray(content)) {
+ for (const block of content) {
+ const text = (block as { text?: unknown } | null)?.text;
+ if (typeof text === "string") haystacks.push(text);
+ }
+ }
+ }
+
+ return haystacks.some((h) => {
+ const lower = h.toLowerCase();
+ return SESSION_CONTEXT_MARKERS.some((m) => lower.includes(m));
+ });
+}
+
+export const SESSION_CONTEXT_NOTE =
+ "Operational context note. This session may include text injected by the harness " +
+ "itself — SessionStart hook output, coaching or insight blocks, tooling banners, " +
+ "status lines. That material is addressed to you, not to the user, and it is not " +
+ "part of the task. Never reproduce, summarise, or quote it in your answer, and never " +
+ "let it open your response. Begin your answer with the requested deliverable and " +
+ "nothing before it.";
+
+/** The request handler, exported for unit tests. */
+export function sessionContextRequest(ctx: RequestContext): RequestAction[] {
+ if (!hasInjectedSessionContext(ctx.request.systemText, ctx.request.messages)) return [];
+ return [act.injectSystemNote(SESSION_CONTEXT_NOTE)];
+}
+
+export const sessionContextHook: BuiltinHook = {
+ apiVersion: 1,
+ id: SESSION_CONTEXT_HOOK_ID,
+ description:
+ "Stop foreign models opening their answer with harness-injected session context " +
+ "(SessionStart hook output, coaching/insight blocks).",
+ defaultSeverity: "fix",
+ // Native Claude treats this context as operational already; the measured
+ // failures were foreign models only.
+ routes: "foreign",
+ on: { request: sessionContextRequest },
+};
diff --git a/packages/cli/src/behavior/harness.test.ts b/packages/cli/src/hooks/harness.test.ts
similarity index 100%
rename from packages/cli/src/behavior/harness.test.ts
rename to packages/cli/src/hooks/harness.test.ts
diff --git a/packages/cli/src/behavior/harness.ts b/packages/cli/src/hooks/harness.ts
similarity index 97%
rename from packages/cli/src/behavior/harness.ts
rename to packages/cli/src/hooks/harness.ts
index 25833272..5908dad4 100644
--- a/packages/cli/src/behavior/harness.ts
+++ b/packages/cli/src/hooks/harness.ts
@@ -7,9 +7,12 @@
* than a hunt through every rule.
*
* Anchors verified against the Claude Code 2.1.220 binary.
+ *
+ * Moved unchanged from the behavior layer (`behavior/harness.ts`); the hook
+ * request stage and the built-in hooks read it.
*/
-import type { HarnessFacts } from "./types.js";
+import type { HarnessFacts } from "./public.js";
/**
* Plan-file path anchors, in the three forms CC emits.
diff --git a/packages/cli/src/hooks/index.ts b/packages/cli/src/hooks/index.ts
new file mode 100644
index 00000000..0110acb4
--- /dev/null
+++ b/packages/cli/src/hooks/index.ts
@@ -0,0 +1,101 @@
+/**
+ * The hook engine of this process: loaded once, from the global config.
+ *
+ * `loadHooksOnce()` is one memoised promise per process. It reads `hooks` from
+ * the global config, reports a pre-hook-system `behavior` block and a project
+ * `hooks` key (both ignored), loads the user modules, and builds the registry
+ * (built-ins first) and the engine. Every failure degrades — a broken hook
+ * module or a malformed `hooks` block warns and is skipped; the promise never
+ * rejects, because claudish must always start.
+ *
+ * The host mode of the FIRST call wins: one process is one host. Callers:
+ * `createProxyServer` (awaited before any handler is built, so no handler sees a
+ * half-loaded registry) and the MCP server entry (started in the background
+ * right after protocol stdout is isolated).
+ */
+
+import { log } from "../logger.js";
+import { loadConfig } from "../profile-config.js";
+import { BUILTIN_HOOKS } from "./builtins/index.js";
+import {
+ type HooksConfig,
+ hooksConfigDir,
+ parseHooksConfig,
+ reportBehaviorBlock,
+ reportProjectHooks,
+} from "./config.js";
+import { HookEngine } from "./engine.js";
+import { loadUserHooks } from "./loader.js";
+import type { HostMode } from "./public.js";
+import { HookRegistry, type UserHookInput } from "./registry.js";
+
+let enginePromise: Promise<HookEngine> | null = null;
+let loadedEngine: HookEngine | null = null;
+
+export interface LoadHooksOptions {
+ /** This process's host. Default `"other"`. Only the first call's value is used. */
+ hostMode?: HostMode;
+}
+
+/** The process's hook engine, loaded on first call. Never rejects. */
+export function loadHooksOnce(opts: LoadHooksOptions = {}): Promise<HookEngine> {
+ if (!enginePromise) {
+ enginePromise = buildEngine(opts.hostMode ?? "other").then((engine) => {
+ loadedEngine = engine;
+ return engine;
+ });
+ }
+ return enginePromise;
+}
+
+/** The engine once `loadHooksOnce()` has resolved; null before. */
+export function getHookEngine(): HookEngine | null {
+ return loadedEngine;
+}
+
+/** Test seam: forget the memoised engine so the next call loads again. */
+export function resetHookEngineForTests(): void {
+ enginePromise = null;
+ loadedEngine = null;
+}
+
+async function buildEngine(hostMode: HostMode): Promise<HookEngine> {
+ let raw: { hooks?: unknown; behavior?: unknown } = {};
+ try {
+ raw = loadConfig();
+ } catch (err) {
+ log(`[hooks] config unreadable, built-in hooks only: ${errorText(err)}`);
+ }
+
+ const config: HooksConfig = parseHooksConfig(raw.hooks);
+ reportBehaviorBlock(raw.behavior);
+ reportProjectHooks();
+
+ let users: UserHookInput[] = [];
+ try {
+ const loaded = await loadUserHooks({
+ modules: config.modules,
+ configDir: hooksConfigDir(),
+ hostMode,
+ });
+ users = loaded.hooks;
+ } catch (err) {
+ // The loader reports per module and does not throw; this guards the
+ // promise contract against anything it did not anticipate.
+ log(`[hooks] user hook loading failed, built-in hooks only: ${errorText(err)}`);
+ }
+
+ const engine = new HookEngine({
+ registry: new HookRegistry(BUILTIN_HOOKS, users, config.severity),
+ config,
+ hostMode,
+ });
+ log(
+ `[hooks] engine ready (host ${hostMode}): ${BUILTIN_HOOKS.length} built-in, ${users.length} user hook(s)`
+ );
+ return engine;
+}
+
+function errorText(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
diff --git a/packages/cli/src/hooks/mcp-isolation.test.ts b/packages/cli/src/hooks/mcp-isolation.test.ts
new file mode 100644
index 00000000..e91cacc3
--- /dev/null
+++ b/packages/cli/src/hooks/mcp-isolation.test.ts
@@ -0,0 +1,208 @@
+/**
+ * X-9: the MCP server's protocol stdout, with hooks loaded.
+ *
+ * X-9 spawns the claudish entry with `--mcp` (from source, the hermetic suite
+ * does not build), a temp config naming one noisy hook module, and the debug
+ * log on, then speaks newline-delimited JSON-RPC over its stdio. The module
+ * writes through every stdout route, both from callbacks claudish's own I/O
+ * emits later (a `process.stdin` listener, a signal listener — unreachable by
+ * the hook scope) and from a timer it schedules at import (reachable).
+ * Nothing but JSON-RPC may reach stdout.
+ *
+ * Its positive control imports the same module in a bare `bun` process with no
+ * isolation and shows every marker on stdout, so X-9 can fail.
+ */
+
+import { afterEach, describe, expect, it } from "bun:test";
+import { readFileSync, readdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { serverEnv } from "../test-helpers/contract-mcp.js";
+import { type TempLayout, makeTempLayout, waitFor } from "../test-helpers/contract-records.js";
+
+const ENTRY = join(import.meta.dir, "..", "index.ts");
+const SUPPORTED = process.platform === "darwin" || process.platform === "linux";
+
+const NOISY_MODULE = `import { writeSync } from "node:fs";
+function leak(prefix) {
+ console.log(prefix + "-A");
+ process.stdout.write(prefix + "-B\\n");
+ writeSync(1, prefix + "-C\\n");
+ Bun.write(Bun.stdout, prefix + "-D\\n");
+}
+process.stdin.on("data", () => leak("LEAK"));
+process.on("SIGUSR2", () => leak("LEAK"));
+setTimeout(() => leak("SCOPED"), 0);
+export default { apiVersion: 1, id: "noisy", on: { request: () => [] } };
+`;
+
+const layouts: TempLayout[] = [];
+afterEach(() => {
+ for (const layout of layouts.splice(0)) layout.cleanup();
+});
+
+/** A line-buffered reader over a child's stream. */
+function lineReader(stream: ReadableStream<Uint8Array>) {
+ const state = { text: "", done: false };
+ void (async () => {
+ const decoder = new TextDecoder();
+ const reader = stream.getReader();
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ state.text += decoder.decode(value, { stream: true });
+ }
+ state.done = true;
+ })();
+ return state;
+}
+
+function debugLog(cwd: string): string {
+ try {
+ const dir = join(cwd, "logs");
+ return readdirSync(dir)
+ .map((f) => readFileSync(join(dir, f), "utf8"))
+ .join("\n");
+ } catch {
+ return "";
+ }
+}
+
+describe.skipIf(!SUPPORTED)("MCP protocol stdout with hooks loaded", () => {
+ it(
+ "X-9: no hook write, by any route, reaches the JSON-RPC stream",
+ async () => {
+ const layout = makeTempLayout("hooks-x9");
+ layouts.push(layout);
+ const modulePath = join(layout.root, "noisy.ts");
+ writeFileSync(modulePath, NOISY_MODULE);
+ const configPath = join(layout.root, "config.json");
+ writeFileSync(configPath, JSON.stringify({ hooks: { modules: [modulePath] } }));
+
+ const proc = Bun.spawn(["bun", ENTRY, "--mcp"], {
+ cwd: layout.cwd,
+ env: serverEnv(layout, { CLAUDISH_CONFIG: configPath, CLAUDISH_DEBUG: "1" }),
+ stdin: "pipe",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const out = lineReader(proc.stdout);
+ const err = lineReader(proc.stderr);
+ const send = (msg: object) => {
+ proc.stdin.write(`${JSON.stringify(msg)}\n`);
+ proc.stdin.flush();
+ };
+ const responseFor = (id: number) =>
+ out.text
+ .split("\n")
+ .filter((l) => l.trim().length > 0)
+ .some((l) => {
+ try {
+ return JSON.parse(l).id === id;
+ } catch {
+ return false;
+ }
+ });
+
+ try {
+ // The module was imported and its import-time timer ran.
+ await waitFor(() => err.text.includes("SCOPED-C"), {
+ what: "the hook module's import-time timer",
+ timeoutMs: 15_000,
+ });
+
+ send({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: "2025-06-18",
+ capabilities: {},
+ clientInfo: { name: "x9", version: "0.0.0" },
+ },
+ });
+ await waitFor(() => responseFor(1), { what: "initialize response", timeoutMs: 10_000 });
+ send({ jsonrpc: "2.0", method: "notifications/initialized" });
+ send({ jsonrpc: "2.0", id: 2, method: "tools/list" });
+ send({ jsonrpc: "2.0", id: 3, method: "ping" });
+ await waitFor(() => responseFor(2) && responseFor(3), { what: "tools/list and ping" });
+
+ const leaksBefore = err.text.match(/LEAK-C/g)?.length ?? 0;
+ expect(leaksBefore).toBeGreaterThanOrEqual(1);
+ // process.kill, not proc.kill: measured on Bun 1.4.0, `Subprocess.kill("SIGUSR2")`
+ // terminates a child whose SIGUSR2 listener `process.kill(pid, …)` reaches.
+ process.kill(proc.pid, "SIGUSR2");
+ await waitFor(() => (err.text.match(/LEAK-C/g)?.length ?? 0) > leaksBefore, {
+ what: "the signal listener's writes",
+ });
+ send({ jsonrpc: "2.0", id: 4, method: "tools/list" });
+ await waitFor(() => responseFor(4), { what: "the second tools/list" });
+
+ // Every listener ran: the stdin one per line sent, the signal one once.
+ await waitFor(
+ () =>
+ [
+ "[stdout] LEAK-A",
+ "[stdout] LEAK-B",
+ `[hook ${modulePath}] SCOPED-A`,
+ `[hook ${modulePath}] SCOPED-B`,
+ ].every((marker) => debugLog(layout.cwd).includes(marker)),
+ { what: "the diverted writes in the debug log", timeoutMs: 10_000 }
+ );
+ } finally {
+ proc.stdin.end();
+ proc.kill();
+ await proc.exited;
+ }
+
+ const lines = out.text.split("\n").filter((l) => l.trim().length > 0);
+ expect(lines.length).toBeGreaterThanOrEqual(4);
+ for (const line of lines) {
+ expect(line).not.toContain("LEAK");
+ expect(line).not.toContain("SCOPED");
+ expect(JSON.parse(line).jsonrpc).toBe("2.0");
+ }
+ const answered = lines.map((l) => JSON.parse(l).id).filter((id) => id !== undefined);
+ expect(answered).toEqual(expect.arrayContaining([1, 2, 3, 4]));
+
+ // Direct descriptor writes land on stderr.
+ for (const marker of ["LEAK-C", "LEAK-D", "SCOPED-C", "SCOPED-D"]) {
+ expect(err.text).toContain(marker);
+ }
+ const log = debugLog(layout.cwd);
+ expect(log).toContain("[stdout] LEAK-A");
+ expect(log).toContain("[stdout] LEAK-B");
+ expect(log).toContain(`[hook ${modulePath}] SCOPED-A`);
+ expect(log).toContain(`[hook ${modulePath}] SCOPED-B`);
+ },
+ { timeout: 60_000 }
+ );
+
+ it("X-9 positive control: without isolation the same module puts every marker on stdout", async () => {
+ const layout = makeTempLayout("hooks-x9-control");
+ layouts.push(layout);
+ const modulePath = join(layout.root, "noisy.ts");
+ writeFileSync(modulePath, NOISY_MODULE);
+ const script = join(layout.root, "bare.ts");
+ writeFileSync(script, `await import(${JSON.stringify(modulePath)});\n`);
+
+ const proc = Bun.spawn(["bun", script], {
+ cwd: layout.cwd,
+ stdin: "pipe",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const out = lineReader(proc.stdout);
+ try {
+ await waitFor(() => out.text.includes("SCOPED-D"), { what: "the import-time writes" });
+ proc.stdin.write("a line\n");
+ proc.stdin.flush();
+ await waitFor(() => ["A", "B", "C", "D"].every((s) => out.text.includes(`LEAK-${s}`)), {
+ what: "every LEAK marker on stdout",
+ });
+ } finally {
+ proc.kill();
+ await proc.exited;
+ }
+ for (const s of ["A", "B", "C", "D"]) expect(out.text).toContain(`LEAK-${s}`);
+ });
+});
diff --git a/packages/cli/src/hooks/request-stage.test.ts b/packages/cli/src/hooks/request-stage.test.ts
new file mode 100644
index 00000000..60898f8a
--- /dev/null
+++ b/packages/cli/src/hooks/request-stage.test.ts
@@ -0,0 +1,399 @@
+import { afterEach, describe, expect, it } from "bun:test";
+import { BUILTIN_HOOKS } from "./builtins/index.js";
+import { HookEngine } from "./engine.js";
+import type { JournalEntry } from "./journal.js";
+import { type HookDefinition, act } from "./public.js";
+import { HookRegistry, type UserHookInput } from "./registry.js";
+import {
+ HOOK_SCOPE_CONTEXT_KEY,
+ RequestHooks,
+ isNativeRoute,
+ proxySessionFromEnv,
+ systemTextOf,
+} from "./request-stage.js";
+import { resetTelemetryState } from "./telemetry/aggregate.js";
+
+const SESSION_A = "ce7d9e68-f907-444f-9680-69ec3048ce9c";
+const SESSION_B = "62e11a50-15c1-4863-b880-0a518425db74";
+const FOREIGN = { modelId: "gpt-5.6-sol", provider: "openai-codex", native: false };
+
+afterEach(() => resetTelemetryState());
+
+function userHook(id: string, def: Omit<HookDefinition, "apiVersion" | "id">, index = 0) {
+ return {
+ id: `hook:m/${id}`,
+ module: "/hooks/m.ts",
+ moduleIndex: 0,
+ exportIndex: index,
+ def: { apiVersion: 1, id, ...def } as HookDefinition,
+ } satisfies UserHookInput;
+}
+
+function engineWith(
+ users: UserHookInput[] = [],
+ opts: { builtins?: boolean; severity?: Record<string, "off" | "warn" | "fix"> } = {}
+) {
+ const journal: JournalEntry[] = [];
+ const engine = new HookEngine({
+ registry: new HookRegistry(opts.builtins ? BUILTIN_HOOKS : [], users, opts.severity),
+ config: opts.severity ? { severity: opts.severity } : {},
+ hostMode: "other",
+ journalSink: (e) => journal.push(e),
+ warn: () => {},
+ drainTelemetryOutbox: false,
+ });
+ return { engine, journal };
+}
+
+function fakeContext() {
+ const vars = new Map<string, unknown>();
+ return {
+ get: (k: string) => vars.get(k),
+ set: (k: string, v: unknown) => vars.set(k, v),
+ vars,
+ };
+}
+
+// biome-ignore lint/suspicious/noExplicitAny: Claude-format requests are untyped at this layer
+function requestFor(sessionId: string | undefined, system: any = "base system"): any {
+ const req: Record<string, unknown> = {
+ system,
+ messages: [{ role: "user", content: "hello" }],
+ tools: [{ name: "ExitPlanMode", description: "Exit.", input_schema: { type: "object" } }],
+ };
+ if (sessionId) {
+ req.metadata = {
+ user_id: JSON.stringify({ device_id: "abc", account_uuid: "", session_id: sessionId }),
+ };
+ }
+ return req;
+}
+
+async function begin(
+ hooks: RequestHooks,
+ // biome-ignore lint/suspicious/noExplicitAny: see requestFor
+ claudeRequest: any,
+ route = FOREIGN,
+ c = fakeContext()
+) {
+ const scope = await hooks.beginAttempt(c, {
+ claudeRequest,
+ route,
+ model: route.modelId,
+ stream: true,
+ });
+ return { scope, c };
+}
+
+describe("isNativeRoute (RouteInfo.native for proxied routes)", () => {
+ it("is today's rule: claude-* names and the anthropic provider, unless forceForeignModel", () => {
+ expect(isNativeRoute("claude-opus-4-8", "openrouter")).toBe(true);
+ expect(isNativeRoute("Claude.sonnet", "x")).toBe(true);
+ expect(isNativeRoute("glm-5", "anthropic")).toBe(true);
+ expect(isNativeRoute("gpt-5.6-sol", "openai-codex")).toBe(false);
+ expect(isNativeRoute("my-claude-clone", "openrouter")).toBe(false);
+ expect(isNativeRoute("claude-sonnet-5-medium", "devin", true)).toBe(false);
+ expect(isNativeRoute("glm-5", "anthropic", true)).toBe(false);
+ });
+});
+
+describe("systemTextOf / proxySessionFromEnv", () => {
+ it("flattens string and block system prompts", () => {
+ expect(systemTextOf("plain")).toBe("plain");
+ expect(
+ systemTextOf([
+ { type: "text", text: "a" },
+ { type: "text", text: "b" },
+ ])
+ ).toBe("a\n\nb");
+ expect(systemTextOf(undefined)).toBe("");
+ });
+
+ it("reads CLAUDISH_HOOK_SESSION and rejects malformed values", () => {
+ expect(
+ proxySessionFromEnv({ CLAUDISH_HOOK_SESSION: '{"kind":"team","id":"r:s1","role":"judge"}' })
+ ).toEqual({ kind: "team", id: "r:s1", role: "judge" });
+ expect(
+ proxySessionFromEnv({ CLAUDISH_HOOK_SESSION: '{"kind":"channel","id":"ab12cd34"}' })
+ ).toEqual({
+ kind: "channel",
+ id: "ab12cd34",
+ role: null,
+ });
+ expect(proxySessionFromEnv({ CLAUDISH_HOOK_SESSION: '{"kind":"nope","id":"x"}' })).toBeNull();
+ expect(proxySessionFromEnv({ CLAUDISH_HOOK_SESSION: "not json" })).toBeNull();
+ expect(proxySessionFromEnv({})).toBeNull();
+ });
+});
+
+describe("RequestHooks.beginAttempt — stage A and stage B", () => {
+ it("hooks see the request before stage A, and stage A replaces system/messages without mutating them", async () => {
+ let seen: { systemText?: string; firstUser?: unknown; session?: unknown; host?: unknown } = {};
+ const { engine } = engineWith([
+ userHook("edit", {
+ on: {
+ request: (ctx) => {
+ seen = {
+ systemText: ctx.request.systemText,
+ firstUser: ctx.request.messages[0]?.content,
+ session: ctx.session,
+ host: ctx.host,
+ };
+ return [act.injectSystemNote("NOTE"), act.appendUserText("APPENDED")];
+ },
+ },
+ }),
+ ]);
+ const session = { kind: "channel" as const, id: "ab12cd34", role: null };
+ const req = requestFor(SESSION_A);
+ const originalMessages = req.messages;
+ const originalFirst = req.messages[0];
+ const { scope, c } = await begin(new RequestHooks(engine, session), req);
+
+ expect(seen).toEqual({
+ systemText: "base system",
+ firstUser: "hello",
+ session,
+ host: { mode: "other" },
+ });
+ expect(req.system).toBe("base system\n\nNOTE");
+ expect(req.messages).not.toBe(originalMessages);
+ expect(originalFirst).toEqual({ role: "user", content: "hello" });
+ expect(req.messages[0].content).toEqual([
+ { type: "text", text: "hello" },
+ { type: "text", text: "APPENDED" },
+ ]);
+ expect(c.vars.get(HOOK_SCOPE_CONTEXT_KEY)).toBe(scope);
+ });
+
+ it("holds description actions for stage B and applies them to both representations", async () => {
+ const { engine, journal } = engineWith([
+ userHook("desc", {
+ on: { request: () => [act.rewriteToolDescription("ExitPlanMode", " +B")] },
+ }),
+ ]);
+ const req = requestFor(SESSION_A);
+ const { scope } = await begin(new RequestHooks(engine), req);
+
+ // Not applied at stage A.
+ expect(req.tools[0].description).toBe("Exit.");
+ expect(scope.hasToolDescriptionWork).toBe(true);
+
+ const converted = [
+ { type: "function", function: { name: "ExitPlanMode", description: "Exit." } },
+ ];
+ scope.applyToolDescriptions(req.tools, converted);
+ expect(req.tools[0].description).toBe("Exit. +B");
+ expect(converted[0]?.function.description).toBe("Exit. +B");
+ expect(scope.hasToolDescriptionWork).toBe(false);
+
+ // A second call is a no-op.
+ scope.applyToolDescriptions(req.tools, converted);
+ expect(req.tools[0].description).toBe("Exit. +B");
+ expect(
+ journal.filter((e) => e.action === "rewriteToolDescription").map((e) => e.decision)
+ ).toEqual(["matched"]);
+ });
+
+ it("the foreign-scoped built-ins stay off on a native route", async () => {
+ const { engine } = engineWith([], { builtins: true });
+ const req = requestFor(SESSION_A, "SessionStart hook additional context");
+ req.messages[0].content =
+ "You should create your plan at /tmp/p/assigned.md using the Write tool.";
+ const native = { modelId: "claude-opus-4-8", provider: "anthropic", native: true };
+ const { scope } = await begin(new RequestHooks(engine), req, native);
+
+ expect(req.system).toBe("SessionStart hook additional context");
+ expect(scope.hasToolDescriptionWork).toBe(false);
+ });
+
+ it("skips the harness scan when no hook applies", async () => {
+ const { engine } = engineWith();
+ const req = requestFor(SESSION_A);
+ req.messages[0].content = "You should create your plan at /tmp/p/assigned.md now.";
+ const { scope } = await begin(new RequestHooks(engine), req);
+
+ expect(scope.harness).toEqual({ planModeActive: false, sessionId: SESSION_A });
+ });
+
+ it("detects harness facts when a hook applies", async () => {
+ const { engine } = engineWith([userHook("noop", { on: { request: () => [] } })]);
+ const req = requestFor(SESSION_A);
+ req.messages[0].content = "You should create your plan at /tmp/p/assigned.md now.";
+ const { scope } = await begin(new RequestHooks(engine), req);
+
+ expect(scope.harness.planModeActive).toBe(true);
+ expect(scope.harness.planFilePath).toBe("/tmp/p/assigned.md");
+ expect(scope.harness.sessionId).toBe(SESSION_A);
+ });
+
+ it("evaluates toolCall armed() and responseRewrite claims() for fix-severity hooks only", async () => {
+ const { engine } = engineWith(
+ [
+ userHook("armed", {
+ on: {
+ toolCall: {
+ tools: ["Write"],
+ armed: (ctx) => ctx.harness.planModeActive,
+ handle: () => [],
+ },
+ },
+ }),
+ userHook(
+ "unarmed",
+ {
+ on: { toolCall: { tools: ["Edit"], armed: () => false, handle: () => [] } },
+ },
+ 1
+ ),
+ userHook(
+ "observer",
+ {
+ on: { toolCall: { tools: ["Read"], observe: true, handle: () => [] } },
+ },
+ 2
+ ),
+ userHook("warned", { on: { toolCall: { tools: ["Bash"], handle: () => [] } } }, 3),
+ userHook("claims", { on: { responseRewrite: { handle: () => [] } } }, 4),
+ userHook(
+ "declines",
+ {
+ on: { responseRewrite: { claims: () => false, handle: () => [] } },
+ },
+ 5
+ ),
+ userHook(
+ "throws",
+ {
+ on: {
+ responseRewrite: {
+ claims: () => {
+ throw new Error("boom");
+ },
+ handle: () => [],
+ },
+ },
+ },
+ 6
+ ),
+ ],
+ { severity: { "hook:m/warned": "warn" } }
+ );
+ const req = requestFor(SESSION_A);
+ req.messages[0].content = "You should create your plan at /tmp/p/assigned.md now.";
+ const { scope } = await begin(new RequestHooks(engine), req);
+
+ expect([...scope.armedTools]).toEqual(["Write"]);
+ expect(scope.rewriteClaimants).toEqual(["hook:m/claims"]);
+ });
+});
+
+describe("pending notes (ported from behavior/output-rules.test.ts)", () => {
+ it("applies a queued note to the next request of the same session", async () => {
+ const { engine, journal } = engineWith();
+ engine.queueNote(SESSION_A, "hook:m/judge", "Run the verification before claiming completion.");
+ const next = requestFor(SESSION_A, "turn two system");
+ await begin(new RequestHooks(engine), next);
+
+ expect(next.system).toBe("turn two system\n\nRun the verification before claiming completion.");
+ expect(
+ journal.some((e) => e.hookId === "behavior/pending-correction" && e.decision === "matched")
+ ).toBe(true);
+ });
+
+ it("does not leak a note to a different session id", async () => {
+ const { engine } = engineWith();
+ engine.queueNote(SESSION_A, "hook:m/judge", "Session A correction");
+ const other = requestFor(SESSION_B);
+ await begin(new RequestHooks(engine), other);
+
+ expect(other.system).toBe("base system");
+ });
+
+ it("drains a note once the request carrying it commits", async () => {
+ const { engine } = engineWith();
+ const hooks = new RequestHooks(engine);
+ engine.queueNote(SESSION_A, "hook:m/judge", "One-shot correction");
+ const next = requestFor(SESSION_A);
+ const { scope } = await begin(hooks, next);
+ scope.commit();
+ const later = requestFor(SESSION_A);
+ await begin(hooks, later);
+
+ expect(next.system).toBe("base system\n\nOne-shot correction");
+ expect(later.system).toBe("base system");
+ });
+
+ it("keeps a note when the attempt carrying it is abandoned (a failed fallback attempt)", async () => {
+ const { engine } = engineWith();
+ const hooks = new RequestHooks(engine);
+ engine.queueNote(SESSION_A, "hook:m/judge", "Survives a failed attempt");
+ const c = fakeContext();
+ const first = await begin(hooks, requestFor(SESSION_A), FOREIGN, c);
+ // The second attempt on the same context abandons the first.
+ const secondReq = requestFor(SESSION_A);
+ const second = await begin(hooks, secondReq, FOREIGN, c);
+ expect(first.scope.settled).toBe("abandoned");
+ expect(secondReq.system).toBe("base system\n\nSurvives a failed attempt");
+ second.scope.abandon();
+
+ const third = requestFor(SESSION_A);
+ await begin(hooks, third);
+ expect(third.system).toBe("base system\n\nSurvives a failed attempt");
+ });
+
+ it("carries a note on every concurrent request that starts before any of them commits", async () => {
+ const { engine } = engineWith();
+ const hooks = new RequestHooks(engine);
+ engine.queueNote(SESSION_A, "hook:m/judge", "Concurrent note");
+ const a = requestFor(SESSION_A);
+ const b = requestFor(SESSION_A);
+ const [sa, sb] = await Promise.all([begin(hooks, a), begin(hooks, b)]);
+ sa.scope.commit();
+ sb.scope.commit();
+
+ expect(a.system).toBe("base system\n\nConcurrent note");
+ expect(b.system).toBe("base system\n\nConcurrent note");
+ expect(engine.peekNotes(SESSION_A)).toEqual([]);
+ });
+
+ it("applies an identical note from a hook and from the store once", async () => {
+ const { engine } = engineWith([
+ userHook("same", { on: { request: () => [act.injectSystemNote("Same text")] } }),
+ ]);
+ engine.queueNote(SESSION_A, "hook:m/judge", "Same text");
+ const req = requestFor(SESSION_A);
+ await begin(new RequestHooks(engine), req);
+
+ expect(req.system).toBe("base system\n\nSame text");
+ });
+
+ it("applies no hook action at warn severity", async () => {
+ const { engine, journal } = engineWith(
+ [userHook("w", { on: { request: () => [act.injectSystemNote("withheld")] } })],
+ { severity: { "hook:m/w": "warn" } }
+ );
+ const req = requestFor(SESSION_A);
+ await begin(new RequestHooks(engine), req);
+
+ expect(req.system).toBe("base system");
+ expect(journal.some((e) => e.hookId === "hook:m/w" && e.decision === "warned")).toBe(true);
+ });
+
+ it("a throwing request hook fails open", async () => {
+ const { engine } = engineWith([
+ userHook("boom", {
+ on: {
+ request: () => {
+ throw new Error("request hook exploded");
+ },
+ },
+ }),
+ userHook("ok", { on: { request: () => [act.injectSystemNote("still applied")] } }, 1),
+ ]);
+ const req = requestFor(SESSION_A);
+ await begin(new RequestHooks(engine), req);
+
+ expect(req.system).toBe("base system\n\nstill applied");
+ });
+});
diff --git a/packages/cli/src/hooks/request-stage.ts b/packages/cli/src/hooks/request-stage.ts
new file mode 100644
index 00000000..a59105bc
--- /dev/null
+++ b/packages/cli/src/hooks/request-stage.ts
@@ -0,0 +1,395 @@
+/**
+ * The request stage: `request` hooks run once per upstream attempt, 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 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.
+ *
+ * The stage runs only when `withHooks` put the per-request `RequestHooks` on the
+ * Hono context. The classifier passthrough, monitor mode, `--probe` and direct
+ * handler use in tests therefore run no hooks.
+ *
+ * A `HookRequestScope` is one attempt's state. A FallbackHandler runs one
+ * attempt per candidate on the same context; each attempt begins from a fresh
+ * deep copy of the request (`transformOpenAIToClaude`), so nothing one attempt
+ * applies leaks into the next, and the LAST attempt's scope is the one the
+ * decorator commits or abandons. Pending notes are peeked, not taken: they are
+ * removed only on `commit()`, so a correction survives a failed first attempt.
+ */
+
+import type { Context } from "hono";
+import { log } from "../logger.js";
+import {
+ type MutableClaudeRequest,
+ type PlannedAction,
+ applyStageA,
+ applyStageB,
+} from "./actions.js";
+import { type HookEngine, type JournalMeta, PENDING_NOTE_ID } from "./engine.js";
+import { detectHarnessFacts, extractAvailableSkills, extractSessionId } from "./harness.js";
+import type {
+ ClaudeMessage,
+ ClaudeTool,
+ HarnessFacts,
+ ProxySessionRef,
+ RequestAction,
+ RequestContext,
+ RequestFacts,
+ RouteInfo,
+} from "./public.js";
+import type { ApplicableHook } from "./registry.js";
+import { recordTelemetryTurn } from "./telemetry/aggregate.js";
+
+/** Hono context key: the per-proxy `RequestHooks`, set by `withHooks`. */
+export const HOOKS_CONTEXT_KEY = "claudishHooks";
+/** Hono context key: the current attempt's `HookRequestScope` (the last attempt overwrites). */
+export const HOOK_SCOPE_CONTEXT_KEY = "claudishHookScope";
+
+/** The pane-child env var naming the session a proxy event belongs to (§2.3). */
+export const HOOK_SESSION_ENV = "CLAUDISH_HOOK_SESSION";
+
+/**
+ * `RouteInfo.native` for a proxied route: today's exact rule.
+ *
+ * A naming rule, not a pinned model list: Claude models are `claude-*`, and the
+ * `anthropic` provider serves them. `forceForeignModel` is the one escape
+ * hatch, set by a provider profile whose uids merely LOOK like Claude's (a
+ * subscription aggregator serving `claude-sonnet-5-medium` over a foreign
+ * protocol), where the 87/87 plan-mode measurement says nothing.
+ */
+export function isNativeRoute(
+ bareModelName: string,
+ providerName: string,
+ forceForeignModel?: boolean
+): boolean {
+ return !forceForeignModel && (/^claude[-.]/i.test(bareModelName) || providerName === "anthropic");
+}
+
+/** A system prompt (string, or an array of text blocks) flattened to text. */
+export function systemTextOf(system: unknown): string {
+ if (typeof system === "string") return system;
+ if (!Array.isArray(system)) return "";
+ const parts: string[] = [];
+ for (const block of system) {
+ if (typeof block === "string") parts.push(block);
+ else if (typeof (block as { text?: unknown } | null)?.text === "string") {
+ parts.push((block as { text: string }).text);
+ }
+ }
+ return parts.join("\n\n");
+}
+
+/** `CLAUDISH_HOOK_SESSION` (`{"kind","id","role"}`), or null when absent or malformed. */
+export function proxySessionFromEnv(env: NodeJS.ProcessEnv = process.env): ProxySessionRef | null {
+ const raw = env[HOOK_SESSION_ENV];
+ if (!raw) return null;
+ try {
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
+ const kinds = ["interactive", "channel", "team"];
+ const roles = ["slot", "judge", null];
+ if (
+ typeof parsed?.id !== "string" ||
+ !kinds.includes(parsed.kind as string) ||
+ !roles.includes((parsed.role ?? null) as string | null)
+ ) {
+ return null;
+ }
+ return {
+ kind: parsed.kind as ProxySessionRef["kind"],
+ id: parsed.id,
+ role: (parsed.role ?? null) as ProxySessionRef["role"],
+ };
+ } catch {
+ return null;
+ }
+}
+
+/* ───────────── context access ───────────── */
+
+// Hono's Context is the production carrier; tests pass minimal fakes, some
+// without get/set, which must keep running no hooks.
+type ContextLike = Pick<Context, "get" | "set"> | undefined;
+
+function contextGet<T>(c: ContextLike, key: string): T | undefined {
+ return typeof c?.get === "function" ? (c.get(key as never) as T | undefined) : undefined;
+}
+
+function contextSet(c: ContextLike, key: string, value: unknown): void {
+ if (typeof c?.set === "function") c.set(key as never, value as never);
+}
+
+/** The per-request hooks `withHooks` put on the context, if any. */
+export function requestHooksOf(c: ContextLike): RequestHooks | undefined {
+ return contextGet<RequestHooks>(c, HOOKS_CONTEXT_KEY);
+}
+
+/** The current attempt's scope, if a terminal handler began one. */
+export function hookScopeOf(c: ContextLike): HookRequestScope | undefined {
+ return contextGet<HookRequestScope>(c, HOOK_SCOPE_CONTEXT_KEY);
+}
+
+/** Put the per-request hooks on a context (`withHooks` does this). */
+export function attachRequestHooks(c: ContextLike, hooks: RequestHooks): void {
+ contextSet(c, HOOKS_CONTEXT_KEY, hooks);
+}
+
+/* ───────────── attempts ───────────── */
+
+/** What a terminal handler hands the stage for one attempt. */
+export interface AttemptInput {
+ /**
+ * The Claude-format request this attempt owns. Stage A REPLACES its `system`,
+ * `messages` and `tools` (never mutating a message, block or tool in place),
+ * so it is safe on a copy-on-write view of a shared payload.
+ */
+ claudeRequest: MutableClaudeRequest & { metadata?: unknown };
+ route: RouteInfo;
+ /** The model as Claude Code asked for it. */
+ model: string;
+ stream: boolean;
+}
+
+/** The engine-facing part of one proxy: shared by every request it serves. */
+export class RequestHooks {
+ constructor(
+ readonly engine: HookEngine,
+ /** Which session this process's proxy events belong to; `CLAUDISH_HOOK_SESSION` by default. */
+ readonly session: ProxySessionRef | null = proxySessionFromEnv()
+ ) {}
+
+ /**
+ * Run the `request` hooks for one attempt and apply stage A. The scope is
+ * stored on the context, replacing (and abandoning) a previous attempt's.
+ */
+ async beginAttempt(c: ContextLike, input: AttemptInput): Promise<HookRequestScope> {
+ hookScopeOf(c)?.abandon();
+ const scope = await HookRequestScope.begin(this.engine, this.session, input);
+ contextSet(c, HOOK_SCOPE_CONTEXT_KEY, scope);
+ return scope;
+ }
+}
+
+type ScopeState = "open" | "committed" | "abandoned";
+
+/** One upstream attempt's hook state. */
+export class HookRequestScope {
+ /** Tool names a fix-severity `toolCall` hook armed for this request. Consumed by the response seam. */
+ readonly armedTools: ReadonlySet<string>;
+ /** Ids of fix-severity `responseRewrite` hooks whose `claims` was true. Consumed by the response seam. */
+ readonly rewriteClaimants: ReadonlyArray<string>;
+
+ private held: PlannedAction<RequestAction>[];
+ private state: ScopeState = "open";
+
+ private constructor(
+ private readonly engine: HookEngine,
+ readonly route: RouteInfo,
+ readonly harness: HarnessFacts,
+ readonly sessionId: string | undefined,
+ readonly meta: JournalMeta,
+ held: PlannedAction<RequestAction>[],
+ private readonly removedTools: ReadonlySet<string>,
+ private readonly pendingSeqs: ReadonlyArray<number>,
+ armedTools: ReadonlySet<string>,
+ rewriteClaimants: ReadonlyArray<string>
+ ) {
+ this.held = held;
+ this.armedTools = armedTools;
+ this.rewriteClaimants = rewriteClaimants;
+ }
+
+ /** Steps 1–7 of §5.1, in order. */
+ static async begin(
+ engine: HookEngine,
+ session: ProxySessionRef | null,
+ input: AttemptInput
+ ): Promise<HookRequestScope> {
+ const { claudeRequest, route } = input;
+ const sessionId = extractSessionId(claudeRequest);
+ const meta: JournalMeta = sessionId
+ ? { model: route.modelId, provider: route.provider, sessionId }
+ : { model: route.modelId, provider: route.provider };
+
+ // 2. Applicable hooks. Selection is cheap; the harness scan is not (it walks
+ // a conversation that can be ~180K tokens), so it runs only when some
+ // hook will read it.
+ 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>,
+ };
+ const requestContext = (base: object): RequestContext =>
+ ({
+ ...base,
+ event: "request",
+ host: { mode: engine.hostMode },
+ route,
+ request: facts,
+ harness,
+ session,
+ }) 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.
+ 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);
+
+ // 6. Armed tools and rewrite claims, evaluated once, before any response.
+ const armedTools = new Set<string>();
+ for (const applicable of toolCallHooks) {
+ if (applicable.severity !== "fix") continue;
+ const tc = applicable.hook.def.on?.toolCall;
+ if (!tc || tc.observe === true) continue;
+ const ctx = requestContext(predicateBase(applicable));
+ if (!engine.callPredicate(applicable.hook.id, tc.armed, tc, ctx, true)) continue;
+ for (const tool of tc.tools) armedTools.add(tool);
+ }
+ const rewriteClaimants: string[] = [];
+ for (const applicable of rewriteHooks) {
+ if (applicable.severity !== "fix") continue;
+ const rr = applicable.hook.def.on?.responseRewrite;
+ if (!rr) continue;
+ const ctx = requestContext(predicateBase(applicable));
+ if (engine.callPredicate(applicable.hook.id, rr.claims, rr, ctx, true)) {
+ rewriteClaimants.push(applicable.hook.id);
+ }
+ }
+
+ const applied = stageA.results.filter((r) => r.decision === "matched").length;
+ if (applied > 0 || stageA.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`
+ );
+ }
+
+ // 5. Stage-B actions are held until the converted tools exist.
+ return new HookRequestScope(
+ engine,
+ route,
+ harness,
+ sessionId,
+ meta,
+ [...stageA.held],
+ stageA.removedTools,
+ notes.map((n) => n.seq),
+ armedTools,
+ rewriteClaimants
+ );
+ }
+
+ /** True while stage-B actions are waiting for `applyToolDescriptions`. */
+ get hasToolDescriptionWork(): boolean {
+ return this.held.length > 0;
+ }
+
+ /**
+ * Stage B: apply the held description actions to both tool representations.
+ * `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;
+ * later calls do nothing.
+ */
+ // biome-ignore lint/suspicious/noExplicitAny: Claude-format and provider-format tool arrays
+ applyToolDescriptions(claudeTools: any[], convertedTools: any[] | null): void {
+ if (this.held.length === 0) return;
+ const held = this.held;
+ this.held = [];
+ const results = applyStageB(claudeTools, convertedTools, held, this.removedTools);
+ if (results.length > 0) this.engine.recordResults("request", results, this.meta);
+ }
+
+ /**
+ * The attempt's response was accepted (2xx): remove the pending notes it
+ * carried. Idempotent; a no-op after `abandon()`.
+ */
+ commit(): void {
+ if (this.state !== "open") return;
+ this.state = "committed";
+ if (this.sessionId && this.pendingSeqs.length > 0) {
+ this.engine.consumeNotes(this.sessionId, this.pendingSeqs);
+ }
+ }
+
+ /** The attempt failed or was superseded: its pending notes stay queued. */
+ abandon(): void {
+ if (this.state !== "open") return;
+ this.state = "abandoned";
+ }
+
+ get settled(): ScopeState {
+ return this.state;
+ }
+
+ /**
+ * A turn finished on the wire, at this context size. Runs on every turn,
+ * because a session where no hook ever fired is the denominator every
+ * violation-rate question needs. Counts only; no-op unless telemetry is
+ * opted in.
+ */
+ noteTurnComplete(inputTokens?: number): void {
+ recordTelemetryTurn({
+ sessionId: this.sessionId,
+ model: this.route.modelId,
+ provider: this.route.provider,
+ inputTokens,
+ });
+ }
+}
+
+/** A predicate's base context. `armed`/`claims` get no signal of their own: they are synchronous. */
+function predicateBase(applicable: ApplicableHook): object {
+ return {
+ hookId: applicable.hook.id,
+ severity: applicable.severity,
+ log: (message: string) => log(`[hook ${applicable.hook.id}] ${message}`),
+ signal: new AbortController().signal,
+ };
+}
+
+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;
+}
diff --git a/packages/cli/src/hooks/response-seam.test.ts b/packages/cli/src/hooks/response-seam.test.ts
new file mode 100644
index 00000000..d6319355
--- /dev/null
+++ b/packages/cli/src/hooks/response-seam.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, it } from "bun:test";
+import type { Context } from "hono";
+import type { ModelHandler } from "../handlers/types.js";
+import { HookEngine } from "./engine.js";
+import { HookRegistry } from "./registry.js";
+import { hookScopeOf, requestHooksOf } from "./request-stage.js";
+import { HooksHandler, withHooks } from "./response-seam.js";
+
+const SESSION = "ce7d9e68-f907-444f-9680-69ec3048ce9c";
+
+function engine() {
+ return new HookEngine({
+ registry: new HookRegistry([], [], undefined),
+ config: {},
+ hostMode: "other",
+ journalSink: () => {},
+ warn: () => {},
+ drainTelemetryOutbox: false,
+ });
+}
+
+function fakeContext(): Context {
+ const vars = new Map<string, unknown>();
+ return {
+ get: (k: string) => vars.get(k),
+ set: (k: string, v: unknown) => vars.set(k, v),
+ } as unknown as Context;
+}
+
+function payload() {
+ return {
+ model: "glm-5",
+ system: "base",
+ messages: [{ role: "user", content: "hi" }],
+ metadata: {
+ user_id: JSON.stringify({ device_id: "d", account_uuid: "", session_id: SESSION }),
+ },
+ };
+}
+
+/** A terminal handler that begins one attempt (as ComposedHandler does) and answers `status`. */
+function terminal(status: number, onHandle?: () => void): ModelHandler & { shutdowns: number } {
+ return {
+ shutdowns: 0,
+ async handle(c: Context, body: unknown) {
+ onHandle?.();
+ const hooks = requestHooksOf(c);
+ await hooks?.beginAttempt(c, {
+ claudeRequest: structuredClone(body) as Record<string, unknown>,
+ route: { modelId: "glm-5", provider: "zai", native: false },
+ model: "glm-5",
+ stream: true,
+ });
+ return new Response("data: {}\n\n", { status });
+ },
+ async shutdown() {
+ this.shutdowns++;
+ },
+ };
+}
+
+describe("withHooks", () => {
+ it("returns the inner Response object itself in mode none (the identity case)", async () => {
+ const inner: ModelHandler = {
+ handle: async () => sentinel,
+ shutdown: async () => {},
+ };
+ const sentinel = new Response("data: x\n\n", { status: 200 });
+ // Even with a scope: begin one through a terminal that keeps the same Response.
+ const c = fakeContext();
+ const wrapped = withHooks(
+ {
+ async handle(ctx, body) {
+ await requestHooksOf(ctx)?.beginAttempt(ctx, {
+ claudeRequest: structuredClone(body),
+ route: { modelId: "m", provider: "p", native: false },
+ model: "m",
+ stream: true,
+ });
+ return inner.handle(ctx, body);
+ },
+ shutdown: async () => {},
+ },
+ engine()
+ );
+
+ expect(await wrapped.handle(c, payload())).toBe(sentinel);
+ expect(hookScopeOf(c)?.settled).toBe("committed");
+ });
+
+ it("forwards shutdown() to the inner handler exactly once", async () => {
+ const inner = terminal(200);
+ await withHooks(inner, engine()).shutdown();
+ expect(inner.shutdowns).toBe(1);
+ });
+
+ it("is idempotent", () => {
+ const e = engine();
+ const once = withHooks(terminal(200), e);
+ expect(withHooks(once, e)).toBe(once);
+ expect(once).toBeInstanceOf(HooksHandler);
+ });
+
+ it("commits on 2xx: a pending note is consumed", async () => {
+ const e = engine();
+ e.queueNote(SESSION, "hook:m/j", "NOTE");
+ await withHooks(terminal(200), e).handle(fakeContext(), payload());
+ expect(e.peekNotes(SESSION)).toEqual([]);
+ });
+
+ it("abandons on non-2xx: a pending note stays queued for the next request", async () => {
+ const e = engine();
+ e.queueNote(SESSION, "hook:m/j", "NOTE");
+ const c = fakeContext();
+ const res = await withHooks(terminal(529), e).handle(c, payload());
+ expect(res.status).toBe(529);
+ expect(hookScopeOf(c)?.settled).toBe("abandoned");
+ expect(e.peekNotes(SESSION).map((n) => n.text)).toEqual(["NOTE"]);
+ });
+
+ it("abandons and rethrows when the inner handler throws", async () => {
+ const e = engine();
+ e.queueNote(SESSION, "hook:m/j", "NOTE");
+ const c = fakeContext();
+ const inner: ModelHandler = {
+ async handle(ctx, body) {
+ await requestHooksOf(ctx)?.beginAttempt(ctx, {
+ claudeRequest: structuredClone(body),
+ route: { modelId: "m", provider: "p", native: false },
+ model: "m",
+ stream: true,
+ });
+ throw new Error("upstream exploded");
+ },
+ shutdown: async () => {},
+ };
+ await expect(withHooks(inner, e).handle(c, payload())).rejects.toThrow("upstream exploded");
+ expect(hookScopeOf(c)?.settled).toBe("abandoned");
+ expect(e.peekNotes(SESSION)).toHaveLength(1);
+ });
+
+ it("passes the response through untouched when no terminal began a scope", async () => {
+ const sentinel = new Response("{}", { status: 200 });
+ const res = await withHooks(
+ { handle: async () => sentinel, shutdown: async () => {} },
+ engine()
+ ).handle(fakeContext(), payload());
+ expect(res).toBe(sentinel);
+ });
+});
diff --git a/packages/cli/src/hooks/response-seam.ts b/packages/cli/src/hooks/response-seam.ts
new file mode 100644
index 00000000..cca6b3f2
--- /dev/null
+++ b/packages/cli/src/hooks/response-seam.ts
@@ -0,0 +1,80 @@
+/**
+ * The response seam: the `withHooks` decorator at the `/v1/messages` call site.
+ *
+ * `withHooks(handler)` wraps the RESOLVED handler, inside the advisor:
+ * `withAdvisor(withHooks(await getHandlerForRequest(model)))`. It is never
+ * applied inside `getHandlerForRequest` and never to a FallbackHandler
+ * candidate, so the `instanceof ComposedHandler` checks in fallback-handler.ts
+ * and the `instanceof NativeHandler` check in count_tokens are untouched. Sitting
+ * inside the advisor means the advisor's tee scans exactly what the client
+ * receives.
+ *
+ * It puts the per-request `RequestHooks` on the Hono context, which is the only
+ * thing that makes a terminal handler run the request stage. After the inner
+ * handler returns: no scope or a non-2xx response → `abandon()` and the response
+ * unchanged; otherwise `commit()` and `applyResponseSeam`.
+ *
+ * This revision implements closed mode `none` only: the seam returns the inner
+ * `Response` object itself. The `intercept` and `buffer` modes, the raw
+ * `response` stage and the observe tap come with the response half.
+ */
+
+import type { Context } from "hono";
+import type { ModelHandler } from "../handlers/types.js";
+import { log } from "../logger.js";
+import type { HookEngine } from "./engine.js";
+import {
+ type HookRequestScope,
+ RequestHooks,
+ attachRequestHooks,
+ hookScopeOf,
+} from "./request-stage.js";
+
+/** The decorator `withHooks` returns. Exported for `instanceof` checks. */
+export class HooksHandler implements ModelHandler {
+ constructor(
+ readonly inner: ModelHandler,
+ readonly hooks: RequestHooks
+ ) {}
+
+ // biome-ignore lint/suspicious/noExplicitAny: the Messages API payload is untyped at this layer, as in ModelHandler
+ async handle(c: Context, payload: any): Promise<Response> {
+ attachRequestHooks(c, this.hooks);
+ let response: Response;
+ try {
+ response = await this.inner.handle(c, payload);
+ } catch (err) {
+ hookScopeOf(c)?.abandon();
+ throw err;
+ }
+ const scope = hookScopeOf(c);
+ if (!scope) return response;
+ if (!response.ok) {
+ scope.abandon();
+ return response;
+ }
+ scope.commit();
+ return applyResponseSeam(response, scope);
+ }
+
+ /** Forwarded: `AdvisorSwapHandler.shutdown()` calls it on whatever it wraps. */
+ shutdown(): Promise<void> {
+ return this.inner.shutdown();
+ }
+}
+
+/** Wrap a resolved handler so its requests run hooks. Idempotent. */
+export function withHooks(inner: ModelHandler, engine: HookEngine): ModelHandler {
+ if (inner instanceof HooksHandler) return inner;
+ return new HooksHandler(inner, new RequestHooks(engine));
+}
+
+/**
+ * Assemble the response stages for an accepted response. With no stage needed
+ * — the only case this revision builds — it returns the SAME object, so
+ * streaming takes exactly today's path.
+ */
+export function applyResponseSeam(response: Response, _scope: HookRequestScope): Response {
+ log("[hooks] seam mode=none raw=0 tap=0");
+ return response;
+}
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 45279cc1..5b8b877e 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -6,6 +6,7 @@
import {
assertNotNested,
assertPaneChildInteractive,
+ isPaneChild,
paneChildBootNotes,
} from "./pane/child-env.js";
@@ -1230,6 +1231,9 @@ async function runCli() {
effortOverride: cliConfig.effortOverride,
modelParams: cliConfig.modelParams,
proOnUltracode: cliConfig.proOnUltracode,
+ // Proxy events run in the process that hosts the proxy: a pane child
+ // for MCP/team slots, the interactive launcher otherwise.
+ hostMode: isPaneChild() ? "pane-child" : cliConfig.interactive ? "interactive" : "other",
}
)
);
diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.ts
index 531bfcb5..2f1ee439 100644
--- a/packages/cli/src/mcp-server.ts
+++ b/packages/cli/src/mcp-server.ts
@@ -23,6 +23,9 @@ import { searchCatalogModels } from "./adapters/model-catalog.js";
import { prehydrateCredentialsForSpawn } from "./auth/credentials/prehydrate.js";
import { setCredentialPromptRole } from "./auth/credentials/prompt-role.js";
import { isSubscriptionProvider } from "./handlers/shared/remote-provider-types.js";
+import { loadHooksOnce } from "./hooks/index.js";
+import { type ProtocolStdout, isolateProtocolStdout } from "./hooks/output-capture.js";
+import { initLogger, log } from "./logger.js";
import { SessionManager } from "./mcp-session/index.js";
import { parentSessionForCall } from "./mcp-session/parent-session.js";
import { NESTED_INSTRUCTIONS, NESTED_MCP_TOOL_NAMES } from "./mcp/nested-mode.js";
@@ -266,7 +269,7 @@ async function getProxy(): Promise<ProxyServer> {
false, // not monitor mode
process.env.ANTHROPIC_API_KEY,
undefined, // no model map
- { quiet: true }
+ { quiet: true, hostMode: "mcp" }
);
proxyInstance = proxy;
return proxy;
@@ -2381,6 +2384,27 @@ function unknownToolModeWarning(mode: string): string | undefined {
// ─── Server Setup ────────────────────────────────────────────────────────────
async function main() {
+ // FIRST, before anything can start loadHooksOnce(): descriptor 1 belongs to
+ // the JSON-RPC writer alone. Every other stdout route — Bun's native
+ // console.log, process.stdout.write, fs.writeSync(1), Bun.write(Bun.stdout),
+ // an inheriting child — lands on stderr or in the debug log, so no hook
+ // output (and no stray write of claudish's own) can corrupt the protocol.
+ // Where libc cannot be bound, `active` is false, stdout is untouched, and the
+ // loader loads no user hook module in this process.
+ const iso: ProtocolStdout = isolateProtocolStdout();
+
+ // `CLAUDISH_DEBUG` (1/true) is the documented always-on debug switch; the MCP
+ // server never parses CLI flags, so it reads the env var directly. The debug
+ // log is also where hook output and diverted stdout writes go.
+ const debugEnv = process.env.CLAUDISH_DEBUG?.toLowerCase();
+ if (debugEnv === "1" || debugEnv === "true") initLogger(true, "debug", true);
+ if (!iso.active) log(`[mcp] protocol stdout not isolated: ${iso.reason ?? "unknown"}`);
+
+ // Session hooks need the engine without a proxy, so loading starts now, in the
+ // background. The MCP server's own proxy (run_prompt, preflight) awaits the
+ // same memoised promise before it builds a handler.
+ void loadHooksOnce({ hostMode: "mcp" });
+
const toolMode = (process.env.CLAUDISH_MCP_TOOLS || "all").toLowerCase();
// Inside a session a claudish owner started, one level of nesting is the limit:
// only the one-shot tools of NESTED_MCP_TOOL_NAMES, intersected with the groups
@@ -2493,8 +2517,9 @@ async function main() {
}
});
- // Connect via stdio transport.
- const transport = new StdioServerTransport();
+ // Connect via stdio transport, writing through the protocol writer (the real
+ // stdout's private descriptor when isolation is active).
+ const transport = new StdioServerTransport(process.stdin, iso.protocolOut);
await server.connect(transport);
installMcpShutdown(sessionManager);
// The startup sweep: panes whose owner died (and whose watcher died too) are reaped
diff --git a/packages/cli/src/providers/transport/conversation-key.ts b/packages/cli/src/providers/transport/conversation-key.ts
index 610fca46..ec9b4c73 100644
--- a/packages/cli/src/providers/transport/conversation-key.ts
+++ b/packages/cli/src/providers/transport/conversation-key.ts
@@ -8,7 +8,7 @@
*/
import { createHash, randomBytes } from "node:crypto";
-import { extractSessionId } from "../../behavior/harness.js";
+import { extractSessionId } from "../../hooks/harness.js";
/**
* Fallback conversation key, minted once per process.
diff --git a/packages/cli/src/proxy-server.ts b/packages/cli/src/proxy-server.ts
index 9c39a3d8..3def0e2b 100644
--- a/packages/cli/src/proxy-server.ts
+++ b/packages/cli/src/proxy-server.ts
@@ -6,8 +6,6 @@ import { isEffortLevel } from "./adapters/base-api-format.js";
import { LocalModelAdapter } from "./adapters/local-adapter.js";
import { OpenRouterAPIFormat } from "./adapters/openrouter-api-format.js";
import { credentials } from "./auth/credentials/authority.js";
-import { loadHookRules } from "./behavior/hooks.js";
-import { parseBehaviorConfig, registerHookRules } from "./behavior/index.js";
import {
isAutoModeClassifierRequest,
rewriteClassifierForNative,
@@ -24,6 +22,10 @@ import { loadAdvisorSwapConfig } from "./handlers/native-handler-advisor.js";
import { NativeHandler } from "./handlers/native-handler.js";
import { wrapAnthropicError } from "./handlers/shared/anthropic-error.js";
import type { ModelHandler } from "./handlers/types.js";
+import type { HookEngine } from "./hooks/engine.js";
+import { loadHooksOnce } from "./hooks/index.js";
+import type { HostMode } from "./hooks/public.js";
+import { withHooks } from "./hooks/response-seam.js";
import { log, logStderr } from "./logger.js";
import { warmRecommendedModels } from "./model-loader.js";
import { loadConfig } from "./profile-config.js";
@@ -163,6 +165,18 @@ export interface ProxyServerOptions {
* no filesystem work at all.
*/
proOnUltracode?: boolean;
+ /**
+ * Run hooks on this proxy's `/v1/messages` traffic. Default true. `--probe`
+ * passes false: hooks never see probe traffic. Monitor mode and the
+ * classifier passthrough never run hooks whatever this says.
+ */
+ hooks?: boolean;
+ /**
+ * Which host this process is, for hook loading and `ctx.host.mode`: the
+ * interactive launcher, a pane child, `serve`, the MCP server, or other.
+ * Default `"other"`. The first proxy of a process decides it.
+ */
+ hostMode?: HostMode;
}
/**
@@ -267,17 +281,26 @@ export async function createProxyServer(
);
}
- // Load behavior-layer hook rules before any handler is constructed: the
- // engine is memoized on first use, and registering rules after that point
- // would leave already-built handlers on a stale rule set.
- try {
- const hookRules = await loadHookRules(parseBehaviorConfig(loadConfig().behavior).hooks);
- if (hookRules.length > 0) registerHookRules(hookRules);
- } catch (err) {
- // Same posture as customEndpoints: a broken optional extension warns and is
- // skipped, it never blocks startup.
- log(`[Proxy] behavior hooks load skipped: ${err instanceof Error ? err.message : String(err)}`);
+ // Load the hook engine before any handler is built and before the first
+ // request, so no request sees a half-loaded registry. Memoised per process.
+ // Monitor mode forwards everything to Anthropic untouched, so it runs no hooks.
+ let hookEngine: HookEngine | null = null;
+ if (options.hooks !== false && !monitorMode) {
+ try {
+ hookEngine = await loadHooksOnce({ hostMode: options.hostMode ?? "other" });
+ } catch (err) {
+ // loadHooksOnce never rejects; same posture as customEndpoints if it did:
+ // a broken optional extension is skipped, it never blocks startup.
+ log(`[Proxy] hooks load skipped: ${err instanceof Error ? err.message : String(err)}`);
+ }
}
+ /**
+ * `withHooks` goes on the RESOLVED handler, inside the advisor — never inside
+ * `getHandlerForRequest` and never on a FallbackHandler candidate, for the same
+ * `instanceof` reasons as the advisor below. Not on the classifier passthrough.
+ */
+ const withRequestHooks = (handler: ModelHandler): ModelHandler =>
+ hookEngine ? withHooks(handler, hookEngine) : handler;
// Define handlers for different roles
const nativeHandler = new NativeHandler(
@@ -1295,8 +1318,12 @@ export async function createProxyServer(
}
// The advisor wrapper goes on the RESOLVED handler (FallbackHandler
- // included), once per request. See `withAdvisor` above.
- const handler = withAdvisor(await getHandlerForRequest(body.model), advisorPresence);
+ // included), once per request, around the hooks. See `withAdvisor` and
+ // `withRequestHooks` above.
+ const handler = withAdvisor(
+ withRequestHooks(await getHandlerForRequest(body.model)),
+ advisorPresence
+ );
// Route. The `await` is load-bearing: `return handler.handle(...)` hands
// the promise back BEFORE it settles, so a rejection escapes this
diff --git a/packages/cli/src/serve-command.ts b/packages/cli/src/serve-command.ts
index 7040f1ac..0bc5aa01 100644
--- a/packages/cli/src/serve-command.ts
+++ b/packages/cli/src/serve-command.ts
@@ -176,6 +176,7 @@ export async function serveCommand(args: string[]): Promise<void> {
{
slotMap,
servedSlotIds: slotIds,
+ hostMode: "serve",
}
);
diff --git a/packages/cli/src/tui/probe-proxy.ts b/packages/cli/src/tui/probe-proxy.ts
index 3f8b1df0..f9ab8270 100644
--- a/packages/cli/src/tui/probe-proxy.ts
+++ b/packages/cli/src/tui/probe-proxy.ts
@@ -50,7 +50,8 @@ export async function ensureProbeProxy(): Promise<string> {
false,
process.env.ANTHROPIC_API_KEY,
undefined,
- { quiet: true }
+ // Hooks never see --probe traffic.
+ { quiet: true, hooks: false }
);
probeProxy = proxy;
return proxy.url;