Skip to content

Commit 283b66f

Browse files
committed
refactor(anthropic): own SDK process trees and streamline runtime
1 parent 9ac7497 commit 283b66f

17 files changed

Lines changed: 362 additions & 177 deletions

‎CHANGELOG.md‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ Docs: https://docs.openclaw.ai
66

77
### Changes
88

9-
- **Anthropic Claude subscriptions:** explore the official Claude Agent SDK for existing Claude Code logins while preserving OpenClaw-owned tool approvals, MCP grants, streaming, and explicitly selected credential paths.
109
- **Secret egress host binding:** bind each shared-store secret to exact HTTPS destination hosts across CLI, Gateway RPC, and Control UI so unbound sentinel substitution fails closed before plaintext egress.
1110
- **Release validation:** defer beta candidate Parallels smoke to postpublish `release:beta-smoke` by default, keep stable/full prepublish coverage, and bound nested release workflow monitors with explicit job timeouts.
1211
- **macOS app profiles:** isolate named app instances across state, preferences, Keychain, Gateway services, and duplicate-instance ownership while keeping host-global login and node services untouched.

‎Dockerfile‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ RUN mkdir -p /out/packages "/out/${OPENCLAW_BUNDLED_PLUGIN_DIR}" && \
5050
done && \
5151
node /tmp/docker-plugin-selection.mjs "/tmp/${OPENCLAW_BUNDLED_PLUGIN_DIR}" "$OPENCLAW_EXTENSIONS" \
5252
> /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 && \
5355
node /tmp/docker-plugin-selection.mjs "/tmp/${OPENCLAW_BUNDLED_PLUGIN_DIR}" "$OPENCLAW_EXTENSIONS" \
5456
--required-bundled /tmp/package.json > /tmp/openclaw-workspace-plugin-dirs && \
5557
while IFS= read -r ext; do \
@@ -87,6 +89,7 @@ COPY scripts/lib/package-dist-imports.mjs ./scripts/lib/package-dist-imports.mjs
8789
COPY --from=workspace-deps /out/packages/ ./packages/
8890
COPY --from=workspace-deps /out/${OPENCLAW_BUNDLED_PLUGIN_DIR}/ ./${OPENCLAW_BUNDLED_PLUGIN_DIR}/
8991
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
9093

9194
# Reduce OOM risk on low-memory hosts during dependency installation.
9295
# Docker builds on small VMs may otherwise fail with "Killed" (exit 137).
@@ -174,6 +177,7 @@ FROM build AS runtime-assets
174177
ARG OPENCLAW_BUNDLED_PLUGIN_DIR
175178
# BuildKit cache mounts are not part of cached layers; seed tarballs for the
176179
# installed prod graph in the same step that runs offline prune.
180+
# Keep SDK-native binaries only for selected plugins that explicitly require them.
177181
RUN --mount=type=cache,id=openclaw-pnpm-store,target=/root/.local/share/pnpm/store,sharing=locked \
178182
node scripts/list-prod-store-packages.mjs | xargs -r pnpm store add && \
179183
CI=true pnpm prune --prod \
@@ -196,6 +200,10 @@ RUN --mount=type=cache,id=openclaw-pnpm-store,target=/root/.local/share/pnpm/sto
196200
/app/node_modules/openclaw \
197201
/app/node_modules/.bin/openclaw \
198202
/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 && \
199207
node --input-type=module -e 'await import("grammy")' && \
200208
node scripts/check-package-dist-imports.mjs /app
201209

‎THIRD_PARTY_NOTICES.md‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,6 @@ This file records third-party notices for code or substantial implementation
44
portions incorporated into OpenClaw source, beyond normal package-manager
55
dependency metadata.
66

7-
## Anthropic Claude Agent SDK
8-
9-
The bundled Anthropic provider incorporates the official Claude Agent SDK.
10-
11-
- Upstream: https://github.com/anthropics/claude-agent-sdk-typescript
12-
- Package: `@anthropic-ai/claude-agent-sdk`
13-
- License: https://code.claude.com/docs/en/legal-and-compliance
14-
- Copyright: © Anthropic PBC. All rights reserved.
15-
167
## Pi / pi-mono
178

189
Portions of OpenClaw were adapted from Pi / pi-mono, and OpenClaw also depends

‎docs/gateway/cli-backends.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ Use it as a safety net for "always works" text responses, not a primary path. Fo
2525
The bundled Anthropic plugin registers a default `claude-cli` backend, so it works with no config beyond having Claude Code installed and logged in:
2626

