Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ai): claude-cli replays a prior tool call's arguments instead of [object Object] (#6236)
time-attack151613a7ee65
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex ac6cbe662d..1adafdc1bc 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`. `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-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`). `renderPrompt` replays an earlier tool call with its input as JSON (`[tool_use name({...})]`).- `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 7068f36c4a..6d17dd74f1 100644--- a/src/core/ai/providers/claude-cli-language-model.ts+++ b/src/core/ai/providers/claude-cli-language-model.ts@@ -278,7 +278,8 @@ function renderPrompt(prompt: LanguageModelV2Prompt): { systemText: string; userif (p.type === 'text') return p.text;if (p.type === 'reasoning') return ''; // dropped on replayif (p.type === 'tool-call') {- return `[tool_use ${p.toolName}(${p.input})]`;+ // #6236: the V2 prompt's input is an object; a template literal rendered it as [object Object].+ return `[tool_use ${p.toolName}(${typeof p.input === 'string' ? p.input : JSON.stringify(p.input)})]`;}if (p.type === 'tool-result') {const out = typeof p.output === 'string' ? p.output : JSON.stringify(p.output);diff --git a/test/claude-cli-stop-reason.test.ts b/test/claude-cli-stop-reason.test.tsindex 99227382ec..0d5520b2a3 100644--- a/test/claude-cli-stop-reason.test.ts+++ b/test/claude-cli-stop-reason.test.ts@@ -7,7 +7,7 @@* 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 { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { tmpdir } from 'node:os';import type { LanguageModelV2CallOptions } from '@ai-sdk/provider';@@ -16,10 +16,11 @@ 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');+const stdinPath = join(stubDir, 'stdin.txt');beforeAll(() => {mkdirSync(stubDir, { recursive: true });- writeFileSync(stubBin, ['#!/bin/sh', 'cat > /dev/null', `cat "${responsePath}"`].join('\n'));+ writeFileSync(stubBin, ['#!/bin/sh', `cat > "${stdinPath}"`, `cat "${responsePath}"`].join('\n'));chmodSync(stubBin, 0o755);});afterAll(() => rmSync(stubDir, { recursive: true, force: true }));@@ -55,3 +56,24 @@ describe('claude-cli finish reason follows the CLI stop_reason (#6260)', () => {expect(await finishFor('max_tokens', call)).toBe('length');});});++describe('claude-cli replays earlier tool calls with their arguments (#6236)', () => {+ test('a replayed tool call renders its input as JSON, not [object Object]', async () => {+ await finishFor('end_turn', 'ok');+ writeFileSync(responsePath, JSON.stringify({ type: 'result', subtype: 'success', is_error: false, result: 'ok', stop_reason: 'end_turn',+ session_id: 's', num_turns: 1, usage: { input_tokens: 1, output_tokens: 1 } }));+ await withEnv({ GBRAIN_CLAUDE_CLI_BIN: stubBin }, async () => {+ const { ClaudeCliLanguageModel } = await import('../src/core/ai/providers/claude-cli-language-model.ts');+ await new ClaudeCliLanguageModel('claude-sonnet-4-6').doGenerate({+ prompt: [+ { role: 'user', content: [{ type: 'text', text: 'find it' }] },+ { role: 'assistant', content: [{ type: 'tool-call', toolCallId: 't1', toolName: 'brain_get_page', input: { slug: 'wiki/personal/patterns/x' } }] },+ { role: 'tool', content: [{ type: 'tool-result', toolCallId: 't1', toolName: 'brain_get_page', output: { type: 'text', value: 'page' } }] },+ ],+ } as LanguageModelV2CallOptions);+ });+ const sent = readFileSync(stdinPath, 'utf8');+ expect(sent).toContain('[tool_use brain_get_page({"slug":"wiki/personal/patterns/x"})]');+ expect(sent).not.toContain('[object Object]');+ });+});