Skip to content

Commit 1b9d3ac

Browse files
VACInccursoragentPatrick-Erichsen
authored
fix(claude-cli): apply thinking and keep live sessions warm (#125528)
* fix(models): preserve CLI runtime thinking capabilities * fix(models): preserve configured thinking overrides * fix: keep Claude live CLI process warm across captured turns MCP delivery capture no longer kills the warm Claude process after every turn. Capture-key admission is fenced by grant activate/deactivate so prompt-cache continuity can survive across messages. Co-authored-by: Cursor <[email protected]> * fix(claude-cli): apply thinking levels * fix(claude-cli): materialize thinking capabilities * test(claude-cli): cover warm thinking budget reuse * test(models): restore prepared catalog contracts * fix(agents): restore catalog test boundaries * fix(agents): break prepared catalog import cycle * refactor(gateway): extract model-choice runtime resolution into public-projection module Keeps models-list-result.ts under the max-lines cap after the origin/main merge by moving resolveModelChoiceAgentRuntime next to the projection helpers it feeds. Claude-Session: https://claude.ai/code/session_01QXUQuDVataA5o16kxNnmoX * test(claude-cli): cover thinking cache reuse * test(claude-cli): cover captured live reuse * fix(claude-cli): rotate MCP grants across live turns * fix(anthropic): respect mandatory adaptive thinking * fix(claude-cli): restore warm MCP bearer * fix(anthropic): keep Mythos adaptive thinking * test(claude-cli): prove live MCP cache reuse * test(claude-cli): align live cache coverage * fix(claude-cli): reuse live sessions across MCP grant rotation * test(claude-cli): satisfy cache lane static gates * fix(claude-cli): preserve runtime thinking policy * fix(thinking): honor concrete runtime policy * fix(gateway): honor mandatory thinking in model list * refactor(auto-reply): extract prepared catalog merge * docs(cli-backend): document thinking execution input * refactor(auto-reply): extract catalog lookup helper * style(auto-reply): format catalog helper import * fix(claude-cli): stabilize live context budget * fix(auto-reply): type prepared context metadata --------- Co-authored-by: VACInc <[email protected]> Co-authored-by: Cursor <[email protected]> Co-authored-by: Patrick Erichsen <[email protected]>
1 parent 4b32275 commit 1b9d3ac

72 files changed

Lines changed: 2372 additions & 612 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/gateway/cli-backends.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ Under a restrictive policy, Claude asks OpenClaw over stdio before using one of
149149

150150
Claude Code can drive a Chrome browser through the [Claude in Chrome extension](https://code.claude.com/docs/en/chrome), including [1Password for Claude](/gateway/1password#browser-sign-in-with-1password-for-claude) credential autofill. The bundled backend does not enable it; register a [CLI backend plugin](/plugins/cli-backend-plugins) that appends `--chrome` to the launch args of a `claude-stream-json`-dialect backend. OpenClaw preserves a configured `--chrome` on normal runs and always forces `--no-chrome` on runs with a restricted tool policy, such as side questions. The Chrome window, the extension, and any 1Password approval prompts live on the gateway host, so someone must be at that machine to approve credential use.
151151

152-
The backend also maps OpenClaw `/think` levels to Claude Code's native `--effort` flag: `minimal`/`low` -> `low`, `medium` -> `medium`, and `high`/`xhigh`/`max` pass through directly. This keeps the supported Fable 5 effort levels the same for subscription-backed Claude CLI and API-key routes. `adaptive` removes configured `--effort` flags and supplies no replacement, so Claude Code resolves effective effort from its own environment, settings, and model defaults. Other CLI backends need their owning plugin to declare an equivalent argv mapper before `/think` affects the spawned CLI.
152+
The backend maps OpenClaw `/think` levels to Claude Code's native `--effort` flag: `minimal`/`low` -> `low`, `medium` -> `medium`, and `high`/`xhigh`/`max` pass through directly. For models that allow fixed thinking budgets, it also launches Claude Code with `MAX_THINKING_TOKENS`: `off=0`, `minimal=1024`, `low=2048`, `medium=8192`, `high`/`xhigh=16384`, and `max=32768`; positive fixed budgets disable adaptive thinking. Models that require adaptive thinking omit the fixed budget and continue to use `--effort`. `adaptive` removes configured effort flags and fixed-budget environment overrides, so Claude Code resolves effective thinking from its own environment, settings, and model defaults. Other CLI backends need their owning plugin to map the selected level before `/think` affects the spawned CLI.
153153

154154
Before OpenClaw can use `claude-cli`, Claude Code itself must be logged in on the same host:
155155

‎docs/plugins/cli-backend-plugins.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,11 @@ because of its version string.
255255

256256
`prepareExecution(ctx)` receives `ctx.contextTokenBudget`, the effective token
257257
limit selected for the run. Backends that own native compaction can map that
258-
budget into their CLI-specific launch contract.
258+
budget into their CLI-specific launch contract. It also receives the optional
259+
effective `ctx.thinkingLevel`: `off`, `minimal`, `low`, `medium`, `high`,
260+
`xhigh`, `adaptive`, or `max`. Use that field when the selected level must be
261+
applied through launch environment or staged configuration; the same field is
262+
available to `resolveExecutionArgs(ctx)` for native CLI flags.
259263

260264
`runtimeArtifact` is plugin-owned. It is consulted
261265
only when a live inference turn mints or revalidates verified setup authority;

‎docs/plugins/sdk-overview.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -658,8 +658,11 @@ AI CLI backend such as `claude-cli` or `my-cli`.
658658
- Use `prepareExecution` for backend-owned launch environment or temporary
659659
auth/config bridges. Its `ctx.contextTokenBudget` is the effective token
660660
limit selected for the run, so native-compaction backends can align their
661-
own threshold without provider-specific core branches. It also receives the
662-
core-prepared `ctx.env` when backend staging must extend bundled MCP settings.
661+
own threshold without provider-specific core branches. Its optional
662+
`ctx.thinkingLevel` is the effective `off`, `minimal`, `low`, `medium`,
663+
`high`, `xhigh`, `adaptive`, or `max` selection for backends that apply the
664+
level through launch environment or staged configuration. It also receives
665+
the core-prepared `ctx.env` when backend staging must extend bundled MCP settings.
663666
- Backends that can disable all native tools for a specific run may declare
664667
`nativeToolMode: "selectable"`. Restricted calls pass an exact
665668
`ctx.toolAvailability.native` list plus canonical

‎docs/tools/thinking.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ title: "Thinking levels"
5959
## Application by agent
6060

6161
- **Embedded OpenClaw**: the resolved level is passed to the in-process OpenClaw agent runtime.
62-
- **Claude CLI backend**: concrete non-off levels are passed to Claude Code as `--effort` when using `claude-cli`; `adaptive` removes configured effort flags and delegates effective effort to Claude Code's environment, settings, and model defaults. See [CLI backends](/gateway/cli-backends).
62+
- **Claude CLI backend**: concrete levels are mapped to Claude Code `--effort`; models that allow fixed budgets also receive a matching `MAX_THINKING_TOKENS` launch value. `adaptive` removes both configured effort flags and fixed-budget overrides, delegating effective thinking to Claude Code's environment, settings, and model defaults. See [CLI backends](/gateway/cli-backends).
6363

6464
## Fast mode (/fast)
6565

‎extensions/anthropic/api.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
* Claude CLI helpers, and stream wrappers for config/runtime consumers.
44
*/
55
export { CLAUDE_CLI_BACKEND_ID, isClaudeCliProvider } from "./cli-shared.js";
6+
export { buildAnthropicCliBackend } from "./cli-backend.js";
67
export { buildAnthropicProvider } from "./register.runtime.js";
78
export {
89
createAnthropicBetaHeadersWrapper,

‎extensions/anthropic/cli-backend.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
normalizeClaudeBackendConfig,
2222
resolveClaudeCliAutoCompactEnv,
2323
resolveClaudeCliExecutionArgs,
24+
resolveClaudeCliThinkingEnv,
2425
} from "./cli-shared.js";
2526

2627
type ClaudeCliAuthCredential =
@@ -262,6 +263,7 @@ export function buildAnthropicCliBackend(
262263
const isolatedCompletion = credentialContext.isolatedCompletionPrompt !== undefined;
263264
const env = {
264265
...resolveClaudeCliAutoCompactEnv(context.contextTokenBudget),
266+
...resolveClaudeCliThinkingEnv(context.thinkingLevel, context.modelId),
265267
...authInput?.env,
266268
};
267269
return Object.keys(env).length > 0 || isolatedCompletion
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { describe, expect, it } from "vitest";
2+
import { buildAnthropicCliBackend } from "./cli-backend.js";
3+
import { resolveClaudeCliThinkingEnv } from "./cli-shared.js";
4+
5+
describe("Claude CLI execution environment", () => {
6+
it("preserves the prepared launch environment for the same context budget", () => {
7+
const backend = buildAnthropicCliBackend();
8+
9+
expect(
10+
backend.prepareExecution?.({
11+
workspaceDir: "/tmp/openclaw-claude-cli",
12+
provider: "claude-cli",
13+
modelId: "claude-opus-4-8",
14+
contextTokenBudget: 100_000,
15+
}),
16+
).toEqual({ env: { CLAUDE_CODE_AUTO_COMPACT_WINDOW: "100000" } });
17+
});
18+
19+
it.each([
20+
["high", { CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING: "1", MAX_THINKING_TOKENS: "16384" }],
21+
["off", { MAX_THINKING_TOKENS: "0" }],
22+
["adaptive", undefined],
23+
] as const)("maps %s thinking to Claude Code's process environment", (level, expected) => {
24+
expect(resolveClaudeCliThinkingEnv(level, "claude-opus-4-8")).toEqual(expected);
25+
});
26+
27+
it.each(["off", "high", "max"] as const)(
28+
"leaves mandatory-adaptive Fable thinking %s to Claude Code effort args",
29+
(level) => {
30+
expect(resolveClaudeCliThinkingEnv(level, "claude-fable-5")).toBeUndefined();
31+
},
32+
);
33+
});

‎extensions/anthropic/cli-shared.test.ts‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -56,19 +56,6 @@ describe("Claude CLI adapter equivalence", () => {
5656
expect(backend.config.clearEnv).toEqual([...CLAUDE_CLI_CLEAR_ENV]);
5757
});
5858

59-
it("preserves the prepared launch environment for the same context budget", () => {
60-
const backend = buildAnthropicCliBackend();
61-
62-
expect(
63-
backend.prepareExecution?.({
64-
workspaceDir: "/tmp/openclaw-claude-cli",
65-
provider: "claude-cli",
66-
modelId: "claude-opus-4-8",
67-
contextTokenBudget: 100_000,
68-
}),
69-
).toEqual({ env: { CLAUDE_CODE_AUTO_COMPACT_WINDOW: "100000" } });
70-
});
71-
7259
it("privately acknowledges isolated completion preparation", () => {
7360
const backend = buildAnthropicCliBackend();
7461
const prepared = backend.prepareExecution?.({
@@ -500,6 +487,19 @@ describe("resolveClaudeCliExecutionArgs", () => {
500487
},
501488
);
502489

490+
it("defensively maps impossible Fable off requests to the lowest Claude effort", () => {
491+
expect(
492+
resolveClaudeCliExecutionArgs({
493+
workspaceDir: "/tmp",
494+
provider: "claude-cli",
495+
modelId: "claude-fable-5",
496+
thinkingLevel: "off",
497+
useResume: false,
498+
baseArgs: ["-p", "--effort", "high"],
499+
}),
500+
).toEqual(["-p", "--effort", "low"]);
501+
});
502+
503503
it.each([
504504
["minimal", "low"],
505505
["low", "low"],

‎extensions/anthropic/cli-shared.ts‎

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import type {
88
CliBackendResolveExecutionArgsContext,
99
} from "openclaw/plugin-sdk/cli-backend";
1010
import { resolveExecModePolicy } from "openclaw/plugin-sdk/exec-approvals-runtime";
11+
import { requiresClaudeMandatoryAdaptiveThinking } from "openclaw/plugin-sdk/provider-model-shared";
1112
import { normalizeOptionalLowercaseString } from "openclaw/plugin-sdk/string-coerce-runtime";
1213
import { CLAUDE_CLI_BACKEND_ID } from "./cli-constants.js";
1314
export {
@@ -35,6 +36,9 @@ export const CLAUDE_CLI_CLEAR_ENV = [
3536
"CLAUDE_CONFIG_DIR",
3637
// Re-injected per run from OpenClaw's canonical context budget.
3738
"CLAUDE_CODE_AUTO_COMPACT_WINDOW",
39+
"CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING",
40+
// Re-injected per run from OpenClaw's effective thinking level.
41+
"MAX_THINKING_TOKENS",
3842
"CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR",
3943
"CLAUDE_CODE_ENTRYPOINT",
4044
"CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
@@ -137,6 +141,44 @@ export function resolveClaudeCliAutoCompactEnv(
137141
};
138142
}
139143

144+
/**
145+
* Map OpenClaw's fixed thinking levels to Claude Code's per-process budget.
146+
*
147+
* Claude Code 2.x reads MAX_THINKING_TOKENS for print-mode runs and a positive
148+
* integer requests that fixed token budget. Mandatory-adaptive models ignore
149+
* that projection, so they retain adaptive thinking and use --effort instead.
150+
* These fixed budgets match OpenClaw's canonical provider defaults in
151+
* packages/ai/src/providers/simple-options.ts.
152+
*/
153+
export function resolveClaudeCliThinkingEnv(
154+
thinkingLevel: CliBackendResolveExecutionArgsContext["thinkingLevel"],
155+
modelId?: string,
156+
): Record<string, string> | undefined {
157+
if (requiresClaudeMandatoryAdaptiveThinking({ id: modelId })) {
158+
return undefined;
159+
}
160+
switch (thinkingLevel) {
161+
case "off":
162+
return { MAX_THINKING_TOKENS: "0" };
163+
case "minimal":
164+
return { CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING: "1", MAX_THINKING_TOKENS: "1024" };
165+
case "low":
166+
return { CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING: "1", MAX_THINKING_TOKENS: "2048" };
167+
case "medium":
168+
return { CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING: "1", MAX_THINKING_TOKENS: "8192" };
169+
case "high":
170+
case "xhigh":
171+
return { CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING: "1", MAX_THINKING_TOKENS: "16384" };
172+
case "max":
173+
return { CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING: "1", MAX_THINKING_TOKENS: "32768" };
174+
case "adaptive":
175+
case undefined:
176+
return undefined;
177+
default:
178+
return thinkingLevel satisfies never;
179+
}
180+
}
181+
140182
/** Return whether the startup-probed Claude Code build supports the cache-control flag. */
141183
export function supportsClaudeDynamicSystemPromptSections(
142184
versionOutput: string | undefined,
@@ -279,8 +321,15 @@ function normalizeClaudeSettingSourcesArgs(args?: string[]): string[] | undefine
279321
}
280322

281323
/** Resolve whether a run preserves, removes, or sets a Claude CLI effort override. */
282-
function resolveClaudeCliEffortArgAction(thinkingLevel?: string | null): ClaudeCliEffortArgAction {
324+
function resolveClaudeCliEffortArgAction(
325+
thinkingLevel?: string | null,
326+
modelId?: string,
327+
): ClaudeCliEffortArgAction {
283328
switch (normalizeOptionalLowercaseString(thinkingLevel)) {
329+
case "off":
330+
return requiresClaudeMandatoryAdaptiveThinking({ id: modelId })
331+
? { mode: "set", effort: "low" }
332+
: { mode: "preserve" };
284333
case "minimal":
285334
case "low":
286335
return { mode: "set", effort: "low" };
@@ -499,7 +548,7 @@ export function resolveClaudeCliExecutionArgs(
499548
if (context.executionMode === "side-question") {
500549
return resolveClaudeCliSideQuestionExecutionArgs(context.baseArgs);
501550
}
502-
const action = resolveClaudeCliEffortArgAction(context.thinkingLevel);
551+
const action = resolveClaudeCliEffortArgAction(context.thinkingLevel, context.modelId);
503552
switch (action.mode) {
504553
case "preserve":
505554
return [...context.baseArgs];

‎extensions/anthropic/index.test.ts‎

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -658,7 +658,7 @@ describe("anthropic provider replay hooks", () => {
658658
name: "resolves Claude Fable 5 with its always-adaptive model contract",
659659
modelId: "claude-fable-5",
660660
cost: { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 },
661-
thinkingLevelMap: { off: "low", minimal: "low", xhigh: "xhigh", max: "max" },
661+
thinkingLevelMap: { minimal: "low", xhigh: "xhigh", max: "max" },
662662
checksMedia: true,
663663
checksCliPolicy: true,
664664
},
@@ -707,16 +707,11 @@ describe("anthropic provider replay hooks", () => {
707707
provider: "anthropic",
708708
modelId,
709709
} as never);
710-
expect(levelIds(profile)).toStrictEqual([
711-
"off",
712-
"minimal",
713-
"low",
714-
"medium",
715-
"high",
716-
"xhigh",
717-
"adaptive",
718-
"max",
719-
]);
710+
expect(levelIds(profile)).toStrictEqual(
711+
modelId === "claude-fable-5"
712+
? ["minimal", "low", "medium", "high", "xhigh", "adaptive", "max"]
713+
: ["off", "minimal", "low", "medium", "high", "xhigh", "adaptive", "max"],
714+
);
720715
expect(requireRecord(profile, `${modelId} thinking profile`).defaultLevel).toBe("high");
721716
const normalized = provider.normalizeResolvedModel?.({
722717
provider: "anthropic",
@@ -866,7 +861,6 @@ describe("anthropic provider replay hooks", () => {
866861
contextTokens: 1_000_000,
867862
maxTokens: 128_000,
868863
thinkingLevelMap: {
869-
off: "low",
870864
minimal: "low",
871865
xhigh: "xhigh",
872866
max: "max",
@@ -875,12 +869,12 @@ describe("anthropic provider replay hooks", () => {
875869
expect(requireRecord(resolved, "Mythos model").mediaInput).toEqual({
876870
image: { maxSidePx: 2576, preferredSidePx: 2576, tokenMode: "provider" },
877871
});
878-
expect(
879-
provider.resolveThinkingProfile?.({
880-
provider: "anthropic",
881-
modelId: "claude-mythos-5",
882-
} as never)?.defaultLevel,
883-
).toBe("high");
872+
const thinkingProfile = provider.resolveThinkingProfile?.({
873+
provider: "anthropic",
874+
modelId: "claude-mythos-5",
875+
} as never);
876+
expect(thinkingProfile?.defaultLevel).toBe("high");
877+
expect(levelIds(thinkingProfile)).not.toContain("off");
884878
expect(
885879
provider.resolveDynamicModel?.({
886880
provider: "claude-cli",

0 commit comments

Comments
 (0)