Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

subagent: empty or refused turns stop error/refusal, never end_turn (#6448 items 2/3)

garrytan6e04cd66d16e
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index f983dffa28..e75395f478 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. 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.
- `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.md
index 063b9e8491..af1e51d32a 100644
--- a/docs/architecture/key-files/core-minions-1.md
+++ b/docs/architecture/key-files/core-minions-1.md
@@ -56,7 +56,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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.
-- `src/core/minions/handlers/subagent.ts` — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via `resolveMaxOutputTokens` (`data.max_tokens` → `agent.max_output_tokens` config → 8192 default); a `stop_reason: 'max_tokens'` final turn surfaces as `SubagentStopReason 'max_tokens'` (not a silent `end_turn`), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full. Both loop paths (the direct Anthropic SDK turn loop and the gateway toolLoop's `acquireTurnPermit`) heartbeat the held lease at ttl/3 for the duration of each provider call — single-flight renewals so a stalled renewal never stacks behind a starved pool; a FALSE renewal means the lease row was pruned/stolen (the slot is already re-admitted), so the in-flight call aborts and converts to a lease-full requeue instead of running above `maxConcurrent`. Anthropic 400 `prompt is too long` responses (status 400 + body matches `/prompt is too long|prompt_too_long|context.*length/i`) classify as `UnrecoverableError` so the job goes straight to `dead` on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that `synthesize.ts`'s chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in `stop_reason: 'end_turn'`, the handler returns `{ ok: true }` immediately instead of issuing another `messages.create` call (re-prompting past `end_turn` would get a 400 and dead-letter an already-successful job). Pinned by `test/subagent-handler.test.ts`. Oneshot dispatch: `data.mode === 'oneshot'` on a FRESH job (zero persisted messages) routes to `runSubagentOneshot` (subagent-oneshot.ts) before either loop; a validation fallback re-enters the loops in the SAME job, stamped `synth_mode_used: 'agentic_fallback'` + `fallback_reason`. Write accounting (`finalizeWriteAccounting` in subagent-persistence.ts): every job's result carries pages_attempted/written/failed derived from the tool-execution ledger (settled rows only); `data.require_writes` jobs (dream synthesize + patterns fan-outs) require at least one settled successful page write; zero successes, including a clean prose-only finish or pending-only ledger, throw UnrecoverableError, except the deliberate zero-write completions `isLegitimateZeroWrite` accepts (an explicit oneshot skip, or an `allow_clean_zero_writes` child with a completed tool execution). Optional-write jobs can still complete without writing. `resolveMaxOutputTokens` takes the model: thinking-by-default models (Claude 5 by name or recipe-declared `thinking_by_default` such as DeepSeek v4, via the gateway's shared `isThinkingModel`) default to 32000 when neither per-job nor config caps are set. Gateway-path `onToolCallStart` has a uniq_subagent_tools_use_id backstop: a provider repeating a tool id across turns persists under a `#m<idx>o<ordinal>`-suffixed debug id (second violation reconciles to the existing row's gbrain_tool_use_id) instead of dead-lettering the job. Persistence helpers live in subagent-persistence.ts (pure peel; `__testing` unchanged). Tool-execution rows carry NO job-wide unique on the raw provider `tool_use_id` (migration v131 drops `uniq_subagent_tools_use_id`: providers like claude-cli legitimately re-mint the same short id every turn, and a collision would dead-letter the job); row identity is the stable `(job_id, message_idx, ordinal)` unique, and readers/settlement resolve an execution by `(message_idx, tool_use_id)`. Settle writes (complete/failed) target exactly ONE row — the call's own ordinal first, then a legacy ordinal=NULL row, never a row that already settled complete (a broader status disjunct could only capture a same-id sibling's row); pending inserts guard legacy NULL-ordinal rows via NOT EXISTS and use the stable-id `ON CONFLICT` as the zombie-worker backstop. Replay/reconcile resolve an execution by persisted ordinal first (validated against the raw id), then by `(message_idx, tool_use_id)` only when the id is unique within the turn, then the same-tool legacy positional fallback. Mixed-version window: a still-running pre-v131 `gbrain jobs work` daemon errors on tool persistence after the migration until it restarts (its two-phase writes targeted the dropped constraint)
+- `src/core/minions/handlers/subagent.ts` — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via `resolveMaxOutputTokens` (`data.max_tokens` → `agent.max_output_tokens` config → 8192 default); a `stop_reason: 'max_tokens'` final turn surfaces as `SubagentStopReason 'max_tokens'` (not a silent `end_turn`), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Every stop-reason mapping lives in `src/core/minions/subagent-stop-reason.ts` (#6448): `directStopReason` (Messages path: `max_tokens` → `max_tokens`, `refusal` → `refusal`, an empty or whitespace-only final text on a clean stop → `error`), `gatewayStopReason` (`toolLoop`'s `length` → `max_tokens`, `refusal`/`content_filter` → `refusal`, `empty_response`/`aborted`/`unrecoverable` → `error`) and `replayTerminalStopReason` (a persisted terminal turn: `tokens_out >= cap` → `max_tokens`, else `error` when its text is empty); on both replay paths ANY trailing assistant turn without tool calls is terminal, text or not, so a thinking-only tail is answered from the transcript instead of re-sent as an assistant prefill. Pinned by `test/subagent-stop-reason-6448.test.ts`. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full. Both loop paths (the direct Anthropic SDK turn loop and the gateway toolLoop's `acquireTurnPermit`) heartbeat the held lease at ttl/3 for the duration of each provider call — single-flight renewals so a stalled renewal never stacks behind a starved pool; a FALSE renewal means the lease row was pruned/stolen (the slot is already re-admitted), so the in-flight call aborts and converts to a lease-full requeue instead of running above `maxConcurrent`. Anthropic 400 `prompt is too long` responses (status 400 + body matches `/prompt is too long|prompt_too_long|context.*length/i`) classify as `UnrecoverableError` so the job goes straight to `dead` on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that `synthesize.ts`'s chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in `stop_reason: 'end_turn'`, the handler returns `{ ok: true }` immediately instead of issuing another `messages.create` call (re-prompting past `end_turn` would get a 400 and dead-letter an already-successful job). Pinned by `test/subagent-handler.test.ts`. Oneshot dispatch: `data.mode === 'oneshot'` on a FRESH job (zero persisted messages) routes to `runSubagentOneshot` (subagent-oneshot.ts) before either loop; a validation fallback re-enters the loops in the SAME job, stamped `synth_mode_used: 'agentic_fallback'` + `fallback_reason`. Write accounting (`finalizeWriteAccounting` in subagent-persistence.ts): every job's result carries pages_attempted/written/failed derived from the tool-execution ledger (settled rows only); `data.require_writes` jobs (dream synthesize + patterns fan-outs) require at least one settled successful page write; zero successes, including a clean prose-only finish or pending-only ledger, throw UnrecoverableError, except the deliberate zero-write completions `isLegitimateZeroWrite` accepts (an explicit oneshot skip, or an `allow_clean_zero_writes` child with a completed tool execution). Optional-write jobs can still complete without writing. `resolveMaxOutputTokens` takes the model: thinking-by-default models (Claude 5 by name or recipe-declared `thinking_by_default` such as DeepSeek v4, via the gateway's shared `isThinkingModel`) default to 32000 when neither per-job nor config caps are set. Gateway-path `onToolCallStart` has a uniq_subagent_tools_use_id backstop: a provider repeating a tool id across turns persists under a `#m<idx>o<ordinal>`-suffixed debug id (second violation reconciles to the existing row's gbrain_tool_use_id) instead of dead-lettering the job. Persistence helpers live in subagent-persistence.ts (pure peel; `__testing` unchanged). Tool-execution rows carry NO job-wide unique on the raw provider `tool_use_id` (migration v131 drops `uniq_subagent_tools_use_id`: providers like claude-cli legitimately re-mint the same short id every turn, and a collision would dead-letter the job); row identity is the stable `(job_id, message_idx, ordinal)` unique, and readers/settlement resolve an execution by `(message_idx, tool_use_id)`. Settle writes (complete/failed) target exactly ONE row — the call's own ordinal first, then a legacy ordinal=NULL row, never a row that already settled complete (a broader status disjunct could only capture a same-id sibling's row); pending inserts guard legacy NULL-ordinal rows via NOT EXISTS and use the stable-id `ON CONFLICT` as the zombie-worker backstop. Replay/reconcile resolve an execution by persisted ordinal first (validated against the raw id), then by `(message_idx, tool_use_id)` only when the id is unique within the turn, then the same-tool legacy positional fallback. Mixed-version window: a still-running pre-v131 `gbrain jobs work` daemon errors on tool persistence after the migration until it restarts (its two-phase writes targeted the dropped constraint)
- `src/core/minions/handlers/supervisor-audit.ts` — supervisor lifecycle JSONL audit at `~/.gbrain/audit/supervisor-YYYY-Www.jsonl` (ISO-week rotation; shares `computeIsoWeekName()` with `shell-audit.ts`). `writeSupervisorEvent(emission, supervisorPid)` appends one line per event (`started`, `worker_spawned`, `worker_exited`, `backoff`, `health_warn`, `health_error`, `max_crashes_exceeded`, `shutting_down`, `stopped`, `worker_spawn_failed`). `readSupervisorEvents({sinceMs})` is the readback for `gbrain doctor`. Exports `isCrashExit(event)`, `summarizeCrashes(events)`, `CrashSummary` type, and `CLEAN_EXIT_CAUSES` denylist (`'clean_exit' | 'graceful_shutdown' | 'wedge_restart' | 'configuration_blocked'`). Single shared point — both `gbrain doctor` (supervisor check) and `gbrain jobs supervisor status` import from here so the two surfaces can't drift. `isCrashExit` classifies a single `worker_exited` against the denylist: clean/graceful, deliberate wedge restarts and configuration blocks are NON-crashes; everything else (incl. any future `likely_cause` from `child-worker-supervisor.ts`) is a crash; audit lines lacking `likely_cause` fall back to `code !== 0`. `summarizeCrashes` returns `{total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits}` — the `legacy` bucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned by `test/supervisor-audit.test.ts` (14 cases) and 4 source-grep wiring assertions in `test/doctor.test.ts`.
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 96a4265e77..fbe8e98a13 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -3963,7 +3963,7 @@ export type TurnPermit =
| (() => Promise<void> | void)
| { release: () => Promise<void> | void; signal?: AbortSignal };
-export type ToolLoopStopReason = 'end' | 'length' | 'max_turns' | 'refusal' | 'content_filter' | 'aborted' | 'unrecoverable';
+export type ToolLoopStopReason = 'end' | 'length' | 'max_turns' | 'refusal' | 'content_filter' | 'aborted' | 'unrecoverable' | 'empty_response';
export interface ToolLoopResult {
finalText: string;
@@ -4097,8 +4097,9 @@ export async function toolLoop(opts: ToolLoopOpts): Promise<ToolLoopResult> {
// #4088: an output-cap hit is NOT a clean finish. Folding 'length' into
// 'end' made truncated zero-tool-call runs indistinguishable from the
// model choosing to stop — the exact honesty bug #2778 fixed on the
- // direct Anthropic path.
- stopReason = chatResult.stopReason === 'length' ? 'length' : 'end';
+ // direct Anthropic path. #6448: a clean stop with no text (refusal
+ // body, thinking-only turn) is 'empty_response', not 'end'.
+ stopReason = chatResult.stopReason === 'length' ? 'length' : chatResult.text.trim() === '' ? 'empty_response' : 'end';
finalText = chatResult.text;
break;
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 04f73052dd..38eb70527b 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -437,6 +437,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.165.0', text: '`gbrain extract --stale` and `extract links|all --source db` skip and count a page another writer changed mid-run (`skipped_concurrent_write`) instead of aborting the run; the page stays stale for the next run. `extract all --source db` marks a page extracted only when both its links and its timeline finished at the same revision. On a managed brain, `extract timeline --from-meetings` (and its job) now writes through the coordinator as one `managed_maintenance_meeting_timeline` request per entity page, gated at the meeting\'s trust tier; a refused or pending write fails the job and the command exits 1. An owner on an older build refuses that request kind until it upgrades. On a managed brain, `extract_entities` now writes stubs, timeline rows and backlinks through the coordinator (creating a stub needs permission to write pages); a refusal or pending write returns its error envelope and names the entities already written, instead of a raw `writer_coordinator_required` error or a silently missing timeline row.' },
// Memory proof wave 2 W1 (question-ranked recall).
{ since: '0.60.169.0', text: '`recall` takes an optional `question` and returns saved facts ranked by relevance to it (facts below the match threshold are left out); calls without it still return the newest facts, every response now says `facts_order`, and a call that passes only `query` carries a `recall_hint` notice. `gbrain recall --question` passes the question instead of reading its value as an entity name. In `query`, the facts of an entity the question names come only from that entity page\'s own source, and the temporal fact reserve (`search.temporal_fact_reserve`, off by default) scores with the same question scorer: whole-word matches, and a long fact\'s word matches count for less.' },
+ // Fix wave 15 G6 (GBRA-79).
+ { since: '0.60.176.0', text: 'A subagent job whose final model turn produced no answer (an empty or whitespace-only body, a thinking-only turn) now ends with `stop_reason: error`, and a turn the provider stopped with `refusal` ends `refusal`; both used to be reported as a clean `end_turn`. A resumed job whose stored transcript already ends on such a turn is answered from the transcript with that stop reason instead of sending the turn back to the provider as an assistant prefill (which Haiku 5.5 and Sonnet 4.6+ reject with HTTP 400). The queue\'s terminal-state policy is unchanged; `require_writes` jobs that produced nothing already failed.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.ts
index de274b1cf7..e0fdfcd75d 100644
--- a/src/core/minions/handlers/subagent.ts
+++ b/src/core/minions/handlers/subagent.ts
@@ -57,6 +57,7 @@ import { toolLoop as gatewayToolLoop, isThinkingModel, THINKING_MODEL_MAX_OUTPUT
import type { ChatToolDef, ChatMessage, ChatBlock, ChatResult, ToolHandler } from '../../ai/gateway.ts';
import { classifyCapabilities } from '../../ai/capabilities.ts';
import { runSubagentOneshot, ONESHOT_TOOL_USE_ID_PREFIX } from './subagent-oneshot.ts';
+import { directStopReason, gatewayStopReason, replayTerminalStopReason } from '../subagent-stop-reason.ts';
import type { OneshotFallbackReason } from '../types.ts';
import {
loadPriorMessages,
@@ -192,14 +193,16 @@ export interface SubagentDeps {
/**
* F1 (adversarial review): a replayed terminal assistant turn that hit the
- * output cap must NOT launder into 'end_turn'. The zero-attempt honesty gate
- * (finalizeWriteAccounting) keys on stop_reason, and a truncated zero-write
- * run replaying as a clean finish would consume the transcript's idempotency
- * key with zero pages written — the exact silent-loss class #4217 kills. The
- * live stop reason is not persisted; `tokens_out >= cap` recovers it (a
- * length stop reports the capped count). A clean turn producing EXACTLY cap
- * tokens is a theoretical false positive; its consequence is dead-letter +
- * key release + nightly retry — self-healing, never silent loss.
+ * output cap must NOT launder into 'end_turn' (replayTerminalStopReason in
+ * ../subagent-stop-reason.ts, which also maps an empty persisted turn to
+ * 'error', #6448). The zero-attempt honesty gate (finalizeWriteAccounting)
+ * keys on stop_reason, and a truncated zero-write run replaying as a clean
+ * finish would consume the transcript's idempotency key with zero pages
+ * written — the exact silent-loss class #4217 kills. The live stop reason is
+ * not persisted; `tokens_out >= cap` recovers it (a length stop reports the
+ * capped count). A clean turn producing EXACTLY cap tokens is a theoretical
+ * false positive; its consequence is dead-letter + key release + nightly
+ * retry — self-healing, never silent loss.
*/
/**
* Convert a lease-lost abort into the lease-full requeue vocabulary. When
@@ -245,13 +248,6 @@ async function runLoopConvertingLeaseLoss<T>(
}
}
-function replayTerminalStopReason(
- tokensOut: number | null | undefined,
- maxOutputTokens: number,
-): SubagentStopReason {
- return tokensOut != null && tokensOut >= maxOutputTokens ? 'max_tokens' : 'end_turn';
-}
-
export function makeSubagentHandler(deps: SubagentDeps) {
const engine = deps.engine;
// sdk.messages IS the MessagesClient-shaped object. The v0.16.0 bug was
@@ -381,8 +377,9 @@ export function makeSubagentHandler(deps: SubagentDeps) {
: null;
// Terminal = assistant turn with NO pending tool dispatch in EITHER
// block vocabulary (legacy Anthropic `tool_use`, gateway `tool-call`)
- // AND actual text (the gateway terminal rule) — a pending-tool replay
- // must still pass the gate before the loop resumes on the provider.
+ // AND actual text — stricter than the replay rule (#6448: an empty
+ // tail replays as 'error' with no provider call), because an empty
+ // tail holds no completed work for this exception to protect.
const alreadyTerminal = lastRow?.role === 'assistant'
&& Array.isArray(lastBlocks)
&& !lastBlocks.some(b => b?.type === 'tool_use' || b?.type === 'tool-call')
@@ -662,7 +659,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {
return {
result: finalText,
turns_count: assistantTurns,
- stop_reason: replayTerminalStopReason(last.tokens_out, maxOutputTokens),
+ stop_reason: replayTerminalStopReason(last.tokens_out, maxOutputTokens, finalText),
tokens: tokenTotals,
};
}
@@ -976,15 +973,16 @@ export function makeSubagentHandler(deps: SubagentDeps) {
b.type === 'tool_use',
);
if (toolUses.length === 0) {
- // #2778: an output-cap hit is NOT end_turn — the text (and possibly a
- // dropped trailing tool_use block) is truncated. Surface it as its own
- // stop_reason instead of silently reporting a clean end_turn.
- stopReason = assistantMsg.stop_reason === 'max_tokens' ? 'max_tokens' : 'end_turn';
// Concatenate text blocks as the final answer.
finalText = blocks
.filter(b => b.type === 'text' && typeof b.text === 'string')
.map(b => b.text as string)
.join('\n');
+ // #2778: an output-cap hit is NOT end_turn — the text (and possibly a
+ // dropped trailing tool_use block) is truncated. #6448: a refusal is
+ // 'refusal' and an empty body on a clean stop is 'error', never a
+ // silently reported clean end_turn.
+ stopReason = directStopReason(assistantMsg.stop_reason, finalText);
break;
}
@@ -1261,7 +1259,7 @@ async function runSubagentViaGateway(args: GatewayRunArgs): Promise<SubagentResu
return {
result: terminalText,
turns_count: priorChatMessages.filter(m => m.role === 'assistant').length,
- stop_reason: replayTerminalStopReason(lastAssistant?.tokens_out, maxOutputTokens),
+ stop_reason: replayTerminalStopReason(lastAssistant?.tokens_out, maxOutputTokens, terminalText),
tokens: priorTokens,
};
}
@@ -1478,23 +1476,10 @@ async function runSubagentViaGateway(args: GatewayRunArgs): Promise<SubagentResu
maxConcurrent,
);
- // Map gateway stop reason to SubagentStopReason. 'length' (output-cap hit)
- // maps to 'max_tokens' — the #2778 honesty vocabulary the direct Anthropic
- // path already uses — NOT 'end_turn' (#4088: truncation is not a clean
- // finish). aborted maps to error.
- const stopReason: SubagentStopReason = result.stopReason === 'end'
- ? 'end_turn'
- : result.stopReason === 'length'
- ? 'max_tokens'
- : result.stopReason === 'max_turns'
- ? 'max_turns'
- : result.stopReason === 'refusal'
- ? 'refusal'
- : result.stopReason === 'content_filter'
- ? 'refusal'
- : result.stopReason === 'aborted'
- ? 'error'
- : 'end_turn';
+ // Map gateway stop reason to SubagentStopReason (../subagent-stop-reason.ts):
+ // 'length' is 'max_tokens' (#2778/#4088: truncation is not a clean finish);
+ // empty_response, aborted and unrecoverable are 'error' (#6448).
+ const stopReason: SubagentStopReason = gatewayStopReason(result.stopReason);
return {
result: result.finalText,
@@ -1680,20 +1665,19 @@ async function reconcileGatewayReplay(args: ReconcileArgs): Promise<ReconcileRes
const chatMessages: ChatMessage[] = work.map(w => ({ role: w.role, content: w.blocks }));
- // Terminal case: the transcript already ends on an assistant turn that
- // carried real text and made no tool calls (prior run reached end_turn).
- // Surface its text; skip the loop. An assistant turn whose blocks are all
- // empty (e.g. a reasoning-only/null-text turn that adaptation dropped) is NOT
- // terminal — falling through lets the loop re-issue the call rather than
- // returning an empty result.
+ // Terminal case: the transcript already ends on an assistant turn that made
+ // no tool calls (the prior run reached its last turn). Surface its text and
+ // skip the loop. #6448: ANY such tail is terminal, text or not — a
+ // reasoning-only / blank turn re-issued to the provider would end the
+ // request on an assistant message (a prefill Haiku 5.5 rejects with HTTP
+ // 400); the caller maps the empty text to stop_reason 'error' instead.
const lastMsg = work[work.length - 1];
let terminalText: string | null = null;
if (lastMsg && lastMsg.role === 'assistant' && !lastMsg.blocks.some(b => b.type === 'tool-call')) {
- const text = lastMsg.blocks
+ terminalText = lastMsg.blocks
.filter((b): b is Extract<ChatBlock, { type: 'text' }> => b.type === 'text')
.map(b => b.text)
.join('\n');
- if (text.trim() !== '') terminalText = text;
}
return { chatMessages, nextMessageIdx: maxIdx + 1, terminalText };
diff --git a/src/core/minions/subagent-stop-reason.ts b/src/core/minions/subagent-stop-reason.ts
new file mode 100644
index 0000000000..1766cf08f2
--- /dev/null
+++ b/src/core/minions/subagent-stop-reason.ts
@@ -0,0 +1,74 @@
+/**
+ * subagent-stop-reason — the one mapping from what a provider turn produced
+ * to the `SubagentStopReason` the subagent handler reports (#6448).
+ *
+ * The handler used to classify a turn by its `stop_reason` and whether it
+ * carried tool calls, never by whether it produced an answer: a turn with no
+ * text (a refusal with an empty body, a thinking-only turn, a blank string)
+ * reported `end_turn`, and `finalizeWriteAccounting` then treated the empty
+ * result as a clean finish. These helpers make "finished with nothing" its
+ * own answer (`error`, which `SubagentStopReason` already defines as "empty
+ * response") on the direct Messages path, the gateway path and both replay
+ * paths, and keep the output-cap (`max_tokens`) and `refusal` words.
+ */
+import type { SubagentStopReason } from './types.ts';
+import type { ToolLoopStopReason } from '../ai/gateway.ts';
+
+/** True when the final text carries no answer (empty, or whitespace only). */
+export function isEmptyFinalText(text: string | null | undefined): boolean {
+ return text == null || text.trim() === '';
+}
+
+/**
+ * Direct Messages path: the terminal turn's provider `stop_reason` plus the
+ * text it produced. `max_tokens` wins over empty (a truncated reply may have
+ * lost its text); `refusal` is reported as such (Claude 5 / Haiku 5.5 stop
+ * with `stop_reason: "refusal"`); an empty body on a clean stop is `error`.
+ */
+export function directStopReason(
+ providerStopReason: string | null | undefined,
+ finalText: string,
+): SubagentStopReason {
+ if (providerStopReason === 'max_tokens') return 'max_tokens';
+ if (providerStopReason === 'refusal') return 'refusal';
+ if (isEmptyFinalText(finalText)) return 'error';
+ return 'end_turn';
+}
+
+/**
+ * Gateway path: `toolLoop`'s stop reason. `length` is the output cap
+ * (#2778 / #4088 honesty vocabulary); `empty_response`, `aborted` and
+ * `unrecoverable` are all `error` (the loop produced no answer); `refusal`
+ * and `content_filter` are `refusal`.
+ */
+export function gatewayStopReason(stop: ToolLoopStopReason): SubagentStopReason {
+ switch (stop) {
+ case 'end': return 'end_turn';
+ case 'length': return 'max_tokens';
+ case 'max_turns': return 'max_turns';
+ case 'refusal':
+ case 'content_filter':
+ return 'refusal';
+ case 'empty_response':
+ case 'aborted':
+ case 'unrecoverable':
+ return 'error';
+ }
+}
+
+/**
+ * Replay of a persisted terminal assistant turn (both paths). The live stop
+ * reason is not persisted; `tokens_out >= cap` recovers an output-cap stop
+ * (F1: a truncated zero-write run must not launder into `end_turn`, #4217),
+ * and a persisted turn whose text is empty replays as `error` without a new
+ * provider request (re-sending it would be an assistant prefill, which
+ * Sonnet 4.6+ and Haiku 5.5 reject with HTTP 400).
+ */
+export function replayTerminalStopReason(
+ tokensOut: number | null | undefined,
+ maxOutputTokens: number,
+ finalText: string,
+): SubagentStopReason {
+ if (tokensOut != null && tokensOut >= maxOutputTokens) return 'max_tokens';
+ return isEmptyFinalText(finalText) ? 'error' : 'end_turn';
+}
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index dc4ca93222..2691c0f4fc 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -1898,7 +1898,7 @@
"kind": "type",
"name": "ToolLoopStopReason",
"signature": [
- "\"length\" | \"unrecoverable\" | \"end\" | \"refusal\" | \"content_filter\" | \"max_turns\" | \"aborted\""
+ "\"length\" | \"unrecoverable\" | \"end\" | \"refusal\" | \"content_filter\" | \"max_turns\" | \"aborted\" | \"empty_response\""
]
},
{
diff --git a/test/subagent-stop-reason-6448.test.ts b/test/subagent-stop-reason-6448.test.ts
new file mode 100644
index 0000000000..dae0723e25
--- /dev/null
+++ b/test/subagent-stop-reason-6448.test.ts
@@ -0,0 +1,272 @@
+/**
+ * #6448 items 2/3 — a subagent turn that produced no answer is reported as
+ * `error` (or `refusal`), never as a clean `end_turn`, on the direct Messages
+ * path, the gateway path and both replay paths; a thinking-only or blank
+ * terminal tail is read from the stored transcript instead of being sent
+ * back to the provider as an assistant prefill.
+ *
+ * Hermetic: PGLite in-memory, FakeMessagesClient for the direct path, the
+ * gateway test transport for the gateway path. No provider call.
+ *
+ * Contributed by @javieraldape (#6478: diagnosis + the five fail-first
+ * shapes); the direct-path refusal arm is this wave's.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import type Anthropic from '@anthropic-ai/sdk';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { makeSubagentHandler, type MessagesClient } from '../src/core/minions/handlers/subagent.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import {
+ __setChatTransportForTests,
+ configureGateway,
+ resetGateway,
+ toolLoop,
+ type ChatBlock,
+ type ChatResult,
+} from '../src/core/ai/gateway.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+}, 60_000);
+
+afterAll(async () => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM subagent_tool_executions');
+ await engine.executeRaw('DELETE FROM subagent_messages');
+ await engine.executeRaw('DELETE FROM subagent_rate_leases');
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'agent.use_gateway_loop'`);
+ configureGateway({
+ chat_model: 'anthropic:claude-sonnet-4-6',
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ expansion_model: 'anthropic:claude-haiku-4-5',
+ env: { ANTHROPIC_API_KEY: 'stub', OPENAI_API_KEY: 'stub' },
+ });
+});
+
+type FakeResponse = Partial<Anthropic.Message> & { content: Anthropic.Message['content'] };
+
+class FakeMessagesClient implements MessagesClient {
+ public calls: Anthropic.MessageCreateParamsNonStreaming[] = [];
+ constructor(private responses: FakeResponse[]) {}
+ async create(params: Anthropic.MessageCreateParamsNonStreaming): Promise<Anthropic.Message> {
+ this.calls.push(params);
+ if (this.responses.length === 0) throw new Error('FakeMessagesClient: out of scripted responses');
+ const r = this.responses.shift()!;
+ return {
+ id: `msg_${this.calls.length}`,
+ type: 'message',
+ role: 'assistant',
+ model: params.model,
+ stop_reason: 'end_turn',
+ stop_sequence: null,
+ usage: { input_tokens: 10, output_tokens: 5, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } as any,
+ ...r,
+ } as Anthropic.Message;
+ }
+}
+
+async function makeCtx(input: Record<string, unknown>): Promise<MinionJobContext> {
+ const job = await queue.add('subagent', input, {}, { allowProtectedSubmit: true });
+ return {
+ id: job.id, name: job.name, data: input, attempts_made: 0,
+ signal: new AbortController().signal, deadlineAtMs: null, shutdownSignal: new AbortController().signal,
+ async updateProgress() {}, async updateTokens() {}, async log() {},
+ async isActive() { return true; }, async readInbox() { return []; },
+ };
+}
+
+async function messageCount(jobId: number): Promise<number> {
+ const rows = await engine.executeRaw<{ c: string }>(
+ `SELECT count(*)::text AS c FROM subagent_messages WHERE job_id = $1`, [jobId],
+ );
+ return parseInt(rows[0]!.c, 10);
+}
+
+async function seed(jobId: number, idx: number, role: string, blocks: unknown[], tokensOut: number | null = null, schemaVersion = 1): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO subagent_messages (job_id, message_idx, role, content_blocks, model, tokens_in, tokens_out, schema_version)
+ VALUES ($1, $2, $3, $4::text::jsonb, 'claude-sonnet-4-6', 100, $5, $6)`,
+ [jobId, idx, role, JSON.stringify(blocks), tokensOut, schemaVersion],
+ );
+}
+
+const noUsage = { input_tokens: 5, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 };
+
+describe('gateway.toolLoop empty-response stop reason (#6448)', () => {
+ test('a zero-tool-call turn with no text stops `empty_response`, not `end`', async () => {
+ __setChatTransportForTests(async () => ({
+ text: '', blocks: [] as ChatBlock[], stopReason: 'end', usage: noUsage,
+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',
+ }));
+ const result = await toolLoop({ initialMessages: [{ role: 'user', content: 'hi' }], tools: [], toolHandlers: new Map() });
+ expect(result.stopReason).toBe('empty_response');
+ expect(result.finalText).toBe('');
+ expect(result.totalUsage.input_tokens).toBe(5);
+ });
+
+ test('whitespace-only text is an empty response too', async () => {
+ __setChatTransportForTests(async () => ({
+ text: ' \n\t', blocks: [{ type: 'text', text: ' \n\t' }] as ChatBlock[], stopReason: 'end', usage: noUsage,
+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',
+ }));
+ const result = await toolLoop({ initialMessages: [{ role: 'user', content: 'hi' }], tools: [], toolHandlers: new Map() });
+ expect(result.stopReason).toBe('empty_response');
+ });
+
+ test('an output-cap stop with no text stays `length` (truncation is never reported as empty)', async () => {
+ __setChatTransportForTests(async () => ({
+ text: '', blocks: [] as ChatBlock[], stopReason: 'length', usage: { ...noUsage, output_tokens: 8192 },
+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',
+ }));
+ const result = await toolLoop({ initialMessages: [{ role: 'user', content: 'hi' }], tools: [], toolHandlers: new Map() });
+ expect(result.stopReason).toBe('length');
+ });
+
+ test('a turn with real text still stops `end`', async () => {
+ __setChatTransportForTests(async () => ({
+ text: 'done', blocks: [{ type: 'text', text: 'done' }] as ChatBlock[], stopReason: 'end', usage: noUsage,
+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',
+ }));
+ const result = await toolLoop({ initialMessages: [{ role: 'user', content: 'hi' }], tools: [], toolHandlers: new Map() });
+ expect(result.stopReason).toBe('end');
+ });
+});
+
+describe('direct Messages path (#6448)', () => {
+ test('a blockless end_turn reports stop_reason=error, keeps the persisted rows and the token accounting', async () => {
+ const client = new FakeMessagesClient([{ content: [] as any, stop_reason: 'end_turn' }]);
+ const handler = makeSubagentHandler({ engine, client, toolRegistry: [] });
+ const ctx = await makeCtx({ prompt: 'hi' });
+ const result = await handler(ctx);
+ expect(result.stop_reason).toBe('error');
+ expect(result.result).toBe('');
+ expect(result.turns_count).toBe(1);
+ expect(result.tokens.in).toBe(10);
+ expect(result.tokens.out).toBe(5);
+ expect(await messageCount(ctx.id)).toBe(2); // user seed + the empty assistant turn, kept for replay
+ });
+
+ test('a whitespace-only text block is an empty response', async () => {
+ const client = new FakeMessagesClient([{ content: [{ type: 'text', text: ' \n' }] as any, stop_reason: 'end_turn' }]);
+ const handler = makeSubagentHandler({ engine, client, toolRegistry: [] });
+ const result = await handler(await makeCtx({ prompt: 'hi' }));
+ expect(result.stop_reason).toBe('error');
+ });
+
+ test('a provider refusal reports stop_reason=refusal', async () => {
+ const client = new FakeMessagesClient([{ content: [] as any, stop_reason: 'refusal' as any }]);
+ const handler = makeSubagentHandler({ engine, client, toolRegistry: [] });
+ const result = await handler(await makeCtx({ prompt: 'hi' }));
+ expect(result.stop_reason).toBe('refusal');
+ expect(result.result).toBe('');
+ });
+
+ test('an output-cap stop with no text is still max_tokens', async () => {
+ const client = new FakeMessagesClient([{ content: [] as any, stop_reason: 'max_tokens' }]);
+ const handler = makeSubagentHandler({ engine, client, toolRegistry: [] });
+ const result = await handler(await makeCtx({ prompt: 'hi', max_tokens: 1024 }));
+ expect(result.stop_reason).toBe('max_tokens');
+ });
+
+ test('replay of a thinking-only terminal tail returns error without a provider request', async () => {
+ const ctx = await makeCtx({ prompt: 'start' });
+ await seed(ctx.id, 0, 'user', [{ type: 'text', text: 'start' }]);
+ await seed(ctx.id, 1, 'assistant', [{ type: 'thinking', thinking: 'reasoning only, no answer' }], 50);
+ const client = new FakeMessagesClient([]);
+ const handler = makeSubagentHandler({ engine, client, toolRegistry: [] });
+ const result = await handler(ctx);
+ expect(client.calls.length).toBe(0);
+ expect(result.stop_reason).toBe('error');
+ expect(result.result).toBe('');
+ expect(result.tokens.out).toBe(50);
+ });
+
+ test('replay of an empty tail that hit the cap stays max_tokens', async () => {
+ const ctx = await makeCtx({ prompt: 'start', max_tokens: 50 });
+ await seed(ctx.id, 0, 'user', [{ type: 'text', text: 'start' }]);
+ await seed(ctx.id, 1, 'assistant', [], 50);
+ const client = new FakeMessagesClient([]);
+ const result = await makeSubagentHandler({ engine, client, toolRegistry: [] })(ctx);
+ expect(client.calls.length).toBe(0);
+ expect(result.stop_reason).toBe('max_tokens');
+ });
+});
+
+describe('gateway path (#6448)', () => {
+ beforeEach(async () => {
+ await engine.setConfig('agent.use_gateway_loop', 'true');
+ });
+
+ function gatewayHandler() {
+ return makeSubagentHandler({
+ engine, config: {} as any, toolRegistry: [],
+ makeAnthropic: () => ({ messages: { create: async () => { throw new Error('legacy path unused'); } } }) as any,
+ });
+ }
+
+ test('a live empty completion reports stop_reason=error and persists the turn', async () => {
+ __setChatTransportForTests(async () => ({
+ text: '', blocks: [] as ChatBlock[], stopReason: 'end', usage: noUsage,
+ model: 'openai:gpt-4o', providerId: 'openai',
+ } satisfies ChatResult));
+ const ctx = await makeCtx({ prompt: 'hi', model: 'openai:gpt-4o' });
+ const result = await gatewayHandler()(ctx);
+ expect(result.stop_reason).toBe('error');
+ expect(result.result).toBe('');
+ expect(await messageCount(ctx.id)).toBe(2);
+ });
+
+ test('a legacy thinking-only assistant tail is terminal: no new provider request, stop_reason=error', async () => {
+ const ctx = await makeCtx({ prompt: 'start', model: 'openai:gpt-4o' });
+ await seed(ctx.id, 0, 'user', [{ type: 'text', text: 'start' }], null, 2);
+ await seed(ctx.id, 1, 'assistant', [{ type: 'reasoning', text: 'thought about it' }], 40, 2);
+ let calls = 0;
+ __setChatTransportForTests(async () => {
+ calls++;
+ return { text: 'SHOULD NOT RUN', blocks: [] as ChatBlock[], stopReason: 'end', usage: noUsage, model: 'openai:gpt-4o', providerId: 'openai' } satisfies ChatResult;
+ });
+ const result = await gatewayHandler()(ctx);
+ expect(calls).toBe(0);
+ expect(result.stop_reason).toBe('error');
+ expect(result.result).toBe('');
+ expect(result.tokens.out).toBe(40);
+ });
+
+ test('an empty tail persisted at the output cap replays as max_tokens, still without a request', async () => {
+ const ctx = await makeCtx({ prompt: 'start', model: 'openai:gpt-4o', max_tokens: 40 });
+ await seed(ctx.id, 0, 'user', [{ type: 'text', text: 'start' }], null, 2);
+ await seed(ctx.id, 1, 'assistant', [], 40, 2);
+ let calls = 0;
+ __setChatTransportForTests(async () => {
+ calls++;
+ return { text: 'SHOULD NOT RUN', blocks: [] as ChatBlock[], stopReason: 'end', usage: noUsage, model: 'openai:gpt-4o', providerId: 'openai' } satisfies ChatResult;
+ });
+ const result = await gatewayHandler()(ctx);
+ expect(calls).toBe(0);
+ expect(result.stop_reason).toBe('max_tokens');
+ });
+
+ test('a text-bearing terminal tail still replays as end_turn with its text', async () => {
+ const ctx = await makeCtx({ prompt: 'start', model: 'openai:gpt-4o' });
+ await seed(ctx.id, 0, 'user', [{ type: 'text', text: 'start' }], null, 2);
+ await seed(ctx.id, 1, 'assistant', [{ type: 'text', text: 'the final answer' }], 7, 2);
+ __setChatTransportForTests(async () => { throw new Error('must not be called'); });
+ const result = await gatewayHandler()(ctx);
+ expect(result.stop_reason).toBe('end_turn');
+ expect(result.result).toBe('the final answer');
+ });
+});
diff --git a/test/subagent-stop-reason-helper.test.ts b/test/subagent-stop-reason-helper.test.ts
new file mode 100644
index 0000000000..c39e0edc03
--- /dev/null
+++ b/test/subagent-stop-reason-helper.test.ts
@@ -0,0 +1,52 @@
+/**
+ * Unit pins for src/core/minions/subagent-stop-reason.ts (#6448): the one
+ * mapping from a provider turn to the SubagentStopReason the handler reports.
+ */
+import { describe, expect, test } from 'bun:test';
+import {
+ directStopReason,
+ gatewayStopReason,
+ isEmptyFinalText,
+ replayTerminalStopReason,
+} from '../src/core/minions/subagent-stop-reason.ts';
+
+describe('subagent-stop-reason', () => {
+ test('isEmptyFinalText: null, empty and whitespace-only are empty; text is not', () => {
+ expect(isEmptyFinalText(null)).toBe(true);
+ expect(isEmptyFinalText(undefined)).toBe(true);
+ expect(isEmptyFinalText('')).toBe(true);
+ expect(isEmptyFinalText(' \n\t')).toBe(true);
+ expect(isEmptyFinalText('ok')).toBe(false);
+ });
+
+ test('directStopReason: max_tokens and refusal win over emptiness; empty clean stop is error', () => {
+ expect(directStopReason('max_tokens', '')).toBe('max_tokens');
+ expect(directStopReason('max_tokens', 'truncated')).toBe('max_tokens');
+ expect(directStopReason('refusal', '')).toBe('refusal');
+ expect(directStopReason('end_turn', '')).toBe('error');
+ expect(directStopReason('end_turn', ' ')).toBe('error');
+ expect(directStopReason('end_turn', 'done')).toBe('end_turn');
+ expect(directStopReason(null, 'done')).toBe('end_turn');
+ expect(directStopReason(undefined, '')).toBe('error');
+ });
+
+ test('gatewayStopReason covers every ToolLoopStopReason', () => {
+ expect(gatewayStopReason('end')).toBe('end_turn');
+ expect(gatewayStopReason('length')).toBe('max_tokens');
+ expect(gatewayStopReason('max_turns')).toBe('max_turns');
+ expect(gatewayStopReason('refusal')).toBe('refusal');
+ expect(gatewayStopReason('content_filter')).toBe('refusal');
+ expect(gatewayStopReason('empty_response')).toBe('error');
+ expect(gatewayStopReason('aborted')).toBe('error');
+ expect(gatewayStopReason('unrecoverable')).toBe('error');
+ });
+
+ test('replayTerminalStopReason: cap recovers max_tokens, empty text is error, text is end_turn', () => {
+ expect(replayTerminalStopReason(8192, 8192, '')).toBe('max_tokens');
+ expect(replayTerminalStopReason(9000, 8192, 'partial')).toBe('max_tokens');
+ expect(replayTerminalStopReason(50, 8192, '')).toBe('error');
+ expect(replayTerminalStopReason(null, 8192, ' ')).toBe('error');
+ expect(replayTerminalStopReason(undefined, 8192, 'answer')).toBe('end_turn');
+ expect(replayTerminalStopReason(50, 8192, 'answer')).toBe('end_turn');
+ });
+});