Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(ai): a model_not_found fix names the config key that selected the model (#5304)

garrytan936a4ded951a
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index f983dffa28..7e583c4c9b 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/embed-batch-plan.ts` — the embedding request plan shared by `embed()` and spend preflights: per-input truncation (`EMBED_MAX_CHARS`), the `max_batch_tokens` × safety-factor pre-split (`splitByTokenBudget`, re-exported by the gateway), the item cap (`capBatchItems`, `NO_BATCH_CAP_SUB_BATCH_ITEMS` for `no_batch_cap` recipes) and the per-request input ceiling a guard reserves (`embedRequestMaxInputTokens`: one token per UTF-8 byte, capped per text by a declared `max_input_tokens`, additive so any split or retry of the same texts stays inside it). `embedRequestCeilings(texts, model)` replays the plan for a model string without a gateway; `rerankRequestMaxInputTokens` is the rerank twin. Pinned by `test/embedding-migration-settle.serial.test.ts` and the adaptive-batch suites.
- `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. `fitMatryoshkaPrefix(recipe, modelId, vector, expected)` (PR #5921, wave 14): when the recipe's embedding touchpoint declares the model in `matryoshka` (`{ native, prefixes }`, folded ids; `recipes/nvidia.ts` declares Nemotron-3-Embed-8B at 4096 with 1024/2048) and the provider answered at the native width for a listed target, the vector is sliced from the start and L2-normalized before `gateway.embedSubBatch`'s dim-mismatch check; every other vector returns untouched, an overflowing norm is refused, a zero or non-finite prefix falls to the per-item screen. 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/errors.ts` — error normalization and classification. One private generator, `wrappedErrorLayers`, opens a thrown error's wrappers outermost first (`cause`, else RetryError's `lastError`; objects only, at most five layers, a repeated layer ends the walk). `isStructuredOutputRejection` and `readProviderFailureSignals` use it; the latter returns the first finite `status`/`statusCode`/`apiErrorStatus` plus every string `name` and `code` and never throws (a throwing getter ends the walk). `page-summary.ts` `classifyChatError` reads those signals, so a wrapped claude-cli 429, an AI SDK RetryError's 429/5xx or a `TimeoutError`/network code on `cause` classifies as rate_limit/provider_5xx/timeout/network instead of `malformed` (which drops the page to the title tier). `classifyGlobalLlmError` keeps its own depth-3 loop over `cause ?? lastError`, so a 404 there halts as `model_not_found`; the model-not-found phrases (`model_not_found`, `not_found_error`, "does not exist or you do not have access", "does not have access to [the] model") are tested before the status map, so a provider 403 that denies a project access to a model classifies `model_not_found` with the model fix, never `auth` (a plain 401/403 stays `auth`; `test/ai/model-not-found-class.test.ts`); the `--- raw ---` phrase barrier and billing-over-429 precedence hold (`test/synopsis-chat-failure-class.test.ts`, `test/ai/classify-global-llm-error.test.ts`).
+- `src/core/ai/errors.ts` — error normalization and classification. One private generator, `wrappedErrorLayers`, opens a thrown error's wrappers outermost first (`cause`, else RetryError's `lastError`; objects only, at most five layers, a repeated layer ends the walk). `isStructuredOutputRejection` and `readProviderFailureSignals` use it; the latter returns the first finite `status`/`statusCode`/`apiErrorStatus` plus every string `name` and `code` and never throws (a throwing getter ends the walk). `page-summary.ts` `classifyChatError` reads those signals, so a wrapped claude-cli 429, an AI SDK RetryError's 429/5xx or a `TimeoutError`/network code on `cause` classifies as rate_limit/provider_5xx/timeout/network instead of `malformed` (which drops the page to the title tier). `classifyGlobalLlmError` keeps its own depth-3 loop over `cause ?? lastError`, so a 404 there halts as `model_not_found`; the model-not-found phrases (`model_not_found`, `not_found_error`, "does not exist or you do not have access", "does not have access to [the] model") are tested before the status map, so a provider 403 that denies a project access to a model classifies `model_not_found` with the model fix, never `auth` (a plain 401/403 stays `auth`; `test/ai/model-not-found-class.test.ts`). #5304: `normalizeAIError(err, context, redact, routeHint)` appends `routeHint` to a 404's fix only; `src/core/ai/model-not-found-hint.ts` renders it from the gateway's recorded provenance (`gatewayModelNotFoundHint(touchpoint, model)` → `modelRouteHint`: "Selected via models.tier.reasoning. Fix: gbrain config set models.tier.reasoning <provider>:<model>"; env and config.json pins say what to clear; a deprecated key names the `models.*` key to set instead; the built-in default names the touchpoint's tier key; unrecorded or stale provenance adds nothing) and `embeddingModelNotFoundHint()` names `embedding_model` with the doctor route, never a bare `config set`. `gateway.ts` passes it at its `embed`, `expand` and `chat` 404 sites (`test/ai/model-not-found-hint-5304.test.ts`); the `--- raw ---` phrase barrier and billing-over-429 precedence hold (`test/synopsis-chat-failure-class.test.ts`, `test/ai/classify-global-llm-error.test.ts`).
- `src/core/ai/gateway.ts` — unified seam for every AI call. The `ai` SDK loads at the first provider call (lazy default transports), not on configure. `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`. `src/core/ai/multimodal-model.ts:multimodalEmbeddingModel()` answers the model `embedMultimodal()` would use when it passes those same recipe and allow-list checks (null otherwise, or when the gateway is unconfigured); hybrid search routes an inferred image intent and the LLM modality tie-break to the image arm only when it is set (`test/cross-modal-hybrid-integration.serial.test.ts`). 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 too: `docs/ai-providers/google.md`). `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.timeoutMs` replaces the default chat backstop (`GBRAIN_AI_CHAT_TIMEOUT_MS`, 300 s) for one call and `ToolLoopOpts.turnTimeoutMs` forwards it to every turn (the subagent handler's per-turn cap, #4921); `ChatOpts.thinking: 'off'` maps per route through `thinking-off.ts` (#5331). `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. `embedQuery` caches query vectors per process (`src/core/ai/query-embed-cache.ts`: 512-entry LRU, 10-min TTL), keyed by recipe, model id, `base_urls` override, effective dims and the exact provider input (prefix + text). It stores only resolved vectors, as copies; the cache clears with `_modelCache` (configure, env refresh, engine re-stamp, reset, `__setEmbedTransportForTests`) and a generation counter drops an embed straddling a clear. Document-side `embed()` is never cached; a caller under an AI invocation guard skips the cache read.
- `src/core/ai/chat-fallback.ts`: the `chat_fallback_chain` consumer. `gateway.chat()` hands a call to `chatWithFallback` when a chain is configured and the caller did not pass `allowFallback: false`; `configureGateway` normalizes the chain with `normalizeChatFallbackChain` (a comma-separated string, the env and DB form, is split). Attempts run the call's own model, then each chain entry not already tried (`chatFallbackAttempts`), each as a complete single-model `chat()`, so budget, usage ledger, guardrails and `ChatResult.model` follow the model that ran; an answer from a chain entry also carries `ChatResult.fallbackFrom` (the call's own model). A provider error (a claude-cli subscription limit arrives as `apiErrorStatus` 429) or a structural refusal (`stopReason` `refusal`/`content_filter`) moves to the next model with one `[ai.gateway]` stderr line, and the first hop of a process queues one `chat_fallback_hop` safety notice in `fallback-hop-queue.ts`; with `chat_fallback_on_refusal: false` (`ChatFallbackOptions.onRefusal`, passed by `chat()` from the gateway config) a structural refusal is returned and a provider content block (`providerContentBlockReason`: a Gemini prompt block, or an HTTP 400 content-policy body such as OpenAI `invalid_prompt`, Azure `content_filter` or DeepSeek "Content Exists Risk") is thrown instead of being sent on, while provider errors still fall back; a policy refusal (`isAIInvocationPolicyError` or a BudgetTracker `BudgetExhausted`, including an unpriced chain entry under an explicit cap) or the caller's own abort stops the chain, and a cancel that lands while an attempt refuses returns that refusal instead of forwarding it; an earlier refusal is returned in preference to a later error, otherwise the call's own model's error is thrown (the last failure logged), so retry and halt classification follow the configured model. `toolLoop` forwards `allowFallback` to every turn. Judge, critic and eval call sites pin their model: brainstorm judges, grade_takes, drift, the edge_contradictions judge (apply mode defaults from a per-model certification), voice-gate, eval-contradictions, notability-eval, takes-quality-eval, cross-modal eval, skillopt (judge, optimizer, rollouts), the LongMemEval reader and judge, the functional-area-resolver harness, the `models doctor` / `providers test` probes, `decide()` (its egress gate cleared one provider), `auto_think` (its BudgetMeter priced one model), and `think` with an explicit `--model`; the synthesize triage and concept synthesis fall back. Pinned by `test/ai/gateway-chat-fallback.test.ts` and `test/ai/chat-fallback-on-refusal.test.ts` (refusal switch through the real loader on every plane, the once-per-process hop notice).
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 8a9728fade..c89d15a8ee 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -16,7 +16,7 @@
| Conversation facts are dated 1970-01-01 | same preview: `gbrain repair conversation-labels` (an undated page's pre-fix facts carry a `segment 1970-01-01` context); add a `date:` to the page frontmatter before re-extracting it | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
| `remember` or `put_page` refused `source_changed` "The canonical file contains an uncoordinated local edit" on many pages nobody edited, or doctor `lost_caller_writes` warns | upgrade to v0.60.157.0 or later (a database-only v0.13.1 `validate: false` stamp was read as a file edit, #6429); then `gbrain repair failed-writes --source <id>` previews the refused writes and prints the apply command ([failed writes](repair.md#failed-writes)) | agent; the apply after the user agrees | none to preview | `gbrain doctor --only lost_caller_writes --json` is ok |
| A write (`add_timeline_entry`, `put_page`, `remember`, any `mutating` tool) refused `invalid_params` "unknown parameter … write operations always reject unknown parameters; nothing was written" | the call named a parameter the tool does not declare (for example `content` instead of `detail`); the `suggestion` names the submitted key and the declared one; resend with the declared name. Reads keep the `mcp.strict_params` warn grace period | agent | none | the resent call returns no `invalid_params` and no `unknown_param` warning |
-| Facts extraction or embedding reports `(cause=AIConfigError model_not_found)` or `gbrain models doctor` says `model_not_found` while the key is valid | the provider refused the model, not the key (a 404, or a 403 "project does not have access to model"): check the model id with `gbrain models`, enable the model for the project in the provider console or set another model (`gbrain config set models.facts <provider:model>`) | user (provider console); agent for the config change, after the user agrees | none | `gbrain models doctor` reports the model `ok` |
+| Facts extraction or embedding reports `(cause=AIConfigError model_not_found)` or `gbrain models doctor` says `model_not_found` while the key is valid | the provider refused the model, not the key (a 404, or a 403 "project does not have access to model"): the fix text names the config key that selected the model when the gateway knows it ("Selected via models.tier.reasoning. Fix: gbrain config set …"; an env var or config.json pin says what to clear); otherwise check the model id with `gbrain models`, enable the model for the project in the provider console or set another model (`gbrain config set models.facts <provider:model>`) | user (provider console); agent for the config change, after the user agrees | none | `gbrain models doctor` reports the model `ok` |
| A gbrain call failed with a code you don't recognize | follow `fix.next` ([protocol](../protocol/AGENT_OPERATOR_v1.md)); `gbrain errors <code>` | agent | as the fix's `consent` | the fix's `verify` |
| A graph read omits a relationship you know existed, or says someone still works somewhere they left | the default read returns relationships true today: repeat with `status: "all"` or `as_of`; to record an end, add a dated timeline line (`Ended works_at [[companies/x]]`) or `add_link ... valid_until` ([temporal edges](temporal-edges.md)) | agent | none | `gbrain doctor --only edge_validity --json` |
| A command exited 3 (`confirmation_required`) | relay `user_message`; run `fix.command` only after the user agrees | agent, after the user agrees | the payload's `effects` | the fix's `verify` |
diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.ts
index 8c374a432c..7443145224 100644
--- a/src/core/ai/errors.ts
+++ b/src/core/ai/errors.ts
@@ -91,23 +91,26 @@ const KNOWN_MODEL_RENAMES: Readonly<Record<string, string>> = {
/**
* Recovery text for a provider 404 (`model_not_found`): the model id and
* provider from the call context (`chat(provider:model)`), the command that
- * lists the configured routes, and a known rename when there is one.
+ * lists the configured routes, a known rename when there is one and, #5304,
+ * `routeHint`: the sentence naming the config key that selected the model
+ * (`model-not-found-hint.ts`), appended when the caller knows it.
*/
-export function modelNotFoundFix(context: string | undefined): string {
+export function modelNotFoundFix(context: string | undefined, routeHint = ''): string {
const model = context?.match(/\(([^()\s]+:[^()\s]+)\)\s*$/)?.[1];
const provider = model?.slice(0, model.indexOf(':'));
const rename = model ? KNOWN_MODEL_RENAMES[model] : undefined;
return `Check the model id: ${model ? `the ${provider} provider does not serve ${model}` : 'the provider does not serve this model'}, or this key has no access to it. ` +
'Run `gbrain models` to see the configured model routes, then set a model the provider lists.' +
- (rename ? ` ${model} was renamed: use ${rename}.` : '');
+ (rename ? ` ${model} was renamed: use ${rename}.` : '') +
+ (routeHint ? ` ${routeHint}` : '');
}
/**
* `redact` scrubs upstream text before it becomes the message, and in the
* wrapped error (#5137: the gateway passes its provider-key redactor, since
- * auth errors echo keys).
+ * auth errors echo keys). `routeHint` (#5304) is appended to a 404's fix only.
*/
-export function normalizeAIError(err: unknown, context?: string, redact?: (text: string) => string): AIServiceError {
+export function normalizeAIError(err: unknown, context?: string, redact?: (text: string) => string, routeHint = ''): AIServiceError {
if (redact) scrubErrorChain(err, redact);
if (err instanceof AIServiceError) return err;
@@ -136,7 +139,7 @@ export function normalizeAIError(err: unknown, context?: string, redact?: (text:
if (typeof status === 'number' && status >= 400 && status < 500 && status !== 429) {
return carryStatusFields(err, new AIConfigError(
`${ctxPrefix}${msg}`,
- status === 404 || MODEL_NOT_FOUND_MESSAGE_RE.test(msg) ? modelNotFoundFix(context)
+ status === 404 || MODEL_NOT_FOUND_MESSAGE_RE.test(msg) ? modelNotFoundFix(context, routeHint)
: status === 401 || status === 403 ? 'Check your API key is valid and has access to this model.'
: 'Check your model id + provider options match the provider API.',
err,
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 96a4265e77..97e1ea6473 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -62,6 +62,7 @@ import type { BrainEngine } from '../engine.ts';
import { dimsProviderOptions } from './dims.ts';
import { hasAnthropicKey, stashGatewayAnthropicKeyFromEnv } from './anthropic-key.ts';
import { AIConfigError, AITransientError, isStructuredOutputRejection, isUnbilledEmbeddingRejection, normalizeAIError } from './errors.ts';
+import { embeddingModelNotFoundHint, gatewayModelNotFoundHint } from './model-not-found-hint.ts';
import { fitMatryoshkaPrefix, isEmbeddingZeroNormError, screenAlignedEmbeddings, screenEmbeddings, sendableEmbeddingInputs } from './embedding-guard.ts';
import { getProviderCapabilities } from './capabilities.ts';
import { runGuardrails, hasGuardrails, type GuardrailHook } from '../guardrails.ts';
@@ -1805,7 +1806,7 @@ async function embedSubBatch(
};
}
reportEmbeddingAuthFailure(recipe, err);
- throw normalizeAIError(err, `embed(${recipe.id}:${modelId})`, redactKeys);
+ throw normalizeAIError(err, `embed(${recipe.id}:${modelId})`, redactKeys, embeddingModelNotFoundHint());
}
}
@@ -2639,7 +2640,7 @@ export async function expand(query: string): Promise<string[]> {
} catch (err) {
if (isAIInvocationPolicyError(err)) throw err;
// Expansion is best-effort: on failure, fall back to the original query alone.
- const normalized = normalizeAIError(err, 'expand', redactKeys);
+ const normalized = normalizeAIError(err, `expand(${_config?.expansion_model ?? ''})`, redactKeys, gatewayModelNotFoundHint('expansion', _config?.expansion_model ?? ''));
if (normalized instanceof AIConfigError) {
console.warn(`[ai.gateway] expansion disabled: ${normalized.message}`);
}
@@ -3840,7 +3841,7 @@ async function chatAdmitted(opts: ChatOpts, admitted: {
// Pessimistic fallback (A3 amended): when err.usage isn't there, charge
// the worst-case ceiling — better to overcount on failure than under.
_recordBudget(failedCallUsage(err, { inputTokens: estimatedInputTokens, outputTokens: maxOutputTokens }));
- throw normalizeAIError(err, `chat(${recipe.id}:${modelId})`, redactKeys);
+ throw normalizeAIError(err, `chat(${recipe.id}:${modelId})`, redactKeys, gatewayModelNotFoundHint('chat', modelStr));
}
}
diff --git a/src/core/ai/model-not-found-hint.ts b/src/core/ai/model-not-found-hint.ts
new file mode 100644
index 0000000000..45d817e5eb
--- /dev/null
+++ b/src/core/ai/model-not-found-hint.ts
@@ -0,0 +1,48 @@
+/**
+ * #5304: the sentence a provider 404 (`model_not_found`) gets after the model
+ * id: which config key selected the failing model and the one command that
+ * changes it. The gateway records each touchpoint's resolution provenance in
+ * `gateway-model-sources.ts`; this module renders it so `normalizeAIError`
+ * can append it to the 404 fix. Nothing here is consulted for other errors.
+ */
+import { getGatewayModelSource, type GatewayModelSource } from './gateway-model-sources.ts';
+
+type Touchpoint = 'expansion' | 'chat';
+
+const TIER_KEY: Record<Touchpoint, string> = { expansion: 'models.tier.utility', chat: 'models.tier.reasoning' };
+const CONFIG_KEY: Record<Touchpoint, string> = { expansion: 'models.expansion', chat: 'models.chat' };
+
+/** The route sentence for a recorded provenance; `touchpoint` names the tier key a built-in default should be replaced through. */
+export function modelRouteHint(route: GatewayModelSource, touchpoint: Touchpoint): string {
+ const { source, origin } = route;
+ switch (source) {
+ case 'config_key':
+ case 'models_default':
+ case 'tier_config':
+ return `Selected via ${origin}. Fix: gbrain config set ${origin} <provider>:<model>`;
+ case 'deprecated_key':
+ return `Selected via ${origin} (deprecated key). Fix: gbrain config unset ${origin}, then gbrain config set ${CONFIG_KEY[touchpoint]} <provider>:<model>`;
+ case 'cli_flag':
+ return `Selected via ${origin}. Fix: pass a model the provider serves.`;
+ case 'env':
+ return `Selected via the ${origin} environment variable. Fix: unset ${origin} or point it at a model the provider serves.`;
+ case 'file_config': {
+ const key = origin.split(' ')[0];
+ return `Selected via ${key} in ~/.gbrain/config.json. Fix: remove ${key} there or set it to a model the provider serves.`;
+ }
+ case 'tier_default':
+ case 'fallback':
+ return `Selected via the built-in default. Fix: gbrain config set ${TIER_KEY[touchpoint]} <provider>:<model>`;
+ }
+}
+
+/** The route sentence for the gateway's own `expansion` / `chat` model, or '' when its provenance is unrecorded or stale. */
+export function gatewayModelNotFoundHint(touchpoint: Touchpoint, model: string): string {
+ const route = getGatewayModelSource(touchpoint, model);
+ return route ? modelRouteHint(route, touchpoint) : '';
+}
+
+/** The embedding model is always `embedding_model`, a schema-sizing key: changing it re-embeds the brain, so the fix routes through doctor. */
+export function embeddingModelNotFoundHint(): string {
+ return 'Selected via embedding_model. Changing it changes the vector column, so check `gbrain doctor --only embedding_health` and `gbrain config get embedding_model` before setting another model.';
+}
diff --git a/test/ai/model-not-found-hint-5304.test.ts b/test/ai/model-not-found-hint-5304.test.ts
new file mode 100644
index 0000000000..5d7a15477c
--- /dev/null
+++ b/test/ai/model-not-found-hint-5304.test.ts
@@ -0,0 +1,86 @@
+/**
+ * #5304: a provider 404 (`model_not_found`) names the config key that selected
+ * the failing model and the one command that changes it, not only the model
+ * id. The gateway records each touchpoint's resolution provenance
+ * (`gateway-model-sources.ts`); `src/core/ai/model-not-found-hint.ts` turns
+ * it into the sentence `normalizeAIError` appends to the 404 fix. Golden per
+ * caller: chat (models.tier.reasoning / models.chat / env / config.json pin /
+ * built-in default), expansion (models.tier.utility) and embed
+ * (embedding_model, a schema-sizing key with its own guard).
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { AIConfigError, normalizeAIError } from '../../src/core/ai/errors.ts';
+import { clearGatewayModelSources, setGatewayModelSource } from '../../src/core/ai/gateway-model-sources.ts';
+// Resolved at run time so the fail-first run on a tree without the module reports the missing behaviour, not an import error.
+const hint = await import('../../src/core/ai/model-not-found-hint.ts').catch(() => null as never as typeof import('../../src/core/ai/model-not-found-hint.ts'));
+
+const openai404 = (model: string) => Object.assign(new Error(`The model \`${model}\` does not exist or you do not have access to it.`), { statusCode: 404 });
+
+afterEach(() => clearGatewayModelSources());
+
+describe('#5304 model_not_found names the selecting config key', () => {
+ test('normalizeAIError appends the route hint to the 404 fix after the model sentence', () => {
+ const err = normalizeAIError(openai404('gpt-x'), 'chat(openai:gpt-x)', undefined, 'Selected via models.tier.reasoning. Fix: gbrain config set models.tier.reasoning <provider>:<model>');
+ expect(err).toBeInstanceOf(AIConfigError);
+ const fix = (err as AIConfigError).fix!;
+ expect(fix).toContain('the openai provider does not serve openai:gpt-x');
+ expect(fix.indexOf('`gbrain models`')).toBeLessThan(fix.indexOf('Selected via models.tier.reasoning.'));
+ expect(fix.endsWith('Fix: gbrain config set models.tier.reasoning <provider>:<model>')).toBe(true);
+ });
+
+ test('chat: a tier_config route names models.tier.reasoning and the config set command', () => {
+ setGatewayModelSource('chat', 'openai:gpt-x', { source: 'tier_config', origin: 'models.tier.reasoning' });
+ const err = normalizeAIError(openai404('gpt-x'), 'chat(openai:gpt-x)', undefined, hint.gatewayModelNotFoundHint('chat', 'openai:gpt-x'));
+ expect(err).toBeInstanceOf(AIConfigError);
+ const fix = (err as AIConfigError).fix!;
+ expect(fix).toContain('the openai provider does not serve openai:gpt-x');
+ expect(fix).toContain('Selected via models.tier.reasoning.');
+ expect(fix).toContain('gbrain config set models.tier.reasoning <provider>:<model>');
+ });
+
+ test('chat: config_key, models_default, deprecated_key and cli_flag routes name their origin', () => {
+ expect(hint.modelRouteHint({ source: 'config_key', origin: 'models.chat' }, 'chat')).toBe('Selected via models.chat. Fix: gbrain config set models.chat <provider>:<model>');
+ expect(hint.modelRouteHint({ source: 'models_default', origin: 'models.default' }, 'chat')).toBe('Selected via models.default. Fix: gbrain config set models.default <provider>:<model>');
+ expect(hint.modelRouteHint({ source: 'deprecated_key', origin: 'chat_model' }, 'chat')).toBe('Selected via chat_model (deprecated key). Fix: gbrain config unset chat_model, then gbrain config set models.chat <provider>:<model>');
+ expect(hint.modelRouteHint({ source: 'cli_flag', origin: '--model' }, 'chat')).toBe('Selected via --model. Fix: pass a model the provider serves.');
+ });
+
+ test('chat: env and config.json pins say what to clear', () => {
+ expect(hint.modelRouteHint({ source: 'env', origin: 'GBRAIN_CHAT_MODEL' }, 'chat')).toBe('Selected via the GBRAIN_CHAT_MODEL environment variable. Fix: unset GBRAIN_CHAT_MODEL or point it at a model the provider serves.');
+ expect(hint.modelRouteHint({ source: 'file_config', origin: 'chat_model (config.json)' }, 'chat')).toBe('Selected via chat_model in ~/.gbrain/config.json. Fix: remove chat_model there or set it to a model the provider serves.');
+ });
+
+ test('chat: the built-in default names the tier key to set', () => {
+ setGatewayModelSource('chat', 'anthropic:claude-old', { source: 'tier_default', origin: 'built-in default' });
+ expect(hint.gatewayModelNotFoundHint('chat', 'anthropic:claude-old')).toBe('Selected via the built-in default. Fix: gbrain config set models.tier.reasoning <provider>:<model>');
+ });
+
+ test('expansion: the utility tier and models.expansion are named for the expansion touchpoint', () => {
+ setGatewayModelSource('expansion', 'openai:gpt-small', { source: 'tier_config', origin: 'models.tier.utility' });
+ expect(hint.gatewayModelNotFoundHint('expansion', 'openai:gpt-small')).toBe('Selected via models.tier.utility. Fix: gbrain config set models.tier.utility <provider>:<model>');
+ setGatewayModelSource('expansion', 'openai:gpt-small', { source: 'tier_default', origin: 'built-in default' });
+ expect(hint.gatewayModelNotFoundHint('expansion', 'openai:gpt-small')).toBe('Selected via the built-in default. Fix: gbrain config set models.tier.utility <provider>:<model>');
+ const err = normalizeAIError(openai404('gpt-small'), 'expand(openai:gpt-small)', undefined, hint.gatewayModelNotFoundHint('expansion', 'openai:gpt-small'));
+ expect((err as AIConfigError).fix).toContain('models.tier.utility');
+ });
+
+ test('embed: embedding_model is named with its schema-sizing guard, never a bare config set', () => {
+ const text = hint.embeddingModelNotFoundHint();
+ expect(text).toContain('Selected via embedding_model.');
+ expect(text).toContain('gbrain doctor');
+ expect(text).not.toMatch(/Fix: gbrain config set embedding_model <provider>:<model>$/);
+ const err = normalizeAIError(openai404('text-embedding-old'), 'embed(openai:text-embedding-old)', undefined, text);
+ expect((err as AIConfigError).fix).toContain('embedding_model');
+ });
+
+ test('an unrecorded or stale route adds nothing, and the hint never reaches a non-404 fix', () => {
+ expect(hint.gatewayModelNotFoundHint('chat', 'openai:never-recorded')).toBe('');
+ setGatewayModelSource('chat', 'openai:gpt-x', { source: 'tier_config', origin: 'models.tier.reasoning' });
+ expect(hint.gatewayModelNotFoundHint('chat', 'openai:gpt-other')).toBe('');
+ const plain = normalizeAIError(openai404('gpt-x'), 'chat(openai:gpt-x)', undefined, '');
+ expect((plain as AIConfigError).fix).toContain('`gbrain models`');
+ expect((plain as AIConfigError).fix).not.toContain('Selected via');
+ const auth = normalizeAIError(Object.assign(new Error('bad key'), { statusCode: 401 }), 'chat(openai:gpt-x)', undefined, hint.gatewayModelNotFoundHint('chat', 'openai:gpt-x'));
+ expect((auth as AIConfigError).fix).toBe('Check your API key is valid and has access to this model.');
+ });
+});