openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
586 lines (585 loc) • 23.4 kB
JavaScript
import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { u as getPluginMetadataSnapshotCache } from "./plugin-cache-B_eRuqTM.mjs";
import { t as normalizePluginPolicyId } from "./plugin-policy-id-CkilMowp.mjs";
import { u as normalizePluginsConfig } from "./config-state-B1JlHgba.mjs";
import { t as loadPluginManifestRegistryCore } from "./manifest-registry-CuWv8ibc.mjs";
import { l as getPluginValueInstance, m as runPluginCleanup } from "./plugin-instance-scope-oezVdCr2.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { S as listPluginCacheRetiringRegistries } from "./registry-lifecycle-CJjWnl-y.mjs";
import { Z as withPluginHostCleanupTimeout } from "./runtime-ezCEpumg.mjs";
import { a as runPluginCleanupScope } from "./registry-inspection-resources-CDO3vUtM.mjs";
import { n as loadPluginRegistryHandle } from "./loader--j41eir2.mjs";
import { C as setStandaloneMemoryManagerActive, a as getMemoryCapabilityRegistration, b as resolveMemoryCapabilityRegistration, c as getMemoryRuntime, s as getMemoryProviderRuntime, w as setStandaloneMemoryOwner } from "./memory-state-BAtmlQOR.mjs";
import { a as isHostMemoryAudience, r as assertMemoryCallerCurrent, s as prepareMemoryCallerRead } from "./memory-audience-RRQiHS6M.mjs";
import { a as stripMemoryAnnotationCarriers } from "./curated-annotations-GumWCHHf.mjs";
import { i as readMemorySearchManagerStatus, n as isAutomaticMemoryEntryEligible, s as resolveMemorySearchStaleness } from "./types-Bo5s7TN4.mjs";
import path from "node:path";
import fs from "node:fs/promises";
//#region src/plugins/memory-provider-adapter.ts
function legacyCoverageWarning(e) {
const t = resolveMemorySearchStaleness(e);
if (t) return t.warning;
const n = e.custom?.providerState;
if (n && typeof n === "object" && "mode" in n) {
if (n.mode === "pending" && e.requestedProvider !== "none") return "Memory embeddings are pending. Search results may be incomplete.";
if (n.mode === "degraded" || n.mode === "fts-only" && e.requestedProvider !== void 0 && e.requestedProvider !== "none") return "Memory embeddings are unavailable. Keyword search remains available; results may be incomplete.";
}
if (e.dirty) return "Memory indexing is pending. Search results may be incomplete.";
if (e.provider !== "none" && e.vector?.enabled && (e.vector.index?.state === "incomplete" || e.vector.index?.state === "unverified")) return "Memory vector indexing is incomplete. Search results may be incomplete.";
}
const refreshHandoffs = /* @__PURE__ */ new WeakMap();
/** Join caller admission before handing asynchronous refresh to the provider owner. */
function refreshMemoryProviderWithHandoff(e, t) {
const n = refreshHandoffs.get(e);
if (!n) throw new Error("memory refresh requires a bound provider handle");
return n(t);
}
/** Recheck both caller and provider lifetime after every asynchronous boundary. */
function bindMemoryProvider(e, t, n, r) {
let i = false;
const a = getPluginValueInstance(e) ?? (r ? getPluginValueInstance(r) : void 0);
const assertCurrent = (e) => {
if (i) throw new Error("memory provider handle is closed");
assertMemoryCallerCurrent(n);
if (a && (e && !a.acceptingCalls || a.owner?.revoked || a.lifecycle.signal.aborted)) throw new Error("memory provider instance is no longer current");
};
const invoke = async (e) => {
const t = prepareMemoryCallerRead(n);
if (t) await racePromiseWithAbortSignal(t, n.signal);
assertCurrent(true);
const r = await e();
const i = prepareMemoryCallerRead(n);
if (i) await racePromiseWithAbortSignal(i, n.signal);
assertCurrent(false);
return r;
};
const assertReference = (e) => {
if (e.providerId !== t) throw new Error("memory reference belongs to a different provider");
};
const assertCitations = (e) => {
for (const t of e ?? []) if (t.reference) assertReference(t.reference);
};
const validatePage = (e) => {
for (const t of e.hits) {
assertReference(t.reference);
assertCitations(t.citations);
}
return e;
};
const o = Object.freeze({
...e.capabilities,
sources: Object.freeze([...e.capabilities.sources]),
candidates: Object.freeze([...e.capabilities.candidates])
});
const assertSearchCapabilities = (e) => {
const t = e.sources?.find((e) => !o.sources.includes(e));
if (t) throw new Error(`memory provider does not support the ${t} source capability`);
if (e.cursor !== void 0 && !o.pagination) throw new Error("memory provider does not support the pagination capability");
if (e.activeProjectKeys?.length && !o.projectFilter) throw new Error("memory provider does not support the project filter capability");
};
const s = e.refresh ? (t) => invoke(() => {
const n = e.refresh();
t?.();
return n;
}) : void 0;
const c = {
capabilities: o,
search: (t) => invoke(async () => {
assertSearchCapabilities(t);
return validatePage(await e.search(t));
}),
get: (t) => invoke(async () => {
assertReference(t.reference);
const n = await e.get(t);
if (n.status === "ok") {
assertReference(n.reference);
assertCitations(n.citations);
}
return n;
}),
health: () => invoke(() => e.health()),
...e.candidates ? { candidates: (t) => {
return invoke(async () => {
if (!o.candidates.includes(t.kind)) throw new Error(`memory provider does not support the ${t.kind} candidates capability`);
if (t.activeProjectKeys?.length && !o.projectFilter) throw new Error("memory provider does not support the project filter capability");
return validatePage(await e.candidates(t));
});
} } : {},
...s ? { refresh: () => s() } : {},
async close() {
if (i) return;
i = true;
await runPluginCleanup(e, () => e.close());
}
};
if (s) refreshHandoffs.set(c, s);
return c;
}
function redactLegacyHealthDetails(e) {
const { workspaceDir: t, dbPath: n, extraPaths: r, ...i } = e;
if (!i.vector) return i;
const { extensionPath: a, ...o } = i.vector;
return {
...i,
vector: o
};
}
/** Translate the legacy contract without mutating managers or changing their receiver. */
async function adaptLegacyMemoryProvider(e, t, n) {
const r = await e.getMemorySearchManager({
cfg: n.cfg,
agentId: n.agentId,
purpose: n.purpose
});
const i = r.manager;
if (!i) return {
provider: null,
error: r.error
};
const { context: a } = n;
const o = a.authority.kind === "session" ? a.authority : void 0;
const assertCurrent = () => {
a.assertCurrent();
a.signal?.throwIfAborted();
};
const authorize = async (t) => {
assertCurrent();
const r = e.authorizeSearchHits ? await e.authorizeSearchHits({
cfg: n.cfg,
agentId: n.agentId,
requesterSessionKey: o?.sessionKey,
sandboxed: o?.sandboxed ?? false,
trustedAgentScope: !o,
conversationRecall: o?.conversationRecall,
hits: t
}) : t.filter((e) => e.source !== "sessions");
assertCurrent();
return r;
};
const convert = (e) => {
const n = {
providerId: t,
id: e.path,
fragment: `L${e.startLine}-L${e.endLine}`
};
const r = e.projectKey?.split(";").map((e) => e.trim()).filter(Boolean);
return {
reference: n,
excerpt: stripMemoryAnnotationCarriers(e.snippet),
score: e.score,
source: e.source,
citations: [{
label: e.citation ?? `${e.path}#L${e.startLine}-L${e.endLine}`,
reference: n,
startLine: e.startLine,
endLine: e.endLine
}],
automaticRecall: {
eligible: e.source === "memory" && isAutomaticMemoryEntryEligible(e) && r?.length !== 0,
projectKeys: r,
triggers: e.triggers,
importance: e.importance
}
};
};
const readCoverage = async (e) => {
try {
const t = await readMemorySearchManagerStatus(i, { includeCounts: e });
return {
status: t,
warning: legacyCoverageWarning(t)
};
} catch {
assertCurrent();
return { warning: "Memory index coverage could not be verified. Search results may be incomplete." };
}
};
return { provider: {
capabilities: {
sources: ["memory", "sessions"],
pagination: false,
candidates: [],
projectFilter: true
},
async search(e) {
if (e.cursor !== void 0) throw new Error("legacy memory search does not support cursors");
if (typeof i.search !== "function") throw new Error("memory runtime manager must implement search");
const { query: t, cursor: n, activeProjectKeys: r, ...s } = e;
const c = await i.search(t, {
...s,
activeProjectKeys: r ? [...r] : void 0,
sessionKey: o?.sessionKey,
signal: a.signal
});
const l = (await authorize(c)).map(convert);
const { warning: u } = await readCoverage(false);
return {
hits: l,
coverage: u ? "partial" : "complete",
...u ? { warning: u } : {}
};
},
async get(e) {
if (typeof i.readFile !== "function") throw new Error("memory runtime manager must implement readFile");
const n = await i.readFile({
relPath: e.reference.id,
from: e.from,
lines: e.lines
});
if (n.status === "not_found") return { status: "not_found" };
return {
status: "ok",
reference: {
providerId: t,
id: n.path
},
text: n.text,
truncated: n.truncated,
from: n.from,
lines: n.lines,
nextFrom: n.nextFrom
};
},
async health() {
const { status: e, warning: t } = await readCoverage();
return {
status: t ? "degraded" : "ready",
message: t,
...e ? { details: { legacy: redactLegacyHealthDetails(e) } } : {}
};
},
...i.sync ? { refresh: () => i.sync({ reason: "provider-refresh" }) } : {},
async close() {
if (n.purpose === "cli" || n.purpose === "status") await runPluginCleanup(i, () => i.close?.());
}
} };
}
//#endregion
//#region src/plugins/memory-runtime.ts
const enrolledStandaloneMemoryRuntimes = /* @__PURE__ */ new WeakSet();
let standaloneMemoryRegistrySlot;
const registeredMemoryManagerAdapters = /* @__PURE__ */ new WeakMap();
function normalizeRegisteredMemoryManager(e) {
const t = registeredMemoryManagerAdapters.get(e);
if (t) return t;
const readFile = async (t) => {
const n = await e.readFile(t);
return n.status === "ok" || n.status === "not_found" ? n : {
...n,
status: "ok"
};
};
const n = new Proxy({ readFile }, { get(t, n) {
if (n === "readFile") return readFile;
const r = Reflect.get(e, n, e);
if (typeof r !== "function") return r;
return r.bind(e);
} });
registeredMemoryManagerAdapters.set(e, n);
return n;
}
/** Resolves the configured memory slot to the single runtime plugin that may load memory. */
function resolveMemoryRuntimePluginIds(e) {
const t = normalizePluginsConfig(e.plugins);
const n = t.slots.memory;
if (!t.enabled || !n) return [];
const r = normalizePluginPolicyId(n);
if (t.deny.includes(r) || t.entries[r]?.enabled === false) return [];
return [n];
}
function listCurrentMemoryRuntimes() {
const e = new Set(standaloneMemoryRegistrySlot?.retiredRuntimes);
for (const t of [
getMemoryRuntime(),
getMemoryProviderRuntime(),
standaloneMemoryRegistrySlot?.providerRuntime,
standaloneMemoryRegistrySlot?.runtime
]) if (t) e.add(t);
return [...e];
}
function assertMemoryProviderRuntime(e) {
if (e !== void 0 && (!e || typeof e.open !== "function")) throw new Error("memory providerRuntime must implement open");
}
function isValidMemoryProviderCapabilities(e) {
return Array.isArray(e?.sources) && e.sources.length > 0 && e.sources.every((e) => e === "memory" || e === "sessions") && typeof e.pagination === "boolean" && Array.isArray(e.candidates) && e.candidates.every((e) => e === "trigger" || e === "project") && typeof e.projectFilter === "boolean";
}
function ensureMemoryRuntime(e) {
const t = getMemoryRuntime();
const n = getMemoryProviderRuntime();
assertMemoryProviderRuntime(n);
if (t || n) return {
runtime: t,
providerRuntime: n,
providerId: getMemoryCapabilityRegistration()?.pluginId,
searchRuntimeRegistered: true
};
const r = resolveMemoryRuntimePluginIds(e.cfg);
if (r.length === 0) return;
const i = resolveAgentWorkspaceDir(e.cfg, e.agentId);
const a = loadPluginRegistryHandle({
config: e.cfg,
registrationConfigOrigin: e.cfg,
manifestRegistry: loadPluginManifestRegistryCore({
config: e.cfg,
workspaceDir: i
}),
onlyPluginIds: r,
workspaceDir: i,
activate: false
});
const o = resolveMemoryCapabilityRegistration(a.memoryCapabilities);
const s = o?.capability.runtime;
const c = o?.capability.providerRuntime;
assertMemoryProviderRuntime(c);
const l = s || c ? void 0 : a.plugins.find((e) => e.id === r[0]);
const u = s || c ? {
runtime: s,
providerRuntime: c,
providerId: o?.pluginId,
standalone: true,
searchRuntimeRegistered: true
} : l?.status === "error" ? { error: l.error ?? `Memory plugin "${l.id}" failed to load` } : l?.status === "loaded" && l.memorySlotSelected === true ? { searchRuntimeRegistered: false } : void 0;
const d = standaloneMemoryRegistrySlot;
if (d?.runtime === s && d?.providerRuntime === c) return u;
const f = new Set(d?.retiredRuntimes);
for (const e of [d?.runtime, d?.providerRuntime]) if (e) f.add(e);
standaloneMemoryRegistrySlot = {
runtime: s,
providerRuntime: c,
retiredRuntimes: f
};
setStandaloneMemoryOwner(o && (s || c) ? {
pluginId: o.pluginId,
native: c !== void 0
} : void 0);
for (const e of [u?.runtime, u?.providerRuntime]) if (e && !enrolledStandaloneMemoryRuntimes.has(e)) {
const t = getPluginValueInstance(e)?.lifecycle;
if (t) {
t.onDispose(() => {
const t = standaloneMemoryRegistrySlot;
t?.retiredRuntimes.delete(e);
if (t?.runtime === e) delete t.runtime;
if (t?.providerRuntime === e) delete t.providerRuntime;
});
enrolledStandaloneMemoryRuntimes.add(e);
}
}
return u;
}
/** Returns the active plugin-backed memory search manager for an agent. */
async function getActiveMemorySearchManagerCore(e) {
const t = ensureMemoryRuntime(e);
if (!t?.runtime) return {
manager: null,
error: t?.error ?? "memory plugin unavailable",
searchRuntimeRegistered: t?.searchRuntimeRegistered
};
if (t.standalone) setStandaloneMemoryManagerActive(true);
const n = await t.runtime.getMemorySearchManager(e);
return {
...n,
manager: n.manager ? normalizeRegisteredMemoryManager(n.manager) : null,
...t.runtime.searchForCli ? { searchForCli: t.runtime.searchForCli.bind(t.runtime) } : {},
searchRuntimeRegistered: true
};
}
/** Applies the selected memory plugin's authorization policy to raw search hits. */
async function authorizeActiveMemorySearchHits(e) {
const t = ensureMemoryRuntime(e);
return t?.runtime?.authorizeSearchHits ? await t.runtime.authorizeSearchHits(e) : e.hits.filter((e) => e.source !== "sessions");
}
/**
* Reports whether the selected slot owner registers the provider-neutral runtime.
* Consumers keep their legacy manager path for every other owner, so this resolves
* the owner the same way that path would without opening a manager.
*/
function isActiveMemoryProviderNative(e) {
return ensureMemoryRuntime(e)?.providerRuntime !== void 0;
}
/** Resolves one selected provider; native provider failures never retry through legacy storage. */
async function getActiveMemoryProviderCore(e) {
if (typeof e.context.assertCurrent !== "function") throw new Error("memory provider requires caller authority with assertCurrent");
if (e.context.authority.kind === "session" && e.context.authority.audience !== void 0 && !isHostMemoryAudience(e.context.authority.audience)) throw new Error("memory provider requires a host-minted memory audience");
const t = {
...e.context,
assertCurrent: () => assertMemoryCallerCurrent(e.context)
};
const n = {
...e,
context: t
};
const r = prepareMemoryCallerRead(t);
if (r) await racePromiseWithAbortSignal(r, t.signal);
t.assertCurrent();
const i = ensureMemoryRuntime(e);
if (!i?.runtime && !i?.providerRuntime) return {
provider: null,
error: i?.error ?? "memory plugin unavailable"
};
if (i.standalone) setStandaloneMemoryManagerActive(true);
const a = i.providerId ?? normalizePluginsConfig(e.cfg.plugins).slots.memory;
if (typeof a !== "string" || !a) return {
provider: null,
error: "memory provider identity unavailable"
};
const o = i.providerRuntime ? "native" : "legacy";
const s = i.providerRuntime ? await i.providerRuntime.open(n) : await adaptLegacyMemoryProvider(i.runtime, a, n);
try {
const e = prepareMemoryCallerRead(t);
if (e) await racePromiseWithAbortSignal(e, t.signal);
t.assertCurrent();
if (s.provider && (typeof s.provider.search !== "function" || typeof s.provider.get !== "function" || typeof s.provider.health !== "function" || typeof s.provider.close !== "function" || !isValidMemoryProviderCapabilities(s.provider.capabilities) || s.provider.capabilities.candidates.length > 0 !== (typeof s.provider.candidates === "function"))) throw new Error("memory provider must implement search, get, health, close, and valid capabilities with matching candidates");
} catch (e) {
if (s.provider && typeof s.provider.close === "function") await runPluginCleanup(s.provider, () => s.provider.close());
throw e;
}
return {
...s,
providerId: a,
adapter: o,
provider: s.provider ? bindMemoryProvider(s.provider, a, e.context, i.providerRuntime ?? i.runtime) : null
};
}
/** Classifies workspace memory paths through the selected memory plugin's provenance owner. */
async function classifyActiveMemoryWorkspacePaths(e) {
const t = ensureMemoryRuntime(e);
if (!t?.runtime) return { status: "unavailable" };
if (!t.runtime.classifyWorkspaceMemoryPaths || e.readSources !== void 0 && !t.runtime.supportsWorkspaceMemoryReadSources) {
const { normalizeMemoryArtifactRelativePath: t, readMemoryArtifactProvenance: n } = await import("./memory-artifact-provenance-vYO2ZFVF.mjs");
const r = e.readSources === void 0 ? await fs.realpath(e.workspaceDir).catch(() => void 0) : void 0;
return {
status: "classified",
classifications: await Promise.all(e.relativePaths.map(async (i) => {
let a = e.readSources?.find((e) => e.relativePath === i)?.canonicalRelativePath;
if (e.readSources === void 0 && r) {
const t = await fs.realpath(path.resolve(e.workspaceDir, i)).catch(() => void 0);
if (t) a = path.relative(r, t).replaceAll(path.sep, "/");
}
const o = a && t(a);
if (!o || o.includes("\0") || o !== a || path.posix.normalize(o) !== o) return {
relativePath: i,
originClass: "untrusted"
};
return {
relativePath: i,
originClass: (await n({
workspaceDir: e.workspaceDir,
relativePath: o
}))?.originClass ?? "agent"
};
}))
};
}
return {
status: "classified",
classifications: await t.runtime.classifyWorkspaceMemoryPaths(e)
};
}
/** Resolves current memory backend config without constructing a manager. */
function resolveActiveMemoryBackendConfig(e) {
const t = ensureMemoryRuntime(e);
if (t?.providerRuntime) {
const n = t.providerId ?? normalizePluginsConfig(e.cfg.plugins).slots.memory?.trim();
return n ? {
backend: "provider-runtime",
providerId: n
} : null;
}
return t?.runtime ? t.runtime.resolveMemoryBackendConfig(e) : null;
}
/** Closes all active plugin-backed memory search managers. */
async function closeActiveMemorySearchManagersCore(e) {
await Promise.all(listCurrentMemoryRuntimes().map(async (e) => runPluginCleanup(e, () => e.closeAllMemorySearchManagers?.())));
standaloneMemoryRegistrySlot?.retiredRuntimes.clear();
setStandaloneMemoryManagerActive(false);
}
/** Closes the plugin-backed memory search manager for one agent. */
async function closeActiveMemorySearchManagerCore(e) {
await Promise.all(listCurrentMemoryRuntimes().map(async (t) => runPluginCleanup(t, () => t.closeMemorySearchManager?.(e))));
}
function resetStandaloneMemoryRegistrySlot() {
standaloneMemoryRegistrySlot = void 0;
setStandaloneMemoryOwner(void 0);
setStandaloneMemoryManagerActive(false);
}
if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.memoryRuntimeTestApi")] = { resetStandaloneMemoryRegistrySlot };
/**
* Prepare memory consumers before any changed plugin loses ordinary call admission.
* `retiringMetadata` is the published metadata snapshot whose plugin cache this reload
* retires; its lazily loaded registries' adapters retire even when no plugin changes.
*/
function prepareMemoryRuntimeReload(e, t, n) {
const r = n ? listPluginCacheRetiringRegistries(getPluginMetadataSnapshotCache(n)) : [];
const runtimes = (e) => new Set(e.memoryCapabilities.flatMap(({ capability: e }) => [e.runtime, e.providerRuntime].filter((e) => e !== void 0)));
const i = runtimes(t);
const a = new Set(t.embeddingProviders.map(({ provider: e }) => e));
const o = [...new Set([e, ...r].flatMap((e) => e.embeddingProviders.map(({ provider: e }) => e)))].filter((e) => !a.has(e));
const s = [];
let c;
const resume = (e, n = t) => {
const r = [];
const i = runtimes(n);
for (const { runtime: t, handle: n } of s) if (!e || i.has(t)) try {
runPluginCleanup(t, () => n.resume());
} catch (e) {
r.push(e);
}
if (r.length) throw new AggregateError(r, "Memory reload admission recovery failed");
};
try {
for (const t of runtimes(e)) {
const e = !i.has(t);
if (!e && o.length === 0) continue;
const n = runPluginCleanup(t, () => {
if (t.prepareReload) return t.prepareReload({
retireRuntime: e,
retiringEmbeddingProviders: o
});
if (t.closeAllMemorySearchManagers) return {
drain: () => t.closeAllMemorySearchManagers(),
resume() {}
};
});
if (n) s.push({
runtime: t,
handle: n
});
}
} catch (e) {
try {
resume(false);
} catch (t) {
throw new AggregateError([e, t], "Memory reload preparation failed", { cause: t });
}
throw e;
}
const close = () => {
if (!c) c = runPluginCleanupScope([...s.map(({ runtime: e }) => e), ...o], () => Promise.allSettled(s.map(({ runtime: e, handle: t }) => Promise.resolve().then(() => runPluginCleanup(e, async () => {
try {
return await t.drain();
} catch (e) {
return { errors: [e] };
}
}))))).then((e) => {
const t = e.flatMap((e) => e.status === "rejected" ? [e.reason] : []);
if (t.length) throw new AggregateError(t, t.map(formatErrorMessage).join("; "));
return { errors: e.flatMap((e) => e.status === "fulfilled" ? e.value?.errors ?? [] : []) };
});
return c;
};
return {
restartPluginIds: new Set(o.length === 0 ? [] : e.memoryCapabilities.flatMap(({ pluginId: e, capability: t }) => [t.runtime, t.providerRuntime].some((e) => e !== void 0 && i.has(e)) ? [e] : [])),
drain: () => withPluginHostCleanupTimeout("memory managers", close),
close,
commit: (e = t) => resume(true, e),
rollback: () => {
resume(false);
return new Set(e.memoryCapabilities.flatMap(({ pluginId: e, capability: t }) => c && s.some(({ runtime: e }) => e === t.runtime || e === t.providerRuntime) ? [e] : []));
}
};
}
//#endregion
export { getActiveMemoryProviderCore as a, prepareMemoryRuntimeReload as c, closeActiveMemorySearchManagersCore as i, resolveActiveMemoryBackendConfig as l, classifyActiveMemoryWorkspacePaths as n, getActiveMemorySearchManagerCore as o, closeActiveMemorySearchManagerCore as r, isActiveMemoryProviderNative as s, authorizeActiveMemorySearchHits as t, refreshMemoryProviderWithHandoff as u };