openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
291 lines (290 loc) • 10.7 kB
JavaScript
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { O as appendPluginInstanceCleanupFailures } from "./plugin-cache-B_eRuqTM.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { t as isConfiguredSessionStoreAgentId } from "./targets-configured-agents-CQxugAIz.mjs";
import { a as getRuntimeConfigSnapshot } from "./runtime-snapshot-WbwbY5b7.mjs";
import { m as runPluginCleanup, r as getPluginInstance } from "./plugin-instance-scope-oezVdCr2.mjs";
import { l as getPluginRecordRegistry } from "./registry-lifecycle-CJjWnl-y.mjs";
import { L as cleanupPluginSessionSchedulerJobs, R as clearPluginRunContext, V as makePluginSessionSchedulerJobKey, Z as withPluginHostCleanupTimeout, l as getActivePluginRegistry } from "./runtime-ezCEpumg.mjs";
import { a as normalizeOptionalAgentRuntimeId } from "./agent-runtime-id-D8s1CaYB.mjs";
import { t as captureRuntimeConfigAsyncReader } from "./io.runtime-DsJ2dLCQ.mjs";
import { S as readAgentDatabaseAdmissionRefusal } from "./agent-database-admission-CL6wHJ_N.mjs";
import "./targets-BVE0__Jb.mjs";
import "./session-accessor-CizTbDQj.mjs";
import { h as cleanupPluginHostSessionStore } from "./session-accessor.entry-mutation-IJ4DYZ4a.mjs";
import { n as resolveAllAgentSessionStoreTargetsAsync } from "./targets-runtime-pFH3Bycg.mjs";
import { r as getPluginRuntimeLoadContext } from "./load-context-CwTU1iXB.mjs";
import { a as listRetainedDeletedAgentIdsForCleanup } from "./agent-deletion-discovery-BUESMyCH.mjs";
//#region src/plugins/host-hook-cleanup.ts
const log = createSubsystemLogger("plugins/cleanup");
function shouldCleanPlugin(e, t) {
return !t || e === t;
}
async function clearPluginSessionStores(e) {
if (!e.pluginId && !e.sessionKey || e.mode === "promoted-slots" && e.sessionEntrySlotKeys?.size === 0) return 0;
const t = e.storeTargets ?? await e.resolveStoreTargets?.() ?? await resolveAllAgentSessionStoreTargetsAsync(e.cfg);
let n = /* @__PURE__ */ new Set();
if (t.some((t) => !isConfiguredSessionStoreAgentId(e.cfg, t.agentId))) try {
n = await listRetainedDeletedAgentIdsForCleanup(process.env);
} catch {}
let r = 0;
for (const i of t) {
if (e.shouldCleanup && !e.shouldCleanup()) break;
try {
if (readAgentDatabaseAdmissionRefusal(i.agentId)) continue;
if (!isConfiguredSessionStoreAgentId(e.cfg, i.agentId) && n.has(i.agentId)) continue;
r += await cleanupPluginHostSessionStore({
agentId: i.agentId,
storePath: i.storePath,
mode: e.mode,
pluginId: e.pluginId,
sessionKey: e.sessionKey,
sessionEntrySlotKeys: e.sessionEntrySlotKeys,
preserveLockedHarnessIds: e.preserveLockedHarnessIds,
shouldCleanup: e.shouldCleanup
});
} catch (t) {
e.failures.push({
pluginId: e.pluginId ?? "plugin-host",
hookId: "session-store",
error: t
});
}
}
return r;
}
function collectSessionEntrySlotKeys(e, t) {
const n = /* @__PURE__ */ new Set();
for (const r of e?.sessionExtensions ?? []) {
if (!shouldCleanPlugin(r.pluginId, t)) continue;
const e = r.extension.sessionEntrySlotKey;
if (e === void 0) continue;
n.add(e);
}
return n;
}
function collectAgentHarnessIds(e, t) {
const n = /* @__PURE__ */ new Set();
for (const r of e?.agentHarnesses ?? []) {
if (!shouldCleanPlugin(r.pluginId, t)) continue;
const e = normalizeOptionalAgentRuntimeId(r.harness.id);
if (e) n.add(e);
}
return n;
}
/** Release callbacks before module disposal, independently of persistent-state retirement. */
async function runPluginHostLifecycleCleanup(e) {
const t = [];
let n = 0;
const r = {
reason: e.reason,
sessionKey: e.sessionKey
};
const i = [...e.registry.sessionExtensions.map(({ pluginId: e, extension: t }) => ({
pluginId: e,
hookId: `session:${t.namespace}`,
cleanup: t.cleanup,
context: r
})), ...e.registry.runtimeLifecycles.map(({ pluginId: e, lifecycle: t }) => ({
pluginId: e,
hookId: `runtime:${t.id}`,
cleanup: t.cleanup,
context: {
...r,
runId: void 0
}
}))];
for (const { pluginId: r, hookId: a, cleanup: o, context: s } of i) {
if (e.shouldCleanup?.() === false) break;
if (!o || !shouldCleanPlugin(r, e.pluginId)) continue;
try {
await withPluginHostCleanupTimeout(a, () => runPluginCleanup(o, () => o(s)));
n += 1;
} catch (e) {
t.push({
pluginId: r,
hookId: a,
error: e
});
}
}
return {
cleanupCount: n,
failures: t
};
}
/** Runs persistent and in-memory cleanup for a plugin, session, or host lifecycle event. */
async function runPluginHostCleanup(e) {
const t = [];
const n = e.shouldCleanup ?? (() => true);
if (!n()) return {
cleanupCount: 0,
failures: t
};
const r = await (async () => {
const r = e.registry;
const i = r ?? getActivePluginRegistry();
const a = collectSessionEntrySlotKeys(i, e.pluginId);
const o = e.reason === "disable" ? collectAgentHarnessIds(i, e.pluginId) : void 0;
const s = e.restartPromotedSessionEntrySlotKeys ?? a;
let c = 0;
if (!e.skipPersistentSessionState && n()) try {
c = await clearPluginSessionStores({
cfg: e.cfg ?? await captureRuntimeConfigAsyncReader()(),
mode: e.reason === "restart" ? "promoted-slots" : "plugin-owned-state",
pluginId: e.pluginId,
sessionKey: e.sessionKey,
sessionEntrySlotKeys: e.reason === "restart" ? s : a,
preserveLockedHarnessIds: o,
storeTargets: e.sessionStoreTargets,
resolveStoreTargets: e.resolveSessionStoreTargets,
shouldCleanup: n,
failures: t
});
} catch (n) {
t.push({
pluginId: e.pluginId ?? "plugin-host",
hookId: "session-store",
error: n
});
}
if (r) {
const i = await runPluginHostLifecycleCleanup({
...e,
registry: r
});
c += i.cleanupCount;
t.push(...i.failures);
if (!n()) return {
cleanupCount: c,
failures: t
};
const a = await cleanupPluginSessionSchedulerJobs({
pluginId: e.pluginId,
reason: e.reason,
sessionKey: e.sessionKey,
records: r.sessionSchedulerJobs,
preserveJobIds: e.preserveSchedulerJobIds,
cleanupOwnerRegistry: r,
preserveOwnerRegistry: e.preserveSchedulerOwnerRegistry,
shouldCleanup: n
});
t.push(...a);
}
if (e.reason !== "restart" && n()) {
const i = new Set((r?.sessionSchedulerJobs ?? []).filter((t) => !e.pluginId || t.pluginId === e.pluginId).map((e) => makePluginSessionSchedulerJobKey(e.pluginId, e.job.id)));
const a = await cleanupPluginSessionSchedulerJobs({
pluginId: e.pluginId,
reason: e.reason,
sessionKey: e.sessionKey,
preserveJobIds: e.preserveSchedulerJobIds,
excludeJobKeys: i,
cleanupOwnerRegistry: r ?? void 0,
shouldCleanup: n
});
t.push(...a);
}
if (n() && e.pluginId && e.reason !== "restart") clearPluginRunContext(e);
return {
cleanupCount: c,
failures: t
};
})();
if (e.reason === "reset" || e.reason === "delete") for (const { pluginId: t, hookId: n, error: i } of r.failures) log.warn(`Plugin host cleanup failed during session ${e.reason}; check the reported cleanup error and retry.`, {
pluginId: t,
hookId: n,
error: String(i)
});
return r;
}
function collectHostHookPluginIds(e) {
return [
...e.sessionExtensions,
...e.runtimeLifecycles,
...e.agentEventSubscriptions,
...e.sessionSchedulerJobs
].map((e) => e.pluginId);
}
function collectLoadedPluginIds(e) {
return new Set(e.plugins.filter((e) => e.status === "loaded").map((e) => e.id));
}
function collectSchedulerJobIds(e, t) {
return new Set((e?.sessionSchedulerJobs ?? []).filter((e) => e.pluginId === t).map((e) => e.job.id));
}
function collectRestartPromotedSessionEntrySlotKeys(e, t, n) {
const r = collectSessionEntrySlotKeys(e, n);
const i = collectSessionEntrySlotKeys(t, n);
for (const e of i) r.delete(e);
return r;
}
function createPluginHostRetirementObserver(e) {
return async (t) => {
const n = await Promise.all(e.map((e) => e(t)));
const r = n.flatMap((e) => e.deferredPluginIds ?? []);
return {
cleanupCount: n.reduce((e, t) => e + t.cleanupCount, 0),
failures: n.flatMap((e) => e.failures),
...r.length ? { deferredPluginIds: r } : {}
};
};
}
/** Prepares one retirement; each waiter keeps its caller's exact instance admission. */
function createPluginHostRegistryRetirement(e) {
const t = e.previousRegistry;
const n = e.shouldCleanup ?? (() => true);
if (!t || t === e.nextRegistry || !n()) return async () => ({
cleanupCount: 0,
failures: []
});
const r = e.cfg ?? getPluginRuntimeLoadContext(t)?.config ?? getRuntimeConfigSnapshot() ?? void 0;
const i = captureRuntimeConfigAsyncReader();
const a = e.nextRegistry ? collectLoadedPluginIds(e.nextRegistry) : /* @__PURE__ */ new Set();
const o = /* @__PURE__ */ new Set([...collectLoadedPluginIds(t), ...collectHostHookPluginIds(t)]);
const s = /* @__PURE__ */ new Set([...t.plugins.map((e) => e.id), ...o]);
let c;
const resolveSessionStoreTargets = async () => c ??= resolveAllAgentSessionStoreTargetsAsync(r ?? await i());
const l = [];
for (const c of s) {
const s = t.plugins.find((e) => e.id === c);
if (s && (getPluginRecordRegistry(t, s) !== t || e.nextRegistry?.plugins.includes(s))) continue;
const u = s ? getPluginInstance(s) : void 0;
const d = e.skipPersistentSessionState || a.has(c);
let f = {
cleanupCount: 0,
failures: []
};
const p = o.has(c) ? async () => {
f = await runPluginHostCleanup({
cfg: e.skipPersistentSessionState ? r : r ?? await i(),
registry: t,
pluginId: c,
reason: d ? "restart" : "disable",
preserveSchedulerJobIds: d ? collectSchedulerJobIds(e.nextRegistry, c) : void 0,
shouldCleanup: n,
restartPromotedSessionEntrySlotKeys: d ? collectRestartPromotedSessionEntrySlotKeys(t, e.nextRegistry, c) : void 0,
preserveSchedulerOwnerRegistry: d ? e.nextRegistry : void 0,
resolveSessionStoreTargets,
skipPersistentSessionState: e.skipPersistentSessionState
});
for (const e of f.failures) log.warn(`Plugin ${e.pluginId} cleanup failed (${e.hookId}): ${formatErrorMessage(e.error)}`);
} : void 0;
const m = u ? u.dispose(u.disposing ? void 0 : p) : Promise.resolve().then(p).then(() => ({ errors: [] }));
m.catch(() => {});
l.push(async (e) => {
if (e?.deferConsumers && u?.hasRetainedConsumers) return {
...f,
deferredPluginIds: [c]
};
const t = await (u ? u.dispose() : m);
const n = [...f.failures];
appendPluginInstanceCleanupFailures(n, c, t);
return {
cleanupCount: f.cleanupCount,
failures: n
};
});
}
return createPluginHostRetirementObserver(l);
}
//#endregion
export { runPluginHostCleanup as n, runPluginHostLifecycleCleanup as r, createPluginHostRegistryRetirement as t };