UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

530 lines (529 loc) • 18.9 kB
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import "./utils-C8YECn2Q.mjs"; import "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { g as resolveDefaultAgentDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs"; import { G as getScopedAuthProfileEnv } from "./user-model-account-authority-CRj924IP.mjs"; import { a as resolveMergedModelProviderConfig } from "./model-provider-config-Bbah_2ON.mjs"; import { a as isAuthModeAllowedForModel, i as assertAuthModeAllowedForModel } from "./model-runtime-policy-Cfudvy7O.mjs"; import { c as mintSecretSentinel, s as looksLikeSecretSentinel } from "./sentinel-BfPjneyJ.mjs"; import { r as isFailedOAuthRefreshFence } from "./oauth-refresh-marker-Bm1Qb0ET.mjs"; import { b as resolveAuthProfileDatabasePath } from "./sqlite-B2CoJ4Om.mjs"; import { d as resolveSharedAuthStorePath } from "./path-resolve-CpNl_n1M.mjs"; import { a as assertAuthProfileMigrationStateAtDatabasePath, c as hasLegacyAuthProfileCredentialSourceAsync } from "./legacy-source-diagnostic-cbBtIQVj.mjs"; import { n as SecretSurfaceUnavailableError } from "./runtime-degraded-state-BSnwk5PQ.mjs"; import { n as OAuthRefreshFailureError, o as buildOAuthRefreshFailureLoginCommand } from "./oauth-refresh-failure-DxrQiYzV.mjs"; import { a as resolveAuthProfileOrder, f as listProfilesForProvider, n as isStoredCredentialCompatibleWithAuthProvider } from "./order-jOvee2J6.mjs"; import { l as isNonSecretApiKeyMarker, p as resolveExplicitProviderNoAuth } from "./model-auth-markers-4YSUG71a.mjs"; import { g as resolveManagedSecretRefRuntimeProviderAuth, h as assertRuntimeProviderSecretOwnerAvailable, m as resolveProviderAuthScope } from "./loader-runtime-load-Ba16vW6K.mjs"; import { n as externalCliDiscoveryForProviderAuth } from "./external-cli-discovery-DZ419koV.mjs"; import { C as shouldUseImplicitAwsSdkAuth, E as assertProviderAuthSupportsHttp, M as resolveDirectProviderCredentialMode, S as shouldPreferExplicitConfigApiKeyAuth, T as ProviderAuthError, _ as resolveProviderEntryApiKeyBinding, b as resolveUsableCustomProviderApiKey, c as profileTypeToAuthMode, d as resolveAwsSdkAuthInfo, f as resolveConfigAwareEnvApiKey, h as resolveProviderAuthOverride, l as projectResolvedProfileAuth, o as isConfigBackedInlineProviderApiKey, p as resolveConfiguredAwsSdkProfileAuth, t as assertInlineProviderApiKeyUsable, v as resolveProviderEntryApiKeyProfileReference, x as sentinelizeConfigSecretRefEnvApiKey } from "./model-auth-provider-config-Bnc4upRS.mjs"; import { f as resolveOwningPluginIdsForProviderRef } from "./providers-B9AkUbSZ.mjs"; import { f as loadAuthProfileStoreForRuntimeAsync, i as ensureAuthProfileStoreAsync, r as ensureAuthProfileStore } from "./store-runtime-dW0pXLJI.mjs"; import { A as shouldDeferProviderSyntheticProfileAuthWithPlugin, _ as resolvePluginOwnedProviderAuth, b as resolveProviderDeprecatedAuthProfileIds, r as buildProviderMissingAuthMessageWithPlugin } from "./provider-runtime-BddjXkmv.mjs"; import { i as resolveAuthStorePathForDisplayAsync } from "./paths-BSElhsGi.mjs"; import { n as resolveApiKeyForProfile } from "./oauth--EeX6RHc.mjs"; import "./auth-profiles-VRLhewIH.mjs"; import { t as resolveModelProviderAuthConfig } from "./model-auth-provider-route-nEDhMXpO.mjs"; import { i as prepareSyntheticLocalProviderAuth } from "./model-auth-runtime-BVYiZt5s.mjs"; //#region src/agents/model-auth-provider-admission.ts async function assertProviderAuthReady(e) { const t = cloneEnvWithPlatformSemantics(getScopedAuthProfileEnv() ?? process.env); t.OPENCLAW_STATE_DIR = resolveStateDir(t); const n = e.agentDir ? resolveAuthProfileDatabasePath(e.agentDir) : void 0; if (await hasLegacyAuthProfileCredentialSourceAsync(e.agentDir, t)) await loadAuthProfileStoreForRuntimeAsync(e.agentDir, { migrationProvider: e.provider, config: e.cfg, readOnly: true, externalCli: { mode: "none" } }, t); assertAuthProfileMigrationStateAtDatabasePath(n ?? resolveSharedAuthStorePath(t), e.provider, e.cfg); assertRuntimeProviderSecretOwnerAvailable({ cfg: e.cfg, provider: e.provider }); } //#endregion //#region src/agents/model-auth-provider.ts /** * Ordered credential resolution for one provider request. */ const log = createSubsystemLogger("model-auth"); function assertAuthProfileNotRetired(e) { if (!e.deprecatedProfileIds.has(e.profileId)) return; throw new Error(`Auth profile "${e.profileId}" is retired. Run ${formatCliCommand("openclaw doctor --fix")}.`); } function shouldDeferSyntheticProfileAuth(e) { const t = resolveMergedModelProviderConfig(e.cfg, e.provider); return shouldDeferProviderSyntheticProfileAuthWithPlugin({ provider: e.provider, config: e.cfg, modelApi: e.modelApi, context: { config: e.cfg, provider: e.provider, providerConfig: t, resolvedApiKey: e.resolvedApiKey } }) === true; } /** @deprecated Use resolveScopedAuthProfileStoreAsync to read through the auth owner worker. */ function resolveScopedAuthProfileStore(e) { return ensureAuthProfileStore(void 0, { migrationProvider: e.provider, config: e.cfg, externalCli: externalCliDiscoveryForProviderAuth(e) }); } async function resolveScopedAuthProfileStoreAsync(e) { return ensureAuthProfileStoreAsync(e.agentDir, { migrationProvider: e.provider, config: e.cfg, profileId: e.profileId, externalCli: externalCliDiscoveryForProviderAuth(e) }); } /** Resolves a stored provider-entry binding without general credential discovery. */ async function resolveProviderEntryApiKeyAuth(e) { e.signal?.throwIfAborted(); const { provider: t, cfg: n } = e; await assertProviderAuthReady(e); const r = resolveProviderEntryApiKeyProfileReference(e); if (!("profileId" in r)) return; assertAuthProfileNotRetired({ profileId: r.profileId, deprecatedProfileIds: new Set(resolveProviderDeprecatedAuthProfileIds({ provider: t, config: n })) }); const i = await resolveProviderEntryApiKeyBinding(e); e.signal?.throwIfAborted(); if (i.kind === "profile-resolved") { assertAuthModeAllowedForModel({ provider: t, modelApi: e.modelApi, modelBaseUrl: e.modelBaseUrl, capability: e.capability, profileId: i.auth.profileId ?? t, mode: i.auth.mode, authFlow: i.auth.authFlow }); return i.auth; } if (i.kind === "profile-incompatible") { const e = i.reason === "credential-class" ? "which is not a bearer-style auth class" : "which is not compatible with this provider entry's auth binding"; const n = i.reason === "credential-class" ? "Use an api-key or token profile, or set apiKey to a literal bearer token." : "Use a compatible provider auth alias, configure the referenced provider entry with the same baseUrl, or set apiKey to a literal bearer token."; throw new Error(`Per-entry apiKey "${i.profileId}" for provider "${t}" references a "${i.credentialType}" credential for provider "${i.credentialProvider}", ${e}. ${n}`); } if (i.kind === "profile-unresolved") { const e = i.error ? formatErrorMessage(i.error) : "credential resolution returned no key"; throw new Error(`Per-entry apiKey "${i.profileId}" for provider "${t}" matched a stored profile but failed to resolve: ${e}. Fix the referenced profile or set apiKey to a literal bearer token.`); } } /** Resolves the credential that should be used for one provider request. */ async function resolveApiKeyForProviderCore(e) { e.signal?.throwIfAborted(); const t = { provider: e.provider, config: e.cfg, workspaceDir: e.workspaceDir }; if (resolveProviderAuthScope(t) === "plugin") { const n = resolvePluginOwnedProviderAuth({ ...t, profileId: e.profileId, preferredProfile: e.preferredProfile }); e.signal?.throwIfAborted(); assertProviderAuthSupportsHttp(n, e.provider); assertAuthModeAllowedForModel({ provider: e.provider, modelApi: e.modelApi, modelBaseUrl: e.modelBaseUrl, capability: e.capability, mode: n.mode, profileId: n.source }); return e.secretSentinels && !isNonSecretApiKeyMarker(n.apiKey) && !looksLikeSecretSentinel(n.apiKey) ? { ...n, apiKey: mintSecretSentinel(n.apiKey, { label: `model-auth:${e.provider}` }) } : n; } const n = resolveModelProviderAuthConfig({ provider: e.provider, config: e.cfg, workspaceDir: e.workspaceDir, modelBaseUrl: e.modelBaseUrl }); const r = { ...e, cfg: n }; const { provider: i, cfg: a, profileId: o, preferredProfile: s } = r; const c = resolveExplicitProviderNoAuth({ provider: i, providerConfig: resolveMergedModelProviderConfig(a, i), modelApi: r.modelApi }); if (c) return c; const l = { provider: i, modelApi: r.modelApi, modelBaseUrl: r.modelBaseUrl, capability: r.capability }; let u; const getDeprecatedProfileIds = () => u ??= new Set(resolveProviderDeprecatedAuthProfileIds({ provider: i, config: a })); const d = r.agentDir?.trim() || (a ? resolveDefaultAgentDir(a) : void 0); await assertProviderAuthReady({ cfg: a, provider: i, agentDir: d }); let f = r.store; const getScopedStore = async (e) => f ??= await resolveScopedAuthProfileStoreAsync({ agentDir: d, cfg: a, provider: i, profileId: e, preferredProfile: s }); const projectProfileAuth = (e, t, n, a) => { const o = e.profileType ?? n?.type; return projectResolvedProfileAuth({ apiKey: e.apiKey, enabled: r.secretSentinels, profileId: t, provider: i, store: a, mode: o ? profileTypeToAuthMode(o) : "api-key", authFlow: n?.type === "oauth" ? n.authFlow : void 0 }); }; if (o) { const e = resolveConfiguredAwsSdkProfileAuth({ cfg: a, provider: i, profileId: o }); if (e) return e; const t = await getScopedStore(o); assertAuthProfileNotRetired({ profileId: o, deprecatedProfileIds: getDeprecatedProfileIds() }); const n = t.profiles[o]; const assertCompatibleProfile = (e, t = o) => { if (!isStoredCredentialCompatibleWithAuthProvider({ cfg: a, provider: i, credential: { provider: e } })) throw new Error(`Auth profile "${t}" is not compatible with the resolved model endpoint for "${i}". Select a compatible provider profile.`); }; if (n) assertCompatibleProfile(n.provider); const s = n?.type; if (s) assertAuthModeAllowedForModel({ ...l, profileId: o, mode: profileTypeToAuthMode(s), authFlow: n?.type === "oauth" ? n.authFlow : void 0 }); const c = await resolveApiKeyForProfile({ cfg: a, store: t, profileId: o, agentDir: d, signal: r.signal, forceRefresh: r.forceRefresh, allowProfileFallback: !r.lockedProfile, validateOAuthCredential: r.validateOAuthCredential, assertRefreshAdmission: r.assertRefreshAdmission }); r.signal?.throwIfAborted(); if (!c) throw new Error(`No credentials found for profile "${o}".`); const u = c.profileId ?? o; if (r.lockedProfile && u !== o) throw new Error("Locked auth profile resolution returned a different profile."); const f = c.credential ?? t.profiles[u]; assertCompatibleProfile(c.provider, u); const p = projectProfileAuth(c, u, f, t); assertAuthModeAllowedForModel({ ...l, profileId: u, mode: p.mode, authFlow: p.authFlow }); if (!r.lockedProfile && shouldDeferSyntheticProfileAuth({ cfg: a, provider: i, resolvedApiKey: c.apiKey, modelApi: r.modelApi })) return resolveApiKeyForProviderCore({ ...r, store: t, profileId: void 0, lockedProfile: true }).catch((e) => { r.signal?.throwIfAborted(); if (e instanceof OAuthRefreshFailureError || e instanceof SecretSurfaceUnavailableError) throw e; return p; }); return p; } if (r.allowAuthProfileFallback !== false && (a?.auth?.profiles || a?.auth?.order)) { const e = await getScopedStore(); const t = resolveAuthProfileOrder({ cfg: a, store: e, provider: i, preferredProfile: s, forModel: r.modelId }); for (const e of t) { const t = resolveConfiguredAwsSdkProfileAuth({ cfg: a, provider: i, profileId: e }); if (t) return t; } } if (resolveProviderAuthOverride(a, i) === "aws-sdk") return resolveAwsSdkAuthInfo(); if (shouldUseImplicitAwsSdkAuth({ cfg: a, provider: i, modelApi: r.modelApi })) return resolveAwsSdkAuthInfo(); const modeAllowed = (e, t) => isAuthModeAllowedForModel({ ...l, mode: e, authFlow: t }); const assertInlineSourceUsable = async (e) => { const t = await getScopedStore(); if (isConfigBackedInlineProviderApiKey({ cfg: a, provider: i, source: e, store: t })) assertInlineProviderApiKeyUsable({ store: t, provider: i }); }; const resolveEnvAuth = async () => { const e = resolveConfigAwareEnvApiKey(a, i, r.workspaceDir, r.skipSetupProviderFallback); if (!e) return null; const t = resolveDirectProviderCredentialMode({ cfg: a, provider: i, inferredMode: e.source.includes("OAUTH_TOKEN") ? "oauth" : "api-key" }); if (t === "api-key") await assertInlineSourceUsable(e.source); if (!modeAllowed(t)) return "incompatible"; return { apiKey: sentinelizeConfigSecretRefEnvApiKey({ apiKey: e.apiKey, source: e.source, cfg: a, provider: i, enabled: r.secretSentinels }), source: e.source, mode: t }; }; if (r.credentialPrecedence === "env-first") { const e = await resolveEnvAuth(); if (e === "incompatible") return resolveApiKeyForProviderCore({ ...r, credentialPrecedence: "profile-first" }); if (e) return e; } const p = await resolveProviderEntryApiKeyAuth({ cfg: a, provider: i, store: await getScopedStore(), agentDir: d, signal: r.signal, modelApi: r.modelApi, modelBaseUrl: r.modelBaseUrl, capability: r.capability, secretSentinels: r.secretSentinels }); r.signal?.throwIfAborted(); if (p) return p; const m = { cfg: a, provider: i, secretSentinels: r.secretSentinels }; if (shouldPreferExplicitConfigApiKeyAuth(a, i)) { const e = resolveManagedSecretRefRuntimeProviderAuth(m); if (e) { assertInlineProviderApiKeyUsable({ store: await getScopedStore(), provider: i }); return e; } const t = resolveUsableCustomProviderApiKey(m); if (t) { assertInlineProviderApiKeyUsable({ store: await getScopedStore(), provider: i }); return { ...t, mode: "api-key" }; } } const h = resolveMergedModelProviderConfig(a, i); const g = resolveUsableCustomProviderApiKey(m); if (g && isNonSecretApiKeyMarker(g.apiKey)) return { ...g, mode: "api-key" }; const _ = resolveConfigAwareEnvApiKey(a, i, r.workspaceDir, r.skipSetupProviderFallback); if (_ && isNonSecretApiKeyMarker(_.apiKey)) return { ..._, mode: "api-key" }; const v = await getScopedStore(); const y = r.allowAuthProfileFallback === false ? [] : resolveAuthProfileOrder({ cfg: a, store: v, provider: i, preferredProfile: s, forModel: r.modelId, includePendingOAuthRefresh: true }); let b = null; let x; for (const e of y) { const t = v.profiles[e]; const n = t?.type; const o = t?.type === "oauth" ? t.authFlow : void 0; const s = n ? profileTypeToAuthMode(n) : void 0; if (s && !modeAllowed(s, o)) continue; if (getDeprecatedProfileIds().has(e)) continue; try { const t = resolveConfiguredAwsSdkProfileAuth({ cfg: a, provider: i, profileId: e }); if (t) return t; const n = await resolveApiKeyForProfile({ cfg: a, store: v, profileId: e, agentDir: d, signal: r.signal, forceRefresh: r.forceRefresh }); r.signal?.throwIfAborted(); if (n) { const t = n.profileId ?? e; const o = projectProfileAuth(n, t, n.credential ?? v.profiles[t], v); if (!modeAllowed(o.mode, o.authFlow)) continue; if (shouldDeferSyntheticProfileAuth({ cfg: a, provider: i, resolvedApiKey: n.apiKey, modelApi: r.modelApi })) { b ??= o; continue; } return o; } } catch (t) { r.signal?.throwIfAborted(); if (t instanceof SecretSurfaceUnavailableError) throw t; if (!x && t instanceof OAuthRefreshFailureError && (!s || modeAllowed(s, o))) x = t; log.debug?.(`auth profile "${e}" failed for provider "${i}": ${String(t)}`); } } if (x) throw x; const S = await resolveEnvAuth(); if (S && S !== "incompatible") return S; const C = resolveManagedSecretRefRuntimeProviderAuth(m); if (C && modeAllowed(C.mode)) { await assertInlineSourceUsable(C.source); return C; } const w = resolveUsableCustomProviderApiKey(m); if (w) { const e = resolveDirectProviderCredentialMode({ cfg: a, provider: i, inferredMode: "api-key" }); if (modeAllowed(e)) { assertInlineProviderApiKeyUsable({ store: await getScopedStore(), provider: i }); return { ...w, mode: e }; } } if (b) return b; const T = await prepareSyntheticLocalProviderAuth({ cfg: a, provider: i, modelApi: r.modelApi, workspaceDir: r.workspaceDir, secretSentinels: r.secretSentinels, allowPluginSyntheticAuth: r.allowAuthProfileFallback !== false }); r.signal?.throwIfAborted(); if (T) { assertProviderAuthSupportsHttp(T, i); return T; } const E = (h?.models?.length ?? 0) > 0; if ((r.allowAuthProfileFallback !== false && !E ? resolveOwningPluginIdsForProviderRef({ provider: i, config: a }) : void 0)?.length) { const e = buildProviderMissingAuthMessageWithPlugin({ provider: i, config: a, context: { config: a, agentDir: d, env: process.env, provider: i, listProfileIds: (e) => listProfilesForProvider(v, e) } }); if (e) throw new ProviderAuthError("missing-provider-auth", i, e, { providerGuidance: true }); } const D = listProfilesForProvider(v, i).find((e) => { const t = v.profiles[e]; return t?.type === "oauth" && isFailedOAuthRefreshFence(t); }); if (D) throw new ProviderAuthError("missing-provider-auth", i, `The ${i} sign-in ${JSON.stringify(D)} has ended or was rejected. Sign in again with ${buildOAuthRefreshFailureLoginCommand(i, { profileId: D })}.`, { providerGuidance: true }); const O = await resolveAuthStorePathForDisplayAsync(d); const k = d ? ` (agentDir: ${resolveUserPath(d)})` : ""; throw new ProviderAuthError("missing-provider-auth", i, [ `No API key found for provider "${i}".`, `Auth store: ${O}${k}.`, `Configure an API key (${formatCliCommand(`openclaw models auth paste-api-key --provider ${i}`)}; add --agent <id> for a non-default agent) or copy only portable static auth profiles from the main agentDir.` ].join(" ")); } //#endregion export { resolveScopedAuthProfileStoreAsync as i, resolveProviderEntryApiKeyAuth as n, resolveScopedAuthProfileStore as r, resolveApiKeyForProviderCore as t };