UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

312 lines (311 loc) • 15.2 kB
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as ok, t as err } from "./result-CV1-31DB.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import { a as isSameOpenClawAgentDatabasePath, c as resolveOpenClawAgentSqlitePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs"; import { a as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs"; import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs"; import { c as registerAgentDatabaseReaderCloser, s as matchesAgentDatabaseReadCandidatePath } from "./agent-database-readers-kAORIt-A.mjs"; import { i as captureAgentDeletionResourceOwner } from "./agent-deletion-cleanup-BweMIhGD.mjs"; import path from "node:path"; import { isMainThread } from "node:worker_threads"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/state/agent-creation-claim.ts const creationClaim = resolveGlobalSingleton(Symbol.for("openclaw.agentCreationClaim"), () => new AsyncLocalStorage()); const creationResources = resolveGlobalSingleton(Symbol.for("openclaw.agentCreationClaimResources"), () => /* @__PURE__ */ new Map()); /** Runs creation-owned staging that may write the recreated identity's databases. */ async function runWithAgentCreationClaim(e, t) { let n = true; const r = /* @__PURE__ */ new Set(); let i; const closeHandles = () => { i ??= (async () => { const e = []; for (const t of [...r].toReversed()) try { await t(); r.delete(t); } catch (t) { e.push(t); } return e; })().finally(() => { i = void 0; }); return i; }; const a = { kind: "host", agentId: normalizeAgentId(e.agentId), statePath: path.resolve(resolveOpenClawStateSqlitePath(e.env ?? process.env)), isActive: () => n, registerClose: (e) => { if (!n) throw new Error("Agent creation claim is no longer active."); r.add(e); }, retryClose: async () => { if (n) throw new Error("Agent database belongs to an active agent creation claim."); await i; const e = await closeHandles(); if (e.length > 0) throw new AggregateError(e, "Agent creation database close retry failed."); } }; return await creationClaim.run(a, async () => { let e; const r = []; try { for (const e of new Set(creationResources.values())) if (e.agentId === a.agentId && e.statePath === a.statePath) await e.retryClose(); e = ok(await t()); } catch (t) { e = err(t); } finally { n = false; r.push(...await closeHandles()); } if (!e.ok) throw r.length > 0 ? new AggregateError([e.error, ...r], "Agent creation claim failed.") : e.error; if (r.length > 0) throw r.length === 1 ? r[0] : new AggregateError(r, "Agent creation claim failed."); return e.value; }); } function getActiveAgentCreationClaim(e, t) { const n = creationClaim.getStore(); if (!n || n.kind !== "host" || !n.isActive() || n.agentId !== normalizeAgentId(e) || n.statePath !== path.resolve(t)) return; return n; } /** The identity the live creation scope may admit beneath its own completed deletion record. */ function resolveAgentCreationClaimAgentId(e, t) { const n = creationClaim.getStore(); if (n && n.kind === "worker" && n.agentId === normalizeAgentId(e) && n.statePath === path.resolve(t)) { n.assertCurrent(); return n.agentId; } return getActiveAgentCreationClaim(e, t)?.agentId; } /** The transport carries identity; the retained host scope remains the authority. */ function captureAgentCreationClaim(e) { const t = getActiveAgentCreationClaim(e.agentId, resolveOpenClawStateSqlitePath(e.env ?? process.env)); if (!t) return; return { witness: { agentId: t.agentId, statePath: t.statePath }, assertCurrent() { if (!t.isActive() || creationClaim.getStore() !== t) throw new Error("Agent database belongs to an active agent creation claim."); } }; } /** Native admission borrows the host claim; its executor already owns native cleanup. */ function withAgentCreationClaimWitness(e, t, n) { if (isMainThread) throw new Error("Agent creation witnesses require their native worker"); t(); return creationClaim.run({ kind: "worker", ...e, assertCurrent: t }, n); } /** Hold pending native custody until publication hands it to the handle, or disposal succeeds. */ function reserveAgentCreationClaimAdmission(e, t, n) { const r = getActiveAgentCreationClaim(t.agentId, resolveOpenClawStateSqlitePath(t.env ?? process.env)); if (!r) return; creationResources.set(e, r); r.registerClose(async () => { if (creationResources.get(e) !== r) return; await n(); creationResources.delete(e); }); return () => { creationResources.delete(e); }; } /** Tag a freshly opened handle as owned by the live creation scope for its identity. */ function registerAgentCreationClaimHandle(e, t) { const n = getActiveAgentCreationClaim(t.agentId, resolveOpenClawStateSqlitePath(t.env ?? process.env)); if (n) creationResources.set(e, n); return n; } /** Refuse a creation-owned handle to every caller outside that same live scope. */ function assertAgentCreationClaimAccess(e, t) { assertAgentCreationClaimCurrent(t); const n = creationResources.get(e); if (!n) return; if (n !== getActiveAgentCreationClaim(t.agentId, resolveOpenClawStateSqlitePath(t.env ?? process.env))) throw new Error("Agent database belongs to an active agent creation claim."); } /** A retained admission must stop before resuming native work after settlement. */ function assertAgentCreationClaimCurrent(e) { const t = creationClaim.getStore(); if (t && t.kind === "host" && !t.isActive() && t.agentId === normalizeAgentId(e.agentId) && t.statePath === path.resolve(resolveOpenClawStateSqlitePath(e.env ?? process.env))) throw new Error("Agent creation claim is no longer active."); } /** A different spelling or state root must not borrow a creation-owned physical store. */ function assertAgentCreationClaimAliases(e) { const t = resolveOpenClawAgentSqlitePath(e); for (const n of creationResources.keys()) if (isSameOpenClawAgentDatabasePath(n.path, t)) assertAgentCreationClaimAccess(n, e); } /** Release the tag once the native owner has closed the handle. */ function releaseAgentCreationClaimHandle(e) { creationResources.delete(e); } //#endregion //#region src/state/agent-database-admission-error.ts /** A database owner refused new work; an admitted command's failure is never classified here. */ const AgentDatabaseExecutionAdmissionClosedError = resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseExecutionAdmissionClosedError"), () => class AdmissionClosedError extends Error {}); /** A receipt lost its publication race; fresh admission can obtain current proof. */ const AgentDatabaseSchemaAdmissionChangedError = resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseSchemaAdmissionChangedError"), () => class SchemaAdmissionChangedError extends Error { constructor() { super("Agent schema admission changed before publication; retry the operation"); } }); const AgentDatabaseSchemaAdmissionInvalidError = resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseSchemaAdmissionInvalidError"), () => class SchemaAdmissionInvalidError extends Error { constructor() { super("Invalid agent schema admission receipt"); } }); /** Runtime publications kept replacing this one past its retries; the database stayed intact. */ const AgentDatabaseStartupPublicationError = resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseStartupPublicationError"), () => class StartupPublicationError extends Error { constructor(e) { super(formatErrorMessage(e), { cause: e }); } }); //#endregion //#region src/state/openclaw-agent-db-resources.ts const resources = resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseAsyncResources"), () => ({ active: /* @__PURE__ */ new Set(), closing: /* @__PURE__ */ new Map(), selections: /* @__PURE__ */ new Map() })); /** CLI cleanup can skip loading native database owners when no Worker was admitted. */ function hasOpenClawAgentDatabaseAsyncResources() { return resources.active.size > 0 || resources.closing.size > 0; } /** Observe a full close without admitting a reader into its retiring lifetime. */ function isAgentDatabaseClosing(e) { const t = { agentId: normalizeAgentId(e.agentId), path: path.resolve(e.path) }; return [...resources.selections.keys()].some((e) => matchesAgentDatabaseClose(e, t)); } registerAgentDatabaseReaderCloser(async (e, t) => { const n = (await Promise.allSettled([.../* @__PURE__ */ new Set([...resources.active, ...resources.closing.keys()])].filter((n) => !t?.has(path.resolve(n.path)) && e.some((e) => matchesAgentDatabaseReadCandidatePath(e, n.path))).map((e) => closeAgentDatabaseResource(e)))).flatMap((e) => e.status === "rejected" ? [e.reason] : []); if (n.length > 0) throw new AggregateError(n, "Agent database resource cleanup failed"); }); function matchesAgentDatabaseClose(e, t) { return (e.path === void 0 || e.path === t.path || t.ownership === "unresolved" && matchesAgentDatabaseReadCandidatePath(t, e.path)) && (e.rootPath === void 0 || isPathInside(e.rootPath, t.path) || t.ownership === "unresolved" && matchesAgentDatabaseReadCandidatePath(t, e.rootPath)) && (e.agentId === void 0 || t.ownership === "unresolved" || e.agentId === t.agentId); } /** Register before admitting a Worker; revocation is synchronous, native drainage is joined. */ function registerOpenClawAgentDatabaseAsyncResource(e, t) { return registerAgentDatabaseResource({ ...e, ownership: "known", agentId: normalizeAgentId(e.agentId) }, t); } /** Native readers close synchronously, so successful retirement leaves no asynchronous barrier. */ function registerOpenClawAgentDatabaseSyncResource(e) { return registerAgentDatabaseResource({ ...e, ownership: "known", agentId: normalizeAgentId(e.agentId), close: async () => e.close(), closeSync: e.close }); } /** Retain discovery until the known owner is registered, then release this candidate. */ function registerOpenClawAgentDatabaseReadCandidateResource(e) { return registerAgentDatabaseResource({ ...e, ownership: "unresolved" }); } function registerAgentDatabaseResource(e, t) { const n = { ...e, path: path.resolve(e.path) }; n.cleanupOwner = captureAgentDeletionResourceOwner((e) => matchesAgentDatabaseClose(e, n)); assertAgentDatabaseResourceAdmission(n); const r = t && n.ownership === "known" ? reserveAgentCreationClaimAdmission(n, t, () => closeAgentDatabaseResource(n)) : void 0; const unregister = () => { resources.active.delete(n); r?.(); }; getOpenClawDatabaseMaintenanceScope()?.own(unregister, "agent-resources", () => closeAgentDatabaseResource(n)); resources.active.add(n); return unregister; } /** Fresh native opens and resource registrations share the same close custody. */ function assertAgentDatabaseResourceAdmission(e) { if ([...resources.selections.keys()].some((t) => matchesAgentDatabaseClose(t, e)) || [...resources.closing.keys()].some((t) => (t.path === e.path || t.ownership === "unresolved" && matchesAgentDatabaseReadCandidatePath(t, e.path) || e.ownership === "unresolved" && matchesAgentDatabaseReadCandidatePath(e, t.path)) && (t.ownership === "unresolved" || e.ownership === "unresolved" || t.agentId === e.agentId))) throw new AgentDatabaseExecutionAdmissionClosedError(`Agent database resources are closing: ${e.path}`); } function closeAgentDatabaseResource(e, t) { if (e.ownership === "known" && e.closeSync) { resources.closing.set(e, void 0); try { e.revoke(); e.closeSync(); resources.active.delete(e); resources.closing.delete(e); return Promise.resolve(); } catch (n) { if (t) t(e.path, n); const r = Promise.reject(toErrorObject(n, "Agent database cleanup failed")); r.catch(() => {}); return r; } } let n = resources.closing.get(e); if (!n) { n = Promise.resolve().then(() => e.close()); resources.closing.set(e, n); n.then(() => { resources.active.delete(e); resources.closing.delete(e); }, () => { resources.closing.set(e, void 0); }).catch(() => {}); } if (t) n.catch((n) => t(e.path, n)).catch(() => {}); e.revoke(); return n; } function revokeAgentDatabaseResources(e, t) { const n = /* @__PURE__ */ new Set([...resources.active, ...resources.closing.keys()]); const r = []; for (const i of n) { if (!matchesAgentDatabaseClose(e, i)) continue; r.push(closeAgentDatabaseResource(i, t)); } return r; } async function drainAgentDatabaseResources(e, t, n) { return withAgentDatabaseCloseFence(e, async () => { const r = [.../* @__PURE__ */ new Set([...resources.active, ...resources.closing.keys()])].filter((t) => matchesAgentDatabaseClose(e, t) && (!n || t.cleanupOwner === n)); const i = r.filter((e) => e.retireAfterResources); for (const e of i) { if (!resources.closing.has(e)) resources.closing.set(e, void 0); e.revoke(); } const a = (await Promise.allSettled(r.filter((e) => !e.retireAfterResources).map((e) => closeAgentDatabaseResource(e)))).flatMap((e) => e.status === "rejected" ? [e.reason] : []); if (a.length > 0) throw new AggregateError(a, "Agent database resource drainage failed"); const o = (await Promise.allSettled(i.map((e) => closeAgentDatabaseResource(e)))).flatMap((e) => e.status === "rejected" ? [e.reason] : []); if (o.length > 0) throw new AggregateError(o, "Agent database native retirement failed"); return t(); }); } /** Keep the complete selection fenced while its physical databases retire independently. */ async function withAgentDatabaseCloseFence(e, t) { const n = { ...e }; resources.selections.set(n, void 0); try { const e = t([.../* @__PURE__ */ new Set([...resources.active, ...resources.closing.keys()])].filter((e) => matchesAgentDatabaseClose(n, e)).map((e) => e.path)); resources.selections.set(n, e); return await e; } finally { resources.selections.delete(n); } } //#endregion export { runWithAgentCreationClaim as C, resolveAgentCreationClaimAgentId as S, assertAgentCreationClaimCurrent as _, matchesAgentDatabaseClose as a, releaseAgentCreationClaimHandle as b, registerOpenClawAgentDatabaseSyncResource as c, AgentDatabaseExecutionAdmissionClosedError as d, AgentDatabaseSchemaAdmissionChangedError as f, assertAgentCreationClaimAliases as g, assertAgentCreationClaimAccess as h, isAgentDatabaseClosing as i, revokeAgentDatabaseResources as l, AgentDatabaseStartupPublicationError as m, drainAgentDatabaseResources as n, registerOpenClawAgentDatabaseAsyncResource as o, AgentDatabaseSchemaAdmissionInvalidError as p, hasOpenClawAgentDatabaseAsyncResources as r, registerOpenClawAgentDatabaseReadCandidateResource as s, assertAgentDatabaseResourceAdmission as t, withAgentDatabaseCloseFence as u, captureAgentCreationClaim as v, withAgentCreationClaimWitness as w, reserveAgentCreationClaimAdmission as x, registerAgentCreationClaimHandle as y };