UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

252 lines (251 loc) • 11.6 kB
import { u as isStringArray } from "./record-coerce-CVPuDqcc.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { a as isSqliteCorruptionError } from "./sqlite-error-diagnostics-6_hREUnq.mjs"; import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely, v as expressionBuilder } from "./kysely-sync-YJo2lmGV.mjs"; import { a as tableExists, o as tableHasColumn } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs"; import { o as runSqliteReadSnapshotSync } from "./sqlite-transaction-BHHu6P5-.mjs"; import { r as resolveDatabasePath, s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs"; import { m as withExistingOpenClawStateDatabaseReadOnly, n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { i as prepareOpenClawStateReadSource } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { _ as hasPreJournalStateSchema } from "./openclaw-state-db-ARhwdPJg.mjs"; import { i as ensureAgentDeletionJournalPhaseSchema } from "./openclaw-state-db-schema-additive-BOxd1NE5.mjs"; import { n as isSessionStoreTopologyChange, o as sessionChanges } from "./session-row-changes-BA4BqVwF.mjs"; import { s as readAgentDeletionRecoveryHolds } from "./agent-deletion-journal-recovery.kernel-BMlEn3jf.mjs"; import { n as getAgentDeletionJournalStatus, s as loadAgentDeletionJournalStatus, u as seedAgentDeletionDiscovery } from "./agent-deletion-journal-status-CZ5XyH3P.mjs"; import { r as readRegisteredAgentDatabaseRows } from "./openclaw-agent-db-registry.read-DpiFiW8m.mjs"; import { d as prepareOpenClawAgentDatabaseRegistrySnapshotRead, o as isAgentDatabaseRegistryChangedError, s as isOpenClawAgentDatabaseRegistryChange } from "./openclaw-agent-db-registry-listing-CbXBL50a.mjs"; import path from "node:path"; //#region src/templates/provenance-secondary-references.ts const TEMPLATE_SECONDARY_REFERENCE_TABLES = [ "template_package_refs", "template_mcp_server_refs", "template_cron_refs" ]; function readTemplateSecondaryReferenceTables(e, t) { return TEMPLATE_SECONDARY_REFERENCE_TABLES.filter((n) => { if (!tableExists(e, n)) return false; return Boolean(e.prepare(`SELECT 1 FROM ${n} WHERE agent_id = ? LIMIT 1`).get(t)); }); } //#endregion //#region src/state/agent-deletion-journal-authority.worker.ts /** Deletion authority requires its admitted journal; unavailable rows must never grant cleanup. */ function readAgentDeletionJournalAuthorityInDatabase(e, t) { const n = executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("agent_deletion_journal").select([ "agent_id", "operation_id", "cleanup_completed" ]).where("agent_id", "=", normalizeAgentId(t))); if (!n) return; if (typeof n.operation_id !== "string" || !n.operation_id || n.cleanup_completed !== 0 && n.cleanup_completed !== 1) throw new Error("Agent deletion journal authority is unreadable."); return { agentId: n.agent_id, operationId: n.operation_id, cleanupCompleted: n.cleanup_completed === 1 }; } function hasTemplateDeletionOwnership(e, t) { const n = getNodeSqliteKysely(e.db); return ["template_installs", "template_workspace_files"].some((r) => tableExists(e.db, r) && executeSqliteQueryTakeFirstSync(e.db, n.selectFrom(r).select("agent_id").where("agent_id", "=", t).limit(1)) !== void 0) || readTemplateSecondaryReferenceTables(e.db, t).length > 0; } function retireAgentDeletionJournalInDatabase(e, t, n) { ensureAgentDeletionJournalPhaseSchema(e.db); const r = executeSqliteQuerySync(e.db, getNodeSqliteKysely(e.db).updateTable("agent_deletion_journal").set({ phase: "retiring" }).where("agent_id", "=", normalizeAgentId(t)).where("operation_id", "=", n).where("cleanup_completed", "=", 0)).numAffectedRows === 1n; if (r) sessionChanges.emit({ all: true, scope: "stores" }, e.db); return r; } //#endregion //#region src/state/agent-deletion-journal.read.ts var AgentDatabaseDeletionSnapshotChangedError = class extends Error { constructor() { super("Agent database deletion snapshot changed during consumption."); this.name = "AgentDatabaseDeletionSnapshotChangedError"; } }; /** These owners require a fresh read, never replay of an already-entered consumer. */ function isAgentDatabaseDeletionSnapshotChangedError(e) { return e instanceof AgentDatabaseDeletionSnapshotChangedError || isAgentDatabaseRegistryChangedError(e); } async function readAgentDeletionRecoveryHoldsInWorker(e = {}) { const t = resolveDatabasePath(e); return (await executeExistingOpenClawStateRead({ ...e, path: t }, { type: "agentRecovery.holds", input: { statePath: t } }, { current: true }))?.held ?? []; } async function readAgentDeletionJournalForCreation(e, t = {}) { return (await executeExistingOpenClawStateRead(t, { type: "agentRecovery.creationJournal", input: { agentId: normalizeAgentId(e) } }, { current: true }))?.journal; } /** Completed cleanup still retains a deletion tombstone. */ function readAgentDeletionJournalStatusInDatabase(e, t) { const n = getAgentDeletionJournalStatus(e, t); if (n) return n; if (!tableExists(e, "agent_deletion_journal")) return "absent"; const r = executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("agent_deletion_journal").select("cleanup_completed").where("agent_id", "=", normalizeAgentId(t))); return r ? r.cleanup_completed === 1 ? "complete" : "pending" : "absent"; } async function readAgentDeletionJournalStatusInWorker(e, t = {}, n) { n?.throwIfAborted(); return loadAgentDeletionJournalStatus(resolveDatabasePath(t), e, async () => { return (await executeExistingOpenClawStateRead(t, { type: "agentDeletionJournal.status", agentId: normalizeAgentId(e) }, { current: true, signal: n }))?.status ?? "absent"; }); } function parseAgentDeletionDatabasePaths(e) { const t = JSON.parse(e); if (isStringArray(t)) return t; throw new Error("Invalid agent deletion database path journal."); } /** Read existing deletion history without initializing or repairing the journal. */ function readRetainedAgentDeletionsFromDatabase(e, t, n = "maintenance", r) { let i = []; let a = false; let o; try { a = !tableExists(e, "agent_deletion_journal"); if (!a) { const t = expressionBuilder(); const a = t.and([t("cleanup_completed", "=", 1), t("delete_files", "=", 0)]); const s = n !== "runtime" ? t.or([a, t("cleanup_completed", "=", 0)]) : a; i = executeSqliteQuerySync(e, getNodeSqliteKysely(e).selectFrom("agent_deletion_journal").select(["agent_id", "cleanup_completed"]).select(tableHasColumn(e, "agent_deletion_journal", "phase") ? "phase" : t.lit(null).as("phase")).select([t.case().when(s).then(t.ref("agent_dir")).else(null).end().as("agent_dir"), t.case().when(s).then(t.ref("database_paths_json")).else("[]").end().as("database_paths_json")]).$if(!r, (e) => e.where(s)).orderBy("agent_id", "asc")).rows.flatMap((t) => { r?.push({ agentId: t.agent_id, status: t.cleanup_completed === 1 ? "complete" : "pending" }); if (t.agent_dir === null) return []; let i = []; try { i = parseAgentDeletionDatabasePaths(t.database_paths_json); } catch (e) { if (n === "maintenance") o ??= formatErrorMessage(e); } const a = { agentId: t.agent_id, agentDir: t.agent_dir, databasePaths: [path.join(t.agent_dir, "openclaw-agent.sqlite"), ...i], cleanupCompleted: t.cleanup_completed === 1 }; if (t.cleanup_completed === 0 && t.phase == null && hasTemplateDeletionOwnership({ db: e }, t.agent_id)) a.manualTemplateRemoval = true; return a; }); } } catch (e) { if (isSqliteCorruptionError(e)) throw e; o = formatErrorMessage(e); } let s = []; try { if (tableExists(e, "migration_sources")) s = readAgentDeletionRecoveryHolds({ db: e, path: t }); } catch (e) { if (n === "maintenance" || isSqliteCorruptionError(e)) throw e; } if (a && s.length === 0 && hasPreJournalStateSchema(e)) return { status: "empty" }; if (a || o !== void 0) return { status: "unavailable", cause: a ? "missing" : "unreadable", reason: a ? "deletion journal missing" : `deletion journal unreadable: ${o}`, ...i.length || s.length ? { known: { entries: i, held: s } } : {} }; return i.length || s.length ? { status: "present", entries: i, held: s } : { status: "empty" }; } /** Read journal and registered-owner facts from one shared-state generation. */ function readAgentDatabaseDeletionSnapshot(e, t = "maintenance") { return withExistingOpenClawStateDatabaseReadOnly(({ db: e, path: n }) => runSqliteReadSnapshotSync(e, () => ({ retainedDeletions: readRetainedAgentDeletionsFromDatabase(e, n, t), registeredAgentDatabases: readRegisteredAgentDatabaseRows(e, n, false) }), { operationLabel: "agentDeletionJournal.snapshot" }), { env: e }); } /** Repeated discovery reads keep their original source custody and observe current committed facts. */ function prepareAgentDatabaseDeletionSnapshotRead(e = {}, t = "maintenance", n) { const r = cloneEnvWithPlatformSemantics(e.env ?? process.env); r.OPENCLAW_STATE_DIR = resolveStateDir(r); const i = { env: r, path: path.resolve(e.path ?? resolveOpenClawStateSqlitePath(r)) }; const a = prepareOpenClawStateReadSource(i); const o = a.workerContext(); const readSnapshot = async (e) => { const assertReadCurrent = () => { n?.throwIfAborted(); e.maintenanceScope?.assertAdmission(); e.admission.assertCurrent(); }; assertReadCurrent(); const r = await executeExistingOpenClawStateRead(i, { type: "agentDatabaseDeletion.snapshot", purpose: t }, { context: e, current: true, signal: n }); assertReadCurrent(); if (t === "runtime-discovery" && r) seedAgentDeletionDiscovery(i.path, r.snapshot.retainedDeletions); return { snapshot: r?.snapshot, assertCurrent: assertReadCurrent }; }; const read = () => readSnapshot(o); return { read, async readWithCurrentAdmission() { return a.withCurrent(readSnapshot); }, async withCurrentSnapshot(e) { let t; let n; const r = sessionChanges.subscribeFacts((e) => { if (isSessionStoreTopologyChange(e) && (!n || !isOpenClawAgentDatabaseRegistryChange(e))) t = true; }); try { for (;;) { t = false; const { snapshot: r, assertCurrent: a } = await read(); a(); if (t) continue; n = prepareOpenClawAgentDatabaseRegistrySnapshotRead(i, (e) => e.kind === "upsert" && e.sources.every((e) => r?.registeredAgentDatabases.some((t) => t.agentId === e.agentId && t.path === e.path && t.schemaVersion === e.schemaVersion))).assertCurrent; return await e(r, () => { a(); if (t) throw new AgentDatabaseDeletionSnapshotChangedError(); n?.(); }); } } finally { t = true; r(); } } }; } //#endregion export { readAgentDeletionJournalForCreation as a, readAgentDeletionRecoveryHoldsInWorker as c, readAgentDeletionJournalAuthorityInDatabase as d, retireAgentDeletionJournalInDatabase as f, readAgentDatabaseDeletionSnapshot as i, readRetainedAgentDeletionsFromDatabase as l, parseAgentDeletionDatabasePaths as n, readAgentDeletionJournalStatusInDatabase as o, prepareAgentDatabaseDeletionSnapshotRead as r, readAgentDeletionJournalStatusInWorker as s, isAgentDatabaseDeletionSnapshotChangedError as t, hasTemplateDeletionOwnership as u };