Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(ai): chat_fallback_chain safety audit (#6012 follow-up, fix wave 9 lane B)

time-attacka67293f4ffc7
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index 3f0a064536..906d21da60 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -15,7 +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/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`) is thrown instead of being sent on, while provider errors still fall back; a policy refusal (`isAIInvocationPolicyError` or a BudgetTracker `BudgetExhausted`) or the caller's own abort stops the chain; 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, 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).
+- `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).
- `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`.
diff --git a/docs/guides/chat-fallback.md b/docs/guides/chat-fallback.md
index e86bba373c..5b7ad9064f 100644
--- a/docs/guides/chat-fallback.md
+++ b/docs/guides/chat-fallback.md
@@ -70,7 +70,9 @@ chain on its own.
`chat_fallback_hop` safety notice naming the model that failed and the one
that received the request.
- A refusal (a `refusal` / `content_filter` stop reason, or a provider
- content block) also moves on by default, so content one provider refused
+ content block, including an HTTP 400 that refuses the prompt on content
+ policy: OpenAI `invalid_prompt`, Azure OpenAI `content_filter`, DeepSeek
+ "Content Exists Risk") also moves on by default, so content one provider refused
goes to the next. To keep outage fallback but never forward refused
content:
@@ -81,10 +83,14 @@ chain on its own.
The same key works as `GBRAIN_CHAT_FALLBACK_ON_REFUSAL=false` or
`"chat_fallback_on_refusal": false` in `config.json`, with the same
precedence as the chain.
-- A gbrain budget refusal or your own cancel stops the chain. When every
+- A gbrain budget refusal or your own cancel stops the chain. A cancel that
+ lands while a model is refusing returns that refusal; the content is not
+ sent on. When every
entry fails, the call's own model's error is reported, so retry and halt
decisions follow the configured model.
-- Judges, critics, evals, the `models doctor` / `providers test` probes,
+- Judges, critics, evals (including the `edge_contradictions` judge, whose
+ apply mode depends on which model it certified), the `models doctor` /
+ `providers test` probes,
`decide()`, `think --model` and `auto_think` pin their model and never use
the chain.
- A fallback call is billed by the entry's provider; budget caps price each
diff --git a/src/core/ai/chat-fallback.ts b/src/core/ai/chat-fallback.ts
index 27dda7fab0..bcd7bb9b48 100644
--- a/src/core/ai/chat-fallback.ts
+++ b/src/core/ai/chat-fallback.ts
@@ -25,7 +25,8 @@
* The chain stops on a gbrain policy refusal (an invocation-guard denial or a
* BudgetTracker `BudgetExhausted`: budget, caps and pricing describe gbrain's
* own accounting, and the next model is billed by the same ledger)
- * and once the caller's own abort signal has fired. When every model fails,
+ * and once the caller's own abort signal has fired, including a cancel that
+ * lands while an attempt is refusing (the refusal is returned, not forwarded). When every model fails,
* a refusal from an earlier attempt is returned in preference to a later
* attempt's error; otherwise the call's own model's error is thrown, so retry
* and halt classification (a 429 stays a rate limit) follow the configured
@@ -116,7 +117,7 @@ export async function chatWithFallback(
const next = models[i + 1];
try {
const result = await attempt({ ...opts, model, allowFallback: false });
- if (next === undefined || !isStructuralRefusal(result) || !onRefusal) return answered(result, model);
+ if (next === undefined || !isStructuralRefusal(result) || !onRefusal || opts.abortSignal?.aborted) return answered(result, model);
refused ??= answered(result, model);
console.warn(`[ai.gateway] chat ${result.model} stopped with ${result.stopReason}; trying ${next} from chat_fallback_chain`);
queueFirstHop(result.model, next, `stopReason ${result.stopReason}`, true);
diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.ts
index c83b035731..9858ea3a05 100644
--- a/src/core/ai/errors.ts
+++ b/src/core/ai/errors.ts
@@ -132,12 +132,33 @@ export function normalizeAIError(err: unknown, context?: string, redact?: (text:
return carryStatusFields(err, new AITransientError(`${ctxPrefix}${msg}`, err));
}
+/**
+ * HTTP 400 bodies that are a content-policy refusal of the prompt rather than
+ * a malformed request: OpenAI's `invalid_prompt` usage-policy flag, OpenAI and
+ * Azure OpenAI `content_policy_violation` / `content_filter` (Azure's
+ * `ResponsibleAIPolicyViolation`), and DeepSeek's "Content Exists Risk".
+ */
+const CONTENT_POLICY_400_CODES = new Set(['invalid_prompt', 'content_policy_violation', 'content_filter', 'ResponsibleAIPolicyViolation']);
+
+function contentPolicy400Reason(responseBody: string): string | undefined {
+ let error: { code?: unknown; message?: unknown; innererror?: { code?: unknown } } | undefined;
+ try { error = JSON.parse(responseBody)?.error; } catch { return undefined; }
+ for (const code of [error?.innererror?.code, error?.code]) {
+ if (typeof code === 'string' && CONTENT_POLICY_400_CODES.has(code)) return code;
+ }
+ return error?.message === 'Content Exists Risk' ? 'content_exists_risk' : undefined;
+}
+
/** A provider refusal tied to the prompt, even when the SDK wraps its response. */
export function providerContentBlockReason(err: unknown): string | undefined {
for (let depth = 0; depth < 8 && err != null; depth++) {
try {
if (typeof err !== 'object') break;
const value = err as { responseBody?: unknown; statusCode?: unknown; status?: unknown; cause?: unknown };
+ if (typeof value.responseBody === 'string' && (value.statusCode === 400 || value.status === 400)) {
+ const reason = contentPolicy400Reason(value.responseBody);
+ if (reason) return reason;
+ }
if (typeof value.responseBody === 'string' &&
(value.statusCode == null || value.statusCode === 200) &&
(value.status == null || value.status === 200)) {
diff --git a/src/core/cycle/edge-contradictions.ts b/src/core/cycle/edge-contradictions.ts
index da3ddd648d..c5414b8196 100644
--- a/src/core/cycle/edge-contradictions.ts
+++ b/src/core/cycle/edge-contradictions.ts
@@ -166,6 +166,7 @@ export async function defaultEdgeJudge(input: Parameters<EdgeJudgeFn>[0]): Promi
messages: [{ role: 'user', content: buildEdgeJudgePrompt(input.subject, input.relationships) }],
...(input.modelHint ? { model: input.modelHint } : {}),
maxTokens: input.maxOutputTokens ?? JUDGE_MAX_OUTPUT_TOKENS,
+ allowFallback: false,
});
return parseEdgeJudgeOutput(result.text, input.relationships.length);
}
diff --git a/test/ai/gateway-chat-fallback.test.ts b/test/ai/gateway-chat-fallback.test.ts
index 9f03b80662..bb5b6e7cec 100644
--- a/test/ai/gateway-chat-fallback.test.ts
+++ b/test/ai/gateway-chat-fallback.test.ts
@@ -34,6 +34,7 @@ import { probeModel } from '../../src/commands/models.ts';
import { defaultDriftJudge } from '../../src/core/cycle/drift.ts';
import { makeJudgeClient } from '../../src/core/cycle/synthesize.ts';
import { runJudge } from '../../src/eval/shared/judge-runner.ts';
+import { defaultEdgeJudge } from '../../src/core/cycle/edge-contradictions.ts';
const PRIMARY = 'claude-cli:claude-sonnet-4-6';
const FALLBACK = 'openai:gpt-5.6-luna';
@@ -275,6 +276,10 @@ describe('toolLoop() and judge flows with chat_fallback_chain (#5490)', () => {
name: 'LongMemEval judge',
run: () => runJudge({ client: chat, model: PRIMARY, prompt: 'synthetic', maxTokens: 16, temperature: 0, parse: () => 'yes' as never, retries: 0 }),
},
+ {
+ name: 'edge_contradictions judge (apply mode is certified per model)',
+ run: () => defaultEdgeJudge({ subject: { slug: 'people/alice-example', title: 'Alice Example' }, relationships: [], modelHint: PRIMARY }),
+ },
{
name: 'contradiction eval judge',
run: () => judgeContradiction({
@@ -360,3 +365,118 @@ describe('chain sources and budget refusals (#5490)', () => {
expect(warn).not.toHaveBeenCalled();
});
});
+
+describe('fallback safety audit (fix wave 9 lane B, #6012)', () => {
+ const OPENAI_PRIMARY = 'openai:gpt-5.6-luna';
+ const DEEPSEEK_FALLBACK = 'deepseek:deepseek-v4-flash';
+
+ /** An AI SDK APICallError-shaped 400 whose body is the provider's content-policy refusal. */
+ const contentPolicy400 = (body: unknown) => Object.assign(new Error('Bad Request'), {
+ statusCode: 400,
+ responseBody: JSON.stringify(body),
+ });
+
+ test.each([
+ {
+ name: 'OpenAI invalid_prompt (usage-policy flag)',
+ body: { error: { message: 'Invalid prompt: your prompt was flagged as potentially violating our usage policy.', type: 'invalid_request_error', param: null, code: 'invalid_prompt' } },
+ },
+ {
+ name: 'Azure OpenAI content_filter',
+ body: { error: { message: "The response was filtered due to the prompt triggering Azure OpenAI's content management policy.", param: 'prompt', code: 'content_filter', status: 400, innererror: { code: 'ResponsibleAIPolicyViolation' } } },
+ },
+ {
+ name: 'DeepSeek Content Exists Risk',
+ body: { error: { message: 'Content Exists Risk', type: 'invalid_request_error', param: null, code: 'invalid_request_error' } },
+ },
+ ])('with chat_fallback_on_refusal false, a $name 400 is not sent to the next model', async ({ body }) => {
+ configureGateway({ chat_model: OPENAI_PRIMARY, chat_fallback_chain: [DEEPSEEK_FALLBACK], chat_fallback_on_refusal: false, env: ENV });
+ __setGenerateTextTransportForTests((async (args: any) => {
+ attempts.push(args.model.modelId);
+ throw contentPolicy400(body);
+ }) as any);
+
+ const err = await chat({ model: OPENAI_PRIMARY, messages: [{ role: 'user', content: 'hello' }] }).catch(e => e);
+
+ expect(attempts).toEqual(['gpt-5.6-luna']);
+ expect(err).toBeInstanceOf(Error);
+ });
+
+ test('an ordinary 400 (context length) still falls back', async () => {
+ configureGateway({ chat_model: OPENAI_PRIMARY, chat_fallback_chain: [DEEPSEEK_FALLBACK], chat_fallback_on_refusal: false, env: ENV });
+ __setGenerateTextTransportForTests((async (args: any) => {
+ attempts.push(args.model.modelId);
+ if (args.model.modelId === 'gpt-5.6-luna') {
+ throw contentPolicy400({ error: { message: 'This model maximum context length is 128000 tokens.', type: 'invalid_request_error', code: 'context_length_exceeded' } });
+ }
+ return { content: [{ type: 'text', text: 'ok' }], finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } };
+ }) as any);
+
+ const result = await chat({ model: OPENAI_PRIMARY, messages: [{ role: 'user', content: 'hello' }] });
+
+ expect(attempts).toEqual(['gpt-5.6-luna', 'deepseek-v4-flash']);
+ expect(result.model).toBe(DEEPSEEK_FALLBACK);
+ });
+
+ test("a cancel that lands while the primary refuses stops the walk and returns the refusal", async () => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: [FALLBACK], env: ENV });
+ const controller = new AbortController();
+ __setGenerateTextTransportForTests((async (args: any) => {
+ attempts.push(args.model.modelId);
+ controller.abort();
+ return {
+ content: [{ type: 'text', text: '' }],
+ finishReason: 'stop',
+ usage: { inputTokens: 1, outputTokens: 1 },
+ providerMetadata: { anthropic: { stopReason: 'refusal' } },
+ };
+ }) as any);
+
+ const result = await ask({ abortSignal: controller.signal });
+
+ expect(attempts).toEqual(['claude-sonnet-4-6']);
+ expect(result.model).toBe(PRIMARY);
+ expect(result.stopReason).toBe('refusal');
+ });
+
+ test('an unpriced chain entry under an explicit cap is refused with no_pricing guidance, never called', async () => {
+ configureGateway({
+ chat_model: 'anthropic:claude-sonnet-4-6',
+ chat_fallback_chain: ['deepseek:deepseek-unpriced-example'],
+ env: { ...ENV, ANTHROPIC_API_KEY: 'fake-anthropic' },
+ });
+ installTransport({ 'claude-sonnet-4-6': 'outage' });
+ const tracker = new BudgetTracker({ label: 'chat-fallback-unpriced', maxCostUsd: 5, auditPath: '/dev/null' });
+
+ const err = await withBudgetTracker(tracker, () => chat({
+ model: 'anthropic:claude-sonnet-4-6',
+ messages: [{ role: 'user', content: 'hello' }],
+ maxTokens: 256,
+ })).catch(e => e);
+
+ expect(attempts).toEqual(['claude-sonnet-4-6']);
+ expect(err).toBeInstanceOf(BudgetExhausted);
+ expect(err.reason).toBe('no_pricing');
+ expect(err.modelId).toBe('deepseek:deepseek-unpriced-example');
+ expect(String(err.message)).toContain('gbrain pricing set');
+ });
+
+ test('an unpriced chain entry under a default cap warns and runs', async () => {
+ configureGateway({
+ chat_model: 'anthropic:claude-sonnet-4-6',
+ chat_fallback_chain: ['deepseek:deepseek-unpriced-example'],
+ env: { ...ENV, ANTHROPIC_API_KEY: 'fake-anthropic' },
+ });
+ installTransport({ 'claude-sonnet-4-6': 'outage' });
+ const tracker = new BudgetTracker({ label: 'chat-fallback-default-cap', maxCostUsd: 5, capSource: 'default', auditPath: '/dev/null' });
+
+ const result = await withBudgetTracker(tracker, () => chat({
+ model: 'anthropic:claude-sonnet-4-6',
+ messages: [{ role: 'user', content: 'hello' }],
+ maxTokens: 256,
+ }));
+
+ expect(attempts).toEqual(['claude-sonnet-4-6', 'deepseek-unpriced-example']);
+ expect(result.model).toBe('deepseek:deepseek-unpriced-example');
+ });
+});