Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ai): claude-cli reports a clipped answer as length and a refusal as content-filter (#6260)
time-attacka43be781e46d
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex 1ab4567fe9..ac6cbe662d 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -36,7 +36,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ai/key-warnings.ts` — #5137 print seam with one replaceable sink and two once-per-process latches: `warnShadowedProviderKeys` (called from `src/cli.ts` for every command except `gbrain hook`; `gbrain serve` starts through the same path) names the variable, the config key, that env is in effect, and both fixes (remove the variable from that process's environment and restart it, or `gbrain config unset <key>`, which also silences it); `reportEmbeddingAuthFailure` prints `embedding_auth_failed` (catalogue entry) on the first embedding 401/403, naming the key source in effect and the fix plus `gbrain embed --stale`. Never prints a key or fragment. Doctor `embedding_key_source` (`src/commands/doctor/checks/embedding-health.ts`, engine-free filesystem-lane entry `embeddingKeySourceEntry`) reports the same shadows and the embedding key's source, and says it sees only the environment doctor runs in.- `src/core/ai/key-redact.ts` — `redactProviderKeys(text, env)`: scrubs every `*_API_KEY`/`*_TOKEN`/`*_SECRET`/`*_PASSWORD` value in the gateway env, masked echoes (`sk-...****abcd`) and 8+ character key fragments from upstream error text. The gateway passes it to `normalizeAIError` (which also scrubs the wrapped error's cause chain in place, keeping status and headers for `.cause` walkers) on embed, multimodal, expand and chat errors, and applies it to multimodal response bodies.-- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter that shells out to the locally-installed `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-instructed JSON emission: 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 does not ask for an id, and a stray `id` field is deliberately 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`). doStream not implemented; callers (gateway.toolLoop) use 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 NoObjectGeneratedError on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`.+- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter that shells out to the locally-installed `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-instructed JSON emission: 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 does not ask for an id, and a stray `id` field is deliberately 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`). doStream not implemented; callers (gateway.toolLoop) use 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 NoObjectGeneratedError 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 a clipped answer (`test/claude-cli-stop-reason.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-language-model.ts b/src/core/ai/providers/claude-cli-language-model.tsindex c69b99c6ac..7068f36c4a 100644--- a/src/core/ai/providers/claude-cli-language-model.ts+++ b/src/core/ai/providers/claude-cli-language-model.ts@@ -622,6 +622,19 @@ function normalizeModel(model: string): string {return idx >= 0 ? model.slice(idx + 1) : model;}+/**+ * #6260: the CLI's own `stop_reason` decides the finish reason, so a response+ * cut off at the output cap reads as `length` and a refusal as+ * `content-filter`; callers that refuse to commit a clipped answer can only+ * see it this way. Tool calls parsed from the text finish as `tool-calls`+ * unless the answer was cut off. A missing or unknown reason stays `stop`.+ */+export function claudeCliFinishReason(stopReason: string | null | undefined, hasToolCalls: boolean): 'stop' | 'length' | 'content-filter' | 'tool-calls' {+ if (stopReason === 'max_tokens') return 'length';+ if (stopReason === 'refusal') return 'content-filter';+ return hasToolCalls ? 'tool-calls' : 'stop';+}+export class ClaudeCliLanguageModel implements LanguageModelV2 {readonly specificationVersion = 'v2' as const;readonly provider = 'claude-cli';@@ -666,7 +679,7 @@ export class ClaudeCliLanguageModel implements LanguageModelV2 {content.push({ type: 'text', text: result.result ?? '' });}- const finishReason = toolCalls.length > 0 ? 'tool-calls' as const : 'stop' as const;+ const finishReason = claudeCliFinishReason(result.stop_reason, toolCalls.length > 0);const inputTokens = result.usage?.input_tokens;const outputTokens = result.usage?.output_tokens;const totalTokens = (inputTokens ?? 0) + (outputTokens ?? 0);diff --git a/test/claude-cli-stop-reason.test.ts b/test/claude-cli-stop-reason.test.tsnew file mode 100644index 0000000000..99227382ec--- /dev/null+++ b/test/claude-cli-stop-reason.test.ts@@ -0,0 +1,57 @@+/**+ * claude-cli provider: the CLI's `stop_reason` reaches the AI SDK finish+ * reason (#6260). Before, every answer finished `stop`, so a response cut+ * off at the output cap looked complete to callers that refuse to commit a+ * clipped answer (extract_atoms, synthesize_concepts).+ *+ * A POSIX shell stub at GBRAIN_CLAUDE_CLI_BIN emits a scripted JSON envelope.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { chmodSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import type { LanguageModelV2CallOptions } from '@ai-sdk/provider';+import { withEnv } from './helpers/with-env.ts';++const stubDir = join(tmpdir(), `claude-cli-stop-reason-${process.pid}`);+const stubBin = join(stubDir, 'claude');+const responsePath = join(stubDir, 'response.json');++beforeAll(() => {+ mkdirSync(stubDir, { recursive: true });+ writeFileSync(stubBin, ['#!/bin/sh', 'cat > /dev/null', `cat "${responsePath}"`].join('\n'));+ chmodSync(stubBin, 0o755);+});+afterAll(() => rmSync(stubDir, { recursive: true, force: true }));++async function finishFor(stopReason: string | null, result = 'partial answer'): Promise<string> {+ writeFileSync(responsePath, JSON.stringify({+ type: 'result', subtype: 'success', is_error: false, result, stop_reason: stopReason,+ session_id: 's', num_turns: 1, usage: { input_tokens: 1, output_tokens: 1 },+ }));+ return withEnv({ GBRAIN_CLAUDE_CLI_BIN: stubBin }, async () => {+ const { ClaudeCliLanguageModel } = await import('../src/core/ai/providers/claude-cli-language-model.ts');+ const out = await new ClaudeCliLanguageModel('claude-sonnet-4-6').doGenerate({+ prompt: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }],+ } as LanguageModelV2CallOptions);+ return out.finishReason;+ });+}++describe('claude-cli finish reason follows the CLI stop_reason (#6260)', () => {+ test('max_tokens finishes as length', async () => {+ expect(await finishFor('max_tokens')).toBe('length');+ });+ test('refusal finishes as content-filter', async () => {+ expect(await finishFor('refusal')).toBe('content-filter');+ });+ test('end_turn and a missing stop_reason still finish as stop', async () => {+ expect(await finishFor('end_turn')).toBe('stop');+ expect(await finishFor(null)).toBe('stop');+ });+ test('a parsed tool call finishes as tool-calls unless the answer was cut off', async () => {+ const call = '<use_tools>\n[{"id": "t1", "name": "search", "input": {"q": "x"}}]\n</use_tools>';+ expect(await finishFor('end_turn', call)).toBe('tool-calls');+ expect(await finishFor('max_tokens', call)).toBe('length');+ });+});