Skip to content

Commit 0015076

Browse files
Merge remote-tracking branch 'origin/main' into fix/live-updater-command-timeouts
2 parents d0d7ff4 + 8393b37 commit 0015076

44 files changed

Lines changed: 1172 additions & 406 deletions

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: 37 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,29 @@ The `openclaw agent` command also has its own request deadline. Its 600-second f
116116

117117
### Claude CLI specifics
118118

119+
OpenClaw's managed Claude stdio sessions require the `msg_lifecycle_v1`
120+
capability, first observed in the published Claude Code 2.1.206 build. At
121+
runtime OpenClaw does not trust the version string alone: it waits for
122+
Claude Code's `system/init` record to advertise `msg_lifecycle_v1`, then accepts
123+
assistant, tool, and result records only after the matching input lifecycle has
124+
started. Unknown capabilities are ignored. A CLI that omits the required
125+
capability fails immediately with `claude update` and gateway-restart guidance
126+
instead of waiting for the no-output watchdog.
127+
128+
Setup and Doctor treat 2.1.206 as advisory, so a lower-version compatible
129+
backport or wrapper remains selectable and is verified by the runtime gate.
130+
131+
```bash
132+
claude --version
133+
claude update
134+
# Restart the OpenClaw gateway after updating.
135+
```
136+
137+
Claude Code's public CLI documentation covers stream-json mode and updates but
138+
does not currently document the lifecycle event itself. OpenClaw therefore
139+
feature-detects the advertised capability; 2.1.206 is the first published
140+
Claude Code build observed to provide it.
141+
119142
The bundled `claude-cli` backend prefers Claude Code's native skill resolver. When the current skills snapshot has at least one selected skill with a materialized path, OpenClaw passes a temporary Claude Code plugin via `--plugin-dir` and omits the duplicate OpenClaw skills catalog from the appended system prompt. Without a materialized plugin skill, OpenClaw keeps the prompt catalog as a fallback. Skill env/API key overrides still apply to the child process environment for the run.
120143

121144
Claude CLI has its own noninteractive permission mode; OpenClaw maps that to the existing exec policy instead of adding Claude-specific config. For OpenClaw-managed Claude live sessions, the effective exec policy is authoritative: YOLO (`tools.exec.mode: "full"`) normally launches Claude with `--permission-mode bypassPermissions`, while a restrictive policy launches it with `--permission-mode default`. Root-run gateways also use `default` because Claude Code rejects bypass mode for root. Per-agent `agents.entries.*.tools.exec` settings override the global `tools.exec` for that agent. The Anthropic plugin normalizes Claude's permission flags to match the effective policy and host restriction.
@@ -202,19 +225,20 @@ Anthropic owns `claude-cli` and Google owns `google-gemini-cli`. OpenAI Codex ag
202225

203226
The bundled Anthropic plugin registers for `claude-cli`:
204227

205-
| Key | Value |
206-
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
207-
| `command` | `claude` |
208-
| `args` | `-p --output-format stream-json --include-partial-messages --verbose --setting-sources user --allowedTools mcp__openclaw__* --disallowedTools ScheduleWakeup,CronCreate,Bash(run_in_background:true),Monitor` |
209-
| `output` | `jsonl` |
210-
| `input` | `stdin` |
211-
| `modelArg` | `--model` |
212-
| `sessionArgs` | `["--session-id", "{sessionId}"]` |
213-
| `sessionMode` | `always` |
214-
| `imageArg` | `@` |
215-
| `imagePathScope` | `workspace` |
216-
| `systemPromptFileArg` | `--append-system-prompt-file` |
217-
| `systemPromptMode` | `append` |
228+
| Key | Value |
229+
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
230+
| `command` | `claude` |
231+
| `args` | `-p --output-format stream-json --include-partial-messages --verbose --setting-sources user --allowedTools mcp__openclaw__* --disallowedTools ScheduleWakeup,CronCreate,Bash(run_in_background:true),Monitor` |
232+
| `output` | `jsonl` |
233+
| `input` | `stdin` |
234+
| `modelArg` | `--model` |
235+
| `sessionArgs` | `["--session-id", "{sessionId}"]` |
236+
| `sessionMode` | `always` |
237+
| live-session requirement | `msg_lifecycle_v1` (first observed in Claude Code 2.1.206) |
238+
| `imageArg` | `@` |
239+
| `imagePathScope` | `workspace` |
240+
| `systemPromptFileArg` | `--append-system-prompt-file` |
241+
| `systemPromptMode` | `append` |
218242

