Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

synopsis: cache the page document across per-chunk synopsis calls (PR #6341)

garrytana78d7f80fff8
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index e75395f478..a7aca9d54b 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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/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; and `'empty_response'` (#6448): a zero-tool-call clean stop whose text is empty or whitespace-only, so a refusal body or thinking-only turn is never reported as a finished answer (the subagent handler maps it to `error`). 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/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; and `'empty_response'` (#6448): a zero-tool-call clean stop whose text is empty or whitespace-only, so a refusal body or thinking-only turn is never reported as a finished answer (the subagent handler maps it to `error`). 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. **Prompt-cache breakpoints:** `cacheSystem: true` on a prompt-cache-capable route derives ONE `cacheControlValue` (config TTL override honoured) that marks the system block, the last tool def, the call-level auto marker and, since PR #6341, any user text `ChatBlock` flagged `cache: true` (`toModelMessages(messages, cacheControlValue)` merges `providerOptions.anthropic.cacheControl` onto that block); without a value the flag is dropped and the block is plain text, so non-caching routes and the claude-cli adapter (which joins text parts with `\n`) see the same prompt text. Pinned by `test/page-summary-prompt-cache.test.ts`.
- `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.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 94d3c5537d..be84363e62 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -60,5 +60,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/page-state/version-types.ts` — complete canonical version contract with nullable legacy fields, re-exported by `types.ts` for existing callers. `page-state/versions.ts` records deletion, timeline, tags and originating revision in the page publication transaction.
+- `src/core/page-summary.ts` — `generatePerChunkSynopsis`: the per-chunk synopsis call (utility-tier default, `thinking: 'off'`, `SYNOPSIS_DOC_MAX_CHARS` surrogate-safe head truncation, D27 failure envelope). One user message of TWO text blocks (PR #6341): the stable title + document block flagged `cache: true` (the only prefix every chunk of a page shares) and the per-chunk block; joined with `\n` they equal the former single string, so `SYNOPSIS_PROMPT_VERSION` stays 1. Pinned by `test/page-summary-prompt-cache.test.ts`.
+
- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 821a174f3c..cd30d6c834 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -2787,7 +2787,10 @@ export type ChatRole = 'system' | 'user' | 'assistant' | 'tool';
* on turn 2 without this: `chat()` previously never captured the part at all.
*/
export type ChatBlock =
- | { type: 'text'; text: string; providerMetadata?: Record<string, unknown> }
+ // `cache: true` (PR #6341): an explicit prompt-cache breakpoint after this block, so a
+ // single-turn caller's stable USER prefix (page-summary's title + document) caches. Honoured
+ // only when the call derives a cache-control value; other routes see a plain text block.
+ | { type: 'text'; text: string; cache?: true; providerMetadata?: Record<string, unknown> }
| { type: 'reasoning'; text: string; providerMetadata?: Record<string, unknown> }
| { type: 'tool-call'; toolCallId: string; toolName: string; input: unknown; providerMetadata?: Record<string, unknown> }
| { type: 'tool-result'; toolCallId: string; toolName: string; output: unknown; isError?: boolean; providerMetadata?: Record<string, unknown> };
@@ -2920,7 +2923,10 @@ function ensureToolCallId(id: unknown, toolName: string): string {
return `glmfix-${toolName}-${randomUUID()}`;
}
-export function toModelMessages(messages: ChatMessage[]): unknown[] {
+export function toModelMessages(
+ messages: ChatMessage[],
+ cacheControl?: { type: 'ephemeral'; ttl?: '5m' | '1h' },
+): unknown[] {
return messages.map((m) => {
if (typeof m.content === 'string') return { role: m.role, content: m.content };
const blocks = m.content;
@@ -2957,10 +2963,13 @@ export function toModelMessages(messages: ChatMessage[]): unknown[] {
// Gemini 3.x thoughtSignature, OpenAI reasoning-item id) — attached
// only when captured.
if (b.type === 'text') {
+ const providerOptions = b.cache && cacheControl
+ ? { ...b.providerMetadata, anthropic: { ...(b.providerMetadata?.anthropic as Record<string, unknown> | undefined), cacheControl } }
+ : b.providerMetadata;
return {
type: 'text' as const,
text: b.text,
- ...(b.providerMetadata ? { providerOptions: b.providerMetadata } : {}),
+ ...(providerOptions ? { providerOptions } : {}),
};
}
if (b.type === 'reasoning') {
@@ -3714,7 +3723,7 @@ async function chatAdmitted(opts: ChatOpts, admitted: {
const generate = (out: typeof output) => guardedGeneration(modelStr, _generateTextTransport, {
model,
system: systemParam,
- messages: toModelMessages(repairToolPairing(opts.messages)) as any,
+ messages: toModelMessages(repairToolPairing(opts.messages), cacheControlValue) as any,
tools: opts.tools && opts.tools.length > 0 ? tools : undefined,
maxOutputTokens,
...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),
diff --git a/src/core/page-summary.ts b/src/core/page-summary.ts
index ab9809e044..838b106081 100644
--- a/src/core/page-summary.ts
+++ b/src/core/page-summary.ts
@@ -162,7 +162,6 @@ export type GeneratePerChunkSynopsisResult =
export async function generatePerChunkSynopsis(
args: GeneratePerChunkSynopsisArgs,
): Promise<GeneratePerChunkSynopsisResult> {
- const userPrompt = buildUserPrompt(args.pageTitle, args.documentText, args.chunkText);
const maxTokens = args.maxTokens ?? SYNOPSIS_MAX_TOKENS;
const chatOpts: ChatOpts = {
@@ -170,7 +169,19 @@ export async function generatePerChunkSynopsis(
// an OPENAI_API_KEY-only install must not route to Anthropic.
model: args.model ?? resolveTierDefault('utility'),
system: SYSTEM_PROMPT,
- messages: [{ role: 'user', content: userPrompt }],
+ // PR #6341: the title + document block is the only prefix every chunk of
+ // a page shares (the ~190-token system prompt is below every published
+ // minimum cacheable length), so it rides on its own `cache: true` block
+ // and the chunk follows in a second block. Joined with '\n' the two are
+ // byte-identical to the former single string (that is how the claude-cli
+ // adapter renders them), so SYNOPSIS_PROMPT_VERSION is unchanged.
+ messages: [{
+ role: 'user',
+ content: [
+ { type: 'text', text: buildPagePrompt(args.pageTitle, args.documentText), cache: true },
+ { type: 'text', text: buildChunkPrompt(args.chunkText) },
+ ],
+ }],
maxTokens,
thinking: 'off',
abortSignal: args.abortSignal,
@@ -251,11 +262,7 @@ export async function generatePerChunkSynopsis(
return { kind: 'success', synopsis, usage: result.usage };
}
-function buildUserPrompt(
- pageTitle: string,
- documentText: string,
- chunkText: string,
-): string {
+function buildPagePrompt(pageTitle: string, documentText: string): string {
// Tail-truncate `documentText` to `SYNOPSIS_DOC_MAX_CHARS` so small local
// chat models don't stall on >100KB pages. Head preserved (title block,
// frontmatter, intro paragraphs carry the document-level anchor).
@@ -271,6 +278,11 @@ function buildUserPrompt(
'<full_document>',
trimmedDoc,
'</full_document>',
+ ].join('\n');
+}
+
+function buildChunkPrompt(chunkText: string): string {
+ return [
'',
'<chunk>',
chunkText,
diff --git a/test/contextual-retrieval-service-pure.test.ts b/test/contextual-retrieval-service-pure.test.ts
index 9a8ece47f5..fec390eb85 100644
--- a/test/contextual-retrieval-service-pure.test.ts
+++ b/test/contextual-retrieval-service-pure.test.ts
@@ -569,7 +569,10 @@ function makeServiceEngine(chunks: ChunkInput[]) {
}
function extractChunk(opts: ChatOpts): string {
- const content = String(opts.messages[0]?.content ?? '');
+ // The synopsis prompt is two text blocks (page, chunk) since PR #6341;
+ // joined with '\n' they render as the former single string.
+ const raw = opts.messages[0]?.content ?? '';
+ const content = typeof raw === 'string' ? raw : raw.map(b => (b.type === 'text' ? b.text : '')).join('\n');
return content.match(/<chunk>\n([\s\S]*?)\n<\/chunk>/)?.[1] ?? '';
}
diff --git a/test/eval-longmemeval-synopsis-tier.serial.test.ts b/test/eval-longmemeval-synopsis-tier.serial.test.ts
index 85b07c59a2..6a6c3617ff 100644
--- a/test/eval-longmemeval-synopsis-tier.serial.test.ts
+++ b/test/eval-longmemeval-synopsis-tier.serial.test.ts
@@ -60,7 +60,8 @@ beforeAll(() => {
__setEmbedTransportForTests(embedTransport);
__setChatTransportForTests(async (opts) => {
chatModels.push(String(opts.model));
- const user = String(opts.messages[0]?.content ?? '');
+ const raw = opts.messages[0]?.content ?? '';
+ const user = typeof raw === 'string' ? raw : raw.map(b => (b.type === 'text' ? b.text : '')).join('\n');
const chunk = user.slice(user.indexOf('<chunk>') + 8, user.indexOf('</chunk>')).trim();
return {
text: `Synopsis: ${chunk.split(/\s+/).slice(0, 4).join(' ')}`, blocks: [], stopReason: 'end',
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 644f08ac14..74acacdfac 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -1637,7 +1637,7 @@
"kind": "type",
"name": "ChatBlock",
"signature": [
- "{ type: \"text\"; text: string; providerMetadata?: Record<string, unknown>; } | { type: \"reasoning\"; text: string; providerMetadata?: Record<string, unknown>; } | { type: \"tool-call\"; toolCallId: string; toolName: string; input: unknown; providerMetadata?: Record<string, unknown>; } | { type: \"tool-result\"; toolCallId: string; toolName: string; output: unknown; isError?: boolean; providerMetadata?: Record<string, unknown>; }"
+ "{ type: \"text\"; text: string; cache?: true; providerMetadata?: Record<string, unknown>; } | { type: \"reasoning\"; text: string; providerMetadata?: Record<string, unknown>; } | { type: \"tool-call\"; toolCallId: string; toolName: string; input: unknown; providerMetadata?: Record<string, unknown>; } | { type: \"tool-result\"; toolCallId: string; toolName: string; output: unknown; isError?: boolean; providerMetadata?: Record<string, unknown>; }"
]
},
{
@@ -2379,7 +2379,7 @@
"kind": "function",
"name": "toModelMessages",
"signature": [
- "(messages: ChatMessage[]) => unknown[]"
+ "(messages: ChatMessage[], cacheControl?: { type: \"ephemeral\"; ttl?: \"5m\" | \"1h\"; }) => unknown[]"
]
},
{
diff --git a/test/page-summary-length.serial.test.ts b/test/page-summary-length.serial.test.ts
index a51fbb2b3b..667654f2ce 100644
--- a/test/page-summary-length.serial.test.ts
+++ b/test/page-summary-length.serial.test.ts
@@ -130,7 +130,10 @@ describe('surrogate-safe document truncation (#5316)', () => {
'a'.repeat(SYNOPSIS_DOC_MAX_CHARS - 1) + '𝑇' + 'b'.repeat(100);
const result = await generatePerChunkSynopsis({ ...baseArgs, documentText });
expect(result.kind).toBe('success');
- const prompt = captured[0].messages[0].content as string;
+ // Two text blocks since PR #6341 (page, chunk); the truncation lives in the page block.
+ const content = captured[0].messages[0].content;
+ expect(typeof content).not.toBe('string');
+ const prompt = (content as Array<{ type: string; text: string }>).map(b => b.text).join('\n');
expect(prompt.isWellFormed()).toBe(true);
expect(() => JSON.parse(JSON.stringify(prompt))).not.toThrow();
expect(prompt).toContain('chars truncated for synopsis budget');
diff --git a/test/page-summary-prompt-cache.test.ts b/test/page-summary-prompt-cache.test.ts
new file mode 100644
index 0000000000..eedf17d670
--- /dev/null
+++ b/test/page-summary-prompt-cache.test.ts
@@ -0,0 +1,259 @@
+/**
+ * PR #6341 takeover — the per-chunk synopsis prompt must put the page
+ * document on its own cacheable block.
+ *
+ * `generatePerChunkSynopsis` sent ONE user string holding the title, the
+ * (up to 32K-char) document and the chunk. The only explicit Anthropic
+ * breakpoint `chat()` placed was the ~190-token system block, which is below
+ * every published minimum cacheable length, and the call-level auto marker
+ * lands on the varying tail. So every chunk of the same page WROTE a fresh
+ * cache entry and never READ one.
+ *
+ * Fix under test: the prompt is two text blocks — a stable `{title,
+ * document}` block flagged `cache: true` and a per-chunk block — and
+ * `toModelMessages` turns that flag into the block's
+ * `providerOptions.anthropic.cacheControl` ONLY when the call has a
+ * cache-control value (Anthropic-class route with `cacheSystem`). Non-caching
+ * routes see plain text blocks; the claude-cli adapter joins text parts with
+ * '\n', so the rendered prompt text is byte-identical to the old string and
+ * `SYNOPSIS_PROMPT_VERSION` stays at 1.
+ *
+ * These cases inspect the exact args handed to the `generateText` transport,
+ * the same way `test/ai/gateway-cache-breakpoint.test.ts` does.
+ */
+import { describe, test, expect, beforeEach, afterAll } from 'bun:test';
+import {
+ chat,
+ configureGateway,
+ resetGateway,
+ toModelMessages,
+ __setChatTransportForTests,
+ __setGenerateTextTransportForTests,
+ type ChatOpts,
+ type ChatBlock,
+} from '../src/core/ai/gateway.ts';
+import {
+ generatePerChunkSynopsis,
+ SYNOPSIS_PROMPT_VERSION,
+} from '../src/core/page-summary.ts';
+
+const pageArgs = {
+ documentText: 'Full document text about acme-example fundraising.\n\nA second paragraph.',
+ pageTitle: 'Acme Example',
+ pageSlug: 'companies/acme-example',
+ sourceId: 'default',
+};
+
+/** The single string the synopsis prompt was before the split — the token stream to preserve. */
+function legacyPrompt(title: string, document: string, chunk: string): string {
+ return [
+ `<page_title>${title}</page_title>`,
+ '',
+ '<full_document>',
+ document,
+ '</full_document>',
+ '',
+ '<chunk>',
+ chunk,
+ '</chunk>',
+ '',
+ 'Write the one-sentence synopsis for <chunk>:',
+ ].join('\n');
+}
+
+function textBlocks(content: string | ChatBlock[]): Array<Extract<ChatBlock, { type: 'text' }>> {
+ if (typeof content === 'string') throw new Error(`expected text blocks, got a string: ${content.slice(0, 40)}…`);
+ return content.filter((b): b is Extract<ChatBlock, { type: 'text' }> => b.type === 'text');
+}
+
+afterAll(() => {
+ resetGateway();
+ __setChatTransportForTests(null);
+ __setGenerateTextTransportForTests(null);
+});
+
+describe('generatePerChunkSynopsis prompt shape', () => {
+ beforeEach(() => {
+ resetGateway();
+ __setChatTransportForTests(null);
+ __setGenerateTextTransportForTests(null);
+ });
+
+ async function captureChatOpts(chunkText: string, chunkIndex: number): Promise<ChatOpts> {
+ const captured: ChatOpts[] = [];
+ __setChatTransportForTests(async (opts: ChatOpts) => {
+ captured.push(opts);
+ return {
+ text: 'A one-sentence synopsis about the chunk.',
+ blocks: [],
+ stopReason: 'end',
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:stub',
+ providerId: 'anthropic',
+ };
+ });
+ const result = await generatePerChunkSynopsis({ ...pageArgs, chunkText, chunkIndex });
+ expect(result.kind).toBe('success');
+ expect(captured).toHaveLength(1);
+ return captured[0]!;
+ }
+
+ test('two user text blocks: the page block (title + document) is flagged cache: true, the chunk block is not', async () => {
+ const opts = await captureChatOpts('The chunk text about the series A.', 0);
+ expect(opts.messages).toHaveLength(1);
+ expect(opts.messages[0]!.role).toBe('user');
+ const blocks = textBlocks(opts.messages[0]!.content);
+ expect(blocks).toHaveLength(2);
+ expect(blocks[0]!.cache).toBe(true);
+ expect(blocks[0]!.text).toContain('<page_title>Acme Example</page_title>');
+ expect(blocks[0]!.text).toContain(pageArgs.documentText);
+ expect(blocks[0]!.text).not.toContain('<chunk>');
+ expect(blocks[1]!.cache).toBeUndefined();
+ expect(blocks[1]!.text).toContain('<chunk>\nThe chunk text about the series A.\n</chunk>');
+ expect(blocks[1]!.text).not.toContain('<full_document>');
+ expect(opts.cacheSystem).toBe(true);
+ });
+
+ test('the blocks joined with a newline are byte-identical to the previous single-string prompt; the prompt version is unchanged', async () => {
+ const chunk = 'The chunk text about the series A.';
+ const opts = await captureChatOpts(chunk, 0);
+ const rendered = textBlocks(opts.messages[0]!.content).map(b => b.text).join('\n');
+ expect(rendered).toBe(legacyPrompt(pageArgs.pageTitle, pageArgs.documentText, chunk));
+ expect(SYNOPSIS_PROMPT_VERSION).toBe(1);
+ });
+
+ test('two chunks of one page share a byte-identical page block and differ only in the chunk block', async () => {
+ const a = textBlocks((await captureChatOpts('First chunk.', 0)).messages[0]!.content);
+ const b = textBlocks((await captureChatOpts('Second chunk.', 1)).messages[0]!.content);
+ expect(a[0]!.text).toBe(b[0]!.text);
+ expect(a[1]!.text).not.toBe(b[1]!.text);
+ });
+
+ test('a document over the synopsis budget is truncated inside the page block, so the cached prefix is bounded', async () => {
+ const { SYNOPSIS_DOC_MAX_CHARS } = await import('../src/core/page-summary.ts');
+ const captured: ChatOpts[] = [];
+ __setChatTransportForTests(async (opts: ChatOpts) => {
+ captured.push(opts);
+ return {
+ text: 'ok', blocks: [], stopReason: 'end',
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:stub', providerId: 'anthropic',
+ };
+ });
+ await generatePerChunkSynopsis({ ...pageArgs, documentText: 'x'.repeat(SYNOPSIS_DOC_MAX_CHARS + 500), chunkText: 'c', chunkIndex: 0 });
+ const [page, chunk] = textBlocks(captured[0]!.messages[0]!.content);
+ expect(page!.text).toContain('chars truncated for synopsis budget');
+ expect(page!.text.length).toBeLessThan(SYNOPSIS_DOC_MAX_CHARS + 200);
+ expect(chunk!.text).not.toContain('truncated');
+ });
+});
+
+describe('chat() wire shape for a cache-flagged text block', () => {
+ beforeEach(() => {
+ resetGateway();
+ __setChatTransportForTests(null);
+ __setGenerateTextTransportForTests(null);
+ });
+
+ const twoBlockMessage = (): ChatOpts['messages'] => [{
+ role: 'user',
+ content: [
+ { type: 'text', text: '<page_title>T</page_title>\n\n<full_document>\nD\n</full_document>', cache: true },
+ { type: 'text', text: '\n<chunk>\nC\n</chunk>\n\nWrite the one-sentence synopsis for <chunk>:' },
+ ],
+ }];
+
+ async function captureWire(model: string, env: Record<string, string>, opts: Partial<ChatOpts> = {}, cfg: Record<string, unknown> = {}): Promise<any> {
+ let captured: any;
+ __setGenerateTextTransportForTests(async (args: any) => {
+ captured = args;
+ return { content: [{ type: 'text', text: 'ok' }], finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;
+ });
+ configureGateway({ chat_model: model, env, ...cfg } as any);
+ await chat({ model, system: 'SYS', cacheSystem: true, messages: twoBlockMessage(), ...opts });
+ return captured;
+ }
+
+ test('Anthropic + cacheSystem: the page block carries the same cacheControl as the system block; the chunk block carries none; the `cache` flag never reaches the wire', async () => {
+ const args = await captureWire('anthropic:claude-sonnet-4-6', { ANTHROPIC_API_KEY: 'fake' });
+ const systemCc = (args.system as any)?.providerOptions?.anthropic?.cacheControl;
+ expect(systemCc).toEqual({ type: 'ephemeral' });
+ const [page, chunk] = args.messages[0].content;
+ expect(page).toEqual({
+ type: 'text',
+ text: '<page_title>T</page_title>\n\n<full_document>\nD\n</full_document>',
+ providerOptions: { anthropic: { cacheControl: systemCc } },
+ });
+ expect(chunk).toEqual({ type: 'text', text: '\n<chunk>\nC\n</chunk>\n\nWrite the one-sentence synopsis for <chunk>:' });
+ expect('cache' in page).toBe(false);
+ // Explicit breakpoints in this request: system + page block (+ none for
+ // tools) = 2, plus the call-level auto marker — within Anthropic's four.
+ expect(args.providerOptions?.anthropic?.cacheControl).toEqual({ type: 'ephemeral' });
+ });
+
+ test('a configured cacheControl TTL override reaches the page block too (one canonical value per request)', async () => {
+ const args = await captureWire('anthropic:claude-sonnet-4-6', { ANTHROPIC_API_KEY: 'fake' }, {}, {
+ provider_chat_options: { anthropic: { cacheControl: { type: 'ephemeral', ttl: '1h' } } },
+ });
+ expect(args.messages[0].content[0].providerOptions).toEqual({ anthropic: { cacheControl: { type: 'ephemeral', ttl: '1h' } } });
+ });
+
+ test('Anthropic without cacheSystem: plain text blocks, no providerOptions, no `cache` key', async () => {
+ const args = await captureWire('anthropic:claude-sonnet-4-6', { ANTHROPIC_API_KEY: 'fake' }, { cacheSystem: false });
+ expect(typeof args.system).toBe('string');
+ for (const part of args.messages[0].content) {
+ expect(Object.keys(part).sort()).toEqual(['text', 'type']);
+ }
+ });
+
+ test('a recipe that declares no prompt caching gets plain text blocks even with cacheSystem: true', async () => {
+ const { getProviderCapabilities } = await import('../src/core/ai/capabilities.ts');
+ expect(getProviderCapabilities('google:gemini-1.5-pro').supportsPromptCaching).toBe(false);
+ const args = await captureWire('google:gemini-1.5-pro', { GOOGLE_GENERATIVE_AI_API_KEY: 'fake' });
+ expect(typeof args.system).toBe('string');
+ for (const part of args.messages[0].content) {
+ expect(Object.keys(part).sort()).toEqual(['text', 'type']);
+ }
+ });
+});
+
+describe('toModelMessages honours `cache: true` only with a cache-control value', () => {
+ const msgs = (): ChatOpts['messages'] => [{
+ role: 'user',
+ content: [
+ { type: 'text', text: 'stable', cache: true, providerMetadata: { openai: { itemId: 'x' } } },
+ { type: 'text', text: 'varying' },
+ ],
+ }];
+
+ test('no cache-control value: the flag is dropped and captured providerMetadata still round-trips', () => {
+ expect(toModelMessages(msgs())).toEqual([{
+ role: 'user',
+ content: [
+ { type: 'text', text: 'stable', providerOptions: { openai: { itemId: 'x' } } },
+ { type: 'text', text: 'varying' },
+ ],
+ }]);
+ });
+
+ test('with a cache-control value: the anthropic breakpoint is merged next to existing providerOptions on the flagged block only', () => {
+ expect(toModelMessages(msgs(), { type: 'ephemeral', ttl: '1h' })).toEqual([{
+ role: 'user',
+ content: [
+ { type: 'text', text: 'stable', providerOptions: { openai: { itemId: 'x' }, anthropic: { cacheControl: { type: 'ephemeral', ttl: '1h' } } } },
+ { type: 'text', text: 'varying' },
+ ],
+ }]);
+ });
+
+ test('a string message and assistant blocks are untouched by the value', () => {
+ const input: ChatOpts['messages'] = [
+ { role: 'user', content: 'hello' },
+ { role: 'assistant', content: [{ type: 'text', text: 'hi' }] },
+ ];
+ expect(toModelMessages(input, { type: 'ephemeral' })).toEqual([
+ { role: 'user', content: 'hello' },
+ { role: 'assistant', content: [{ type: 'text', text: 'hi' }] },
+ ]);
+ });
+});