Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(contextual): our own implementation of the #6047 fix (#6047)
time-attacka8ccd0bd05f8
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex 2e5e8e654a..8cd3416722 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -16,7 +16,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. 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. `providerErrorChain` (objects only, at most five layers, `cause ?? lastError`) and `providerErrorStatus` (first finite `status`/`statusCode`/`apiErrorStatus`, outermost first) are the one chain walker: `isStructuredOutputRejection` and `page-summary.ts` `classifyChatError` use them, 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` (RetryError keeps the final attempt on `lastError`), so a 404 there halts as `model_not_found`; the `--- raw ---` phrase barrier and billing-over-429 precedence hold (`test/page-summary-chat-errors.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 `--- 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. `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.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.- `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/src/core/ai/errors.ts b/src/core/ai/errors.tsindex 93dd607dff..fcae77ba66 100644--- a/src/core/ai/errors.ts+++ b/src/core/ai/errors.ts@@ -255,34 +255,45 @@ function numericStatusOf(e: unknown): number | undefined {}/**- * A thrown provider error and the errors it wraps, outermost first: the- * `cause` chain, including the AI SDK's RetryError (`lastError`) once its- * retries are spent. normalizeAIError keeps the provider's own error on- * `cause`, so its status, name and code are only reachable this way.- * Objects only, at most five layers.+ * The layers of a thrown provider error, outermost first. chat() throws the+ * gateway's normalized error with the provider's own error on `cause`; the AI+ * SDK's RetryError keeps the final attempt on `lastError` instead. Objects+ * only, and the walk stops after `limit` layers or at a layer already seen,+ * so a self-referencing chain cannot loop.*/-export function providerErrorChain(err: unknown): object[] {- const chain: object[] = [];- let cur: unknown = err;- for (let depth = 0; cur && typeof cur === 'object' && depth < 5; depth++) {- chain.push(cur);- const e = cur as { cause?: unknown; lastError?: unknown };- cur = e.cause ?? e.lastError;+function* wrappedErrorLayers(err: unknown, limit = 5): Generator<Record<string, unknown>> {+ const seen = new Set<object>();+ let layer = err;+ while (layer !== null && typeof layer === 'object' && seen.size < limit && !seen.has(layer)) {+ seen.add(layer);+ const fields = layer as Record<string, unknown>;+ yield fields;+ layer = fields.cause ?? fields.lastError;}- return chain;}-/**- * The HTTP status a thrown provider error carries, outermost first along its- * providerErrorChain: `status`, `statusCode`, or the claude-cli provider's- * `apiErrorStatus`, which normalizeAIError carries to the top level.- */-export function providerErrorStatus(err: unknown): number | undefined {- for (const e of providerErrorChain(err)) {- const status = numericStatusOf(e);- if (status !== undefined) return status;+/** What a thrown provider error reports about itself once its wrappers are opened (#5964). */+export interface ProviderFailureSignals {+ /** The first finite numeric HTTP status on any layer (see numericStatusOf), outermost first. */+ status: number | undefined;+ /** String `name` values on the layers, outermost first (e.g. `TimeoutError`). */+ names: string[];+ /** String `code` values on the layers, outermost first (e.g. `ECONNRESET`). */+ codes: string[];+}++export function readProviderFailureSignals(err: unknown): ProviderFailureSignals {+ const signals: ProviderFailureSignals = { status: undefined, names: [], codes: [] };+ try {+ for (const layer of wrappedErrorLayers(err)) {+ signals.status ??= numericStatusOf(layer);+ if (typeof layer.name === 'string') signals.names.push(layer.name);+ if (typeof layer.code === 'string') signals.codes.push(layer.code);+ }+ } catch {+ // A throwing getter on a wrapped error ends the walk; what was read stands.}- return undefined;+ return signals;}/**@@ -299,11 +310,12 @@ export function providerErrorStatus(err: unknown): number | undefined {const STRUCTURED_OUTPUT_REJECTION_RE = /response_format|json_schema|structured[ _-]?outputs?/i;export function isStructuredOutputRejection(err: unknown): boolean {- const status = providerErrorStatus(err);- const named = providerErrorChain(err).some((e) => {- const { message, responseBody } = e as { message?: unknown; responseBody?: unknown };- return [message, responseBody].some(t => typeof t === 'string' && STRUCTURED_OUTPUT_REJECTION_RE.test(t));- });+ let status: number | undefined;+ let named = false;+ for (const layer of wrappedErrorLayers(err)) {+ status ??= numericStatusOf(layer);+ named ||= [layer.message, layer.responseBody].some(t => typeof t === 'string' && STRUCTURED_OUTPUT_REJECTION_RE.test(t));+ }if (status !== undefined && (status < 400 || status >= 500 || status === 429)) return false;return named;}diff --git a/src/core/page-summary.ts b/src/core/page-summary.tsindex 4d4d2bd847..7c67cfe351 100644--- a/src/core/page-summary.ts+++ b/src/core/page-summary.ts@@ -30,7 +30,7 @@* loop and handles page-level fall-back.*/-import { providerErrorChain, providerErrorStatus } from './ai/errors.ts';+import { readProviderFailureSignals } from './ai/errors.ts';import { chat, type ChatOpts, type ChatResult } from './ai/gateway.ts';import { logSynopsisFailure, type SynopsisFailureKind } from './audit-synopsis.ts';import { sanitizeSynopsis } from './embedding-context.ts';@@ -279,16 +279,21 @@ function buildUserPrompt(].join('\n');}+const TIMEOUT_ERROR_NAMES = new Set(['AbortError', 'TimeoutError']);+const NETWORK_ERROR_CODES = new Set(['ENOTFOUND', 'ECONNREFUSED', 'ECONNRESET']);+// `adapter aborted` is the claude-cli adapter's plain Error when the call's+// signal fires (the gateway's chat timeout or a cancel); it has no abort name.+const TIMEOUT_MESSAGE_RE = /timeout|timed out|adapter aborted/i;+/*** Map a thrown error from `gateway.chat()` into the D27 P1-2 failure envelope.*- * chat() throws the gateway's normalized error, which keeps the provider's- * own error on `cause` (#5964): the claude-cli provider's status rides as- * `apiErrorStatus`, an AI SDK provider's as `statusCode` on the wrapped- * cause (RetryError's `lastError` once retries are spent), and an AI SDK- * timeout keeps its `TimeoutError` name there. Missing them turns a rate- * limit or a timeout into `malformed`, which downgrades the whole page to- * the title tier.+ * chat() throws the gateway's normalized error, so the status, name and code+ * that decide the class can sit on any wrapped layer (#5964): the claude-cli+ * status as `apiErrorStatus`, an AI SDK `statusCode` on `cause` or on+ * RetryError's `lastError`, a `TimeoutError` name on `cause`. Only an error+ * that matches none of the transient classes is `malformed`, which makes the+ * service re-embed the whole page at the title tier.*/function classifyChatError(err: unknown): {kind: SynopsisFailureKind;@@ -297,33 +302,24 @@ function classifyChatError(err: unknown): {if (err == null) {return { kind: 'malformed', detail: 'null error' };}- const e = err as { message?: string; code?: string };- const msg = (e.message ?? String(err)).slice(0, 200);- const status = providerErrorStatus(err);- const chain = providerErrorChain(err) as Array<{ name?: unknown; code?: unknown }>;- const networkCode = chain.map((c) => c.code).find(- (code) => code === 'ENOTFOUND' || code === 'ECONNREFUSED' || code === 'ECONNRESET',- );+ const outer = err as { message?: unknown; code?: unknown };+ const msg = (typeof outer.message === 'string' ? outer.message : String(err)).slice(0, 200);+ const { status, names, codes } = readProviderFailureSignals(err);- if (status === 401 || status === 403) {- return { kind: 'auth_failure', detail: `status=${status} msg=${msg}` };- }- if (status === 429) {- return { kind: 'rate_limit', detail: `status=429 msg=${msg}` };- }- if (status != null && status >= 500 && status < 600) {- return { kind: 'provider_5xx', detail: `status=${status} msg=${msg}` };+ if (status !== undefined) {+ const byStatus: SynopsisFailureKind | null =+ status === 401 || status === 403 ? 'auth_failure'+ : status === 429 ? 'rate_limit'+ : status >= 500 && status < 600 ? 'provider_5xx'+ : null;+ if (byStatus) return { kind: byStatus, detail: `status=${status} msg=${msg}` };}- // The message test covers wrappers that drop the name: the claude-cli- // adapter rejects a timed-out or aborted call as "claude-cli adapter aborted".- if (- chain.some((c) => c.name === 'AbortError' || c.name === 'TimeoutError' || c.code === 'ETIMEDOUT') ||- /timeout|timed out|\baborted\b/i.test(msg)- ) {+ if (names.some(name => TIMEOUT_ERROR_NAMES.has(name)) || codes.includes('ETIMEDOUT') || TIMEOUT_MESSAGE_RE.test(msg)) {return { kind: 'timeout', detail: msg };}+ const networkCode = codes.find(code => NETWORK_ERROR_CODES.has(code));if (networkCode !== undefined || /network|fetch/i.test(msg)) {- return { kind: 'network', detail: `code=${networkCode ?? e.code ?? '?'} msg=${msg}` };+ return { kind: 'network', detail: `code=${networkCode ?? outer.code ?? '?'} msg=${msg}` };}// Unknown error shape — treat as malformed so the service routes itdiff --git a/test/contextual-retrieval-service-pure.test.ts b/test/contextual-retrieval-service-pure.test.tsindex 06f5085089..9a8ece47f5 100644--- a/test/contextual-retrieval-service-pure.test.ts+++ b/test/contextual-retrieval-service-pure.test.ts@@ -24,8 +24,8 @@ import {type ChatOpts,type ChatResult,} from '../src/core/ai/gateway.ts';+import { APICallError, RetryError } from 'ai';import { normalizeAIError } from '../src/core/ai/errors.ts';-import { ClaudeCliProcessError } from '../src/core/ai/providers/claude-cli-language-model.ts';import type { ChunkInput } from '../src/core/types.ts';import { MARKDOWN_CHUNKER_VERSION } from '../src/core/chunkers/recursive.ts';import { mockEmbedProjectionEngine } from './helpers/embed-projection-mock.ts';@@ -349,25 +349,38 @@ describe('per-chunk synopsis concurrency', () => {expect(started).toBeLessThanOrEqual(3);});- test('a claude-cli subscription limit is transient, not a title-tier downgrade (#5964)', async () => {+ // #5964: chat() hands the service a normalized error with the provider's+ // status on a wrapped layer. A provider outage must leave the page's mode+ // alone (transient, retried by the job), while a request-shaped 400 still+ // takes the page-level fall-back.+ const exhaustedRetries = (statusCode: number) => normalizeAIError(new RetryError({+ message: `Failed after 2 attempts (${statusCode})`,+ reason: 'maxRetriesExceeded',+ errors: [1, 2].map(() => new APICallError({+ message: `upstream said ${statusCode}`, url: 'https://llm.example.invalid/v1', requestBodyValues: {},+ statusCode, isRetryable: statusCode >= 500,+ })),+ }), 'chat(anthropic:claude-haiku-4-5)');++ test('a provider 503 behind RetryError stays transient and embeds nothing (#5964)', async () => {const out = await runWithChatStub({- chunks: makeChunks(['chunk-0', 'chunk-1']),- concurrency: 2,- chat: async () => {- // The error chat() throws for this failure: normalizeAIError keeps the- // claude-cli status as apiErrorStatus and leaves `status` unset.- throw normalizeAIError(- new ClaudeCliProcessError("claude-cli API error 429: You've hit your session limit", { apiErrorStatus: 429, exitCode: 1 }),- 'chat(claude-cli:claude-haiku-4-5)',- );- },+ chunks: makeChunks(['chunk-a', 'chunk-b', 'chunk-c']),+ concurrency: 1,+ chat: async () => { throw exhaustedRetries(503); },});- expect(out.result.kind).toBe('transient_error');- if (out.result.kind === 'transient_error') {- expect(out.result.cause).toBe('rate_limit');- }- expect(out.embeddedChunks).toHaveLength(0);+ expect(out.result).toMatchObject({ kind: 'transient_error', cause: 'provider_5xx' });+ expect(out.embeddedChunks).toEqual([]);+ });++ test('control: a request-shaped 400 behind RetryError still falls back at page level', async () => {+ const out = await runWithChatStub({+ chunks: makeChunks(['chunk-a', 'chunk-b']),+ concurrency: 1,+ chat: async () => { throw exhaustedRetries(400); },+ });++ expect(out.result.kind).toBe('page_fallback');});test('fenced code chunks bypass synopsis calls and leases', async () => {diff --git a/test/page-summary-chat-errors.test.ts b/test/page-summary-chat-errors.test.tsdeleted file mode 100644index e8f602d353..0000000000--- a/test/page-summary-chat-errors.test.ts+++ /dev/null@@ -1,107 +0,0 @@-/**- * #5964: generatePerChunkSynopsis classifies a thrown chat() error by its HTTP- * status and its timeout or abort signal, wherever the gateway's normalized- * error carries them.- *- * 1. Protects the D27 P1-2 dispatch: a rate limit, an auth failure, a- * provider outage or a timed-out call must not classify as `malformed`,- * because `malformed` makes the service re-embed the whole page at the- * `title` tier and the job report success.- * 2. Fails when the classifier reads only the top-level error: the claude-cli- * provider carries its status as `apiErrorStatus`, AI SDK providers carry- * `statusCode` on the wrapped error (`cause`, then RetryError's `lastError`- * once the SDK's retries are spent), an AI SDK timeout keeps its- * `TimeoutError` name on `cause`, and the claude-cli adapter rejects an- * aborted call with a plain "claude-cli adapter aborted" error.- * 3. The existing synopsis tests stub chat() whole, so no thrown error ever- * passed through normalizeAIError on its way to the classifier.- * 4. No new seam: it drives the real chat() through the existing- * generateText transport seam.- */-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';-import { APICallError, RetryError } from 'ai';-import { generatePerChunkSynopsis } from '../src/core/page-summary.ts';-import type { SynopsisFailureKind } from '../src/core/audit-synopsis.ts';-import {- __setGenerateTextTransportForTests,- configureGateway,- resetGateway,-} from '../src/core/ai/gateway.ts';-import { ClaudeCliProcessError } from '../src/core/ai/providers/claude-cli-language-model.ts';--const CLAUDE_CLI = 'claude-cli:claude-haiku-4-5';-const ANTHROPIC_API = 'anthropic:claude-haiku-4-5';--function claudeCliError(status: number | undefined, text: string): ClaudeCliProcessError {- const message = status === undefined ? text : `claude-cli API error ${status}: ${text}`;- return new ClaudeCliProcessError(message, { apiErrorStatus: status, exitCode: 1 });-}--function sdkError(statusCode: number): APICallError {- return new APICallError({- message: `synthetic provider error ${statusCode}`,- url: 'https://provider.example.invalid/v1/messages',- requestBodyValues: {},- statusCode,- isRetryable: statusCode === 429 || statusCode >= 500,- });-}--/** The AI SDK's shape once its retries on a retryable status are spent. */-function sdkRetriesExhausted(statusCode: number): RetryError {- const errors = [sdkError(statusCode), sdkError(statusCode), sdkError(statusCode)];- return new RetryError({- message: `Failed after 3 attempts. Last error: synthetic provider error ${statusCode}`,- reason: 'maxRetriesExceeded',- errors,- });-}--beforeEach(() => {- configureGateway({ env: { ANTHROPIC_API_KEY: 'fake-anthropic' } });-});--afterEach(() => {- __setGenerateTextTransportForTests(null);- resetGateway();-});--describe('generatePerChunkSynopsis classifies thrown chat errors by status and timeout (#5964)', () => {- const cases: Array<{ name: string; model: string; error: () => unknown; kind: SynopsisFailureKind }> = [- { name: 'claude-cli subscription limit (429)', model: CLAUDE_CLI, error: () => claudeCliError(429, "You've hit your session limit · resets 3:00am (UTC)"), kind: 'rate_limit' },- { name: 'claude-cli rejected credentials (401)', model: CLAUDE_CLI, error: () => claudeCliError(401, 'Invalid authentication credentials'), kind: 'auth_failure' },- { name: 'claude-cli forbidden (403)', model: CLAUDE_CLI, error: () => claudeCliError(403, 'Request not allowed'), kind: 'auth_failure' },- { name: 'claude-cli overloaded (529)', model: CLAUDE_CLI, error: () => claudeCliError(529, 'Overloaded'), kind: 'provider_5xx' },- { name: 'claude-cli failure with no status', model: CLAUDE_CLI, error: () => claudeCliError(undefined, 'claude-cli returned an unexpected result'), kind: 'malformed' },- { name: 'API provider rejected key (401, not retried)', model: ANTHROPIC_API, error: () => sdkError(401), kind: 'auth_failure' },- { name: 'API provider rate limit after retries (429)', model: ANTHROPIC_API, error: () => sdkRetriesExhausted(429), kind: 'rate_limit' },- { name: 'API provider outage after retries (529)', model: ANTHROPIC_API, error: () => sdkRetriesExhausted(529), kind: 'provider_5xx' },- { name: 'API provider request-shaped 400', model: ANTHROPIC_API, error: () => sdkError(400), kind: 'malformed' },- // The reason AbortSignal.timeout() rejects with when the gateway's default chat timeout fires.- { name: 'API provider call timed out', model: ANTHROPIC_API, error: () => new DOMException('The operation timed out.', 'TimeoutError'), kind: 'timeout' },- { name: 'API provider call aborted', model: ANTHROPIC_API, error: () => new DOMException('The operation was aborted.', 'AbortError'), kind: 'timeout' },- { name: 'claude-cli call timed out or aborted', model: CLAUDE_CLI, error: () => new Error('claude-cli adapter aborted'), kind: 'timeout' },- { name: 'API provider connection reset on the wrapped cause', model: ANTHROPIC_API, error: () => new Error('socket closed by peer', { cause: Object.assign(new Error('read failed'), { code: 'ECONNRESET' }) }), kind: 'network' },- { name: 'thrown primitive string with no status', model: ANTHROPIC_API, error: () => 'unexpected provider reply', kind: 'malformed' },- ];-- for (const c of cases) {- test(`${c.name} -> ${c.kind}`, async () => {- __setGenerateTextTransportForTests((async () => {- throw c.error();- }) as never);-- const result = await generatePerChunkSynopsis({- documentText: 'Full document text about widget-co.',- chunkText: 'The chunk about the widget-co launch.',- pageTitle: 'Widget Co',- pageSlug: 'companies/widget-co',- sourceId: 'default',- chunkIndex: 0,- model: c.model,- });-- expect(result.kind).toBe(c.kind);- });- }-});diff --git a/test/synopsis-chat-failure-class.test.ts b/test/synopsis-chat-failure-class.test.tsnew file mode 100644index 0000000000..6de393fb6d--- /dev/null+++ b/test/synopsis-chat-failure-class.test.ts@@ -0,0 +1,121 @@+/**+ * #5964: a thrown chat() error is classified for the per-chunk synopsis by the+ * status, name and code on ANY layer of the gateway's normalized error.+ *+ * 1. Protects the D27 P1-2 dispatch: rate limits, auth failures, provider+ * outages, timeouts and network faults must not land in `malformed`, the+ * class that re-embeds the whole page at the title tier and reports success.+ * 2. Fails when the classifier reads only the outermost error: chat() keeps+ * the provider's error on `cause` (claude-cli `apiErrorStatus`, AI SDK+ * `statusCode`, RetryError `lastError`, a DOMException `TimeoutError`).+ * 3. Existing synopsis tests stub chat() whole, so no error ever went through+ * normalizeAIError on its way to the classifier.+ * 4. No new seam: the real chat() runs behind the existing generateText+ * transport seam; the bounded-walk cases call the exported reader directly.+ */+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { APICallError, RetryError } from 'ai';+import { ClaudeCliProcessError } from '../src/core/ai/providers/claude-cli-language-model.ts';+import { readProviderFailureSignals } from '../src/core/ai/errors.ts';+import { __setGenerateTextTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import type { SynopsisFailureKind } from '../src/core/audit-synopsis.ts';+import { generatePerChunkSynopsis } from '../src/core/page-summary.ts';++const CLI_ROUTE = 'claude-cli:claude-haiku-4-5';+const API_ROUTE = 'anthropic:claude-haiku-4-5';++const cliFailure = (apiErrorStatus: number | undefined, text: string) =>+ new ClaudeCliProcessError(apiErrorStatus === undefined ? text : `claude-cli API error ${apiErrorStatus}: ${text}`,+ { apiErrorStatus, exitCode: 1 });++const httpFailure = (statusCode: number) => new APICallError({+ message: `provider answered ${statusCode}`, url: 'https://llm.example.invalid/v1/messages', requestBodyValues: {},+ statusCode, isRetryable: statusCode >= 500 || statusCode === 429,+});++const afterRetries = (statusCode: number) => new RetryError({+ message: `Failed after 2 attempts. Last error: provider answered ${statusCode}`,+ reason: 'maxRetriesExceeded',+ errors: [httpFailure(statusCode), httpFailure(statusCode)],+});++async function classify(model: string, thrown: () => unknown): Promise<string> {+ __setGenerateTextTransportForTests((async () => { throw thrown(); }) as never);+ const result = await generatePerChunkSynopsis({+ documentText: 'Notes on the acme-example rollout.',+ chunkText: 'The rollout slipped a week.',+ pageTitle: 'Acme Example',+ pageSlug: 'companies/acme-example',+ sourceId: 'default',+ chunkIndex: 0,+ model,+ });+ return result.kind;+}++beforeEach(() => {+ configureGateway({ env: { ANTHROPIC_API_KEY: 'sk-ant-placeholder' } });+});++afterEach(() => {+ resetGateway();+ __setGenerateTextTransportForTests(null);+});++describe('synopsis chat failures are classified through the wrapped error (#5964)', () => {+ const rows: Array<[label: string, model: string, thrown: () => unknown, expected: SynopsisFailureKind]> = [+ ['claude-cli usage limit 429', CLI_ROUTE, () => cliFailure(429, 'usage limit reached'), 'rate_limit'],+ ['claude-cli 401', CLI_ROUTE, () => cliFailure(401, 'invalid credentials'), 'auth_failure'],+ ['claude-cli 503', CLI_ROUTE, () => cliFailure(503, 'service unavailable'), 'provider_5xx'],+ ['claude-cli adapter abort (timeout or cancel)', CLI_ROUTE, () => new Error('claude-cli adapter aborted'), 'timeout'],+ ['SDK 403, not retried', API_ROUTE, () => httpFailure(403), 'auth_failure'],+ ['SDK 429 after retries', API_ROUTE, () => afterRetries(429), 'rate_limit'],+ ['SDK 502 after retries', API_ROUTE, () => afterRetries(502), 'provider_5xx'],+ ['SDK default chat timeout', API_ROUTE, () => new DOMException('The operation timed out.', 'TimeoutError'), 'timeout'],+ ['wrapped ETIMEDOUT', API_ROUTE, () => new Error('request failed', { cause: Object.assign(new Error('socket'), { code: 'ETIMEDOUT' }) }), 'timeout'],+ ['wrapped ECONNREFUSED', API_ROUTE, () => new Error('request failed', { cause: Object.assign(new Error('connect'), { code: 'ECONNREFUSED' }) }), 'network'],+ // Controls: request-shaped or statusless failures stay malformed.+ ['control: claude-cli without a status', CLI_ROUTE, () => cliFailure(undefined, 'claude-cli returned no result'), 'malformed'],+ ['control: claude-cli 400', CLI_ROUTE, () => cliFailure(400, 'prompt is too long'), 'malformed'],+ ['control: SDK 404', API_ROUTE, () => httpFailure(404), 'malformed'],+ ['control: "aborted" in an unrelated message', API_ROUTE, () => new Error('upstream reply aborted mid-stream by policy'), 'malformed'],+ ['control: a status given as a string', API_ROUTE, () => Object.assign(new Error('odd provider'), { cause: { statusCode: '429' } }), 'malformed'],+ ['control: a NaN status', API_ROUTE, () => Object.assign(new Error('odd provider'), { cause: { status: Number.NaN } }), 'malformed'],+ ];++ for (const [label, model, thrown, expected] of rows) {+ test(`${label} -> ${expected}`, async () => {+ expect(await classify(model, thrown)).toBe(expected);+ });+ }+});++describe('readProviderFailureSignals walks a bounded chain', () => {+ test('outermost status wins over a deeper one', () => {+ const err = Object.assign(new Error('outer'), { status: 503, cause: { statusCode: 429 } });+ expect(readProviderFailureSignals(err).status).toBe(503);+ });++ test('a self-referencing cause terminates and reads each layer once', () => {+ const err = Object.assign(new Error('loop'), { code: 'ECONNRESET' }) as Error & { cause?: unknown };+ err.cause = err;+ expect(readProviderFailureSignals(err)).toEqual({ status: undefined, names: ['Error'], codes: ['ECONNRESET'] });+ });++ test('a status beyond five layers is not read', () => {+ let err: unknown = { statusCode: 429 };+ for (let i = 0; i < 5; i++) err = { cause: err };+ expect(readProviderFailureSignals(err).status).toBeUndefined();+ });++ test('a throwing getter ends the walk without throwing and keeps what was read', () => {+ const hostile = { status: 429, get cause(): unknown { throw new Error('getter trap'); } };+ expect(readProviderFailureSignals(hostile).status).toBe(429);+ });++ test('primitives and null carry no signals', () => {+ for (const value of [null, undefined, 'rate limited', 429]) {+ expect(readProviderFailureSignals(value)).toEqual({ status: undefined, names: [], codes: [] });+ }+ });+});