Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(minions): subagent turns get a per-turn timeout instead of the 300 s chat backstop (#4921)
time-attack5940a3203585
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex 5493f0d516..73e226f5cf 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -14,7 +14,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/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (`test/ai/gateway.test.ts` drives both layers through `embed()`). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance.+- `src/core/ai/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).- `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-minions-1.md b/docs/architecture/key-files/core-minions-1.mdindex 1d8877dfb9..2d48aec44b 100644--- a/docs/architecture/key-files/core-minions-1.md+++ b/docs/architecture/key-files/core-minions-1.md@@ -32,7 +32,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/errors.ts` — dependency-free `UnrecoverableError` and `JobDeferredError(reason, message, retryInMs)`, re-exported through `types.ts` for compatibility. Delegated policy imports this leaf directly, avoiding initialization cycles through durable authority. Fresh-process import tests preserve the shared error identity and isolated-worker reconstruction. A `JobDeferredError` returns the job to `delayed` for `retryInMs` through `MinionQueue.deferJob` (no attempt counted, no stacktrace entry); the worker, the facts drain and the isolation codec (`errorKind: 'deferred'`) all route it (`test/facts-absorb-keyless-deferral.test.ts`).-- `src/core/minions/handler-timeouts.ts` — per-handler-type defaults for BOTH per-job time knobs, co-located so they can't drift apart unseen (they are different quantities: the budget bounds total runtime, the lease bounds dead-worker reclaim — never derive one from the other). `HANDLER_DEFAULT_TIMEOUT_MS`: 30 min for `subagent`, `subagent_aggregator`, `embed-backfill`, `autopilot-cycle`, `autopilot-global-maintenance`, `extract` (a brain-wide `extract --stale` pass); 10 min for `chronicle_extract` + `facts-absorb`; 60 min for `contextual_reindex_per_chunk`. `HANDLER_DEFAULT_LOCK_DURATION_MS`: 300 s for the long LLM/loop handlers, 120 s for the single-LLM-call handlers, `shell` deliberately absent (fast dead-worker reclaim; verify-before-evict protects it anyway). `defaultTimeoutMsFor` / `defaultLockDurationMsFor` return the mapped default or `null` (short handlers keep the tight null-default wall-clock / the 30 s worker lease). `clampLockDurationMs` + `LOCK_DURATION_MS_MIN/MAX` ([5s, 1h]) is the ONE clamp shared by `queue.add`, the CLI `--lock-duration-ms` flag (`--dry-run` echoes the clamped value), and the MCP `submit_job` param; the same bound is mirrored in SQL at claim time and by the `minion_jobs.lock_duration_ms` range CHECK, so every layer agrees. Layers (explicit value always wins): `MinionQueue.add()` stamps at submit; `MinionQueue.claim()` COALESCEs NULL columns from the maps (durable invariant); migration v128 one-shot backfilled `timeout_ms` with authoring-time snapshot values — do NOT sync v128 when editing the maps (`lock_duration_ms` has no backfill: NULL = worker default). Pinned by `test/minions.test.ts` + `test/migrations-v128.test.ts` + `test/migrations-v130.test.ts`.+- `src/core/minions/handler-timeouts.ts` — per-handler-type defaults for BOTH per-job time knobs, co-located so they can't drift apart unseen (they are different quantities: the budget bounds total runtime, the lease bounds dead-worker reclaim — never derive one from the other). `HANDLER_DEFAULT_TIMEOUT_MS`: 30 min for `subagent`, `subagent_aggregator`, `embed-backfill`, `autopilot-cycle`, `autopilot-global-maintenance`, `extract` (a brain-wide `extract --stale` pass); 10 min for `chronicle_extract` + `facts-absorb`; 60 min for `contextual_reindex_per_chunk`. `HANDLER_DEFAULT_LOCK_DURATION_MS`: 300 s for the long LLM/loop handlers, 120 s for the single-LLM-call handlers, `shell` deliberately absent (fast dead-worker reclaim; verify-before-evict protects it anyway). `defaultTimeoutMsFor` / `defaultLockDurationMsFor` return the mapped default or `null` (short handlers keep the tight null-default wall-clock / the 30 s worker lease). `clampLockDurationMs` + `LOCK_DURATION_MS_MIN/MAX` ([5s, 1h]) is the ONE clamp shared by `queue.add`, the CLI `--lock-duration-ms` flag (`--dry-run` echoes the clamped value), and the MCP `submit_job` param; the same bound is mirrored in SQL at claim time and by the `minion_jobs.lock_duration_ms` range CHECK, so every layer agrees. Layers (explicit value always wins): `MinionQueue.add()` stamps at submit; `MinionQueue.claim()` COALESCEs NULL columns from the maps (durable invariant); migration v128 one-shot backfilled `timeout_ms` with authoring-time snapshot values — do NOT sync v128 when editing the maps (`lock_duration_ms` has no backfill: NULL = worker default). `DEFAULT_CHAT_PER_TURN_TIMEOUT_MS` (30 min) and `resolveChatPerTurnTimeoutMs` resolve `ai.chat.per_turn_timeout_ms`, the per-turn chat timeout the subagent handler hands every gateway-loop turn (`ToolLoopOpts.turnTimeoutMs` → `ChatOpts.timeoutMs`, replacing the 300 s gateway backstop) and the oneshot sub-budget ceiling; the job's own signal still ends a turn at the job deadline (#4921). Pinned by `test/minions.test.ts` + `test/migrations-v128.test.ts` + `test/migrations-v130.test.ts` + `test/minions/subagent-turn-timeout.test.ts`.- `src/core/minions/handlers/contextual-reindex-per-chunk.ts` — per-page contextual re-embed handler. Resolves `models.contextual_synopsis` once and isolates cross-worker leases by the full resolved model id. `GBRAIN_CONTEXTUAL_SYNOPSIS_RPM` controls the cap; `GBRAIN_CONTEXTUAL_HAIKU_RPM` is the compatibility alias.@@ -52,7 +52,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/handlers/subagent-audit.ts` — JSONL audit + heartbeat writer at `~/.gbrain/audit/subagent-jobs-YYYY-Www.jsonl`. Events: `submission` (one per submit) + `heartbeat` (per turn boundary: `llm_call_started | llm_call_completed | tool_called | tool_result | tool_failed`, plus the oneshot markers `oneshot_fallback | oneshot_timeout`; oneshot-path events carry `mode: 'oneshot'` and fallback events a `reason` — both rendered by `gbrain agent logs`). Never logs prompts or tool inputs. `readSubagentAuditForJob(jobId, {sinceIso})` is the readback for `gbrain agent logs`.-- `src/core/minions/handlers/subagent-oneshot.ts` — oneshot synthesis runner. ONE rate-leased tool-less `gateway.chat` call (static `ONESHOT_SYSTEM` JSON contract rides the prompt-cache prefix; sub-budget min(5 min, timeout/4) → `fallback_reason: 'oneshot_timeout'`), then all-or-nothing validation BEFORE any write: JSON contract (`parseOneshotResponse`, ≤12 pages), slug grammar + `allowed_slug_prefixes` + reflections/originals task shape + the exact `oneshot_slug_suffix` (the idempotency boundary, enforced structurally), exact-match wikilink rule against existing ∪ in-batch slugs (`extractWikilinkTargets`; cold-brain relaxation: <5 pages AND no manifest accepts syntactic presence). Writes go through the SAME `brain_put_page` ToolDef the loop uses (fences/side-effects/provenance identical) with `deferEmbeds`, bracketed by standard ledger rows under invocation-scoped ids `oneshot-<inv8>-p<i>`; a post-batch `autoLinkWrittenPage` pass materializes in-batch forward wikilink edges. Ledger-first crash recovery: any prior oneshot rows → finalize from the ledger, never re-call the nondeterministic model. Transcript rows persist ONLY after success (a failed attempt is never replayable as a completed result). Every failure shape returns `{kind:'fallback', reason}` and the same job falls through to the agentic loop. Pinned by `test/minions/subagent-oneshot.test.ts` + the oneshot describes in `test/subagent-handler.test.ts` and `test/e2e/dream-synthesize-pglite.test.ts`. `ONESHOT_SYSTEM` spells out JSON string escaping (quotes, backslashes, line breaks). A parse failure whose reported output usage reaches the requested cap falls back as `length` even when the provider normalized the stop to `end`/`other`; below-cap malformed output stays `unparseable`, and valid JSON at the cap proceeds normally.+- `src/core/minions/handlers/subagent-oneshot.ts` — oneshot synthesis runner. ONE rate-leased tool-less `gateway.chat` call (static `ONESHOT_SYSTEM` JSON contract rides the prompt-cache prefix; sub-budget min(`ai.chat.per_turn_timeout_ms`, time left/4) with a job deadline, else 5 min, passed as the call's `timeoutMs` so the gateway's 300 s default backstop cannot cut it short → `fallback_reason: 'oneshot_timeout'`), then all-or-nothing validation BEFORE any write: JSON contract (`parseOneshotResponse`, ≤12 pages), slug grammar + `allowed_slug_prefixes` + reflections/originals task shape + the exact `oneshot_slug_suffix` (the idempotency boundary, enforced structurally), exact-match wikilink rule against existing ∪ in-batch slugs (`extractWikilinkTargets`; cold-brain relaxation: <5 pages AND no manifest accepts syntactic presence). Writes go through the SAME `brain_put_page` ToolDef the loop uses (fences/side-effects/provenance identical) with `deferEmbeds`, bracketed by standard ledger rows under invocation-scoped ids `oneshot-<inv8>-p<i>`; a post-batch `autoLinkWrittenPage` pass materializes in-batch forward wikilink edges. Ledger-first crash recovery: any prior oneshot rows → finalize from the ledger, never re-call the nondeterministic model. Transcript rows persist ONLY after success (a failed attempt is never replayable as a completed result). Every failure shape returns `{kind:'fallback', reason}` and the same job falls through to the agentic loop. Pinned by `test/minions/subagent-oneshot.test.ts` + the oneshot describes in `test/subagent-handler.test.ts` and `test/e2e/dream-synthesize-pglite.test.ts`. `ONESHOT_SYSTEM` spells out JSON string escaping (quotes, backslashes, line breaks). A parse failure whose reported output usage reaches the requested cap falls back as `length` even when the provider normalized the stop to `end`/`other`; below-cap malformed output stays `unparseable`, and valid JSON at the cap proceeds normally.- `src/core/minions/handlers/subagent-persistence.ts` — subagent transcript + tool-execution persistence (pure peel from subagent.ts): loadPriorMessages/Tools/ToolsV2, persistMessage, persistToolExecPending/Complete/Failed (all `$N::text::jsonb` discipline), plus `finalizeWriteAccounting`: derives pages_attempted/written/failed from the job's put_page ledger rows (settled only — pending counts toward neither), merges them into every SubagentResult, and throws UnrecoverableError on require_writes jobs with no settled successful write, including zero-attempt clean finishes, unless `isLegitimateZeroWrite` accepts the zero-attempt `end_turn` finish: the oneshot explicit skip (`oneshot_skipped: true` on a `synth_mode_used: 'oneshot'` result) or, when the submitter set `allow_clean_zero_writes` (the patterns phase), a run with at least one completed tool execution in its ledger — all-attempted-failed, dirty stops, prose-only finishes and runs whose only tools failed still dead-letter (the oneshot runner banks each skip as a `oneshot-<inv8>-skip` ledger row before its transcript, so a retried job's ledger-first recovery completes as the same skip without a model call); `scopeToolUseIdPrefix` narrows the scan to the oneshot invocation family. Fresh `brain_put_page` rejects are normalized by `src/core/minions/tools/put-page-result.ts` before ledger settlement; accounting reclassifies rejected historical completed envelopes (including JSON strings) without changing the stored rows. Unchanged-page saves and persisted pages whose embedding failed still count as writes.diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex f6b81ac727..62ee0a9cf4 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -3030,6 +3030,12 @@ export interface ChatOpts {*/temperature?: number;abortSignal?: AbortSignal;+ /**+ * Replaces the default chat backstop (`GBRAIN_AI_CHAT_TIMEOUT_MS`, 300 s)+ * for this call; `abortSignal` still composes (shorter wins). Set by+ * callers that own a longer budget, such as a subagent turn (#4921).+ */+ timeoutMs?: number;/*** Per-call provider options keyed by recipe id, deep-merged LAST — after* the derived cache markers and configured `provider_chat_options` — so a@@ -3649,7 +3655,7 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {// v0.42.20.0 — default a chat timeout (composes with the caller's signal,// shorter wins). Covers native-anthropic (the default provider + facts Haiku).// Fresh signal per attempt so the schemaless retry gets its own timeout.- abortSignal: withDefaultTimeout(opts.abortSignal, AI_CHAT_TIMEOUT_MS),+ abortSignal: withDefaultTimeout(opts.abortSignal, opts.timeoutMs ?? AI_CHAT_TIMEOUT_MS),providerOptions: Object.keys(providerOptions).length > 0 ? providerOptions : undefined,...(requestHeaders ? { headers: requestHeaders } : {}),});@@ -3810,6 +3816,8 @@ export interface ToolLoopOpts {purpose?: string;/** Forwarded to every `chat()` turn; see `ChatOpts.allowFallback`. */allowFallback?: boolean;+ /** Forwarded to every `chat()` turn as `ChatOpts.timeoutMs`. */+ turnTimeoutMs?: number;/** Crash-replay state. When set, the loop resumes from the recorded position. */replayState?: ToolLoopReplayState;@@ -3960,6 +3968,7 @@ export async function toolLoop(opts: ToolLoopOpts): Promise<ToolLoopResult> {cacheSystem: opts.cacheSystem,purpose: opts.purpose,allowFallback: opts.allowFallback,+ timeoutMs: opts.turnTimeoutMs,});} catch (err) {if (isAIInvocationPolicyError(err)) throw err;diff --git a/src/core/config.ts b/src/core/config.tsindex 098aff1f81..c5540e284f 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1271,6 +1271,10 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['agent.use_gateway_loop',// #2778: per-turn output-token cap for the subagent loop (default 8192).'agent.max_output_tokens',+ // #4921: per-turn chat timeout for subagent jobs (default 1800000, the+ // 30-min subagent budget; minions/handler-timeouts.ts). Replaces the 300 s+ // gateway backstop for those turns only.+ 'ai.chat.per_turn_timeout_ms',// File-plane bootstrap hook-lane keys (routed to ~/.gbrain/config.json by// `config set` — engine-free hook/push children read loadConfigFileOnly).'push.allow_unverified_remote',diff --git a/src/core/minions/handler-timeouts.ts b/src/core/minions/handler-timeouts.tsindex eed88ca169..a5f2714005 100644--- a/src/core/minions/handler-timeouts.ts+++ b/src/core/minions/handler-timeouts.ts@@ -127,3 +127,19 @@ export const LOCK_DURATION_MS_MAX = 3_600_000;export function clampLockDurationMs(raw: number): number {return Math.max(LOCK_DURATION_MS_MIN, Math.min(LOCK_DURATION_MS_MAX, Math.floor(raw)));}++/**+ * Per-turn chat timeout for subagent jobs (#4921), `ai.chat.per_turn_timeout_ms`.+ * The gateway's default chat backstop (300 s) killed long thinking-model+ * turns inside a 30-min job, and the replay retried into the same wall.+ * A subagent turn instead gets this cap (default: the 30-min subagent+ * budget); the job's own signal still aborts at its deadline, so a turn ends+ * at whichever comes first. Calls outside a job keep the 300 s backstop.+ */+export const DEFAULT_CHAT_PER_TURN_TIMEOUT_MS = THIRTY_MIN_MS;++/** The configured per-turn cap, or the default when unset or not a positive integer. */+export function resolveChatPerTurnTimeoutMs(raw: string | null | undefined): number {+ const n = raw == null || raw.trim() === '' ? NaN : Number(raw);+ return Number.isSafeInteger(n) && n > 0 ? n : DEFAULT_CHAT_PER_TURN_TIMEOUT_MS;+}diff --git a/src/core/minions/handlers/subagent-oneshot.ts b/src/core/minions/handlers/subagent-oneshot.tsindex 645a759845..6bf1018f98 100644--- a/src/core/minions/handlers/subagent-oneshot.ts+++ b/src/core/minions/handlers/subagent-oneshot.ts@@ -205,6 +205,12 @@ export interface OneshotArgs {data: SubagentHandlerData;model: string;maxOutputTokens: number;+ /**+ * `ai.chat.per_turn_timeout_ms` (#4921): with a job deadline the call's+ * sub-budget is min(this, a quarter of the time left); without one it+ * stays 5 min. Unset keeps the 5-min ceiling.+ */+ turnTimeoutMs?: number;/** The deferEmbeds-enabled brain_put_page ToolDef (same executor as the loop). */putPageTool: ToolDef | undefined;leaseKey: string;@@ -212,7 +218,7 @@ export interface OneshotArgs {leaseTtlMs: number;/** Test seam (extract-atoms pattern). */_chat?: typeof gatewayChat;- /** Test seam: override the OV-9 sub-budget (default min(5min, deadline/4)). */+ /** Test seam: override the OV-9 sub-budget (default min(turnTimeoutMs, deadline/4)). */_budgetMs?: number;}@@ -345,7 +351,7 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutc// ── Single provider call under a rate lease + sub-budget (OV-9) ─────────const budgetMs = args._budgetMs ?? (ctx.deadlineAtMs- ? Math.min(ONESHOT_CALL_BUDGET_MS, Math.max(30_000, Math.floor((ctx.deadlineAtMs - Date.now()) / 4)))+ ? Math.min(args.turnTimeoutMs ?? ONESHOT_CALL_BUDGET_MS, Math.max(30_000, Math.floor((ctx.deadlineAtMs - Date.now()) / 4))): ONESHOT_CALL_BUDGET_MS);// Lease TTL must OUTLIVE the call it guards: the sub-budget hard-bounds// the call (AbortSignal.timeout below), so ttl = budget + slack. With the@@ -374,6 +380,9 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutcmessages: [{ role: 'user', content: data.prompt }],maxTokens: args.maxOutputTokens,abortSignal: callSignal,+ // The sub-budget above is this call's whole bound; without it the+ // gateway's 300 s default backstop would cut a longer budget short.+ timeoutMs: budgetMs,// cacheSystem marks the system block as a cache breakpoint. Note:// ONESHOT_SYSTEM alone is under Anthropic's ~1024-token cache minimum,// so cross-job prefix hits only materialize on providers/models with adiff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.tsindex 47d528b2a1..092427f419 100644--- a/src/core/minions/handlers/subagent.ts+++ b/src/core/minions/handlers/subagent.ts@@ -76,6 +76,7 @@ import { applyDelegatedData, guardDelegatedTools } from '../delegated-tools.ts';import { withDelegatedSpend } from '../delegated-spend.ts';import { invokeAI, sdkInvocationUsage, hasAIInvocationGuard } from '../../ai/invocation-guard.ts';import { chatInvocation } from '../../ai/guarded-generation.ts';+import { resolveChatPerTurnTimeoutMs } from '../handler-timeouts.ts';// ── Defaults ────────────────────────────────────────────────@@ -432,6 +433,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {await engine.getConfig('agent.max_output_tokens').catch(() => null),model,);+ const turnTimeoutMs = resolveChatPerTurnTimeoutMs(await engine.getConfig('ai.chat.per_turn_timeout_ms').catch(() => null));// v0.41 Approach C: systemPrompt is now built AFTER toolDefs (a few// lines below) so the renderer can splice a tool-usage preamble// listing each available tool's usage_hint. The renderer is@@ -553,6 +555,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {data,model,maxOutputTokens,+ turnTimeoutMs,putPageTool: oneshotTools.find(t => t.name === 'brain_put_page'),leaseKey: gatewayLeaseKey,maxConcurrent,@@ -578,6 +581,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {toolDefs,maxTurns,maxOutputTokens,+ turnTimeoutMs,leaseKey: gatewayLeaseKey,maxConcurrent,leaseTtlMs,@@ -1148,6 +1152,8 @@ interface GatewayRunArgs {maxTurns: number;/** #2778: per-turn output-token cap (resolved by resolveMaxOutputTokens). */maxOutputTokens: number;+ /** `ai.chat.per_turn_timeout_ms`: each turn's chat backstop (#4921). */+ turnTimeoutMs: number;/*** #4194/CDX-7 — per-turn rate-lease parameters. Pre-fix the gateway path* made provider calls with no lease at all (the legacy loop's acquisition@@ -1176,7 +1182,7 @@ interface GatewayRunArgs {* reconciler sees both shapes uniformly.*/async function runSubagentViaGateway(args: GatewayRunArgs): Promise<SubagentResult> {- const { engine, ctx, data, model, systemPrompt, toolDefs, maxTurns, maxOutputTokens, leaseKey, maxConcurrent, leaseTtlMs } = args;+ const { engine, ctx, data, model, systemPrompt, toolDefs, maxTurns, maxOutputTokens, turnTimeoutMs, leaseKey, maxConcurrent, leaseTtlMs } = args;// Map ToolDef → ChatToolDef (gateway shape). The gateway's chat() bridges// this to provider-specific tool definitions via the Vercel AI SDK.@@ -1316,6 +1322,7 @@ async function runSubagentViaGateway(args: GatewayRunArgs): Promise<SubagentResumaxTurns,maxTokens: maxOutputTokens,abortSignal: ctx.signal,+ turnTimeoutMs,cacheSystem,// #4194/CDX-7: every provider round-trip holds a rate-lease slot (worker// parity with the legacy loop's per-turn acquisition). Lease-full throwsdiff --git a/test/minions/subagent-turn-timeout.test.ts b/test/minions/subagent-turn-timeout.test.tsnew file mode 100644index 0000000000..ef57295a10--- /dev/null+++ b/test/minions/subagent-turn-timeout.test.ts@@ -0,0 +1,203 @@+/**+ * #4921: a subagent turn is bounded by the per-turn cap+ * (`ai.chat.per_turn_timeout_ms`, default 30 min) and the job's own deadline,+ * not by the gateway's 300 s default chat backstop, which killed long+ * thinking-model turns inside a 30-min job. Calls outside a job keep 300 s.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { makeSubagentHandler } from '../../src/core/minions/handlers/subagent.ts';+import { runSubagentOneshot, type OneshotArgs } from '../../src/core/minions/handlers/subagent-oneshot.ts';+import {+ DEFAULT_CHAT_PER_TURN_TIMEOUT_MS,+ resolveChatPerTurnTimeoutMs,+} from '../../src/core/minions/handler-timeouts.ts';+import { KNOWN_CONFIG_KEYS } from '../../src/core/config.ts';+import type { MinionJobContext, SubagentHandlerData } from '../../src/core/minions/types.ts';+import {+ __setChatTransportForTests,+ __setGenerateTextTransportForTests,+ chat,+ configureGateway,+ resetGateway,+ toolLoop,+ type ChatOpts,+ type ChatResult,+} from '../../src/core/ai/gateway.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', '85');+ await engine.setConfig('agent.use_gateway_loop', 'true');+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'stub' } });+});++afterEach(() => {+ __setChatTransportForTests(null);+ __setGenerateTextTransportForTests(null);+ resetGateway();+});++const DONE: ChatResult = {+ text: 'done',+ blocks: [{ type: 'text', text: 'done' }],+ stopReason: 'end',+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-sonnet-4-6',+ providerId: 'anthropic',+};++function captureChatOpts(): ChatOpts[] {+ const seen: ChatOpts[] = [];+ __setChatTransportForTests(async (opts) => {+ seen.push(opts);+ return DONE;+ });+ return seen;+}++async function makeCtx(data: SubagentHandlerData, deadlineAtMs: number | null): Promise<MinionJobContext> {+ const rows = await engine.executeRaw<{ id: number }>(+ `INSERT INTO minion_jobs (submission_authority, name, status, data, queue, priority, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'active', $1::jsonb, 'default', 0, now())+ RETURNING id`,+ [JSON.stringify(data)],+ );+ return {+ id: rows[0].id,+ name: 'subagent',+ data: data as unknown as Record<string, unknown>,+ attempts_made: 0,+ signal: new AbortController().signal,+ deadlineAtMs,+ shutdownSignal: new AbortController().signal,+ updateProgress: async () => {},+ updateTokens: async () => {},+ log: async () => {},+ isActive: async () => true,+ readInbox: async () => [],+ };+}++function buildHandler() {+ return makeSubagentHandler({+ engine,+ config: {} as any,+ toolRegistry: [],+ makeAnthropic: () => ({ messages: { create: async () => { throw new Error('legacy path should not be invoked'); } } }) as any,+ });+}++describe('subagent gateway loop turn timeout (#4921)', () => {+ test('every turn gets the 30-min per-turn cap instead of the 300 s backstop by default', async () => {+ const seen = captureChatOpts();+ const ctx = await makeCtx({ prompt: 'hello', model: 'anthropic:claude-sonnet-4-6' }, Date.now() + 30 * 60_000);++ await buildHandler()(ctx);++ expect(seen).toHaveLength(1);+ expect(seen[0]!.timeoutMs).toBe(DEFAULT_CHAT_PER_TURN_TIMEOUT_MS);+ expect(seen[0]!.timeoutMs).toBeGreaterThan(300_000);+ });++ test('ai.chat.per_turn_timeout_ms sets the cap', async () => {+ await engine.setConfig('ai.chat.per_turn_timeout_ms', '3600000');+ const seen = captureChatOpts();+ const ctx = await makeCtx({ prompt: 'hello', model: 'anthropic:claude-sonnet-4-6' }, null);++ await buildHandler()(ctx);++ expect(seen[0]!.timeoutMs).toBe(3_600_000);+ });+});++describe('oneshot sub-budget (#4921)', () => {+ async function oneshotTimeoutMs(deadlineAtMs: number | null, turnTimeoutMs?: number): Promise<number | undefined> {+ const data: SubagentHandlerData = { prompt: 'p', mode: 'oneshot', allowed_slug_prefixes: ['wiki/*'], oneshot_slug_suffix: 'abc123' };+ const ctx = await makeCtx(data, deadlineAtMs);+ let seen: number | undefined;+ const args: OneshotArgs = {+ engine,+ ctx,+ data,+ model: 'anthropic:claude-sonnet-4-6',+ maxOutputTokens: 8192,+ ...(turnTimeoutMs !== undefined ? { turnTimeoutMs } : {}),+ putPageTool: { name: 'brain_put_page', description: 'stub', input_schema: { type: 'object' }, idempotent: false, execute: async () => ({}) },+ leaseKey: 'anthropic:messages',+ maxConcurrent: 32,+ leaseTtlMs: 120_000,+ _chat: (async (opts: ChatOpts) => { seen = opts.timeoutMs; return { ...DONE, text: 'not json' }; }) as OneshotArgs['_chat'],+ };+ await runSubagentOneshot(args);+ return seen;+ }++ test('a long job gives the single call a quarter of the time left, up to the per-turn cap, past 300 s', async () => {+ expect(await oneshotTimeoutMs(Date.now() + 3 * 60 * 60_000, DEFAULT_CHAT_PER_TURN_TIMEOUT_MS)).toBe(DEFAULT_CHAT_PER_TURN_TIMEOUT_MS);+ const quarter = await oneshotTimeoutMs(Date.now() + 40 * 60_000, DEFAULT_CHAT_PER_TURN_TIMEOUT_MS);+ expect(quarter).toBeGreaterThan(300_000);+ expect(quarter).toBeLessThanOrEqual(10 * 60_000);+ });++ test('a job without a deadline keeps the 300 s oneshot budget', async () => {+ expect(await oneshotTimeoutMs(null, DEFAULT_CHAT_PER_TURN_TIMEOUT_MS)).toBe(300_000);+ });+});++describe('chat() timeoutMs (#4921)', () => {+ test('timeoutMs bounds a hung provider call', async () => {+ __setGenerateTextTransportForTests((async (args: any) => {+ await new Promise((resolve, reject) => {+ const timer = setTimeout(resolve, 2_000);+ args.abortSignal.addEventListener('abort', () => { clearTimeout(timer); reject(args.abortSignal.reason); });+ });+ return { content: [{ type: 'text', text: 'late' }], finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } };+ }) as any);++ const started = Date.now();+ const err = await chat({ messages: [{ role: 'user', content: 'x' }], timeoutMs: 50 }).catch(e => e);++ expect(err).toBeInstanceOf(Error);+ expect(Date.now() - started).toBeLessThan(1_500);+ });++ test('a tool loop outside a job sends no timeoutMs, so the 300 s backstop applies', async () => {+ const seen = captureChatOpts();++ await toolLoop({ initialMessages: [{ role: 'user', content: 'x' }], tools: [], toolHandlers: new Map() });++ expect(seen[0]!.timeoutMs).toBeUndefined();+ });+});++describe('ai.chat.per_turn_timeout_ms config key (#4921)', () => {+ test('is a known key', () => {+ expect(KNOWN_CONFIG_KEYS).toContain('ai.chat.per_turn_timeout_ms');+ });++ test.each([+ [null, DEFAULT_CHAT_PER_TURN_TIMEOUT_MS],+ ['', DEFAULT_CHAT_PER_TURN_TIMEOUT_MS],+ ['abc', DEFAULT_CHAT_PER_TURN_TIMEOUT_MS],+ ['0', DEFAULT_CHAT_PER_TURN_TIMEOUT_MS],+ ['-5', DEFAULT_CHAT_PER_TURN_TIMEOUT_MS],+ ['1.5', DEFAULT_CHAT_PER_TURN_TIMEOUT_MS],+ ['600000', 600_000],+ ])('resolves %p to %p', (raw, expected) => {+ expect(resolveChatPerTurnTimeoutMs(raw)).toBe(expected);+ });+});