Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(ai): provider-agnostic ChatOpts.thinking 'off' for judges (#5331)

time-attack2fa824c39c27
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index 906d21da60..5493f0d516 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -19,6 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/fallback-hop-queue.ts`: the process-level queue for the first hop's `chat_fallback_hop` notice (at most one per process; type-only imports so every drain site loads it cheaply). Drained by stdio MCP dispatch, the CLI op notice channel (`src/cli/op-notices.ts`) and `finishCliTeardown`; never by HTTP, because the notice names models.
- `src/core/ai/chat-fallback-planes.ts`: where the effective `chat_fallback_chain` comes from, read without network, subprocess or inference. `readChatFallbackPlanes(db)` reads env `GBRAIN_CHAT_FALLBACK_CHAIN` > the config.json key > the DB row (`parseDbChatFallbackChain` in `config-db-merge.ts`) with the loader's rule that the first plane that speaks wins even when its value yields no chain, and returns the winner, shadowed values, unreadable planes and the `chat_fallback_on_refusal` value with its plane. `diagnoseChatFallbackEntry` checks one entry by presence: `provider:model` parse, known provider with chat, the provider's own credential (recipe env keys or `authPresent`; for `claude-cli` the binary on PATH or `GBRAIN_CLAUDE_CLI_BIN`), and a price when a key in `USER_CHAT_CAP_KEYS` sets a user cap. `chatFallbackRemovalFix` is the per-plane removal guidance (DB `gbrain config unset chat_fallback_chain` with `destructive` consent → `ask_user`; env/file are the user's, with the restart note). Consumers: the `chat_fallback_chain` doctor check and the `behavior_changes` notice.
- `src/core/ai/sdk-warnings.ts` — AI SDK provider warnings to stderr (#5892). The gateway calls `installAiSdkWarningWriter()` when it loads, which sets `globalThis.AI_SDK_LOG_WARNINGS` to a writer with the `ai` logger signature (`{ warnings, provider, model }`) that prints each warning in the SDK's own wording to stderr and never the SDK's `console.info` banner, which landed on stdout and broke `--json` output (the claude-cli model's v2-compat notice fires on every process's first call). A user-set value (`false` or a function) is kept. Tests: `ai-sdk-warnings.test.ts`, `json-stdout-ai-warnings.test.ts`.
+- `src/core/ai/thinking-off.ts`: the per-route mapping behind `ChatOpts.thinking: 'off'` (#5331). `thinkingOffNamespace(modelStr)` names the provider-options namespace that carries a per-call thinking switch (native `anthropic`, `deepseek`, and `openrouter` with a `deepseek/` model; every other route has none). `applyThinkingOff` sets `thinking: { type: 'disabled' }` there, replacing a configured thinking object so a configured `budgetTokens` never rides along, while siblings such as `cacheControl` survive; `chat()` applies it after the call-scoped `providerOptions` merge, on the resolved recipe. `thinkingOffMaxOutputTokens` keeps the requested cap where thinking really turns off, and raises a thinking-by-default route without a switch (claude-cli Claude 5, GLM, local reasoning families) to the thinking headroom, since reasoning bills against the cap and a judge-sized cap would return empty text; `chat()` reserves budget against that cap. Callers: the takes-quality and cross-modal judges and the synthesize triage judge. Pinned by `test/ai/chat-thinking-off.test.ts` (request bodies per route against a local stub) and `test/ai/gateway-chat.test.ts`.
- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId)` checks the PROVIDER's capability only (anthropic has no embedding touchpoint; voyage/ollama have no chat) and never gates on the model id. Recipe `models:` arrays are informational — default-model selection (`models[0]` for `--model <provider>` shorthand and env-ready pickers), guard-test fixtures for the repo's own hardcoded defaults, and `gbrain providers list` display — NOT a runtime allowlist, so frontier models newer than a recipe work without a recipe PR. A nonexistent id surfaces as the provider's own `model_not_found` at call time; `gbrain models doctor` live-probes the configured models for a pre-flight check. Exception: `gateway.rerank()` keeps its own model-list check because each listed reranker id maps to a known request/response wire shape. `embeddingDimsForModel` matches recipe `model_dims` keys exactly first, then case-insensitively with BOTH sides folded (configured ids arrive cased, and user-editable recipe tables can carry cased keys; without the fold a cased id would fall through to `default_dims` and `gbrain init` would build a wrong-width column), before falling back to `default_dims`.
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 279db7360f..f6b81ac727 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -37,6 +37,7 @@ export { splitByTokenBudget, capBatchItems, NO_BATCH_CAP_SUB_BATCH_ITEMS } from
import { BudgetTracker, type BudgetKind } from '../budget/budget-tracker.ts';
import { failedCallUsage, recordOnTracker } from './budget-record.ts';
import { chatWithFallback, normalizeChatFallbackChain } from './chat-fallback.ts';
+import { applyThinkingOff, thinkingOffMaxOutputTokens } from './thinking-off.ts';
import type {
AIGatewayConfig,
EmbedMultimodalOpts,
@@ -3058,6 +3059,13 @@ export interface ChatOpts {
responseSchema?: { name: string; description?: string; schema: Record<string, unknown> };
/** Caller purpose (`skillopt.judge`, …) stamped on the BudgetTracker ledger row. */
purpose?: string;
+ /**
+ * `'off'` turns thinking off for this call on routes with a per-call switch
+ * (native Anthropic, DeepSeek, OpenRouter DeepSeek), replacing a configured
+ * thinking object; elsewhere a thinking-by-default model keeps thinking and
+ * gets the thinking output headroom instead (see `thinking-off.ts`).
+ */
+ thinking?: 'off';
/**
* `false` pins the call to its own model: `chat_fallback_chain` is not
* consulted (see `chat-fallback.ts`). Judge, critic and eval call sites set
@@ -3450,7 +3458,10 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {
}
}
const estimatedInputTokens = estimateChatInputTokens(opts);
- const maxOutputTokens = opts.maxTokens ?? defaultMaxOutputTokens(modelStrEarly);
+ const requestedMaxOutputTokens = opts.maxTokens ?? defaultMaxOutputTokens(modelStrEarly);
+ const maxOutputTokens = opts.thinking === 'off'
+ ? thinkingOffMaxOutputTokens(modelStrEarly, requestedMaxOutputTokens, isThinkingModel(modelStrEarly), THINKING_MODEL_MAX_OUTPUT_TOKENS)
+ : requestedMaxOutputTokens;
const chatRecord = { requestedModelId: modelStrEarly, purpose: opts.purpose, label: 'gateway.chat' };
// TX5: reserve BEFORE the provider call. Throws BudgetExhausted on cost,
@@ -3559,6 +3570,7 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {
applyConfiguredChatProviderOptions(providerOptions, cfg, recipe.id, modelId);
// Call-scoped options merge last so they win over configured siblings.
providerOptions = deepMergeRecords(providerOptions, opts.providerOptions);
+ if (opts.thinking === 'off') applyThinkingOff(providerOptions, `${recipe.id}:${modelId}`);
// Derive ONE canonical cache-control value AFTER config merging and reuse
// it for every breakpoint (system block, last tool def, call-level). If
@@ -3631,7 +3643,7 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {
system: systemParam,
messages: toModelMessages(repairToolPairing(opts.messages)) as any,
tools: opts.tools && opts.tools.length > 0 ? tools : undefined,
- maxOutputTokens: opts.maxTokens ?? defaultMaxOutputTokens(modelStr),
+ maxOutputTokens,
...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),
output: out,
// v0.42.20.0 — default a chat timeout (composes with the caller's signal,
diff --git a/src/core/ai/thinking-off.ts b/src/core/ai/thinking-off.ts
new file mode 100644
index 0000000000..594cde0fdd
--- /dev/null
+++ b/src/core/ai/thinking-off.ts
@@ -0,0 +1,58 @@
+/**
+ * `ChatOpts.thinking: 'off'` (#5331): one provider-agnostic way for a call
+ * with a strict output contract and a small `maxTokens` (an eval judge) to
+ * opt out of a deployment-wide or model-default thinking mode, without the
+ * call site knowing each provider's option shape.
+ *
+ * Routes with a documented per-call switch get `thinking: { type: 'disabled' }`
+ * in their own provider-options namespace, REPLACING any configured thinking
+ * object (a merged `{type:'disabled', budgetTokens}` would be forwarded
+ * verbatim to an openai-compatible body) while sibling options such as
+ * Anthropic `cacheControl` survive:
+ * - native Anthropic (`anthropic`)
+ * - DeepSeek (`deepseek`; thinking is on by default for v4)
+ * - OpenRouter-hosted DeepSeek (`openrouter` with a `deepseek/` model)
+ * Every other route is left untouched. When such a route still thinks by
+ * default (`isThinkingModel`: Claude 5 behind claude-cli, a local reasoning
+ * family, GLM), the call cannot turn thinking off, so its output cap is raised
+ * to the thinking-model headroom: reasoning bills against the cap and a
+ * judge-sized cap would come back empty.
+ */
+
+import { splitProviderModelId } from '../model-id.ts';
+
+const THINKING_OFF_RECIPES: ReadonlySet<string> = new Set(['anthropic', 'deepseek']);
+
+/** The provider-options namespace that carries a per-call thinking switch for this route, or undefined. */
+export function thinkingOffNamespace(modelStr: string): string | undefined {
+ const { provider, model } = splitProviderModelId(modelStr);
+ if (!provider) return undefined;
+ if (THINKING_OFF_RECIPES.has(provider)) return provider;
+ if (provider === 'openrouter' && model.trim().toLowerCase().startsWith('deepseek/')) return provider;
+ return undefined;
+}
+
+/** Disable thinking in `providerOptions` for routes that have the switch; returns the same object. */
+export function applyThinkingOff(
+ providerOptions: Record<string, any>,
+ modelStr: string,
+): Record<string, any> {
+ const namespace = thinkingOffNamespace(modelStr);
+ if (!namespace) return providerOptions;
+ providerOptions[namespace] = { ...(providerOptions[namespace] ?? {}), thinking: { type: 'disabled' } };
+ return providerOptions;
+}
+
+/**
+ * Output cap for a `thinking: 'off'` call: the requested cap where thinking
+ * really turns off (or the model never thinks), else at least `headroom`.
+ */
+export function thinkingOffMaxOutputTokens(
+ modelStr: string,
+ requested: number,
+ thinksByDefault: boolean,
+ headroom: number,
+): number {
+ if (!thinksByDefault || thinkingOffNamespace(modelStr)) return requested;
+ return Math.max(requested, headroom);
+}
diff --git a/src/core/cross-modal-eval/runner.ts b/src/core/cross-modal-eval/runner.ts
index 805862a751..9170a24f94 100644
--- a/src/core/cross-modal-eval/runner.ts
+++ b/src/core/cross-modal-eval/runner.ts
@@ -237,6 +237,7 @@ async function callSlot(
maxTokens: opts.maxTokens,
abortSignal: opts.abortSignal,
allowFallback: false,
+ thinking: 'off',
});
const parsed = parseModelJSON(result.text ?? '');
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index 21e64967ef..b83a4db991 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -1902,15 +1902,10 @@ export function makeJudgeClient(verdictModel: string): JudgeClient | null {
maxTokens: params.max_tokens,
// DeepSeek v4 thinks by default and bills reasoning as OUTPUT tokens
// against max_tokens (recipe thinking_by_default, #4172) — same for
- // OpenRouter's DeepSeek hosts (#4758). The judge wants only the small
- // JSON verdict, so pin thinking off per-call — the openai-compatible
- // adapter spreads providerOptions[recipe.id] into the wire body,
- // where `thinking` is DeepSeek's documented knob.
- ...(v.parsed.providerId === 'deepseek'
- || (v.parsed.providerId === 'openrouter'
- && v.parsed.modelId.trim().toLowerCase().startsWith('deepseek/'))
- ? { providerOptions: { [v.parsed.providerId]: { thinking: { type: 'disabled' } } } }
- : {}),
+ // OpenRouter's DeepSeek hosts (#4758) and a configured Anthropic
+ // thinking mode. The judge wants only the small JSON verdict, so it
+ // turns thinking off per call (#5331; per-route mapping in thinking-off.ts).
+ thinking: 'off',
// #4077: a cancelled cycle tears down the in-flight judge call too.
abortSignal: options?.signal,
});
diff --git a/src/core/takes-quality-eval/runner.ts b/src/core/takes-quality-eval/runner.ts
index 0f16d0b038..cb12403b2a 100644
--- a/src/core/takes-quality-eval/runner.ts
+++ b/src/core/takes-quality-eval/runner.ts
@@ -129,6 +129,7 @@ async function callOneModel(
maxTokens: 2000,
abortSignal,
allowFallback: false,
+ thinking: 'off',
});
try {
const parsed = parseModelJSON(result.text);
diff --git a/test/ai/chat-thinking-off.test.ts b/test/ai/chat-thinking-off.test.ts
new file mode 100644
index 0000000000..28fe2f3e9d
--- /dev/null
+++ b/test/ai/chat-thinking-off.test.ts
@@ -0,0 +1,133 @@
+/**
+ * #5331: `ChatOpts.thinking: 'off'` turns thinking off per call without the
+ * call site knowing each provider's option shape.
+ *
+ * Drives the real gateway against a local stub of the Anthropic Messages and
+ * OpenAI-compatible chat completions APIs and asserts the request body that
+ * leaves gbrain, per route: native Anthropic (a configured thinking object is
+ * replaced, cache control survives), DeepSeek, OpenRouter DeepSeek, a route
+ * with no switch that does not think (unchanged), and a route with no switch
+ * that thinks by default (keeps thinking, gets the thinking output headroom).
+ */
+
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { chat, configureGateway, resetGateway, THINKING_MODEL_MAX_OUTPUT_TOKENS } from '../../src/core/ai/gateway.ts';
+
+let server: ReturnType<typeof Bun.serve>;
+let bodies: any[] = [];
+
+beforeAll(() => {
+ server = Bun.serve({
+ port: 0,
+ hostname: '127.0.0.1',
+ async fetch(req) {
+ const body = await req.json();
+ bodies.push(body);
+ if (new URL(req.url).pathname.endsWith('/messages')) {
+ return Response.json({
+ id: 'msg_stub', type: 'message', role: 'assistant', model: body.model,
+ content: [{ type: 'text', text: '{"ok":true}' }],
+ stop_reason: 'end_turn', usage: { input_tokens: 1, output_tokens: 1 },
+ });
+ }
+ return Response.json({
+ id: 'chatcmpl_stub', object: 'chat.completion', created: 0, model: body.model,
+ choices: [{ index: 0, message: { role: 'assistant', content: '{"ok":true}' }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
+ });
+ },
+ });
+});
+
+afterAll(() => {
+ server.stop(true);
+ resetGateway();
+});
+
+beforeEach(() => {
+ bodies = [];
+ resetGateway();
+});
+
+function configure(model: string, providerChatOptions?: Record<string, Record<string, unknown>>): void {
+ const base = `http://127.0.0.1:${server.port}/v1`;
+ configureGateway({
+ chat_model: model,
+ env: {
+ ANTHROPIC_API_KEY: 'stub', ANTHROPIC_BASE_URL: base,
+ DEEPSEEK_API_KEY: 'stub', OPENROUTER_API_KEY: 'stub', ZHIPUAI_API_KEY: 'stub', GROQ_API_KEY: 'stub',
+ },
+ base_urls: { deepseek: base, openrouter: base, zhipu: base, groq: base },
+ ...(providerChatOptions ? { provider_chat_options: providerChatOptions } : {}),
+ });
+}
+
+const judgeCall = (model: string, extra: Record<string, unknown> = {}) => chat({
+ model,
+ system: 'Return strict JSON.',
+ messages: [{ role: 'user', content: 'score this' }],
+ maxTokens: 2000,
+ thinking: 'off',
+ ...extra,
+});
+
+describe("chat({ thinking: 'off' }) request bodies (#5331)", () => {
+ test('native Anthropic: a configured thinking budget is replaced, configured cache control survives', async () => {
+ configure('anthropic:claude-sonnet-4-6', {
+ anthropic: { thinking: { type: 'enabled', budgetTokens: 4000 }, cacheControl: { type: 'ephemeral', ttl: '1h' } },
+ });
+
+ await judgeCall('anthropic:claude-sonnet-4-6', { cacheSystem: true });
+
+ expect(bodies).toHaveLength(1);
+ expect(bodies[0].thinking?.type).not.toBe('enabled');
+ expect(JSON.stringify(bodies[0])).not.toContain('budget_tokens');
+ expect(bodies[0].max_tokens).toBe(2000);
+ expect(JSON.stringify(bodies[0].system)).toContain('"ttl":"1h"');
+ });
+
+ test('native Anthropic without the switch keeps the configured thinking budget', async () => {
+ configure('anthropic:claude-sonnet-4-6', {
+ anthropic: { thinking: { type: 'enabled', budgetTokens: 4000 } },
+ });
+
+ await chat({ model: 'anthropic:claude-sonnet-4-6', messages: [{ role: 'user', content: 'x' }], maxTokens: 8000 });
+
+ expect(bodies[0].thinking).toEqual({ type: 'enabled', budget_tokens: 4000 });
+ });
+
+ test('DeepSeek (thinks by default) gets its documented thinking switch', async () => {
+ configure('deepseek:deepseek-v4-flash');
+
+ await judgeCall('deepseek:deepseek-v4-flash');
+
+ expect(bodies[0].thinking).toEqual({ type: 'disabled' });
+ expect(bodies[0].max_tokens).toBe(2000);
+ });
+
+ test('OpenRouter-hosted DeepSeek gets the same switch', async () => {
+ configure('openrouter:deepseek/deepseek-v4-flash-0731');
+
+ await judgeCall('openrouter:deepseek/deepseek-v4-flash-0731');
+
+ expect(bodies[0].thinking).toEqual({ type: 'disabled' });
+ });
+
+ test('a route with no switch that does not think is unchanged', async () => {
+ configure('groq:llama-3.3-70b-versatile');
+
+ await judgeCall('groq:llama-3.3-70b-versatile');
+
+ expect('thinking' in bodies[0]).toBe(false);
+ expect(bodies[0].max_tokens).toBe(2000);
+ });
+
+ test('a thinking-by-default model with no switch keeps thinking and gets the thinking output headroom', async () => {
+ configure('zhipu:glm-5.3');
+
+ await judgeCall('zhipu:glm-5.3');
+
+ expect('thinking' in bodies[0]).toBe(false);
+ expect(bodies[0].max_tokens).toBe(THINKING_MODEL_MAX_OUTPUT_TOKENS);
+ });
+});
diff --git a/test/ai/gateway-chat.test.ts b/test/ai/gateway-chat.test.ts
index d581f6056b..25c7a36848 100644
--- a/test/ai/gateway-chat.test.ts
+++ b/test/ai/gateway-chat.test.ts
@@ -404,6 +404,52 @@ describe('chat touchpoint — provider_chat_options passthrough', () => {
});
});
+ test('anthropic call-scoped thinking override wins without dropping configured siblings (#5331)', async () => {
+ // From @kvnloo's #5972: the generic providerOptions merge is a per-call
+ // seam where call-scoped leaves win and configured siblings survive.
+ const providerOptions = await captureProviderOptions({
+ chat_model: 'anthropic:claude-sonnet-4-6',
+ provider_chat_options: {
+ anthropic: {
+ thinking: { type: 'adaptive' },
+ cacheControl: { type: 'ephemeral', ttl: '1h' },
+ },
+ },
+ env: { ANTHROPIC_API_KEY: 'fake' },
+ }, {
+ providerOptions: { anthropic: { thinking: { type: 'disabled' } } },
+ });
+
+ expect(providerOptions).toEqual({
+ anthropic: {
+ thinking: { type: 'disabled' },
+ cacheControl: { type: 'ephemeral', ttl: '1h' },
+ },
+ });
+ });
+
+ test("thinking: 'off' replaces a configured thinking object instead of merging into it (#5331)", async () => {
+ // A deep merge of { type: 'disabled' } into { type: 'enabled', budgetTokens }
+ // keeps budgetTokens; the switch replaces the whole thinking object.
+ const providerOptions = await captureProviderOptions({
+ chat_model: 'anthropic:claude-sonnet-4-6',
+ provider_chat_options: {
+ anthropic: {
+ thinking: { type: 'enabled', budgetTokens: 4000 },
+ cacheControl: { type: 'ephemeral', ttl: '1h' },
+ },
+ },
+ env: { ANTHROPIC_API_KEY: 'fake' },
+ }, { thinking: 'off' });
+
+ expect(providerOptions).toEqual({
+ anthropic: {
+ thinking: { type: 'disabled' },
+ cacheControl: { type: 'ephemeral', ttl: '1h' },
+ },
+ });
+ });
+
test('anthropic cacheControl survives provider_chat_options merging', async () => {
// gbrain#2490: this call-level cacheControl is real (not a no-op) —
// @ai-sdk/anthropic serializes it as the Anthropic API's documented
diff --git a/test/cycle/synthesize-gateway-adapter.test.ts b/test/cycle/synthesize-gateway-adapter.test.ts
index 79311d91e0..4558c7fbd2 100644
--- a/test/cycle/synthesize-gateway-adapter.test.ts
+++ b/test/cycle/synthesize-gateway-adapter.test.ts
@@ -17,6 +17,8 @@
import { describe, test, expect, afterEach } from 'bun:test';
import {
__setChatTransportForTests,
+ __setGenerateTextTransportForTests,
+ configureGateway,
resetGateway,
type ChatResult,
} from '../../src/core/ai/gateway.ts';
@@ -27,6 +29,7 @@ import type { DiscoveredTranscript } from '../../src/core/cycle/transcript-disco
afterEach(() => {
__setChatTransportForTests(null);
+ __setGenerateTextTransportForTests(null);
resetGateway();
});
@@ -171,8 +174,8 @@ describe('JudgeClient.create — gateway routing + shape adapter', () => {
expect(receivedSystem).toBe('judge system prompt');
// Gateway model gets the anthropic: prefix normalized
expect(receivedModel).toBe('anthropic:claude-haiku-4-5-20251001');
- // The thinking-disable pin is DeepSeek-only; other providers must not
- // receive call-scoped provider options from the judge.
+ // The judge asks for `thinking: 'off'`, not provider options: the
+ // per-route mapping happens inside chat() (thinking-off.ts).
expect(receivedProviderOptions).toBeUndefined();
// Anthropic.Message shape returned
expect(result.content?.[0]?.type).toBe('text');
@@ -180,71 +183,44 @@ describe('JudgeClient.create — gateway routing + shape adapter', () => {
});
});
- test('A3b: DeepSeek verdict judge disables thinking for its own call only', async () => {
- // DeepSeek v4 models think by default and bill reasoning as OUTPUT tokens
- // against max_tokens (recipe thinking_by_default, gbrain#4172). The triage
- // judge wants the plain JSON verdict, so it pins thinking off per-call via
- // ChatOpts.providerOptions instead of burning budget on reasoning.
- // No DEEPSEEK_API_KEY needed: non-anthropic construction skips the key
- // probe (A9) and the transport is stubbed.
- const judge = makeJudgeClient('deepseek:deepseek-v4-flash');
+ /** Provider options the judge's call hands the AI SDK (after per-route `thinking: 'off'` mapping). */
+ async function judgeSdkProviderOptions(model: string): Promise<Record<string, any> | undefined> {
+ configureGateway({ chat_model: model, env: { DEEPSEEK_API_KEY: 'fake-deepseek', OPENROUTER_API_KEY: 'fake-openrouter' } });
+ let captured: Record<string, any> | undefined;
+ __setGenerateTextTransportForTests((async (args: any) => {
+ captured = args.providerOptions;
+ return { content: [{ type: 'text', text: WORTH_PROCESSING_JSON }], finishReason: 'stop', usage: { inputTokens: 10, outputTokens: 20 } };
+ }) as any);
+ const judge = makeJudgeClient(model);
expect(judge).not.toBeNull();
-
- let receivedProviderOptions: Record<string, Record<string, unknown>> | undefined;
- __setChatTransportForTests(async (opts): Promise<ChatResult> => {
- receivedProviderOptions = opts.providerOptions;
- return {
- text: WORTH_PROCESSING_JSON,
- blocks: [],
- stopReason: 'end',
- usage: { input_tokens: 10, output_tokens: 20, cache_read_tokens: 0, cache_creation_tokens: 0 },
- model: 'deepseek:deepseek-v4-flash',
- providerId: 'deepseek',
- };
- });
-
await judge!.create({
- model: 'deepseek:deepseek-v4-flash',
+ model,
max_tokens: 1024,
system: 'judge system prompt',
messages: [{ role: 'user', content: 'judge this' }],
});
+ return captured;
+ }
- expect(receivedProviderOptions).toEqual({
+ test('A3b: DeepSeek verdict judge disables thinking for its own call only', async () => {
+ // DeepSeek v4 models think by default and bill reasoning as OUTPUT tokens
+ // against max_tokens (recipe thinking_by_default, gbrain#4172). The triage
+ // judge wants the plain JSON verdict, so it turns thinking off per call
+ // (ChatOpts.thinking 'off', #5331), which reaches the SDK as DeepSeek's knob.
+ // No DEEPSEEK_API_KEY needed: non-anthropic construction skips the key
+ // probe (A9) and the transport is stubbed.
+ expect(await judgeSdkProviderOptions('deepseek:deepseek-v4-flash')).toEqual({
deepseek: { thinking: { type: 'disabled' } },
});
});
test('A3c: OpenRouter DeepSeek verdict judge disables thinking for its own call only', async () => {
// Same contract as A3b for the OpenRouter-hosted DeepSeek routes (#4758):
- // the recipe declares thinking_by_default for `deepseek/…`, so the judge
- // pins thinking off per-call under the openrouter providerOptions
- // namespace (the openai-compatible adapter spreads
- // providerOptions[recipe.id] into the wire body).
- const judge = makeJudgeClient('openrouter:deepseek/deepseek-v4-flash-0731');
- expect(judge).not.toBeNull();
-
- let receivedProviderOptions: Record<string, Record<string, unknown>> | undefined;
- __setChatTransportForTests(async (opts): Promise<ChatResult> => {
- receivedProviderOptions = opts.providerOptions;
- return {
- text: WORTH_PROCESSING_JSON,
- blocks: [],
- stopReason: 'end',
- usage: { input_tokens: 10, output_tokens: 20, cache_read_tokens: 0, cache_creation_tokens: 0 },
- model: 'openrouter:deepseek/deepseek-v4-flash-0731',
- providerId: 'openrouter',
- };
- });
-
- await judge!.create({
- model: 'openrouter:deepseek/deepseek-v4-flash-0731',
- max_tokens: 1024,
- system: 'judge system prompt',
- messages: [{ role: 'user', content: 'judge this' }],
- });
-
- expect(receivedProviderOptions).toEqual({
+ // the recipe declares thinking_by_default for `deepseek/…`, so the switch
+ // lands under the openrouter providerOptions namespace (the
+ // openai-compatible adapter spreads providerOptions[recipe.id] into the
+ // wire body).
+ expect(await judgeSdkProviderOptions('openrouter:deepseek/deepseek-v4-flash-0731')).toEqual({
openrouter: { thinking: { type: 'disabled' } },
});
});
@@ -252,30 +228,7 @@ describe('JudgeClient.create — gateway routing + shape adapter', () => {
test('A3d: OpenRouter non-DeepSeek routes receive no thinking pin', async () => {
// The pin is family-scoped: an anthropic/ route via OR must not get a
// DeepSeek-shaped `thinking` knob sprayed into its wire body.
- const judge = makeJudgeClient('openrouter:anthropic/claude-haiku-4.5');
- expect(judge).not.toBeNull();
-
- let receivedProviderOptions: Record<string, Record<string, unknown>> | undefined;
- __setChatTransportForTests(async (opts): Promise<ChatResult> => {
- receivedProviderOptions = opts.providerOptions;
- return {
- text: WORTH_PROCESSING_JSON,
- blocks: [],
- stopReason: 'end',
- usage: { input_tokens: 10, output_tokens: 20, cache_read_tokens: 0, cache_creation_tokens: 0 },
- model: 'openrouter:anthropic/claude-haiku-4.5',
- providerId: 'openrouter',
- };
- });
-
- await judge!.create({
- model: 'openrouter:anthropic/claude-haiku-4.5',
- max_tokens: 1024,
- system: 'judge system prompt',
- messages: [{ role: 'user', content: 'judge this' }],
- });
-
- expect(receivedProviderOptions).toBeUndefined();
+ expect(await judgeSdkProviderOptions('openrouter:anthropic/claude-haiku-4.5')).toBeUndefined();
});
test('A4: ChatResult.text → Anthropic.Message.content[0].text mapping', async () => {
diff --git a/test/e2e/cross-modal-eval.test.ts b/test/e2e/cross-modal-eval.test.ts
index df4d6f8453..619dcdf9ac 100644
--- a/test/e2e/cross-modal-eval.test.ts
+++ b/test/e2e/cross-modal-eval.test.ts
@@ -73,9 +73,9 @@ function makeChatStub(scoresBySlot: Record<string, number[]>) {
describe('gbrain eval cross-modal — judge call shape (#4338 data boundary)', () => {
test('callSlot sends EVALUATOR_SYSTEM_PROMPT as `system` and the data-bounded prompt as the user turn', async () => {
- const seen: Array<{ system?: string; messages?: Array<{ role: string; content: string }> }> = [];
- const chatStub = mock(async (opts: { model?: string; system?: string; messages?: Array<{ role: string; content: string }> }) => {
- seen.push({ system: opts.system, messages: opts.messages });
+ const seen: Array<{ system?: string; messages?: Array<{ role: string; content: string }>; thinking?: string }> = [];
+ const chatStub = mock(async (opts: { model?: string; system?: string; messages?: Array<{ role: string; content: string }>; thinking?: string }) => {
+ seen.push({ system: opts.system, messages: opts.messages, thinking: opts.thinking });
const model = opts.model ?? '';
return {
text: JSON.stringify({ scores: { goal: { score: 8 }, depth: { score: 8 } }, overall: 8, improvements: ['1. x'] }),
@@ -110,6 +110,8 @@ describe('gbrain eval cross-modal — judge call shape (#4338 data boundary)', (
expect(call.messages![0]!.role).toBe('user');
expect(call.messages![0]!.content).toContain('<task_to_grade>');
expect(call.messages![0]!.content).toContain('<candidate_output>\nsample output content\n</candidate_output>');
+ // #5331: the judge turns thinking off so its JSON fits the output cap.
+ expect(call.thinking).toBe('off');
}
});
});