openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,089 lines (1,088 loc) • 43 kB
JavaScript
import { a as resolveGlobalSingleton, n as readGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import { t as isAbortError } from "./abort-signal-D4Q6SEw7.mjs";
import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs";
import { n as mergeProcessEnv } from "./process-env-DVJdcOcM.mjs";
import { a as getOpenClawDatabaseMaintenanceScope, d as observeOpenClawDatabaseMaintenanceResource, i as getOpenClawDatabaseMaintenanceResourceScope, o as isOpenClawDatabaseMaintenanceResourceOwned } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import { n as isPostgresSqlConnection } from "./sql-connection-Beiyg5Dt.mjs";
import { B as revokeSqliteDatabaseAdmissionsForPath, b as publishSqliteDatabaseAdmission, o as getSqliteDatabaseAdmission, z as revokeSqliteDatabaseAdmissions } from "./sqlite-database-admission-DQIqro3d.mjs";
import { a as isSqliteCorruptionError, h as sqlitePrimaryResultCode, o as isSqliteLockError } from "./sqlite-error-diagnostics-6_hREUnq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.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 { f as registerNodeSqliteKyselyQueryErrorHandler, u as registerNodeSqliteDisposeCallback } from "./kysely-sync-cache-state-Bb1gOqQO.mjs";
import { h as runSqliteReadOperationSync, m as registerSqliteSchemaMutationListener } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { r as getStateRuntimeSchemaAdmission } from "./openclaw-state-db-admission-Bw1Mtc4x.mjs";
import { n as openNodeSqliteDatabase, r as resolveExistingSqliteFileUri } from "./node-sqlite-CU4puofF.mjs";
import { n as isArtifactPreservingStateRead } from "./artifact-preserving-state-reads-BfhmBr-V.mjs";
import { o as registerSqliteCacheExitClose } from "./sqlite-wal-DGPrWPl6.mjs";
import { a as registerSqliteWalWorkerMaintenance } from "./sqlite-wal-write-admission-BDhnPj3y.mjs";
import { r as resolveDatabasePath, s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { i as isStateDatabaseReadAdmissionInvalidatedError, r as createOpenClawStateDatabaseAsyncLifecycle, t as StateDatabaseReadAdmissionInvalidatedError } from "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { i as assertStateDatabaseReadAllowed, r as assertStateDatabaseAccessAllowed } from "./gateway-state-owner-Bnv5owvG.mjs";
import { u as registerLiveSqliteSnapshotOwner } from "./sqlite-snapshot-source-Q9S7_uQN.mjs";
import { S as OpenClawQuarantineReadCleanupError, x as markOpenClawStateDatabaseFailure } from "./openclaw-state-worker-error-C8y1JGQN.mjs";
import { n as getDatabaseEngineSelection } from "./context-DE59wyBs.mjs";
import { i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs";
import { i as readOpenClawDatabaseQuarantineFailure } from "./openclaw-quarantine-store-Bi4DSTmN.mjs";
import { t as SQLITE_IDLE_HANDLE_TTL_MS } from "./sqlite-handle-lifecycle-Dw0xPd8_.mjs";
import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs";
import { t as getGatewayServiceInstallation } from "./gateway-service-installation-context-CHlb7Eod.mjs";
import { o as isGatewayExternallySupervised } from "./gateway-supervision-C1X-e8qk.mjs";
import { r as captureOpenClawStateSchemaReadAdmission, t as assertExistingOpenClawStateSchemaCacheAdmission } from "./openclaw-state-db-schema-policy-DvHzXD76.mjs";
import { o as resolveLegacyCronDefaultStoreKey } from "./openclaw-state-db-cron-identity-migration-XoyKZWfG.mjs";
import { a as readTrackedStateDatabaseIdentity, t as closeStateDatabaseHandle } from "./openclaw-state-db-handle-BxpEWiaT.mjs";
import { r as assertSqliteIntegrity } from "./sqlite-integrity-CCmEgO_m.mjs";
import { existsSync } from "node:fs";
import path from "node:path";
import { isMainThread } from "node:worker_threads";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/infra/sqlite-terminal-open-latch.ts
/**
* Per-path latch for terminal database-open failures (newer schema, proven
* corruption). Recording quarantines the path: any live handle is closed and
* every later open fails fast until doctor repairs the file and clears it.
*/
function createSqliteTerminalOpenLatch(e) {
const t = /* @__PURE__ */ new Map();
return {
/** Read the owner's recorded fact without running filesystem or database inspection. */
peek: (e) => t.get(path.resolve(e)),
get: (e) => t.get(path.resolve(e)),
record: (n, r) => {
const i = path.resolve(n);
materializeErrorStack(r);
t.set(i, r);
e.closeByPath(i, r);
},
clear: (e) => {
t.delete(path.resolve(e));
},
clearAll: (e) => {
for (const n of t.keys()) if (e === void 0 || isPathInside(e, n)) t.delete(n);
}
};
}
//#endregion
//#region src/state/openclaw-state-db-borrow.ts
/** The canonical cache supplies identity and custody; this owner manages its native references. */
function createStateDatabaseRetainer(e, t) {
const admit = (e, n, r) => {
const i = getOpenClawDatabaseMaintenanceScope();
if (n === "cached-read") i?.assertReadAdmission();
else i?.assertAdmission();
t.assertOpen(e, n, r);
return i;
};
const retain = (n, r, i = false) => {
t.capture(n.path).assertCurrent();
if (e.cachedDatabases.get(n.path) !== n || !n.db.isOpen) throw new Error("OpenClaw state database borrow requires its current canonical handle");
const a = e.borrowers.get(n.db) ?? {
references: /* @__PURE__ */ new Set(),
retiring: false,
cleanupComplete: false
};
if (a.retiring) throw new Error("OpenClaw state database native owner is retiring");
if (!i) observeOpenClawDatabaseMaintenanceResource(n.db);
e.borrowers.set(n.db, a);
const isCurrent = () => !r || isOpenClawDatabaseMaintenanceResourceOwned(n.db, r);
/** Preserve the requesting owner's retirement when the last reference is only a read pin. */
const o = i ? void 0 : {
ordinary: r === void 0,
isCurrent,
retire: () => {
if (!isCurrent()) {
a.retiring = false;
return;
}
t.retire(n, r === void 0);
}
};
function createAsyncStateDatabaseRetirement() {
const e = {};
let r;
let i;
const finish = (r) => {
a.references.delete(e);
if (r?.isCurrent()) r.retire();
else a.retiring = false;
a.retirement = void 0;
a.asyncRetirement = void 0;
i?.();
i = void 0;
t.touch(n);
};
const run = () => {
if (r) return r;
if (a.cleanupComplete || a.references.size > (a.references.has(e) ? 1 : 0)) return Promise.resolve();
if (!a.retirement?.isCurrent()) {
finish();
return Promise.resolve();
}
a.retiring = true;
a.references.add(e);
i ??= t.ownRetirement(n, close);
r = Promise.resolve().then(async () => {
await n.walMaintenance.stop();
finish(a.retirement);
}).catch((r) => {
a.references.add(e);
t.retainFailed(n);
throw r;
});
r.catch(() => {});
return r;
};
function close() {
const e = run();
return e.catch((t) => {
if (r === e) r = void 0;
throw t;
});
}
return {
start: () => void run(),
close
};
}
const s = {};
a.references.add(s);
let c = false;
const release = () => {
if (c || a.cleanupComplete) {
c = true;
return;
}
c = true;
a.references.delete(s);
if (a.retirement && !a.retirement.isCurrent()) {
a.retirement = void 0;
a.asyncRetirement = void 0;
a.retiring = false;
}
if (o?.isCurrent() && !a.retirement?.ordinary) a.retirement = o;
if (a.references.size > 0) return;
if (!a.retirement) {
t.touch(n);
return;
}
a.retiring = true;
if (a.asyncRetirement) {
a.asyncRetirement.start();
return;
}
try {
a.retirement.retire();
} catch (e) {
c = false;
t.retainFailed(n);
throw e;
}
a.retirement = void 0;
t.touch(n);
};
const l = {
release,
async releaseAsync() {
if (a.cleanupComplete) return;
if ((o?.isCurrent() && !a.retirement?.ordinary ? o : a.retirement)?.isCurrent()) a.asyncRetirement ??= createAsyncStateDatabaseRetirement();
release();
await a.asyncRetirement?.close();
}
};
r?.own(l, "shared-references", () => l.releaseAsync());
return l;
};
const findReadDatabase = (t, n, r) => {
const i = resolveDatabasePath({ path: t });
const a = e.cachedDatabases.get(i);
if (!a?.db.isOpen) return {
database: void 0,
scope: void 0
};
return {
database: a,
scope: admit(i, n, r)
};
};
const retainReadReference = (t, n) => {
const r = retain(t, n, true);
const assertCurrent = () => {
if (e.cachedDatabases.get(t.path) !== t || !t.db.isOpen) throw new Error("Shared-state read lost its original native owner");
};
return {
assertCurrent,
observe() {
assertCurrent();
observeOpenClawDatabaseMaintenanceResource(t.db);
},
release: () => r.release()
};
};
return {
retain: (e) => retain(e, admit(e.path)),
retainForIndependentRead(e, t, n) {
const { database: r, scope: i } = findReadDatabase(e, t, n);
return r ? retainReadReference(r, i) : void 0;
},
borrowForRead(e, t, n) {
const { database: r, scope: i } = findReadDatabase(e, t, n);
if (!r) return;
if (r.db.isTransaction) throw new Error("Asynchronous shared-state reads cannot run inside a native transaction");
return {
database: r,
...retainReadReference(r, i)
};
}
};
}
function assertStateDatabaseBorrowersReleased(e, t) {
if (e?.references.size) throw new Error(`OpenClaw state database still has active native borrowers: ${t}`);
}
//#endregion
//#region src/state/openclaw-state-db-cache.admission.ts
/** Keep cached reads and terminal failures with their exact native owner. */
function createStateDatabaseCacheAdmission(e) {
return {
closeTerminalFailure(t, n) {
markOpenClawStateDatabaseFailure(n, t);
revokeSqliteDatabaseAdmissionsForPath(t);
e.invalidate(t);
const r = e.cachedDatabases.get(t);
const i = [];
try {
if (r) e.evict(r);
} catch (e) {
i.push(e);
}
try {
e.notifyTerminalFailure(t, n);
} catch (e) {
i.push(e);
}
throwSqliteLifecycleErrors(i, "Terminal shared-state failure cleanup failed");
},
read(t, n) {
if (!t.db.isOpen) return n(t);
let r = false;
try {
return runSqliteReadOperationSync(t.db, () => {
r = true;
return n(t);
});
} catch (n) {
if (r) throw n;
const i = n instanceof Error ? n : new Error(String(n));
if (isSqliteCorruptionError(i)) {
e.evict(t);
return;
}
throw i;
}
}
};
}
//#endregion
//#region src/state/openclaw-state-db-cache.idle.ts
const log = createSubsystemLogger("state/db");
/** Schedule native retirement against the canonical cache's handles and borrow pins. */
function createStateDatabaseIdleRetirement({ cachedDatabases: e, retainedDatabaseHandles: t, idleTimers: n, idleReferences: r, borrowers: i }, a) {
const touch = (o) => {
if (!(e.get(o.path) === o && o.db.isOpen) && t.get(o.db) !== o) return;
const s = n.get(o.db);
if (s) {
s.refresh();
return;
}
const c = runInDetachedAsyncContext(() => setTimeout(() => {
n.delete(o.db);
try {
if (o.db.isOpen && o.db.isTransaction) touch(o);
else if (!i.get(o.db)?.references.size && !r.get(o.db)?.size) a(o, false, {
busyTimeoutMs: 0,
checkpointMode: "PASSIVE"
});
} catch (e) {
log.warn("Idle shared-state database cleanup failed", {
path: o.path,
error: e
});
touch(o);
}
}, SQLITE_IDLE_HANDLE_TTL_MS));
c.unref();
n.set(o.db, c);
};
return {
touch,
/** Retained consumers postpone idle eviction without blocking explicit retirement. */
retain(t) {
if (e.get(t.path) !== t || !t.db.isOpen || i.get(t.db)?.retiring) throw new Error("OpenClaw state database idle retention requires its current canonical handle");
const n = r.get(t.db) ?? /* @__PURE__ */ new Set();
const a = {};
n.add(a);
r.set(t.db, n);
return () => {
if (!n.delete(a)) return;
if (e.get(t.path) === t && t.db.isOpen) touch(t);
};
}
};
}
//#endregion
//#region src/state/openclaw-state-worker-context.capture.ts
/** Capture read authority without constructing a worker environment. */
function captureOpenClawStateReadContextWithAdmission(e, t, n) {
const r = captureOpenClawStateSchemaReadAdmission(e);
const i = t(e);
const a = getGatewayServiceInstallation();
const o = i.captureIntegrity?.();
const s = i.assertCurrent;
let c = i;
let runInCapturedSchemaScope;
if (r) {
const e = AsyncLocalStorage.snapshot();
c = {
databasePath: i.databasePath,
coordinationKey: i.coordinationKey,
get identity() {
return i.identity;
},
captureIntegrity: i.captureIntegrity,
assertCurrent() {
i.assertCurrent();
r.assertCurrent();
}
};
runInCapturedSchemaScope = (t) => e(() => {
c.assertCurrent();
return t();
});
}
return {
databaseEngineSelection: getDatabaseEngineSelection(),
maintenanceScope: getOpenClawDatabaseMaintenanceScope(),
admission: c,
assertPublicationCurrent: s,
existingSchemaPath: r?.path,
gatewayServiceInstallation: a && n(a.databasePath)?.key === i.identity.key ? a : void 0,
stateIntegrity: o,
runInCapturedSchemaScope,
artifactPreservingReads: isArtifactPreservingStateRead("agent", e) || void 0
};
}
/** Read-only workers need resolved runtime facts, not the initialization environment. */
function captureOpenClawStateReadWorkerContextWithAdmission(e, t, n) {
const r = e.env ?? process.env;
const i = process.platform === "win32" ? cloneEnvWithPlatformSemantics(r) : r;
const a = {
OPENCLAW_STATE_DIR: resolveStateDir(i),
...isGatewayExternallySupervised(i) ? { OPENCLAW_SUPERVISOR_MODE: "external" } : {}
};
return {
...captureOpenClawStateReadContextWithAdmission(e.path ?? resolveOpenClawStateSqlitePath(a), t, n),
environment: a
};
}
/** Capture host facts before asynchronous work, without opening SQLite. */
function captureOpenClawStateWorkerContextWithAdmission(e, t, n) {
const r = captureOpenClawStateReadWorkerContextWithAdmission(e, t, n);
return {
...r,
initializationCronDefaultStoreKey: resolveLegacyCronDefaultStoreKey(e.env ?? process.env),
initializationEnvironment: mergeProcessEnv([
e.env ?? process.env,
{
OPENCLAW_STATE_DIR: void 0,
OPENCLAW_SUPERVISOR_MODE: void 0
},
r.environment
]),
...e.initializationAgentPaths ? { initializationAgentPaths: e.initializationAgentPaths.map((e) => path.resolve(e)) } : {}
};
}
//#endregion
//#region src/state/openclaw-state-db-cache.wal.ts
/** Bind periodic maintenance and its observations to the cache's exact native owner. */
function createStateDatabaseWalOwner({ cachedDatabases: e, retainedDatabaseHandles: t, databaseIdentities: n, asyncResources: r }, i, a) {
return {
ownRetirement(e, t) {
const n = {
admission: { identity: a(e) },
close: t
};
const i = r.register(n);
getOpenClawDatabaseMaintenanceResourceScope(e.db)?.own(n, "shared-references", () => n.close());
return i;
},
async stop(r, i) {
const a = /* @__PURE__ */ new Set([...t.values(), ...e.values()]);
await Promise.all([...a].filter((e) => r === void 0 || e.path === r || i !== void 0 && n.get(e.db)?.key === i.key).flatMap(({ walMaintenance: e }) => e ? [e.stop()] : []));
},
register(t, n, a, o) {
if (!isMainThread || isPostgresSqlConnection(t.db)) return;
const s = captureOpenClawStateWorkerContextWithAdmission({
path: t.path,
env: o
}, () => a, r.knownIdentity);
const c = new AbortController();
let l;
const cancel = () => {
c.abort();
if (!l) {
d();
return;
}
return l.then(() => void 0, () => void 0);
};
const u = {
admission: { identity: n },
async close() {
cancel();
await t.walMaintenance.stop();
d();
}
};
const d = r.register(u);
const run = async (r) => {
const a = getOpenClawDatabaseMaintenanceResourceScope(t.db);
const o = {
...s,
maintenanceScope: a
};
const assertCurrent = () => {
c.signal.throwIfAborted();
o.admission.assertCurrent();
a?.assertAdmission();
if (getOpenClawDatabaseMaintenanceResourceScope(t.db) !== a || e.get(t.path) !== t || !t.db.isOpen) throw new StateDatabaseReadAdmissionInvalidatedError("Shared-state WAL maintenance owner changed");
};
let l;
let u = false;
try {
assertCurrent();
l = i(t);
const { runOpenClawStateWorkerOperation: e } = await import("./openclaw-state-worker-store-BURqchns.mjs");
assertCurrent();
return await e(o, (e) => e.execute({
type: "database.walMaintenance",
input: r
}, { signal: c.signal }), {
existingOnly: true,
assertCurrent,
createAdmission: () => ({
nativeLocations: [t.path, n.canonicalPath],
databaseIdentity: {
databasePath: t.path,
key: n.key,
birthtime: n.birthtime
},
admission: createSqliteWorkerOperationAdmission((e, t) => {
assertCurrent();
if (!t()) throw new StateDatabaseReadAdmissionInvalidatedError("Shared-state WAL maintenance authority expired");
u = true;
})
})
});
} catch (e) {
if (!u && (isStateDatabaseReadAdmissionInvalidatedError(e) || c.signal.aborted && isAbortError(e))) return;
throw e;
} finally {
l?.();
}
};
registerSqliteWalWorkerMaintenance(t.db, (e) => {
if (c.signal.aborted) return Promise.resolve(void 0);
const t = run(e);
l = t;
return t.finally(() => {
if (l === t) l = void 0;
if (c.signal.aborted) d();
});
}, cancel);
},
/** Report the last observation without opening or querying SQLite. */
readHealth() {
const t = e.get(path.resolve(resolveOpenClawStateSqlitePath()));
return t?.db.isOpen ? t.walMaintenance.health : void 0;
}
};
}
//#endregion
//#region src/state/openclaw-state-db-integrity-admission.ts
const bindings = resolveGlobalSingleton(Symbol.for("openclaw.stateIntegrityBindings"), () => /* @__PURE__ */ new WeakMap());
const integrityKey = {
name: "state.integrity",
lifetime: "process",
read: (e) => e === true ? true : void 0
};
function hasStateDatabaseIntegrityAdmission(e) {
return Boolean(getStateRuntimeSchemaAdmission(e) || getSqliteDatabaseAdmission(e, integrityKey));
}
/** Ordinary opens share physical-file proof; Doctor calls the uncached integrity owner. */
function assertStateDatabaseIntegrityOnce(e, t) {
if (!hasStateDatabaseIntegrityAdmission(e)) {
assertSqliteIntegrity(e, t);
publishSqliteDatabaseAdmission(e, integrityKey, true);
}
}
function invalidate(e) {
let t = Atomics.load(e, 0);
while (t >= 0n) {
const n = Atomics.compareExchange(e, 0, t, t + 1n);
if (n === t) return;
t = n;
}
}
/** Corruption observed in an isolate revokes the exact host proof borrowed by its native handle. */
function invalidateOpenClawStateRuntimeIntegrity(e) {
revokeSqliteDatabaseAdmissions(e);
const t = bindings.get(e);
if (t) {
invalidate(new BigInt64Array(t.revision));
invalidate(new BigInt64Array(t.lifetimeRevision));
}
}
/** Native bindings revoke borrowed proof; the host generation alone owns its lifetime. */
function bind(e, t) {
if (bindings.get(e)?.revision === t.revision) return;
bindings.get(e)?.release();
const n = new BigInt64Array(t.revision);
const r = registerSqliteSchemaMutationListener(e, () => invalidate(n));
const release = () => {
r();
i();
};
const i = registerNodeSqliteDisposeCallback(e, (e) => {
if (e === "replace") {
invalidate(n);
invalidate(new BigInt64Array(t.lifetime.revision));
}
release();
});
bindings.set(e, {
revision: t.revision,
lifetimeRevision: t.lifetime.revision,
release
});
}
/** Reuse only completed integrity proof; shape and mutable metadata retain their admission owners. */
function assertOpenClawStateRuntimeIntegrity(e, t, n, r, i = "verify") {
const a = r && readTrackedStateDatabaseIdentity(e);
if (!r || !a || !a.key.startsWith("file:") || a.key !== r.identity.key || a.birthtime !== r.identity.birthtime) {
if (i === "require-proof") throw new Error("Shared-state reader requires current worker integrity proof");
assertStateDatabaseIntegrityOnce(e, t);
return;
}
bind(e, r);
const o = new BigInt64Array(r.revision);
const s = new BigInt64Array(r.proof);
const c = BigInt.asIntN(64, BigInt(n.userVersion >>> 0) << 32n | BigInt(n.schemaVersion >>> 0));
const l = Atomics.load(s, 0);
if (Atomics.load(o, 0) === r.epoch && l !== -1n) {
if (l === c && Atomics.load(o, 0) === r.epoch && hasStateDatabaseIntegrityAdmission(e)) return;
invalidate(o);
}
if (i === "require-proof") throw new Error("Shared-state reader requires current worker integrity proof");
assertStateDatabaseIntegrityOnce(e, t);
const publish = () => {
if (Atomics.load(o, 0) === r.epoch) Atomics.store(s, 0, c);
};
return () => {
if (e.isTransaction) stageSqliteTransactionState(e, { commit: publish });
else publish();
};
}
//#endregion
//#region src/state/openclaw-state-db-removal-exclusion.ts
/** Hold native file-removal exclusion under the maintenance owner until it drains. */
function retainSqliteDatabaseRemovalExclusion(e, t) {
if (!existsSync(e)) return;
const n = openNodeSqliteDatabase(resolveExistingSqliteFileUri(e));
const close = () => {
if (!n.isOpen) return;
const e = [];
try {
if (n.isTransaction) n.exec("ROLLBACK");
} catch (t) {
e.push(t);
}
try {
n.close();
} catch (t) {
e.push(t);
}
throwSqliteLifecycleErrors(e, "SQLite state removal exclusion cleanup failed.");
};
try {
t.own(n, "shared-handles", close);
n.exec("PRAGMA busy_timeout = 0; PRAGMA locking_mode = EXCLUSIVE; BEGIN EXCLUSIVE;");
} catch (e) {
try {
close();
} catch (t) {
throw createSqliteLifecycleAggregateError([e, t], "SQLite state removal admission and cleanup both failed.", e);
}
if (isSqliteLockError(e)) throw new Error("Cannot remove OpenClaw state directory while another SQLite connection is active", { cause: e });
const t = sqlitePrimaryResultCode(e);
if (t !== 11 && t !== 26) throw e;
return;
}
if (process.platform === "win32") close();
}
//#endregion
//#region src/state/openclaw-state-db-snapshot-owner.ts
function createOpenClawStateSnapshotOwnerRegistry() {
const e = /* @__PURE__ */ new WeakMap();
return {
register(t, n) {
if (isPostgresSqlConnection(t.db)) return;
e.set(t.db, registerLiveSqliteSnapshotOwner({
database: t.db,
databasePath: t.path,
assertCurrent: () => {
if (n() !== t || !t.db.isOpen) throw new Error("OpenClaw state snapshot owner is no longer current");
}
}));
},
release(t) {
if (isPostgresSqlConnection(t)) return;
e.get(t)?.();
e.delete(t);
}
};
}
const openClawStateSnapshotOwners = resolveGlobalSingleton(Symbol.for("openclaw.stateSnapshotOwners"), createOpenClawStateSnapshotOwnerRegistry);
//#endregion
//#region src/state/openclaw-state-db-cache.ts
const STATE_DATABASE_LIFECYCLE_KEY = Symbol.for("openclaw.stateDatabaseLifecycle");
const stateDatabaseLifecycle = resolveGlobalSingleton(STATE_DATABASE_LIFECYCLE_KEY, () => ({
cachedDatabases: /* @__PURE__ */ new Map(),
retainedDatabaseHandles: /* @__PURE__ */ new Map(),
idleTimers: /* @__PURE__ */ new WeakMap(),
idleReferences: /* @__PURE__ */ new WeakMap(),
unregisterRetainedExitClose: void 0,
databaseIdentities: /* @__PURE__ */ new WeakMap(),
borrowers: /* @__PURE__ */ new WeakMap(),
databaseLifecycleListeners: /* @__PURE__ */ new Set(),
terminalOpenLatch: createSqliteTerminalOpenLatch({ closeByPath: (e, t) => cacheAdmission.closeTerminalFailure(e, t) }),
asyncResources: createOpenClawStateDatabaseAsyncLifecycle()
}), () => closeOpenClawStateDatabaseAsync(), "shared-state");
const { cachedDatabases, retainedDatabaseHandles, idleTimers, idleReferences, databaseIdentities, borrowers, databaseLifecycleListeners, terminalOpenLatch, asyncResources } = stateDatabaseLifecycle;
const { touch: touchStateDatabase, retain: retainOpenClawStateDatabaseForIdle } = createStateDatabaseIdleRetirement(stateDatabaseLifecycle, retireOpenClawStateDatabaseHandle);
const { register: registerStateDatabaseWalAdmission, readHealth: readOpenClawStateWalHealth, ownRetirement: ownStateDatabaseRetirement, stop: stopOpenClawStateDatabaseMaintenance } = createStateDatabaseWalOwner(stateDatabaseLifecycle, retainOpenClawStateDatabaseForIdle, requireOpenClawStateDatabaseIdentity);
function notifyOpenClawStateDatabaseLifecycle(e) {
const t = e.kind === "open-error" ? {
...e,
identity: e.identity ?? asyncResources.knownIdentity(e.path)
} : e;
for (const e of databaseLifecycleListeners) e(t);
}
function notifyOpenClawStateDatabaseClosed(e) {
notifyOpenClawStateDatabaseLifecycle({
kind: "closed",
path: e.path,
identity: requireOpenClawStateDatabaseIdentity(e)
});
}
function requireOpenClawStateDatabaseIdentity(e) {
const t = databaseIdentities.get(e.db);
if (!t) throw new Error("Published shared-state owner has no recorded database identity");
return t;
}
const cacheAdmission = createStateDatabaseCacheAdmission({
cachedDatabases,
evict: evictCachedOpenClawStateDatabase,
invalidate: (e) => asyncResources.invalidate(e),
notifyTerminalFailure: (e, t) => notifyOpenClawStateDatabaseLifecycle({
kind: "terminal-failure",
path: e,
error: t,
identity: asyncResources.knownIdentity(e)
})
});
function registerOpenClawStateDatabaseLifecycleListener(e) {
databaseLifecycleListeners.add(e);
for (const t of cachedDatabases.values()) if (t.db.isOpen) e({
kind: "opened",
database: t,
identity: requireOpenClawStateDatabaseIdentity(t)
});
return () => databaseLifecycleListeners.delete(e);
}
/** Invalidate path-scoped projections on non-open database lifecycle events. */
function registerOpenClawStatePathCacheInvalidation(e) {
return registerOpenClawStateDatabaseLifecycleListener((t) => {
if (t.kind !== "opened") {
for (const [n, r] of e) if (r.path === (t.identity?.canonicalPath ?? t.path)) e.delete(n);
}
});
}
function retainStateDatabaseClose(e) {
retainedDatabaseHandles.set(e.db, e);
stateDatabaseLifecycle.unregisterRetainedExitClose ??= registerSqliteCacheExitClose(closeOpenClawStateDatabase);
}
function ownMaintenanceStateDatabaseHandle(e) {
getOpenClawDatabaseMaintenanceScope()?.own(e.db, "shared-handles", async () => {
const t = getOpenClawDatabaseMaintenanceScope();
if (!t || !isOpenClawDatabaseMaintenanceResourceOwned(e.db, t)) return;
if (cachedDatabases.get(e.path) === e || retainedDatabaseHandles.get(e.db) === e) {
await e.walMaintenance?.stop();
if (isOpenClawDatabaseMaintenanceResourceOwned(e.db, t) && (cachedDatabases.get(e.path) === e || retainedDatabaseHandles.get(e.db) === e)) retireOpenClawStateDatabaseHandle(e, false);
}
});
}
function closeUnpublishedOpenClawStateDatabaseHandle(e) {
const t = closeOpenClawStateDatabaseHandle(e);
if (retainedDatabaseHandles.get(e.db) === e) ownMaintenanceStateDatabaseHandle(e);
return t;
}
/** Retain one exact canonical native owner; only the final reference retires its handle. */
const { retain: retainOpenClawStateDatabase, borrowForRead: borrowOpenClawStateDatabaseForAsyncRead, retainForIndependentRead: retainOpenClawStateDatabaseForIndependentRead } = createStateDatabaseRetainer(stateDatabaseLifecycle, {
assertOpen(e, t, n) {
assertOpenClawStateDatabaseOpenAllowed(e, t, n);
assertExistingOpenClawStateSchemaCacheAdmission(e, stateDatabaseLifecycle);
},
capture: (e) => asyncResources.capture(e),
retire: retireOpenClawStateDatabaseHandle,
retainFailed: retainStateDatabaseClose,
ownRetirement: ownStateDatabaseRetirement,
touch: touchStateDatabase
});
/** Close both physical-handle owners while retaining every cleanup failure. */
function closeOpenClawStateDatabaseHandle(e, t) {
clearTimeout(idleTimers.get(e.db));
idleTimers.delete(e.db);
try {
assertStateDatabaseBorrowersReleased(borrowers.get(e.db), e.path);
} catch (n) {
const r = borrowers.get(e.db);
if (r) {
r.retiring = true;
r.retirement = {
ordinary: true,
isCurrent: () => true,
retire: () => {
throwSqliteLifecycleErrors(closeOpenClawStateDatabaseHandle(e, t), `OpenClaw state database cleanup failed for ${e.path}.`);
r.cleanupComplete = true;
borrowers.delete(e.db);
}
};
}
retainStateDatabaseClose(e);
return [n];
}
idleReferences.delete(e.db);
openClawStateSnapshotOwners.release(e.db);
const { errors: n, cleanupPending: r } = closeStateDatabaseHandle(e, t);
if (e.db.isOpen || r) retainStateDatabaseClose(e);
else retainedDatabaseHandles.delete(e.db);
if (cachedDatabases.get(e.path)?.db === e.db) cachedDatabases.delete(e.path);
if (retainedDatabaseHandles.size === 0) {
stateDatabaseLifecycle.unregisterRetainedExitClose?.();
stateDatabaseLifecycle.unregisterRetainedExitClose = void 0;
}
return n;
}
function evictCachedOpenClawStateDatabase(e) {
if (!isPostgresSqlConnection(e.db)) invalidateOpenClawStateRuntimeIntegrity(e.db);
if (cachedDatabases.get(e.path) !== e) return false;
asyncResources.invalidate(e.path);
cachedDatabases.delete(e.path);
notifyOpenClawStateDatabaseClosed(e);
closeOpenClawStateDatabaseHandle(e, { checkpointMode: "PASSIVE" });
return true;
}
/** Evict an exact cached shared-state owner after a proven corruption read. */
function evictOpenClawStateDatabaseAfterCorruption(e, t) {
return isSqliteCorruptionError(t) && evictCachedOpenClawStateDatabase(e);
}
/** Publish a fully opened handle and bind query corruption to its exact cache owner. */
function publishOpenClawStateDatabase(e, t) {
const { db: n, path: r } = e;
const { identity: i, admission: a } = asyncResources.publish(r);
databaseIdentities.set(n, readTrackedStateDatabaseIdentity(n) ?? i);
cachedDatabases.set(r, e);
registerStateDatabaseWalAdmission(e, i, a, t);
touchStateDatabase(e);
openClawStateSnapshotOwners.register(e, () => cachedDatabases.get(r));
ownMaintenanceStateDatabaseHandle(e);
notifyOpenClawStateDatabaseLifecycle({
kind: "opened",
database: e,
identity: i
});
if (!isPostgresSqlConnection(n)) registerNodeSqliteKyselyQueryErrorHandler(n, (t) => {
if (!n.isTransaction && isSqliteCorruptionError(t)) evictCachedOpenClawStateDatabase(e);
});
terminalOpenLatch.clear(r);
return e;
}
/** Looking up an admitted handle does not consume schema or row facts. */
function getCachedOpenClawStateDatabase(e, t) {
const n = resolveDatabasePath({ path: e });
const r = terminalOpenLatch.get(n);
if (r) throw r;
return readCachedOpenClawStateDatabase(n, t);
}
function readCachedOpenClawStateDatabase(e, t) {
const n = getOpenClawDatabaseMaintenanceScope();
if (t?.readOnly) n?.assertReadAdmission();
else n?.assertAdmission();
assertExistingOpenClawStateSchemaCacheAdmission(e, stateDatabaseLifecycle);
const r = cachedDatabases.get(e);
if (r) {
if (borrowers.get(r.db)?.retiring) throw new Error(`OpenClaw state database native borrower cleanup is pending: ${e}`);
touchStateDatabase(r);
}
return r;
}
/** Prepared host facts retain admission; native transactions still expose their staged facts. */
function prepareOpenClawStateCachedRead(e) {
const t = resolveDatabasePath({ path: e });
const n = { readOnly: true };
getCachedOpenClawStateDatabase(t, n);
const r = asyncResources.capture(t);
return () => {
r.assertCurrent();
return readCachedOpenClawStateDatabase(t, n);
};
}
/** Keep the admitted revision live while a synchronous reader consumes its row facts. */
function withCachedOpenClawStateDatabase(e, t, n) {
const r = getCachedOpenClawStateDatabase(e, t);
return r && cacheAdmission.read(r, n);
}
function getOpenClawStateDatabaseIfOpenAtPath(e) {
const t = getCachedOpenClawStateDatabase(e);
observeOpenClawDatabaseMaintenanceResource(t?.db.isOpen ? t.db : void 0);
return t?.db.isOpen ? t : void 0;
}
/** Remove a closed cached owner while fresh-open access is held. */
function closeStaleCachedOpenClawStateDatabase(e) {
if (cachedDatabases.get(e.path) !== e) return;
asyncResources.invalidate(e.path);
const t = closeOpenClawStateDatabaseHandle(e);
notifyOpenClawStateDatabaseClosed(e);
throwSqliteLifecycleErrors(t, `Stale OpenClaw state database cleanup failed for ${e.path}.`);
}
/** Latch integrity refusals so later opens fail without rescanning. */
function recordOpenClawStateDatabaseOpenFailure(e, t) {
terminalOpenLatch.record(resolveDatabasePath({ path: e }), t);
}
/** Clear a terminal open failure after doctor rewrites the database file. */
function clearOpenClawStateDatabaseOpenFailure(e) {
const t = resolveDatabasePath({ path: e });
terminalOpenLatch.clear(t);
asyncResources.invalidate(t);
notifyOpenClawStateDatabaseLifecycle({
kind: "failure-cleared",
path: t,
identity: asyncResources.knownIdentity(t)
});
}
/** Validate the canonical terminal fact before acquiring a domain-operation lease. */
async function getOpenClawStateDatabaseTerminalFailureAsync(e, t) {
e.admission.assertCurrent();
t?.throwIfAborted();
return terminalOpenLatch.get(e.admission.databasePath);
}
/** Reject shared-state access after a process-local terminal failure. */
function assertOpenClawStateDatabaseOpenAllowed(e, t, n) {
const r = resolveDatabasePath({ path: e });
const i = t === "cached-read" ? assertStateDatabaseReadAllowed : assertStateDatabaseAccessAllowed;
if (t === "cached-read" && n) n.assertReadAllowed();
else i(e);
const { identity: a } = asyncResources.capture(r);
const o = terminalOpenLatch.get(r);
if (o) throw o;
for (const t of retainedDatabaseHandles.values()) if (borrowers.get(t.db)?.retiring && (t.path === r || databaseIdentities.get(t.db)?.key === a.key)) throw new Error(`OpenClaw state database native borrower cleanup is pending: ${e}`);
}
function recordOpenClawStateDatabaseLifecycleOpenError(e, t) {
notifyOpenClawStateDatabaseLifecycle({
kind: "open-error",
path: resolveDatabasePath({ path: e }),
error: t
});
}
/** Reject a fresh shared-state open after known corruption until repair clears it. */
function assertOpenClawStateDatabaseFreshOpenAllowedAtPath(e, t, n) {
assertOpenClawStateDatabaseOpenAllowed(e);
let r;
try {
r = readOpenClawDatabaseQuarantineFailure("state", e, { env: t });
} catch (e) {
if (!(e instanceof OpenClawQuarantineReadCleanupError)) throw e;
n?.(e);
return;
}
if (r?.cause instanceof OpenClawQuarantineReadCleanupError) n?.(r.cause);
if (r) {
cacheAdmission.closeTerminalFailure(e, r);
throw r;
}
}
/** SQLite owns checkpoint exclusion; retirement joins the actual native handle. */
function retireOpenClawStateDatabaseHandle(e, t = true, n) {
assertStateDatabaseBorrowersReleased(borrowers.get(e.db), e.path);
const r = borrowers.get(e.db);
try {
const r = cachedDatabases.get(e.path)?.db === e.db;
if (t) asyncResources.invalidate(e.path);
const i = closeOpenClawStateDatabaseHandle(e, n);
if (r && t) try {
notifyOpenClawStateDatabaseClosed(e);
} catch (e) {
i.push(e);
}
throwSqliteLifecycleErrors(i, `OpenClaw state database cleanup failed for ${e.path}.`);
} catch (t) {
if (r) retainStateDatabaseClose(e);
throw t;
}
if (r) {
r.cleanupComplete = true;
borrowers.delete(e.db);
}
}
/** Close cached and disposal-only handles, preserving independent cleanup failures. */
function retireOpenClawStateDatabaseHandles(e, t, n) {
const r = /* @__PURE__ */ new Set([...retainedDatabaseHandles.values(), ...cachedDatabases.values()]);
const i = [];
let a = false;
for (const o of r) {
if (e !== void 0 && o.path !== e && (n === void 0 || databaseIdentities.get(o.db)?.key !== n.key)) continue;
a = true;
try {
retireOpenClawStateDatabaseHandle(o, true, t);
} catch (e) {
i.push(e);
}
}
throwSqliteLifecycleErrors(i, "OpenClaw state database cleanup failed.");
return a;
}
function closeOpenClawStateDatabaseByPath(e, t) {
return retireOpenClawStateDatabaseHandles(resolveDatabasePath({ path: e }), t, asyncResources.identity(e));
}
function closeOpenClawStateDatabase(e) {
retireOpenClawStateDatabaseHandles(void 0, e);
}
/** Register a resource owner before it can admit any shared-state worker opens. */
const registerOpenClawStateDatabaseAsyncResource = asyncResources.register;
/** Close the admitted file or its canonical path, retaining first-creation identity getters. */
function registerOpenClawStatePathAsyncResource(e, t) {
return registerOpenClawStateDatabaseAsyncResource({ close(n) {
if (!n || n.key === e.identity.key || n.canonicalPath === e.identity.canonicalPath) return t();
return Promise.resolve();
} });
}
/** Capture the canonical read generation before any asynchronous worker admission. */
const captureOpenClawStateDatabaseReadAdmission = asyncResources.capture;
const captureOpenClawStateIntegrityAdmission = asyncResources.integrity;
/** Bind worker-created storage to its captured admission without publishing a native handle. */
function publishOpenClawStateDatabaseWorkerAdmission(e, t) {
if (t) e.assertCurrent();
asyncResources.publish(e.databasePath, t);
e.assertCurrent();
}
/** Drain worker resources before native checkpoint/close at one exact path. */
/** Drain worker-held connections while retaining the native owner at this path. */
function closeOpenClawStateDatabaseWorkersByPathAsync(e) {
return asyncResources.close(resolveDatabasePath({ path: e }), () => false);
}
function closeOpenClawStateDatabaseByPathAsync(e, t) {
const n = resolveDatabasePath({ path: e });
return asyncResources.close(n, async (e) => {
await stopOpenClawStateDatabaseMaintenance(n, e);
return retireOpenClawStateDatabaseHandles(n, t, e);
});
}
/** Orderly lifecycle close; synchronous close remains native/exit cleanup only. */
async function closeOpenClawStateDatabaseAsync(e) {
await asyncResources.close(void 0, async () => {
await stopOpenClawStateDatabaseMaintenance();
return retireOpenClawStateDatabaseHandles(void 0, e);
});
}
function isOpenClawStateDatabaseOpen(e) {
if (e !== void 0) return cachedDatabases.get(resolveDatabasePath({ path: e }))?.db.isOpen === true;
return Array.from(cachedDatabases.values()).some((e) => e.db.isOpen);
}
/**
* Close shared state handles and clear terminal failure latches for test isolation.
* Worker retirement continues after return; await closeOpenClawStateDatabaseAsync()
* before raw SQLite or file access to a database that workers have used.
*/
function closeOpenClawStateDatabaseForTest() {
closeOpenClawStateDatabase();
terminalOpenLatch.clearAll();
}
/**
* Owners that register with this cache must serve only the published lifecycle.
* Every runtime chunk shares that lifecycle; only a retired module generation
* (a re-evaluated test graph whose detached work outlived its file) can differ.
*/
function assertPublishedOpenClawStateDatabaseLifecycle() {
if (readGlobalSingleton(STATE_DATABASE_LIFECYCLE_KEY) !== stateDatabaseLifecycle) throw new Error("OpenClaw state database lifecycle is retired; its owners cannot serve the published lifecycle");
}
/** Process-wide owner for cached shared-state handles and terminal open failures. */
const openClawStateDatabaseCache = {
assertOpenClawStateDatabaseFreshOpenAllowedAtPath,
assertOpenClawStateDatabaseOpenAllowed,
clearOpenClawStateDatabaseOpenFailure,
closeOpenClawStateDatabase,
closeOpenClawStateDatabaseByPath,
closeOpenClawStateDatabaseForTest,
closeOpenClawStateDatabaseHandle,
closeUnpublishedOpenClawStateDatabaseHandle,
closeStaleCachedOpenClawStateDatabase,
evictCachedOpenClawStateDatabase,
evictOpenClawStateDatabaseAfterCorruption,
getCachedOpenClawStateDatabase,
peekOpenClawStateDatabaseConnection: (e) => cachedDatabases.get(resolveDatabasePath({ path: e }))?.db,
withCachedOpenClawStateDatabase,
getOpenClawStateDatabaseRecordedFailure: terminalOpenLatch.peek,
getOpenClawStateDatabaseIfOpenAtPath,
getKnownOpenClawStateDatabaseIdentity: asyncResources.knownIdentity,
isOpenClawStateDatabaseOpen,
/** Only the exact published, open owner carries canonical schema readiness. */
isOpenClawStateDatabaseSchemaReady: (e) => cachedDatabases.get(e.path) === e && e.db.isOpen,
publishOpenClawStateDatabase,
recordOpenClawStateDatabaseOpenFailure,
recordOpenClawStateDatabaseLifecycleOpenError,
touchStateDatabase
};
/** Offline removal drains local work and refuses an active native SQLite owner. */
async function prepareOpenClawStateDatabaseRemoval(e, t) {
const n = resolveDatabasePath({ path: e });
const r = getOpenClawDatabaseMaintenanceScope();
if (!r?.ownsSchemaMaintenance) throw new Error("State removal requires the installation's maintenance owner");
r.assertAdmission();
const i = asyncResources.holdExclusion(n);
try {
await closeOpenClawStateDatabaseByPathAsync(n);
r.assertOwnerCurrent();
retainSqliteDatabaseRemovalExclusion(n, r);
r.assertOwnerCurrent();
} catch (e) {
i();
throw e;
}
let a = true;
return {
assertCurrent() {
if (!a) throw new Error("State removal admission has been released");
t();
},
release() {
if (a) {
a = false;
i();
}
}
};
}
//#endregion
export { invalidateOpenClawStateRuntimeIntegrity as A, registerOpenClawStatePathCacheInvalidation as C, retainOpenClawStateDatabaseForIndependentRead as D, retainOpenClawStateDatabaseForIdle as E, captureOpenClawStateReadWorkerContextWithAdmission as M, captureOpenClawStateWorkerContextWithAdmission as N, assertOpenClawStateRuntimeIntegrity as O, createSqliteTerminalOpenLatch as P, registerOpenClawStatePathAsyncResource as S, retainOpenClawStateDatabase as T, publishOpenClawStateDatabaseWorkerAdmission as _, clearOpenClawStateDatabaseOpenFailure as a, registerOpenClawStateDatabaseAsyncResource as b, closeOpenClawStateDatabaseByPath as c, closeOpenClawStateDatabaseWorkersByPathAsync as d, getOpenClawStateDatabaseTerminalFailureAsync as f, prepareOpenClawStateDatabaseRemoval as g, prepareOpenClawStateCachedRead as h, captureOpenClawStateIntegrityAdmission as i, captureOpenClawStateReadContextWithAdmission as j, assertStateDatabaseIntegrityOnce as k, closeOpenClawStateDatabaseByPathAsync as l, openClawStateDatabaseCache as m, borrowOpenClawStateDatabaseForAsyncRead as n, closeOpenClawStateDatabase as o, isOpenClawStateDatabaseOpen as p, captureOpenClawStateDatabaseReadAdmission as r, closeOpenClawStateDatabaseAsync as s, assertPublishedOpenClawStateDatabaseLifecycle as t, closeOpenClawStateDatabaseForTest as u, readOpenClawStateWalHealth as v, requireOpenClawStateDatabaseIdentity as w, registerOpenClawStateDatabaseLifecycleListener as x, recordOpenClawStateDatabaseOpenFailure as y };