UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

458 lines (457 loc) • 15.9 kB
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { c as inspectDatabasePathIdentitySync } from "./sqlite-worker-identity-BH8ZkJU9.mjs"; import { a as getOrLoadSqliteDatabaseAdmissionForPath, b as publishSqliteDatabaseAdmission } from "./sqlite-database-admission-DQIqro3d.mjs"; import { t as OPENCLAW_AGENT_SCHEMA_VERSION } from "./openclaw-schema-versions-E_10NoI6.mjs"; import { c as createSqliteLifecycleAggregateError, u as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-D8BU4VLa.mjs"; import { s as stageSqliteTransactionState } from "./sqlite-post-commit-BrUVQObC.mjs"; import { r as resolveDatabasePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import { i as isStateDatabaseReadAdmissionInvalidatedError } from "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs"; import { t as getDatabaseEngineInput } from "./context-DE59wyBs.mjs"; import { a as resolveSqliteDatabaseFilePaths } from "./sqlite-files-rWisKj_V.mjs"; import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs"; import { f as withExistingOpenClawStateDatabaseArtifactPreservingReadOnlyAsync, m as withExistingOpenClawStateDatabaseReadOnly, n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import "./openclaw-agent-db-contract-aCH9b8Uc.mjs"; import { t as captureOpenClawStateReadContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { a as readOpenClawAgentDatabaseIdentity } from "./openclaw-agent-db-identity-C8MGU8lp.mjs"; import { o as sessionChanges } from "./session-row-changes-BA4BqVwF.mjs"; import { r as readRegisteredAgentDatabaseRows } from "./openclaw-agent-db-registry.read-DpiFiW8m.mjs"; import { lstatSync, statSync } from "node:fs"; import path from "node:path"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/state/openclaw-agent-db-registry-listing.ts function registeredPathKey(e) { return { name: `agent.registry:${JSON.stringify([ e.agentId, path.resolve(e.path), e.identity, e.schemaVersion ?? 38 ])}`, read: (e) => typeof e === "boolean" ? e : void 0 }; } /** Physical schema admission does not register a newly used lexical alias. */ function hasRegisteredOpenClawAgentDatabasePath(e, t) { const { identity: n } = readOpenClawAgentDatabaseIdentity(e); return getOrLoadSqliteDatabaseAdmissionForPath(resolveDatabasePath(t), registeredPathKey({ ...e, identity: `file:${n}` }), () => void 0) === true; } const registry = resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseRegistryMemo"), () => ({ pending: /* @__PURE__ */ new Map(), publications: /* @__PURE__ */ new WeakSet() })); /** Registry facts retain their owner through deferred COMMIT publication. */ function emitOpenClawAgentDatabaseRegistryChange(e, t) { const n = { all: true, scope: { agentId: e, topology: true } }; registry.publications.add(n); sessionChanges.emit(n, t); } function isOpenClawAgentDatabaseRegistryChange(e) { return registry.publications.has(e); } function activateRegisteredAgentDatabasesMemo(e) { const t = resolveDatabasePath(e); if (registry.memo?.pathname !== t) registry.memo = { pathname: t, token: Symbol(t) }; return registry.memo; } /** Return the process-stable generation for the active agent database registry. */ function readOpenClawAgentDatabaseRegistryToken(e = {}) { return activateRegisteredAgentDatabasesMemo(e).token; } function invalidateRegisteredAgentDatabasesMemo(e) { return advanceRegisteredAgentDatabasesMemo(resolveDatabasePath(e)); } function advanceRegisteredAgentDatabasesMemo(e, t) { if (t?.phase === "begin") registry.pending.set(t.operation, { ...t, pathname: e }); else if (t?.phase === "finish") registry.pending.delete(t.operation); const n = registry.memo; if (n?.pathname !== e) return; const r = { pathname: e, token: Symbol(e), transition: t }; n.next = r; registry.memo = r; return { previous: n.token, current: r.token }; } function captureRegistryMutation(e, t) { try { const n = []; for (const e of t) { const t = e.capturedIdentity ?? inspectDatabasePathIdentitySync(e.path); if (!t) return; n.push({ agentId: e.agentId, path: path.resolve(e.path), physicalPath: t.canonicalPath, identity: t.key, schemaVersion: e.schemaVersion ?? 38 }); } return { kind: e, sources: n }; } catch { return; } } /** Retain physical sources before deletion removes their files; COMMIT still owns publication. */ async function prepareOpenClawAgentDatabaseRegistryRemoval(e, t) { const n = await prepareOpenClawAgentDatabaseRegistrySnapshotRead({ ...t, includeIncompatibleSchemaVersions: true }).read(); n.assertCurrent(); if (n.result.status !== "available") throw new Error("OpenClaw agent database registry is unavailable during deletion."); const r = n.result.entries.filter((t) => t.agentId === e); const i = r.length > 0 ? captureRegistryMutation("remove", r) : void 0; const a = resolveDatabasePath(t); return () => { advanceRegisteredAgentDatabasesMemo(a, { operation: Symbol("agent-registry-removal"), mutation: i, phase: "commit" }); emitOpenClawAgentDatabaseRegistryChange(e); }; } /** Stage exact registry facts at the same native transaction boundary as their rows. */ function recordOpenClawAgentDatabaseRegistryMutation(e, t, n) { const r = Symbol("agent-registry-mutation"); const i = captureRegistryMutation(t, n); for (const n of i?.sources ?? []) publishSqliteDatabaseAdmission(e.db, registeredPathKey(n), t === "upsert"); const advance = (t) => advanceRegisteredAgentDatabasesMemo(e.path, { operation: r, mutation: i, phase: t }); if (!stageSqliteTransactionState(e.db, { stage: () => advance("begin"), commit: () => { advance("commit"); advance("finish"); }, rollback: () => advance("finish") })) throw new Error("Registry mutation requires its canonical transaction publication scope"); } async function settleAgentRegistration(e, t) { let n; try { n = { ok: true, value: await t() }; } catch (e) { n = { ok: false, error: e }; } try { e.finish(await e.nativeSettlement); } catch (e) { if (!n.ok) throw createSqliteLifecycleAggregateError([n.error, e], "Agent open and registration publication failed", n.error); throw e; } if (!n.ok) throw n.error; return n.value; } /** Fence native registry settlement under its original shared generation. */ function captureOpenClawAgentDatabaseRegistration(e) { const t = { path: e.admission.databasePath }; const n = Symbol("agent-registry-registration"); const r = captureRegistryMutation(e.kind ?? "upsert", [{ agentId: e.agentId, path: e.agentPath, capturedIdentity: e.capturedIdentity }]); const advance = (i) => { const a = advanceRegisteredAgentDatabasesMemo(t.path, { operation: n, mutation: r, phase: i }); if (a) e.onRegistryChange?.(a); }; let i = false; let a = false; let o = false; const publishChange = () => { try { (e.assertPublicationCurrent ?? e.admission.assertCurrent)(); } catch (e) { if (isStateDatabaseReadAdmissionInvalidatedError(e)) return; throw e; } emitOpenClawAgentDatabaseRegistryChange(e.agentId); }; return { begin() { if (o) throw new Error("Agent database registration admission is closed"); if (!i) { i = true; advance("begin"); } }, recordCommitted(n) { if (o || !i || n.agentId !== e.agentId || n.agentPath !== e.agentPath || n.stateDatabasePath !== e.admission.databasePath || n.stateDatabaseIdentity !== e.admission.identity.key) throw new Error("Agent registration commit differs from its captured owner"); a = true; try { e.admission.assertCurrent(); } catch (e) { invalidateRegisteredAgentDatabasesMemo(t); if (isStateDatabaseReadAdmissionInvalidatedError(e)) return; throw e; } advance("commit"); }, finish(r) { if (o) return; o = true; const s = i && !a && r?.kind === "unknown"; const c = []; try { try { if (s) { const n = invalidateRegisteredAgentDatabasesMemo(t); if (n) e.onRegistryChange?.(n); } e.admission.assertCurrent(); } catch (e) { if (isStateDatabaseReadAdmissionInvalidatedError(e)) return; throw e; } finally { registry.pending.delete(n); } if (i && !s) advance("finish"); } catch (e) { c.push(e); } finally { if (a || s) try { publishChange(); } catch (e) { c.push(e); } throwSqliteLifecycleErrors(c, "Agent registration settlement failed"); } } }; } function cloneRegisteredAgentDatabases(e, t) { const n = e.map((e) => ({ ...e })); return t.includeIncompatibleSchemaVersions ? n : n.filter((e) => e.schemaVersion === 38); } function hasUnavailableMissingSqlitePath(e) { for (const t of resolveSqliteDatabaseFilePaths(e)) try { lstatSync(t); return true; } catch (e) { if (e.code !== "ENOENT") return true; } let t = path.dirname(e); while (true) { try { const e = lstatSync(t); if (!e.isSymbolicLink()) return !e.isDirectory(); try { return !statSync(t).isDirectory(); } catch { return true; } } catch (e) { if (e.code !== "ENOENT") return true; } const e = path.dirname(t); if (e === t) return false; t = e; } } var AgentDatabaseRegistryChangedError = class extends Error { constructor(e = "Agent database registry changed during discovery; retry the read.") { super(e); this.name = "AgentDatabaseRegistryChangedError"; } }; function isAgentDatabaseRegistryChangedError(e) { return e instanceof AgentDatabaseRegistryChangedError; } function readRegisteredAgentDatabases(e, t) { const n = resolveDatabasePath(e); const read = ({ db: e }) => readRegisteredAgentDatabaseRows(e, n, t); const finish = (t) => { if (t === void 0) { if (hasUnavailableMissingSqlitePath(n)) throw new Error(`OpenClaw state database ${n} is unavailable.`); return []; } return e.includeIncompatibleSchemaVersions ? t : t.filter((e) => e.schemaVersion === 38); }; return t ? withExistingOpenClawStateDatabaseArtifactPreservingReadOnlyAsync(read, e).then(finish) : finish(withExistingOpenClawStateDatabaseReadOnly(read, e)); } /** Inspect a copied registry without creating SQLite artifacts or runtime memo state. */ async function inspectOpenClawRegisteredAgentDatabases(e = {}) { if (getDatabaseEngineInput("state")) { const t = await executeExistingOpenClawStateRead(e, { type: "agentDatabaseRegistry.read" }, { current: true }); if (t?.result.status === "unavailable") throw new Error(`OpenClaw state database ${resolveDatabasePath(e)} is unavailable.`); return cloneRegisteredAgentDatabases(t?.result.entries ?? [], e); } return readRegisteredAgentDatabases(e, true); } function listOpenClawRegisteredAgentDatabases(e = {}) { const t = activateRegisteredAgentDatabasesMemo(e); return cloneRegisteredAgentDatabases(t.entries ??= readRegisteredAgentDatabases({ ...e, includeIncompatibleSchemaVersions: true }, false), e); } /** Runtime discovery loads the registry through its existing read worker. */ async function listOpenClawRegisteredAgentDatabasesAsync(e = {}) { const t = await prepareOpenClawAgentDatabaseRegistrySnapshotRead(e).read(); if (t.result.status !== "available") throw new Error(`OpenClaw state database ${resolveDatabasePath(e)} is unavailable.`); return t.result.entries; } function createRegistrySnapshotReader(e, t, n, r) { const i = AsyncLocalStorage.snapshot(); return async (a) => { for (;;) { a?.throwIfAborted(); const o = n(); const { memo: s, assertCurrent: c, followRegistration: l } = o; const u = t ? c : r; u(); let d = e.fresh ? void 0 : s.entries; if (!d) { const n = (await i(() => executeExistingOpenClawStateRead(e, { type: "agentDatabaseRegistry.read" }, { signal: a, current: e.fresh })))?.result; if (!t && s.next) continue; o.acceptEntries(n?.status === "available" ? n.entries : []); u(); if (n?.status === "unavailable" || n === void 0 && hasUnavailableMissingSqlitePath(e.path)) return { result: { status: "unavailable" }, assertCurrent: c, followRegistration: l }; d = e.fresh ? n?.entries ?? [] : s.entries ??= n?.entries ?? []; } return { result: { status: "available", entries: cloneRegisteredAgentDatabases(d, e) }, assertCurrent: c, followRegistration: l }; } }; } /** Scoped publication witnesses are immediate; native registry rows remain demand-driven. */ function prepareOpenClawAgentDatabaseRegistrySnapshotRead(e = {}, t) { try { const n = cloneEnvWithPlatformSemantics(e.env ?? process.env); n.OPENCLAW_STATE_DIR = resolveStateDir(n); const r = { ...e, env: n, path: resolveDatabasePath({ ...e, env: n }) }; const i = captureOpenClawStateReadContext(r.path).admission.assertCurrent; const captureWitness = () => { const e = activateRegisteredAgentDatabasesMemo(r); let n = e; let a = false; let o = e.entries; const s = /* @__PURE__ */ new Set(); const unchanged = (e) => { if (!e || !t) return false; return t(e, o); }; const assertCurrent = () => { i(); const e = registry.memo; if (a) throw new AgentDatabaseRegistryChangedError(); if ((t ? [...registry.pending.values()].filter((e) => e.pathname === r.path && !s.has(e.operation) && !unchanged(e.mutation)) : []).length > 0) throw new AgentDatabaseRegistryChangedError("Agent database registry ownership is changing during discovery"); while (n !== e) { const e = n.next; if (!t || !e?.transition || e.transition.phase === "commit" && !unchanged(e.transition.mutation)) { a = true; throw new AgentDatabaseRegistryChangedError(); } n = e; } }; const followRegistration = (e) => { i(); if (a || registry.memo?.pathname !== n.pathname) { a = true; throw new Error("Agent registration cannot replace an invalidated registry read"); } const t = n.token === e.current ? n : n.next; if (n.token !== e.previous && n.token !== e.current || t?.token !== e.current) { if (e.current !== registry.memo.token) return; a = true; throw new Error("Agent registration cannot replace an invalidated registry read"); } const r = t.transition?.operation; if (r) s.add(r); n = t; }; return { memo: e, assertCurrent, followRegistration, acceptEntries(e) { o = e; } }; }; const a = t ? captureWitness() : void 0; let o = a; return { assertAdmissionCurrent: i, assertCurrent: () => (o?.assertCurrent ?? i)(), followRegistration(e) { if (!o) throw new Error("Agent registration requires a captured registry witness"); o.followRegistration(e); }, read: createRegistrySnapshotReader(r, a, () => { return o = a ?? captureWitness(); }, i) }; } catch (e) { const rethrow = () => { throw e; }; return { assertAdmissionCurrent: rethrow, assertCurrent: rethrow, followRegistration: rethrow, read: async () => rethrow() }; } } //#endregion export { invalidateRegisteredAgentDatabasesMemo as a, listOpenClawRegisteredAgentDatabases as c, prepareOpenClawAgentDatabaseRegistrySnapshotRead as d, readOpenClawAgentDatabaseRegistryToken as f, settleAgentRegistration as h, inspectOpenClawRegisteredAgentDatabases as i, listOpenClawRegisteredAgentDatabasesAsync as l, recordOpenClawAgentDatabaseRegistryMutation as m, emitOpenClawAgentDatabaseRegistryChange as n, isAgentDatabaseRegistryChangedError as o, readRegisteredAgentDatabases as p, hasRegisteredOpenClawAgentDatabasePath as r, isOpenClawAgentDatabaseRegistryChange as s, captureOpenClawAgentDatabaseRegistration as t, prepareOpenClawAgentDatabaseRegistryRemoval as u };