UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

416 lines (415 loc) • 14.3 kB
import { l as normalizeOptionalString } from "../../string-coerce-CCIiB4H7.mjs"; import { a as asOptionalRecord, l as isRecord } from "../../record-coerce-CVPuDqcc.mjs"; import { n as resolvePreferredOpenClawTmpDir } from "../../tmp-openclaw-dir-Bf0oU1Cn.mjs"; import "../../string-coerce-runtime-BwAZZDf5.mjs"; import { r as replaceFileAtomic } from "../../security-runtime-C-zE_Zy_.mjs"; import { t as tempWorkspace } from "../../fs-safe-compat-Cbx7s6au.mjs"; import { t as CliBackendAuthProfilePreparationError } from "../../cli-backend-errors-CqOz9I6N.mjs"; import "../../temp-path-CW7QMeae.mjs"; import { n as resolveGeminiCliProfileHome$1, t as GOOGLE_GEMINI_CLI_PROVIDER_ID } from "../../gemini-cli-auth-home-DngmW3qy.mjs"; import { a as readGeminiCliJsonObject, i as isolatedCompletionUnsupportedError, n as assertGeminiCliLiteralIsolatedPrompt, o as resolveGeminiCliAmbientAuth, r as isolatedCompletionInputError, s as resolveGeminiCliTrustedTransportEnv, t as GEMINI_CLI_EXACT_TOOL_ENV_BARRIERS } from "../../cli-backend-isolated-auth.runtime-CatFbc5q.mjs"; import path from "node:path"; import crypto from "node:crypto"; import fs from "node:fs/promises"; //#region extensions/google/cli-backend-auth.runtime.ts const GOOGLE_PROVIDER_ID = "google"; const VERCEL_AI_GATEWAY_PROVIDER_ID = "vercel-ai-gateway"; const GEMINI_CLI_CREDENTIALS_FILENAME = "gemini-credentials.json"; const GEMINI_CLI_PROFILE_AUTH_ENV = [...[ ...[ "GOOGLE_GENAI_USE_GCA", "GOOGLE_CLOUD_ACCESS_TOKEN", "GOOGLE_APPLICATION_CREDENTIALS", "GEMINI_FORCE_ENCRYPTED_FILE_STORAGE", "GEMINI_FORCE_FILE_STORAGE" ], "GOOGLE_GENAI_USE_VERTEXAI", "GOOGLE_API_KEY", "GOOGLE_CLOUD_PROJECT", "GOOGLE_CLOUD_PROJECT_ID", "GOOGLE_CLOUD_QUOTA_PROJECT", "GOOGLE_CLOUD_LOCATION", "GOOGLE_GEMINI_BASE_URL", "GEMINI_CLI_CUSTOM_HEADERS", "GEMINI_API_KEY_AUTH_MECHANISM" ], "GEMINI_API_KEY"]; const GEMINI_CLI_PROFILE_SETTINGS_ENV = ["GEMINI_CLI_SYSTEM_SETTINGS_PATH"]; const GEMINI_CLI_SUPPORTED_AUTH_GUIDANCE = "Open Models settings and connect Google with an AI Studio API key, then select that profile for this model."; function throwUnsupportedGeminiCredential(e) { if (e.provider === VERCEL_AI_GATEWAY_PROVIDER_ID) throw new Error("Gemini CLI execution cannot use a vercel-ai-gateway auth profile. Use the OpenClaw vercel-ai-gateway provider instead."); throw new Error("Gemini CLI execution requires a google-gemini-cli auth profile."); } function throwUnstageableSelectedGeminiProfile(e, t) { if (!normalizeOptionalString(e.authProfileId)) throw new Error("Gemini CLI execution requires a selected auth profile."); if (!t) throw new CliBackendAuthProfilePreparationError(`Gemini CLI auth profile was selected but no credential material was found. ${GEMINI_CLI_SUPPORTED_AUTH_GUIDANCE}`); if (t.provider !== "google-gemini-cli") throwUnsupportedGeminiCredential(t); throw new Error(`Gemini CLI execution requires a Google AI Studio API-key profile or a previously configured valid Gemini CLI OAuth profile. ${GEMINI_CLI_SUPPORTED_AUTH_GUIDANCE}`); } function requireGeminiOAuthCredential(e) { if (e?.type !== "oauth") return null; if (e.provider !== "google-gemini-cli") throwUnsupportedGeminiCredential(e); const t = normalizeOptionalString(e.access); const n = normalizeOptionalString(e.refresh); if (!t || !n || typeof e.expires !== "number" || !Number.isFinite(e.expires)) throw new CliBackendAuthProfilePreparationError(`Gemini CLI OAuth profile is incomplete and cannot be repaired by OpenClaw. ${GEMINI_CLI_SUPPORTED_AUTH_GUIDANCE}`); return { ...e, type: "oauth", provider: GOOGLE_GEMINI_CLI_PROVIDER_ID, access: t, refresh: n, expires: e.expires, idToken: normalizeOptionalString(e.idToken), projectId: normalizeOptionalString(e.projectId) }; } function requireGeminiApiKeyCredential(e) { if (e?.type !== "api_key") return null; if (e.provider !== "google-gemini-cli" && e.provider !== GOOGLE_PROVIDER_ID) throwUnsupportedGeminiCredential(e); const t = normalizeOptionalString(e.key); if (!t) throw new CliBackendAuthProfilePreparationError("Gemini CLI API-key profile is missing usable key material."); return { ...e, type: "api_key", provider: e.provider, key: t }; } function resolveGeminiCliProfileHome(e) { const t = normalizeOptionalString(e.agentDir); if (!t) throw new Error("Gemini CLI auth profile execution requires an agent directory."); const n = normalizeOptionalString(e.authProfileId); if (!n) throw new Error("Gemini CLI auth profile execution requires a selected auth profile."); const r = resolveGeminiCliProfileHome$1(t, n); return { home: r, geminiDir: path.join(r, ".gemini") }; } function readGeminiAuthProfileCredential(e) { if (!isRecord(e)) return; return e; } async function buildGeminiCliSystemSettings(e, t, n = {}) { const r = await readGeminiCliJsonObject(e.systemSettingsPath); const i = asOptionalRecord(n.privacy); const a = asOptionalRecord(r.privacy); const o = asOptionalRecord(n.telemetry); const s = asOptionalRecord(r.telemetry); let c = { ...n, ...r, ...i || a ? { privacy: { ...i, ...a } } : {}, ...o || s ? { telemetry: { ...o, ...s } } : {} }; if (t) { const e = { ...asOptionalRecord(c.security) }; const n = { ...asOptionalRecord(e.auth) }; const r = normalizeOptionalString(n.enforcedType); if (r && r !== t) throw new Error(`Gemini CLI system settings enforce ${r} auth, but the selected OpenClaw profile requires ${t}.`); e.auth = { ...n, selectedType: t }; c = { ...c, security: e }; } return applyGeminiCliIsolatedCompletionSettings(e.toolAvailability ? applyGeminiCliToolAvailability(c, e.toolAvailability) : c, e); } function applyGeminiCliIsolatedCompletionSettings(e, t) { if (t.isolatedCompletionSystemPrompt === void 0) return e; const n = normalizeOptionalString(t.isolatedCompletionModelId); if (!n || n === "auto" || n.startsWith("auto-")) throw isolatedCompletionInputError("Gemini isolated completion requires one concrete model id."); const r = { model: n, isLastResort: true, actions: { terminal: "prompt", transient: "prompt", not_found: "prompt", unknown: "prompt" }, stateTransitions: { terminal: "terminal", transient: "terminal", not_found: "terminal", unknown: "terminal" } }; const i = { default: n }; return { ...e, general: { ...asOptionalRecord(e.general), maxAttempts: 1, retryFetchErrors: false }, experimental: { ...asOptionalRecord(e.experimental), dynamicModelConfiguration: true, gemmaModelRouter: { enabled: false } }, modelConfigs: { aliases: {}, customAliases: {}, overrides: [], customOverrides: [], modelIdResolutions: { [n]: i }, classifierIdResolutions: { flash: i, pro: i }, modelChains: { preview: [r], default: [r], lite: [r], [n]: [r] } }, context: { includeDirectoryTree: false, discoveryMaxDirs: 1, memoryBoundaryMarkers: [], includeDirectories: [], loadMemoryFromIncludeDirectories: false }, telemetry: { ...asOptionalRecord(e.telemetry), logPrompts: false } }; } function applyGeminiCliToolAvailability(e, t) { if (t.native.length > 0) throw new Error("Gemini CLI cannot expose backend-native tools in an exact restricted run."); const n = asOptionalRecord(e.mcpServers); const r = t.openClaw.length > 0; let i = {}; if (r) { const e = n?.openclaw; if (!isRecord(e)) throw new Error("Gemini CLI exact tool availability requires the OpenClaw MCP server."); i = { openclaw: { ...e, includeTools: [...t.openClaw] } }; } const { allowed: a, core: o, discoveryCommand: s, callCommand: c, ...l } = asOptionalRecord(e.tools) ?? {}; const { serverCommand: u, ...d } = asOptionalRecord(e.mcp) ?? {}; const f = r ? ["openclaw"] : [crypto.randomUUID()]; const p = asOptionalRecord(e.agents); const m = asOptionalRecord(p?.overrides); return { ...e, tools: { ...l, core: r ? ["mcp_openclaw_*"] : [], discoveryCommand: "", callCommand: "" }, mcp: { ...d, allowed: f, serverCommand: "" }, mcpServers: i, experimental: { ...asOptionalRecord(e.experimental), enableAgents: false }, agents: { ...p, overrides: { ...m, codebase_investigator: { ...asOptionalRecord(m?.codebase_investigator), enabled: false }, cli_help: { ...asOptionalRecord(m?.cli_help), enabled: false } } }, hooksConfig: { ...asOptionalRecord(e.hooksConfig), enabled: false }, skills: { ...asOptionalRecord(e.skills), enabled: false } }; } async function writeGeminiCliJson(e, t) { await writeGeminiCliPrivateFile(e, `${JSON.stringify(t, null, 2)}\n`); } async function writeGeminiCliPrivateFile(e, t) { const n = await fs.realpath(path.dirname(e)); await replaceFileAtomic({ filePath: path.join(n, path.basename(e)), content: t }); } async function stageGeminiCliIsolatedCwd(e) { const t = normalizeOptionalString(e.isolatedCompletionCwd); if (!t) return; await writeGeminiCliPrivateFile(path.join(t, ".env"), ""); } async function clearGeminiCliCachedCredentials(e) { await fs.rm(path.join(e, GEMINI_CLI_CREDENTIALS_FILENAME), { force: true }); } function buildGeminiCliProjectEnv(e) { const t = normalizeOptionalString(e); if (!t) return {}; return { GOOGLE_CLOUD_PROJECT: t, GOOGLE_CLOUD_PROJECT_ID: t, GOOGLE_CLOUD_QUOTA_PROJECT: t }; } async function prepareGeminiCliCredentialHome(e, t) { const n = requireGeminiOAuthCredential(t) ?? requireGeminiApiKeyCredential(t); if (!n) return null; const r = n.type === "oauth"; const i = e.toolAvailability !== void 0; if (r && i) { const t = "Gemini CLI exact tool availability does not support OAuth; Code Assist auth can inject administrator-required tools."; throw e.isolatedCompletionSystemPrompt === void 0 ? /* @__PURE__ */ new Error(t) : isolatedCompletionUnsupportedError(t); } const a = !r && assertGeminiCliLiteralIsolatedPrompt(e); const o = i ? await resolveGeminiCliTrustedTransportEnv(e) : void 0; const s = r ? "oauth-personal" : "gemini-api-key"; const c = { security: { auth: { selectedType: s } } }; const l = await buildGeminiCliSystemSettings(e, s); const u = e.isolatedCompletionSystemPrompt !== void 0; const d = e.toolAvailability !== void 0; const f = u || d ? void 0 : resolveGeminiCliProfileHome(e); const p = await tempWorkspace({ rootDir: resolvePreferredOpenClawTmpDir(), prefix: "openclaw-gemini-cli-" }); const { home: m, geminiDir: h } = f ?? { home: path.join(p.dir, "home"), geminiDir: path.join(p.dir, "home", ".gemini") }; const g = p.path("settings.json"); const _ = e.isolatedCompletionSystemPrompt; const v = u ? p.path("system.md") : void 0; const beforeProfileExecution = async () => { await stageGeminiCliIsolatedCwd(e); await fs.mkdir(h, { recursive: true, mode: 448 }); await fs.chmod(m, 448); await fs.chmod(h, 448); await Promise.all([ writeGeminiCliJson(path.join(h, "settings.json"), c), writeGeminiCliJson(path.join(m, "settings.json"), c), writeGeminiCliJson(g, l), ...v && _ !== void 0 ? [writeGeminiCliPrivateFile(v, _)] : [] ]); }; return { env: { GEMINI_CLI_HOME: m, GEMINI_CLI_SYSTEM_SETTINGS_PATH: g, GEMINI_FORCE_FILE_STORAGE: "true", ...r ? buildGeminiCliProjectEnv(n.projectId) : { GEMINI_API_KEY: n.key }, ...i ? GEMINI_CLI_EXACT_TOOL_ENV_BARRIERS : {}, ...o, ...v ? { GEMINI_SYSTEM_MD: v, GEMINI_TELEMETRY_LOG_PROMPTS: "false" } : {} }, clearEnv: [ ...GEMINI_CLI_PROFILE_AUTH_ENV, ...GEMINI_CLI_PROFILE_SETTINGS_ENV, ...i ? ["GEMINI_CLI_HOME"] : [], ...v ? [ "GEMINI_SYSTEM_MD", ...r ? ["GEMINI_CLI_HOME"] : [], "GEMINI_TELEMETRY_LOG_PROMPTS" ] : [], ...i ? Object.keys(GEMINI_CLI_EXACT_TOOL_ENV_BARRIERS) : [], ...Object.keys(o ?? {}) ], beforeExecution: async () => { await beforeProfileExecution(); const e = path.join(h, "oauth_creds.json"); if (r) { await clearGeminiCliCachedCredentials(h); await writeGeminiCliJson(e, { access_token: n.access, refresh_token: n.refresh, expiry_date: n.expires, token_type: "Bearer", ...n.idToken ? { id_token: n.idToken } : {} }); } else await Promise.all([fs.rm(e, { force: true }), clearGeminiCliCachedCredentials(h)]); }, cleanup: p[Symbol.asyncDispose], ...a ? { isolatedCompletionEnforced: true } : {} }; } async function prepareGeminiCliRestrictedSystemSettings(e) { const t = e.isolatedCompletionSystemPrompt !== void 0; const n = assertGeminiCliLiteralIsolatedPrompt(e); const r = await resolveGeminiCliAmbientAuth(e); const i = await buildGeminiCliSystemSettings(e, r.selectedType, r.safeSettings); const a = await tempWorkspace({ rootDir: resolvePreferredOpenClawTmpDir(), prefix: "openclaw-gemini-cli-policy-" }); const o = a.path("settings.json"); const s = e.isolatedCompletionSystemPrompt; const c = t ? a.path("system.md") : void 0; const l = path.join(a.dir, "home"); return { env: { GEMINI_CLI_SYSTEM_SETTINGS_PATH: o, GEMINI_CLI_HOME: l, ...c ? { GEMINI_SYSTEM_MD: c } : {}, ...t ? { GEMINI_TELEMETRY_LOG_PROMPTS: "false" } : {}, ...r.envOverrides }, clearEnv: [ ...GEMINI_CLI_PROFILE_AUTH_ENV, ...GEMINI_CLI_PROFILE_SETTINGS_ENV, "GEMINI_CLI_HOME", ...c ? ["GEMINI_SYSTEM_MD", "GEMINI_TELEMETRY_LOG_PROMPTS"] : [], ...Object.keys(r.envOverrides) ], beforeExecution: async () => { await stageGeminiCliIsolatedCwd(e); await fs.mkdir(l, { recursive: true, mode: 448 }); await fs.chmod(l, 448); await Promise.all([writeGeminiCliJson(o, i), ...c && s !== void 0 ? [writeGeminiCliPrivateFile(c, s)] : []]); }, cleanup: a[Symbol.asyncDispose], toolAvailabilityEnforced: true, ...n ? { isolatedCompletionEnforced: true } : {} }; } async function prepareGeminiCliExecution(e, t) { const n = readGeminiAuthProfileCredential(t); const r = await prepareGeminiCliCredentialHome(e, n); if (r) return e.toolAvailability ? { ...r, toolAvailabilityEnforced: true } : r; if (normalizeOptionalString(e.authProfileId)) throwUnstageableSelectedGeminiProfile(e, n); return e.toolAvailability ? await prepareGeminiCliRestrictedSystemSettings(e) : null; } //#endregion export { prepareGeminiCliExecution };