219243
The bundled Google plugin registers for `google-gemini-cli`:
220244

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,10 +240,18 @@ only for behavior that really belongs to the backend.
240240
| `ownsNativeCompaction` | Backend owns its own compaction - OpenClaw defers |
241241
| `subscriptionAuthDispatch` | Opted-in embedded runs on subscription credentials execute via this backend |
242242
| `runtimeArtifact` | Bound a script launcher to its complete bundled package tree |
243+
| `liveSessionRequirement` | Require an init capability before trusting long-lived session output |
243244

244245
Keep these hooks provider-owned. Do not add CLI-specific branches to core when
245246
a backend hook can express the behavior.
246247

248+
`liveSessionRequirement` declares one exact capability that the CLI must
249+
advertise in its initialization record before OpenClaw trusts streamed output.
250+
It also supplies the first known compatible version, version-probe arguments,
251+
and update command used by setup and Doctor. Runtime support remains
252+
capability-based, so a compatible backport or wrapper is not rejected only
253+
because of its version string.
254+
247255
`prepareExecution(ctx)` receives `ctx.contextTokenBudget`, the effective token
248256
limit selected for the run. Backends that own native compaction can map that
249257
budget into their CLI-specific launch contract.

‎docs/providers/anthropic.md‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,11 +91,22 @@ OpenClaw release:
9191

9292
<Steps>
9393
<Step title="Ensure Claude CLI is installed and logged in">
94-
Verify with:
94+
OpenClaw's streamed session correlation requires the
95+
`msg_lifecycle_v1` capability. Claude Code 2.1.206 is the first
96+
published build known to advertise it. Verify the installed version:
9597

