Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(claude-cli): turn thinking off for caps at or under the 1024-token floor (#6918)

time-attackdf2e1e82213e
diff --git a/docs/ai-providers/claude-cli.md b/docs/ai-providers/claude-cli.md
index e38420f134..63eeece1ba 100644
--- a/docs/ai-providers/claude-cli.md
+++ b/docs/ai-providers/claude-cli.md
@@ -94,6 +94,14 @@ stdin:
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.
+- A call with an output cap carries it as `CLAUDE_CODE_MAX_OUTPUT_TOKENS` in
+ both the `--settings` env and the child env. Claude Code thinks by default
+ on Claude 5 models, and the API needs a thinking budget of at least 1024
+ tokens below that cap, so a call capped at 1024 tokens or fewer (the
+ `models doctor` probe, query-intent and classification calls) also sets
+ `MAX_THINKING_TOKENS=0` in both places and reports
+ `providerMetadata['claude-cli'].thinking = 'disabled_below_floor'`. A larger
+ cap leaves thinking to the CLI.
- The subprocess env is a copy of gbrain's own process env with the
cloud-auth routing variables scrubbed before spawn: the three direct-API
keys (`ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_BASE_URL`)
diff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.ts
index b35ac3bbc7..2bf3f97587 100644
--- a/src/core/ai/providers/claude-cli-language-model.ts
+++ b/src/core/ai/providers/claude-cli-language-model.ts
@@ -362,6 +362,18 @@ function claudeCliVersion(env: NodeJS.ProcessEnv): string | null {
return /\d+\.\d+\.\d+/.exec(typeof r.stdout === 'string' ? r.stdout : '')?.[0] ?? null;
}
+/**
+ * #6918: Claude Code thinks by default on Claude 5 models, and the API needs
+ * thinking.budget_tokens of at least 1024 and below max_tokens, so a call
+ * capped at 1024 output tokens or fewer runs with thinking off.
+ */
+export const CLAUDE_THINKING_BUDGET_FLOOR = 1024;
+
+export function thinkingDisabledBelowFloor(maxOutputTokens: number | undefined): boolean {
+ return typeof maxOutputTokens === 'number' && Number.isInteger(maxOutputTokens) && maxOutputTokens > 0
+ && maxOutputTokens <= CLAUDE_THINKING_BUDGET_FLOOR;
+}
+
/**
* Spawn `claude --print` with the contamination-suppression flags and return
* the parsed `--output-format json` envelope. Aborts propagate to SIGTERM on
@@ -380,8 +392,9 @@ function runClaude(
const outputCap = typeof maxOutputTokens === 'number' && Number.isInteger(maxOutputTokens) && maxOutputTokens > 0
? String(maxOutputTokens)
: undefined;
+ const thinkingOff = thinkingDisabledBelowFloor(maxOutputTokens);
const settings = outputCap
- ? JSON.stringify({ disableAllHooks: true, env: { CLAUDE_CODE_MAX_OUTPUT_TOKENS: outputCap } })
+ ? JSON.stringify({ disableAllHooks: true, env: { CLAUDE_CODE_MAX_OUTPUT_TOKENS: outputCap, ...(thinkingOff ? { MAX_THINKING_TOKENS: '0' } : {}) } })
: '{"disableAllHooks":true}';
const args = [
'--print',
@@ -438,6 +451,7 @@ function runClaude(
const hermeticConfigDir = resolveHermeticConfigDir();
if (hermeticConfigDir) env.CLAUDE_CONFIG_DIR = hermeticConfigDir;
if (outputCap) env.CLAUDE_CODE_MAX_OUTPUT_TOKENS = outputCap;
+ if (thinkingOff) env.MAX_THINKING_TOKENS = '0';
const child = spawn(claudeBin(), args, {
stdio: ['pipe', 'pipe', 'pipe'],
cwd: ensureCleanCwd(),
@@ -740,13 +754,14 @@ export class ClaudeCliLanguageModel implements LanguageModelV2 {
// #6791: a continued answer is rebuilt from its segments, or refused
// before any tool block in its tail can be parsed and dispatched.
+ const thinking = thinkingDisabledBelowFloor(options.maxOutputTokens) ? { thinking: 'disabled_below_floor' } : null;
const answer = resolveClaudeCliAnswer(result, options.maxOutputTokens);
if (answer.kind === 'unproven') {
return {
content: [{ type: 'text', text: '' }],
finishReason: 'length',
usage,
- providerMetadata: continuationUnprovenMetadata(answer.reason),
+ providerMetadata: { 'claude-cli': { ...continuationUnprovenMetadata(answer.reason)['claude-cli'], ...thinking } },
warnings: [],
};
}
@@ -772,6 +787,7 @@ export class ClaudeCliLanguageModel implements LanguageModelV2 {
content,
finishReason: claudeCliFinishReason(result.stop_reason, toolCalls.length > 0),
usage,
+ ...(thinking ? { providerMetadata: { 'claude-cli': thinking } } : {}),
warnings: [],
};
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d35c767e75..a544b2f0f2 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -917,6 +917,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// #6796 (apply-migrations applied_pending_host_work).
{ since: '0.60.307.0', text: '`gbrain apply-migrations --list` now shows v0.53.0 as `applied_pending_host_work` instead of `applied` while its stored shared-skills report still names host work (a source\'s inventory, writer, projection or publication-policy stage, or a brain-level pending action), and no longer prints "All migrations up to date" for it; `--list --json` rows carry that status and an `applied_pending_host_work` array whose fix is the read-only `gbrain apply-migrations --migration 0.53.0 --dry-run --json` inventory. Scripts that match `applied` should accept both. `gbrain doctor` warns on `minions_migration` (`details.code: migration_host_work_pending`) until a later `gbrain apply-migrations --yes` re-check finds the work done. Unenrolled members (every new brain), sources that opted out and a declined migration are never reported.' },
{ since: '0.60.307.0', text: 'A queued job under a cost cap you set that calls a model with a registered price but no known context-token ceiling (OpenRouter models) now stops with `no_context_ceiling` instead of `no_pricing`. The message says the price is already known; the fix asks before rerunning without your cap (`--yes` in place of `--max-usd`), or asks for the model\'s context size for the brain-host operator. Under a default or derived cap the warning names the missing ceiling. Nothing else changed: no provider call is made either way.' },
+ { since: '0.60.307.0', text: 'A `claude-cli:` chat call capped at 1024 output tokens or fewer (the `gbrain models doctor` probe, query intent, fact classification, decisions, calibration and grading calls) now runs with Claude Code\'s thinking turned off (`MAX_THINKING_TOKENS=0`), because the API needs a thinking budget of at least 1024 tokens below the cap; those calls failed with a 400 before. The call reports `thinking: \'disabled_below_floor\'` in its claude-cli provider metadata. Calls with a larger cap are unchanged.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/test/claude-cli-thinking-floor-6918.test.ts b/test/claude-cli-thinking-floor-6918.test.ts
new file mode 100644
index 0000000000..d557e76171
--- /dev/null
+++ b/test/claude-cli-thinking-floor-6918.test.ts
@@ -0,0 +1,72 @@
+/**
+ * #6918: Claude Code thinks by default on Claude 5 models, and the API needs
+ * thinking.budget_tokens >= 1024 and below max_tokens, so every claude-cli call
+ * capped at 1024 output tokens or fewer (models doctor's 16-token probe,
+ * llm-intent, facts/classify, ai/decide, ...) failed with a 400. Such a call now
+ * sets MAX_THINKING_TOKENS=0 in both the inline --settings env and the child
+ * env, and reports `thinking: 'disabled_below_floor'` in its provider metadata.
+ * A larger cap, or no cap, leaves thinking to the CLI.
+ *
+ * A POSIX shell stub at GBRAIN_CLAUDE_CLI_BIN plays the CLI and records what it
+ * was handed; no live CLI or provider account is used.
+ */
+import { describe, expect, test } from 'bun:test';
+import { chmodSync, mkdtempSync, 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 { withEnv } from './helpers/with-env.ts';
+
+const SUCCESS = { type: 'result', subtype: 'success', is_error: false, result: 'OK', stop_reason: 'end_turn', session_id: 'synthetic-session', num_turns: 1, usage: { input_tokens: 5, output_tokens: 1 } };
+
+async function call(maxOutputTokens: number | undefined): Promise<{ env: string; settings: unknown; metadata: unknown; text: unknown }> {
+ const dir = mkdtempSync(join(tmpdir(), 'claude-thinking-floor-'));
+ const record = join(dir, 'record');
+ const response = join(dir, 'response.json');
+ writeFileSync(response, JSON.stringify(SUCCESS));
+ const bin = join(dir, 'claude');
+ writeFileSync(bin, [
+ '#!/bin/sh',
+ 'cat > /dev/null',
+ `printf 'env=%s\\n' "\${MAX_THINKING_TOKENS-unset}" > "${record}"`,
+ 'while [ $# -gt 0 ]; do',
+ ` if [ "$1" = "--settings" ]; then printf '%s\\n' "$2" >> "${record}"; fi`,
+ ' shift',
+ 'done',
+ `cat "${response}"`,
+ ].join('\n') + '\n');
+ chmodSync(bin, 0o755);
+ try {
+ const out = await withEnv({ GBRAIN_CLAUDE_CLI_BIN: bin, MAX_THINKING_TOKENS: undefined, CLAUDE_CODE_MAX_OUTPUT_TOKENS: undefined }, () =>
+ new ClaudeCliLanguageModel('claude-sonnet-5-5').doGenerate({
+ prompt: [{ role: 'user', content: [{ type: 'text', text: 'Reply OK' }] }],
+ ...(maxOutputTokens === undefined ? {} : { maxOutputTokens }),
+ } as LanguageModelV2CallOptions));
+ const [envLine, settingsLine] = readFileSync(record, 'utf8').trimEnd().split('\n');
+ return { env: envLine!.slice('env='.length), settings: JSON.parse(settingsLine!), metadata: out.providerMetadata, text: out.content };
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+describe('claude-cli turns thinking off under the 1024-token floor (#6918)', () => {
+ for (const cap of [16, 200, 1024]) {
+ test(`cap ${cap}: MAX_THINKING_TOKENS=0 in settings and child env, reported in metadata`, async () => {
+ const r = await call(cap);
+ expect(r.env).toBe('0');
+ expect(r.settings).toEqual({ disableAllHooks: true, env: { CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(cap), MAX_THINKING_TOKENS: '0' } });
+ expect(r.metadata).toEqual({ 'claude-cli': { thinking: 'disabled_below_floor' } });
+ expect(r.text).toEqual([{ type: 'text', text: 'OK' }]);
+ });
+ }
+
+ for (const cap of [1025, 4000, undefined]) {
+ test(`cap ${cap ?? 'none'}: thinking is left to the CLI`, async () => {
+ const r = await call(cap);
+ expect(r.env).toBe('unset');
+ expect(r.settings).toEqual(cap === undefined ? { disableAllHooks: true } : { disableAllHooks: true, env: { CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(cap) } });
+ expect(r.metadata).toBeUndefined();
+ });
+ }
+});