UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

327 lines (326 loc) • 14.5 kB
import { p as asPositiveSafeInteger } from "./number-coercion-D6u-4YD8.mjs"; import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { i as assertExistingDatabaseIdentity } from "./sqlite-worker-identity-BH8ZkJU9.mjs"; import { t as captureOpenClawStateReadContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { s as normalizeModelFamily } from "./model-catalog-types-DFHCZ2Xr.mjs"; import { d as isUserModelAuthProfileId, f as parseUserModelAuthProfileId } from "./user-model-account-authority-CRj924IP.mjs"; import { g as readUserProfileVersion, n as captureUserProfileAuthorityRead, r as captureUserProfileModelAccountLinksAuthority } from "./user-profile-events-BhLFevt9.mjs"; import { i as resolveSessionAuthProfileOverrideSource, r as resolveCollapsedSessionAuthPinSource } from "./auth-profile-override-provenance-B7WULxR7.mjs"; import { a as normalizeOptionalAgentRuntimeId, r as isDefaultAgentRuntimeId } from "./agent-runtime-id-D8s1CaYB.mjs"; import { t as captureRuntimeConfig } from "./runtime-source-projection-DTwMWCo9.mjs"; import { a as createModelCatalogIdentityKeyResolver } from "./model-catalog-entry-pfJ-_t4l.mjs"; import { i as modelMatchesProviderModelRoute } from "./provider-model-route-hB9HZIqE.mjs"; import { h as resolveSessionPinnedHarnessId } from "./agent-harness-session-key-BRYGtzM6.mjs"; import { s as isLocalBaseUrl } from "./model-catalog-view-CsclLtvK.mjs"; import { s as getPreparedModelRuntimeAuthMaterializations } from "./prepared-model-runtime-auth-DVZroiat.mjs"; import { r as resolveSessionModelRef } from "./session-model-ref-Cha0Enxi.mjs"; import { a as resolveGatewaySessionRuntimeSelectionLocked } from "./session-utils-projection-D6w4h0yr.mjs"; import { r as PreparedModelRuntimePublicationSupersededError } from "./prepared-model-runtime-admission-errors-LxrcCg4d.mjs"; import { s as readUserModelAccountSelectionAsync } from "./user-model-account-operations-DmkXXwRf.mjs"; import { r as supportsOpenAIResponsesFastMode } from "./openai-fast-mode-Cvvl2GbK.mjs"; import { t as readAcpSessionMetaForEntries } from "./session-meta-readonly-B5S0IsZ_.mjs"; import "./prepared-model-runtime.errors-BRsU9-dm.mjs"; import { n as withCurrentReadAuthority, t as settleCurrentReadPreparations } from "./current-read-authority-BoawkY8k.mjs"; import { t as workerInferenceMetadata } from "./inference-placement-DTrb-mxJ.mjs"; import { toUSVString } from "node:util"; //#region src/gateway/server-methods/chat-account-selection.ts async function prepareChatAccountSelection(e) { const t = e.requesterProfileId; const n = e.sessionEntry?.authProfileOverride?.trim(); let r; let i; let isCurrent; if (n && isUserModelAuthProfileId(n)) { const { admission: e } = captureOpenClawStateReadContext(); const a = t ? captureUserProfileModelAccountLinksAuthority(e, t) : void 0; const o = await captureUserProfileAuthorityRead(e); const s = readUserProfileVersion(); const c = await readUserModelAccountSelectionAsync({ profileId: t, authProfileId: n }, { path: e.databasePath }); r = c?.personal; i = c?.owner?.displayName; const l = parseUserModelAuthProfileId(n); const u = o.bind([ t, l?.ownerProfileId, c?.owner?.profileId ].filter((e) => e !== void 0)); isCurrent = () => { if (e.identity.key.startsWith("file:")) assertExistingDatabaseIdentity(e.databasePath, e.identity.key, e.identity.birthtime); return Boolean(u?.()) && a?.() !== false && readUserProfileVersion() === s; }; } return () => { if (isCurrent?.() === false || e.sessionEntry?.authProfileOverride?.trim() !== n) throw new PreparedModelRuntimePublicationSupersededError("Personal account changed while preparing its metadata. Retry the request."); return resolveChatAccountSelection({ ...e, personal: r, ownerDisplayName: i }); }; } /** The session owns this preference; it is not a receipt for the account that served a turn. */ function resolveChatAccountSelection(e) { const t = e.sessionEntry?.authProfileOverride?.trim(); if (!t) return { kind: "automatic", label: "Automatic account selection" }; const n = resolveSessionAuthProfileOverrideSource(e.sessionEntry); if (!isUserModelAuthProfileId(t)) { const r = e.authStore.profiles[t]; return { kind: "shared", authProfileId: t, label: truncateUtf16Safe(toUSVString(r?.displayName?.trim() || t), 256), source: n }; } const r = e.personal; if (r) return { kind: "personal", authProfileId: t, label: r.label, source: n }; const i = e.ownerDisplayName?.trim(); const a = i ? toUSVString(i) : void 0; return { kind: "personal", label: a ? truncateUtf16Safe(`${a}'s account`, 256) : "Personal account", source: n }; } //#endregion //#region src/gateway/server-methods/models-list-public-projection.ts const pinnedAccountChoices = /* @__PURE__ */ new WeakSet(); function retainModelChoiceAccountPin(e, t) { if (t) pinnedAccountChoices.add(e); return e; } function hasModelChoiceAccountPin(e) { return pinnedAccountChoices.has(e); } /** Account observations are never model metadata donors or native-login readiness. */ function resolveModelCatalogServiceTiers(e) { const { snapshot: t, entry: n, evaluation: r, runtimeId: i } = e; const a = r.selectedRoute; const o = r.selectedCredential; if (!e.isCurrent() || r.availability !== true || !o || o.source === "harness" || !a || !i) return; if (i === "openclaw" && normalizeProviderId(n.provider) === "openai" && o.requirement === "api-key" && a.authRequirement === "api-key" && a.api === "openai-responses" && supportsOpenAIResponsesFastMode({ provider: "openai", ...a })) return [...e.modelServiceTiers ?? ["priority", "ultrafast"]]; if (o.source !== "profile" || a.requestTransportOverrides === "present" || t.refreshFailed || t.pendingProviders?.some((e) => normalizeProviderId(e) === normalizeProviderId(n.provider))) return; const s = t.providerOutcomes?.find((e) => normalizeProviderId(e.provider) === normalizeProviderId(n.provider) && e.profileId === o.profileId); if (s?.status !== "ready") return; const c = s.modelServiceTiers?.find((e) => e.modelId === n.id && e.runtimeId === i && modelMatchesProviderModelRoute({ provider: n.provider, api: e.api, baseUrl: e.baseUrl, route: a })); return c ? [...c.serviceTiers] : void 0; } /** Harness policy can remove tiers from account/route evidence, never grant new ones. */ function projectModelServiceTiers(e) { const t = resolveModelCatalogServiceTiers(e); if (t === void 0) return; const n = e.pluginRegistry?.agentHarnesses.find((t) => t.harness.id === e.runtimeId)?.harness; if (!n?.filterModelServiceTiers) return t; const r = new Set(n.filterModelServiceTiers({ config: e.config, agentId: e.agentId, provider: e.entry.provider, modelId: e.entry.id, serviceTiers: t })); return t.filter((e) => r.has(e)); } /** Keeps concrete route, auth, cost, and provider parameters out of public model rows. */ function buildPublicModelProjection(e, t = {}) { const n = asPositiveSafeInteger(e.contextWindow); const r = asPositiveSafeInteger(e.contextTokens); const i = normalizeModelFamily(e.family); return { id: e.id, name: e.name, provider: e.provider, ...e.alias ? { alias: e.alias } : {}, ...i ? { family: i } : {}, ...n ? { contextWindow: n } : {}, ...r ? { contextTokens: r } : {}, ...e.baseUrl ? { local: isLocalBaseUrl(e.baseUrl) } : {}, ...t.includeDetails && e.input?.length ? { input: e.input } : {}, ...e.contextWindows ? { contextWindows: e.contextWindows } : {}, ...e.contextWindowDefault ? { contextWindowDefault: e.contextWindowDefault } : {}, ...typeof e.reasoning === "boolean" ? { reasoning: e.reasoning } : {}, ...typeof e.compat?.supportsTools === "boolean" ? { supportsTools: e.compat.supportsTools } : {} }; } function projectProviderCatalogOutcomes(e) { return e?.map(({ provider: e, profileId: t, status: n, unlistedConfiguredModelIds: r }) => ({ provider: e, ...t ? { profileId: t } : {}, status: n, ...n === "ready" && r?.length ? { unlistedConfiguredModelIds: [...r] } : {} })); } //#endregion //#region src/gateway/server-methods/chat-metadata-session-projection.ts function readPreparedChatMetadata(e, t, n, r, i, a) { t.draftAccountSelection?.assertCurrent(); const { agent: o } = e; const s = { ...e.read(), ...o.commands !== void 0 ? { commands: o.commands } : {}, swarmEnabled: o.swarmEnabled, accountSelection: a?.() ?? resolveChatAccountSelection({ authStore: o.authStore, sessionEntry: t.sessionEntry }) }; const c = s.models ? { ...s, models: projectSessionModelCatalog(t, s.models, n, i) } : s; if (!t.sessionKey) return c; return { ...c, runtimeSelectionLocked: resolveGatewaySessionRuntimeSelectionLocked(t.sessionEntry, r ?? void 0), requiredWorkerInferenceProfileId: resolveRequiredWorkerInferenceProfileId(t, n) }; } async function prepareSessionAcpMeta(e, t) { if (!e.sessionKey) return null; const [n] = await readAcpSessionMetaForEntries({ cfg: t, entries: [{ agentId: e.agentId, sessionKey: e.sessionKey, entry: e.sessionEntry }] }); return n ?? null; } async function prepareChatMetadataModelProjection(e) { const [{ prepareModelsListResult: t }, { prepareModelCatalogDecisions: n }] = await Promise.all([import("./models-list-result-CrCsj4M9.mjs"), import("./model-catalog-decisions-BD72dc6E.mjs")]); await withCurrentReadAuthority(e, () => {}); const r = e.facts.modelCatalog; const i = captureRuntimeConfig(e.facts.owner.config); const a = await n({ cfg: i, agentId: e.facts.agentId, snapshot: r, metadataSnapshot: e.facts.owner.metadataSnapshot, preparedAuthStore: e.facts.authStore, accountCatalog: e.facts.owner.accountCatalog, requesterProfileId: e.requesterProfileId, preparedRuntimeAuthModes: e.facts.authModes, preparedRuntimeAuthMaterializations: getPreparedModelRuntimeAuthMaterializations(e.facts.owner), pluginRegistry: e.facts.owner.pluginRegistry, isCurrent: e.facts.owner.isCurrent, observationConfig: e.facts.owner.observationConfig, ...e.preferredProfileId ? { preferredProfileId: e.preferredProfileId } : {}, ...e.pinnedProfileId ? { pinnedProfileId: e.pinnedProfileId } : {}, ...e.profileProvider ? { profileProvider: e.profileProvider } : {}, ...e.runtimeOverride ? { runtimeOverride: e.runtimeOverride } : {} }, e); const o = [a.projectCatalog(e), t({ source: { kind: "gateway", context: e.context }, agentId: e.facts.agentId, params: { view: "configured", includeDefaultModels: false }, preloadedCatalog: { agentId: e.facts.agentId, config: i, snapshot: r }, preloadedOnly: true, preparationAuthority: e, catalogProjector: a })]; const [s, c] = await settleCurrentReadPreparations(o); await withCurrentReadAuthority(e, () => {}); return { modelCatalog: s, read: () => ({ models: c.read().models }), isCurrent: c.isCurrent }; } function resolveSessionCatalogProfiles(e, t, n) { const r = e?.authProfileOverride?.trim(); const i = e?.agentRuntimeOverride?.trim(); const a = e?.providerOverride ?? (i ? resolveSessionModelRef(t, e, n, { allowPluginNormalization: false }).provider : void 0); const o = { ...a ? { profileProvider: a } : {}, ...i ? { runtimeOverride: i } : {} }; if (!r) return o; const s = resolveCollapsedSessionAuthPinSource(e); return { preferredProfileId: r, ...o, ...s === "user" ? { pinnedProfileId: r } : {} }; } function sessionProjectionKey(e, t) { return [ normalizeAgentId(e), t.preferredProfileId ?? "", t.pinnedProfileId ?? "", t.profileProvider ?? "", t.runtimeOverride ?? "" ].join("\0"); } function hasSessionCatalogContext(e) { return e.preferredProfileId !== void 0 || e.pinnedProfileId !== void 0 || e.profileProvider !== void 0 || e.runtimeOverride !== void 0; } function resolveRequiredWorkerInferenceProfileId(e, t) { const n = t.cloudWorkers?.requiredProfile; const r = n ? t.cloudWorkers?.profiles?.[n] : void 0; const i = resolveSessionPinnedHarnessId(e.sessionEntry) ?? normalizeOptionalAgentRuntimeId(e.sessionEntry?.agentRuntimeOverride); return (isDefaultAgentRuntimeId(i) || i === "openclaw") && r && workerInferenceMetadata({ providerId: r.provider, profileSnapshot: r }).inference ? n : void 0; } function projectSessionModelCatalog(e, t, n, r, i = "hidden") { const a = resolveRequiredWorkerInferenceProfileId(e, n); const o = r?.auth === "native"; const s = e.sessionEntry; const c = resolveCollapsedSessionAuthPinSource(s); const l = (e.workerInference === "worker" || a !== void 0) && !e.draftAccountSelection && (!s?.agentRuntimeOverride?.trim() || normalizeOptionalAgentRuntimeId(s.agentRuntimeOverride) === "openclaw") && !(s?.authProfileOverride?.trim() && c === "user"); if (!o && !l) return t; const u = createModelCatalogIdentityKeyResolver(); const d = new Set(l && a !== void 0 ? Object.entries(n.models?.providers ?? {}).flatMap(([e, t]) => t.models.map((t) => u({ provider: e, id: t.id }))) : []); const f = l && (s?.modelOverrideSource === "default" || !s?.modelOverride?.trim()) && !s?.agentRuntimeOverride?.trim() && (e.sessionKey !== void 0 || e.workerInference === "worker"); const p = r?.modelRef ?? resolveSessionModelRef(n, e.sessionEntry, e.agentId, { allowPluginNormalization: false }); return t.map((e) => { if (l && hasModelChoiceAccountPin(e)) return e; const t = l && (!e.agentRuntime || e.agentRuntime.id === "openclaw") && d.has(u(e)); const n = e.provider === p.provider && e.id === p.model; if (!t && (!o && !f || !n)) return e; if (l && e.unavailableReason !== "missing-auth" && e.unavailableReason !== "auth-failed") return e; const { available: r, unavailableReason: a, unavailableUntil: s, ...c } = e; return i === "admitted" && n ? { ...c, available: true } : c; }); } //#endregion export { readPreparedChatMetadata as a, sessionProjectionKey as c, projectProviderCatalogOutcomes as d, retainModelChoiceAccountPin as f, projectSessionModelCatalog as i, buildPublicModelProjection as l, prepareChatMetadataModelProjection as n, resolveRequiredWorkerInferenceProfileId as o, prepareChatAccountSelection as p, prepareSessionAcpMeta as r, resolveSessionCatalogProfiles as s, hasSessionCatalogContext as t, projectModelServiceTiers as u };