9698
```bash
9799
claude --version
98100
```
101+
102+
A lower-version compatible backport or wrapper remains selectable;
103+
OpenClaw verifies the capability at runtime. If the runtime rejects the
104+
installed build, update Claude Code and restart OpenClaw so the gateway
105+
launches the new binary:
106+
107+
```bash
108+
claude update
109+
```
99110
</Step>
100111
<Step title="Run onboarding">
101112
```bash
@@ -114,6 +125,8 @@ OpenClaw release:
114125

115126
<Note>
116127
Setup and runtime details for the Claude CLI backend are in [CLI Backends](/gateway/cli-backends).
128+
`openclaw doctor` also reports advisory guidance for an installed Claude
129+
Code version below the first-known compatible release.
117130
</Note>
118131

119132
<Warning>

‎extensions/anthropic/cli-backend.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,14 @@ export function buildAnthropicCliBackend(): CliBackendPlugin {
135135
entrypoint: "command",
136136
nativeExecutableNames: ["claude", "claude.exe"],
137137
},
138+
// Claude Code 2.1.206 first shipped per-input lifecycle correlation. The
139+
// runtime checks the advertised capability so backports and wrappers work.
140+
liveSessionRequirement: {
141+
capability: "msg_lifecycle_v1",
142+
minimumVersion: "2.1.206",
143+
versionArgs: ["--version"],
144+
updateCommand: "claude update",
145+
},
138146
bundleMcp: true,
139147
bundleMcpMode: "claude-config-file",
140148
nativeToolMode: "selectable",

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,12 @@ describe("normalizeClaudeBackendConfig", () => {
659659
entrypoint: "command",
660660
nativeExecutableNames: ["claude", "claude.exe"],
661661
});
662+
expect(backend.liveSessionRequirement).toEqual({
663+
capability: "msg_lifecycle_v1",
664+
minimumVersion: "2.1.206",
665+
versionArgs: ["--version"],
666+
updateCommand: "claude update",
667+
});
662668

663669
const normalized = normalizeConfig?.({
664670
...backend.config,

‎src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { expectDefined } from "@openclaw/normalization-core";
1010
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
1111
import { FILE_LOCK_TIMEOUT_ERROR_CODE, resetFileLockStateForTest } from "../../infra/file-lock.js";
1212
import { closeOpenClawAgentDatabasesForTest } from "../../state/openclaw-agent-db.js";
13-
import { captureEnv, setTestEnvValue } from "../../test-utils/env.js";
13+
import { captureEnv, deleteTestEnvValue, setTestEnvValue } from "../../test-utils/env.js";
1414
import { OAuthRefreshFailureError } from "./oauth-refresh-failure.js";
1515
import { buildRefreshContentionError } from "./oauth-refresh-lock-errors.js";
1616
import {
@@ -154,7 +154,7 @@ function requireOAuthContext(context: unknown): OAuthCredential {
154154
}
155155

156156
describe("resolveApiKeyForProfile openai refresh fallback", () => {
157-
const envSnapshot = captureEnv(OAUTH_AGENT_ENV_KEYS);
157+
const envSnapshot = captureEnv([...OAUTH_AGENT_ENV_KEYS, "OPENAI_API_KEY"]);
158158
let tempRoot = "";
159159
let agentDir = "";
160160
let caseIndex = 0;
@@ -186,6 +186,7 @@ describe("resolveApiKeyForProfile openai refresh fallback", () => {
186186
await fs.mkdir(agentDir, { recursive: true });
187187
setTestEnvValue("OPENCLAW_STATE_DIR", caseRoot);
188188
setTestEnvValue("OPENCLAW_AGENT_DIR", agentDir);
189+
deleteTestEnvValue("OPENAI_API_KEY");
189190
});
190191

191192
afterEach(async () => {

‎src/agents/bash-tools.exec-host-gateway.test.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -948,6 +948,7 @@ describe("processGatewayAllowlist", () => {
948948
fs.writeFileSync(shadowGit, "#!/bin/sh\nexit 0\n", { mode: 0o755 });
949949
try {
950950
const command = "git status";
951+
const canonicalShadowGit = fs.realpathSync(shadowGit);
951952
await configurePlanBackedCommand({
952953
command,
953954
env: { PATH: tempDir },
@@ -961,9 +962,9 @@ describe("processGatewayAllowlist", () => {
961962
});
962963

963964
expect(defaultExecAutoReviewerMock).toHaveBeenCalledWith(
964-
expect.objectContaining({ resolvedPath: shadowGit }),
965+
expect.objectContaining({ resolvedPath: canonicalShadowGit }),
965966
);
966-
expect(result).toEqual({ execCommandOverride: `${shadowGit} status` });
967+
expect(result).toEqual({ execCommandOverride: `${canonicalShadowGit} status` });
967968
} finally {
968969
fs.rmSync(tempDir, { recursive: true, force: true });
969970
}
@@ -1157,6 +1158,15 @@ describe("processGatewayAllowlist", () => {
11571158
if (!authorizationPlan.ok) {
11581159
throw new Error(authorizationPlan.reason);
11591160
}
1161+
const enforced = buildAuthorizedShellCommandFromPlan({
1162+
plan: authorizationPlan,
1163+
mode: "enforced",
1164+
segmentSatisfiedBy: ["safeBuiltins"],
1165+
});
1166+
expect(enforced.ok).toBe(true);
1167+
if (!enforced.ok) {
1168+
throw new Error(enforced.reason);
1169+
}
11601170
hasDurableExecApprovalMock.mockReturnValue(true);
11611171
hasExactCommandDurableExecApprovalMock.mockReturnValue(true);
11621172
evaluateShellAllowlistWithAuthorizationMock.mockReturnValue({
@@ -1183,7 +1193,7 @@ describe("processGatewayAllowlist", () => {
11831193
const result = await runGatewayAllowlist({ command });
11841194

11851195
expect(createAndRegisterDefaultExecApprovalRequestMock).not.toHaveBeenCalled();
1186-
expect(result).toEqual({ execCommandOverride: command });
1196+
expect(result).toEqual({ execCommandOverride: enforced.command });
11871197
expect(commitExecAuthorizationMock).toHaveBeenCalledWith(
11881198
expect.objectContaining({
11891199
authorization: expect.objectContaining({

‎src/agents/btw.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import { expectDefined } from "@openclaw/normalization-core";
44
import { MAX_TIMER_TIMEOUT_MS } from "@openclaw/normalization-core/number-coercion";
5-
import { beforeEach, describe, expect, it, vi } from "vitest";
5+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66
import type { SessionEntry } from "../config/sessions.js";
77
import {
88
looksLikeSecretSentinel,
@@ -571,6 +571,10 @@ function mockOpenAIPlatformProfile(): void {
571571
}
572572

573573
describe("runBtwSideQuestion", () => {
574+
afterEach(() => {
575+
vi.unstubAllEnvs();
576+
});
577+
574578
beforeEach(() => {
575579
streamSimpleMock.mockReset();
576580
readFileMock.mockReset();
@@ -1001,6 +1005,7 @@ describe("runBtwSideQuestion", () => {
10011005
});
10021006

10031007
it("lets native Codex bootstrap auth without a host profile", async () => {
1008+
vi.stubEnv("OPENAI_API_KEY", "");
10041009
const supports = vi.fn((ctx: Parameters<AgentHarness["supports"]>[0]) => {
10051010
if (ctx.modelProvider?.preparedAuth?.source !== "harness") {
10061011
return supportsPreparedOpenAIAuth(ctx);
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/** Shared version guidance for provider-owned CLI backend protocol requirements. */
2+
import { coerce as coerceSemver } from "semver";
3+
import { compareValidSemver } from "../infra/semver.js";
4+
import type { CliBackendLiveSessionRequirement } from "../plugins/cli-backend.types.js";
5+
6+
type CliBackendVersionGuidance =
7+
| { status: "at-or-above-known-floor"; version: string }
8+
| { status: "below-known-floor"; version: string }
9+
| { status: "unknown" };
10+
11+
/** Compare human CLI version output with the provider's first-known compatible release. */
12+
export function resolveCliBackendVersionGuidance(
13+
versionOutput: string | undefined,
14+
requirement: CliBackendLiveSessionRequirement,
15+
): CliBackendVersionGuidance {
16+
const parsed = versionOutput ? coerceSemver(versionOutput)?.version : undefined;
17+
if (!parsed) {
18+
return { status: "unknown" };
19+
}
20+
const comparison = compareValidSemver(parsed, requirement.minimumVersion);
21+
if (comparison === null) {
22+
return { status: "unknown" };
23+
}
24+
return {
25+
status: comparison < 0 ? "below-known-floor" : "at-or-above-known-floor",
26+
version: parsed,
27+
};
28+
}
29+
30+
/** Advisory guidance; runtime capability negotiation remains authoritative. */
31+
export function formatCliBackendVersionAdvisory(params: {
32+
label: string;
33+
requirement: CliBackendLiveSessionRequirement;
34+
version: string;
35+
}): string {
36+
return `${params.label} ${params.requirement.minimumVersion} is the first published build known to advertise ${params.requirement.capability}; found ${params.version}. OpenClaw verifies this capability at runtime. If this build is rejected, run \`${params.requirement.updateCommand}\`, restart OpenClaw, and retry.`;
37+
}

0 commit comments

Comments
 (0)