Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(judges): per-model thinking capability table; price judge preflights at the cap chat() sends (W9F item 5)
time-attackc56d963224d7
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex 9c2ddb60e7..da16e49962 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -24,7 +24,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/thinking-off.ts`: the per-route mapping behind `ChatOpts.thinking: 'off'` (#5331). `thinkingOffControl(modelStr)` is the per-model capability table: the provider-options namespace and keys to set, and whether they turn reasoning off (`disables`) or only set its floor. Full off: native `anthropic`, `deepseek`, `openrouter` with a `deepseek/` model (`thinking: { type: 'disabled' }`), Gemini 2.5 Flash/Flash-Lite (`thinkingConfig.thinkingBudget: 0`), OpenAI gpt-5.1/5.2/5.4/5.5/5.6 (`reasoningEffort: 'none'`). Floor: Gemini 2.5 Pro (`thinkingBudget: 128`), Gemini 3.x (`thinkingLevel` `minimal`, or `low` on 3.7/3.8 Flash and 3.x Pro, where `minimal` is a 400), gpt-5/-mini/-nano (`minimal`), o-series (`low`). Other Gemini 3+ and OpenAI reasoning ids, gpt-6 included (the pinned @ai-sdk/openai drops its effort), get no option. Only native recipes get an option; the two Google fields are never sent together. `applyThinkingOff` sets the keys, replacing a configured value under the same key while siblings such as `cacheControl` or `promptCacheKey` survive; `chat()` applies it after the call-scoped `providerOptions` merge, on the resolved recipe. `thinkingOffMaxOutputTokens` keeps the requested cap where reasoning turns off and raises a route that keeps reasoning (a floor row, or no row and `isThinkingModel`) to the thinking headroom. gateway.ts `thinkingOffOutputCap(model, requested)` wraps it for `chat()` and for the takes-quality and cross-modal preflight estimates, so they price the cap the call sends. Callers: those two judges and the synthesize triage judge. Rows were checked live on 2026-10-07 (`docs/w9f/lane-j.md`). Pinned by `test/ai/chat-thinking-off.test.ts` (request bodies per route against a local stub, estimate parity per default panel model) 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/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.mdindex 9290ad3fc1..e2108d8134 100644--- a/docs/architecture/key-files/evaluation.md+++ b/docs/architecture/key-files/evaluation.md@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cross-modal-eval/receipt-write.ts` — wraps `fs.writeFileSync` with `mkdirSync({recursive:true})` ahead of every write (`gbrainPath()` does NOT auto-mkdir).-- `src/core/cross-modal-eval/runner.ts` — orchestrator. The judge prompt pins the exact `scores` JSON keys per dimension (`dimensionScoreKey` = the label before the em-dash) so judges cannot invent spellings; aggregate.ts's normalization is the backstop. `buildPrompt` wraps the task and the candidate in `<task_to_grade>`/`<candidate_output>` data blocks, and `neutralizeClosingTag` rewrites every closing form of those tags inside the untrusted text (case-insensitive, whitespace-tolerant) to the visibly-escaped `<\/tag`, so a candidate carrying its own closing delimiter cannot terminate the block and land text outside the data boundary — the post-candidate grading-only instruction stays the last thing the judge reads. `callSlot` sends `EVALUATOR_SYSTEM_PROMPT` as `system` and the bounded prompt as the single user turn. Each cycle runs `Promise.allSettled([gwChat(slotA), gwChat(slotB), gwChat(slotC)])` (bare allSettled, no rate-leases for the CLI path). Stops early on PASS or INCONCLUSIVE; runs up to 3 cycles. Default slots: `openai:gpt-5.2` / `anthropic:claude-opus-4-7` / `deepseek:deepseek-v4-pro`. `estimateCost()` prices via the canonical model-pricing table; `test/cross-modal-default-slots.test.ts` pins recipe support, pricing coverage, and three distinct providers.+- `src/core/cross-modal-eval/runner.ts` — orchestrator. The judge prompt pins the exact `scores` JSON keys per dimension (`dimensionScoreKey` = the label before the em-dash) so judges cannot invent spellings; aggregate.ts's normalization is the backstop. `buildPrompt` wraps the task and the candidate in `<task_to_grade>`/`<candidate_output>` data blocks, and `neutralizeClosingTag` rewrites every closing form of those tags inside the untrusted text (case-insensitive, whitespace-tolerant) to the visibly-escaped `<\/tag`, so a candidate carrying its own closing delimiter cannot terminate the block and land text outside the data boundary — the post-candidate grading-only instruction stays the last thing the judge reads. `callSlot` sends `EVALUATOR_SYSTEM_PROMPT` as `system` and the bounded prompt as the single user turn. Each cycle runs `Promise.allSettled([gwChat(slotA), gwChat(slotB), gwChat(slotC)])` (bare allSettled, no rate-leases for the CLI path). Stops early on PASS or INCONCLUSIVE; runs up to 3 cycles. Default slots: `openai:gpt-5.2` / `anthropic:claude-opus-4-7` / `deepseek:deepseek-v4-pro`. `estimateCost()` prices via the canonical model-pricing table, each slot at the output cap its thinking-off call sends (`thinkingOffOutputCap`; a raised cap is named in the notes, which both the single-run and batch banners print); `test/cross-modal-default-slots.test.ts` pins recipe support, pricing coverage, and three distinct providers.- `src/core/eval/cycle-default.ts` — single source of truth for the eval cycle-count default. Exports `DEFAULT_CYCLES_TTY = 3`, `DEFAULT_CYCLES_NONTTY = 1`, `resolveCycleDefault(explicit, isTty): {cycles, usedNonTtyDefault}`, and `cycleDefaultSuffix(r)` (returns ` (non-interactive default; --cycles N for more)` only when the non-TTY default was applied, else `''`). Consumed by `eval-cross-modal.ts`, `eval-takes-quality.ts` (run + regress), and `takes-quality-eval/runner.ts` (core uses only the constant — library stays TTY-agnostic; the CLI owns the TTY=3 upgrade + banner annotation). `eval-suspected-contradictions.ts` applies the same transparency to its `$5`/`$1` budget default via a `budgetUsdExplicit` flag (the budget is overwritten in-place so explicitness can't be inferred post-hoc). Not shared with `resolveWorkersWithClamp` (different domain, no engine, no dedup). Pinned by `test/eval/cycle-default.test.ts`, `test/eval-suspected-contradictions-budget-default.test.ts`.@@ -30,7 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/eval/ranked-docs.ts` — dependency-free page-level ranking primitive shared by the retrieval eval harness, NamedThingBench, and the qrels correctness gate. `dedupeRankedKeys()` preserves the first/best occurrence of each `${source_id}::${slug}` or slug key before any cutoff, so repeated chunks neither inflate relevance gain nor consume document ranks. Precision retains its fixed-`k` denominator; Recall and nDCG are structurally bounded to `[0,1]`. Pinned across `test/eval.test.ts`, `test/retrieval-quality-harness.test.ts`, `test/bench/qrels-file.test.ts`, and `test/bench/correctness-gate.test.ts`.- `src/core/takes-quality-eval/pricing.ts` — budget pricing for `eval takes-quality run`. `getPricing(model, overrides?)` returns the operator rate registered with `gbrain pricing set` (`pricing.overrides`), else the canonical rate (`canonicalLookup`), else null; schema `{input_per_1m, output_per_1m}`. Every canonically priced model is gateable. Miss policy (new models must run): with no `--budget-usd` an unpriced model runs with a warning naming the registration command and its spend is not counted; under a user cap the runner refuses before any call with `no_pricing` (`unpricedUnderCapError`), whose fix is `gbrain pricing set <model> --input … --output … --source …` (no-pricing.ts). Rates are never copied here; `test/model-pricing.test.ts` pins equality with canonical for every canonical key.-- `src/core/takes-quality-eval/runner.ts` — `eval takes-quality run` orchestrator: samples takes, sends the rendered rubric prompt to every panel model per cycle (`allowFallback: false`, `thinking: 'off'`), and re-asks each malformed slot once with the same model and sample plus the validator's error (`slotFormatFailure` in `aggregate.ts`: `parse_failed` including an empty reply, or `incomplete_scores`; provider errors and valid low scores never re-run). A correction is priced against `--budget-usd` before it is sent and recorded `corrected: null` with `skipped_reason` when it does not fit or the run was aborted; it replaces the first attempt only when it validates. The receipt carries `protocol_version: TAKES_QUALITY_PROTOCOL_VERSION` (2), `correction_selection_rule` and `corrections` (additive at `schema_version: 1`); `regress.ts` lists a protocol change among the dissimilar inputs. Pinned by `test/eval-takes-quality-runner.serial.test.ts` and `test/eval-takes-quality-regress.test.ts`.+- `src/core/takes-quality-eval/runner.ts` — `eval takes-quality run` orchestrator: samples takes, sends the rendered rubric prompt to every panel model per cycle (`allowFallback: false`, `thinking: 'off'`), and re-asks each malformed slot once with the same model and sample plus the validator's error (`slotFormatFailure` in `aggregate.ts`: `parse_failed` including an empty reply, or `incomplete_scores`; provider errors and valid low scores never re-run). The per-cycle projection and each correction price `judgeCallCostUsd(model)`: 5k input tokens plus the output cap the call sends (`thinkingOffOutputCap(model, JUDGE_MAX_TOKENS)`; a raised cap is announced on stderr). A correction is priced against `--budget-usd` before it is sent and recorded `corrected: null` with `skipped_reason` when it does not fit or the run was aborted; it replaces the first attempt only when it validates. The receipt carries `protocol_version: TAKES_QUALITY_PROTOCOL_VERSION` (2), `correction_selection_rule` and `corrections` (additive at `schema_version: 1`); `regress.ts` lists a protocol change among the dissimilar inputs. Pinned by `test/eval-takes-quality-runner.serial.test.ts` and `test/eval-takes-quality-regress.test.ts`.- `src/eval/brainbench/` + `src/commands/eval-brainbench.ts` — BrainBench, the cross-harness memory conformance suite (`gbrain eval brainbench`; methodology in `docs/eval/BRAINBENCH.md`). `types.ts` carries the PUBLISHED interchange shapes (fixture/gold/result/baseline — mirrored as JSON Schemas in `evals/brainbench/schema/`; breaking changes bump the schema versions). `fixtures.ts`: strict loader/validator + corpus `fixtures_hash` (covers fixture AND gold files); a `gold` key inside a fixture turn is a validation error — gold is SEALED in the gold dir and adapters only ever see sanitized `PublicTurn`s. `seed.ts`: fail-fast hermetic seeding (`importFromContent` noEmbed + NULL-embedding `insertFact`; any non-`imported` status ⇒ `SeedError` ⇒ fixture `seed_failed` ⇒ run exit 2). `adapters/shared.ts`: ONE `runReflexPipeline` all three adapters drive with declarative config (pointer budget, suppression mode) — cross-harness comparability is structural; `openclaw.ts` (seam `production`, the shipped pipeline), `claude-code.ts` (seam `production`; drives the shipped `gbrain hook user-prompt` path end-to-end — fixture turns become `UserPromptSubmit` stdin JSON, synthesized Claude Code JSONL transcripts feed the real window parse + cross-turn dedupe, and resolution rides a run-scoped resolve-IPC server with the real shared secret; bench-pinned deviations disclosed in `docs/eval/BRAINBENCH.md`: generous `userPromptDeadlineMs`, push-failure banner suppressed), `codex.ts` (seam `contract`; static entity-index preamble whose slugs deliberately don't count as injections + ≤1 per-turn fragment; fixture conversations round-trip through the real rollout format + the shipped parser `src/core/transcripts/codex.ts` for turn selection — fragment DELIVERY remains harness-shaped until a shipped codex injection path lands). `metrics/`: know-to-ask (+false-fire anti-gaming companion), push (micro-averaged P/R), write-back (drives the PRODUCTION conversation→facts pipeline via the injectable-extractor seam; gold extractor in CI, real extractor under `--llm`), continuity (writer→reader pairs on a shared brain through DIFFERENT adapters; pointer-injection OR stored-fact keyword probe). `harness.ts`: ONE in-memory PGLite per run + `resetTables` between fixtures (longmemeval engine-sharing pattern); read-only suites share one seeding across all adapters; emits per-(harness×suite) cells + re-scoreable turn rows; `source_isolation_violations` counted per turn and gated at zero. `scoreboard.ts`: markdown render, canonical diff-stable committed baseline (4-decimal rounding, sorted keys, receipts excluded), `compareBaselines` with main-baseline governance — same-hash count-aware gate vs corpus-bless mode (the committed baseline must byte-match the run; regressions vs main require a `justification`). The CLI brings its own PGLite (cli.ts routes before connectEngine), writes `--out` as the canonical CI artifact, and terminates via an explicit grace-tick `process.exit(verdict)` (0 pass / 1 regression / 2 error) because PGLite stomps `process.exitCode` and Bun discards queued stdout on exit. `runBrainBenchCore()` is the in-process entry `eval run-all` uses (one record per sweep, `EvalRunRecord` schema_version 3, `mode: 'n/a'`). Pinned by `test/brainbench-*.test.ts` + `test/eval-brainbench-e2e.slow.test.ts`. System One arm: `--decide*` flags (`src/eval/decide-eval-flags.ts`) configure the benchmark brain; the claude-code adapter captures the turn-context `decide.recall_needed` meta onto `turn_rows[].decide`, the result gains a `decide` block, and `--update-baseline` is refused for an arm (`test/eval-brainbench-decide.serial.test.ts`).diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex eca6853315..ae2bcbf3dc 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 2213 ratchet grown v0.46.x per-providsrc/commands/extract.ts 2567 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scansrc/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codessrc/commands/serve-http.ts 926 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts)-src/core/ai/gateway.ts 4425 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts)+src/core/ai/gateway.ts 4427 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts)src/commands/sync.ts 512 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event fieldsrc/core/cycle.ts 3254 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts)src/core/cycle/synthesize.ts 3207 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg)diff --git a/src/commands/eval-cross-modal.ts b/src/commands/eval-cross-modal.tsindex c4a4e46dfb..f9ae31e9e4 100644--- a/src/commands/eval-cross-modal.ts+++ b/src/commands/eval-cross-modal.ts@@ -807,6 +807,9 @@ async function runBatchMode(parsed: ParsedArgs, opts: RunCrossModalOpts): Promis`for ${rows.length} questions x ${cycles} cycle(s) x 3 slots ` +`(per-question ~$${perQuestion.perRunMaxUSD.toFixed(2)}, concurrent=${concurrent})\n`,);+ for (const note of perQuestion.notes) {+ process.stderr.write(`[eval cross-modal batch] note: ${note}\n`);+ }if (estTotal > maxUsd && !parsed.yes) {process.stderr.write(`Error: estimated cost $${estTotal.toFixed(2)} exceeds --max-usd $${maxUsd.toFixed(2)}; ` +diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 90a43c8067..91428742c5 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -2805,6 +2805,8 @@ export function isThinkingModel(modelStr: string | undefined): boolean {export function defaultMaxOutputTokens(modelStr: string | undefined): number {return isThinkingModel(modelStr) ? THINKING_MODEL_MAX_OUTPUT_TOKENS : DEFAULT_MAX_OUTPUT_TOKENS;}+/** The cap `chat({ thinking: 'off', maxTokens: requested })` sends (thinking-off.ts table); judge preflight estimates price with it. */+export const thinkingOffOutputCap = (modelStr: string, requested: number): number => thinkingOffMaxOutputTokens(modelStr, requested, isThinkingModel(modelStr), THINKING_MODEL_MAX_OUTPUT_TOKENS);/*** Deep-serialize a tool output into a plain JSON value for the AI SDK v6@@ -3458,7 +3460,7 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {}}const estimatedInputTokens = estimateChatInputTokens(opts);- const maxOutputTokens = thinkingOffMaxOutputTokens(modelStrEarly, opts.maxTokens ?? defaultMaxOutputTokens(modelStrEarly), opts.thinking === 'off' && isThinkingModel(modelStrEarly), THINKING_MODEL_MAX_OUTPUT_TOKENS);+ const maxOutputTokens = opts.thinking === 'off' ? thinkingOffOutputCap(modelStrEarly, opts.maxTokens ?? defaultMaxOutputTokens(modelStrEarly)) : (opts.maxTokens ?? defaultMaxOutputTokens(modelStrEarly));// TX5: reserve BEFORE the provider call (BudgetExhausted on cost, runtime,// or no_pricing under a user cap) with the pre-resolution model id. record()diff --git a/src/core/ai/thinking-off.ts b/src/core/ai/thinking-off.tsindex e7c1253973..0ee1784ebe 100644--- a/src/core/ai/thinking-off.ts+++ b/src/core/ai/thinking-off.ts@@ -4,56 +4,143 @@* 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.+ * `thinkingOffControl` is the per-model capability table: which+ * provider-options namespace carries the per-call option, what to put there,+ * and whether that option turns reasoning fully off or only sets its floor.+ * The runtime (`applyThinkingOff`, `thinkingOffMaxOutputTokens`, both used by+ * `chat()`) and the judge cost estimates (`thinkingOffOutputCap` in+ * gateway.ts) read the same table, so a preflight prices the cap the call+ * sends.+ *+ * Routes whose option turns reasoning off keep the requested cap:+ * - native Anthropic (`anthropic`) and DeepSeek (`deepseek`; thinking is on+ * by default for v4): `thinking: { type: 'disabled' }`+ * - OpenRouter-hosted DeepSeek (`openrouter` with a `deepseek/` model): same+ * - Gemini 2.5 Flash and Flash-Lite: `thinkingConfig: { thinkingBudget: 0 }`+ * - OpenAI models that accept `reasoningEffort: 'none'` (gpt-5.1, 5.2, 5.4,+ * 5.5 and the 5.6 family)+ * Routes that cannot turn reasoning off send their floor and get the+ * thinking-model output headroom, because reasoning bills against the cap and+ * a judge-sized cap could come back empty:+ * - Gemini 2.5 Pro: `thinkingBudget: 128` (never `thinkingLevel`)+ * - Gemini 3.x: the lowest `thinkingLevel` the model accepts (`minimal` is+ * a 400 on 3.7/3.8 Flash and 3.x Pro, so those get `low`; never a budget)+ * - OpenAI gpt-5/-mini/-nano (`minimal`) and the o-series (`low`)+ * - other Gemini 3+ and OpenAI reasoning ids: no option (an unsupported+ * level or effort is a 400), headroom only. That includes gpt-6: the+ * pinned @ai-sdk/openai (3.0.58) does not know gpt-6 is a reasoning model+ * and drops `reasoningEffort` with a warning, so no option would arrive.+ * The option REPLACES any configured value under the same key: a configured+ * Anthropic `{type:'enabled', budgetTokens}` would otherwise be forwarded+ * verbatim, and a configured Google `thinkingConfig.thinkingLevel` merged+ * with `thinkingBudget` is a 400. Sibling options such as Anthropic+ * `cacheControl` or OpenAI `promptCacheKey` survive. A provider namespace+ * alone is not an off switch: only the native recipes listed here get an+ * option. Every other route is untouched; when it still thinks by default+ * (`isThinkingModel`: Claude 5 behind claude-cli, a local reasoning family,+ * GLM) its cap gets the headroom.+ *+ * Gemini rows follow Google's generateContent thinking docs; OpenAI rows+ * follow the reasoning guide. Both were checked live on 2026-10-07+ * (docs/w9f/lane-j.md).*/import { splitProviderModelId } from '../model-id.ts';-const THINKING_OFF_RECIPES: ReadonlySet<string> = new Set(['anthropic', 'deepseek']);+export interface ThinkingOffControl {+ /** The provider-options namespace and the keys set there; absent when the route has no per-call option. */+ set?: { namespace: string; options: Record<string, unknown> };+ /** True when `set` turns reasoning fully off; false when the model keeps reasoning, so the cap gets headroom. */+ disables: boolean;+}++const THINKING_DISABLED: Record<string, unknown> = { thinking: { type: 'disabled' } };++const GEMINI_ID_RE = /^gemini-(\d+(?:\.\d+)?)-(flash-lite|flash|pro)(?:-|$)/;+const GEMINI_NON_CHAT_RE = /-(?:image|tts|audio|live|transcribe|computer-use)(?:-|$)/;+const GEMINI_THINKING_LEVEL_FLOOR: Readonly<Record<string, 'minimal' | 'low'>> = {+ '3-flash': 'minimal',+ '3.5-flash': 'minimal',+ '3.6-flash': 'minimal',+ '3.7-flash': 'low',+ '3.8-flash': 'low',+ '3.1-flash-lite': 'minimal',+ '3.5-flash-lite': 'minimal',+ '3-pro': 'low',+ '3.1-pro': 'low',+};++function googleControl(model: string): ThinkingOffControl | undefined {+ if (GEMINI_NON_CHAT_RE.test(model)) return undefined;+ const m = GEMINI_ID_RE.exec(model);+ if (!m) return /^gemini-(?:flash|flash-lite|pro)-latest$/.test(model) ? { disables: false } : undefined;+ const version = Number.parseFloat(m[1]!);+ const tier = m[2]!;+ if (version < 2.5) return undefined;+ if (version === 2.5) {+ return tier === 'pro'+ ? { set: { namespace: 'google', options: { thinkingConfig: { thinkingBudget: 128 } } }, disables: false }+ : { set: { namespace: 'google', options: { thinkingConfig: { thinkingBudget: 0 } } }, disables: true };+ }+ if (version < 3) return { disables: false };+ const level = GEMINI_THINKING_LEVEL_FLOOR[`${m[1]}-${tier}`];+ return level+ ? { set: { namespace: 'google', options: { thinkingConfig: { thinkingLevel: level } } }, disables: false }+ : { disables: false };+}++const OPENAI_DATE_SUFFIX = '(?:-\\d{4}-\\d{2}-\\d{2})?$';+const OPENAI_EFFORT_NONE_RE = new RegExp(`^gpt-(?:5\\.[1245](?:-mini|-nano)?|5\\.6-(?:luna|sol|terra))${OPENAI_DATE_SUFFIX}`);+const OPENAI_EFFORT_MINIMAL_RE = new RegExp(`^gpt-5(?:-mini|-nano)?${OPENAI_DATE_SUFFIX}`);+const OPENAI_EFFORT_LOW_RE = new RegExp(`^(?:o1|o3|o3-mini|o4-mini)${OPENAI_DATE_SUFFIX}`);+const OPENAI_REASONING_RE = /^(?:gpt-(?:[5-9]|\d{2,})|o\d)/;+const OPENAI_NON_REASONING_RE = /-chat(?:-|$)/;++function openaiControl(model: string): ThinkingOffControl | undefined {+ const effort = (reasoningEffort: string) => ({ namespace: 'openai', options: { reasoningEffort } });+ if (OPENAI_EFFORT_NONE_RE.test(model)) return { set: effort('none'), disables: true };+ if (OPENAI_EFFORT_MINIMAL_RE.test(model)) return { set: effort('minimal'), disables: false };+ if (OPENAI_EFFORT_LOW_RE.test(model)) return { set: effort('low'), disables: false };+ if (OPENAI_REASONING_RE.test(model) && !OPENAI_NON_REASONING_RE.test(model)) return { disables: false };+ return undefined;+}-/** 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);+/** The thinking-off capability of a route, or undefined when the table has no row for it. */+export function thinkingOffControl(modelStr: string): ThinkingOffControl | undefined {+ const { provider, model: rawModel } = splitProviderModelId(modelStr);if (!provider) return undefined;- if (THINKING_OFF_RECIPES.has(provider)) return provider;- if (provider === 'openrouter' && model.trim().toLowerCase().startsWith('deepseek/')) return provider;+ const model = rawModel.trim().toLowerCase();+ if (provider === 'anthropic' || provider === 'deepseek') return { set: { namespace: provider, options: THINKING_DISABLED }, disables: true };+ if (provider === 'openrouter') return model.startsWith('deepseek/') ? { set: { namespace: provider, options: THINKING_DISABLED }, disables: true } : undefined;+ if (provider === 'google') return googleControl(model);+ if (provider === 'openai') return openaiControl(model);return undefined;}-/** Disable thinking in `providerOptions` for routes that have the switch; returns the same object. */+/** Set the route's thinking-off option in `providerOptions`; 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' } };+ const set = thinkingOffControl(modelStr)?.set;+ if (!set) return providerOptions;+ providerOptions[set.namespace] = { ...(providerOptions[set.namespace] ?? {}), ...set.options };return providerOptions;}/**- * A call's output cap: the requested cap, unless `thinking: 'off'` was asked- * of a thinking-by-default model (`offOnThinkingModel`) whose route has no- * switch, which gets at least `headroom`.+ * A `thinking: 'off'` call's output cap: the requested cap where the route's+ * option turns reasoning off, otherwise at least `headroom` for a model that+ * keeps reasoning (a table row without a full off switch, or a route with no+ * row whose model thinks by default, `thinkingByDefault`).*/export function thinkingOffMaxOutputTokens(modelStr: string,requested: number,- offOnThinkingModel: boolean,+ thinkingByDefault: boolean,headroom: number,): number {- if (!offOnThinkingModel || thinkingOffNamespace(modelStr)) return requested;- return Math.max(requested, headroom);+ const control = thinkingOffControl(modelStr);+ const keepsReasoning = control ? !control.disables : thinkingByDefault;+ return keepsReasoning ? Math.max(requested, headroom) : requested;}diff --git a/src/core/cross-modal-eval/runner.ts b/src/core/cross-modal-eval/runner.tsindex 9170a24f94..4ba5d13e91 100644--- a/src/core/cross-modal-eval/runner.ts+++ b/src/core/cross-modal-eval/runner.ts@@ -15,7 +15,7 @@import { join } from 'path';-import { chat as gwChat } from '../ai/gateway.ts';+import { chat as gwChat, thinkingOffOutputCap } from '../ai/gateway.ts';import type { ChatMessage } from '../ai/gateway.ts';import { aggregate } from './aggregate.ts';import type { AggregateResult, SlotResult } from './aggregate.ts';@@ -399,21 +399,29 @@ export function estimateCost(slots: SlotConfig[], cycles: number, maxTokens: num// file" note (cost estimate may be low), preserving prior behavior.const ESTIMATED_INPUT_TOKENS = 5000;+ // Each slot is priced at the output cap its thinking-off call sends, which+ // is above `maxTokens` on a route that cannot turn reasoning off.const notes: string[] = [];let perCycle = 0;+ let largestCap = maxTokens;for (const slot of slots) {+ const cap = thinkingOffOutputCap(slot.model, maxTokens);+ largestCap = Math.max(largestCap, cap);+ if (cap !== maxTokens) {+ notes.push(`(${slot.model}): cannot turn thinking off; its calls send and are priced at a ${cap}-token output cap`);+ }const p = canonicalLookup(slot.model);if (!p) {notes.push(`(${slot.model}): no pricing on file; cost estimate may be low`);continue;}- const cost = (ESTIMATED_INPUT_TOKENS * p.input + maxTokens * p.output) / 1_000_000;+ const cost = (ESTIMATED_INPUT_TOKENS * p.input + cap * p.output) / 1_000_000;perCycle += cost;}return {perCycleUSD: round2(perCycle),perRunMaxUSD: round2(perCycle * cycles),- perCallTokens: ESTIMATED_INPUT_TOKENS + maxTokens,+ perCallTokens: ESTIMATED_INPUT_TOKENS + largestCap,notes,};}diff --git a/src/core/takes-quality-eval/runner.ts b/src/core/takes-quality-eval/runner.tsindex b1bc7fba4b..a7f19ac9c1 100644--- a/src/core/takes-quality-eval/runner.ts+++ b/src/core/takes-quality-eval/runner.ts@@ -20,7 +20,7 @@* (the CLI wires receipt-write after the runner returns).*/import type { BrainEngine } from '../engine.ts';-import { chat } from '../ai/gateway.ts';+import { chat, thinkingOffOutputCap } from '../ai/gateway.ts';import { parseModelJSON } from '../eval-shared/json-repair.ts';import { aggregate, slotFormatFailure, type SlotResult, type AggregateResult } from './aggregate.ts';import {@@ -34,6 +34,7 @@ import {} from './receipt-name.ts';import type { TakesQualityCorrection, TakesQualityReceipt } from './receipt.ts';import { estimateCost, getPricing, unpricedUnderCapError, unpricedWarning } from './pricing.ts';+import type { PricingOverrides } from '../budget/reservation-cost.ts';import { loadPricingOverrides } from '../budget/budget-tracker.ts';import { DEFAULT_CYCLES_NONTTY } from '../eval/cycle-default.ts';@@ -54,6 +55,16 @@ function correctionPrompt(prompt: string, formatFailure: string): string {'Do not invent scores when evidence is insufficient.';}+/** Each judge call's requested output cap; `judgeCallCostUsd` prices the cap `chat()` actually sends. */+export const JUDGE_MAX_TOKENS = 2000;+/** Assumed judge prompt size for the pre-call projection (real usage is counted after each call). */+const PROJECTED_INPUT_TOKENS = 5000;++/** Worst-case price of one judge call (or correction) to `modelId`, or null when unpriced. */+export function judgeCallCostUsd(modelId: string, overrides?: PricingOverrides): number | null {+ return estimateCost(modelId, PROJECTED_INPUT_TOKENS, thinkingOffOutputCap(modelId, JUDGE_MAX_TOKENS), overrides);+}+export const DEFAULT_MODEL_PANEL = ['openai:gpt-5.2','anthropic:claude-opus-4-7',@@ -137,7 +148,7 @@ async function callOneModel(model: modelId,system: 'You are an evaluation judge. Return strict JSON in the requested shape. Do not include markdown fences in your final response.',messages: [{ role: 'user', content: systemPrompt }],- maxTokens: 2000,+ maxTokens: JUDGE_MAX_TOKENS,abortSignal,allowFallback: false,thinking: 'off',@@ -188,6 +199,13 @@ export async function runEval(engine: BrainEngine, opts: RunOpts = {}): Promise<if (budgetUsd !== null) throw unpricedUnderCapError(m, budgetUsd);process.stderr.write(`${unpricedWarning(m)}\n`);}+ for (const m of models) {+ const cap = thinkingOffOutputCap(m, JUDGE_MAX_TOKENS);+ if (cap === JUDGE_MAX_TOKENS) continue;+ process.stderr.write(+ `[eval takes-quality] note: ${m} cannot turn thinking off; its calls send and are priced at a ${cap}-token output cap\n`,+ );+ }// Sample the corpus.const { takesText, nTakes } = await sampleTakesAsText(engine, { limit, slugPrefix: opts.slugPrefix ?? null });@@ -213,14 +231,14 @@ export async function runEval(engine: BrainEngine, opts: RunOpts = {}): Promise<break;}- // Project the worst-case spend for this cycle if budget is set. We- // assume the prompt is ~5k tokens input + ~2k output per model; the- // cap fires before the call if the projection would exceed remaining- // budget. (Real usage is captured post-call from result.usage.)+ // Project the worst-case spend for this cycle if budget is set: ~5k+ // input tokens plus the output cap each call sends. The cap fires before+ // the call if the projection would exceed remaining budget. (Real usage+ // is captured post-call from result.usage.)if (budgetUsd !== null) {let projected = 0;for (const m of models) {- projected += estimateCost(m, 5000, 2000, overrides) ?? 0;+ projected += judgeCallCostUsd(m, overrides) ?? 0;}if (cumulativeCost + projected > budgetUsd) {process.stderr.write(@@ -256,7 +274,7 @@ export async function runEval(engine: BrainEngine, opts: RunOpts = {}): Promise<if (!firstError) continue;const m = models[i]!;const skipped = opts.abortSignal?.aborted ? 'aborted'- : budgetUsd !== null && cumulativeCost + (estimateCost(m, 5000, 2000, overrides) ?? 0) > budgetUsd ? 'budget'+ : budgetUsd !== null && cumulativeCost + (judgeCallCostUsd(m, overrides) ?? 0) > budgetUsd ? 'budget': null;if (skipped) {corrections.push({ cycle, modelId: m, first_error: firstError, corrected: null, skipped_reason: skipped });diff --git a/test/ai/chat-thinking-off.test.ts b/test/ai/chat-thinking-off.test.tsindex 28fe2f3e9d..3a0fe18c5c 100644--- a/test/ai/chat-thinking-off.test.ts+++ b/test/ai/chat-thinking-off.test.ts@@ -8,21 +8,50 @@* 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).+ *+ * W9F item 5: the per-model capability table for native Google (the+ * generateContent request is caught at `fetch`, since the Google route takes+ * no base URL) and native OpenAI (Responses API on the stub): a full off+ * switch keeps the requested cap, a floor gets the headroom, the two Google+ * thinking fields are never sent together, and a configured value under the+ * same key is replaced.*/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';+import { applyThinkingOff } from '../../src/core/ai/thinking-off.ts';let server: ReturnType<typeof Bun.serve>;let bodies: any[] = [];+const realFetch = globalThis.fetch;beforeAll(() => {+ globalThis.fetch = (async (input: any, init?: any) => {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;+ if (!url.startsWith('https://generativelanguage.googleapis.com/')) return realFetch(input, init);+ bodies.push(JSON.parse(String(init?.body)));+ return Response.json({+ candidates: [{ content: { role: 'model', parts: [{ text: '{"ok":true}' }] }, finishReason: 'STOP' }],+ usageMetadata: { promptTokenCount: 1, candidatesTokenCount: 1, totalTokenCount: 2 },+ });+ }) as typeof fetch;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('/responses')) {+ return Response.json({+ id: 'resp_stub', object: 'response', created_at: 0, status: 'completed', model: body.model,+ output: [{+ type: 'message', id: 'msg_stub', status: 'completed', role: 'assistant',+ content: [{ type: 'output_text', text: '{"ok":true}', annotations: [] }],+ }],+ incomplete_details: null,+ usage: { input_tokens: 1, output_tokens: 1, input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 0 } },+ });+ }if (new URL(req.url).pathname.endsWith('/messages')) {return Response.json({id: 'msg_stub', type: 'message', role: 'assistant', model: body.model,@@ -40,6 +69,7 @@ beforeAll(() => {});afterAll(() => {+ globalThis.fetch = realFetch;server.stop(true);resetGateway();});@@ -55,6 +85,7 @@ function configure(model: string, providerChatOptions?: Record<string, Record<stchat_model: model,env: {ANTHROPIC_API_KEY: 'stub', ANTHROPIC_BASE_URL: base,+ OPENAI_API_KEY: 'stub', OPENAI_BASE_URL: base, GOOGLE_GENERATIVE_AI_API_KEY: 'stub',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 },@@ -131,3 +162,158 @@ describe("chat({ thinking: 'off' }) request bodies (#5331)", () => {expect(bodies[0].max_tokens).toBe(THINKING_MODEL_MAX_OUTPUT_TOKENS);});});++describe("chat({ thinking: 'off' }) capability table: native Google and OpenAI (W9F item 5)", () => {+ const H = THINKING_MODEL_MAX_OUTPUT_TOKENS;+ const google: Array<[string, Record<string, unknown> | undefined, number]> = [+ ['gemini-2.5-flash', { thinkingBudget: 0 }, 2000],+ ['gemini-2.5-flash-lite', { thinkingBudget: 0 }, 2000],+ ['gemini-2.5-pro', { thinkingBudget: 128 }, H],+ ['gemini-3.8-flash', { thinkingLevel: 'low' }, H],+ ['gemini-3.7-flash', { thinkingLevel: 'low' }, H],+ ['gemini-3.6-flash', { thinkingLevel: 'minimal' }, H],+ ['gemini-3.5-flash', { thinkingLevel: 'minimal' }, H],+ ['gemini-3-flash-preview', { thinkingLevel: 'minimal' }, H],+ ['gemini-3.5-flash-lite', { thinkingLevel: 'minimal' }, H],+ ['gemini-3.1-pro-preview', { thinkingLevel: 'low' }, H],+ ['gemini-4-flash', undefined, H],+ ];+ for (const [model, thinkingConfig, cap] of google) {+ test(`google:${model} sends ${JSON.stringify(thinkingConfig ?? null)} at a ${cap}-token cap`, async () => {+ configure(`google:${model}`);++ await judgeCall(`google:${model}`);++ expect(bodies).toHaveLength(1);+ expect(bodies[0].generationConfig.thinkingConfig).toEqual(thinkingConfig);+ expect(bodies[0].generationConfig.maxOutputTokens).toBe(cap);+ });+ }++ test('a configured Google thinkingConfig is replaced, so the two thinking fields never meet', async () => {+ configure('google:gemini-2.5-flash', { google: { thinkingConfig: { thinkingLevel: 'high', includeThoughts: true } } });++ await judgeCall('google:gemini-2.5-flash');++ expect(bodies[0].generationConfig.thinkingConfig).toEqual({ thinkingBudget: 0 });+ });++ test('a Google call without thinking off is unchanged', async () => {+ configure('google:gemini-2.5-flash');++ await chat({ model: 'google:gemini-2.5-flash', messages: [{ role: 'user', content: 'x' }], maxTokens: 2000 });++ expect(bodies[0].generationConfig.thinkingConfig).toBeUndefined();+ expect(bodies[0].generationConfig.maxOutputTokens).toBe(2000);+ });++ const openai: Array<[string, string | undefined, number]> = [+ ['gpt-5.2', 'none', 2000],+ ['gpt-5.4-mini', 'none', 2000],+ ['gpt-5.5', 'none', 2000],+ ['gpt-5.6-terra', 'none', 2000],+ ['gpt-5', 'minimal', H],+ ['gpt-5-mini', 'minimal', H],+ ['o3', 'low', H],+ ['gpt-6-sol', undefined, H],+ ['gpt-6-astra', undefined, H],+ ['gpt-5.5-pro', undefined, H],+ ['gpt-6.2-sol', undefined, H],+ ['gpt-5.2-chat-latest', undefined, 2000],+ ['gpt-4o-mini', undefined, 2000],+ ];+ for (const [model, effort, cap] of openai) {+ test(`openai:${model} sends reasoning effort ${effort ?? '(none set)'} at a ${cap}-token cap`, async () => {+ configure(`openai:${model}`);++ await judgeCall(`openai:${model}`);++ expect(bodies).toHaveLength(1);+ expect(bodies[0].reasoning?.effort).toBe(effort);+ expect(bodies[0].max_output_tokens).toBe(cap);+ });+ }++ test('OpenAI: a configured reasoning effort is replaced and the prompt cache key survives', async () => {+ configure('openai:gpt-5.2', { openai: { reasoningEffort: 'high' } });++ await judgeCall('openai:gpt-5.2');++ expect(bodies[0].reasoning).toEqual({ effort: 'none' });+ expect(typeof bodies[0].prompt_cache_key).toBe('string');+ });++ test('provider-options snapshot per model id: only native recipes get an option', () => {+ const snapshot = Object.fromEntries([+ 'google:gemini-2.5-flash', 'google:gemini-2.5-pro', 'google:gemini-3.8-flash', 'google:gemini-3.6-flash',+ 'google:gemini-flash-latest', 'google:gemini-2.0-flash', 'google:gemini-2.5-flash-preview-tts',+ 'openai:gpt-5.2', 'openai:gpt-5', 'openai:gpt-6-astra', 'openai:gpt-4o-mini',+ 'openrouter:openai/gpt-5.2', 'openrouter:google/gemini-2.5-flash', 'litellm:gemini-2.5-flash',+ ].map(m => [m, applyThinkingOff({}, m)]));+ expect(snapshot).toEqual({+ 'google:gemini-2.5-flash': { google: { thinkingConfig: { thinkingBudget: 0 } } },+ 'google:gemini-2.5-pro': { google: { thinkingConfig: { thinkingBudget: 128 } } },+ 'google:gemini-3.8-flash': { google: { thinkingConfig: { thinkingLevel: 'low' } } },+ 'google:gemini-3.6-flash': { google: { thinkingConfig: { thinkingLevel: 'minimal' } } },+ 'google:gemini-flash-latest': {},+ 'google:gemini-2.0-flash': {},+ 'google:gemini-2.5-flash-preview-tts': {},+ 'openai:gpt-5.2': { openai: { reasoningEffort: 'none' } },+ 'openai:gpt-5': { openai: { reasoningEffort: 'minimal' } },+ 'openai:gpt-6-astra': {},+ 'openai:gpt-4o-mini': {},+ 'openrouter:openai/gpt-5.2': {},+ 'openrouter:google/gemini-2.5-flash': {},+ 'litellm:gemini-2.5-flash': {},+ });+ });+});++describe('judge preflight estimates price the cap chat() sends (W9F item 5)', () => {+ const sentCap = (body: any): number => body.max_tokens ?? body.max_output_tokens ?? body.generationConfig?.maxOutputTokens;+ const round2 = (n: number) => Math.round(n * 100) / 100;++ test('takes-quality: each default panel model, and a route that keeps reasoning', async () => {+ const tq = await import('../../src/core/takes-quality-eval/runner.ts');+ const { estimateCost } = await import('../../src/core/takes-quality-eval/pricing.ts');+ const sent: Record<string, number> = {};+ for (const m of [...tq.DEFAULT_MODEL_PANEL, 'openai:gpt-5']) {+ bodies = [];+ configure(m);+ await judgeCall(m, { maxTokens: tq.JUDGE_MAX_TOKENS });+ sent[m] = sentCap(bodies[0]);+ expect(tq.judgeCallCostUsd(m)).toBe(estimateCost(m, 5000, sent[m]!));+ }+ expect(sent).toEqual({+ 'openai:gpt-5.2': 2000,+ 'anthropic:claude-opus-4-7': 2000,+ 'google:gemini-2.5-flash': 2000,+ 'openai:gpt-5': THINKING_MODEL_MAX_OUTPUT_TOKENS,+ });+ });++ test('cross-modal: each default slot, and a slot that keeps reasoning, named in the notes', async () => {+ const cm = await import('../../src/core/cross-modal-eval/runner.ts');+ const { canonicalLookup } = await import('../../src/core/model-pricing.ts');+ const sent: Record<string, number> = {};+ for (const slot of [...cm.DEFAULT_SLOTS, { id: 'X', model: 'openai:gpt-5' }]) {+ bodies = [];+ configure(slot.model);+ await judgeCall(slot.model, { maxTokens: 4000 });+ sent[slot.model] = sentCap(bodies[0]);+ const p = canonicalLookup(slot.model)!;+ const est = cm.estimateCost([slot], 1, 4000);+ expect(est.perCycleUSD).toBe(round2((5000 * p.input + sent[slot.model]! * p.output) / 1_000_000));+ expect(est.perCallTokens).toBe(5000 + sent[slot.model]!);+ }+ expect(sent).toEqual({+ 'openai:gpt-5.2': 4000,+ 'anthropic:claude-opus-4-7': 4000,+ 'deepseek:deepseek-v4-pro': 4000,+ 'openai:gpt-5': THINKING_MODEL_MAX_OUTPUT_TOKENS,+ });+ expect(cm.estimateCost([{ id: 'X', model: 'openai:gpt-5' }], 1, 4000).notes)+ .toEqual([`(openai:gpt-5): cannot turn thinking off; its calls send and are priced at a ${THINKING_MODEL_MAX_OUTPUT_TOKENS}-token output cap`]);+ expect(cm.estimateCost(cm.DEFAULT_SLOTS, 1, 4000).notes).toEqual([]);+ });+});diff --git a/test/eval-takes-quality-runner.serial.test.ts b/test/eval-takes-quality-runner.serial.test.tsindex c7f1e70029..02e7f234a1 100644--- a/test/eval-takes-quality-runner.serial.test.ts+++ b/test/eval-takes-quality-runner.serial.test.ts@@ -211,6 +211,20 @@ describe('runner — budget cap (codex review #4)', () => {// the cycle ran, not the verdict.expect(r.receipt.cycles_run).toBe(1);});++ test('a model that cannot turn thinking off is projected at the output cap its call sends (W9F item 5)', async () => {+ // openai:gpt-5 ($5/$20) keeps a `minimal` reasoning floor under thinking+ // off, so chat() sends the 32000-token headroom cap, not 2000. Projected:+ // 2000-token pricing = $0.065 (fits $0.30), 32000-token = $0.665 (does not).+ chatHandler = async (_opts) => {+ throw new Error('chat should not be called when the projection exceeds the cap');+ };++ const r = await runEval(engine, { limit: 5, cycles: 1, models: ['openai:gpt-5'], budgetUsd: 0.30 });++ expect(r.budgetAborted).toBe(true);+ expect(r.receipt.cycles_run).toBe(0);+ });});describe('runner — pricing gate (new models must run)', () => {