Skip to content

Commit 17ba3bc

Browse files
committed
fix: load staged Gemini CLI auth profiles
1 parent c38c4e9 commit 17ba3bc

7 files changed

Lines changed: 246 additions & 6 deletions

File tree

‎extensions/google/cli-backend.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import crypto from "node:crypto";
21
import fs from "node:fs/promises";
32
import os from "node:os";
43
import path from "node:path";
@@ -7,14 +6,18 @@ import {
76
CLI_FRESH_WATCHDOG_DEFAULTS,
87
CLI_RESUME_WATCHDOG_DEFAULTS,
98
} from "openclaw/plugin-sdk/cli-backend";
9+
import {
10+
GOOGLE_GEMINI_CLI_PROVIDER_ID,
11+
resolveGeminiCliProfileHome as resolveGeminiCliProfileHomePath,
12+
} from "./gemini-cli-auth-home.js";
1013

1114
const GEMINI_MODEL_ALIASES: Record<string, string> = {
1215
pro: "gemini-3.1-pro-preview",
1316
flash: "gemini-3.1-flash-preview",
1417
"flash-lite": "gemini-3.1-flash-lite",
1518
};
1619
const GEMINI_CLI_DEFAULT_MODEL_REF = "google-gemini-cli/gemini-3-flash-preview";
17-
const GEMINI_CLI_PROVIDER_ID = "google-gemini-cli";
20+
const GEMINI_CLI_PROVIDER_ID = GOOGLE_GEMINI_CLI_PROVIDER_ID;
1821
const GOOGLE_PROVIDER_ID = "google";
1922
const VERCEL_AI_GATEWAY_PROVIDER_ID = "vercel-ai-gateway";
2023
const GEMINI_CLI_CREDENTIALS_FILENAME = "gemini-credentials.json";
@@ -195,8 +198,7 @@ function resolveGeminiCliProfileHome(ctx: GeminiCliAuthHomeContext): {
195198
throw new Error("Gemini CLI auth profile execution requires a selected auth profile.");
196199
}
197200

198-
const profileHash = crypto.createHash("sha256").update(authProfileId).digest("hex").slice(0, 24);
199-
const home = path.join(agentDir, "cli-runtimes", GEMINI_CLI_PROVIDER_ID, "profiles", profileHash);
201+
const home = resolveGeminiCliProfileHomePath(agentDir, authProfileId);
200202
return { home, geminiDir: path.join(home, ".gemini") };
201203
}
202204

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import crypto from "node:crypto";
2+
import path from "node:path";
3+
4+
export const GOOGLE_GEMINI_CLI_PROVIDER_ID = "google-gemini-cli";
5+
export const GEMINI_CLI_OAUTH_CREDS_RELATIVE_PATH = ".gemini/oauth_creds.json";
6+
7+
export function resolveGeminiCliProfileHome(agentDir: string, profileId: string): string {
8+
const profileHash = crypto.createHash("sha256").update(profileId).digest("hex").slice(0, 24);
9+
return path.join(
10+
agentDir,
11+
"cli-runtimes",
12+
GOOGLE_GEMINI_CLI_PROVIDER_ID,
13+
"profiles",
14+
profileHash,
15+
);
16+
}
17+
18+
export function resolveGeminiCliProfileCredentialsPath(
19+
agentDir: string,
20+
profileId: string,
21+
): string {
22+
return path.join(
23+
resolveGeminiCliProfileHome(agentDir, profileId),
24+
GEMINI_CLI_OAUTH_CREDS_RELATIVE_PATH,
25+
);
26+
}