2727
```bash
28-
openclaw agent --agent main --message "hi" --model claude-cli/claude-sonnet-4-6
28+
openclaw agent --agent main --message "hi" --model claude-cli/claude-sonnet-5
2929
```
3030

3131
`main` is the default agent id when no explicit agent list is configured; swap in your own agent id otherwise.
@@ -48,11 +48,11 @@ Add the CLI backend to your fallback list so it only runs when primary models fa
4848
defaults: {
4949
model: {
5050
primary: "anthropic/claude-opus-4-6",
51-
fallbacks: ["claude-cli/claude-sonnet-4-6"],
51+
fallbacks: ["claude-cli/claude-sonnet-5"],
5252
},
5353
models: {
5454
"anthropic/claude-opus-4-6": { alias: "Opus" },
55-
"claude-cli/claude-sonnet-4-6": {},
55+
"claude-cli/claude-sonnet-5": {},
5656
},
5757
},
5858
},

‎docs/providers/anthropic.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -655,6 +655,19 @@ OpenClaw supports Anthropic's prompt caching feature for API-key auth.
655655
## Troubleshooting
656656

657657
<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+
658671
<Accordion title="401 errors / token suddenly invalid">
659672
Anthropic token auth expires and can be revoked. For new setups, use an Anthropic API key instead.
660673
</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`.

‎extensions/anthropic/agent-sdk.runtime.test.ts‎

Lines changed: 38 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ describe("Anthropic Agent SDK runtime ownership", () => {
223223
expect(sideQuestion).not.toHaveProperty("execute");
224224
});
225225

226-
it("delivers a selected credential only through descriptor 3 and zeroes its delivered buffer", async () => {
226+
it("owns the selected-credential process tree while keeping its descriptor private and zeroed", async () => {
227227
const backend = buildAnthropicCliBackend();
228228
const token = "selected-private-descriptor-fixture";
229229
const prepared = (await backend.prepareExecution?.({
@@ -256,9 +256,12 @@ describe("Anthropic Agent SDK runtime ownership", () => {
256256
"-e",
257257
[
258258
'const data = require("node:fs").readFileSync(3);',
259+
'require("node:fs").writeSync(2, Buffer.alloc(1024 * 1024));',
259260
'const digest = require("node:crypto").createHash("sha256").update(data).digest("hex");',
260-
"process.stdout.write(JSON.stringify({fd: Number(process.env.CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR), digest}));",
261+
'const descendant = require("node:child_process").spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {stdio: "ignore"});',
262+
"process.stdout.write(JSON.stringify({fd: Number(process.env.CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR), digest, descendantPid: descendant.pid}));",
261263
"data.fill(0);",
264+
"setInterval(() => {}, 1000);",
262265
].join(""),
263266
];
264267
const env = { PATH: process.env.PATH, ...prepared.env };
@@ -275,17 +278,30 @@ describe("Anthropic Agent SDK runtime ownership", () => {
275278
let stdout = "";
276279
child.stdout.on("data", (chunk: Buffer | string) => {
277280
stdout += chunk.toString();
281+
child.kill("SIGTERM");
278282
});
279283
child.once("error", reject);
280-
child.once("exit", (code) => {
281-
if (code === 0) {
284+
child.once("exit", (code, signal) => {
285+
if (signal === "SIGTERM" || (process.platform === "win32" && code !== null)) {
282286
resolve(stdout);
283287
} else {
284288
reject(new Error(`Credential descriptor proof exited ${String(code)}.`));
285289
}
286290
});
287291
});
288-
descriptorOutput = JSON.parse(output) as { fd: number; digest: string };
292+
const { descendantPid, ...descriptor } = JSON.parse(output) as {
293+
fd: number;
294+
digest: string;
295+
descendantPid: number;
296+
};
297+
descriptorOutput = descriptor;
298+
try {
299+
await vi.waitFor(() => expect(() => process.kill(descendantPid, 0)).toThrow());
300+
} finally {
301+
try {
302+
process.kill(descendantPid, "SIGKILL");
303+
} catch {}
304+
}
289305
});
290306

291307
const events: Record<string, unknown>[] = [];
@@ -310,10 +326,7 @@ describe("Anthropic Agent SDK runtime ownership", () => {
310326
[
311327
{
312328
name: "denies",
313-
decision: {
314-
behavior: "deny" as const,
315-
message: "OpenClaw denied restricted native Bash execution.",
316-
},
329+
decision: { behavior: "deny" as const, message: "OpenClaw denied restricted Bash." },
317330
},
318331
{
319332
name: "allows",
@@ -331,10 +344,7 @@ describe("Anthropic Agent SDK runtime ownership", () => {
331344
"$name restricted native Bash through the prepared SDK approval owner",
332345
async ({ credential, decision }) => {
333346
const backend = buildAnthropicCliBackend();
334-
const toolAvailability = {
335-
native: ["Bash"],
336-
openClaw: ["message"],
337-
};
347+
const toolAvailability = { native: ["Bash"], openClaw: ["message"] };
338348
const prepareContext = {
339349
workspaceDir: "/tmp/openclaw-workspace",
340350
provider: "claude-cli",
@@ -371,7 +381,7 @@ describe("Anthropic Agent SDK runtime ownership", () => {
371381
tool_input: input,
372382
tool_use_id: "restricted-native-bash",
373383
},
374-
"restricted-native-bash",
384+
undefined,
375385
{ signal },
376386
);
377387
callbackDecision = await sdkNativeTool(options)("Bash", input, {
@@ -754,7 +764,9 @@ describe("Anthropic Agent SDK runtime ownership", () => {
754764
"--allowedTools",
755765
"mcp__openclaw__message",
756766
"--disallowedTools",
757-
"Bash,Edit,Write",
767+
"Bash",
768+
"Edit",
769+
"Write",
758770
],
759771
toolAvailability: {
760772
native: [],
@@ -783,13 +795,20 @@ describe("Anthropic Agent SDK runtime ownership", () => {
783795
).not.toContain(context.env.OPENCLAW_MCP_TOKEN);
784796
});
785797

786-
it("preserves managed skill plugins without letting isolated plugins discover MCP servers", async () => {
798+
it("preserves variadic directories, tools, and managed plugin MCP isolation", async () => {
787799
useSdkMessages();
788800

789801
await collect(
790802
createContext({
791803
args: [
792804
"-p",
805+
"--add-dir",
806+
"/tmp/a",
807+
"/tmp/b",
808+
"--add-dir=/tmp/c",
809+
"--tools",
810+
"Read",
811+
"Grep",
793812
"--plugin-dir",
794813
"/tmp/openclaw-native-skills",
795814
"--plugin-dir-no-mcp",
@@ -802,6 +821,8 @@ describe("Anthropic Agent SDK runtime ownership", () => {
802821
{ type: "local", path: "/tmp/openclaw-native-skills" },
803822
{ type: "local", path: "/tmp/openclaw-isolated-skills", skipMcpDiscovery: true },
804823
]);
824+
expect(sdkOptions().additionalDirectories).toEqual(["/tmp/a", "/tmp/b", "/tmp/c"]);
825+
expect(sdkOptions().tools).toEqual(["Read", "Grep"]);
805826
});
806827

807828
it.each([
@@ -825,7 +846,7 @@ describe("Anthropic Agent SDK runtime ownership", () => {
825846

826847
await collect(
827848
createContext({
828-
args: ["-p", "--allowedTools", "Bash,mcp__openclaw__*,Edit"],
849+
args: ["-p", "--allowedTools", "Bash", "mcp__openclaw__*", "Edit"],
829850
toolAvailability: {
830851
native: [],
831852
openClaw: ["message", "memory_search"],
@@ -914,37 +935,6 @@ describe("Anthropic Agent SDK runtime ownership", () => {
914935
});
915936
});
916937

917-
it("projects an approved native pre-tool action with the exact host-authorized input", async () => {
918-
const updatedInput = { command: "printf SDK_TOOL_OK" };
919-
const requestToolPermission = vi.fn(async () => ({ behavior: "allow" as const, updatedInput }));
920-
let decision: unknown;
921-
useSdkMessages([SUCCESS_RESULT], async (options) => {
922-
decision = await sdkPreToolUse(options)(
923-
{
924-
hook_event_name: "PreToolUse",
925-
tool_name: "Bash",
926-
tool_input: { command: "printf original" },
927-
tool_use_id: "approved-native-tool",
928-
},
929-
undefined,
930-
{ signal: new AbortController().signal },
931-
);
932-
});
933-
934-
await collect(createContext({ requestToolPermission }));
935-
936-
expect(decision).toEqual({
937-
hookSpecificOutput: {
938-
hookEventName: "PreToolUse",
939-
permissionDecision: "allow",
940-
updatedInput,
941-
},
942-
});
943-
expect(requestToolPermission).toHaveBeenCalledWith(
944-
expect.objectContaining({ toolCallId: "approved-native-tool" }),
945-
);
946-
});
947-
948938
it("keeps bypass-shaped backend arguments behind the host permission callback", async () => {
949939
const requestToolPermission = vi.fn(async () => ({
950940
behavior: "deny" as const,

0 commit comments

Comments
 (0)