Skip to content

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

fix(hooks): select gemini/thought-signature from catalog data after rebase onto v11.1.0

Jack Rudenko1eb86203fe15
diff --git a/ai-docs/architecture/hooks.md b/ai-docs/architecture/hooks.md
index 381d0466..d7aaa3e2 100644
--- a/ai-docs/architecture/hooks.md
+++ b/ai-docs/architecture/hooks.md
@@ -410,8 +410,12 @@ that returns normally after emptying `messages` is applied as written, which is
`handlers/composed-handler-raw.test.ts` holds one test per failure mode above (X-1 to X-8), each with a
control, plus the in-place edit and the `warn` replacement built from the view.
-**The Gemini built-in** (`gemini/thought-signature`, `order: "pre"`, model names containing `gemini`
-or `google/`) keeps a cache keyed `"<provider>\0<modelId>"`, which reproduces the old per-handler
+**The Gemini built-in** (`gemini/thought-signature`, `order: "pre"`) is selected from catalog data
+when the handler has a catalog connection: a Gemini-API wire, or a model whose catalog vendor is
+`google` behind a gateway, whatever its (possibly opaque) id. This is `BuiltinHook.selectByUpstream`
+over the internal `UpstreamFacts` that `ComposedHandler` passes in the applicability scope; they never
+reach a hook context. Without a connection (custom endpoints, dynamic subscriptions) its `models`
+globs decide: names containing `gemini` or `google/`. It keeps a cache keyed `"<provider>\0<modelId>"`, which reproduces the old per-handler
scope. The old middleware's `afterResponse` had no production caller and was deleted, not migrated.
`statsNames()` reports the `statsName` of the built-in raw hooks active for a model, so the OTLP
`middleware_names` attribute is unchanged and user hooks never appear in it.
diff --git a/docs/advanced/hooks.md b/docs/advanced/hooks.md
index b3497918..8be2cd66 100644
--- a/docs/advanced/hooks.md
+++ b/docs/advanced/hooks.md
@@ -801,7 +801,7 @@ and requests from team judges, are not held at all.
| Id | What it does |
|---|---|
-| `gemini/thought-signature` | Raw. Carries Gemini thought signatures between turns, for model names containing `gemini` or `google/`. |
+| `gemini/thought-signature` | Raw. Carries Gemini thought signatures between turns: on a Gemini-API wire or a Google model behind a gateway, as the model catalog lists the route, and otherwise for model names containing `gemini` or `google/`. |
| `plan-mode/plan-file-path` | Foreign routes. In plan mode, puts the assigned plan-file path into the `ExitPlanMode` tool description, and moves a `Write`, `Edit` or `NotebookEdit` aimed at another file in the plan directory onto the assigned plan file. |
| `session-context/no-harness-echo` | Foreign routes. Adds a system note telling the model not to reproduce the session context Claude Code injects (hook output, reminders) in its answer. |
| `observer/divergence` | Foreign routes, off until `hooks.observer.enabled`: `claudish hooks list` shows the severity it would act with (`fix`) and marks it `inactive` while that setting is off. Asks a small local model whether a watched tool call breaks one of claudish's conformance rules, and logs the verdict to `~/.claudish/behavior-divergences.jsonl`. Advisory only. |
diff --git a/packages/cli/src/handlers/composed-handler-hooks.test.ts b/packages/cli/src/handlers/composed-handler-hooks.test.ts
index 237d46ec..0570334f 100644
--- a/packages/cli/src/handlers/composed-handler-hooks.test.ts
+++ b/packages/cli/src/handlers/composed-handler-hooks.test.ts
@@ -9,14 +9,16 @@
import { describe, expect, it } from "bun:test";
import { OpenAIAPIFormat } from "../adapters/openai-api-format.js";
-import { BUILTIN_HOOKS } from "../hooks/builtins/index.js";
+import { BUILTIN_HOOKS, builtinHooks } 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 { hookScopeOf } from "../hooks/request-stage.js";
import { withHooks } from "../hooks/response-seam.js";
+import { declaredConnection, declaredWire } from "../providers/declared-wire.js";
import type { ProviderTransport } from "../providers/transport/types.js";
import { ComposedHandler, type ComposedHandlerOptions } from "./composed-handler.js";
@@ -251,4 +253,39 @@ describe("ComposedHandler hook request stage ordering", () => {
expect(JSON.stringify(adapter.last?.built.messages)).toContain("APPENDED-BY-HOOK");
});
+
+ it("selects the Gemini built-in from the catalog connection, not the model name (0d40e396)", async () => {
+ const engine = new HookEngine({
+ registry: new HookRegistry(builtinHooks({}), [], undefined),
+ config: {},
+ hostMode: "other",
+ journalSink: () => {},
+ warn: () => {},
+ drainTelemetryOutbox: false,
+ });
+ const providerRequestHooks = async (model: string, vendor: string | undefined) => {
+ const connection = {
+ ...declaredConnection(
+ "openrouter",
+ model,
+ "http://127.0.0.1:1",
+ declaredWire("chat-completions", undefined)
+ ),
+ ...(vendor ? { vendor } : {}),
+ };
+ const handler = new ComposedHandler(makeFakeTransport("openrouter"), model, model, 8080, {
+ adapter: new RecordingOpenAIAPIFormat(model),
+ connection,
+ });
+ const c = fakeContext();
+ await handleOnce(handler, engine, makePayload(model), c);
+ return hookScopeOf(c)
+ ?.raw.hooks("providerRequest")
+ .map((a) => a.hook.id);
+ };
+ // an opaque gateway id whose catalog vendor is google
+ expect(await providerRequestHooks("or-7f3a2c", "google")).toEqual(["gemini/thought-signature"]);
+ // a connected route that is not Google: a `gemini` substring is not asked again
+ expect(await providerRequestHooks("gemini-lookalike", "openai")).toEqual([]);
+ });
});
diff --git a/packages/cli/src/handlers/composed-handler-wire.test.ts b/packages/cli/src/handlers/composed-handler-wire.test.ts
index 1cbc4693..e9541b3a 100644
--- a/packages/cli/src/handlers/composed-handler-wire.test.ts
+++ b/packages/cli/src/handlers/composed-handler-wire.test.ts
@@ -4,6 +4,10 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { Hono } from "hono";
import { OpenAIAPIFormat } from "../adapters/openai-api-format.js";
+import { builtinHooks } from "../hooks/builtins/index.js";
+import { HookEngine } from "../hooks/engine.js";
+import { HookRegistry } from "../hooks/registry.js";
+import { withHooks } from "../hooks/response-seam.js";
import type { DiskCacheV3 } from "../providers/all-models-cache.js";
import { resolveConnection } from "../providers/connection-resolver.js";
import { getProviderByName, toRemoteProvider } from "../providers/provider-definitions.js";
@@ -204,8 +208,19 @@ test.each(["google/gemini-3.8-flash", "opaque-model"])(
{ headers: { "content-type": "text/event-stream" } }
);
}) as typeof fetch;
+ // The thought signatures are carried by the built-in raw hook
+ // `gemini/thought-signature`, which runs inside the hook seam, as in the proxy.
+ const engine = new HookEngine({
+ registry: new HookRegistry(builtinHooks({}), [], undefined),
+ config: {},
+ hostMode: "other",
+ journalSink: () => {},
+ warn: () => {},
+ drainTelemetryOutbox: false,
+ });
+ const hooked = withHooks(handler, engine);
const app = new Hono();
- app.post("/", async (c) => handler.handle(c, await c.req.json()));
+ app.post("/", async (c) => hooked.handle(c, await c.req.json()));
const base = {
model,
stream: true,
diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.ts
index 38c2db07..bc4269fa 100644
--- a/packages/cli/src/handlers/composed-handler.ts
+++ b/packages/cli/src/handlers/composed-handler.ts
@@ -43,6 +43,7 @@ import { resolveQuotaAdapter } from "../auth/quota/registry.js";
import { PLAN_POLL_INTERVAL_MS } from "../auth/quota/types.js";
import { getHookEngine } from "../hooks/index.js";
import { type RawStreamTap, statsNames } from "../hooks/raw.js";
+import type { UpstreamFacts } from "../hooks/registry.js";
import { type HookRequestScope, isNativeRoute, requestHooksOf } from "../hooks/request-stage.js";
import {
getLogLevel,
@@ -396,7 +397,21 @@ export class ComposedHandler implements ModelHandler {
* appear, so the OTLP `llm.middleware` attribute is unchanged for them.
*/
private rawStatsNames(): string[] {
- return statsNames(getHookEngine(), this.routeInfo());
+ return statsNames(getHookEngine(), this.routeInfo(), this.upstreamFacts());
+ }
+
+ /**
+ * What the catalog says about this handler's upstream, for built-ins selected
+ * from data rather than by model name (`BuiltinHook.selectByUpstream`). Only
+ * with a catalog connection: without one the hooks' name globs decide.
+ */
+ private upstreamFacts(): UpstreamFacts | undefined {
+ const connection = this.options.connection;
+ if (!connection) return undefined;
+ return {
+ wireApi: connection.wire.status === "known" ? connection.wire.api : null,
+ vendor: connection.vendor ?? null,
+ };
}
/** Provider adapter — handles transport format (messages, tools, payload) */
@@ -1057,6 +1072,7 @@ export class ComposedHandler implements ModelHandler {
? await hooks.beginAttempt(c, {
claudeRequest,
route: this.routeInfo(),
+ upstream: this.upstreamFacts(),
model: typeof payload?.model === "string" ? payload.model : this.bareModelName,
stream: payload?.stream === true,
})
diff --git a/packages/cli/src/hooks/builtins/gemini-thought-signature.ts b/packages/cli/src/hooks/builtins/gemini-thought-signature.ts
index 3ffbf95c..505e7a4e 100644
--- a/packages/cli/src/hooks/builtins/gemini-thought-signature.ts
+++ b/packages/cli/src/hooks/builtins/gemini-thought-signature.ts
@@ -20,8 +20,13 @@
* - `providerRequest` (was `beforeRequest`) puts the cached array back on each
* assistant message whose tool calls it was recorded for.
*
- * Active when the bare model name contains `gemini` or `google/`, today's rule.
- * The cache is keyed per route (`<provider>\0<modelId>`): the middleware was
+ * Selection follows the middleware's last rule (claudish 0d40e396). With a
+ * catalog connection it is chosen from data: a Gemini-API wire, or a Google
+ * model behind a gateway (OpenRouter carries the signatures in
+ * `reasoning_details`); the model name, possibly an opaque gateway id, is not
+ * asked again (`selectByUpstream`). Without a connection (custom endpoints,
+ * dynamic subscriptions) the bare model name must contain `gemini` or `google/`
+ * (`models`). The cache is keyed per route (`<provider>\0<modelId>`): the middleware was
* constructed once per handler, i.e. per served model, and that scope is kept.
* Each per-route cache stays unbounded, as before.
*
@@ -83,6 +88,7 @@ export function createGeminiThoughtSignatureHook(): BuiltinHook {
"Sends Gemini's reasoning_details back with the assistant tool calls they were produced for",
order: "pre",
models: ["*gemini*", "*google/*"],
+ selectByUpstream: (upstream) => upstream.wireApi === "gemini" || upstream.vendor === "google",
routes: "all",
defaultSeverity: "fix",
statsName: GEMINI_THOUGHT_SIGNATURE_STATS_NAME,
diff --git a/packages/cli/src/hooks/raw.test.ts b/packages/cli/src/hooks/raw.test.ts
index 24977221..5e5fe402 100644
--- a/packages/cli/src/hooks/raw.test.ts
+++ b/packages/cli/src/hooks/raw.test.ts
@@ -131,6 +131,39 @@ describe("statsNames", () => {
expect(statsNames(null, route("gemini-2.5-flash"))).toEqual([]);
});
+ it("with a catalog connection, selects the Gemini built-in from the catalog data, not the name (0d40e396)", () => {
+ const engine = engineOf(builtinHooks({}));
+ const names = (modelId: string, wireApi: string | null, vendor: string | null) =>
+ statsNames(engine, route(modelId), { wireApi, vendor });
+ // a Google model behind a gateway, under an id with neither `gemini` nor `google/`
+ expect(names("or-7f3a2c", "chat-completions", "google")).toEqual(["GeminiThoughtSignature"]);
+ // a Gemini-API wire, vendor unpublished
+ expect(names("opaque-id", "gemini", null)).toEqual(["GeminiThoughtSignature"]);
+ // a connection that is neither: the name is not asked again
+ expect(names("gemini-lookalike", "chat-completions", "openai")).toEqual([]);
+ expect(names("google/whatever", null, null)).toEqual([]);
+ });
+
+ it("the raw tier of a connected attempt runs the Gemini built-in by the same rule", () => {
+ const engine = engineOf(builtinHooks({}));
+ const facts = { model: "x", stream: true, systemText: "", messages: [], tools: [] };
+ const meta = { model: "or-7f3a2c", provider: "openrouter" };
+ const google = new RawRequest(engine, route("or-7f3a2c"), meta, facts, {
+ wireApi: "chat-completions",
+ vendor: "google",
+ });
+ expect(google.hooks("providerRequest").map((a) => a.hook.id)).toEqual([
+ "gemini/thought-signature",
+ ]);
+ const other = new RawRequest(engine, route("gemini-lookalike"), meta, facts, {
+ wireApi: "chat-completions",
+ vendor: "openai",
+ });
+ expect(other.hooks("providerRequest")).toEqual([]);
+ // no connection: the name globs decide
+ expect(rawFor(engine, route("gemini-2.5-flash")).hooks("providerRequest")).toHaveLength(1);
+ });
+
it("never names a user hook, and an off built-in is not active", () => {
const user: UserHookInput = {
id: "hook:u/raw",
diff --git a/packages/cli/src/hooks/raw.ts b/packages/cli/src/hooks/raw.ts
index 1714eade..56e7240c 100644
--- a/packages/cli/src/hooks/raw.ts
+++ b/packages/cli/src/hooks/raw.ts
@@ -68,7 +68,7 @@ import type {
RequestFacts,
RouteInfo,
} from "./public.js";
-import type { ApplicableHook, HookEventName } from "./registry.js";
+import type { ApplicableHook, HookEventName, UpstreamFacts } from "./registry.js";
import { HOLD_CAP_BYTES, PING_FRAME } from "./seam-transform.js";
export type RawStage = "providerRequest" | "providerChunk" | "providerStreamEnd" | "response";
@@ -174,13 +174,18 @@ function rawOf(applicable: ApplicableHook): RawMiddleware {
* `middleware_names` for stats: the `statsName` of every BUILT-IN raw hook that
* applies to the route. User hooks never appear, so the OTLP `llm.middleware`
* attribute does not change for users with hooks. Empty when no engine is
- * loaded in this process.
+ * loaded in this process. `upstream` is the route's catalog facts, when the
+ * handler has a catalog connection.
*/
-export function statsNames(engine: HookEngine | null | undefined, route: RouteInfo): string[] {
+export function statsNames(
+ engine: HookEngine | null | undefined,
+ route: RouteInfo,
+ upstream?: UpstreamFacts
+): string[] {
if (!engine) return [];
const names: string[] = [];
for (const stage of RAW_STAGES) {
- for (const { hook } of engine.registry.applicable(`raw.${stage}`, { route })) {
+ for (const { hook } of engine.registry.applicable(`raw.${stage}`, { route, upstream })) {
if (hook.source === "builtin" && hook.statsName && !names.includes(hook.statsName)) {
names.push(hook.statsName);
}
@@ -209,12 +214,14 @@ export class RawRequest {
readonly route: RouteInfo,
readonly meta: JournalMeta,
/** The request as response-side hooks see it. */
- readonly facts: RequestFacts
+ readonly facts: RequestFacts,
+ /** Catalog facts about the route's upstream, when the handler has a catalog connection. */
+ readonly upstream?: UpstreamFacts
) {}
/** Applicable hooks for one stage, in effective order, minus breaker-disabled ones. */
hooks(stage: RawStage): ApplicableHook[] {
- return this.engine.select(`raw.${stage}`, { route: this.route });
+ return this.engine.select(`raw.${stage}`, { route: this.route, upstream: this.upstream });
}
/** How many raw `response` hooks apply (the seam log's `raw=<n>`). */
diff --git a/packages/cli/src/hooks/registry.ts b/packages/cli/src/hooks/registry.ts
index ab9bded5..4dac4c45 100644
--- a/packages/cli/src/hooks/registry.ts
+++ b/packages/cli/src/hooks/registry.ts
@@ -55,10 +55,29 @@ export function isProxyEvent(event: HookEventName): boolean {
return PROXY_EVENTS.has(event);
}
+/**
+ * What the model catalog says about the upstream a route reaches, when the
+ * handler serving it has a catalog connection. Internal to claudish: never on a
+ * hook context, so it adds nothing to the `claudish/hooks` contract.
+ */
+export interface UpstreamFacts {
+ /** The connection's wire API when the catalog knows it (`"gemini"`, `"chat-completions"`, …). */
+ wireApi: string | null;
+ /** The catalog vendor of the model (`"google"`, …), when known. */
+ vendor: string | null;
+}
+
/** A built-in hook. Its id carries no `hook:` prefix. */
export type BuiltinHook = HookDefinition & {
/** Name reported in stats `middleware_names` while this raw built-in is active. */
statsName?: string;
+ /**
+ * Selects the hook from catalog data instead of `models` when the route has a
+ * catalog connection (`ApplicabilityScope.upstream`). The model name, possibly
+ * an opaque gateway id, is then not asked again. Without a connection the
+ * `models` globs decide, as for every hook.
+ */
+ selectByUpstream?: (upstream: UpstreamFacts) => boolean;
};
/** A user hook as the loader produced it. */
@@ -89,6 +108,8 @@ export interface RegisteredHook {
/** Every event this hook declares a handler for, in a fixed order. */
events: ReadonlyArray<HookEventName>;
statsName?: string;
+ /** Built-ins only: see `BuiltinHook.selectByUpstream`. */
+ selectByUpstream?: (upstream: UpstreamFacts) => boolean;
}
/** A hook selected for one event, with its resolved severity. */
@@ -101,6 +122,8 @@ export interface ApplicableHook {
export interface ApplicabilityScope {
/** Proxy events: the route (models, routes, model-scoped severity keys). */
route?: RouteInfo;
+ /** Proxy events: catalog facts about the route's upstream, when it has a connection. */
+ upstream?: UpstreamFacts;
/** Session events: the model the caller asked for (model-scoped severity keys). */
sessionModel?: string;
}
@@ -127,7 +150,8 @@ function register(
id: string,
source: RegisteredHook["source"],
module?: string,
- statsName?: string
+ statsName?: string,
+ selectByUpstream?: (upstream: UpstreamFacts) => boolean
): RegisteredHook {
const hook: RegisteredHook = {
id,
@@ -142,6 +166,7 @@ function register(
};
if (module !== undefined) hook.module = module;
if (statsName !== undefined) hook.statsName = statsName;
+ if (selectByUpstream !== undefined) hook.selectByUpstream = selectByUpstream;
return hook;
}
@@ -157,7 +182,7 @@ export class HookRegistry {
) {
const ranked = [
...builtins.map((def, i) => ({
- hook: register(def, def.id, "builtin", undefined, def.statsName),
+ hook: register(def, def.id, "builtin", undefined, def.statsName, def.selectByUpstream),
key: [0, 0, i] as const,
})),
...users.map((u) => ({
@@ -199,15 +224,16 @@ export class HookRegistry {
/**
* Hooks that apply to `event` in this scope, in effective order: severity is
- * not `off`, and for proxy events the route's model matches `models` and its
- * nativeness matches `routes`.
+ * not `off`, and for proxy events the route's nativeness matches `routes` and
+ * its model matches `models` (or, for a built-in with `selectByUpstream` on a
+ * route with a catalog connection, the catalog facts select it).
*/
applicable(event: HookEventName, scope: ApplicabilityScope = {}): ApplicableHook[] {
const proxy = isProxyEvent(event);
const modelId = proxy ? scope.route?.modelId : scope.sessionModel;
const out: ApplicableHook[] = [];
for (const hook of this.declaring(event)) {
- if (proxy && scope.route && !routeMatches(hook, scope.route)) continue;
+ if (proxy && scope.route && !routeMatches(hook, scope.route, scope.upstream)) continue;
const severity = this.severityOf(hook, modelId);
if (severity === "off") continue;
out.push({ hook, severity });
@@ -216,8 +242,9 @@ export class HookRegistry {
}
}
-function routeMatches(hook: RegisteredHook, route: RouteInfo): boolean {
+function routeMatches(hook: RegisteredHook, route: RouteInfo, upstream?: UpstreamFacts): boolean {
if (hook.routes === "native" && !route.native) return false;
if (hook.routes === "foreign" && route.native) return false;
+ if (upstream && hook.selectByUpstream) return hook.selectByUpstream(upstream);
return hook.models.some((glob) => globMatches(glob, route.modelId));
}
diff --git a/packages/cli/src/hooks/request-stage.ts b/packages/cli/src/hooks/request-stage.ts
index eee6eae8..2565442d 100644
--- a/packages/cli/src/hooks/request-stage.ts
+++ b/packages/cli/src/hooks/request-stage.ts
@@ -61,7 +61,7 @@ import type {
RouteInfo,
} from "./public.js";
import { RawRequest } from "./raw.js";
-import type { ApplicableHook } from "./registry.js";
+import type { ApplicableHook, UpstreamFacts } from "./registry.js";
import { recordTelemetryTurn } from "./telemetry/aggregate.js";
/** Hono context key: the per-proxy `RequestHooks`, set by `withHooks`. */
@@ -168,6 +168,11 @@ export interface AttemptInput {
*/
claudeRequest: MutableClaudeRequest & { metadata?: unknown };
route: RouteInfo;
+ /**
+ * Catalog facts about the route's upstream, when the handler has a catalog
+ * connection. Built-ins with `selectByUpstream` are selected from them.
+ */
+ upstream?: UpstreamFacts;
/** The model as Claude Code asked for it. */
model: string;
stream: boolean;
@@ -251,7 +256,8 @@ export class HookRequestScope {
/** The request as the response-side hooks see it: the request chain's final view. */
readonly facts: RequestFacts,
readonly session: ProxySessionRef | null,
- response: ResponsePlan
+ response: ResponsePlan,
+ upstream?: UpstreamFacts
) {
this.held = held;
this.response = response;
@@ -259,7 +265,7 @@ export class HookRequestScope {
for (const h of response.interceptHooks) for (const t of h.tools) armed.add(t);
this.armedTools = armed;
this.rewriteClaimants = response.rewriteHooks.map((a) => a.hook.id);
- this.raw = new RawRequest(engine, route, meta, facts);
+ this.raw = new RawRequest(engine, route, meta, facts, upstream);
}
/**
@@ -286,7 +292,7 @@ export class HookRequestScope {
session: ProxySessionRef | null,
input: AttemptInput
): Promise<HookRequestScope> {
- const { claudeRequest, route } = input;
+ const { claudeRequest, route, upstream } = input;
const sessionId = extractSessionId(claudeRequest);
const meta: JournalMeta = sessionId
? { model: route.modelId, provider: route.provider, sessionId }
@@ -295,11 +301,11 @@ export class HookRequestScope {
// 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 requestHooks = engine.select("request", { route, upstream });
+ const toolCallHooks = engine.select("toolCall", { route, upstream });
+ const rewriteHooks = engine.select("responseRewrite", { route, upstream });
// responseEnd reads ctx.harness too: selected once, here, for the plan below
- const endHooks = engine.select("responseEnd", { route });
+ const endHooks = engine.select("responseEnd", { route, upstream });
const anyHook =
requestHooks.length + toolCallHooks.length + rewriteHooks.length + endHooks.length > 0;
@@ -454,7 +460,8 @@ export class HookRequestScope {
notes.map((n) => n.seq),
postFacts,
hookSession,
- plan
+ plan,
+ upstream
);
}