UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

257 lines (256 loc) • 12.8 kB
import { y as toErrorObject } from "./paths-0xDagtub.mjs"; import { W as resolveGlobalSingleton, a as resolveStateDir, n as isPathInside } from "./path-guards-quCEQx1i.mjs"; import { t as formatErrorMessage } from "./errors-hqLS1E8Y.mjs"; import "./sqlite-worker-identity-CiWdPbPl.mjs"; import { o as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-5PCLNGIM.mjs"; import { n as ok, t as err } from "./result-CV1-31DB.mjs"; import { n as matchesAgentDatabaseReadCandidatePath, r as registerAgentDatabaseReaderCloser } from "./agent-database-readers-JO-3dg3f.mjs"; import { s as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-db-async-lifecycle-DLH47xBr.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; import { isDeepStrictEqual } from "node:util"; import { realpathSync, statSync } from "node:fs"; import path from "node:path"; import "@openclaw/fs-safe/advanced"; import { isMainThread } from "node:worker_threads"; //#region packages/normalization-core/src/agent-id.ts const DEFAULT_AGENT_ID = "main"; const VALID_ID_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/i; const INVALID_CHARS_RE = /[^a-z0-9_-]+/g; const LEADING_DASH_RE = /^-+/; const TRAILING_DASH_RE = /-+$/; /** Normalizes an OpenClaw agent id to its filesystem-safe canonical form. */ function normalizeAgentId(e) { const t = normalizeAgentIdStrict(e); return t.ok ? t.value : DEFAULT_AGENT_ID; } /** Normalizes an explicitly supplied agent id without falling back to the default agent. */ function normalizeAgentIdStrict(e) { const t = (e ?? "").trim(); const n = t.toLowerCase(); if (VALID_ID_RE.test(t)) return ok(n); const r = n.replace(INVALID_CHARS_RE, "-").replace(LEADING_DASH_RE, "").replace(TRAILING_DASH_RE, "").slice(0, 64); return r ? ok(r) : err("unrepresentable"); } //#endregion //#region src/state/openclaw-agent-db.paths.ts const INCOGNITO_AGENT_SQLITE_BASENAME = "incognito-openclaw-agent.sqlite"; const agentSqlitePaths = /* @__PURE__ */ new Map(); const agentSqlitePathKeys = agentSqlitePaths.keys(); function resolveOpenClawAgentSqlitePath(e) { if (e.path != null) return path.resolve(e.path); const t = normalizeAgentId(e.agentId); const n = resolveStateDir(e.env ?? process.env); const r = `${t}:${n}`; const i = agentSqlitePaths.get(r); if (i !== void 0) return i; const a = path.resolve(n, "agents", t, "agent", "openclaw-agent.sqlite"); agentSqlitePaths.set(r, a); if (agentSqlitePaths.size > 256) { const e = agentSqlitePathKeys.next(); if (!e.done) agentSqlitePaths.delete(e.value); } return a; } /** Resolve the lexical sentinel path used by an agent's memory session owner. */ function resolveIncognitoOpenClawAgentSqlitePath(e) { return path.join(path.dirname(resolveOpenClawAgentSqlitePath(e)), INCOGNITO_AGENT_SQLITE_BASENAME); } //#endregion //#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()); 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; } /** 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); }; } //#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/agent-deletion-cleanup.ts const databaseCleanup = resolveGlobalSingleton(Symbol.for("openclaw.agentDeletionDatabaseCleanup"), () => new AsyncLocalStorage()); const cleanupHandles = resolveGlobalSingleton(Symbol.for("openclaw.agentDeletionDatabaseCleanupHandles"), () => /* @__PURE__ */ new Map()); const cleanupExecutions = resolveGlobalSingleton(Symbol.for("openclaw.agentDeletionDatabaseCleanupExecutions"), () => /* @__PURE__ */ new Map()); /** Resource registration captures only the cleanup scope that admitted this target. */ function captureAgentDeletionResourceOwner(e) { const t = databaseCleanup.getStore(); if (!t?.ownsDatabase || !e(t) && (!t.canonicalPath || !e({ agentId: t.agentId, path: t.canonicalPath }))) return; t.assertCurrentHost(); return t; } //#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 { matchesAgentDatabaseClose as a, registerOpenClawAgentDatabaseSyncResource as c, INCOGNITO_AGENT_SQLITE_BASENAME as d, resolveIncognitoOpenClawAgentSqlitePath as f, isAgentDatabaseClosing as i, revokeAgentDatabaseResources as l, normalizeAgentId as m, drainAgentDatabaseResources as n, registerOpenClawAgentDatabaseAsyncResource as o, resolveOpenClawAgentSqlitePath as p, hasOpenClawAgentDatabaseAsyncResources as r, registerOpenClawAgentDatabaseReadCandidateResource as s, assertAgentDatabaseResourceAdmission as t, withAgentDatabaseCloseFence as u };