openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
410 lines (409 loc) • 20 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { t as LruCache } from "./lru-cache-wquJPIr-.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { a as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import { n as isPostgresSqlConnection } from "./sql-connection-Beiyg5Dt.mjs";
import { m as readDatabasePathIdentitySync } from "./sqlite-worker-identity-BH8ZkJU9.mjs";
import { B as revokeSqliteDatabaseAdmissionsForPath, rt as OPENCLAW_STATE_SCHEMA_SQL } from "./sqlite-database-admission-DQIqro3d.mjs";
import { t as extractSqliteTableSchema } from "./sqlite-schema-sql-CPyk_2Hd.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { t as deferSqlitePostCommitPublication } from "./sqlite-post-commit-BrUVQObC.mjs";
import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs";
import { a as tableExists } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import { i as runWithSqliteBusyTimeout } from "./sqlite-busy-timeout-BEDmnGR_.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { t as getFileLockProcessStartTime } from "./pid-alive-D899x-ak.mjs";
import { a as prepareSqliteReadOnlyLocationSync } from "./sqlite-snapshot-source-Q9S7_uQN.mjs";
import { c as SqliteWorkerOpenRefusedError } from "./sqlite-worker-contract--dxXkOty.mjs";
import { m as openClawStateDatabaseCache, w as requireOpenClawStateDatabaseIdentity } from "./openclaw-state-db-cache-CkwtTqzF.mjs";
import { r as ensureOpenClawQuarantineStore } from "./openclaw-quarantine-store-Bi4DSTmN.mjs";
import { a as isStatePostgres } from "./openclaw-state-db-engine-sM0tpxNy.mjs";
import { c as createAgentDatabaseLeaseStaleReasonReader, l as mayShareAgentDatabaseFile, s as agentDatabaseLeaseProcessDeathRefusal, u as readAgentDatabaseLeaseProvenance } from "./openclaw-state-db-existing-schema-C1h5v6Xh.mjs";
import { o as withOpenClawStateReadOnlyLocation } from "./openclaw-state-db-read-connection-DoTwzEPO.mjs";
import { l as runOpenClawStateWriteTransaction, r as openOpenClawStateDatabase } from "./openclaw-state-db-ARhwdPJg.mjs";
import { r as ensureAgentDatabaseLeaseSchema } from "./openclaw-state-db-schema-additive-BOxd1NE5.mjs";
import { n as agentDatabaseMaintenanceAuthority } from "./openclaw-agent-db-maintenance-authority-C4Yhyki9.mjs";
import { d as prepareAgentDeletionPathFence, n as assertAgentDeletionPathFence, t as AgentDatabaseDeletionRefusedError } from "./agent-deletion-journal-DgNbVVSp.mjs";
import { n as runExistingOpenClawStateWriteTransaction } from "./openclaw-state-db-existing-write-CwPoAnNn.mjs";
import { m as invalidateOpenClawAgentDatabaseValidation } from "./openclaw-agent-db-validation-cache-lnjWuypr.mjs";
import fs from "node:fs";
import path from "node:path";
import { randomUUID } from "node:crypto";
//#region src/state/openclaw-agent-db-existing-write.ts
const existingAgentLeaseSchema = [
"schema_meta",
"state_leases",
"agent_database_leases"
].map((e) => extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, e, {
endMarker: ") STRICT;",
errorMessage: "Existing agent lease schema is unavailable."
})).join("\n");
function withExistingAgentLeaseWrite(e, t, n) {
return runExistingOpenClawStateWriteTransaction(({ db: t }) => {
e.assertOwnedInTransaction(t);
const r = n(t);
e.assertOwnedInTransaction(t);
return r;
}, t, {
operationLabel: "agent.database.maintenance.admission",
schemaSql: existingAgentLeaseSchema,
integrityCheck: getOpenClawDatabaseMaintenanceScope()?.sqliteIntegrityCheck,
schemaCompatibility: { allowedMissingColumns: ["agent_database_leases.provenance"] }
});
}
//#endregion
//#region src/state/openclaw-agent-db-lease.ts
const log = createSubsystemLogger("state/agent-db");
const closeReceipts = resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseCloseReceipts"), () => new LruCache(128), (e) => e.clear());
const AGENT_DATABASE_MAINTENANCE_LEASE = {
scope: "core:agent-database-maintenance",
key: "global"
};
var OpenClawAgentDatabaseLeaseActiveError = class extends Error {
constructor(e, t = []) {
super(e);
this.ownerPids = t;
this.name = "OpenClawAgentDatabaseLeaseActiveError";
}
};
/** Ordinary agent worker routing cannot borrow native maintenance authority. */
function hasAgentDatabaseMaintenanceAuthority() {
return agentDatabaseMaintenanceAuthority.getStore() !== void 0;
}
function runWithAgentDatabaseMaintenanceAuthority(e, t, n) {
const r = getOpenClawDatabaseMaintenanceScope();
return agentDatabaseMaintenanceAuthority.run({
authority: e,
databasePath: path.resolve(t),
assertScopeCurrent: r ? () => r.assertAdmission() : void 0
}, n);
}
/** Revalidate a maintenance owner when present, without requiring ordinary opens to hold one. */
function assertAgentDatabaseMaintenanceAuthorityIfPresent() {
agentDatabaseMaintenanceAuthority.getStore()?.assertScopeCurrent?.();
agentDatabaseMaintenanceAuthority.getStore()?.authority.assertOwned();
}
/** Raw maintenance writers revoke admitted facts before changing stored bytes. */
function invalidateOpenClawAgentDatabaseIntegrityBeforeMutation(e) {
agentDatabaseMaintenanceAuthority.getStore()?.authority.assertOwned();
invalidateOpenClawAgentDatabaseValidation(e);
revokeSqliteDatabaseAdmissionsForPath(e);
}
/** Verify the maintenance owner and its independent heartbeat before a synchronous phase. */
function renewAgentDatabaseMaintenanceAuthorityIfPresent() {
const e = agentDatabaseMaintenanceAuthority.getStore()?.authority;
if (!e) return;
if (!e.renew) throw new Error("Agent database maintenance authority cannot renew its lease.");
e.renew();
}
function claimOpenClawAgentDatabaseLease(e, t = randomUUID(), n) {
const r = normalizeAgentId(e.agentId);
const i = prepareAgentDeletionPathFence({
agentId: r,
path: e.path
}, { env: e.env });
const a = getFileLockProcessStartTime(process.pid);
runOpenClawStateWriteTransaction((o) => claimAgentDatabaseLeaseInDatabase(o, {
leaseId: t,
agentId: r,
path: e.path,
ownerPid: process.pid,
ownerStartTime: a,
provenance: readAgentDatabaseLeaseProvenance(e.path)
}, i, n), {
env: e.env,
initializationAgentPaths: [e.path]
});
return t;
}
function claimAgentDatabaseLeaseInDatabase(e, t, n, r) {
ensureAgentDatabaseLeaseSchema(e.db);
const i = getNodeSqliteKysely(e.db);
const a = executeSqliteQueryTakeFirstSync(e.db, i.selectFrom("state_leases").select("owner").where("scope", "=", AGENT_DATABASE_MAINTENANCE_LEASE.scope).where("lease_key", "=", AGENT_DATABASE_MAINTENANCE_LEASE.key).where("expires_at", ">", Date.now()));
const o = agentDatabaseMaintenanceAuthority.getStore();
if (a || o) throw new Error("Agent database maintenance is in progress; retry after openclaw doctor --fix completes.");
assertAgentDeletionPathFence(e, n);
let s = false;
let c = false;
let l;
let u;
const d = createAgentDatabaseLeaseStaleReasonReader();
for (const n of readAgentDatabaseLeases(e.db)) {
const r = mayShareAgentDatabaseFile(n.path, t.path);
const a = r ? d(n) : void 0;
if (a) {
const r = agentDatabaseLeaseProcessDeathRefusal(n, t.path, a);
u ??= r;
log.info(`agent database stale lease: ${a}; previous release not observed`, {
agentId: n.agent_id,
leaseId: n.lease_id,
path: n.path,
staleReason: a,
ownerPid: n.owner_pid,
ownerStartTime: n.owner_start_time,
because: r ?? "same-boot-dead-owner"
});
clearAgentDatabaseLeaseVerifications(e.db, n.path);
s = true;
executeSqliteQuerySync(e.db, i.deleteFrom("agent_database_leases").where("lease_id", "=", n.lease_id));
reportPriorBootLeaseRelease(e.db, n.lease_id, a);
} else if (r && n.lease_id !== t.leaseId && (t.ownerStartTime === null || n.owner_pid !== t.ownerPid || n.owner_start_time === null || n.owner_start_time !== t.ownerStartTime)) {
c = true;
if (n.path === t.path && n.provenance !== null && n.provenance === t.provenance && n.opened_at > 0 && n.owner_start_time !== null && getFileLockProcessStartTime(n.owner_pid) === n.owner_start_time) l = n.provenance;
}
}
r?.(!c, s, u ?? (c ? "live-or-unknown-owner" : void 0), l);
executeSqliteQuerySync(e.db, i.insertInto("agent_database_leases").values({
lease_id: t.leaseId,
provenance: t.provenance,
agent_id: t.agentId,
path: t.path,
owner_pid: t.ownerPid,
owner_start_time: t.ownerStartTime,
opened_at: 0
}));
}
function releaseOpenClawAgentDatabaseLease(e, t = {}, n) {
const release = (t) => {
const r = getNodeSqliteKysely(t);
const i = executeSqliteQueryTakeFirstSync(t, n === void 0 ? r.selectFrom("agent_database_leases").select(["path", "agent_id"]).where("lease_id", "=", e) : r.deleteFrom("agent_database_leases").where("lease_id", "=", e).returning(["path", "agent_id"]));
if (n === void 0) {
if (i) clearAgentDatabaseLeaseVerifications(t, i.path);
executeSqliteQuerySync(t, r.deleteFrom("agent_database_leases").where("lease_id", "=", e));
}
let a;
if (!i) a = "lease-not-held";
else if (typeof n !== "object") a = n === "uncheckpointed" ? "checkpoint-incomplete" : n ?? "close-unconfirmed";
else if (i.path !== n.path) a = "path-mismatch";
else if (hasAgentDatabasePathLease(t, n.path)) a = "active-leases";
else a = n.publishSeal() ? "written" : "verification-missing";
const publish = () => {
if (i) {
const e = closeReceipts.get(i.path);
if (e?.agentId === i.agent_id && e.receipt === a) return;
closeReceipts.set(i.path, {
agentId: i.agent_id,
receipt: a
});
}
log.info(`agent database clean-close receipt: ${a}; agent=${i?.agent_id ?? "unknown"}`, {
agentId: i?.agent_id,
path: i?.path,
leaseId: e,
receipt: a
});
};
if (!deferSqlitePostCommitPublication(t, publish)) publish();
};
const r = agentDatabaseMaintenanceAuthority.getStore();
const i = path.resolve(t.database?.path ?? t.path ?? resolveOpenClawStateSqlitePath(t.env));
if (r?.databasePath === i) return withExistingAgentLeaseWrite(r.authority, t, release);
runOpenClawStateWriteTransaction((e) => {
ensureAgentDatabaseLeaseSchema(e.db);
release(e.db);
}, typeof n === "object" ? {
...t,
initializationAgentPaths: [...t.initializationAgentPaths ?? [], n.path]
} : t);
}
function agentDatabaseLeasePaths(e) {
const t = getNodeSqliteKysely(e);
return executeSqliteQuerySync(e, t.selectFrom("agent_database_leases").select("path").distinct()).rows.map((e) => e.path);
}
function hasAgentDatabasePathLease(e, t) {
return agentDatabaseLeasePaths(e).some((e) => mayShareAgentDatabaseFile(e, t));
}
/** Preserve a known FULL requirement across death, then replace it on completed admission. */
function recordOpenClawAgentDatabaseAdmission(e, t, n = "complete") {
runOpenClawStateWriteTransaction((r) => {
ensureOpenClawQuarantineStore(t.env ?? process.env);
if (executeSqliteQuerySync(r.db, getNodeSqliteKysely(r.db).updateTable("agent_database_leases").set({ opened_at: n === "full-required" ? -1 : Date.now() }).where("lease_id", "=", e).where("agent_id", "=", t.agentId).where("path", "=", t.path).where("owner_pid", "=", process.pid)).numAffectedRows !== 1n) throw new Error(`Agent database open lost its runtime lease: ${t.path}`);
}, { env: t.env }, { singleStatement: true });
}
function clearAgentDatabaseLeaseVerifications(e, t) {
for (const n of /* @__PURE__ */ new Set([t, ...agentDatabaseLeasePaths(e)])) if (mayShareAgentDatabaseFile(n, t)) {
invalidateOpenClawAgentDatabaseValidation(n);
revokeSqliteDatabaseAdmissionsForPath(n);
}
}
/** An awaited open may consume its scan only while its original runtime claim survives. */
function assertOpenClawAgentDatabaseLease(e, t) {
readOpenClawAgentDatabaseLeaseClaim(e, t);
}
function readOpenClawAgentDatabaseLeaseClaim(e, t) {
const n = getFileLockProcessStartTime(process.pid);
const r = openOpenClawStateDatabase({
env: t.env,
initializationAgentPaths: [t.path]
});
const i = readAgentDatabaseLeases(r.db, e)[0];
if (!i || i.agent_id !== t.agentId || i.path !== t.path || i.owner_pid !== process.pid || i.owner_start_time !== null && n !== null && i.owner_start_time !== n) throw new Error(`Agent database open lost its runtime lease: ${t.path}`);
return {
database: r,
held: i
};
}
/** Preparation grants no access; claim repeats admission on the captured shared owner. */
function prepareOpenClawAgentDatabaseWorkerLease(e, t, n) {
const r = { ...t };
const i = requireOpenClawStateDatabaseIdentity(r);
const assertCurrent = () => {
if (!r.db.isOpen || requireOpenClawStateDatabaseIdentity(r) !== i) throw new Error("Prepared agent database lease lost its original shared owner");
};
assertCurrent();
const a = process.pid;
const o = readAgentDatabaseLeaseProvenance(e.path);
const s = Object.freeze({
leaseId: n,
agentId: normalizeAgentId(e.agentId),
path: path.resolve(e.path),
ownerPid: a,
ownerStartTime: getFileLockProcessStartTime(a),
sharedStatePath: r.path,
sharedStateIdentity: i.key
});
const c = {
database: r,
path: r.path,
env: { ...e.env ?? process.env }
};
return {
receipt: s,
provenance: o,
claim(e) {
assertCurrent();
const t = prepareAgentDeletionPathFence({
agentId: s.agentId,
path: s.path
}, c);
try {
runOpenClawStateWriteTransaction((n) => {
assertCurrent();
claimAgentDatabaseLeaseInDatabase(n, {
...s,
provenance: o
}, t, e);
}, c);
} catch (e) {
if (e instanceof AgentDatabaseDeletionRefusedError) throw new SqliteWorkerOpenRefusedError(e);
throw e;
}
return s.leaseId;
}
};
}
/** Capture the exact admitted claim so its parent can finish cleanup after native Worker exit. */
function readOpenClawAgentDatabaseWorkerLeaseReceiptFromClaim(e, t) {
const { database: n, held: r } = readOpenClawAgentDatabaseLeaseClaim(e, t);
return {
leaseId: e,
agentId: r.agent_id,
path: r.path,
ownerPid: r.owner_pid,
ownerStartTime: r.owner_start_time,
sharedStatePath: n.path,
sharedStateIdentity: readDatabasePathIdentitySync(n.path).key
};
}
/** The caller owns the original shared transaction and has joined the exact native Worker exit. */
function releaseExitedOpenClawAgentDatabaseLeaseInDatabase(e, t, n, r) {
const i = getNodeSqliteKysely(e);
const a = readAgentDatabaseLeases(e, t.leaseId)[0];
if (!a) return;
if (a.agent_id !== t.agentId || a.path !== t.path || a.owner_pid !== t.ownerPid || a.owner_start_time !== t.ownerStartTime) throw new Error("SQLite reclamation Worker lease cleanup receipt no longer matches");
if (n !== "refused-before-open") {
r?.();
clearAgentDatabaseLeaseVerifications(e, t.path);
}
executeSqliteQuerySync(e, i.deleteFrom("agent_database_leases").where("lease_id", "=", t.leaseId));
}
function readAgentDatabaseLeases(e, t) {
const n = getNodeSqliteKysely(e).selectFrom("agent_database_leases").selectAll();
return executeSqliteQuerySync(e, t === void 0 ? n : n.where("lease_id", "=", t)).rows;
}
function reportPriorBootLeaseRelease(e, t, n) {
if (n !== "owner-prior-boot") return;
const publish = () => log.warn(`Released legacy agent database lease ${t} from a prior boot.`);
if (!deferSqlitePostCommitPublication(e, publish)) publish();
}
/** Read-only diagnostic observation; an empty result never grants maintenance authority. */
function readActiveOpenClawAgentDatabaseLeasesReadOnly(e = {}, t) {
const n = path.resolve(e.path ?? resolveOpenClawStateSqlitePath(e.env));
try {
fs.statSync(n);
} catch (e) {
if (hasErrnoCode(e, "ENOENT")) return [];
throw e;
}
const r = openClawStateDatabaseCache.isOpenClawStateDatabaseOpen(n) ? openClawStateDatabaseCache.getOpenClawStateDatabaseIfOpenAtPath(n) : void 0;
const readActiveLeases = (e) => {
const read = () => {
if (!tableExists(e, "agent_database_leases")) return [];
const t = createAgentDatabaseLeaseStaleReasonReader();
return readAgentDatabaseLeases(e).filter((e) => !t(e));
};
return isPostgresSqlConnection(e) ? read() : runWithSqliteBusyTimeout(e, 250, read);
};
if (!r) return withOpenClawStateReadOnlyLocation(({ db: e }) => readActiveLeases(e), n, isStatePostgres() ? n : prepareSqliteReadOnlyLocationSync(n), t);
const i = !isPostgresSqlConnection(r.db) && t ? t(r.db) : void 0;
try {
return readActiveLeases(r.db);
} finally {
i?.();
}
}
/** Doctor holds both lifecycle coordinators before checking writers, without schema repair. */
function assertNoOpenClawAgentDatabaseLeasesReadOnly(e = {}, t) {
const n = readActiveOpenClawAgentDatabaseLeasesReadOnly(e, t);
const [r] = n;
if (r) throw new OpenClawAgentDatabaseLeaseActiveError(`Agent ${r.agent_id} database is still open in process ${r.owner_pid}; stop the Gateway and other OpenClaw processes, or reboot, then rerun openclaw doctor --fix.`, [...new Set(n.map((e) => e.owner_pid))]);
}
function assertNoOpenClawAgentDatabaseLeases(e, t = {}) {
if (t.schemaPolicy === "existing") {
if (typeof e === "string") throw new Error("Existing-schema agent drainage requires a real maintenance owner.");
return assertNoExistingAgentDatabaseLeases(e, t);
}
const n = typeof e === "string" ? void 0 : e;
const r = typeof e === "string" ? normalizeAgentId(e) : void 0;
runOpenClawStateWriteTransaction((e) => {
n?.assertOwnedInTransaction(e.db);
ensureAgentDatabaseLeaseSchema(e.db);
const i = getNodeSqliteKysely(e.db);
const a = createAgentDatabaseLeaseStaleReasonReader();
for (const n of readAgentDatabaseLeases(e.db)) {
const o = a(n);
if (o) {
clearAgentDatabaseLeaseVerifications(e.db, n.path);
executeSqliteQuerySync(e.db, i.deleteFrom("agent_database_leases").where("lease_id", "=", n.lease_id));
reportPriorBootLeaseRelease(e.db, n.lease_id, o);
continue;
}
if (!r || n.agent_id === r) throw new OpenClawAgentDatabaseLeaseActiveError(`Agent ${n.agent_id} database is still open in another process; stop the Gateway and other OpenClaw processes, or reboot, then rerun openclaw doctor --fix.`);
assertAgentDeletionPathFence(e, prepareAgentDeletionPathFence({
agentId: n.agent_id,
path: n.path,
fenceAgentId: r
}, t));
}
}, t);
}
/** Stable existing rows can be drained before the candidate is allowed to migrate. */
function assertNoExistingAgentDatabaseLeases(e, t) {
withExistingAgentLeaseWrite(e, t, (e) => {
const t = getNodeSqliteKysely(e);
const n = createAgentDatabaseLeaseStaleReasonReader();
for (const r of readAgentDatabaseLeases(e)) {
const i = n(r);
if (i) {
clearAgentDatabaseLeaseVerifications(e, r.path);
executeSqliteQuerySync(e, t.deleteFrom("agent_database_leases").where("lease_id", "=", r.lease_id));
reportPriorBootLeaseRelease(e, r.lease_id, i);
} else throw new OpenClawAgentDatabaseLeaseActiveError(`Agent ${r.agent_id} database is still open in another process; stop the Gateway and other OpenClaw processes, or reboot, then rerun openclaw doctor --fix.`);
}
});
}
//#endregion
export { runWithAgentDatabaseMaintenanceAuthority as _, assertNoOpenClawAgentDatabaseLeasesReadOnly as a, hasAgentDatabaseMaintenanceAuthority as c, readActiveOpenClawAgentDatabaseLeasesReadOnly as d, readOpenClawAgentDatabaseWorkerLeaseReceiptFromClaim as f, renewAgentDatabaseMaintenanceAuthorityIfPresent as g, releaseOpenClawAgentDatabaseLease as h, assertNoOpenClawAgentDatabaseLeases as i, invalidateOpenClawAgentDatabaseIntegrityBeforeMutation as l, releaseExitedOpenClawAgentDatabaseLeaseInDatabase as m, OpenClawAgentDatabaseLeaseActiveError as n, assertOpenClawAgentDatabaseLease as o, recordOpenClawAgentDatabaseAdmission as p, assertAgentDatabaseMaintenanceAuthorityIfPresent as r, claimOpenClawAgentDatabaseLease as s, AGENT_DATABASE_MAINTENANCE_LEASE as t, prepareOpenClawAgentDatabaseWorkerLease as u };