UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

314 lines (313 loc) • 13.6 kB
import { r as filterStringEntries } from "./string-normalization-DLmfYZXI.mjs"; import { i as getPluginRegistryForContext } from "./gateway-request-scope-BvvDhs5D.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { p as resolveEffectivePluginActivationState, u as normalizePluginsConfig } from "./config-state-B1JlHgba.mjs"; import { _ as wrapCurrentPluginInstance } from "./plugin-instance-scope-oezVdCr2.mjs"; import { b as resolveDirectPluginRegistrationOwner, l as getActivePluginRegistry, p as getPluginRegistrationContext, v as requireActivePluginRegistry } from "./runtime-ezCEpumg.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/plugins/memory-state.ts const log = createSubsystemLogger("plugins/memory-state"); function ownFlushPlanSource(e) { const t = e.capability.providerFlushPlanResolver ?? e.capability.flushPlanResolver; return t ? { resolve: t, pluginId: e.pluginId } : void 0; } function flushPlanSourceOf(e) { return "flushPlanSource" in e ? e.flushPlanSource : ownFlushPlanSource(e); } function resolveMemoryCapabilityRegistration(e) { let t; for (const n of e) { const e = t; if (!e) { const e = ownFlushPlanSource(n); t = { ...n, ...e ? { flushPlanSource: e } : {} }; continue; } const r = e.memorySlotSelected === true; if (r !== (n.memorySlotSelected === true)) { const i = r ? e : n; const a = r ? n : e; const o = flushPlanSourceOf(i) ?? flushPlanSourceOf(a); t = { pluginId: i.pluginId, capability: { ...a.capability, ...i.capability }, memorySlotSelected: true, ...o ? { flushPlanSource: o } : {} }; continue; } const i = Boolean(n.capability.publicArtifacts) && !n.capability.promptBuilder && !n.capability.flushPlanResolver && !n.capability.providerFlushPlanResolver && !n.capability.runtime && !n.capability.providerRuntime; const a = ownFlushPlanSource(n) ?? (i ? e.flushPlanSource : void 0); t = { pluginId: n.pluginId, capability: { ...i ? e.capability : {}, ...n.capability }, memorySlotSelected: n.memorySlotSelected, ...a ? { flushPlanSource: a } : {} }; } return t; } const getMemoryCapability = () => resolveMemoryCapabilityRegistration(getPluginRegistryForContext()?.memoryCapabilities ?? []); const preparedMemoryPromptSections = /* @__PURE__ */ new WeakSet(); const activePreparedMemoryPromptSection = new AsyncLocalStorage(); function registerMemoryCorpusSupplement(e, t) { const n = resolveDirectPluginRegistrationOwner(e) ?? e; const r = requireActivePluginRegistry(); r.memoryCorpusSupplements = r.memoryCorpusSupplements.filter((e) => e.pluginId !== n).concat({ pluginId: n, supplement: wrapCurrentPluginInstance(t) }); } function registerMemoryCapability(e, t) { const n = getPluginRegistrationContext()?.registerMemoryCapability; if (n) { n(t); return; } const r = resolveDirectPluginRegistrationOwner(e) ?? e; requireActivePluginRegistry().memoryCapabilities.push({ pluginId: r, capability: wrapCurrentPluginInstance(t) }); } function getMemoryCapabilityRegistration() { const e = getMemoryCapability(); return e ? { pluginId: e.pluginId, capability: { ...e.capability } } : void 0; } /** The selected memory provider's /learn contribution, when it declares one. */ function getMemoryLearnContribution() { const e = getMemoryCapability(); const t = e?.capability; return e && t?.learnToolNames?.length && t.learnGuidanceBuilder ? { pluginId: e.pluginId, toolNames: t.learnToolNames, buildGuidance: t.learnGuidanceBuilder } : void 0; } function listMemoryCorpusSupplements() { return [...requireActivePluginRegistry().memoryCorpusSupplements]; } function adoptEligibleRuntimeMemoryRegistrations(e, t, n) { const r = new Set(e.map((e) => e.pluginId)); let i; for (const a of t) { if (r.has(a.pluginId) || !n(a.pluginId)) continue; (i ??= [...e]).push(a); r.add(a.pluginId); } return i ?? e; } /** * Discovery scopes cannot safely rerun full memory plugin setup. * Reuse exact root sidecars only while activation and source ownership still match. */ function adoptRuntimeMemoryRegistrations(e, t, n) { const r = normalizePluginsConfig(n.plugins); const canAdopt = (i) => { const a = e.plugins.find((e) => e.id === i); const o = t.plugins.find((e) => e.id === i); return o?.status === "loaded" && resolveEffectivePluginActivationState({ id: o.id, origin: o.origin, config: r, rootConfig: n, enabledByDefault: o.activationSource === "default" }).enabled && (!a || a.status === "loaded" && a.source === o.source); }; const i = adoptEligibleRuntimeMemoryRegistrations(e.memoryCorpusSupplements, t.memoryCorpusSupplements, canAdopt); const a = adoptEligibleRuntimeMemoryRegistrations(e.memoryPromptPreparations, t.memoryPromptPreparations, canAdopt); const o = adoptEligibleRuntimeMemoryRegistrations(e.memoryPromptSupplements, t.memoryPromptSupplements, canAdopt); return i === e.memoryCorpusSupplements && a === e.memoryPromptPreparations && o === e.memoryPromptSupplements ? e : { ...e, memoryCorpusSupplements: i, memoryPromptPreparations: a, memoryPromptSupplements: o }; } function registerMemoryPromptSupplement(e, t) { const n = resolveDirectPluginRegistrationOwner(e) ?? e; const r = requireActivePluginRegistry(); r.memoryPromptSupplements = r.memoryPromptSupplements.filter((e) => e.pluginId !== n).concat({ pluginId: n, builder: wrapCurrentPluginInstance(t) }); } function registerMemoryPromptPreparation(e, t) { const n = resolveDirectPluginRegistrationOwner(e) ?? e; const r = requireActivePluginRegistry(); r.memoryPromptPreparations = r.memoryPromptPreparations.filter((e) => e.pluginId !== n).concat({ pluginId: n, prepare: wrapCurrentPluginInstance(t) }); } function buildSynchronousMemoryPromptSection(e) { const t = requireActivePluginRegistry(); return { primary: filterStringEntries(resolveMemoryCapabilityRegistration(t.memoryCapabilities)?.capability.promptBuilder?.(e) ?? []), supplements: t.memoryPromptSupplements.toSorted((e, t) => e.pluginId.localeCompare(t.pluginId)).map((t) => ({ pluginId: t.pluginId, lines: filterStringEntries(t.builder(e)) })) }; } function cloneMemoryPromptSectionParams(e) { return { availableTools: new Set(e.availableTools), citationsMode: e.citationsMode, agentId: e.agentId, agentSessionKey: e.agentSessionKey, sandboxed: e.sandboxed, projectKey: e.projectKey }; } function snapshotMemoryPromptContext(e) { return Object.freeze({ availableTools: Object.freeze([...e.availableTools].sort()), citationsMode: e.citationsMode, agentId: e.agentId, agentSessionKey: e.agentSessionKey, sandboxed: e.sandboxed === true, projectKey: e.projectKey }); } function preparedMemoryPromptContextMatches(e, t) { return e.context.citationsMode === t.citationsMode && e.context.agentId === t.agentId && e.context.agentSessionKey === t.agentSessionKey && e.context.sandboxed === (t.sandboxed === true) && e.context.projectKey === t.projectKey && e.context.availableTools.length === t.availableTools.size && e.context.availableTools.every((e) => t.availableTools.has(e)); } /** Prepare one immutable memory prompt snapshot for a run. */ async function prepareMemoryPromptSection(e) { const t = cloneMemoryPromptSectionParams(e); const n = snapshotMemoryPromptContext(t); const r = buildSynchronousMemoryPromptSection(cloneMemoryPromptSectionParams(t)); const i = await Promise.all(requireActivePluginRegistry().memoryPromptPreparations.map(async (e) => ({ pluginId: e.pluginId, lines: filterStringEntries(await e.prepare(cloneMemoryPromptSectionParams(t))) }))); const a = Object.freeze([...r.primary, ...[...r.supplements, ...i].sort((e, t) => e.pluginId.localeCompare(t.pluginId)).flatMap((e) => e.lines)]); const o = Object.freeze({ context: n, lines: a }); preparedMemoryPromptSections.add(o); return o; } /** Keep async preparation run-scoped while a context engine assembles synchronously. */ async function runWithPreparedMemoryPromptSection(e, t) { const n = await prepareMemoryPromptSection(e); return activePreparedMemoryPromptSection.run(n, t); } function getActivePreparedMemoryPromptSection() { return activePreparedMemoryPromptSection.getStore(); } function buildMemoryPromptSection(e, t) { if (t) { if (!preparedMemoryPromptSections.has(t) || !preparedMemoryPromptContextMatches(t, e)) throw new Error("prepared memory prompt section does not match the current run"); return [...t.lines]; } const n = buildSynchronousMemoryPromptSection(e); return [...n.primary, ...n.supplements.flatMap((e) => e.lines)]; } function listMemoryPromptPreparations() { return [...requireActivePluginRegistry().memoryPromptPreparations]; } function resolveMemoryFlushPlan(e) { const t = getMemoryCapability(); const n = t?.flushPlanSource; if (!t || !n) return null; const r = n.resolve(e); if (!r) return null; return { plan: r, pluginId: n.pluginId, selectedSlotOwner: t.memorySlotSelected === true && n.pluginId === t.pluginId }; } /** * Whether the flush plan resolver belongs to a selected slot owner that registers the * provider-neutral runtime. Such a provider may persist through its own tools, so its * flush does not depend on a writable workspace; it is answered without calling the resolver. */ function isMemoryFlushPlanNativeProviderOwned() { const e = getMemoryCapability(); return Boolean(e?.flushPlanSource && e.capability.providerRuntime && e.memorySlotSelected === true && e.flushPlanSource.pluginId === e.pluginId); } function getMemoryRuntime() { return getMemoryCapability()?.capability.runtime; } function getMemoryProviderRuntime() { return getMemoryCapability()?.capability.providerRuntime; } let standaloneMemoryManagerActive = false; let standaloneMemoryOwner; /** Records, or clears, the slot owner a standalone memory lookup loaded. */ function setStandaloneMemoryOwner(e) { standaloneMemoryOwner = e; } /** * Classifies the configured memory slot owner from owners this process already * loaded, never loading one: the current registry, then the process registry for * the configured slot, then a standalone owner an earlier memory lookup loaded. * Undefined means no loaded owner answers; callers then keep their legacy path * and its own loading behavior. */ function resolveLoadedMemoryProviderKind(e) { const t = getMemoryCapability()?.capability; if (t?.providerRuntime || t?.runtime) return t.providerRuntime ? "native" : "legacy"; const n = normalizePluginsConfig(e.plugins); const r = n.enabled ? n.slots.memory : void 0; if (!r) return; const i = resolveMemoryCapabilityRegistration(getActivePluginRegistry()?.memoryCapabilities ?? []); if (i?.pluginId === r && (i.capability.providerRuntime || i.capability.runtime)) return i.capability.providerRuntime ? "native" : "legacy"; if (standaloneMemoryOwner?.pluginId === r) return standaloneMemoryOwner.native ? "native" : "legacy"; } function setStandaloneMemoryManagerActive(e) { standaloneMemoryManagerActive = e; } function hasMemoryRuntime() { return standaloneMemoryManagerActive || getMemoryRuntime() !== void 0 || getMemoryProviderRuntime() !== void 0; } function cloneMemoryPublicArtifact(e) { const t = Array.isArray(e.agentIds) ? e.agentIds : []; return { ...e, agentIds: [...t] }; } function isValidMemoryPublicArtifact(e) { return typeof e?.kind === "string" && typeof e.workspaceDir === "string" && typeof e.relativePath === "string" && typeof e.absolutePath === "string" && typeof e.contentType === "string"; } async function listActiveMemoryPublicArtifacts(e) { const t = getMemoryCapability(); const n = t?.pluginId; const r = await t?.capability.publicArtifacts?.listArtifacts(e) ?? []; if (!Array.isArray(r)) { log.warn(`ignoring public memory artifacts from plugin "${n}": not an array`); return []; } const i = r.filter(isValidMemoryPublicArtifact); if (i.length < r.length) log.warn(`ignoring ${r.length - i.length} malformed public memory artifact(s) from plugin "${n}": artifacts must include string kind, workspaceDir, relativePath, absolutePath, and contentType`); return i.map(cloneMemoryPublicArtifact).toSorted((e, t) => e.workspaceDir.localeCompare(t.workspaceDir) || e.relativePath.localeCompare(t.relativePath) || e.kind.localeCompare(t.kind) || e.contentType.localeCompare(t.contentType) || e.agentIds.join("\0").localeCompare(t.agentIds.join("\0")) || e.absolutePath.localeCompare(t.absolutePath)); } function clearMemoryPluginState() { const e = requireActivePluginRegistry(); e.memoryCapabilities = []; e.memoryCorpusSupplements = []; e.memoryPromptPreparations = []; e.memoryPromptSupplements = []; } //#endregion export { setStandaloneMemoryManagerActive as C, runWithPreparedMemoryPromptSection as S, registerMemoryPromptPreparation as _, getMemoryCapabilityRegistration as a, resolveMemoryCapabilityRegistration as b, getMemoryRuntime as c, listActiveMemoryPublicArtifacts as d, listMemoryCorpusSupplements as f, registerMemoryCorpusSupplement as g, registerMemoryCapability as h, getActivePreparedMemoryPromptSection as i, hasMemoryRuntime as l, prepareMemoryPromptSection as m, buildMemoryPromptSection as n, getMemoryLearnContribution as o, listMemoryPromptPreparations as p, clearMemoryPluginState as r, getMemoryProviderRuntime as s, adoptRuntimeMemoryRegistrations as t, isMemoryFlushPlanNativeProviderOwned as u, registerMemoryPromptSupplement as v, setStandaloneMemoryOwner as w, resolveMemoryFlushPlan as x, resolveLoadedMemoryProviderKind as y };