openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
592 lines (591 loc) • 21.5 kB
JavaScript
import os from "node:os";
import path from "node:path";
import { asOptionalRecord, isRecord, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
import crypto from "node:crypto";
import fs from "node:fs/promises";
import { CliBackendAuthProfilePreparationError } from "openclaw/plugin-sdk/cli-backend";
import { replaceFileAtomic } from "openclaw/plugin-sdk/security-runtime";
import { resolvePreferredOpenClawTmpDir, tempWorkspace } from "openclaw/plugin-sdk/temp-path";
import { parse } from "dotenv";
import { extractErrorCode } from "openclaw/plugin-sdk/error-runtime";
//#region extensions/google/cli-backend-isolated-auth.runtime.ts
const GEMINI_CLI_AMBIENT_AUTH_ENV = /* @__PURE__ */ new Set([
"GEMINI_API_KEY",
"GOOGLE_API_KEY",
"GOOGLE_GENAI_USE_VERTEXAI",
"GOOGLE_APPLICATION_CREDENTIALS",
"GOOGLE_CLOUD_PROJECT",
"GOOGLE_CLOUD_PROJECT_ID",
"GOOGLE_CLOUD_QUOTA_PROJECT",
"GOOGLE_CLOUD_LOCATION"
]);
const GEMINI_CLI_UNSAFE_AUTH_ENV = [
"GOOGLE_GENAI_USE_GCA",
"CLOUD_SHELL",
"GEMINI_CLI_USE_COMPUTE_ADC"
];
const GEMINI_CLI_AUTH_SELECTOR_ENV = /* @__PURE__ */ new Set([
"GEMINI_API_KEY",
"GOOGLE_GENAI_USE_GCA",
"GOOGLE_GENAI_USE_VERTEXAI",
"CLOUD_SHELL",
"GEMINI_CLI_USE_COMPUTE_ADC"
]);
const GEMINI_CLI_TRUSTED_TRANSPORT_ENV = /* @__PURE__ */ new Set([
"GOOGLE_GEMINI_BASE_URL",
"GOOGLE_VERTEX_BASE_URL",
"GEMINI_CLI_CUSTOM_HEADERS",
"GEMINI_API_KEY_AUTH_MECHANISM",
"GOOGLE_GENAI_API_VERSION"
]);
const GEMINI_CLI_EXACT_TOOL_ENV_BARRIERS = {
GOOGLE_GENAI_USE_GCA: "false",
CLOUD_SHELL: "false",
GEMINI_CLI_USE_COMPUTE_ADC: "false",
GEMINI_TELEMETRY_LOG_PROMPTS: "false",
GEMINI_WRITE_SYSTEM_MD: "false"
};
const GEMINI_CLI_AT_INCLUDE_PATTERN = /(?<!\\)@(?:(?:"(?:[^"]*)")|(?:\\.|[^ \t\n\r,;!?()[\]{}.]|\.(?!$|[ \t\n\r])))+/u;
function isolatedCompletionInputError(e) {
const t = new Error(e);
t.name = "IsolatedCompletionInputError";
t.code = "input-rejected";
return t;
}
function isolatedCompletionUnsupportedError(e) {
const t = new Error(e);
t.name = "IsolatedCompletionUnsupportedError";
t.code = "unsupported";
return t;
}
function unsupportedExactToolAuthError(e, t) {
return e.isolatedCompletionSystemPrompt === void 0 ? new Error(t) : isolatedCompletionUnsupportedError(t);
}
function assertGeminiCliLiteralIsolatedPrompt(e) {
if (e.isolatedCompletionSystemPrompt === void 0) return false;
const t = e.isolatedCompletionPrompt;
if (t === void 0) return false;
if (GEMINI_CLI_AT_INCLUDE_PATTERN.test(t)) throw isolatedCompletionInputError("Gemini CLI isolated completion cannot safely pass native @-include syntax.");
if (t.startsWith("/") && !t.startsWith("//") && !t.startsWith("/*")) throw isolatedCompletionInputError("Gemini CLI isolated completion cannot safely pass native /command syntax.");
return true;
}
async function readGeminiCliJsonObject(e) {
const t = normalizeOptionalString(e);
if (!t) return {};
try {
const e = JSON.parse(await fs.readFile(t, "utf8"));
if (!isRecord(e)) throw new Error(`Gemini CLI system settings must be a JSON object: ${t}`);
return { ...e };
} catch (e) {
if (extractErrorCode(e) === "ENOENT") return {};
throw e;
}
}
function projectGeminiCliSafeSettings(e) {
const t = {};
const n = asOptionalRecord(e.privacy);
if (typeof n?.usageStatisticsEnabled === "boolean") t.privacy = { usageStatisticsEnabled: n.usageStatisticsEnabled };
const r = asOptionalRecord(e.telemetry);
const i = {};
if (typeof r?.enabled === "boolean") i.enabled = r.enabled;
if (typeof r?.logPrompts === "boolean") i.logPrompts = r.logPrompts;
if (Object.keys(i).length > 0) t.telemetry = i;
return t;
}
function resolveGeminiCliAmbientHome(e) {
return normalizeOptionalString(e.baseEnv?.GEMINI_CLI_HOME) ?? normalizeOptionalString(process.env.GEMINI_CLI_HOME) ?? os.homedir();
}
function projectGeminiCliTrustedTransportEnv(e, t) {
return Object.fromEntries([...GEMINI_CLI_TRUSTED_TRANSPORT_ENV].map((n) => [n, normalizeOptionalString(e.baseEnv?.[n]) ?? normalizeOptionalString(process.env[n]) ?? normalizeOptionalString(t.transport[n]) ?? ""]));
}
async function readGeminiCliAmbientAuthEnv(e) {
try {
const t = parse(await fs.readFile(e, "utf8"));
const n = t.GEMINI_TELEMETRY_ENABLED?.trim().toLowerCase();
return {
auth: Object.fromEntries(Object.entries(t).filter(([e]) => GEMINI_CLI_AMBIENT_AUTH_ENV.has(e))),
transport: Object.fromEntries(Object.entries(t).filter(([e]) => GEMINI_CLI_TRUSTED_TRANSPORT_ENV.has(e))),
unsafeAuth: Object.fromEntries(Object.entries(t).filter(([e]) => GEMINI_CLI_UNSAFE_AUTH_ENV.includes(e))),
...n ? { telemetryEnabled: n === "true" || n === "1" } : {}
};
} catch (e) {
if (extractErrorCode(e) === "ENOENT") return;
throw e;
}
}
async function loadGeminiCliAmbientEnv(e) {
const t = resolveGeminiCliAmbientHome(e);
for (const e of [path.join(t, ".gemini", ".env"), path.join(t, ".env")]) {
const t = await readGeminiCliAmbientAuthEnv(e);
if (t !== void 0) return t;
}
return {
auth: {},
transport: {},
unsafeAuth: {}
};
}
async function resolveGeminiCliTrustedTransportEnv(e) {
return projectGeminiCliTrustedTransportEnv(e, await loadGeminiCliAmbientEnv(e));
}
async function resolveGeminiCliAmbientAuth(e) {
const t = resolveGeminiCliAmbientHome(e);
const n = await readGeminiCliJsonObject(path.join(t, ".gemini", "settings.json"));
const r = await readGeminiCliJsonObject(e.systemSettingsPath);
const i = asOptionalRecord(asOptionalRecord(n.security)?.auth);
const a = asOptionalRecord(asOptionalRecord(r.security)?.auth);
const o = await loadGeminiCliAmbientEnv(e);
const s = [...GEMINI_CLI_AUTH_SELECTOR_ENV].some((t) => {
const n = normalizeOptionalString(e.baseEnv?.[t]);
return n !== void 0 && n !== "false" && n !== "0";
});
const c = normalizeOptionalString(a?.selectedType);
const l = normalizeOptionalString(i?.selectedType);
const u = c ?? (s ? void 0 : l);
const d = normalizeOptionalString(a?.enforcedType);
if (d && d !== "gemini-api-key" && d !== "vertex-ai") throw unsupportedExactToolAuthError(e, "Gemini CLI exact tool availability supports only API-key or Vertex auth; Code Assist auth can inject administrator-required tools.");
const envValue = (t) => {
const n = normalizeOptionalString(e.baseEnv?.[t]);
if (n !== void 0) return n;
if (s && GEMINI_CLI_AUTH_SELECTOR_ENV.has(t)) return;
return normalizeOptionalString(process.env[t]) ?? normalizeOptionalString(o.auth[t]) ?? normalizeOptionalString(o.unsafeAuth[t]);
};
const f = u ?? (envValue("GOOGLE_GENAI_USE_GCA") === "true" ? "oauth-personal" : envValue("GOOGLE_GENAI_USE_VERTEXAI") === "true" ? "vertex-ai" : envValue("GEMINI_API_KEY") ? "gemini-api-key" : envValue("CLOUD_SHELL") === "true" || envValue("GEMINI_CLI_USE_COMPUTE_ADC") === "true" ? "compute-default-credentials" : void 0);
if (f !== "gemini-api-key" && f !== "vertex-ai") throw unsupportedExactToolAuthError(e, "Gemini CLI exact tool availability supports only API-key or Vertex auth; Code Assist auth can inject administrator-required tools.");
if (d !== void 0 && d !== f) throw new Error(`Gemini CLI system settings enforce ${d} auth, but exact tool availability resolved ${f}.`);
const p = {
...Object.fromEntries([...GEMINI_CLI_AMBIENT_AUTH_ENV].map((e) => [e, ""])),
...GEMINI_CLI_EXACT_TOOL_ENV_BARRIERS,
...projectGeminiCliTrustedTransportEnv(e, o)
};
for (const e of GEMINI_CLI_AMBIENT_AUTH_ENV) {
const t = envValue(e);
if (t) p[e] = t;
}
const m = normalizeOptionalString(p.GOOGLE_APPLICATION_CREDENTIALS);
if (m && !path.isAbsolute(m)) {
const t = normalizeOptionalString(e.workspaceDir);
if (!t) throw new Error("Gemini exact tool availability cannot resolve relative GOOGLE_APPLICATION_CREDENTIALS without a workspace.");
p.GOOGLE_APPLICATION_CREDENTIALS = path.resolve(t, m);
}
const h = projectGeminiCliSafeSettings(n);
if (o.telemetryEnabled === false) h.telemetry = {
...asOptionalRecord(h.telemetry),
enabled: false
};
return {
selectedType: u,
envOverrides: p,
safeSettings: h
};
}
//#endregion
//#region extensions/google/gemini-cli-auth-home.ts
const GOOGLE_GEMINI_CLI_PROVIDER_ID = "google-gemini-cli";
function resolveGeminiCliProfileHome$1(e, t) {
const n = crypto.createHash("sha256").update(t).digest("hex").slice(0, 24);
return path.join(e, `${GOOGLE_GEMINI_CLI_PROVIDER_ID}-home`, "profiles", n);
}
//#endregion
//#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 };