Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(claude-cli): child processes run with Claude Code hooks disabled (#5820)
garrytanede123255924
diff --git a/docs/ai-providers/claude-cli.md b/docs/ai-providers/claude-cli.mdindex acf10ac333..1e7d254b1d 100644--- a/docs/ai-providers/claude-cli.md+++ b/docs/ai-providers/claude-cli.md@@ -25,7 +25,10 @@ embeddings the same way the `anthropic` recipe's docs recommend.## Setup-1. Install Claude Code (the `claude` CLI) and run `claude` once to log in.+1. Install Claude Code 2.0.60 or newer (the `claude` CLI) and run `claude`+ once to log in. Older CLIs reject the provider's flags, and the call fails+ with `claude CLI 2.0.60 or newer required (found <version>); upgrade+ Claude Code`.If the binary is not on `PATH`, point the gateway at it explicitly:```bash@@ -54,7 +57,8 @@ recipe — it has no base URL, only a subprocess binary path## What actually happens on a callEach `doGenerate` call spawns `claude --print --output-format json --model-<id> --disable-slash-commands --tools '' --strict-mcp-config` as a+<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`mkdirSync(..., { recursive: true })` if missing — code doesn't otherwise@@ -67,6 +71,18 @@ stdin:every call would boot the user's configured MCP servers — includinggbrain's own MCP, which would recurse and contend for the PGLitesingle-writer lock.+- `--settings '{"disableAllHooks":true}'` stops the child from running your+ Claude Code hooks (user and project settings). Without it, gbrain's own+ Stop hook banked every claude-cli call's prompt as one of your+ conversations, and extracting facts from it spawned another call (#5820).+ Your login is unaffected: credentials are not settings. Hooks from a+ managed policy file (`/etc/claude-code/managed-settings.json` on Linux)+ are a different case. Claude Code 2.1.287 still runs them, because policy+ wins over `--settings`; 2.0.60 suppressed them too (probed with a managed+ SessionStart and Stop hook on Linux). A managed policy that installs+ gbrain's own hooks therefore still fires inside claude-cli calls; gbrain's+ Stop hook, the serve-side harvest and the sweep all skip those+ self-captures, so nothing is extracted from them.- The subprocess env is a copy of gbrain's own process env with thecloud-auth routing variables scrubbed before spawn: the three direct-APIkeys (`ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_BASE_URL`)@@ -150,6 +166,7 @@ investigating directly (run the same model via `gbrain models doctor| `claude-cli spawn failed: ...` / stdin write failure | `spawn()`'s `error` event or a failed `stdin.write` — commonly means the `claude` binary was not found on `PATH` | Install Claude Code, or set `GBRAIN_CLAUDE_CLI_BIN` to the binary's path || `claude-cli API error <status>: <message>` | The CLI reported an API failure in its result envelope (`is_error: true` with `api_error_status`, e.g. 429 on a spend/rate limit) — surfaced whether the subprocess exited non-zero or zero. The error is a `ClaudeCliProcessError` carrying `apiErrorStatus` + `exitCode` for programmatic handling | Read the message — it's the CLI's own human-readable explanation (e.g. a spend-limit notice with the fix URL) || `claude-cli reported error: <message>` | Same envelope-reported failure (`is_error: true`) but without an `api_error_status` field | As above — the message is the CLI's own explanation |+| `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 || `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) || `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 || `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 |diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 1073797c11..88d9239a25 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -59,6 +59,7 @@ test/check-update.test.ts check-update CLI 3 source-surface-helpertest/child-worker-supervisor.test.ts issue #1801 — restartCurrentChild + killChild liveness fix 3 readFileSynctest/chronicle-extract.test.ts runChronicleExtract 9 readFileSynctest/ci-local-empty-mounts.test.ts (file-level) 2 readFileSync+test/claude-cli-recipe.test.ts claude-cli LanguageModel — CLI too old for the provider flags 2 readFileSynctest/claude-cli-recipe.test.ts claude-cli LanguageModel — abort + error envelopes 13 readFileSynctest/claude-cli-recipe.test.ts claude-cli LanguageModel — context isolation 2 readFileSynctest/claude-cli-recipe.test.ts claude-cli LanguageModel — text-only round trip 4 readFileSyncdiff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.tsindex 4510cf346e..c69b99c6ac 100644--- a/src/core/ai/providers/claude-cli-language-model.ts+++ b/src/core/ai/providers/claude-cli-language-model.ts@@ -34,7 +34,7 @@* (gateway.toolLoop primarily) use doGenerate.*/import { randomUUIDv7 } from 'bun';-import { spawn } from 'node:child_process';+import { spawn, spawnSync } from 'node:child_process';import { mkdirSync } from 'node:fs';import {claudeCliConfigDir,@@ -306,6 +306,26 @@ function renderPrompt(prompt: LanguageModelV2Prompt): { systemText: string; userreturn { systemText: systemParts.join('\n'), userPrompt: convo.join('\n\n') };}+/** Oldest claude CLI that accepts every flag `runClaude` passes (probed:+ * 2.0.59 rejects `--disable-slash-commands`, 2.0.60 accepts the full argv). */+export const MIN_CLAUDE_CLI_VERSION = '2.0.60';++/** The CLI's argument parser rejected a flag (`error: unknown option '--x'`). */+export function isUnknownOptionError(stderr: string): boolean {+ return /\bunknown option\b/i.test(stderr);+}++export function oldClaudeCliMessage(version: string | null): string {+ return `claude CLI ${MIN_CLAUDE_CLI_VERSION} or newer required (found ${version ?? 'an unknown version'}); upgrade Claude Code`;+}++/** `claude --version`'s version number, or null. Only called after a failed+ * run, so the extra spawn never sits on the success path. */+function claudeCliVersion(env: NodeJS.ProcessEnv): string | null {+ const r = spawnSync(claudeBin(), ['--version'], { encoding: 'utf8', timeout: 5_000, env });+ return /\d+\.\d+\.\d+/.exec(typeof r.stdout === 'string' ? r.stdout : '')?.[0] ?? null;+}+/*** Spawn `claude --print` with the contamination-suppression flags and return* the parsed `--output-format json` envelope. Aborts propagate to SIGTERM on@@ -331,6 +351,12 @@ function runClaude(// contention). Verified against claude CLI 2.1.145 --help.'--tools', '','--strict-mcp-config',+ // #5820: the child must not run the user's Claude Code hooks — gbrain's+ // own Stop hook would bank this call's prompt as a "conversation" and+ // extracting it spawns another call. Unlike --bare this keeps the+ // subscription login (credentials are not settings). Accepted by every+ // CLI that accepts the flags above.+ '--settings', '{"disableAllHooks":true}',];if (systemPrompt) {args.push('--system-prompt', systemPrompt);@@ -411,8 +437,11 @@ function runClaude(// model/page-derived text, and classifyGlobalLlmError's phrase// regexes only scan text before the marker (an auth-looking essay in// stdout must never read as a whole-run auth outage).+ const headline = isUnknownOptionError(stderr)+ ? oldClaudeCliMessage(claudeCliVersion(env))+ : `claude-cli exited ${code}`;reject(new ClaudeCliProcessError(- `claude-cli exited ${code}\n--- raw ---\n${stderr.trim() || stdout.trim()}`,+ `${headline}\n--- raw ---\n${stderr.trim() || stdout.trim()}`,{ exitCode: code ?? undefined },));return;diff --git a/test/claude-cli-recipe.test.ts b/test/claude-cli-recipe.test.tsindex ca50fddffc..a61cfa6943 100644--- a/test/claude-cli-recipe.test.ts+++ b/test/claude-cli-recipe.test.ts@@ -766,6 +766,9 @@ describe('claude-cli LanguageModel — context isolation', () => {// Agent-isolation hardening: no built-in tools, no inherited MCP servers.expect(argv).toContain('--tools');expect(argv).toContain('--strict-mcp-config');+ // #5820: user/project hooks never run in the child (gbrain's own Stop+ // hook would bank this call as a conversation).+ expect(argv[argv.indexOf('--settings') + 1]).toBe('{"disableAllHooks":true}');expect(argv).toContain('--system-prompt');expect(argv).toContain('You are gbrain subagent.');expect(cwd).toMatch(/gbrain-claude-cli-cwd-\d+$/);@@ -1160,3 +1163,46 @@ describe('claude-cli LanguageModel — abort + error envelopes', () => {await expect(model.doStream()).rejects.toThrow(/does not support streaming/);});});++describe('claude-cli LanguageModel — CLI too old for the provider flags', () => {+ const fixture = (v: string) => readFileSync(join(import.meta.dir, 'fixtures', 'claude-cli-stderr', `unknown-option-${v}.stderr`), 'utf8');++ test('unknown-option detection matches stderr captured from two real CLI versions', async () => {+ const { isUnknownOptionError } = await import('../src/core/ai/providers/claude-cli-language-model.ts');+ expect(isUnknownOptionError(fixture('1.0.30'))).toBe(true);+ expect(isUnknownOptionError(fixture('2.0.59'))).toBe(true);+ expect(isUnknownOptionError('API Error: 500 {"type":"error","error":{"type":"api_error"}}')).toBe(false);+ });++ test('an old CLI fails with the upgrade message naming the probed minimum and the installed version', async () => {+ await withStubEnv(async () => {+ const oldStub = [+ '#!/bin/sh',+ 'if [ "$1" = "--version" ]; then echo "2.0.59 (Claude Code)"; exit 0; fi',+ 'cat > /dev/null',+ `cat "${join(import.meta.dir, 'fixtures', 'claude-cli-stderr', 'unknown-option-2.0.59.stderr')}" >&2`,+ 'exit 1',+ ].join('\n');+ writeFileSync(stubBin, oldStub);+ chmodSync(stubBin, 0o755);+ try {+ const { ClaudeCliLanguageModel, ClaudeCliProcessError, MIN_CLAUDE_CLI_VERSION } = await import('../src/core/ai/providers/claude-cli-language-model.ts');+ expect(MIN_CLAUDE_CLI_VERSION).toBe('2.0.60');+ const model = new ClaudeCliLanguageModel('claude-sonnet-4-6');+ let caught: unknown;+ try {+ await model.doGenerate({ prompt: [userMessage('x')] } as LanguageModelV2CallOptions);+ } catch (e) {+ caught = e;+ }+ expect(caught).toBeInstanceOf(ClaudeCliProcessError);+ const message = (caught as Error).message;+ expect(message.split('\n--- raw ---\n')[0]).toBe('claude CLI 2.0.60 or newer required (found 2.0.59); upgrade Claude Code');+ expect(message).toContain("unknown option '--disable-slash-commands'");+ } finally {+ writeFileSync(stubBin, ['#!/bin/sh', 'cat > /dev/null', `cat "${stubResponsePath}"`].join('\n'));+ chmodSync(stubBin, 0o755);+ }+ });+ });+});diff --git a/test/fixtures/claude-cli-stderr/unknown-option-1.0.30.stderr b/test/fixtures/claude-cli-stderr/unknown-option-1.0.30.stderrnew file mode 100644index 0000000000..37e157e777--- /dev/null+++ b/test/fixtures/claude-cli-stderr/unknown-option-1.0.30.stderr@@ -0,0 +1 @@+error: unknown option '--disable-slash-commands'diff --git a/test/fixtures/claude-cli-stderr/unknown-option-2.0.59.stderr b/test/fixtures/claude-cli-stderr/unknown-option-2.0.59.stderrnew file mode 100644index 0000000000..37e157e777--- /dev/null+++ b/test/fixtures/claude-cli-stderr/unknown-option-2.0.59.stderr@@ -0,0 +1 @@+error: unknown option '--disable-slash-commands'