Skip to content

Commit 12d0fd2

Browse files
authored
refactor(anthropic): replace handwritten Claude sessions with Agent SDK (#128131)
* refactor(anthropic): explore official Claude Agent SDK runtime * refactor(anthropic): replace handwritten Claude sessions with SDK * refactor(anthropic): collapse SDK live-session ownership * refactor(anthropic): simplify SDK ownership and preserve live skills * fix(anthropic): fence cancelled SDK runs before process startup * fix(anthropic): harden SDK approvals, lifecycle, and packaging * refactor(anthropic): own SDK process trees and streamline runtime * fix(anthropic): repair rebased packaging and legacy test fixtures
1 parent 554fb21 commit 12d0fd2

90 files changed

Lines changed: 4705 additions & 10228 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.

‎Dockerfile‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ ARG OPENCLAW_BUNDLED_PLUGIN_DIR
3636
# Podman/Buildah hosts. Full trees stay in this disposable stage; later stages
3737
# receive only extracted manifests.
3838
COPY scripts/lib/docker-plugin-selection.mjs /tmp/docker-plugin-selection.mjs
39+
COPY scripts/lib/root-package-bundled-plugin-excludes.mjs /tmp/root-package-bundled-plugin-excludes.mjs
40+
COPY package.json /tmp/package.json
3941
COPY packages /tmp/packages
4042
COPY ${OPENCLAW_BUNDLED_PLUGIN_DIR} /tmp/${OPENCLAW_BUNDLED_PLUGIN_DIR}
4143
RUN mkdir -p /out/packages "/out/${OPENCLAW_BUNDLED_PLUGIN_DIR}" && \
@@ -48,13 +50,17 @@ RUN mkdir -p /out/packages "/out/${OPENCLAW_BUNDLED_PLUGIN_DIR}" && \
4850
done && \
4951
node /tmp/docker-plugin-selection.mjs "/tmp/${OPENCLAW_BUNDLED_PLUGIN_DIR}" "$OPENCLAW_EXTENSIONS" \
5052
> /out/openclaw-selected-plugin-dirs && \
53+
node /tmp/docker-plugin-selection.mjs "/tmp/${OPENCLAW_BUNDLED_PLUGIN_DIR}" "$OPENCLAW_EXTENSIONS" \
54+
--required-platform-packages > /out/openclaw-required-platform-packages && \
55+
node /tmp/docker-plugin-selection.mjs "/tmp/${OPENCLAW_BUNDLED_PLUGIN_DIR}" "$OPENCLAW_EXTENSIONS" \
56+
--required-bundled /tmp/package.json > /tmp/openclaw-workspace-plugin-dirs && \
5157
while IFS= read -r ext; do \
5258
ext_dir="/tmp/${OPENCLAW_BUNDLED_PLUGIN_DIR}/$ext"; \
5359
if [ -f "$ext_dir/package.json" ]; then \
5460
mkdir -p "/out/${OPENCLAW_BUNDLED_PLUGIN_DIR}/$ext" && \
5561
cp "$ext_dir/package.json" "/out/${OPENCLAW_BUNDLED_PLUGIN_DIR}/$ext/package.json"; \
5662
fi; \
57-
done < /out/openclaw-selected-plugin-dirs
63+
done < /tmp/openclaw-workspace-plugin-dirs
5864

5965
# ── Stage 2: Build ──────────────────────────────────────────────
6066
FROM ${OPENCLAW_BUN_IMAGE} AS bun-binary
@@ -83,6 +89,7 @@ COPY scripts/lib/package-dist-imports.mjs ./scripts/lib/package-dist-imports.mjs
8389
COPY --from=workspace-deps /out/packages/ ./packages/
8490
COPY --from=workspace-deps /out/${OPENCLAW_BUNDLED_PLUGIN_DIR}/ ./${OPENCLAW_BUNDLED_PLUGIN_DIR}/
8591
COPY --from=workspace-deps /out/openclaw-selected-plugin-dirs /tmp/openclaw-selected-plugin-dirs
92+
COPY --from=workspace-deps /out/openclaw-required-platform-packages /tmp/openclaw-required-platform-packages
8693

8794
# Reduce OOM risk on low-memory hosts during dependency installation.
8895
# Docker builds on small VMs may otherwise fail with "Killed" (exit 137).
@@ -170,6 +177,7 @@ FROM build AS runtime-assets
170177
ARG OPENCLAW_BUNDLED_PLUGIN_DIR
171178
# BuildKit cache mounts are not part of cached layers; seed tarballs for the
172179
# installed prod graph in the same step that runs offline prune.
180+
# Keep SDK-native binaries only for selected plugins that explicitly require them.
173181
RUN --mount=type=cache,id=openclaw-pnpm-store,target=/root/.local/share/pnpm/store,sharing=locked \
174182
node scripts/list-prod-store-packages.mjs | xargs -r pnpm store add && \
175183
CI=true pnpm prune --prod \
@@ -192,6 +200,10 @@ RUN --mount=type=cache,id=openclaw-pnpm-store,target=/root/.local/share/pnpm/sto
192200
/app/node_modules/openclaw \
193201
/app/node_modules/.bin/openclaw \
194202
/app/node_modules/.pnpm/openclaw@*/node_modules/openclaw && \
203+
if ! grep -q '^@anthropic-ai/claude-agent-sdk-' /tmp/openclaw-required-platform-packages; then \
204+
find /app/node_modules/@anthropic-ai -maxdepth 1 -type d \
205+
-name 'claude-agent-sdk-linux-*' -exec rm -rf {} +; \
206+
fi && \
195207
node --input-type=module -e 'await import("grammy")' && \
196208
node scripts/check-package-dist-imports.mjs /app
197209

‎config/assertion-safety-baseline.txt‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1747,8 +1747,6 @@ src/agents/cli-runner/bundle-mcp-codex.ts 5
17471747
src/agents/cli-runner/bundle-mcp-gemini.ts 4
17481748
src/agents/cli-runner/bundle-mcp-runtime.ts 1
17491749
src/agents/cli-runner/bundle-mcp.ts 6
1750-
src/agents/cli-runner/claude-live-registry.ts 1
1751-
src/agents/cli-runner/claude-live-session.ts 1
17521750
src/agents/cli-runner/cli-backend-auth-policy.ts 1
17531751
src/agents/cli-runner/cli-run-settlement.ts 1
17541752
src/agents/cli-runner/cli-run-transcript.ts 3

‎docs/gateway/cli-backends.md‎

Lines changed: 50 additions & 42 deletions
Large diffs are not rendered by default.

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

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -241,18 +241,10 @@ only for behavior that really belongs to the backend.
241241
| `manualCompaction` | Atomic command, transport, and positive-acknowledgement contract |
242242
| `subscriptionAuthDispatch` | Opted-in embedded runs on subscription credentials execute via this backend |
243243
| `runtimeArtifact` | Bound a script launcher to its complete bundled package tree |
244-
| `liveSessionRequirement` | Require an init capability before trusting long-lived session output |
245244

246245
Keep these hooks provider-owned. Do not add CLI-specific branches to core when
247246
a backend hook can express the behavior.
248247

249-
`liveSessionRequirement` declares one exact capability that the CLI must
250-
advertise in its initialization record before OpenClaw trusts streamed output.
251-
It also supplies the first known compatible version, version-probe arguments,
252-
and update command used by setup and Doctor. Runtime support remains
253-
capability-based, so a compatible backport or wrapper is not rejected only
254-
because of its version string.
255-
256248
`prepareExecution(ctx)` receives `ctx.contextTokenBudget`, the effective token
257249
limit selected for the run. Backends that own native compaction can map that
258250
budget into their CLI-specific launch contract. It also receives the optional
@@ -261,6 +253,16 @@ effective `ctx.thinkingLevel`: `off`, `minimal`, `low`, `medium`, `high`,
261253
applied through launch environment or staged configuration; the same field is
262254
available to `resolveExecutionArgs(ctx)` for native CLI flags.
263255

256+
`prepareExecution(ctx)` may also return an optional `execute` transport when a
257+
backend owns a vendor-supported SDK for the installed CLI. The transport
258+
receives the exact prepared command, arguments, environment, prompt, session,
259+
and tool availability; it yields the backend's existing structured stream
260+
records. Native tool actions must use the provided, run-bound
261+
`requestToolPermission` callback rather than creating independent approval
262+
authority. OpenClaw retains cancellation, watchdogs, session policy, and MCP
263+
grant ownership. Explicit credential forwarding, paired-node execution, and
264+
manual compaction continue through the existing host-managed process path.
265+
264266
`runtimeArtifact` is plugin-owned. It is consulted
265267
only when a live inference turn mints or revalidates verified setup authority;
266268
normal CLI runs do not require it. A backend without this declaration cannot
@@ -307,16 +309,6 @@ Runtime caps such as cron `toolsAllow` are normalized and group-expanded by
307309
OpenClaw before this contract is built. Native tools are disabled, and a
308310
backend without a complete declared enforcement path fails before execution.
309311

310-
Plugins built against `v2026.7.2-beta.1` through `v2026.7.2-beta.3` may still
311-
read the deprecated `ctx.toolAvailability.mcp` transport-name projection and
312-
may omit `toolAvailabilityEnforcement` when a selectable backend implements
313-
`resolveExecutionArgs`. OpenClaw recognizes that shipped beta path from the
314-
plugin package's required `openclaw.build.openclawVersion` metadata and
315-
preserves it through the `2026.8.x` line. New and updated plugins should use canonical
316-
`ctx.toolAvailability.openClaw` names and declare
317-
`toolAvailabilityEnforcement: "execution-args"` explicitly; the beta
318-
compatibility path is scheduled for removal after that window.
319-
320312
### `parseJsonlEvent`: provider-specific JSONL streams
321313

322314
Set `parseJsonlEvent` when a backend emits line-delimited JSON that does not

‎docs/providers/anthropic.md‎

Lines changed: 37 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ title: "Anthropic"
99
Anthropic builds the **Claude** model family. OpenClaw supports two auth routes:
1010

1111
- **API key** - direct Anthropic API access with usage-based billing (`anthropic/*` models)
12-
- **Claude CLI** - reuse an existing Claude Code login on the same host
12+
- **Claude CLI** - reuse an existing Claude Code login on the same host through Anthropic's official Agent SDK
1313

1414
## Usage and cost tracking
1515

@@ -22,18 +22,11 @@ OpenClaw detects the available Anthropic credential and selects the matching usa
2222
Admin API cost history comes from Anthropic's [Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api). It is actual provider billing, separate from OpenClaw's session-derived estimated cost.
2323

2424
<Warning>
25-
OpenClaw's Claude CLI backend runs the installed Claude Code CLI in
26-
non-interactive print mode (`claude -p`). Anthropic's current Claude Code docs
27-
describe that mode as Agent SDK/programmatic usage. Anthropic's June 15, 2026
28-
support update paused the announced separate Agent SDK billing change: Claude
29-
Agent SDK, `claude -p`, and third-party app usage still draw from a signed-in
30-
subscription's usage limits, and the previously announced monthly Agent SDK
31-
credit is not available while Anthropic revises that plan.
32-
33-
Interactive Claude Code still draws from the signed-in Claude plan's limits.
34-
API key auth is direct pay-as-you-go billing and does not depend on that plan.
35-
For long-lived gateway hosts, shared automation, and predictable production
36-
spend, use an Anthropic API key.
25+
Claude Code owns its existing login and subscription; OpenClaw does not extract
26+
that login or synthesize Anthropic API requests. Agent SDK and `claude -p`
27+
usage currently draw from the signed-in subscription's limits. API-key auth
28+
uses separate pay-as-you-go billing and is preferable for shared automation or
29+
predictable production spend.
3730

3831
Anthropic's current support articles can change this behavior without an
3932
OpenClaw release:
@@ -91,18 +84,15 @@ OpenClaw release:
9184

9285
<Steps>
9386
<Step title="Ensure Claude CLI is installed and logged in">
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:
87+
OpenClaw runs the installed Claude Code executable through Anthropic's
88+
official Agent SDK. Verify that Claude Code is installed and up to date:
9789

9890
```bash
9991
claude --version
10092
```
10193

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:
94+
If the installed build is incompatible, update Claude Code and restart
95+
OpenClaw so the gateway launches the new binary:
10696

10797
```bash
10898
claude update
@@ -114,7 +104,18 @@ OpenClaw release:
114104
# choose: Claude CLI
115105
```
116106

117-
OpenClaw detects and reuses the existing Claude CLI credentials.
107+
OpenClaw detects the existing Claude CLI login. Normal agent turns use
108+
the official Agent SDK with the installed, authenticated Claude Code
109+
executable, including native-tool turns whose approvals remain under
110+
OpenClaw control. Imported native OAuth profiles reuse the verified
111+
Claude Code login; explicitly selected API-key or token credentials
112+
still use protected file-descriptor forwarding. Isolated side-question
113+
completions and paired-node execution retain the supervised CLI path.
114+
115+
Consecutive agent turns reuse the same warm Agent SDK query and Claude
116+
Code subprocess when their authenticated session and execution policy
117+
match. If that process ends or the gateway restarts, the next turn
118+
resumes the persisted Claude Code session.
118119
</Step>
119120
<Step title="Verify the model is available">
120121
```bash
@@ -125,8 +126,6 @@ OpenClaw release:
125126

126127
<Note>
127128
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.
130129
</Note>
131130

132131
<Warning>
@@ -177,8 +176,8 @@ OpenClaw release:
177176

178177
### Billing and `claude -p`
179178

180-
OpenClaw uses Claude Code's non-interactive `claude -p` path for Claude CLI
181-
runs. Anthropic currently treats that path as Agent SDK/programmatic usage:
179+
Anthropic currently treats Agent SDK and non-interactive CLI invocations as
180+
programmatic usage:
182181

183182
- Anthropic's June 15, 2026 support update paused the previously announced
184183
separate Agent SDK credit plan.
@@ -189,14 +188,6 @@ OpenClaw release:
189188
- Console/API-key logins use pay-as-you-go API billing and do not receive
190189
the subscription Agent SDK credit.
191190

192-
See Anthropic's [Agent SDK plan
193-
article](https://support.claude.com/en/articles/15036540-use-the-claude-agent-sdk-with-your-claude-plan)
194-
for the pause notice, and the Claude Code plan articles for
195-
[Pro/Max](https://support.claude.com/en/articles/11145838-use-claude-code-with-your-pro-or-max-plan)
196-
and
197-
[Team/Enterprise](https://support.claude.com/en/articles/11845131-use-claude-code-with-your-team-or-enterprise-plan)
198-
subscription behavior.
199-
200191
Anthropic can change Claude Code billing and rate-limit behavior without an
201192
OpenClaw release. Check `claude auth status`, `/status`, and
202193
Anthropic's linked docs when billing predictability matters.
@@ -664,6 +655,19 @@ OpenClaw supports Anthropic's prompt caching feature for API-key auth.
664655
## Troubleshooting
665656

666657
<AccordionGroup>
658+
<Accordion title="Claude CLI OAuth session expired or could not be refreshed">
659+
Run these commands as the Gateway user on the Gateway host:
660+
661+
```bash
662+
claude auth status --text
663+
claude auth login
664+
openclaw gateway restart
665+
```
666+
667+
Claude Code owns its login and refresh lifecycle; do not copy an OAuth token into OpenClaw.
668+
669+
</Accordion>
670+
667671
<Accordion title="401 errors / token suddenly invalid">
668672
Anthropic token auth expires and can be revoked. For new setups, use an Anthropic API key instead.
669673
</Accordion>

‎docs/tools/exec-approvals.md‎

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -257,15 +257,11 @@ explicitly when a no-UI approval prompt should fall back to allow.
257257

258258
</Warning>
259259

260-
CLI-backed providers that expose their own noninteractive permission mode
261-
can follow this policy. Claude CLI adds
262-
`--permission-mode bypassPermissions` when OpenClaw's effective exec
263-
policy is YOLO. For OpenClaw-managed Claude live sessions, OpenClaw's
264-
effective exec policy is authoritative over Claude's native permission mode:
265-
YOLO normalizes live launches to `--permission-mode bypassPermissions`, and
266-
restrictive effective exec policy normalizes live launches to
267-
`--permission-mode default`, even if raw Claude backend args specify another
268-
mode.
260+
For OpenClaw-managed Claude sessions, the Claude Agent SDK always uses its
261+
`default` permission mode. OpenClaw's effective exec policy remains
262+
authoritative through its native tool approval callback, including YOLO and
263+
restrictive policies, even if raw Claude backend args request
264+
`bypassPermissions`.
269265

270266
If you want a more conservative setup, tighten OpenClaw exec policy back to
271267
`allowlist` / `on-miss` or `deny`.

0 commit comments

Comments
 (0)