Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(ai): send AI SDK warnings to stderr so --json stdout stays JSON (#5892)

garrytan697863818022
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index 0ff209aa64..63f17a6ab4 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -15,6 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/embedding-guard.ts` — the embedding refusal contract (#4616). `degenerateEmbeddingReason` flags zero-norm (L2 norm below `EMBEDDING_NORM_EPSILON`), NaN and ±Inf vectors; `sendableEmbeddingInputs` keeps empty and whitespace-only inputs away from the provider; `screenEmbeddings` / `screenAlignedEmbeddings` put vectors back at their input positions and throw `EmbeddingZeroNormError` (an `AIConfigError`, `code: embedding_zero_norm`, docs `docs/guides/write-refusals.md#embedding_zero_norm`) carrying per-item `failures` and the usable `vectors` aligned with the input (null where refused). `mergeZeroNormErrors` re-aligns per-slice refusals. `suggestionFor(slug, sourceId?)` fills the `gbrain embed <slug>` recovery command. Consumers: `gateway.embed()` and both multimodal embedders, `embedding.ts:embedBatch` (later 100-input slices still run), `embed-retry.ts` (never retried; `embedBatchKeepingUsable` returns the partial result), `embed.ts:embedPageTexts` and markdown/code imports (usable vectors stored, refused chunks stay NULL and the page signature is not stamped). Tests: `test/embedding-zero-norm-4616.serial.test.ts` (+ Postgres wrapper).
- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (`test/ai/gateway.test.ts` drives both layers through `embed()`). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance.
+- `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.serial.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/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 3b973d377e..6bff9a848c 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-provid
src/commands/extract.ts 2623 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)
src/commands/jobs.ts 658 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)
src/commands/serve-http.ts 915 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
-src/core/ai/gateway.ts 4391 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)
+src/core/ai/gateway.ts 4393 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)
src/commands/sync.ts 473 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)
src/core/cycle.ts 3192 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; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set
src/core/cycle/synthesize.ts 3293 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)
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index e38b4b64ba..8c11167cdb 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -22,6 +22,7 @@
*/
import { embed as aiEmbed, embedMany, generateObject, generateText, jsonSchema, type JSONSchema7, type Output } from 'ai';
+import { installAiSdkWarningWriter } from './sdk-warnings.ts';
import { AsyncLocalStorage } from 'node:async_hooks';
import { createHash, randomUUID } from 'node:crypto';
import { listRecipes } from './recipes/index.ts';
@@ -69,6 +70,7 @@ import { reportEmbeddingAuthFailure } from './key-warnings.ts';
import { buildGatewayConfig, foldNativeBaseUrlsFromFilePlane } from './build-gateway-config.ts';
import { invokeAI, sdkInvocationUsage, responseInvocationUsage, hasAIInvocationGuard, isAIInvocationPolicyError } from './invocation-guard.ts';
import { createGuardedGeneration, chatInvocation } from './guarded-generation.ts';
+installAiSdkWarningWriter();
const guardedGeneration = createGuardedGeneration(() => DEFAULT_MAX_OUTPUT_TOKENS);
// ---- Gateway-wide AI-HTTP timeout (v0.42.20.0, #1762/#1775) ----
diff --git a/src/core/ai/sdk-warnings.ts b/src/core/ai/sdk-warnings.ts
new file mode 100644
index 0000000000..4b135d39a0
--- /dev/null
+++ b/src/core/ai/sdk-warnings.ts
@@ -0,0 +1,36 @@
+/**
+ * AI SDK provider warnings go to stderr (#5892). The `ai` package logs a
+ * model's warnings (a claude-cli v2-compat notice, an Anthropic "unsupported
+ * setting") through `globalThis.AI_SDK_LOG_WARNINGS`; left unset, its first
+ * warning prints a banner with `console.info`, which lands on stdout and
+ * corrupts `--json` output. The gateway calls `installAiSdkWarningWriter()`
+ * when it loads (so CLI, worker, serve and library callers are all covered):
+ * a writer that prints the same per-warning lines to stderr and no banner. A
+ * value the user already set (`false` to silence, or their own function) is
+ * kept.
+ */
+import type { LogWarningsFunction, Warning } from 'ai';
+
+/** One warning line in the `ai` package's own wording. */
+export function formatAiSdkWarning(warning: Warning, provider: string, model: string): string {
+ const prefix = `AI SDK Warning (${provider} / ${model}):`;
+ switch (warning.type) {
+ case 'unsupported':
+ return `${prefix} The feature "${warning.feature}" is not supported.${warning.details ? ` ${warning.details}` : ''}`;
+ case 'compatibility':
+ return `${prefix} The feature "${warning.feature}" is used in a compatibility mode.${warning.details ? ` ${warning.details}` : ''}`;
+ case 'other':
+ return `${prefix} ${warning.message}`;
+ default:
+ return `${prefix} ${JSON.stringify(warning)}`;
+ }
+}
+
+export const writeAiSdkWarningsToStderr: LogWarningsFunction = ({ warnings, provider, model }) => {
+ for (const warning of warnings) process.stderr.write(`${formatAiSdkWarning(warning, provider, model)}\n`);
+};
+
+/** Install the stderr writer unless the global is already set. */
+export function installAiSdkWarningWriter(): void {
+ if (globalThis.AI_SDK_LOG_WARNINGS === undefined) globalThis.AI_SDK_LOG_WARNINGS = writeAiSdkWarningsToStderr;
+}
diff --git a/test/ai-sdk-warnings.test.ts b/test/ai-sdk-warnings.test.ts
new file mode 100644
index 0000000000..02e2ec8005
--- /dev/null
+++ b/test/ai-sdk-warnings.test.ts
@@ -0,0 +1,100 @@
+/**
+ * #5892: AI SDK provider warnings never reach stdout.
+ *
+ * Protects: loading the gateway installs a `globalThis.AI_SDK_LOG_WARNINGS`
+ * writer with the installed `ai` logger signature (`{ warnings, provider,
+ * model }`) that prints each warning to stderr and no stdout banner, for the
+ * claude-cli provider (v2 compatibility notice) and the Anthropic provider
+ * (`@ai-sdk/anthropic` "unsupported setting"); a value the user set is kept.
+ * Regression: the `ai` default logger's `console.info` banner on stdout,
+ * which broke `--json` output, or clobbering a user's `false`.
+ * Existing coverage: none at this boundary; the CLI-level check lives in
+ * test/json-stdout-ai-warnings.serial.test.ts.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { chmodSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { generateText } from 'ai';
+import { createAnthropic } from '@ai-sdk/anthropic';
+import '../src/core/ai/gateway.ts';
+import { ClaudeCliLanguageModel } from '../src/core/ai/providers/claude-cli-language-model.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const stubDir = join(tmpdir(), `gbrain-ai-sdk-warnings-${process.pid}`);
+const stubBin = join(stubDir, 'claude');
+
+beforeAll(() => {
+ mkdirSync(stubDir, { recursive: true });
+ const envelope = { type: 'result', subtype: 'success', is_error: false, result: 'ok', stop_reason: 'end_turn', session_id: 's', num_turns: 1, usage: { input_tokens: 1, output_tokens: 1 } };
+ writeFileSync(stubBin, `#!/bin/sh\ncat > /dev/null\necho '${JSON.stringify(envelope)}'\n`);
+ chmodSync(stubBin, 0o755);
+});
+afterAll(() => rmSync(stubDir, { recursive: true, force: true }));
+
+const original = globalThis.AI_SDK_LOG_WARNINGS;
+afterEach(() => { globalThis.AI_SDK_LOG_WARNINGS = original; });
+
+async function captureOutput(fn: () => Promise<unknown>): Promise<{ stdout: string; stderr: string }> {
+ const out: string[] = [];
+ const err: string[] = [];
+ const spies = [
+ spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown) => { out.push(String(chunk)); return true; }) as never),
+ spyOn(console, 'info').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); }),
+ spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); }),
+ spyOn(console, 'warn').mockImplementation((...a: unknown[]) => { err.push(`console.warn ${a.join(' ')}`); }),
+ spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => { err.push(String(chunk)); return true; }) as never),
+ ];
+ try {
+ await fn();
+ } finally {
+ for (const s of spies) s.mockRestore();
+ }
+ return { stdout: out.join(''), stderr: err.join('') };
+}
+
+describe('AI SDK warnings (#5892)', () => {
+ test('loading the gateway installs the stderr writer', () => {
+ expect(typeof original).toBe('function');
+ });
+
+ test('claude-cli: the v2 compatibility warning goes to stderr, no stdout banner', async () => {
+ const { stdout, stderr } = await withEnv({ GBRAIN_CLAUDE_CLI_BIN: stubBin }, () =>
+ captureOutput(() => generateText({ model: new ClaudeCliLanguageModel('claude-opus-5-5') as never, prompt: 'hi' })));
+ expect(stdout).toBe('');
+ expect(stderr).toContain('AI SDK Warning (claude-cli / claude-opus-5-5): The feature "specificationVersion" is used in a compatibility mode. Using v2 specification compatibility mode.');
+ expect(stderr).not.toContain('console.warn');
+ });
+
+ test('anthropic: an unsupported-setting warning goes to stderr, no stdout banner', async () => {
+ const anthropic = createAnthropic({
+ apiKey: 'test-key',
+ fetch: (async () => new Response(JSON.stringify({
+ id: 'msg_1', type: 'message', role: 'assistant', model: 'claude-test',
+ content: [{ type: 'text', text: 'ok' }], stop_reason: 'end_turn', stop_sequence: null,
+ usage: { input_tokens: 1, output_tokens: 1 },
+ }), { headers: { 'content-type': 'application/json' } })) as unknown as typeof fetch,
+ });
+ const { stdout, stderr } = await captureOutput(() => generateText({ model: anthropic('claude-test'), prompt: 'hi', seed: 7 }));
+ expect(stdout).toBe('');
+ expect(stderr).toContain('AI SDK Warning (anthropic.messages / claude-test): The feature "seed" is not supported.');
+ expect(stderr).not.toContain('console.warn');
+ });
+
+ test('a user-set value is kept: false stays false, a function stays theirs', async () => {
+ // Imported here, not at the top: a static import would install the writer
+ // itself and hide a gateway that stopped loading it.
+ const { installAiSdkWarningWriter, writeAiSdkWarningsToStderr } = await import('../src/core/ai/sdk-warnings.ts');
+ expect(original).toBe(writeAiSdkWarningsToStderr);
+ globalThis.AI_SDK_LOG_WARNINGS = false;
+ installAiSdkWarningWriter();
+ expect(globalThis.AI_SDK_LOG_WARNINGS).toBe(false);
+ const mine = () => {};
+ globalThis.AI_SDK_LOG_WARNINGS = mine;
+ installAiSdkWarningWriter();
+ expect(globalThis.AI_SDK_LOG_WARNINGS).toBe(mine);
+ globalThis.AI_SDK_LOG_WARNINGS = undefined;
+ installAiSdkWarningWriter();
+ expect(globalThis.AI_SDK_LOG_WARNINGS as unknown).toBe(writeAiSdkWarningsToStderr);
+ });
+});
diff --git a/test/json-stdout-ai-warnings.serial.test.ts b/test/json-stdout-ai-warnings.serial.test.ts
new file mode 100644
index 0000000000..03c9324684
--- /dev/null
+++ b/test/json-stdout-ai-warnings.serial.test.ts
@@ -0,0 +1,52 @@
+/**
+ * #5892: `gbrain think --json` stdout is JSON only; the AI SDK warning that a
+ * claude-cli model triggers lands on stderr.
+ *
+ * Protects: the real CLI path from the command through the gateway to the
+ * `ai` package's warning logger, with a fake `claude` binary
+ * (GBRAIN_CLAUDE_CLI_BIN) and an isolated keyless PGLite brain.
+ * Regression: the `ai` default logger printing its banner with
+ * `console.info` before the JSON, so `JSON.parse(stdout)` throws.
+ * Existing coverage: test/ai-sdk-warnings.test.ts pins the writer in-process;
+ * this pins that the CLI process actually loads it before the first call.
+ * `gbrain query --json` is not included: on a brain with no embedding
+ * provider it takes the keyword-only path and never reaches the gateway.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli } from './helpers/cli-spawn.ts';
+
+let root: string;
+let home: string;
+let env: Record<string, string | undefined>;
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gbrain-json-stdout-'));
+ home = join(root, 'home');
+ mkdirSync(home, { recursive: true });
+ const claude = join(root, 'claude');
+ const envelope = { type: 'result', subtype: 'success', is_error: false, result: 'The alpha widget is blue.', stop_reason: 'end_turn', session_id: 's', num_turns: 1, usage: { input_tokens: 12, output_tokens: 34 } };
+ writeFileSync(claude, `#!/bin/sh\ncat > /dev/null\necho '${JSON.stringify(envelope)}'\n`);
+ chmodSync(claude, 0o755);
+ env = { GBRAIN_CLAUDE_CLI_BIN: claude, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_API_KEY: undefined, AI_SDK_LOG_WARNINGS: undefined };
+ const init = await runCli(['init', '--pglite', '--no-embedding'], { home, env, timeoutMs: 120_000 });
+ expect(init.exitCode, init.stderr).toBe(0);
+ const set = await runCli(['config', 'set', 'models.think', 'claude-cli:claude-opus-5-5'], { home, env });
+ expect(set.exitCode, set.stderr).toBe(0);
+}, 180_000);
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+describe('--json stdout with an AI SDK warning (#5892)', () => {
+ test('gbrain think --json: stdout parses as JSON and the warning is on stderr', async () => {
+ const r = await runCli(['think', 'what color is the alpha widget', '--json'], { home, env, timeoutMs: 120_000 });
+ expect(r.exitCode, r.stderr).toBe(0);
+ const parsed = JSON.parse(r.stdout) as { answer?: string; modelUsed?: string };
+ expect(parsed.answer).toBe('The alpha widget is blue.');
+ expect(parsed.modelUsed).toBe('claude-cli:claude-opus-5-5');
+ expect(r.stdout).not.toContain('AI SDK Warning');
+ expect(r.stderr).toContain('AI SDK Warning (claude-cli / claude-opus-5-5): The feature "specificationVersion" is used in a compatibility mode.');
+ }, 120_000);
+});