openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
502 lines (501 loc) • 20.5 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { d as withPluginRuntimeRegistryScope } from "./gateway-request-scope-BvvDhs5D.mjs";
import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { a as resolveAgentDir, b as resolveNativeModelPrimary, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { i as getActiveOpenClawStateDatabaseReadSnapshot } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { n as captureOpenClawStateReadWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { u as normalizePluginsConfig } from "./config-state-B1JlHgba.mjs";
import { d as isUserModelAuthProfileId } from "./user-model-account-authority-CRj924IP.mjs";
import { r as captureUserProfileModelAccountLinksAuthority } from "./user-profile-events-BhLFevt9.mjs";
import { t as splitTrailingAuthProfile } from "./model-ref-profile-C7DWqVP0.mjs";
import { i as resolveProviderIdForAuth } from "./provider-auth-aliases-CgGlzANu.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { n as withPluginRuntimeGenerationScope } from "./generation-scope-Cq7RLFex.mjs";
import { i as listCliRuntimeModelBackendBindings } from "./cli-backends-B8PrIwPC.mjs";
import { n as createProviderModelRoutesResolver } from "./provider-model-routes-CbP035Gi.mjs";
import { a as isAuthModeAllowedForModel } from "./model-runtime-policy-Cfudvy7O.mjs";
import { n as isManifestPluginAvailableForControlPlane } from "./manifest-contract-eligibility-DoGGge-2.mjs";
import { o as dedupeModelCatalogEntries } from "./model-selection-shared-9Kz63Hhm.mjs";
import { a as createModelCatalogIdentityKeyResolver, s as openAIModelCatalogRoutePolicy } from "./model-catalog-entry-pfJ-_t4l.mjs";
import { n as resolveDefaultModelForAgent } from "./model-selection-config-Bvf5WqHo.mjs";
import { l as getActiveSecretsRuntimeSnapshotRevisionState } from "./runtime-state-Dq_fFDZp.mjs";
import { t as resolveAgentHarnessPolicy } from "./policy-DzaOuofI.mjs";
import { n as buildAgentHarnessSupportContext } from "./support-LWqLDjUq.mjs";
import { a as resolveLegacyInheritedAuthDir } from "./legacy-inherited-auth-dir-1Y-Cs3kS.mjs";
import { a as prepareModelCatalogView, o as selectModelCatalogRuntimeEntry, r as listModelCatalogObservedRoutes, t as createModelCatalogSnapshotView } from "./model-catalog-view-CsclLtvK.mjs";
import { S as materializePreparedPersonalAuthProfile } from "./store-Bh2lUvOT.mjs";
import { m as resolveProviderAuthScope, p as resolvePluginOwnedProviderAuthWith, v as resolveAuthStoreReadOnlyValidUntil } from "./loader-runtime-load-Ba16vW6K.mjs";
import { r as PreparedModelRuntimePublicationSupersededError } from "./prepared-model-runtime-admission-errors-LxrcCg4d.mjs";
import { a as resolveExternalCliAuthScopeFromConfig } from "./external-cli-discovery-DZ419koV.mjs";
import { a as resolveLoadedProviderRuntimePlugin } from "./provider-hook-runtime-CNiG8a3j.mjs";
import { n as loadManifestModelCatalog } from "./model-catalog-ZbVopayG.mjs";
import "./prepared-model-runtime.errors-BRsU9-dm.mjs";
import { r as isPreparedModelCatalogFull } from "./prepared-model-runtime.full-catalog-FIcw7ozu.mjs";
import { t as createUnlistedClaudeCliWildcardCheck } from "./model-catalog-cli-wildcard-DoiOc2I_.mjs";
import { n as withCurrentReadAuthority } from "./current-read-authority-BoawkY8k.mjs";
import { t as createModelAuthAvailabilityResolver } from "./model-auth-availability-DC3d9ngc.mjs";
import { t as resolveCatalogDecisionRuntime } from "./model-catalog-decision-runtime-BNbeEaZO.mjs";
//#region src/agents/model-catalog-plugin-auth.ts
/** Keep refresh capability and credential evaluation on the same prepared plugin generation. */
function createCatalogPluginAuthCallbacks(e, t) {
const n = e.metadataSnapshot;
return {
canRefreshProviderOAuth: (r) => {
if (!e.pluginRegistry) return false;
try {
return withPluginRuntimeGenerationScope({
metadataSnapshot: n,
pluginRegistry: e.pluginRegistry
}, () => typeof resolveLoadedProviderRuntimePlugin({
provider: r,
config: e.cfg,
workspaceDir: t
})?.refreshOAuth === "function");
} catch {
return false;
}
},
evaluatePluginAuth: (r, i) => {
if (!e.pluginRegistry) return {
availability: void 0,
routeResolution: null,
availabilityAuthoritative: true
};
try {
return withPluginRuntimeGenerationScope({
metadataSnapshot: n,
pluginRegistry: e.pluginRegistry
}, () => {
const a = resolvePluginOwnedProviderAuthWith({
provider: r,
config: e.cfg,
workspaceDir: t,
pluginMetadataSnapshot: n,
profileId: i.requiredProfileId ?? i.pinnedProfileId,
preferredProfile: i.preferredProfileId
}, resolveLoadedProviderRuntimePlugin);
const o = isAuthModeAllowedForModel({
provider: r,
mode: a.mode,
modelApi: i.api ?? void 0,
modelBaseUrl: typeof i.baseUrl === "string" ? i.baseUrl : void 0
}) && (!a.nativeAuth || a.nativeAuth.runtime === i.runtimeId);
return {
availability: o,
selectedAuthMode: a.mode,
...o && a.nativeAuth ? { runtimeAuth: {
id: a.nativeAuth.runtime,
source: "native"
} } : {},
evidence: "runtime",
routeResolution: null,
availabilityAuthoritative: true
};
});
} catch {
return {
availability: false,
unavailableReason: "missing-auth",
evidence: "runtime",
routeResolution: null,
availabilityAuthoritative: true
};
}
}
};
}
//#endregion
//#region src/agents/model-catalog-decisions.ts
/** Prepare private records once under the caller's retained credential authority. */
async function prepareModelCatalogDecisions(e, t) {
const n = e.preferredProfileId && isUserModelAuthProfileId(e.preferredProfileId) ? { profileId: e.preferredProfileId } : !e.preferredProfileId && e.requesterProfileId ? { requesterProfileId: e.requesterProfileId } : void 0;
if (!n || e.preparedPersonalCatalog) return withCurrentReadAuthority(t, () => createModelCatalogDecisions(e));
const r = captureOpenClawStateReadWorkerContext();
const i = "requesterProfileId" in n ? captureUserProfileModelAccountLinksAuthority(r.admission, n.requesterProfileId) : void 0;
const isCurrent = () => {
try {
r.admission.assertCurrent();
return i?.() !== false;
} catch {
return false;
}
};
const assertPreparedCurrent = () => {
if (!isCurrent() || e.isCurrent?.() === false) throw new PreparedModelRuntimePublicationSupersededError("Personal model accounts changed while preparing the catalog");
};
const { readPersonalCatalogProfiles: a } = await import("./sqlite-read-CTxOnSWH.mjs");
const o = await withCurrentReadAuthority(t, () => {
assertPreparedCurrent();
if ("requesterProfileId" in n && getActiveOpenClawStateDatabaseReadSnapshot()) throw new PreparedModelRuntimePublicationSupersededError("Default account selection requires current link authority");
return a(n, r);
});
return withCurrentReadAuthority(t, () => {
assertPreparedCurrent();
return createModelCatalogDecisions({
...e,
preparedPersonalCatalog: {
...o,
isCurrent
}
});
});
}
/** Builds requester/session auth views without changing shared catalog or credential snapshots. */
function createModelCatalogDecisions(e) {
const t = e.metadataSnapshot;
const n = e.workspaceDir ?? resolveAgentWorkspaceDir(e.cfg, e.agentId);
const r = splitTrailingAuthProfile(resolveNativeModelPrimary(e.cfg, e.agentId) ?? "").profile;
const i = resolveDefaultModelForAgent({
...e,
manifestPlugins: t
});
const a = {
provider: i.provider,
id: i.model
};
const o = createModelCatalogIdentityKeyResolver();
const s = o(a);
const configuredPinForEntry = (e) => r !== void 0 && o(e) === s ? r : void 0;
const c = e.pluginRegistry ? withPluginRuntimeRegistryScope(e.pluginRegistry, () => listCliRuntimeModelBackendBindings()) : listCliRuntimeModelBackendBindings();
let l = e.preparedAuthStore;
const u = /* @__PURE__ */ new Map();
const d = /* @__PURE__ */ new Set();
const f = e.preparedPersonalCatalog;
if (!f && (e.preferredProfileId && isUserModelAuthProfileId(e.preferredProfileId) || !e.preferredProfileId && e.requesterProfileId)) throw new Error("Personal model catalog records require asynchronous preparation");
if (e.preferredProfileId && isUserModelAuthProfileId(e.preferredProfileId)) {
l = materializePreparedPersonalAuthProfile(l, e.preferredProfileId, f?.profiles[e.preferredProfileId]);
const t = l.profiles[e.preferredProfileId]?.provider;
if (t) d.add(normalizeProviderId(t));
} else if (!e.preferredProfileId && e.requesterProfileId) for (const t of f?.links ?? []) {
const n = isUserModelAuthProfileId(t.authProfileId) ? materializePreparedPersonalAuthProfile(l, t.authProfileId, f?.profiles[t.authProfileId]) : l;
const r = n.profiles[t.authProfileId]?.provider ?? e.cfg.auth?.profiles?.[t.authProfileId]?.provider;
if (!r || normalizeProviderId(r) !== t.provider) continue;
l = n;
u.set(t.provider, t.authProfileId);
if (isUserModelAuthProfileId(t.authProfileId)) d.add(t.provider);
}
const p = d.size ? [...e.snapshot.staticEntries ?? [], ...loadManifestModelCatalog({
config: e.cfg,
metadataSnapshot: t
})].filter((e) => d.has(normalizeProviderId(e.provider))) : [];
let m = p.length ? {
...e.snapshot,
entries: dedupeModelCatalogEntries([...e.snapshot.entries, ...p]),
routeVariants: [...e.snapshot.routeVariants.length ? e.snapshot.routeVariants : e.snapshot.entries, ...p]
} : e.snapshot;
const h = e.preferredProfileId ?? e.pinnedProfileId;
const g = e.profileProvider ?? (h ? l.profiles[h]?.provider ?? e.cfg.auth?.profiles?.[h]?.provider : void 0);
if (m.pendingProviders?.length && (h || u.size)) {
const authProvider = (n) => resolveProviderIdForAuth(n, {
config: e.cfg,
metadataSnapshot: t
});
m = {
...m,
pendingProviders: m.pendingProviders.filter((e) => !u.has(normalizeProviderId(e)) && (!h || g && authProvider(e) !== authProvider(g)))
};
}
const _ = [...m.providerOutcomes ?? []];
const v = m;
m = {
...m,
providerOutcomes: _,
get refreshFailed() {
return v.refreshFailed;
},
get pendingProviders() {
return v.pendingProviders;
}
};
const y = createProviderModelRoutesResolver({
provider: "openai",
config: e.cfg,
env: process.env
});
const b = prepareModelCatalogView({
...e,
snapshot: m,
workspaceDir: n,
profileProvider: g,
resolveOpenAIProviderRoutes: y
}).evaluateNative;
const evaluateNative = (e, t, n) => u.has(normalizeProviderId(e.provider)) || configuredPinForEntry(e) ? t : b(e, t, n);
const x = resolveAuthStoreReadOnlyValidUntil(l, Date.now());
const isPluginAuthProvider = (r) => resolveProviderAuthScope({
provider: r,
config: e.cfg,
workspaceDir: n,
pluginMetadataSnapshot: t
}) === "plugin";
const S = getActiveSecretsRuntimeSnapshotRevisionState();
const C = m.entries.some((e) => isPluginAuthProvider(e.provider));
const w = resolveAgentDir(e.cfg, e.agentId);
let T;
const E = createModelAuthAvailabilityResolver({
...createCatalogPluginAuthCallbacks(e, n),
cfg: e.cfg,
agentId: e.agentId,
authStore: l,
agentDir: w,
preparedCliRuntimeAuthDirectories: {
agentDir: w,
inheritedAuthDir: resolveLegacyInheritedAuthDir(e.cfg)
},
env: process.env,
metadataSnapshot: t,
preparedRuntimeAuthModes: e.preparedRuntimeAuthModes,
preparedRuntimeAuthMaterializations: e.preparedRuntimeAuthMaterializations,
preparedSyntheticAuthComplete: e.preparedSyntheticAuthComplete ?? isPreparedModelCatalogFull(e.snapshot),
workspaceDir: n,
syntheticAuthProviderRefs: t.plugins.filter((n) => isManifestPluginAvailableForControlPlane({
snapshot: t,
plugin: n,
config: e.cfg,
normalizedConfig: e.cfg.plugins && (T ??= normalizePluginsConfig(e.cfg.plugins))
})).flatMap((e) => e.syntheticAuthRefs ?? []),
externalCliProviderIds: resolveExternalCliAuthScopeFromConfig(e.cfg)?.providerIds ?? [],
preparedRuntimeAuthStore: l,
routeResolverFactory: e.routeResolverFactory,
resolveOpenAIProviderRoutes: y,
accountListedModelIds: (e, t) => {
let n;
for (const r of _) if (r.status === "ready" && r.listedModelIds && r.profileId === t && normalizeProviderId(r.provider) === e) {
n ??= /* @__PURE__ */ new Set();
for (const e of r.listedModelIds) n.add(normalizeLowercaseStringOrEmpty(e));
}
return n;
}
});
const D = /* @__PURE__ */ new Map();
const O = e.preferredProfileId || void 0;
const k = e.pinnedProfileId || void 0;
const A = e.runtimeOverride;
const normalizeAuthProvider = (n) => resolveProviderIdForAuth(n, {
config: e.cfg,
metadataSnapshot: t
});
const isSelectedProvider = (e) => !g || normalizeAuthProvider(g) === normalizeAuthProvider(e);
const pinnedProfileForEntry = (e) => (isSelectedProvider(e.provider) ? k : void 0) ?? u.get(normalizeProviderId(e.provider)) ?? configuredPinForEntry(e);
const j = createUnlistedClaudeCliWildcardCheck({
cfg: e.cfg,
agentId: e.agentId,
outcomes: () => m.providerOutcomes
});
const evaluateStoredEntry = (e, t, n) => {
const r = openAIModelCatalogRoutePolicy.resolveIdentity(e);
const i = listModelCatalogObservedRoutes(t ?? [e]);
const a = JSON.stringify([
o(e),
n,
e.api,
e.baseUrl,
i
]);
const s = isPluginAuthProvider(e.provider);
const c = s ? void 0 : D.get(a);
if (c) return c;
const l = u.get(normalizeProviderId(e.provider));
const d = isSelectedProvider(e.provider);
const f = (d ? O : void 0) ?? l;
const p = pinnedProfileForEntry(e);
const m = n ?? (d && g ? A : void 0);
const h = {
...E.evaluateRuntimeModelAuth(e.provider, {
modelId: r?.id ?? e.id,
runtimeId: m,
...normalizeProviderId(e.provider) === "openai" ? {} : {
api: e.api,
baseUrl: e.baseUrl
},
...f ? { preferredProfileId: f } : {},
...p ? { pinnedProfileId: p } : {},
observedRoutes: i
}),
...m ? { requestedRuntimeId: m } : {}
};
const v = normalizeProviderId(e.provider);
const y = !m && h.availability === true && h.evidence === "runtime" && j(v, r?.id ?? e.id) ? {
...h,
availability: false
} : h;
const b = _.some((e) => e.status === "auth-rejected" && e.rejectionScope !== "catalog" && normalizeProviderId(e.provider) === v && (e.profileId === void 0 || e.profileId === h.selectedProfileId)) ? {
...h,
availability: false,
unavailableReason: "auth-failed",
unavailableUntil: void 0
} : y;
if (!s) D.set(a, b);
return b;
};
const M = Boolean(e.preferredProfileId && isUserModelAuthProfileId(e.preferredProfileId) && !l.profiles[e.preferredProfileId]) ? (e, t, n) => g && normalizeProviderId(g) !== normalizeProviderId(e.provider) ? evaluateStoredEntry(e, t, n) : {
availability: false,
unavailableReason: "missing-auth",
routeResolution: null
} : evaluateStoredEntry;
const N = [];
const isCurrent = () => Date.now() < x && (!C || getActiveSecretsRuntimeSnapshotRevisionState() === S) && f?.isCurrent() !== false && (e.isCurrent?.() ?? e.observationConfig === void 0) && N.every((e) => e());
const prepareSelectedAccountCatalog = async (t, o) => {
const s = e.accountCatalog;
if (!s) return;
const c = {
assertCurrent: t,
withCurrent: o.withCurrent
};
const d = new Map([...u].map(([e, t]) => [t, e]));
if (h && g) d.set(h, normalizeProviderId(g));
if (r && pinnedProfileForEntry(a) === r) d.set(r, normalizeProviderId(i.provider));
for (const [r, i] of d) {
const a = await withCurrentReadAuthority(c, () => l.profiles[r]);
if (!a) continue;
const u = {
profileId: r,
credential: a,
...o,
allowDiscovery: o.refresh === true,
load: async () => {
t();
const a = e.pluginRegistry?.providers.find(({ provider: e }) => normalizeProviderId(e.id) === i)?.provider;
if (!a?.catalog) return [];
const { loadSelectedProviderAccountCatalog: s } = await import("./models-config.providers.catalog-context-9tyRGX7g.mjs");
t();
const u = {
provider: a,
providerId: i,
profileId: r,
authStore: l,
refresh: o.refresh,
config: e.cfg,
agentDir: e.agentDir ?? resolveAgentDir(e.cfg, e.agentId),
workspaceDir: n,
isCurrent,
assertCurrent: t,
withCurrent: o.withCurrent,
beforeRequest: o.beforeRequest
};
return withCurrentReadAuthority(c, () => s(u));
}
};
const d = await withCurrentReadAuthority(c, () => s.acquire(u));
await withCurrentReadAuthority(c, () => {
N.push(d.isCurrent);
if (!d.hasPublishedCatalog) return;
_.splice(0, _.length, ..._.filter((e) => normalizeProviderId(e.provider) !== i || e.profileId !== r), ...d.outcomes);
});
}
};
let P;
return {
preparedPersonalCatalog: f,
projectCatalog: (t) => withCurrentReadAuthority(t, () => {
if (P) return P;
const n = createModelCatalogSnapshotView(e.cfg, m);
const r = n.logicalEntries.map((t) => {
const r = n.variantsOf(t) ?? [t];
const i = M(t, r);
const a = evaluateNative(t, i);
const o = resolveCatalogDecisionRuntime({
cfg: e.cfg,
agentId: e.agentId,
entry: t,
evaluation: a,
pluginRegistry: e.pluginRegistry,
resolveOpenAIProviderRoutes: y
})?.id ?? "openclaw";
const s = selectModelCatalogRuntimeEntry({
entry: t,
routeVariants: r,
runtimeId: o
});
return n.project(s.entry, a, s.variants).runtimeEntry;
});
if (!t) P = r;
return r;
}),
accountCatalog: e.accountCatalog,
prepareSelectedAccountCatalog,
hasPinnedAccount: (e) => pinnedProfileForEntry(e) !== void 0,
evaluateEntry: M,
evaluateNative,
resolveOpenAIProviderRoutes: y,
snapshot: m,
metadataSnapshot: t,
authStore: l,
authModes: e.preparedRuntimeAuthModes,
runtimeChoices(t, n = [t]) {
const r = c.filter((e) => normalizeProviderId(e.provider) === normalizeProviderId(t.provider));
const i = M(t, n);
const a = resolveCatalogDecisionRuntime({
cfg: e.cfg,
agentId: e.agentId,
entry: t,
evaluation: i,
pluginRegistry: e.pluginRegistry,
resolveOpenAIProviderRoutes: y
});
const o = /* @__PURE__ */ new Set([
a?.id ?? "openclaw",
"openclaw",
...n.flatMap((e) => e.nativeRuntime ? [e.nativeRuntime] : []),
...i.routeResolution?.kind === "routes" ? i.routeResolution.routes.flatMap((e) => e.runtimePolicy?.compatibleIds ?? []) : [],
...r.map((e) => e.runtime)
]);
const s = [];
let l = false;
for (const i of o) {
const a = M(t, n, i);
const o = evaluateNative(t, a, i);
if (o.availability === void 0) l = true;
if (o.availability !== true) continue;
const c = o.selectedRoute;
const u = resolveAgentHarnessPolicy({
config: e.cfg,
agentId: e.agentId,
provider: t.provider,
modelId: t.id,
modelApi: c?.api ?? t.api,
modelBaseUrl: c?.baseUrl ?? t.baseUrl,
requestTransportOverrides: c?.requestTransportOverrides,
resolveOpenAIProviderRoutes: y
});
if (u.forcedByEnvironment && u.runtime !== i) continue;
const d = o.selectedRoute?.runtimePolicy?.compatibleIds;
if (d && !d.includes(i)) continue;
if (o.runtimeAuth && o.runtimeAuth.id !== i) continue;
if (i !== "openclaw" && !r.some((e) => e.runtime === i)) {
const n = e.pluginRegistry?.agentHarnesses.find((e) => e.harness.id === i)?.harness;
if (!n) {
l ||= e.pluginRegistry === void 0;
continue;
}
if (!n.supports(buildAgentHarnessSupportContext({
config: e.cfg,
agentId: e.agentId,
provider: t.provider,
modelId: t.id,
requestedRuntime: i,
contextManagement: n.contextManagement,
modelProvider: {
api: c?.api ?? t.api,
baseUrl: c?.baseUrl ?? t.baseUrl,
runtimePolicy: c?.runtimePolicy,
requestTransportOverrides: c?.requestTransportOverrides,
preparedAuth: o.selectedCredential
}
})).supported) continue;
}
s.push(i);
}
return s.length === 0 && l ? void 0 : s;
},
authMaterializations: e.preparedRuntimeAuthMaterializations,
cliRuntimeBindings: c,
pluginRegistry: e.pluginRegistry,
isCurrent,
assertCurrent: () => {
if (!isCurrent()) throw new PreparedModelRuntimePublicationSupersededError("Model catalog changed while selecting runtimes");
},
observationConfig: e.observationConfig
};
}
//#endregion
export { prepareModelCatalogDecisions as n, createModelCatalogDecisions as t };