‎extensions/google/gemini-cli-provider.ts‎

Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Google provider module implements model/runtime integration.
2+
import fs from "node:fs";
23
import type {
34
OpenClawPluginApi,
45
ProviderAuthContext,
@@ -7,11 +8,15 @@ import type {
78
import { buildOauthProviderAuthResult } from "openclaw/plugin-sdk/provider-auth-result";
89
import type { ProviderPlugin } from "openclaw/plugin-sdk/provider-model-shared";
910
import { fetchGeminiUsage } from "openclaw/plugin-sdk/provider-usage";
11+
import {
12+
GOOGLE_GEMINI_CLI_PROVIDER_ID,
13+
resolveGeminiCliProfileCredentialsPath,
14+
} from "./gemini-cli-auth-home.js";
1015
import { formatGoogleOauthApiKey, parseGoogleUsageToken } from "./oauth-token-shared.js";
1116
import { GOOGLE_GEMINI_PROVIDER_HOOKS } from "./provider-hooks.js";
1217
import { isModernGoogleModel, resolveGoogleGeminiForwardCompatModel } from "./provider-models.js";
1318

14-
const PROVIDER_ID = "google-gemini-cli";
19+
const PROVIDER_ID = GOOGLE_GEMINI_CLI_PROVIDER_ID;
1520
const PROVIDER_LABEL = "Gemini CLI OAuth";
1621
const DEFAULT_MODEL = "google/gemini-3.1-pro-preview";
1722
const ENV_VARS = [
@@ -22,6 +27,9 @@ const ENV_VARS = [
2227
] as const;
2328

2429
let oauthRuntimeModulePromise: Promise<typeof import("./oauth.runtime.js")> | null = null;
30+
type GeminiCliExternalAuthContext = Parameters<
31+
NonNullable<ProviderPlugin["resolveExternalAuthProfiles"]>
32+
>[0];
2533

2634
const loadOauthRuntimeModule = async () => {
2735
oauthRuntimeModulePromise ??= import("./oauth.runtime.js");
@@ -32,6 +40,76 @@ async function fetchGeminiCliUsage(ctx: ProviderFetchUsageSnapshotContext) {
3240
return await fetchGeminiUsage(ctx.token, ctx.timeoutMs, ctx.fetchFn, PROVIDER_ID);
3341
}
3442

43+
function normalizeString(value: string | undefined): string | undefined {
44+
const trimmed = value?.trim();
45+
return trimmed ? trimmed : undefined;
46+
}
47+
48+
function decodeJwtPayload(token: string): Record<string, unknown> {
49+
const payload = token.split(".")[1];
50+
if (!payload) {
51+
return {};
52+
}
53+
try {
54+
const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as unknown;
55+
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
56+
? (parsed as Record<string, unknown>)
57+
: {};
58+
} catch {
59+
return {};
60+
}
61+
}
62+
63+
function readGeminiCliProfileCredential(agentDir: string, profileId: string) {
64+
const credentialsPath = resolveGeminiCliProfileCredentialsPath(agentDir, profileId);
65+
let raw: unknown;
66+
try {
67+
raw = JSON.parse(fs.readFileSync(credentialsPath, "utf8")) as unknown;
68+
} catch {
69+
return null;
70+
}
71+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
72+
return null;
73+
}
74+
const data = raw as Record<string, unknown>;
75+
const access = normalizeString(typeof data.access_token === "string" ? data.access_token : "");
76+
const refresh = normalizeString(typeof data.refresh_token === "string" ? data.refresh_token : "");
77+
const expires = data.expiry_date;
78+
if (!access || !refresh || typeof expires !== "number" || !Number.isFinite(expires)) {
79+
return null;
80+
}
81+
82+
const idToken = normalizeString(typeof data.id_token === "string" ? data.id_token : "");
83+
const identity = idToken ? decodeJwtPayload(idToken) : {};
84+
const email = normalizeString(typeof identity.email === "string" ? identity.email : "");
85+
const accountId = normalizeString(typeof identity.sub === "string" ? identity.sub : "");
86+
return {
87+
type: "oauth" as const,
88+
provider: PROVIDER_ID,
89+
access,
90+
refresh,
91+
expires,
92+
...(idToken ? { idToken } : {}),
93+
...(email ? { email } : {}),
94+
...(accountId ? { accountId } : {}),
95+
};
96+
}
97+
98+
function resolveConfiguredGeminiCliOAuthProfileIds(ctx: GeminiCliExternalAuthContext): string[] {
99+
const profileIds = new Set<string>();
100+
for (const [profileId, profile] of Object.entries(ctx.config?.auth?.profiles ?? {})) {
101+
if (profile.provider === PROVIDER_ID && profile.mode === "oauth") {
102+
profileIds.add(profileId);
103+
}
104+
}
105+
for (const [profileId, credential] of Object.entries(ctx.store.profiles)) {
106+
if (credential.provider === PROVIDER_ID && credential.type === "oauth") {
107+
profileIds.add(profileId);
108+
}
109+
}
110+
return [...profileIds].toSorted();
111+
}
112+
35113
export function buildGoogleGeminiCliProvider(): ProviderPlugin {
36114
return {
37115
id: PROVIDER_ID,
@@ -126,6 +204,16 @@ export function buildGoogleGeminiCliProvider(): ProviderPlugin {
126204
providerId: PROVIDER_ID,
127205
ctx,
128206
}),
207+
resolveExternalAuthProfiles: (ctx) => {
208+
const agentDir = normalizeString(ctx.agentDir);
209+
if (!agentDir) {
210+
return [];
211+
}
212+
return resolveConfiguredGeminiCliOAuthProfileIds(ctx).flatMap((profileId) => {
213+
const credential = readGeminiCliProfileCredential(agentDir, profileId);
214+
return credential ? [{ profileId, credential, persistence: "runtime-only" as const }] : [];
215+
});
216+
},
129217
...GOOGLE_GEMINI_PROVIDER_HOOKS,
130218
isModernModelRef: ({ modelId }) => isModernGoogleModel(modelId),
131219
formatApiKey: (cred) => formatGoogleOauthApiKey(cred),

‎extensions/google/index.test.ts‎

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Google tests cover index plugin behavior.
2-
import { mkdtemp, writeFile } from "node:fs/promises";
2+
import { createHash } from "node:crypto";
3+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
34
import os from "node:os";
45
import path from "node:path";
56
import type { Context, Model } from "openclaw/plugin-sdk/llm";
@@ -34,6 +35,80 @@ vi.mock("./oauth.runtime.js", () => ({
3435
}));
3536

3637
describe("google provider plugin hooks", () => {
38+
it("exposes staged Gemini CLI OAuth homes as runtime external auth profiles", async () => {
39+
const agentDir = await mkdtemp(path.join(os.tmpdir(), "openclaw-google-cli-auth-"));
40+
const profileId = "google-gemini-cli:[email protected]";
41+
const profileHash = createHash("sha256").update(profileId).digest("hex").slice(0, 24);
42+
const credentialsDir = path.join(
43+
agentDir,
44+
"cli-runtimes",
45+
"google-gemini-cli",
46+
"profiles",
47+
profileHash,
48+
".gemini",
49+
);
50+
const idTokenPayload = Buffer.from(
51+
JSON.stringify({ sub: "google-account-42", email: "[email protected]" }),
52+
).toString("base64url");
53+
const cfg = {
54+
auth: {
55+
profiles: {
56+
[profileId]: {
57+
provider: "google-gemini-cli",
58+
mode: "oauth",
59+
60+
},
61+
},
62+
},
63+
};
64+
try {
65+
await mkdir(credentialsDir, { recursive: true, mode: 0o700 });
66+
await writeFile(
67+
path.join(credentialsDir, "oauth_creds.json"),
68+
`${JSON.stringify({
69+
access_token: "gemini-access",
70+
refresh_token: "gemini-refresh",
71+
id_token: `header.${idTokenPayload}.signature`,
72+
expiry_date: 1_800_000_000_000,
73+
})}\n`,
74+
"utf8",
75+
);
76+
77+
const { providers } = await registerProviderPlugin({
78+
plugin: googleProviderPlugin,
79+
id: "google",
80+
name: "Google Provider",
81+
});
82+
const cliProvider = requireRegisteredProvider(providers, "google-gemini-cli");
83+
const profiles = cliProvider.resolveExternalAuthProfiles?.({
84+
config: cfg,
85+
agentDir,
86+
workspaceDir: undefined,
87+
env: process.env,
88+
store: { version: 1, profiles: {} },
89+
} as never);
90+
91+
expect(profiles).toEqual([
92+
{
93+
profileId,
94+
persistence: "runtime-only",
95+
credential: {
96+
type: "oauth",
97+
provider: "google-gemini-cli",
98+
access: "gemini-access",
99+
refresh: "gemini-refresh",
100+
expires: 1_800_000_000_000,
101+
idToken: `header.${idTokenPayload}.signature`,
102+
accountId: "google-account-42",
103+
104+
},
105+
},
106+
]);
107+
} finally {
108+
await rm(agentDir, { recursive: true, force: true });
109+
}
110+
});
111+
37112
it("owns replay policy and reasoning mode for the direct Gemini provider", async () => {
38113
const { providers } = await registerProviderPlugin({
39114
plugin: googleProviderPlugin,

‎extensions/google/openclaw.plugin.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,7 @@
666666
}
667667
},
668668
"contracts": {
669+
"externalAuthProviders": ["google-gemini-cli"],
669670
"mediaUnderstandingProviders": ["google"],
670671
"memoryEmbeddingProviders": ["gemini"],
671672
"imageGenerationProviders": ["google"],

‎src/agents/auth-profiles.readonly-sync.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import path from "node:path";
99
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
1010
import { closeOpenClawAgentDatabasesForTest } from "../state/openclaw-agent-db.js";
1111
import { AUTH_STORE_VERSION } from "./auth-profiles/constants.js";
12+
import { externalCliDiscoveryScoped } from "./auth-profiles/external-cli-discovery.js";
1213
import { loadPersistedAuthProfileStore } from "./auth-profiles/persisted.js";
1314
import { saveAuthProfileStore } from "./auth-profiles/store.js";
1415
import type { AuthProfileStore } from "./auth-profiles/types.js";
@@ -120,4 +121,48 @@ describe("auth profiles read-only external auth overlay", () => {
120121
fs.rmSync(agentDir, { recursive: true, force: true });
121122
}
122123
});
124+
125+
it("passes scoped external auth config to provider hooks", () => {
126+
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-auth-scoped-config-"));
127+
const profileId = "google-gemini-cli:[email protected]";
128+
const cfg = {
129+
auth: {
130+
profiles: {
131+
[profileId]: {
132+
provider: "google-gemini-cli",
133+
mode: "oauth" as const,
134+
135+
},
136+
},
137+
},
138+
};
139+
try {
140+
loadAuthProfileStoreForRuntime(agentDir, {
141+
readOnly: true,
142+
externalCli: externalCliDiscoveryScoped({
143+
config: cfg,
144+
providerIds: ["google-gemini-cli"],
145+
profileIds: [profileId],
146+
}),
147+
});
148+
149+
expect(resolveExternalAuthProfilesWithPluginsMock).toHaveBeenCalledTimes(1);
150+
const externalAuthCall = firstMockArg(
151+
resolveExternalAuthProfilesWithPluginsMock,
152+
"resolveExternalAuthProfilesWithPlugins",
153+
) as
154+
| {
155+
config?: unknown;
156+
context?: {
157+
config?: unknown;
158+
};
159+
}
160+
| undefined;
161+
expect(externalAuthCall?.config).toBe(cfg);
162+
expect(externalAuthCall?.context?.config).toBe(cfg);
163+
} finally {
164+
closeOpenClawAgentDatabasesForTest();
165+
fs.rmSync(agentDir, { recursive: true, force: true });
166+
}
167+
});
123168
});

‎src/agents/cli-runner/prepare.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,7 @@ export async function prepareCliRunContext(
294294
authStore = loadAuthProfileStoreForRuntime(agentDir, {
295295
readOnly: true,
296296
externalCli: externalCliDiscoveryForProviderAuth({
297+
cfg: params.config,
297298
provider: params.provider,
298299
profileId: effectiveAuthProfileId,
299300
}),
@@ -311,6 +312,7 @@ export async function prepareCliRunContext(
311312
const authProfileId = effectiveAuthProfileId;
312313
const writableAuthStore = loadAuthProfileStoreForRuntime(agentDir, {
313314
externalCli: externalCliDiscoveryForProviderAuth({
315+
cfg: params.config,
314316
provider: params.provider,
315317
profileId: authProfileId,
316318
}),
@@ -326,6 +328,7 @@ export async function prepareCliRunContext(
326328
authStore = loadAuthProfileStoreForRuntime(agentDir, {
327329
readOnly: true,
328330
externalCli: externalCliDiscoveryForProviderAuth({
331+
cfg: params.config,
329332
provider: params.provider,
330333
profileId: resolvedAuthProfileId,
331334
}),

0 commit comments

Comments
 (0)