Skip to content

Commit 1a42e00

Browse files
fix(anthropic): forward selected profiles to Claude CLI (#112458)
* fix(anthropic): forward Claude CLI auth profiles * fix(system-agent): inject CLI auth route stores * fix(claude-cli): pass profile credentials by descriptor * fix(anthropic): repair selected profile CI coverage * fix(anthropic): preserve profile owner validation * test(system-agent): preserve selected profile fixtures * test(system-agent): narrow selected profile fixture * test(system-agent): resolve profile store merge * fix(anthropic): forward profiles to node Claude runs * fix(system-agent): reconcile profile route projection * test(system-agent): thread profile store through projection * fix(anthropic): make selected profile authoritative * fix(system-agent): type auth setup failures * fix(system-agent): type setup auth failures * style: format Claude profile maintenance * fix(anthropic): keep gateway credentials off nodes * fix(anthropic): clear ambient auth for selected profiles * fix(anthropic): secure paired-node Claude auth * fix(node-host): type Claude fd spawn streams * style(node-host): satisfy Claude spawn lint * fix(process): capture exit before secret delivery * fix(anthropic): preserve node-native Claude auth
1 parent 13716ad commit 1a42e00

30 files changed

Lines changed: 1252 additions & 75 deletions

‎docs/gateway/cli-backends.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,11 @@ If no MCP servers are enabled, OpenClaw still injects a strict config when a bac
319319

320320
Session-scoped bundled MCP runtimes are cached for reuse within a session, then reaped after 10 minutes of idle time. One-shot embedded runs such as auth probes, slug generation, and active-memory recall request cleanup at run end so stdio children and Streamable HTTP/SSE streams do not outlive the run.
321321

322+
For `claude-cli`, a compatible selected or ordered OpenClaw OAuth/token profile
323+
is forwarded to that Claude child. This makes per-agent profiles authoritative
324+
for the turn while preserving Claude's native host login when no compatible
325+
profile exists.
326+
322327
## Reseed history cap
323328

324329
When a fresh CLI session is seeded from a prior OpenClaw transcript (for example after a `session_expired` retry), the rendered `<conversation_history>` block is capped to keep reseed prompts from exploding. The default is 12,288 characters (about 3,000 tokens).

‎extensions/anthropic/cli-backend.ts‎

Lines changed: 104 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
/**
22
* Claude CLI backend descriptor. It configures Claude Code process arguments,
3-
* MCP bundling, session handling, environment scrubbing, and watchdog defaults.
3+
* MCP bundling, session handling, credential transport, and watchdog defaults.
44
*/
5-
import type { CliBackendPlugin } from "openclaw/plugin-sdk/cli-backend";
5+
import { createHmac, randomBytes } from "node:crypto";
6+
import type {
7+
CliBackendPlugin,
8+
CliBackendPreparedExecution,
9+
} from "openclaw/plugin-sdk/cli-backend";
610
import {
711
CLI_FRESH_WATCHDOG_DEFAULTS,
812
CLI_RESUME_WATCHDOG_DEFAULTS,
@@ -19,6 +23,86 @@ import {
1923
resolveClaudeCliRuntimeToolAvailability,
2024
} from "./cli-shared.js";
2125

26+
type ClaudeCliAuthCredential =
27+
| { type: "oauth"; access: string }
28+
| { type: "token"; token: string }
29+
| { type: "api_key"; key: string }
30+
| { type: string };
31+
32+
type ClaudeCliPreparedExecution = CliBackendPreparedExecution & {
33+
secretInput: {
34+
fd: 3;
35+
fingerprint: string;
36+
createData: () => Buffer;
37+
};
38+
};
39+
40+
const CLAUDE_CLI_CREDENTIAL_FINGERPRINT_KEY = randomBytes(32);
41+
42+
function createClaudeCliAuthInput(params: {
43+
envName: "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR" | "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";
44+
value: string;
45+
}): ClaudeCliPreparedExecution | undefined {
46+
const trimmed = params.value.trim();
47+
if (!trimmed) {
48+
return undefined;
49+
}
50+
const source = Buffer.from(trimmed, "utf8");
51+
let destroyed = false;
52+
return {
53+
env: { [params.envName]: "3" },
54+
clearEnv: [...CLAUDE_CLI_CLEAR_ENV],
55+
secretInput: {
56+
fd: 3,
57+
fingerprint: createHmac("sha256", CLAUDE_CLI_CREDENTIAL_FINGERPRINT_KEY)
58+
.update(source)
59+
.digest("hex"),
60+
createData: () => {
61+
if (destroyed) {
62+
throw new Error("Claude CLI credential input is no longer available");
63+
}
64+
return Buffer.from(source);
65+
},
66+
},
67+
cleanup: async () => {
68+
destroyed = true;
69+
source.fill(0);
70+
},
71+
};
72+
}
73+
74+
function resolveClaudeCliAuthInput(
75+
credential: ClaudeCliAuthCredential | undefined,
76+
): ClaudeCliPreparedExecution | undefined {
77+
if (
78+
credential?.type === "oauth" &&
79+
"access" in credential &&
80+
typeof credential.access === "string"
81+
) {
82+
return createClaudeCliAuthInput({
83+
envName: "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
84+
value: credential.access,
85+
});
86+
}
87+
if (
88+
credential?.type === "token" &&
89+
"token" in credential &&
90+
typeof credential.token === "string"
91+
) {
92+
return createClaudeCliAuthInput({
93+
envName: "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
94+
value: credential.token,
95+
});
96+
}
97+
if (credential?.type === "api_key" && "key" in credential && typeof credential.key === "string") {
98+
return createClaudeCliAuthInput({
99+
envName: "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR",
100+
value: credential.key,
101+
});
102+
}
103+
return undefined;
104+
}
105+
22106
/** Build the Claude CLI backend plugin descriptor. */
23107
export function buildAnthropicCliBackend(): CliBackendPlugin {
24108
return {
@@ -106,10 +190,24 @@ export function buildAnthropicCliBackend(): CliBackendPlugin {
106190
serialize: true,
107191
},
108192
normalizeConfig: normalizeClaudeBackendConfig,
109-
autoSelectAuthProfile: false,
110-
prepareExecution: ({ contextTokenBudget }) => {
111-
const env = resolveClaudeCliAutoCompactEnv(contextTokenBudget);
112-
return env ? { env } : undefined;
193+
authEpochMode: "profile-only",
194+
prepareExecution: (context) => {
195+
const credentialContext = context as typeof context & {
196+
authCredential?: ClaudeCliAuthCredential;
197+
};
198+
const authInput = resolveClaudeCliAuthInput(credentialContext.authCredential);
199+
const env = {
200+
...resolveClaudeCliAutoCompactEnv(context.contextTokenBudget),
201+
...authInput?.env,
202+
};
203+
return Object.keys(env).length > 0
204+
? {
205+
env,
206+
...(authInput?.clearEnv ? { clearEnv: authInput.clearEnv } : {}),
207+
...(authInput?.secretInput ? { secretInput: authInput.secretInput } : {}),
208+
...(authInput?.cleanup ? { cleanup: authInput.cleanup } : {}),
209+
}
210+
: undefined;
113211
},
114212
resolveExecutionArgs: resolveClaudeCliExecutionArgs,
115213
resolveRuntimeToolAvailability: resolveClaudeCliRuntimeToolAvailability,

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

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,17 @@ import {
99
resolveClaudeCliRuntimeToolAvailability,
1010
} from "./cli-shared.js";
1111

12+
type ClaudePreparedExecutionWithSecret = {
13+
env?: Record<string, string>;
14+
clearEnv?: string[];
15+
cleanup?: () => Promise<void>;
16+
secretInput: {
17+
fd: number;
18+
fingerprint: string;
19+
createData: () => Buffer;
20+
};
21+
};
22+
1223
const CLAUDE_CLI_DISALLOWED_TOOLS =
1324
"ScheduleWakeup,CronCreate,Bash(run_in_background:true),Monitor";
1425

@@ -702,6 +713,123 @@ describe("normalizeClaudeBackendConfig", () => {
702713
});
703714
});
704715

716+
it("forwards the selected OAuth profile through Claude's private descriptor", async () => {
717+
const backend = buildAnthropicCliBackend();
718+
719+
const prepared = backend.prepareExecution?.({
720+
workspaceDir: "/tmp/openclaw-claude-cli",
721+
provider: "claude-cli",
722+
modelId: "claude-opus-4-7",
723+
authProfileId: "anthropic:claude-cli",
724+
authCredential: {
725+
type: "oauth",
726+
provider: "claude-cli",
727+
access: "selected-access-token",
728+
refresh: "selected-refresh-token",
729+
expires: Date.now() + 60_000,
730+
},
731+
} as Parameters<NonNullable<typeof backend.prepareExecution>>[0] & {
732+
authCredential: {
733+
type: "oauth";
734+
provider: string;
735+
access: string;
736+
refresh: string;
737+
expires: number;
738+
};
739+
}) as ClaudePreparedExecutionWithSecret;
740+
741+
expect(prepared.env).toEqual({
742+
CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR: "3",
743+
});
744+
expect(prepared.env).not.toHaveProperty("CLAUDE_CODE_OAUTH_TOKEN");
745+
expect(prepared.env).not.toHaveProperty("CLAUDE_CODE_SUBPROCESS_ENV_SCRUB");
746+
expect(prepared.clearEnv).toEqual([...CLAUDE_CLI_CLEAR_ENV]);
747+
expect(prepared.secretInput.fd).toBe(3);
748+
expect(prepared.secretInput.fingerprint).not.toContain("selected-access-token");
749+
expect(prepared.secretInput.createData().toString("utf8")).toBe("selected-access-token");
750+
751+
const sameToken = backend.prepareExecution?.({
752+
workspaceDir: "/tmp/openclaw-claude-cli",
753+
provider: "claude-cli",
754+
modelId: "claude-opus-4-7",
755+
authCredential: {
756+
type: "token",
757+
provider: "claude-cli",
758+
token: "selected-access-token",
759+
},
760+
} as Parameters<NonNullable<typeof backend.prepareExecution>>[0] & {
761+
authCredential: { type: "token"; provider: string; token: string };
762+
}) as ClaudePreparedExecutionWithSecret;
763+
const rotatedToken = backend.prepareExecution?.({
764+
workspaceDir: "/tmp/openclaw-claude-cli",
765+
provider: "claude-cli",
766+
modelId: "claude-opus-4-7",
767+
authCredential: {
768+
type: "token",
769+
provider: "claude-cli",
770+
token: "rotated-access-token",
771+
},
772+
} as Parameters<NonNullable<typeof backend.prepareExecution>>[0] & {
773+
authCredential: { type: "token"; provider: string; token: string };
774+
}) as ClaudePreparedExecutionWithSecret;
775+
expect(sameToken.secretInput.fingerprint).toBe(prepared.secretInput.fingerprint);
776+
expect(rotatedToken.secretInput.fingerprint).not.toBe(prepared.secretInput.fingerprint);
777+
778+
await prepared.cleanup?.();
779+
await sameToken.cleanup?.();
780+
await rotatedToken.cleanup?.();
781+
expect(() => prepared.secretInput.createData()).toThrow(
782+
"Claude CLI credential input is no longer available",
783+
);
784+
});
785+
786+
it("keeps native Claude login when no compatible profile is selected", () => {
787+
const backend = buildAnthropicCliBackend();
788+
789+
expect(
790+
backend.prepareExecution?.({
791+
workspaceDir: "/tmp/openclaw-claude-cli",
792+
provider: "claude-cli",
793+
modelId: "claude-opus-4-7",
794+
}),
795+
).toBeUndefined();
796+
});
797+
798+
it("forwards a selected API-key profile through Claude's private descriptor", async () => {
799+
const backend = buildAnthropicCliBackend();
800+
801+
const prepared = backend.prepareExecution?.({
802+
workspaceDir: "/tmp/openclaw-claude-cli",
803+
provider: "claude-cli",
804+
modelId: "claude-opus-4-7",
805+
authProfileId: "claude-cli:api",
806+
authCredential: {
807+
type: "api_key",
808+
provider: "claude-cli",
809+
key: "selected-api-key",
810+
},
811+
} as Parameters<NonNullable<typeof backend.prepareExecution>>[0] & {
812+
authCredential: {
813+
type: "api_key";
814+
provider: string;
815+
key: string;
816+
};
817+
}) as ClaudePreparedExecutionWithSecret;
818+
819+
expect(prepared.env).toEqual({
820+
CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR: "3",
821+
});
822+
expect(prepared.env).not.toHaveProperty("ANTHROPIC_API_KEY");
823+
expect(prepared.env).not.toHaveProperty("CLAUDE_CODE_SUBPROCESS_ENV_SCRUB");
824+
expect(prepared.secretInput.fingerprint).not.toContain("selected-api-key");
825+
expect(prepared.secretInput.createData().toString("utf8")).toBe("selected-api-key");
826+
827+
await prepared.cleanup?.();
828+
expect(() => prepared.secretInput.createData()).toThrow(
829+
"Claude CLI credential input is no longer available",
830+
);
831+
});
832+
705833
it("disables native background Bash and Monitor tools in args and resumeArgs", () => {
706834
const backend = buildAnthropicCliBackend();
707835

‎src/agents/cli-execution-auth.ts‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,17 @@ import { resolveCliBackendConfig } from "./cli-backends.js";
88

99
const GOOGLE_GEMINI_CLI_PROVIDER_ID = "google-gemini-cli";
1010
const GOOGLE_PROVIDER_ID = "google";
11+
const CLAUDE_CLI_PROVIDER_ID = "claude-cli";
1112

1213
type CliExecutionAuthProfileSelection = {
1314
authProfileId?: string;
1415
authProfileIdSource?: "auto" | "user";
1516
};
1617

18+
export class CliExecutionAuthProfileError extends Error {
19+
override name = "CliExecutionAuthProfileError";
20+
}
21+
1722
export function cliBackendAcceptsAuthProfileForwarding(params: {
1823
provider: string;
1924
config: OpenClawConfig;
@@ -22,23 +27,25 @@ export function cliBackendAcceptsAuthProfileForwarding(params: {
2227
const backend = resolveCliBackendConfig(params.provider, params.config, {
2328
agentId: params.agentId,
2429
});
25-
return backend?.id === GOOGLE_GEMINI_CLI_PROVIDER_ID;
30+
return backend?.id === GOOGLE_GEMINI_CLI_PROVIDER_ID || backend?.id === CLAUDE_CLI_PROVIDER_ID;
2631
}
2732

2833
/**
29-
* Resolve the profile a CLI backend may consume. Gemini CLI prefers its own
30-
* OAuth identity, then bridges a canonical Google API key when that model is
31-
* explicitly routed through the CLI runtime. A user-locked profile must fail
32-
* closed here; falling through would silently run the request as another user.
34+
* Resolve the profile a CLI backend may consume. Claude and Gemini use their
35+
* native profile identities; Gemini may additionally bridge a canonical
36+
* Google API key. A user-locked profile must fail closed here because falling
37+
* through would silently run the request as another user.
3338
*/
3439
export function resolveCliExecutionAuthProfileId(params: {
3540
cliExecutionProvider: string;
3641
authProfileProvider: string;
3742
config: OpenClawConfig;
3843
agentDir: string;
3944
selected?: CliExecutionAuthProfileSelection;
45+
loadAuthProfileStoreForRuntime?: typeof loadAuthProfileStoreForRuntime;
4046
}): string | undefined {
41-
const store = loadAuthProfileStoreForRuntime(params.agentDir, {
47+
const loadStore = params.loadAuthProfileStoreForRuntime ?? loadAuthProfileStoreForRuntime;
48+
const store = loadStore(params.agentDir, {
4249
readOnly: true,
4350
allowKeychainPrompt: false,
4451
externalCliProviderIds: [params.cliExecutionProvider],
@@ -59,9 +66,11 @@ export function resolveCliExecutionAuthProfileId(params: {
5966
}
6067
if (params.selected?.authProfileIdSource !== "auto") {
6168
if (!credential) {
62-
throw new Error(`No credentials found for profile "${selectedAuthProfileId}".`);
69+
throw new CliExecutionAuthProfileError(
70+
`No credentials found for profile "${selectedAuthProfileId}".`,
71+
);
6372
}
64-
throw new Error(
73+
throw new CliExecutionAuthProfileError(
6574
`CLI backend "${params.cliExecutionProvider}" cannot use auth profile "${selectedAuthProfileId}" owned by "${credential.provider}".`,
6675
);
6776
}

0 commit comments

Comments
 (0)