UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

483 lines (482 loc) • 16.3 kB
import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { t as captureOpenClawStateReadContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { d as isUserModelAuthProfileId } from "./user-model-account-authority-CRj924IP.mjs"; import { r as captureUserProfileModelAccountLinksAuthority } from "./user-profile-events-BhLFevt9.mjs"; import { r as assertAgentDatabaseReadAdmitted } from "./agent-database-admission-CL6wHJ_N.mjs"; import { s as getPreparedModelRuntimeAuthMaterializations } from "./prepared-model-runtime-auth-DVZroiat.mjs"; import { i as readSessionRuntimeOwnershipAsync } from "./session-utils-model-selection-BGYqZws_.mjs"; import { s as listUserProfileAuthLinksAsync } from "./user-model-accounts-DdCvjiOp.mjs"; import { r as PreparedModelRuntimePublicationSupersededError } from "./prepared-model-runtime-admission-errors-LxrcCg4d.mjs"; import { f as getPendingPreparedModelRuntimeReplacement } from "./prepared-model-runtime-Bbo9uBdt.mjs"; import "./prepared-model-runtime.errors-BRsU9-dm.mjs"; import { n as withCurrentReadAuthority } from "./current-read-authority-BoawkY8k.mjs"; import "./prepared-model-catalog-DSktrHGK.mjs"; import { t as resolveSwarmConfig } from "./swarm-config-Dp8TTyRG.mjs"; import { a as captureGenerationFacts, i as authStoresCurrent, n as ChatMetadataStartingError, o as generationFactsMatch, r as assertPreparedAgentCurrent, t as ChatMetadataSnapshotUnavailableError } from "./chat-metadata-facts-DUNVwVuX.mjs"; import { a as readPreparedChatMetadata, c as sessionProjectionKey, n as prepareChatMetadataModelProjection, o as resolveRequiredWorkerInferenceProfileId, p as prepareChatAccountSelection, r as prepareSessionAcpMeta, s as resolveSessionCatalogProfiles, t as hasSessionCatalogContext } from "./chat-metadata-session-projection-Dqm83JVm.mjs"; import { createHash } from "node:crypto"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/gateway/server-methods/chat-metadata-model-list.ts /** Model-list variants are derived facts of the existing chat metadata generation. */ function createChatMetadataModelList(e) { const t = new Map(e.facts.agents.map((e) => [e.agentId, e])); const n = /* @__PURE__ */ new Map(); const prepare = async (r, i) => { const a = JSON.stringify([ r.agentId, { ...r.params, sessionKey: Boolean(r.params.sessionKey) }, r.includeManualSelection, r.readScope?.sessionEntry ]); const o = n.get(a); if (o) { const e = await o; if (e.isCurrent()) return e; n.delete(a); } const s = t.get(r.agentId); if (!s?.owner.catalogOwner || !s.owner.isCurrent()) throw new PreparedModelRuntimePublicationSupersededError("Model catalog changed while preparing this result. Retry the request."); const { owner: c, modelCatalog: l, authStore: u, authModes: d } = s; const f = s.owner.catalogOwner; const p = import("./models-list-result-CrCsj4M9.mjs").then(({ prepareModelsListResult: e }) => e({ ...r, preparationAuthority: i, source: { kind: "published", owner: { ...c, catalogOwner: f, agentId: r.agentId, workspaceDir: f.workspaceDir, modelCatalog: l, authStore: u, authModes: d, authMaterializations: getPreparedModelRuntimeAuthMaterializations(c) } }, preloadedOnly: true })); n.set(a, p); pruneMapToMaxSize(n, e.maxEntries); p.catch(() => { n.delete(a); }); return p; }; return { async read(e) { const { requesterProfileId: t, readScope: n, ...r } = e; if (n) { const t = n.sessionEntry; if (!n.sessionKey || isUserModelAuthProfileId(t?.authProfileOverride?.trim() ?? "")) return; return prepare({ ...r, readScope: { agentId: e.agentId, sessionKey: n.sessionKey, sessionEntry: t && { modelOverride: t.modelOverride, providerOverride: t.providerOverride, modelOverrideRouteResolution: t.modelOverrideRouteResolution, modelOverrideFallbackOriginProvider: t.modelOverrideFallbackOriginProvider, modelOverrideFallbackOriginModel: t.modelOverrideFallbackOriginModel, agentRuntimeOverride: t.agentRuntimeOverride, authProfileOverride: t.authProfileOverride, authProfileOverrideSource: t.authProfileOverrideSource, authProfileOverrideCompactionCount: t.authProfileOverrideCompactionCount } } }, n); } if (t && e.params.view !== "provider-config") { const e = captureUserProfileModelAccountLinksAuthority(captureOpenClawStateReadContext().admission, t); const n = await listUserProfileAuthLinksAsync(t); if (!e()) return { isCurrent: () => false, read: () => ({ models: [] }) }; if (n.length > 0) return; const i = await prepare(r); return { isCurrent: () => e() && i.isCurrent(), read: () => ({ ...i.read(), accountSelection: { kind: "automatic", label: "Automatic account selection" } }) }; } return prepare(r); } }; } //#endregion //#region src/gateway/server-methods/chat-metadata-runtime.ts const CHAT_METADATA_CACHE_MAX_ENTRIES = 64; function createGatewayChatMetadataRuntime(e) { let t; let n = false; let r; let i; let a = false; let o; const notifyChanged = (t, n = false) => { const r = o; o = t; const i = !r || !t || !generationFactsMatch(r, t, "catalog-notification"); e.onChanged?.({ modelCatalogChanged: i, ...!i && n ? { modelCatalogStatusChanged: true } : {}, authChanged: !r || !t || !generationFactsMatch(r, t, "auth"), ...r && t && generationFactsMatch(r, t, "commands") ? { commandsChanged: false } : {} }); }; let s; const c = /* @__PURE__ */ new Set(); const trackWork = (e) => { if (c.has(e)) return e; c.add(e); const settled = () => c.delete(e); e.then(settled, settled); return e; }; const assertOpen = () => { if (s) throw s; }; let l; let u = false; let d = false; const projectAgent = async (t, n, r, i, a, o = false) => { assertOpen(); a?.assertCurrent?.(); assertPreparedAgentCurrent(n); const s = resolveSessionCatalogProfiles(r, n.owner.config, n.agentId); const c = !hasSessionCatalogContext(s); const l = o && !s.preferredProfileId && i && (await listUserProfileAuthLinksAsync(i)).length > 0 ? i : void 0; const u = !s.preferredProfileId && l || isUserModelAuthProfileId(s.preferredProfileId ?? "") ? /* @__PURE__ */ new Map() : c ? t.neutralProjectionByAgentId : t.sessionProjectionByKey; const d = c ? n.agentId : sessionProjectionKey(n.agentId, s); const f = u.get(d); if (f) { const e = f.state === "ready" ? f.projection : await f.promise; if (await withCurrentReadAuthority(a, () => e.isCurrent())) return e; u.delete(d); } const p = prepareChatMetadataModelProjection({ context: e.getContext(), facts: n, requesterProfileId: l, ...a, ...s }).then((e) => withCurrentReadAuthority(a, () => { const t = { ...e, agent: n }; u.set(d, { state: "ready", projection: t }); pruneMapToMaxSize(u, CHAT_METADATA_CACHE_MAX_ENTRIES); return t; })).catch((e) => { u.delete(d); throw e; }); trackWork(p); u.set(d, { state: "pending", promise: p }); pruneMapToMaxSize(u, CHAT_METADATA_CACHE_MAX_ENTRIES); return p; }; const prepareAgent = (t, n) => { const r = t.agentsById.get(n); if (r) return r.promise; const i = t.facts.agents.find((e) => e.agentId === n); if (!i) return; const a = { promise: trackWork((async () => { let r; try { const { buildCommandsListResult: e } = await import("./commands-list-result-_cv1fPUq.mjs"); r = (await e({ cfg: t.facts.config, agentId: n, includeArgs: true, scope: "text" })).commands; } catch (t) { e.log.warn(`chat metadata continuing without text commands for ${n}: ${formatErrorMessage(t)}`); } const a = resolveSwarmConfig(t.facts.config, n).enabled; return { ...i, ...r !== void 0 ? { commands: r } : {}, swarmEnabled: a, revision: createHash("sha256").update(JSON.stringify({ commands: r, swarmEnabled: a })).digest("base64url") }; })().then((e) => { a.ready = e; return e; }).catch((e) => { t.agentsById.delete(n); throw e; })) }; t.agentsById.set(n, a); pruneMapToMaxSize(t.agentsById, CHAT_METADATA_CACHE_MAX_ENTRIES); return a.promise; }; const runRefresh = async (o) => { for (let e = getPendingPreparedModelRuntimeReplacement(); e; e = getPendingPreparedModelRuntimeReplacement()) { await e; assertOpen(); } assertOpen(); const s = captureGenerationFacts(e.getConfig()); if (!t || !generationFactsMatch(t.facts, s)) { const r = { facts: s, modelLists: t && generationFactsMatch(t.facts, s, "catalog") ? t.modelLists : createChatMetadataModelList({ facts: s, context: e.getContext(), maxEntries: CHAT_METADATA_CACHE_MAX_ENTRIES }), agentsById: /* @__PURE__ */ new Map(), neutralProjectionByAgentId: /* @__PURE__ */ new Map(), sessionProjectionByKey: /* @__PURE__ */ new Map() }; assertOpen(); t = r; n ||= s.agents.length > 0; notifyChanged(s, o.notifyIfUnchanged); } else if (o.notifyIfUnchanged) notifyChanged(s, true); a = false; r = void 0; i?.resolve(); i = void 0; }; const f = AsyncLocalStorage.bind((e = {}) => { if (s) return Promise.reject(s); u = true; d ||= e.notifyIfUnchanged === true; if (l) return l; const t = Promise.resolve().then(async () => { while (u) { u = false; const e = d; d = false; await runRefresh({ notifyIfUnchanged: e }); } }); l = t; t.then(() => { l = void 0; }, (e) => { l = void 0; u = false; d = false; fail(e); }); return t; }); const readCurrent = async (e, a) => { assertOpen(); if (!n && !r) throw new ChatMetadataStartingError("Chat metadata is starting; retry shortly."); await l; if (!t && i) await i.promise; if (!t && r instanceof ChatMetadataSnapshotUnavailableError || t && !authStoresCurrent(t.facts)) await f(); const o = t; if (!o) throw r ?? new ChatMetadataSnapshotUnavailableError(); const s = await a(o); assertOpen(); if (!s.isCurrent()) throw new ChatMetadataSnapshotUnavailableError(); assertAgentDatabaseReadAdmitted(e); return s.read(); }; const p = /* @__PURE__ */ new Map(); const retainedModelsList = async (e, t) => { const n = p.get(e); if (!n) return; if (t.requesterProfileId && t.params.view !== "provider-config" && (await listUserProfileAuthLinksAsync(t.requesterProfileId)).length > 0) return; assertAgentDatabaseReadAdmitted(t.agentId); return n; }; const readModelsList = async (e) => { assertAgentDatabaseReadAdmitted(e.agentId); const n = normalizeAgentId(e.agentId); const r = JSON.stringify([ n, e.params, e.includeManualSelection, e.requesterProfileId, e.readScope?.sessionKey, e.readScope?.sessionEntry ]); const i = l !== void 0 || getPendingPreparedModelRuntimeReplacement() !== void 0 || !t || !authStoresCurrent(t.facts) || t.facts.agents.some((e) => !e.owner.isCurrent()) ? await retainedModelsList(r, e) : void 0; if (i) return i; let a; try { a = await readCurrent(e.agentId, async (t) => { return await t.modelLists.read(e) ?? { isCurrent: () => true, read: () => void 0 }; }); } catch (t) { const n = (t instanceof PreparedModelRuntimePublicationSupersededError || t instanceof ChatMetadataSnapshotUnavailableError) && await retainedModelsList(r, e); if (n) return n; throw t; } if (a) { p.set(r, a); pruneMapToMaxSize(p, CHAT_METADATA_CACHE_MAX_ENTRIES); } return a; }; const read = async (t) => { assertAgentDatabaseReadAdmitted(t.agentId); const { draftAccountSelection: n, isCurrent: r } = t; const i = r ? () => { if (!r()) throw new PreparedModelRuntimePublicationSupersededError("Chat metadata access changed while preparing its metadata. Retry the request."); n?.assertCurrent(); } : n?.assertCurrent; const a = (t.withCurrent || t.assertCurrent || i) && { withCurrent: t.withCurrent, assertCurrent: () => { t.assertCurrent?.(); i?.(); } }; const o = n ? { authProfileOverride: n.authProfileId, authProfileOverrideSource: "user" } : t.sessionEntry; return await readCurrent(t.agentId, async (r) => { const i = normalizeAgentId(t.agentId); const s = await prepareAgent(r, i); if (!s) throw new ChatMetadataSnapshotUnavailableError(`prepared chat metadata is unavailable for agent "${i}"`); await withCurrentReadAuthority(a, () => {}); if (t.includeModels === false) { assertPreparedAgentCurrent(s); return { isCurrent: s.owner.isCurrent, read: () => { n?.assertCurrent(); return { ...t.ifRevision === s.revision ? { unchanged: true } : { commands: s.commands }, swarmEnabled: s.swarmEnabled, revision: s.revision }; } }; } const c = await withCurrentReadAuthority(a, () => projectAgent(r, s, o, n?.owner ?? t.requesterProfileId, a, !t.sessionKey && !t.sessionEntry)); const l = await withCurrentReadAuthority(a, () => prepareChatAccountSelection({ authStore: s.authStore, sessionEntry: o, requesterProfileId: n?.owner ?? t.requesterProfileId })); const u = await withCurrentReadAuthority(a, () => prepareSessionAcpMeta({ ...t, sessionEntry: o }, e.getConfig())); const d = await withCurrentReadAuthority(a, () => readSessionRuntimeOwnershipAsync({ ...t, sessionEntry: o, config: e.getConfig() })); await withCurrentReadAuthority(a, () => {}); return { isCurrent: c.isCurrent, read: () => readPreparedChatMetadata(c, { ...t, sessionEntry: o, requesterProfileId: n?.owner ?? t.requesterProfileId }, e.getConfig(), u, d, l) }; }); }; const readStartup = async (n) => { assertAgentDatabaseReadAdmitted(n.agentId); const r = resolveSessionCatalogProfiles(n.sessionEntry, e.getConfig(), n.agentId); const a = hasSessionCatalogContext(r); const assemble = (t, r) => ({ ...n.readPolicy === "ready" ? {} : { commandsRevision: t.revision, metadata: { commands: t.commands, swarmEnabled: t.swarmEnabled, requiredWorkerInferenceProfileId: resolveRequiredWorkerInferenceProfileId(n, e.getConfig()) } }, ...r }); const o = t; if (!o || i || l || !authStoresCurrent(o.facts)) return; const s = normalizeAgentId(n.agentId); let c = o.agentsById.get(s)?.ready; if (n.readPolicy !== "ready" && a) { c = await prepareAgent(o, s); if (!c || t !== o || i || l || !authStoresCurrent(o.facts)) return; } assertAgentDatabaseReadAdmitted(n.agentId); if (c && !c.owner.isCurrent()) return; const u = o.neutralProjectionByAgentId.get(s); const d = isUserModelAuthProfileId(r.preferredProfileId ?? "") ? void 0 : a ? o.sessionProjectionByKey.get(sessionProjectionKey(s, r)) : u; if (u?.state !== "ready" || d?.state !== "ready" || !u.projection.isCurrent() || !d.projection.isCurrent()) return n.readPolicy !== "ready" && c ? assemble(c) : void 0; return assemble(d.projection.agent, { sessionModelCatalog: d.projection.modelCatalog, defaultModelCatalog: u.projection.modelCatalog }); }; const invalidate = () => { if (s) return; o = void 0; t = void 0; r = void 0; if (!i) { i = createDeferredCore(); i.promise.catch(() => {}); } }; const fail = (e) => { const n = e instanceof Error ? e : new Error(formatErrorMessage(e)); t = void 0; r = n; const o = i; i = void 0; o?.reject(n); if (!s && !a) { a = true; notifyChanged(); } }; const stop = async () => { if (!s) { s = new ChatMetadataSnapshotUnavailableError("gateway chat metadata runtime is stopped"); fail(s); } while (c.size > 0) await Promise.allSettled(c); }; return { fail, invalidate, read: (e) => trackWork(read(e)), readModelsList: (e) => trackWork(readModelsList(e)), readStartup: (e) => trackWork(readStartup(e)), refresh: (e) => trackWork(f(e)), stop }; } //#endregion export { createGatewayChatMetadataRuntime };