Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ai): claude-cli rebuilds or refuses a continued answer instead of returning its tail (#6791)
garrytan8769621f0340
diff --git a/docs/ai-providers/claude-cli.md b/docs/ai-providers/claude-cli.mdindex d2bd245d0e..3ceffed95f 100644--- a/docs/ai-providers/claude-cli.md+++ b/docs/ai-providers/claude-cli.md@@ -56,8 +56,8 @@ recipe — it has no base URL, only a subprocess binary path## What actually happens on a call-Each `doGenerate` call spawns `claude --print --output-format json --model-<id> --disable-slash-commands --tools '' --strict-mcp-config --settings+Each `doGenerate` call spawns `claude --print --output-format json --verbose+--model <id> --disable-slash-commands --tools '' --strict-mcp-config --settings'{"disableAllHooks":true}'` as asubprocess, with `cwd` set to a per-process directory under the OS tmpdir(`join(tmpdir(), 'gbrain-claude-cli-cwd-' + process.pid)`, created via@@ -65,6 +65,14 @@ subprocess, with `cwd` set to a per-process directory under the OS tmpdirtouch or inspect its contents), and pipes the rendered prompt to it onstdin:+- `--verbose` makes stdout the session's event array rather than the bare+ result envelope. When a response hits its output cap, Claude Code continues+ it on its own with a second request, and the envelope's `result` holds only+ the text after that point. The adapter rebuilds the full answer from the+ call's assistant events. When it cannot prove the rebuilt text is the whole+ answer, the call returns no text and no tool calls, finishes `length` (so+ callers retry or escalate, as for any capped answer) and reports+ `providerMetadata['claude-cli'].code = 'continuation_unproven'`.- `--tools ''` disables every built-in tool (Bash/Read/WebSearch/…) — thesubprocess must behave like a raw LLM, not a full agent.- `--strict-mcp-config` skips loading the user's MCP servers. Without it,@@ -196,6 +204,7 @@ check, removal and hosted brains. Two points are specific to `claude-cli`:| `claude CLI 2.0.60 or newer required (found <version>); upgrade Claude Code` | The installed CLI's argument parser rejected one of the provider's flags (`error: unknown option …` after the `--- raw ---` marker); 2.0.59 and older reject `--disable-slash-commands` | Upgrade Claude Code (`claude update`, or reinstall), then rerun | user | `persistent_install` | `claude --version` || `claude-cli exited <code>` + `--- raw ---` blob | Non-zero exit from the `claude` subprocess where stdout carried no parseable result envelope; the CLI's stderr/stdout follows the `--- raw ---` marker (kept behind the marker so error classifiers never phrase-match model-derived text) | Run `claude` interactively with the same model to see the underlying CLI error directly (e.g. not logged in, model unavailable) | user (log in, pick an available model) | `credentials` when logging in | `gbrain models doctor --json` (one tiny call per model) || `claude-cli output not JSON: ...` | `JSON.parse(stdout)` threw (stdout wasn't valid JSON at all) | Confirm the installed `claude` CLI version still supports `--print --output-format json`; this adapter's JSON handling was verified against CLI 2.1.145 | agent | none | `claude --version` |-| `claude-cli JSON event array had no "result" event` | stdout parsed as a JSON array (the `"verbose": true` event-stream shape in `~/.claude/settings.json`) but none of the events had `type: "result"` | Check `~/.claude/settings.json` for `"verbose": true`; the adapter tolerates the array shape but still needs a `result` event in it | user (edits their Claude Code settings) | none | `gbrain models doctor --json` (one tiny call per model) |+| `claude-cli JSON event array had no "result" event` | stdout parsed as the `--verbose` event array but none of the events had `type: "result"` (the run ended before reporting) | Run `claude --print --output-format json --verbose` by hand with the same model to see where it stops | agent | none | `gbrain models doctor --json` (one tiny call per model) |+| `[claude-cli] continuation_unproven (<reason>)` on stderr; the call finishes `length` with no text | The answer hit its output cap and Claude Code continued it, but the adapter could not prove the full text from the event array (`segments_unmatched`), or stdout carried only the bare envelope (`events_missing`) | Nothing to repair: callers treat it as a capped answer and retry or escalate. A caller that keeps hitting it needs a larger output cap | agent | none | rerun the call; a raised cap finishes `stop` || `gbrain models doctor` reports `chat` as `status: unknown` for a `claude-cli:` model | The probe allows 30s for the subprocess (see "Doctor probe timeout" above); a persistent `unknown` means the call genuinely failed or outran even that window — `classifyError` falls through to `unknown` for the adapter's abort message | Investigate directly: run the same model via `gbrain models doctor --json` or call `claude` by hand (e.g. not logged in, model unavailable) | agent | none | `gbrain models doctor --json` (one tiny call per model) || A call bills through the Anthropic API or a cloud backend instead of the local session | The adapter deletes `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` / `ANTHROPIC_BASE_URL` and every `CLAUDE_CODE_USE_*` backend-switch flag from the subprocess env — this covers gbrain's own env leaking into the call. It does not inspect billing switches the installed `claude` CLI carries in its own config files | If billing looks wrong, check the `claude` CLI's own auth/billing configuration on this machine, not just gbrain's env. For intentional cloud routing, use the `anthropic` recipe instead | user | none | the `claude` CLI's own auth status on this machine |diff --git a/docs/architecture/key-files/core-ai-continued.md b/docs/architecture/key-files/core-ai-continued.mdindex 6ebbfde437..cf648cc8d5 100644--- a/docs/architecture/key-files/core-ai-continued.md+++ b/docs/architecture/key-files/core-ai-continued.md@@ -4,7 +4,9 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.Provider adapters, recipes and the Voyage width plumbing.-- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter over the local `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt JSON: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt asks for no id and a stray `id` is ignored (nothing round-trips it; the loop pairs results in memory within one turn). Every child gets `--settings '{"disableAllHooks":true}'` (#5820: user/project hooks never run, so gbrain's own Stop hook cannot bank the call; login is untouched; managed-policy hooks still run on 2.1.287). A CLI that rejects any flag (`unknown option`) fails with `claude CLI 2.0.60 or newer required (found <version>)` (`MIN_CLAUDE_CLI_VERSION`, probed: 2.0.59 rejects `--disable-slash-commands`). No doStream: gateway.toolLoop uses doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`. `claudeCliFinishReason` maps the CLI's `stop_reason` to the finish reason (`max_tokens` → `length`, `refusal` → `content-filter`, parsed tool calls → `tool-calls`, anything else → `stop`), so callers can refuse clipped answers (`test/claude-cli-stop-reason.test.ts`). `renderPrompt` replays an earlier tool call with its input as JSON (`[tool_use name({...})]`). #6424: a positive integer `maxOutputTokens` reaches the child as `CLAUDE_CODE_MAX_OUTPUT_TOKENS` (env, `--settings` env). #6523: the CLI reports a response that hit that cap (or its own default) as an `is_error` envelope whose `result` starts `API Error: Claude's response exceeded the N output token maximum`; `isOutputCapEnvelope` (anchored prefix, `is_error: true`, no `api_error_status`, string `result`, any cap, any exit code) resolves it as a success with empty text and `stop_reason: 'max_tokens'`, so callers see `length` and their escalation ladders run (loops_extract 2048 → 8192, facts/extract 1× → 2×); every other error envelope stays `ClaudeCliProcessError` (`test/claude-cli-output-cap.test.ts`).+- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter over the local `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt JSON: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt asks for no id and a stray `id` is ignored (nothing round-trips it; the loop pairs results in memory within one turn). Every child gets `--settings '{"disableAllHooks":true}'` (#5820: user/project hooks never run, so gbrain's own Stop hook cannot bank the call; login is untouched; managed-policy hooks still run on 2.1.287). A CLI that rejects any flag (`unknown option`) fails with `claude CLI 2.0.60 or newer required (found <version>)` (`MIN_CLAUDE_CLI_VERSION`, probed: 2.0.59 rejects `--disable-slash-commands`). No doStream: gateway.toolLoop uses doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`. `claudeCliFinishReason` maps the CLI's `stop_reason` to the finish reason (`max_tokens` → `length`, `refusal` → `content-filter`, parsed tool calls → `tool-calls`, anything else → `stop`), so callers can refuse clipped answers (`test/claude-cli-stop-reason.test.ts`). `renderPrompt` replays an earlier tool call with its input as JSON (`[tool_use name({...})]`). #6424: a positive integer `maxOutputTokens` reaches the child as `CLAUDE_CODE_MAX_OUTPUT_TOKENS` (env, `--settings` env). #6523: the CLI reports a response that hit that cap (or its own default) as an `is_error` envelope whose `result` starts `API Error: Claude's response exceeded the N output token maximum`; `isOutputCapEnvelope` (anchored prefix, `is_error: true`, no `api_error_status`, string `result`, any cap, any exit code) resolves it as a success with empty text and `stop_reason: 'max_tokens'`, so callers see `length` and their escalation ladders run (loops_extract 2048 → 8192, facts/extract 1× → 2×); every other error envelope stays `ClaudeCliProcessError` (`test/claude-cli-output-cap.test.ts`). #6791: every child also gets `--verbose`, so the json stdout is the session's event array; `doGenerate` takes its text from `resolveClaudeCliAnswer` (`claude-cli-continuation.ts`) and, when that refuses a continued answer, returns empty text, no tool calls, finish `length` and `providerMetadata['claude-cli'] = { code: 'continuation_unproven', reason }` before any `<use_tools>` block is parsed.++- `src/core/ai/providers/claude-cli-continuation.ts` — what text a claude-cli print-mode run answered. Claude Code continues a response that hit its output cap on its own (meta "Resume directly" nudge, second request), and the envelope's `result` / `stop_reason` are then only the continuation's. `resolveClaudeCliAnswer(run, requestedCap)` keeps the envelope `result` when there was no continuation (or the envelope already says `max_tokens`); otherwise it rebuilds the answer from the call's own events (consecutive assistant events sharing a `message.id` are one segment; `<synthetic>` error messages are skipped), joining the segments' text in order. A rebuild needs the last segment's final text block to equal `result`, no `tombstone` event, every earlier text-bearing segment to report `max_tokens` or no stop reason, and every user event between segments to be a "Resume directly" nudge; anything else is `continuation_unproven` with reason `segments_unmatched`. Without events (a bare envelope) a continuation is inferred from `num_turns > 1` or output tokens above the cap (the forwarded positive-integer `maxOutputTokens`, else `CLAUDE_CLI_DEFAULT_OUTPUT_CAP` = 32000) and refused as `events_missing`; one segment with output above a requested cap is `segments_unmatched`. Nothing is read from disk, so a hermetic `CLAUDE_CONFIG_DIR` changes nothing. The first refusal in a process writes one `[claude-cli] continuation_unproven (<reason>)` line to stderr; `continuationUnprovenMetadata` builds the provider metadata. Pinned by `test/claude-cli-continuation-6791.test.ts`.- `src/core/ai/providers/claude-cli-scratch.ts` — the claude-cli provider's per-PID scratch dirs (`claudeCliCwdDir`/`claudeCliConfigDir` off the `CLAUDE_CLI_CWD_PREFIX`/`CLAUDE_CLI_CONFIG_PREFIX` basename constants, plus `sweepDeadClaudeCliScratchDirs`), split into a dependency-light module so transcript discovery (`src/core/transcripts/discover.ts`) can call `isClaudeCliSelfTranscriptPath(path)` WITHOUT importing the provider's @ai-sdk surface. Each `claude --print` subprocess runs with cwd = a per-PID scratch dir (context isolation — no local CLAUDE.md auto-discovery), and Claude Code records a session transcript for that cwd under `~/.claude/projects/<slugified-cwd>/`; those sessions are gbrain's OWN internal LLM calls, and importing them back is a self-ingestion feedback loop (prompt scaffolding + page content re-entering as "conversations"). The prefix is lowercase `[a-z-]` only, so it survives Claude Code's cwd slugification verbatim and a substring match on the discovered path is a reliable self-exclusion fingerprint. `claudeCliSelfSessionIds(projectsRoot = claudeProjectsDir())` lists the session ids of those harness transcripts; `isClaudeCliSelfSessionId(id, projectDirs = claudeCliSelfProjectDirs())` is the single-session classifier (#5820) shared by the serve-side writeback harvest, the sweep and doctor `self_capture`: one listing of the projects root, then an existence check per prefix-matched scratch project (path-shaped ids are refused); the session-end hook named each corpus file `<session id>.txt`, so dream discovery and the sweep's corpus pass use the set to skip self-captures written before the hook refused them (best-effort: a pruned harness transcript leaves its capture unclassifiable). Pinned by `test/transcripts-self-exclusion.test.ts`.diff --git a/src/core/ai/providers/claude-cli-continuation.ts b/src/core/ai/providers/claude-cli-continuation.tsnew file mode 100644index 0000000000..6308fba10b--- /dev/null+++ b/src/core/ai/providers/claude-cli-continuation.ts@@ -0,0 +1,151 @@+/**+ * #6791: Claude Code continues a response that hit its output cap on its own.+ * The query loop withholds the cap error, appends a meta nudge ("Output token+ * limit hit. Resume directly ...") and sends a second request; the model picks+ * up mid-thought. Print mode's `result` is then the text of the LAST assistant+ * message only, and its `stop_reason` is the continuation's (`end_turn`), so the+ * envelope alone reads as a complete answer that is really its tail.+ *+ * Every assistant message the loop yields reaches the SDK output, and with+ * `--output-format json --verbose` stdout is that whole event array (verified in+ * the Claude Code 2.1.296 bundle). The adapter therefore rebuilds the answer+ * from the call's own events, never from a session transcript on disk:+ * consecutive assistant events sharing a `message.id` are one API response+ * (one segment), and the answer is the segments' text in order.+ *+ * A rebuild is accepted only when it is provably this answer: the last+ * segment's final text block is the envelope's `result`, no event retracted a+ * segment, every earlier segment that carries text ended at the cap (or reports+ * no stop reason), and a nudge visible between segments asks to resume rather+ * than rewrite. Otherwise the call is `continuation_unproven`: the adapter+ * returns no text and no tool calls and finishes `length`, the outcome every+ * caller already escalates or retries on (#6523).+ */++/** CLAUDE_CODE_MAX_OUTPUT_TOKENS' default when the CLI's model table names none (Claude Code 2.1.x). */+export const CLAUDE_CLI_DEFAULT_OUTPUT_CAP = 32_000;++export type ContinuationUnprovenReason = 'events_missing' | 'segments_unmatched';++export type ClaudeCliAnswer =+ | { kind: 'answer'; text: string }+ | { kind: 'unproven'; reason: ContinuationUnprovenReason };++/** The parts of a print-mode run the resolution reads. */+export interface ClaudeCliRunView {+ result: string;+ stop_reason: string | null;+ num_turns?: number;+ usage?: { output_tokens?: number };+ /** The session's event array when stdout carried one; null for a bare envelope. */+ events: readonly unknown[] | null;+}++interface Segment {+ id: string;+ text: string;+ lastBlockText: string;+ stopReason: unknown;+ /** Text of the user events between the previous segment and this one. */+ nudges: string[];+}++const RESUME_NUDGE_RE = /\bResume directly\b/;++function record(v: unknown): Record<string, unknown> | null {+ return v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null;+}++function blocksOf(message: Record<string, unknown>): Array<Record<string, unknown>> {+ const content = message.content;+ if (typeof content === 'string') return [{ type: 'text', text: content }];+ return Array.isArray(content) ? content.map(record).filter((b): b is Record<string, unknown> => b !== null) : [];+}++function textOf(blocks: Array<Record<string, unknown>>): string {+ return blocks.map(b => (b.type === 'text' && typeof b.text === 'string' ? b.text : '')).join('');+}++/** The call's assistant segments in order, or null when the events contradict a single linear answer. */+function readSegments(events: readonly unknown[]): Segment[] | null {+ const segments: Segment[] = [];+ const seen = new Set<string>();+ let nudges: string[] = [];+ for (const raw of events) {+ const event = record(raw);+ if (!event) continue;+ if (event.type === 'tombstone') return null;+ const message = record(event.message);+ if (event.type === 'user') {+ if (message && segments.length > 0) nudges.push(textOf(blocksOf(message)));+ continue;+ }+ if (event.type !== 'assistant' || !message || message.model === '<synthetic>') continue;+ if (event.parent_tool_use_id != null || typeof message.id !== 'string') return null;+ const blocks = blocksOf(message);+ const last = segments.at(-1);+ if (last && last.id === message.id) {+ last.text += textOf(blocks);+ if (blocks.length > 0) last.lastBlockText = textOf(blocks.slice(-1));+ last.stopReason = message.stop_reason ?? last.stopReason;+ continue;+ }+ if (seen.has(message.id)) return null;+ seen.add(message.id);+ segments.push({ id: message.id, text: textOf(blocks), lastBlockText: textOf(blocks.slice(-1)), stopReason: message.stop_reason, nudges });+ nudges = [];+ }+ return segments;+}++function rebuild(segments: Segment[], result: string): string | null {+ const final = segments.at(-1)!;+ if (final.lastBlockText.trim() !== result.trim()) return null;+ for (let i = 0; i < segments.length - 1; i++) {+ if (segments[i]!.text === '') continue;+ const stop = segments[i]!.stopReason;+ if (stop != null && stop !== 'max_tokens') return null;+ if (segments[i + 1]!.nudges.some(n => !RESUME_NUDGE_RE.test(n))) return null;+ }+ return segments.map(s => s.text).join('');+}++/**+ * Decide what text a print-mode run answered. A run with no continuation keeps+ * its envelope `result`; a continued run is rebuilt or refused. Continuation+ * shows as more than one segment; without events, as output above the cap+ * (`requestedCap`, forwarded as CLAUDE_CODE_MAX_OUTPUT_TOKENS, else the CLI+ * default) or more than one turn. One segment with output above a REQUESTED+ * cap contradicts the events (one API call cannot exceed it); the CLI default+ * is not that firm, since the CLI's model table can raise it.+ */+export function resolveClaudeCliAnswer(run: ClaudeCliRunView, requestedCap: number | undefined): ClaudeCliAnswer {+ const answer = { kind: 'answer', text: run.result } as const;+ if (run.stop_reason === 'max_tokens') return answer;+ const forwardedCap = typeof requestedCap === 'number' && Number.isInteger(requestedCap) && requestedCap > 0 ? requestedCap : undefined;+ const output = run.usage?.output_tokens;+ const overCap = typeof output === 'number' && output > (forwardedCap ?? CLAUDE_CLI_DEFAULT_OUTPUT_CAP);+ if (run.events === null) {+ return overCap || (run.num_turns ?? 1) > 1 ? unproven('events_missing') : answer;+ }+ const segments = readSegments(run.events);+ if (segments === null) return unproven('segments_unmatched');+ if (segments.length <= 1) return overCap && forwardedCap !== undefined ? unproven('segments_unmatched') : answer;+ const text = rebuild(segments, run.result);+ return text === null ? unproven('segments_unmatched') : { kind: 'answer', text };+}++let noticed = false;++function unproven(reason: ContinuationUnprovenReason): ClaudeCliAnswer {+ if (!noticed) {+ noticed = true;+ process.stderr.write(`[claude-cli] continuation_unproven (${reason}): Claude Code continued an answer past its output cap and gbrain could not prove the full text; the call finishes as length with no text, so callers retry or escalate. A larger output cap avoids the continuation.\n`);+ }+ return { kind: 'unproven', reason };+}++/** Provider metadata of a refused continuation, under the provider's key. */+export function continuationUnprovenMetadata(reason: ContinuationUnprovenReason): { 'claude-cli': { code: 'continuation_unproven'; reason: ContinuationUnprovenReason } } {+ return { 'claude-cli': { code: 'continuation_unproven', reason } };+}diff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.tsindex a96199898a..b35ac3bbc7 100644--- a/src/core/ai/providers/claude-cli-language-model.ts+++ b/src/core/ai/providers/claude-cli-language-model.ts@@ -41,6 +41,7 @@ import {claudeCliCwdDir,sweepDeadClaudeCliScratchDirs,} from './claude-cli-scratch.ts';+import { continuationUnprovenMetadata, resolveClaudeCliAnswer } from './claude-cli-continuation.ts';import type {LanguageModelV2,LanguageModelV2CallOptions,@@ -49,6 +50,7 @@ import type {LanguageModelV2Prompt,LanguageModelV2Message,LanguageModelV2ProviderDefinedTool,+ SharedV2ProviderMetadata,} from '@ai-sdk/provider';function claudeBin(): string {@@ -142,18 +144,20 @@ export class ClaudeCliProcessError extends Error {}}+/** The result envelope plus the session's event array when stdout carried one (`--verbose`, #6791). */+type ClaudeRun = ClaudeJsonResult & { events: readonly unknown[] | null };+type EnvelopeParse =- | { ok: true; envelope: ClaudeJsonResult }+ | { ok: true; envelope: ClaudeRun }| { ok: false; reason: 'not-json'; error: unknown }| { ok: false; reason: 'no-result-event' };/**- * Unwrap `--output-format json` stdout into the result envelope. Tolerates both- * output shapes: the bare result object, and the verbose-mode event ARRAY —- * with `"verbose": true` in ~/.claude/settings.json the CLI emits- * [{type:"system",subtype:"init",...}, ..., {type:"result",...}] instead of the- * bare object, and there is no CLI flag to force it off (no --no-verbose;- * --settings '{}' merges, does not replace). Verified on CLI 2.1.145.+ * Unwrap `--output-format json` stdout into the result envelope and the event+ * array it came in. `runClaude` passes `--verbose` (#6791), so the CLI emits+ * [{type:"system",subtype:"init",...}, ..., {type:"result",...}]; the bare+ * result object (events null) is still accepted. The array shape was verified on+ * CLI 2.1.145; that it carries every assistant message, in the 2.1.296 bundle.*/function parseResultEnvelope(stdout: string): EnvelopeParse {let parsed: unknown;@@ -162,6 +166,7 @@ function parseResultEnvelope(stdout: string): EnvelopeParse {} catch (error) {return { ok: false, reason: 'not-json', error };}+ const events = Array.isArray(parsed) ? parsed : null;if (Array.isArray(parsed)) {const resultEvent = parsed.find((ev): ev is ClaudeJsonResult =>@@ -178,7 +183,7 @@ function parseResultEnvelope(stdout: string): EnvelopeParse {if (!parsed || typeof parsed !== 'object') {return { ok: false, reason: 'not-json', error: new Error('top-level JSON value is not an object') };}- return { ok: true, envelope: parsed as ClaudeJsonResult };+ return { ok: true, envelope: { ...(parsed as ClaudeJsonResult), events } };}/**@@ -212,7 +217,7 @@ function isOutputCapEnvelope(envelope: ClaudeJsonResult): boolean {}/** The cap envelope as the success the API would have returned: no text, `max_tokens`, usage as reported. */-function outputCapAsLength(envelope: ClaudeJsonResult): ClaudeJsonResult {+function outputCapAsLength<T extends ClaudeJsonResult>(envelope: T): T {return { ...envelope, is_error: false, result: '', stop_reason: 'max_tokens' };}@@ -368,7 +373,7 @@ function runClaude(model: string,signal?: AbortSignal,maxOutputTokens?: number,-): Promise<ClaudeJsonResult> {+): Promise<ClaudeRun> {return new Promise((resolve, reject) => {// #6424: forward the call's output cap. The inline --settings env sits// above the user's settings.json env block, so both carry it.@@ -380,7 +385,10 @@ function runClaude(: '{"disableAllHooks":true}';const args = ['--print',- '--output-format', 'json',+ // #6791: --verbose turns the json output into the session's event+ // array, the only record of the segments before an automatic+ // continuation (the envelope's result holds the last one).+ '--output-format', 'json', '--verbose','--model', model,'--disable-slash-commands',// Agent isolation: this subprocess must behave like a raw LLM, not a@@ -703,6 +711,7 @@ export class ClaudeCliLanguageModel implements LanguageModelV2 {totalTokens: number | undefined;cachedInputTokens: number | undefined;};+ providerMetadata?: SharedV2ProviderMetadata;warnings: never[];}> {const { systemText, userPrompt } = renderPrompt(options.prompt);@@ -710,7 +719,38 @@ export class ClaudeCliLanguageModel implements LanguageModelV2 {const systemPrompt = [systemText, toolInstructions].filter(s => s.length > 0).join('\n');const result = await runClaude(systemPrompt, userPrompt, this.modelId, options.abortSignal, options.maxOutputTokens);- const { toolCalls, beforeText, afterText } = extractToolCalls(result.result);+ // The CLI reports Anthropic's separate buckets; LanguageModelV2Usage wants+ // the TOTAL input with the cache read as a subset (what every SDK provider+ // reports), so the gateway prices cache tokens once. Cache creation has no+ // V2 field: it stays inside the total at the input rate.+ const cachedInputTokens =+ result.usage?.cache_read_input_tokens !== undefined+ ? Number(result.usage.cache_read_input_tokens)+ : undefined;+ const inputTokens = result.usage?.input_tokens === undefined ? undefined+ : result.usage.input_tokens + (cachedInputTokens ?? 0) + Number(result.usage.cache_creation_input_tokens ?? 0);+ const outputTokens = result.usage?.output_tokens;+ const totalTokens = (inputTokens ?? 0) + (outputTokens ?? 0);+ const usage = {+ inputTokens,+ outputTokens,+ totalTokens: inputTokens !== undefined && outputTokens !== undefined ? totalTokens : undefined,+ cachedInputTokens,+ };++ // #6791: a continued answer is rebuilt from its segments, or refused+ // before any tool block in its tail can be parsed and dispatched.+ const answer = resolveClaudeCliAnswer(result, options.maxOutputTokens);+ if (answer.kind === 'unproven') {+ return {+ content: [{ type: 'text', text: '' }],+ finishReason: 'length',+ usage,+ providerMetadata: continuationUnprovenMetadata(answer.reason),+ warnings: [],+ };+ }+ const { toolCalls, beforeText, afterText } = extractToolCalls(answer.text);const content: LanguageModelV2Content[] = [];if (beforeText) content.push({ type: 'text', text: beforeText });@@ -725,32 +765,13 @@ export class ClaudeCliLanguageModel implements LanguageModelV2 {if (afterText) content.push({ type: 'text', text: afterText });if (content.length === 0) {// Empty response — still hand the caller a well-formed content array.- content.push({ type: 'text', text: result.result ?? '' });+ content.push({ type: 'text', text: answer.text ?? '' });}- const finishReason = claudeCliFinishReason(result.stop_reason, toolCalls.length > 0);- // The CLI reports Anthropic's separate buckets; LanguageModelV2Usage wants- // the TOTAL input with the cache read as a subset (what every SDK provider- // reports), so the gateway prices cache tokens once. Cache creation has no- // V2 field: it stays inside the total at the input rate.- const cachedInputTokens =- result.usage?.cache_read_input_tokens !== undefined- ? Number(result.usage.cache_read_input_tokens)- : undefined;- const inputTokens = result.usage?.input_tokens === undefined ? undefined- : result.usage.input_tokens + (cachedInputTokens ?? 0) + Number(result.usage.cache_creation_input_tokens ?? 0);- const outputTokens = result.usage?.output_tokens;- const totalTokens = (inputTokens ?? 0) + (outputTokens ?? 0);-return {content,- finishReason,- usage: {- inputTokens,- outputTokens,- totalTokens: inputTokens !== undefined && outputTokens !== undefined ? totalTokens : undefined,- cachedInputTokens,- },+ finishReason: claudeCliFinishReason(result.stop_reason, toolCalls.length > 0),+ usage,warnings: [],};}diff --git a/test/claude-cli-continuation-6791.test.ts b/test/claude-cli-continuation-6791.test.tsnew file mode 100644index 0000000000..9f3bac3666--- /dev/null+++ b/test/claude-cli-continuation-6791.test.ts@@ -0,0 +1,282 @@+/**+ * #6791: when a response hits its output cap, Claude Code continues it on its+ * own (a meta "Output token limit hit. Resume directly" nudge, then a second+ * API response) and its print-mode `result` holds only the text after that+ * nudge, with the final `stop_reason` (`end_turn`). The adapter returned that+ * tail as a complete answer: chronicle parsed the nested `who` array of the+ * tail as the event list and failed `malformed_proposal`.+ *+ * Contract pinned here: the adapter runs the CLI with `--verbose`, so stdout is+ * the session's event array, and rebuilds the full answer from the assistant+ * segments of this call. When a continuation happened but the segments cannot+ * be proven to make up the answer, it returns no text and no tool calls,+ * finishes `length` (callers escalate or retry, #6523) and names the cause in+ * `providerMetadata['claude-cli']`.+ *+ * Authoring gate: (1) protects the full text of a continued answer and the+ * refusal to dispatch a tail; (2) fails when the adapter returns the envelope+ * `result` again or drops `--verbose`; (3) the stop-reason and output-cap suites+ * only cover single-response envelopes; (4) no seam: a POSIX shell stub at+ * GBRAIN_CLAUDE_CLI_BIN plays the CLI and prints the event array only when+ * handed `--verbose`, as the real CLI does. No provider is called.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { chmodSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { LanguageModelV2CallOptions } from '@ai-sdk/provider';+import { ClaudeCliLanguageModel } from '../src/core/ai/providers/claude-cli-language-model.ts';+import { chat, configureGateway, resetGateway, toolLoop } from '../src/core/ai/gateway.ts';+import { isValidProposal, parseJudgeJson } from '../src/core/chronicle/extract-events.ts';+import { withEnv } from './helpers/with-env.ts';++// The issue's minimized reconstruction of the cut (content values replaced).+const PREFIX = '[{"when":"2026-10-13","who":["person-a"],"what":"Reviewed a project","kind":';+const CONTINUATION = '"event"},{"when":"2026-10-13","who":["person-a","person-c"],"what":"Agreed a next step","kind":"decision"}]';+const RESUME_NUDGE = 'Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. '+ + 'Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.';+const ISSUE_USAGE = { input_tokens: 9047, output_tokens: 4386 };++type Block = { type: 'text'; text: string } | { type: 'thinking'; thinking: string; signature: string };++function assistant(id: string, content: Block[], stopReason: string | null = null): Record<string, unknown> {+ return {+ type: 'assistant', parent_tool_use_id: null, session_id: 'synthetic-session', uuid: `uuid-${id}-${content.length}`,+ message: { id, type: 'message', role: 'assistant', model: 'claude-sonnet-5', content, stop_reason: stopReason, usage: { output_tokens: 1 } },+ };+}++function nudge(text: string): Record<string, unknown> {+ return { type: 'user', parent_tool_use_id: null, session_id: 'synthetic-session', message: { role: 'user', content: [{ type: 'text', text }] } };+}++function envelope(result: string, extra: Record<string, unknown> = {}): Record<string, unknown> {+ return {+ type: 'result', subtype: 'success', is_error: false, result, stop_reason: 'end_turn',+ session_id: 'synthetic-session', num_turns: 2, usage: ISSUE_USAGE, ...extra,+ };+}++const init = { type: 'system', subtype: 'init', session_id: 'synthetic-session', tools: [] };++/** The two-segment turn from the issue: max_tokens inside an object, then the automatic continuation. */+function continuedTurn(opts: { withNudge?: boolean; stopReasons?: boolean } = {}): unknown[] {+ const { withNudge = true, stopReasons = true } = opts;+ return [+ init,+ assistant('msg_first', [{ type: 'thinking', thinking: '', signature: 'sig' }]),+ assistant('msg_first', [{ type: 'text', text: PREFIX }], stopReasons ? 'max_tokens' : null),+ ...(withNudge ? [nudge(RESUME_NUDGE)] : []),+ assistant('msg_second', [{ type: 'text', text: CONTINUATION }], stopReasons ? 'end_turn' : null),+ envelope(CONTINUATION),+ ];+}++interface Stub { argv: () => string[]; configDir: () => string }++/**+ * Stage a stub `claude`: prints `verbose` when handed `--verbose` and `bare`+ * otherwise (the real CLI's json shapes), recording its argv and CLAUDE_CONFIG_DIR.+ */+async function withCli<T>(output: { verbose: unknown; bare?: unknown }, run: (stub: Stub) => Promise<T>): Promise<T> {+ const dir = mkdtempSync(join(tmpdir(), 'claude-continuation-'));+ const verbosePath = join(dir, 'verbose.json');+ const barePath = join(dir, 'bare.json');+ const argvPath = join(dir, 'argv');+ const configPath = join(dir, 'config-dir');+ const verbose = output.verbose;+ const bare = output.bare ?? (Array.isArray(verbose) ? verbose.at(-1) : verbose);+ writeFileSync(verbosePath, JSON.stringify(verbose));+ writeFileSync(barePath, JSON.stringify(bare));+ const bin = join(dir, 'claude');+ writeFileSync(bin, [+ '#!/bin/sh',+ 'cat > /dev/null',+ `printf '%s\\n' "$CLAUDE_CONFIG_DIR" > "${configPath}"`,+ 'verbose=',+ `for a in "$@"; do printf '%s\\n' "$a" >> "${argvPath}"; if [ "$a" = "--verbose" ]; then verbose=1; fi; done`,+ `if [ -n "$verbose" ]; then cat "${verbosePath}"; else cat "${barePath}"; fi`,+ ].join('\n') + '\n');+ chmodSync(bin, 0o755);+ const stub: Stub = {+ argv: () => readFileSync(argvPath, 'utf8').trimEnd().split('\n'),+ configDir: () => readFileSync(configPath, 'utf8').trimEnd(),+ };+ try {+ return await withEnv({ GBRAIN_CLAUDE_CLI_BIN: bin, GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG: undefined }, () => run(stub));+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++function options(maxOutputTokens?: number): LanguageModelV2CallOptions {+ return {+ prompt: [{ role: 'user', content: [{ type: 'text', text: 'Extract the events.' }] }],+ ...(maxOutputTokens === undefined ? {} : { maxOutputTokens }),+ } as LanguageModelV2CallOptions;+}++const generate = (maxOutputTokens?: number) => new ClaudeCliLanguageModel('claude-sonnet-5').doGenerate(options(maxOutputTokens));++function textOf(content: Array<{ type: string; text?: string }>): string {+ return content.filter(c => c.type === 'text').map(c => c.text ?? '').join('');+}++function unproven(reason: string) {+ return { 'claude-cli': { code: 'continuation_unproven', reason } };+}++describe('a continued answer is rebuilt from the call\'s own event stream (#6791)', () => {+ test('the issue\'s reconstruction: prefix + continuation, and chronicle\'s parser accepts every proposal', async () => {+ await withCli({ verbose: continuedTurn() }, async (stub) => {+ const out = await generate(4000);+ expect(stub.argv()).toContain('--verbose');+ expect(out.finishReason).toBe('stop');+ expect(textOf(out.content)).toBe(PREFIX + CONTINUATION);+ const proposals = parseJudgeJson(textOf(out.content));+ expect(proposals).toHaveLength(2);+ expect(proposals!.every(isValidProposal)).toBe(true);+ expect(out.usage.outputTokens).toBe(4386);+ });+ });++ test('the tail alone is what the envelope reports and what chronicle rejects', () => {+ const tail = parseJudgeJson(CONTINUATION);+ expect(tail).toEqual(['person-a', 'person-c'] as unknown as typeof tail);+ expect(tail!.every(isValidProposal)).toBe(false);+ });++ test('segments without per-segment stop reasons or a visible nudge still rebuild', async () => {+ await withCli({ verbose: continuedTurn({ withNudge: false, stopReasons: false }) }, async () => {+ const out = await generate(4000);+ expect(out.finishReason).toBe('stop');+ expect(textOf(out.content)).toBe(PREFIX + CONTINUATION);+ });+ });++ test('a hermetic config dir does not matter: nothing is read from it', async () => {+ const configDir = mkdtempSync(join(tmpdir(), 'claude-continuation-config-'));+ try {+ await withCli({ verbose: continuedTurn() }, async (stub) => {+ await withEnv({ GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG: configDir }, async () => {+ const out = await generate(4000);+ expect(stub.configDir()).toBe(configDir);+ expect(out.finishReason).toBe('stop');+ expect(textOf(out.content)).toBe(PREFIX + CONTINUATION);+ });+ });+ expect(readdirSync(configDir)).toEqual([]);+ } finally {+ rmSync(configDir, { recursive: true, force: true });+ }+ });++ test('no requested cap: two segments rebuild; the CLI default cap bounds a lone envelope', async () => {+ await withCli({ verbose: continuedTurn() }, async () => {+ const out = await generate();+ expect(out.finishReason).toBe('stop');+ expect(textOf(out.content)).toBe(PREFIX + CONTINUATION);+ });+ const over = envelope(CONTINUATION, { usage: { input_tokens: 10, output_tokens: 32_001 } });+ await withCli({ verbose: over, bare: over }, async () => {+ const out = await generate();+ expect(out.finishReason).toBe('length');+ expect(out.content).toEqual([{ type: 'text', text: '' }]);+ expect(out.providerMetadata).toEqual(unproven('events_missing'));+ });+ const under = envelope(CONTINUATION, { num_turns: 1, usage: { input_tokens: 10, output_tokens: 32_000 } });+ await withCli({ verbose: under, bare: under }, async () => {+ const out = await generate();+ expect(out.finishReason).toBe('stop');+ expect(textOf(out.content)).toBe(CONTINUATION);+ });+ });++ test('a single-segment answer is unchanged', async () => {+ const single = [init, assistant('msg_only', [{ type: 'text', text: PREFIX + CONTINUATION }], 'end_turn'),+ envelope(PREFIX + CONTINUATION, { num_turns: 1, usage: { input_tokens: 10, output_tokens: 300 } })];+ await withCli({ verbose: single }, async () => {+ const out = await generate(4000);+ expect(out.finishReason).toBe('stop');+ expect(out.content).toEqual([{ type: 'text', text: PREFIX + CONTINUATION }]);+ expect(out.providerMetadata).toBeUndefined();+ });+ });+});++describe('an unprovable continuation is a length outcome with no text and no tool calls (#6791)', () => {+ const cases: Array<[string, unknown, unknown, string]> = [+ ['the CLI printed only the envelope while usage exceeds the requested cap', envelope(CONTINUATION), envelope(CONTINUATION), 'events_missing'],+ ['the last segment does not match the envelope result',+ [init, assistant('a', [{ type: 'text', text: PREFIX }], 'max_tokens'), assistant('b', [{ type: 'text', text: 'other text' }], 'end_turn'), envelope(CONTINUATION)],+ undefined, 'segments_unmatched'],+ ['an earlier segment ended for a reason other than the cap',+ [init, assistant('a', [{ type: 'text', text: PREFIX }], 'end_turn'), assistant('b', [{ type: 'text', text: CONTINUATION }], 'end_turn'), envelope(CONTINUATION)],+ undefined, 'segments_unmatched'],+ ['the nudge between segments asks for a rewrite, not a resume',+ [init, assistant('a', [{ type: 'text', text: PREFIX }]), nudge('Your response above was cut off mid-stream and only your next message is delivered. Write the complete response again from the start.'),+ assistant('b', [{ type: 'text', text: CONTINUATION }]), envelope(CONTINUATION)],+ undefined, 'segments_unmatched'],+ ['a segment was retracted',+ [init, assistant('a', [{ type: 'text', text: PREFIX }]), { type: 'tombstone', message: { uuid: 'uuid-a-1' } }, assistant('b', [{ type: 'text', text: CONTINUATION }]), envelope(CONTINUATION)],+ undefined, 'segments_unmatched'],+ ['one segment but usage exceeds the requested cap',+ [init, assistant('a', [{ type: 'text', text: CONTINUATION }], 'end_turn'), envelope(CONTINUATION)],+ undefined, 'segments_unmatched'],+ ];+ for (const [label, verbose, bare, reason] of cases) {+ test(`${label} → ${reason}`, async () => {+ await withCli({ verbose, bare }, async () => {+ const out = await generate(4000);+ expect(out.finishReason).toBe('length');+ expect(out.content).toEqual([{ type: 'text', text: '' }]);+ expect(out.providerMetadata).toEqual(unproven(reason));+ expect(out.usage.outputTokens).toBe(4386);+ });+ });+ }++ afterEach(() => resetGateway());++ test('a valid write block in the tail of an unprovable continuation dispatches no tool handler', async () => {+ const block = '<use_tools>\n[{"name": "put_page", "input": {"slug": "notes/tail", "content": "tail only"}}]\n</use_tools>';+ const calls: unknown[] = [];+ await withCli({ verbose: envelope(block), bare: envelope(block) }, async () => {+ configureGateway({ chat_model: 'claude-cli:claude-sonnet-5', env: {} });+ const result = await toolLoop({+ initialMessages: [{ role: 'user', content: 'Write the page.' }],+ tools: [{ name: 'put_page', description: 'Write a page.', inputSchema: { type: 'object', properties: { slug: { type: 'string' }, content: { type: 'string' } } } }],+ toolHandlers: new Map([['put_page', { execute: async (input: unknown) => { calls.push(input); return 'ok'; } }]]),+ maxTurns: 2,+ maxTokens: 4000,+ });+ expect(calls).toEqual([]);+ expect(result.stopReason).toBe('length');+ expect(result.finalText).toBe('');+ const answer = await chat({ messages: [{ role: 'user', content: 'Write the page.' }], maxTokens: 4000 });+ expect(answer.stopReason).toBe('length');+ expect(answer.text).toBe('');+ expect(answer.providerMetadata?.['claude-cli']).toEqual(unproven('events_missing')['claude-cli']);+ });+ }, 30_000);++ test('one stderr notice per process', async () => {+ const modulePath = join(import.meta.dir, '..', 'src', 'core', 'ai', 'providers', 'claude-cli-language-model.ts');+ const script = [+ `const { ClaudeCliLanguageModel } = await import(${JSON.stringify(modulePath)});`,+ 'const opts = { prompt: [{ role: "user", content: [{ type: "text", text: "x" }] }], maxOutputTokens: 4000 };',+ 'for (let i = 0; i < 2; i++) {',+ ' const out = await new ClaudeCliLanguageModel("claude-sonnet-5").doGenerate(opts);',+ ' if (out.finishReason !== "length") throw new Error("expected length");',+ '}',+ ].join('\n');+ await withCli({ verbose: envelope(CONTINUATION), bare: envelope(CONTINUATION) }, async () => {+ const child = Bun.spawnSync([process.execPath, '-e', script], { env: { ...process.env }, stderr: 'pipe', stdout: 'pipe' });+ const stderr = child.stderr.toString();+ expect(child.exitCode, stderr).toBe(0);+ const notices = stderr.split('\n').filter(line => line.includes('continuation_unproven'));+ expect(notices).toHaveLength(1);+ expect(notices[0]).toContain('events_missing');+ });+ }, 30_000);+});