UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

138 lines (137 loc) • 6.82 kB
import { r as resolvePathViaExistingAncestorSync } from "./boundary-path-C2gXEiXe.mjs"; import { o as registerSecretValueForRedaction } from "./secret-redaction-registry-Cy0acctn.mjs"; import { r as normalizeProviderId, t as findNormalizedProviderKey } from "./provider-id-b5XGSf9C.mjs"; import { n as normalizeSecretInput } from "./normalize-secret-input-Cxkx67Fv.mjs"; import { d as isUserModelAuthProfileId, t as AuthProfileCredentialPublicationPendingError } from "./user-model-account-authority-CRj924IP.mjs"; import { S as attachRuntimeConfigWriteApplication, w as createRuntimeConfigWriteApplication } from "./io.runtime-DsJ2dLCQ.mjs"; import { a as captureGatewayRootWorkAdmissionContinuationScope } from "./gateway-work-admission-79pid1hQ.mjs"; import { d as resolveSharedAuthStorePath } from "./path-resolve-CpNl_n1M.mjs"; import { a as resolveAuthProfileOrder } from "./order-jOvee2J6.mjs"; import { g as resolveProviderConfigSecretInput, v as resolveProviderEntryApiKeyProfileReference } from "./model-auth-provider-config-Bnc4upRS.mjs"; import { c as ensureAuthProfileStoreWithoutExternalProfilesAsync, y as resolvePersistedAuthProfileOwnerAgentDirAsync } from "./store-runtime-dW0pXLJI.mjs"; import { d as upsertAuthProfileWithLockOrThrow, v as listCandidateAuthProfileStores, y as prepareCandidateAuthProfileCredentialRead } from "./profiles-DbLHYG1P.mjs"; import "./auth-profiles-VRLhewIH.mjs"; import { t as applyAuthProfileConfig } from "./provider-auth-helpers-ByDXB7Po.mjs"; import { i as loadValidConfigSnapshotOrThrow, u as updateConfig } from "./shared-jZuoMzdG.mjs"; import { a as validateOpenAICodexApiKeyInput, i as resolveDefaultTokenProfileId, n as normalizeManualAuthProvider } from "./auth-manual-input-DeJ4s3kg.mjs"; import { isDeepStrictEqual } from "node:util"; //#region src/commands/models/auth-api-key.ts /** Saves a manual key without changing model selection or connection settings. */ async function saveModelProviderApiKey(e) { const t = normalizeManualAuthProvider(e.provider); const n = normalizeSecretInput(e.apiKey); registerSecretValueForRedaction(n); const r = !n ? "API key is required" : t === "openai" ? validateOpenAICodexApiKeyInput(n) : void 0; if (r) throw new Error(r); const i = e.config ?? (await loadValidConfigSnapshotOrThrow()).runtimeConfig; const validateCurrentCredential = (e) => { if (e?.type === "api_key" && e.keyRef) throw new Error("This API-key profile uses an external secret reference. Remove that saved sign-in before storing an inline key."); if (e && (e.type !== "api_key" || normalizeProviderId(e.provider) !== t)) throw new Error("The API-key profile belongs to another sign-in. Manage that saved sign-in first."); }; const configuredKey = (e) => { const n = findNormalizedProviderKey(e.models?.providers, t); const r = n ? e.models?.providers?.[n] : void 0; if (r?.auth && r.auth !== "api-key") throw new Error("This connection uses another sign-in method. Use its sign-in option instead."); return n; }; const configuredBinding = (e, t) => { const { providerConfig: n, ref: r } = resolveProviderConfigSecretInput(e, t); return r ?? n?.apiKey; }; const a = e.profileId ? void 0 : configuredKey(i); const o = a === void 0 ? void 0 : configuredBinding(i, a); const s = await ensureAuthProfileStoreWithoutExternalProfilesAsync(e.agentDir); const c = !a ? resolveAuthProfileOrder({ cfg: i, store: s, provider: t }).find((e) => { const t = s.profiles[e]; return t?.type === "api_key" && !t.keyRef; }) : void 0; const l = a ? resolveProviderEntryApiKeyProfileReference({ cfg: i, provider: a, store: s }) : void 0; const u = l?.kind === "profile" || l?.kind === "profile-incompatible" ? l.profileId : void 0; const d = e.profileId ?? u ?? c ?? resolveDefaultTokenProfileId(t); if (isUserModelAuthProfileId(d)) throw new Error("Personal model accounts are managed in Settings → Profile → Connected accounts."); const f = a ? void 0 : s.profiles[d] ? await resolvePersistedAuthProfileOwnerAgentDirAsync({ agentDir: e.agentDir, profileId: d }) : e.agentDir; const p = a ? (await listCandidateAuthProfileStores({ cfg: i })).filter((e) => e.databasePath !== resolvePathViaExistingAncestorSync(resolveSharedAuthStorePath())) : []; const m = await Promise.all(p.map((e) => prepareCandidateAuthProfileCredentialRead(e, d))); const validateSharedBinding = () => { if (m.some((e) => e.readCurrentCredential())) throw new Error("An agent already overrides this shared key. Remove that agent's override before replacing the shared key."); }; const validateReplacement = (t) => { e.assertCurrent?.(); validateSharedBinding(); validateCurrentCredential(t); }; const withCurrentCredentials = async (t) => { for (;;) try { return await t(); } catch (t) { if (!(t instanceof AuthProfileCredentialPublicationPendingError)) throw t; await t.waitUntilCurrent(); e.assertCurrent?.(); } }; await withCurrentCredentials(async () => { validateReplacement(s.profiles[d]); await upsertAuthProfileWithLockOrThrow({ profileId: d, credential: { type: "api_key", provider: t, key: n }, agentDir: f, preserveApiKeyMetadata: true, resetFailureState: true, validateCurrentCredential: validateReplacement, assertCurrent: e.assertCurrent }); }); const h = createRuntimeConfigWriteApplication(captureGatewayRootWorkAdmissionContinuationScope()?.run); let g = false; await updateConfig((n) => withCurrentCredentials(() => { validateSharedBinding(); e.assertCurrent?.(); const r = e.profileId ? void 0 : configuredKey(n); if (!e.profileId && (r !== a || r !== void 0 && !isDeepStrictEqual(configuredBinding(n, r), o))) throw new Error("The provider connection changed during the key update. Reopen the connection and save the key again"); let i = applyAuthProfileConfig(n, { ...n.auth?.profiles?.[d], profileId: d, provider: t, mode: "api_key" }); if (r && i.models?.providers?.[r]) i = { ...i, models: { ...i.models, providers: { ...i.models.providers, [r]: { ...i.models.providers[r], apiKey: d } } } }; g = !isDeepStrictEqual(n, i); return i; }), void 0, e.assertCurrent, attachRuntimeConfigWriteApplication({ assertCurrent: e.assertCurrent }, h)).catch((e) => { throw new Error("API key saved, but provider settings could not be applied: " + (e instanceof Error ? e.message : String(e)) + ". Reopen Models and save the key again.", { cause: e }); }); if (g && !(h.claimed && await h.result === "applied")) return { profileId: d, warning: "API key saved, but the Gateway has not confirmed applying the provider settings. Run `openclaw gateway restart` to apply them." }; return { profileId: d }; } //#endregion export { saveModelProviderApiKey as t };