UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

930 lines (929 loc) • 37.4 kB
import { o as normalizeLowercaseStringOrEmpty, t as hasNonEmptyString } from "./string-coerce-CCIiB4H7.mjs"; import { p as isValidSecretRef } from "./ref-contract-b8L-9DrQ.mjs"; import { g as parseSecretRef } from "./types.secrets-BmNLLnHp.mjs"; import { i as normalizeProviderIdForAuth, n as findNormalizedProviderValue, r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs"; import { u as normalizePluginsConfig } from "./config-state-B1JlHgba.mjs"; import { r as getRuntimeConfigCapture } from "./runtime-config-capture-state-CvRIlfib.mjs"; import { E as readInlineProviderApiKeyUsage, T as readAuthProfileUsageStats, k as resolveProfileUnusableUntil, w as isProfileInCooldown, y as isActiveUnusableWindow } from "./user-model-account-authority-CRj924IP.mjs"; import { s as resolveAgentModelPrimaryValue } from "./model-input-DrM4DWHG.mjs"; import { t as splitTrailingAuthProfile } from "./model-ref-profile-C7DWqVP0.mjs"; import { a as resolveMergedModelProviderConfig } from "./model-provider-config-Bbah_2ON.mjs"; import { s as resolveProviderAuthLookupMaps } from "./provider-env-vars-DPvuIf4v.mjs"; import { i as passesManifestOwnerBasePolicy } from "./manifest-owner-policy-B8Brw4Zo.mjs"; import { c as resolveCliRuntimeCanonicalProvider, l as resolveCliRuntimeModelBackendBinding } from "./cli-backends-B8PrIwPC.mjs"; import { n as createProviderModelRoutesResolver } from "./provider-model-routes-CbP035Gi.mjs"; import { a as selectProviderModelAuthSources, c as buildProviderModelAuthSourcePlan, f as toProviderModelAuthReadiness, r as resolveProviderModelRouteAuthRequirement, s as buildProviderModelAuthDirectSource, u as fromProviderModelAuthReadiness } from "./provider-model-route-auth-dD2KD9io.mjs"; import { o as resolveProviderModelAuthPolicy, r as resolveModelRuntimePolicy } from "./model-runtime-policy-Cfudvy7O.mjs"; import { c as resolveConfiguredOpenAIAuthMode, d as selectOpenAIModelRouteAuth, o as createOpenAIModelRoutesResolver } from "./model-catalog-entry-pfJ-_t4l.mjs"; import { i as modelMatchesProviderModelRoute } from "./provider-model-route-hB9HZIqE.mjs"; import { n as resolveDefaultModelForAgent } from "./model-selection-config-Bvf5WqHo.mjs"; import { t as hasAuthoredProviderRequestParams } from "./model-extra-params-D2Glrj-b.mjs"; import { r as hasUsableOAuthCredential } from "./credential-state-BiAE74F8.mjs"; import { d as getRuntimeAuthProfileStoreSnapshotCore } from "./runtime-snapshots-1lyYKb7Y.mjs"; import { t as resolveAgentHarnessPolicy } from "./policy-DzaOuofI.mjs"; import { i as resolveAuthProfileEligibility, o as resolveAuthProfileOrderWithMetadata, r as prependAuthProfilePin, t as isConfiguredAwsSdkAuthProfileForProvider } from "./order-jOvee2J6.mjs"; import { c as resolveCliRuntimeExecutionProvider } from "./model-runtime-aliases-DZy9Ea2c.mjs"; import { t as resolveSelectedModelCredential } from "./model-auth-selected-credential-DsmxCC4n.mjs"; import { d as isSecretRefHeaderValueMarker } from "./model-auth-markers-4YSUG71a.mjs"; import { a as resolveExternalCliAuthProfiles, r as listExternalCliSyncProviderIds } from "./external-cli-sync-_MwEKD82.mjs"; import { _ as hasMalformedSecretInputSyntax, b as resolveStoredCredentialReadOnlyAvailability, g as resolveManagedSecretRefRuntimeProviderAuth, m as resolveProviderAuthScope, y as resolveSecretRefReadOnlyAvailability } from "./loader-runtime-load-Ba16vW6K.mjs"; import { i as listProviderEnvAuthLookupKeys, r as resolveProviderEnvAuthEvidence } from "./model-auth-env-kbpGo8fU.mjs"; import { S as shouldPreferExplicitConfigApiKeyAuth, a as hasUsableCustomProviderApiKey, g as resolveProviderConfigSecretInput, i as hasSyntheticLocalProviderAuthConfig, v as resolveProviderEntryApiKeyProfileReference } from "./model-auth-provider-config-Bnc4upRS.mjs"; import { n as collectPreparedModelRuntimeConfiguredRefs, r as collectPreparedModelRuntimeProviderIds } from "./prepared-model-runtime.configured-CCtksPnS.mjs"; import { t as resolveBundledCliBackendAuthPolicy } from "./cli-backend-auth-policy-Crs4uIXe.mjs"; import { i as selectCliExecutionAuthProfile } from "./cli-execution-auth-iYQVEZdU.mjs"; //#region src/agents/model-auth-availability.cli-runtime.ts /** CLI-runtime availability follows execution's forwarded account or native login. */ /** Builds one resolver's CLI-runtime evaluator; undefined leaves provider auth in charge. */ function createCliRuntimeModelAuthEvaluator(e, t) { let n; return (r, i, a, o) => { if (i.runtimeId === "openclaw" || a.routeResolution !== null) return; const s = normalizeProviderId(r); if (s === "openai") return; const c = i.pinnedProfileId?.trim() || i.preferredProfileId?.trim(); const l = i.runtimeId && i.runtimeId !== "auto" ? i.runtimeId : resolveCliRuntimeExecutionProvider({ provider: r, cfg: e.cfg, agentId: e.agentId, modelId: i.modelId, authProfileId: c, metadataSnapshot: e.metadataSnapshot, preparedAuthDirectories: e.preparedCliRuntimeAuthDirectories }, o) ?? s; const u = normalizeProviderId(l); const d = resolveCliRuntimeModelBackendBinding({ provider: r, runtime: l }); const f = e.metadataSnapshot?.owners?.cliBackends.get(u); if (!d && !f?.length && !resolveCliRuntimeCanonicalProvider({ runtime: l })) return; if (i.runtimeId && l !== s && !d) return { availability: false, routeResolution: null, unavailableReason: "missing-auth" }; if (f?.length) { const t = normalizePluginsConfig(e.cfg.plugins); if (!f.some((e) => passesManifestOwnerBasePolicy({ plugin: { id: e }, normalizedConfig: t }))) return { ...a, availability: false, unavailableReason: "missing-auth", unavailableUntil: void 0 }; } const p = resolveBundledCliBackendAuthPolicy(l); if (c && p?.strictSelectedProfile && !p.nativeAuthProfileIds?.includes(c)) return i.pinnedProfileId ? t(r, { modelId: i.modelId, requiredProfileId: c }) : a; if (!c && p?.strictSelectedProfile) { const n = selectCliExecutionAuthProfile({ cliExecutionProvider: l, authProfileProvider: r, config: e.cfg, store: e.authStore, readinessMode: "read-only", metadataSnapshot: e.metadataSnapshot }); if (n) return t(n.provider, { modelId: i.modelId, requiredProfileId: n.profileId }); } const m = { id: l, source: "native" }; if (u === s) return f?.length ? { ...a, runtimeAuth: m } : void 0; const h = e.preparedRuntimeAuthModes?.[normalizeProviderIdForAuth(l)]; if (h !== void 0) return { availability: true, routeResolution: null, selectedAuthMode: typeof h === "string" ? h : h.mode, evidence: "runtime", runtimeAuth: m }; n ??= new Set(collectPreparedModelRuntimeProviderIds(e.cfg, {}, false, collectPreparedModelRuntimeConfiguredRefs(e.cfg, e.agentId), e.agentId)); return e.preparedSyntheticAuthComplete || n.has(u) ? { availability: false, routeResolution: null, unavailableReason: "missing-auth", runtimeAuth: m } : { availability: void 0, routeResolution: null, runtimeAuth: m }; }; } //#endregion //#region src/agents/model-auth-availability.profile-credential.ts /** Snapshot-scoped credential readiness, including owned OAuth refresh paths. */ function modeAllowed(e, t, n, r) { const i = resolveProviderModelAuthPolicy({ provider: e, mode: n, authFlow: r, api: t.api ?? void 0, baseUrl: typeof t.baseUrl === "string" ? t.baseUrl : void 0 }); return i.compatible && (!t.authRequirement || i.authRequirement === t.authRequirement); } function createProfileCredentialAvailability(e) { const { env: t, now: n } = e; const r = new Set(e.externalCliRefreshProfileIds); const i = /* @__PURE__ */ new Map(); const canRefreshProviderOAuth = (t) => { const n = normalizeProviderIdForAuth(t); if (!i.has(n)) i.set(n, e.canRefreshProviderOAuth?.(n) === true); return i.get(n) === true; }; return (i, a, o, s) => { if (!modeAllowed(i, s, o.type, o.type === "oauth" ? o.authFlow : void 0)) return false; if (e.hydratedProfileIds.has(a)) return o.type !== "token" || o.expires === void 0 || o.expires > n; return resolveStoredCredentialReadOnlyAvailability({ credential: o, cfg: e.cfg, env: t, now: n, canRefreshOAuth: i === "openai" || r.has(a) || canRefreshProviderOAuth(i) }); }; } //#endregion //#region src/agents/model-auth-availability.runtime-overlay.ts /** Runtime-snapshot credential overlay for read-only auth availability. */ /** Overlays prepared runtime secrets onto persisted profiles with the same secret ref. */ function createRuntimeCredentialOverlay(e) { const t = /* @__PURE__ */ new Set(); const overlay = (n, r) => { const i = e.runtimeStore?.profiles[n]; if (!i || r.type !== i.type || r.provider !== i.provider) return r; if (r.type === "oauth" && i.type === "oauth" && r.oauthRef && !hasNonEmptyString(r.access) && !hasNonEmptyString(r.refresh) && hasUsableOAuthCredential(i, { now: e.now })) return i; if (r.type === "oauth" || i.type === "oauth") return r; const a = parseSecretRef(r.type === "api_key" ? r.keyRef ?? r.key : r.tokenRef ?? r.token, e.cfg.secrets?.defaults); const o = parseSecretRef(i.type === "api_key" ? i.keyRef : i.tokenRef, e.cfg.secrets?.defaults); const s = i.type === "api_key" ? i.key : i.token; if (a === null || o === null || a.source !== o.source || a.provider !== o.provider || a.id !== o.id || !hasNonEmptyString(s)) return r; t.add(n); return r.type === "api_key" ? { ...r, key: s } : { ...r, token: s }; }; const n = e.runtimeStore ? Object.fromEntries(Object.entries(e.authStore.profiles).map(([e, t]) => [e, overlay(e, t)])) : e.authStore.profiles; return { overlay, hydratedProfileIds: t, orderStore: n === e.authStore.profiles ? e.authStore : { ...e.authStore, profiles: n } }; } //#endregion //#region src/agents/model-auth-availability.ts /** Read-only provider/model auth availability with provider-route selection. */ const OPENAI_PROVIDER_ID = "openai"; const OPENAI_CODEX_RESPONSES_API = "openai-chatgpt-responses"; const EXTERNAL_CLI_REFRESH_PROVIDER_IDS = new Set(listExternalCliSyncProviderIds().map(normalizeProviderIdForAuth)); function normalizeModelIdForProvider(e, t) { const n = splitTrailingAuthProfile(t).model; if (!n) return; const r = n.indexOf("/"); if (r <= 0) return n; return normalizeProviderIdForAuth(n.slice(0, r)) === e ? n.slice(r + 1).trim() || void 0 : void 0; } /** Builds one snapshot-scoped read-only auth evaluator. */ function createModelAuthAvailabilityResolver(e) { const t = getRuntimeConfigCapture(e.cfg)?.source; const isPluginAuthProvider = (t) => resolveProviderAuthScope({ provider: t, config: e.cfg, env: e.env, workspaceDir: e.workspaceDir, pluginMetadataSnapshot: e.metadataSnapshot }) === "plugin"; const n = e.env ?? process.env; const r = Date.now(); const isExternalCliProvider = (e) => EXTERNAL_CLI_REFRESH_PROVIDER_IDS.has(normalizeProviderIdForAuth(e)); const i = (e.externalCliProviderIds ?? []).filter(isExternalCliProvider); const a = i.length ? resolveExternalCliAuthProfiles(e.authStore, { allowKeychainPrompt: false, providerIds: i }) : []; const o = a.length ? { ...e.authStore, profiles: { ...e.authStore.profiles, ...Object.fromEntries(a.map((e) => [e.profileId, e.credential])) } } : e.authStore; const s = e.preparedRuntimeAuthStore ?? getRuntimeAuthProfileStoreSnapshotCore(e.agentDir); const c = createRuntimeCredentialOverlay({ cfg: e.cfg, authStore: o, runtimeStore: s, now: r }); const { aliasMap: l, envCandidateMap: u, authEvidenceMap: d } = resolveProviderAuthLookupMaps({ config: e.cfg, workspaceDir: e.workspaceDir, env: n, metadataSnapshot: e.metadataSnapshot }); const f = new Set((e.syntheticAuthProviderRefs ?? []).map(normalizeProviderIdForAuth)); if (resolveAgentModelPrimaryValue(e.cfg.agents?.defaults?.model)?.split("/", 1)[0] === "codex") f.add("codex"); const p = e.resolveOpenAIProviderRoutes ?? createProviderModelRoutesResolver({ provider: OPENAI_PROVIDER_ID, config: e.cfg, env: n }); const m = (e.routeResolverFactory ?? createOpenAIModelRoutesResolver)({ config: e.cfg, agentId: e.agentId, primaryModel: resolveDefaultModelForAgent({ cfg: e.cfg, agentId: e.agentId, allowManifestNormalization: false, allowPluginNormalization: false }), resolveProfileAuthMode: (e) => o.profiles[e]?.type, resolveProfileAuthFlow: (e) => { const t = c.orderStore.profiles[e]; return t?.type === "oauth" ? t.authFlow : void 0; }, env: n }, p); const h = /* @__PURE__ */ new Map(); const g = /* @__PURE__ */ new Map(); const normalizeProvider = (e) => { const t = normalizeProviderIdForAuth(e); return l[t] ?? t; }; const _ = createProfileCredentialAvailability({ cfg: e.cfg, env: n, now: r, hydratedProfileIds: c.hydratedProfileIds, externalCliRefreshProfileIds: a.map((e) => e.profileId), canRefreshProviderOAuth: e.canRefreshProviderOAuth }); const providerInput = (n) => resolveProviderConfigSecretInput(e.cfg, n, t); const prepareAuthTarget = (e, t) => { if (t.api != null && t.baseUrl != null) return t; const { providerConfig: n } = providerInput(e); const r = t.modelId ? normalizeModelIdForProvider(e, t.modelId) : void 0; const i = r ? n?.models?.find((t) => normalizeModelIdForProvider(e, t.id) === r) : void 0; return { ...t, api: t.api ?? i?.api ?? n?.api, baseUrl: t.baseUrl ?? i?.baseUrl ?? n?.baseUrl }; }; const providerBinding = (n) => resolveProviderEntryApiKeyProfileReference({ cfg: e.cfg, sourceConfig: t, provider: n, store: o }); const envAuth = (t) => { const r = normalizeProvider(t); if (!h.has(r)) h.set(r, resolveProviderEnvAuthEvidence(r, n, { aliasMap: l, candidateMap: u, authEvidenceMap: d, config: e.cfg, workspaceDir: e.workspaceDir })); return h.get(r); }; const profileOrder = (t, n) => { const { modelId: r, preferredProfileId: i, pinnedProfileId: a } = n; const o = normalizeProvider(t); const s = `${o}\u0000${r ?? ""}\u0000${i ?? ""}\u0000${a ?? ""}`; const l = g.get(s); if (l) return l; const u = prependAuthProfilePin(resolveAuthProfileOrderWithMetadata({ cfg: e.cfg, store: c.orderStore, provider: o, preferredProfile: i, forModel: r, readinessMode: "read-only" }), a); g.set(s, u); return u; }; const profileMode = (t) => o.profiles[t]?.type ?? e.cfg.auth?.profiles?.[t]?.mode; const v = /* @__PURE__ */ new Map(); const profilePolicyFacts = (e, t) => { const n = v.get(t); if (n) return n; const r = c.orderStore.profiles[t]; const i = r?.type === "oauth" ? r.authFlow : void 0; const a = i ? { authFlow: i, authRequirement: resolveProviderModelAuthPolicy({ provider: e, mode: profileMode(t), authFlow: i }).authRequirement } : {}; v.set(t, a); return a; }; const profileRequirement = (e, t) => resolveProviderModelRouteAuthRequirement(profileMode(t), profilePolicyFacts(e, t).authRequirement); const profileEligibleForReadOnlyAvailability = (t, n, i) => { const a = o.profiles[n] === i ? o : { ...o, profiles: { ...o.profiles, [n]: i } }; const s = resolveAuthProfileEligibility({ cfg: e.cfg, store: a, provider: normalizeProvider(t), profileId: n, now: r }); return s.eligible || s.reasonCode === "unresolved_ref"; }; const invalidProfilePin = (t, n) => { const i = n.pinnedProfileId?.trim() || void 0; return i !== void 0 && !resolveAuthProfileEligibility({ cfg: e.cfg, store: c.orderStore, provider: normalizeProvider(t), profileId: i, now: r }).eligible; }; const profileInCooldown = (e, t) => { const n = t.modelId ? splitTrailingAuthProfile(t.modelId).model : void 0; return isProfileInCooldown(o, e, r, n); }; const hasPermanentAuthFailure = (e) => e?.disabledReason === "auth_permanent" && isActiveUnusableWindow(e.disabledUntil, r); const profileAvailability = (t, n, r, i = false) => { if (!i && profileInCooldown(n, r)) return false; if (isConfiguredAwsSdkAuthProfileForProvider({ cfg: e.cfg, provider: t, profileId: n })) return modeAllowed(t, r, "aws-sdk"); const a = o.profiles[n]; if (!a) return false; const s = c.overlay(n, a); if (!profileEligibleForReadOnlyAvailability(t, n, s)) return false; return _(t, n, s, r); }; const hasMatchingProfileEvidence = (t, n) => { const r = resolveAuthProfileEligibility({ cfg: e.cfg, store: o, provider: t, profileId: n }).reasonCode; return r !== "provider_mismatch" && r !== "profile_missing"; }; const hasProfileEvidence = (t) => { const n = normalizeProvider(t); return findNormalizedProviderValue(e.cfg.auth?.order, n) !== void 0 || Object.values(e.cfg.auth?.profiles ?? {}).some((e) => normalizeProvider(e.provider) === n) || Object.keys(o.profiles).some((e) => hasMatchingProfileEvidence(n, e)); }; const firstProfileEvidenceId = (t) => { const n = normalizeProvider(t); const r = findNormalizedProviderValue(e.cfg.auth?.order, n); const i = findNormalizedProviderValue(o.order, n); return (r ?? i ?? Object.keys(o.profiles)).find((e) => hasMatchingProfileEvidence(n, e)); }; const unprofiledEvaluation = (t, i) => { const withMode = (e, n, r = modeAllowed(t, i, e)) => ({ availability: r, selectedAuthMode: e, evidence: n }); const { providerConfig: a, ref: s } = providerInput(t); const l = i.pinnedProfileId ? void 0 : a?.auth; if (l === "aws-sdk") return withMode("aws-sdk", "aws-sdk"); const u = i.pinnedProfileId && !s ? void 0 : a?.apiKey; const d = l === "api-key" || l === "oauth" || l === "token" ? l : "api-key"; if (!s && hasMalformedSecretInputSyntax(u)) return { availability: false, evidence: "provider-config" }; const p = i.pinnedProfileId ? { kind: "none" } : providerBinding(t); if (p.kind === "profile") { const e = c.overlay(p.profileId, p.credential); return { availability: !profileInCooldown(p.profileId, i) && profileEligibleForReadOnlyAvailability(p.credential.provider, p.profileId, e) ? _(t, p.profileId, e, i) : false, selectedProfileId: p.profileId, selectedAuthMode: e.type, evidence: "profile" }; } if (p.kind === "profile-incompatible") return { availability: false, evidence: "profile" }; const { stats: m, unusableUntil: h } = readInlineProviderApiKeyUsage(o, t); if (h != null && h > r) return { availability: false, evidence: "provider-config", ...hasPermanentAuthFailure(m) ? { unavailableReason: "auth-failed" } : { unavailableReason: "cooldown", unavailableUntil: h } }; if (p.kind === "literal") return withMode(d, "provider-config"); if (p.kind === "marker") { if (p.evidence === "environment" && typeof u === "string") return withMode(d, "environment", modeAllowed(t, i, d) && hasNonEmptyString(n[u.trim()])); if (!modeAllowed(t, i, d)) return withMode(d, p.evidence, false); if (hasUsableCustomProviderApiKey(e.cfg, t, n)) return withMode(d, p.evidence, true); const r = typeof u === "string" && isSecretRefHeaderValueMarker(u); return { availability: r ? Boolean(resolveManagedSecretRefRuntimeProviderAuth({ provider: t, cfg: e.cfg })) || void 0 : void 0, selectedAuthMode: d, evidence: r ? "runtime" : p.evidence }; } if (s) { if (!isValidSecretRef(s) || !modeAllowed(t, i, d)) return withMode(d, "provider-config", false); const r = resolveSecretRefReadOnlyAvailability(s, e.cfg, n); const a = Boolean(resolveManagedSecretRefRuntimeProviderAuth({ provider: t, cfg: e.cfg })); return { availability: a ? true : r, selectedAuthMode: d, evidence: a ? "runtime" : "provider-config" }; } if (u !== void 0 && !(typeof u === "string" && u.trim() === "")) return { availability: false, evidence: "provider-config" }; if (t === "amazon-bedrock" && (i.api === void 0 || i.api === "bedrock-converse-stream") && a?.auth === void 0 && u === void 0) return withMode("aws-sdk", "aws-sdk"); const g = e.preparedRuntimeAuthModes?.[normalizeProviderIdForAuth(t)] ?? e.preparedRuntimeAuthModes?.[normalizeProvider(t)]; if (typeof g === "string") return withMode(g, "runtime"); const v = envAuth(t); if (v) { if (t === "amazon-bedrock" && v.mode === "aws-sdk") return withMode("aws-sdk", "aws-sdk"); return withMode(a?.auth ?? v.mode, "environment"); } const y = t === OPENAI_PROVIDER_ID && f.has("codex") && (i.authRequirement === "subscription" || i.api === OPENAI_CODEX_RESPONSES_API); const b = f.has(normalizeProviderIdForAuth(t)) || f.has(normalizeProvider(t)); if (hasSyntheticLocalProviderAuthConfig({ cfg: e.cfg, provider: t, route: b ? i : void 0 })) return { availability: true, evidence: "synthetic" }; if (b || y) return e.preparedSyntheticAuthComplete ? { availability: false, evidence: "synthetic", unavailableReason: "missing-auth" } : { availability: void 0, evidence: "synthetic" }; const x = a?.auth !== void 0 || hasProfileEvidence(t); return { availability: x ? false : void 0, unavailableReason: x ? "auth-failed" : "missing-auth", selectedAuthMode: a?.auth }; }; const profileSource = (e, t, n, r = true, i) => ({ kind: "profile", profileId: t, mode: profileMode(t), ...profilePolicyFacts(e, t), readiness: toProviderModelAuthReadiness(profileAvailability(e, t, n, r)), cooldown: i ?? (profileInCooldown(t, n) ? "active" : "clear") }); const cooldownEvaluation = (e, t) => { const n = t.modelId ? splitTrailingAuthProfile(t.modelId).model : void 0; const i = e.flatMap((e) => { if (e.readiness === "unavailable" || e.cooldown !== "active") return []; const t = readAuthProfileUsageStats(o, e.profileId); const i = t && !hasPermanentAuthFailure(t) ? resolveProfileUnusableUntil(t, n) : null; return i !== null && i > r ? [i] : []; }); return { availability: false, unavailableReason: i.length ? "cooldown" : "auth-failed", ...i.length ? { unavailableUntil: Math.min(...i) } : {} }; }; const rejectedSourceEvaluation = (e, t, n) => e === "all-cooldown" && t.kind === "automatic" ? cooldownEvaluation(t.orderedProfiles.filter((e) => !n.authRequirement || resolveProviderModelRouteAuthRequirement(e.mode, e.authRequirement) === n.authRequirement), n) : { availability: false, unavailableReason: "auth-failed" }; const rejectedProfileEvaluation = (e, t, n) => ({ ...rejectedSourceEvaluation(e.reason, t, n), ...e.source ? { selectedProfileId: e.source.profileId, selectedAuthMode: e.source.mode } : {}, evidence: "profile" }); const sourceEvaluation = (e, t, n, r) => { if (e.kind === "none") return r; const i = e.source; if (i.kind === "profile") { const r = e.kind === "unavailable" ? false : fromProviderModelAuthReadiness(i.readiness); const a = r === false ? profileSource(t, i.profileId, n) : void 0; return { ...r === false ? a && a.readiness !== "unavailable" && a.cooldown === "active" ? cooldownEvaluation([a], n) : { availability: r, unavailableReason: "auth-failed" } : { availability: r }, selectedProfileId: i.profileId, selectedAuthMode: i.mode, evidence: "profile" }; } const { unavailableReason: a, ...o } = r; return { ...o, ...i.readiness === "unavailable" ? { unavailableReason: a ?? "auth-failed" } : {}, selectedAuthMode: i.mode }; }; const directPolicy = (t, r) => { const { providerConfig: i, ref: a } = providerInput(t); const o = Boolean(r.pinnedProfileId); const s = o ? void 0 : i?.auth; const c = o ? { kind: "none" } : providerBinding(t); const l = c.kind === "marker" && hasUsableCustomProviderApiKey(e.cfg, t, n); const u = c.kind === "literal" || l || a !== null; const d = s === "aws-sdk" || l || a !== null || u && shouldPreferExplicitConfigApiKeyAuth(e.cfg, t); const f = envAuth(t); const p = f ? s ?? f.mode : void 0; const m = !d && p ? { selectedAuthMode: p, availability: modeAllowed(t, r, p), evidence: p === "aws-sdk" ? "aws-sdk" : "environment" } : unprofiledEvaluation(t, r); const h = buildProviderModelAuthDirectSource({ mode: m.selectedAuthMode, availability: m.availability, evidence: m.evidence ?? "none", authorization: m.evidence === "environment" && !u ? "ambient" : "declared" }); return { binding: c, direct: h, evaluation: m, hasDirectMaterial: u, hasDirectFallback: u || !o && h.evidence !== "none", markerUsable: l, required: d }; }; const sourcePlanForTarget = (e, t, n, r, i, a = {}) => { const { profileLock: o, boundProfileId: s } = a; const c = o || s; const l = c ? { reason: o ? "runtime-binding" : "provider-binding", source: profileSource(e, c, i(c), Boolean(o), "clear") } : n.required ? { reason: "configured-auth", source: n.direct } : void 0; return buildProviderModelAuthSourcePlan({ ...l ? { ownership: l } : {}, profiles: (a.profileIds ?? r.profileIds).map((t) => profileSource(e, t, i(t))), preferredProfileId: t.pinnedProfileId ?? t.preferredProfileId, explicitOrder: r.hasExplicitOrder, preserveProfilePriority: a.preserveProfilePriority, ...n.hasDirectFallback ? { fallback: n.direct } : {} }); }; const automaticSourceRejection = (e, t, n) => { if (t.requiredProfileId?.trim()) return; const r = directPolicy(e, n); if (r.required || r.binding.kind === "profile" || r.binding.kind === "profile-incompatible") return; const i = profileOrder(e, t); const a = sourcePlanForTarget(e, t, r, i, () => n); const o = selectProviderModelAuthSources({ provider: e, plan: a }); return o.kind === "rejected" ? rejectedProfileEvaluation(o, a, n) : void 0; }; const resolveProviderEvaluation = (t, n = {}) => { const r = normalizeProviderIdForAuth(t); if (isPluginAuthProvider(r)) return e.evaluatePluginAuth?.(r, n) ?? { availability: void 0, evidence: "runtime" }; const i = prepareAuthTarget(r, n); const a = n.requiredProfileId?.trim(); if (invalidProfilePin(r, n)) return { availability: false, unavailableReason: "auth-failed", evidence: "profile" }; const o = directPolicy(r, i); if (!a && o.binding.kind === "profile-incompatible") return { availability: false, unavailableReason: "auth-failed", evidence: "profile" }; const s = profileOrder(r, n); const c = !a && o.binding.kind === "profile" ? o.binding.profileId : void 0; const l = sourcePlanForTarget(r, n, o, s, () => i, { profileLock: a, boundProfileId: c }); const u = selectProviderModelAuthSources({ provider: r, plan: l }); if (u.kind === "rejected") return rejectedProfileEvaluation(u, l, i); return sourceEvaluation(u.selection, r, i, o.evaluation); }; const resolveProviderAuthAvailability = (e, t = {}) => resolveProviderEvaluation(e, t).availability; const evaluateModelAuthSources = (t, n = {}) => { const r = normalizeProviderIdForAuth(t); if (isPluginAuthProvider(r)) return { ...resolveProviderEvaluation(r, n), routeResolution: null, availabilityAuthoritative: true }; if (r !== OPENAI_PROVIDER_ID) return { ...resolveProviderEvaluation(r, n), routeResolution: null }; if (invalidProfilePin(r, n)) return { availability: false, unavailableReason: "auth-failed", routeResolution: null }; const i = n.requiredProfileId?.trim(); const a = n.pinnedProfileId ? void 0 : resolveConfiguredOpenAIAuthMode(e.cfg); const o = !i && a === "aws-sdk"; const s = prepareAuthTarget(r, n); const c = directPolicy(r, s); const l = !i && !o && c.binding.kind === "profile" ? c.binding.profileId : void 0; const u = i || n.pinnedProfileId || l; const d = m({ ...n, pinnedAuthRequirement: u ? profileRequirement(r, u) : resolveProviderModelRouteAuthRequirement(a) }); if (!d) return { availability: void 0, routeResolution: null }; if (d.kind === "incompatible") return { availability: false, routeResolution: d }; if (d.kind === "indeterminate") return { ...automaticSourceRejection(r, n, s) ?? { availability: void 0 }, routeResolution: d }; if (!i && !o && c.binding.kind === "profile-incompatible") return { availability: false, unavailableReason: "auth-failed", routeResolution: d }; const p = profileOrder(r, n); const h = normalizeModelIdForProvider(r, n.modelId ?? ""); const materializationMatchesRoute = (e, t) => t.runtimePolicy?.compatibleIds.some((t) => t.trim().toLowerCase() === e.runtimeOwnerId) === true && t.api.toLowerCase() === e.modelApi && t.requestTransportOverrides === e.requestTransportOverrides && modelMatchesProviderModelRoute({ provider: r, api: e.modelApi, baseUrl: e.modelBaseUrl, route: t }); const g = !i && !n.pinnedProfileId && !l && !c.required && h ? e.preparedRuntimeAuthMaterializations?.find((e) => (!p.hasExplicitOrder || e.authProfileId !== void 0 && p.profileIds.includes(e.authProfileId)) && normalizeProvider(e.provider) === r && e.modelId === h && d.routes.some((t) => { const i = resolveProviderModelRouteAuthRequirement(a); return (!i || i === t.authRequirement) && materializationMatchesRoute(e, t) && modeAllowed(r, { ...n, api: t.api, baseUrl: t.baseUrl, authRequirement: t.authRequirement }, e.authMode, e.authProfileId ? profilePolicyFacts(r, e.authProfileId).authFlow : void 0); })) : void 0; const _ = o ? "aws-sdk" : l ? void 0 : a ?? (c.hasDirectMaterial ? "api-key" : void 0); const v = c.hasDirectFallback && !c.required && !a ? void 0 : _; const targetForMode = (e, t) => { const r = resolveProviderModelRouteAuthRequirement(e, t); const i = r ? d.routes.find((e) => e.authRequirement === r) : void 0; return i ? { ...n, api: i.api, baseUrl: i.baseUrl, authRequirement: i.authRequirement } : s; }; const y = directPolicy(r, targetForMode(_ ?? c.direct.mode)); let b = p.profileIds; if (b.length === 0 && !i && !l && !y.required) { const e = firstProfileEvidenceId(r); if (e) b = [e]; } const x = sourcePlanForTarget(r, n, y, p, (e) => targetForMode(profileMode(e), profilePolicyFacts(r, e).authRequirement), { profileLock: i, boundProfileId: l, profileIds: b, preserveProfilePriority: Boolean(n.pinnedProfileId) }); const S = !i && !n.preferredProfileId && !n.pinnedProfileId && !_ && (y.binding.kind === "none" || y.binding.kind === "marker" && !y.markerUsable) && x.kind === "automatic" && !x.profiles.explicitOrder && (x.profiles.kind === "empty" || x.profiles.kind === "all-unavailable") && f.has("codex") && d.routes.every((e) => e.runtimePolicy?.compatibleIds?.some((e) => e.trim().toLowerCase() === "codex")); const C = selectOpenAIModelRouteAuth({ resolution: d, sourcePlan: x, configuredAuthMode: v, ...S ? { runtimeAuthOwner: { id: "codex" } } : {}, ...S && resolveMergedModelProviderConfig(e.cfg, r) === void 0 ? { allowNativeAuthOnSingleRoute: true } : {} }); const w = d.routes.length > 1 && C.kind === "selected" && C.selection.kind === "selected" && C.selection.route.authRequirement === "subscription" ? C.selection : void 0; const T = w && e.accountListedModelIds?.(r, w.source.kind === "profile" ? w.source.profileId : void 0); if (w && T && !T.has(normalizeLowercaseStringOrEmpty(n.modelId))) { const [e, ...t] = d.routes.filter((e) => e.authRequirement !== "subscription"); const n = e ? selectOpenAIModelRouteAuth({ resolution: { ...d, routes: [e, ...t] }, sourcePlan: x, configuredAuthMode: v }) : void 0; if (n?.kind !== "selected" || n.selection.kind !== "selected") return { availability: false, routeResolution: d, selectedRoute: w.route }; } const E = C.kind === "selected" && C.selection.kind === "selected" && C.selection.route.authRequirement === d.preferredAuthRequirement && C.selection.route.authRequirement !== resolveProviderModelRouteAuthRequirement(g?.authMode, g?.authProfileId ? profilePolicyFacts(r, g.authProfileId).authRequirement : void 0); if (g && !E) { const e = d.routes.find((e) => materializationMatchesRoute(g, e)); if (e) return { availability: true, routeResolution: d, selectedRoute: e, selectedAuthMode: g.authMode, ...g.authProfileId ? { selectedProfileId: g.authProfileId } : {}, evidence: "runtime" }; } if (C.kind === "deferred" && S && n.runtimeId === "codex" && !hasAuthoredProviderRequestParams({ config: e.cfg, provider: r, modelId: n.modelId ?? "", agentId: e.agentId })) { const t = e.preparedRuntimeAuthModes?.codex; const n = typeof t === "object" && t.source === "native" ? t.mode : void 0; const r = resolveProviderModelRouteAuthRequirement(n); const i = r ? d.routes.find((e) => e.authRequirement === r) : void 0; return { availability: n ? Boolean(i) : e.preparedSyntheticAuthComplete ? false : void 0, availabilityAuthoritative: true, routeResolution: d, ...i ? { selectedRoute: i, selectedAuthMode: n } : { unavailableReason: "missing-auth" }, evidence: "runtime", runtimeAuth: { id: "codex", source: "native" } }; } if (C.kind === "deferred" && S) return { availability: n.runtimeId === "openclaw" || e.preparedSyntheticAuthComplete ? false : void 0, routeResolution: d, evidence: "synthetic" }; if (C.kind !== "selected") { const e = C.kind === "rejected" ? C.source : void 0; const t = C.kind === "rejected" && e && (C.reason === "all-cooldown" || e.readiness === "unavailable") ? e : void 0; const r = resolveProviderModelRouteAuthRequirement(e?.mode, e?.authRequirement); const i = C.kind === "rejected" ? C.route : void 0; const a = r ? d.routes.find((e) => e.authRequirement === r) : void 0; const o = i ?? a ?? (d.routes.length === 1 ? d.routes[0] : void 0); return { ...C.kind === "rejected" ? rejectedSourceEvaluation(C.reason, x, { ...n, authRequirement: i?.authRequirement ?? (d.routes.length === 1 ? o?.authRequirement : void 0) }) : { availability: false }, ...x.kind === "automatic" && x.profiles.kind === "empty" && !x.profiles.explicitOrder && !y.hasDirectFallback ? { unavailableReason: y.evaluation.unavailableReason } : {}, routeResolution: d, ...C.kind === "rejected" && C.authModeIncompatible ? { availabilityAuthoritative: true } : {}, ...t ? { selectedProfileId: t.profileId, selectedAuthMode: t.mode, evidence: "profile" } : {}, ...o ? { selectedRoute: o } : {} }; } const D = C.selection.route; const O = sourceEvaluation(C.selection, r, { ...n, ...D }, y.evaluation); const k = d.routes.find((e) => e.authRequirement === "subscription"); if (S && O.availability !== true && k) return { availability: void 0, routeResolution: d, evidence: "synthetic" }; return { ...O, availability: O.availability ?? (O.evidence ? void 0 : false), routeResolution: d, selectedRoute: D }; }; const withSelectedCredential = (e, t) => ({ ...t, selectedCredential: resolveSelectedModelCredential({ provider: e, profileId: t.selectedProfileId, mode: t.selectedAuthMode, authRequirement: t.selectedProfileId ? profilePolicyFacts(e, t.selectedProfileId).authRequirement : void 0, runtimeAuth: t.runtimeAuth }) }); const evaluateModelAuth = (e, t) => withSelectedCredential(e, evaluateModelAuthSources(e, t)); const y = /* @__PURE__ */ new Set(); const addProviderDiscoveryProviderId = (e) => { const t = normalizeProvider(e); if (t) y.add(t); }; for (const e of Object.values(o.profiles)) addProviderDiscoveryProviderId(e.provider); for (const t of Object.values(e.cfg.auth?.profiles ?? {})) addProviderDiscoveryProviderId(t.provider); for (const e of listProviderEnvAuthLookupKeys({ envCandidateMap: u, authEvidenceMap: d })) if (envAuth(e)) addProviderDiscoveryProviderId(e); for (const t of e.metadataSnapshot?.index?.plugins ?? []) { if (!t.enabled || !(t.syntheticAuthRefs ?? []).some((e) => f.has(normalizeProviderIdForAuth(e)))) continue; for (const e of [...t.contributions?.providers ?? [], ...t.contributions?.modelCatalogProviders ?? []]) addProviderDiscoveryProviderId(e); } if (f.has("codex")) addProviderDiscoveryProviderId(OPENAI_PROVIDER_ID); const b = createCliRuntimeModelAuthEvaluator({ ...e, authStore: c.orderStore }, evaluateModelAuth); return { providerDiscoveryProviderIds: [...y].toSorted((e, t) => e.localeCompare(t)), evaluateModelAuth, evaluateRuntimeModelAuth: (t, n = {}) => { let r = n.runtimeId; let i; if (r === void 0) { const a = { config: e.cfg, agentId: e.agentId, provider: t, modelId: n.modelId, modelApi: n.api, modelBaseUrl: n.baseUrl, env: e.env, resolveOpenAIProviderRoutes: p }; i = resolveModelRuntimePolicy(a); r = resolveAgentHarnessPolicy(a, i).runtime; } const a = evaluateModelAuth(t, { ...n, runtimeId: r }); if (isPluginAuthProvider(t) || n.requiredProfileId?.trim()) return a; const o = b(t, { ...n, runtimeId: r }, a, i); return o ? withSelectedCredential(t, { ...o, availabilityAuthoritative: true }) : a; }, resolveProviderAuthAvailability }; } //#endregion export { createModelAuthAvailabilityResolver as t };