openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
943 lines (942 loc) • 37.6 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as assertEngineStoreExecutionAllowed } from "./admission-scope-DmxaPNhm.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import "./paths-DAcAg5aV.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { c as resolveOpenClawAgentSqlitePath, t as INCOGNITO_AGENT_SQLITE_BASENAME } from "./openclaw-agent-db.paths-DJxv80ws.mjs";
import { a as getOpenClawDatabaseMaintenanceScope, d as observeOpenClawDatabaseMaintenanceResource } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import { n as isPostgresSqlConnection, r as sqlPublicationAnchor } from "./sql-connection-Beiyg5Dt.mjs";
import { h as resolveDatabasePathKey, i as assertExistingDatabaseIdentity, m as readDatabasePathIdentitySync } from "./sqlite-worker-identity-BH8ZkJU9.mjs";
import { C as readSqliteDatabaseCleanCloseRefusal, s as getSqliteDatabaseAdmissionIdentityForPath, st as supportsNodeSqliteExtensionLoading, w as readSqliteDatabaseIntegrityVerification } from "./sqlite-database-admission-DQIqro3d.mjs";
import { c as withSqlitePostCommitPublications } from "./sqlite-post-commit-BrUVQObC.mjs";
import "./kysely-sync-YJo2lmGV.mjs";
import { a as enableNodeSqliteKyselyStatementCache } from "./kysely-sync-cache-state-Bb1gOqQO.mjs";
import { t as admitSqliteSchema } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { a as isSqliteSchemaVersionError, s as readSqliteWriterAppVersion } from "./sqlite-user-version-C02a4KwH.mjs";
import { l as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "./openclaw-state-db-contract-DfPjvL0M.mjs";
import { t as VERSION } from "./version-GlxUMdxI.mjs";
import { i as runWithSqliteBusyTimeout } from "./sqlite-busy-timeout-BEDmnGR_.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 { r as readExistingAgentSchemaMeta } from "./openclaw-agent-db-metadata-C3YvwHLh.mjs";
import { a as runSqliteImmediateTransactionSync, c as runSqliteSingleStatementSync } from "./sqlite-transaction-BHHu6P5-.mjs";
import { n as configureSqlitePreSchemaPragmas, o as registerSqliteCacheExitClose, s as createSqliteWalReclamationResult, t as configureSqliteConnectionPragmas } from "./sqlite-wal-DGPrWPl6.mjs";
import { r as prepareSqliteDatabaseDirectory } from "./sqlite-wal-filesystem-LJsoYuDu.mjs";
import { a as registerSqliteWalWorkerMaintenance, i as registerDeferredSqliteWalWriteAdmission } from "./sqlite-wal-write-admission-BDhnPj3y.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { s as matchesAgentDatabaseReadCandidatePath } from "./agent-database-readers-kAORIt-A.mjs";
import { _ as assertAgentCreationClaimCurrent, g as assertAgentCreationClaimAliases, h as assertAgentCreationClaimAccess, o as registerOpenClawAgentDatabaseAsyncResource, t as assertAgentDatabaseResourceAdmission, v as captureAgentCreationClaim, x as reserveAgentCreationClaimAdmission, y as registerAgentCreationClaimHandle } from "./openclaw-agent-db-resources-Dp8HvLsg.mjs";
import { n as assertAgentDeletionDatabaseCleanupAccess, o as getAgentDeletionDatabaseCleanup, s as registerAgentDeletionDatabaseCleanup } from "./agent-deletion-cleanup-BweMIhGD.mjs";
import { c as SqliteWorkerOpenRefusedError } from "./sqlite-worker-contract--dxXkOty.mjs";
import { f as requestSqliteWorkerOperationAdmission, i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs";
import { i as quarantineOrphanedSqliteSidecars } from "./sqlite-files-rWisKj_V.mjs";
import { i as readOpenClawDatabaseQuarantineFailure, n as clearOpenClawDatabaseQuarantine } from "./openclaw-quarantine-store-Bi4DSTmN.mjs";
import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs";
import { o as isGatewayExternallySupervised } from "./gateway-supervision-C1X-e8qk.mjs";
import { c as runSqliteIntegrityCheckSync, l as runSqliteIntegrityOperationSync, o as isTerminalSqliteIntegrityError } from "./sqlite-integrity-CCmEgO_m.mjs";
import { o as agentDatabaseAdmissionProvenanceRefusal, u as readAgentDatabaseLeaseProvenance } from "./openclaw-state-db-existing-schema-C1h5v6Xh.mjs";
import "./openclaw-agent-db-contract-aCH9b8Uc.mjs";
import "./openclaw-state-db-ARhwdPJg.mjs";
import { a as readOpenClawAgentDatabaseIdentity, o as registerOpenClawAgentDatabaseIdentity, t as assertOpenClawAgentDatabaseIdentity } from "./openclaw-agent-db-identity-C8MGU8lp.mjs";
import { i as assertSupportedAgentSchemaVersion, n as assertCurrentAgentSchemaMetadata, r as assertExistingAgentSchemaOwner, t as assertCanonicalAgentPersistenceVersion } from "./openclaw-agent-db-schema-read-U5-_81Kg.mjs";
import { i as openAgentEngineStore, n as agentEngineInput } from "./openclaw-agent-db-engine-CFD02117.mjs";
import { n as assertAgentDatabaseAdmitted } from "./agent-database-admission-CL6wHJ_N.mjs";
import { i as retainAgentDatabase, n as getOpenClawAgentDatabaseIfOpen } from "./openclaw-agent-db-borrower-BrziJlyo.mjs";
import { r as hasRegisteredOpenClawAgentDatabasePath } from "./openclaw-agent-db-registry-listing-CbXBL50a.mjs";
import { c as hasAgentDatabaseMaintenanceAuthority, h as releaseOpenClawAgentDatabaseLease, o as assertOpenClawAgentDatabaseLease, p as recordOpenClawAgentDatabaseAdmission, s as claimOpenClawAgentDatabaseLease } from "./openclaw-agent-db-lease-BZhGt_sk.mjs";
import { _ as publishOpenClawAgentDatabaseSchema, c as getOpenClawAgentDatabaseValidation, d as hasRevokedOpenClawAgentDatabaseValidation, i as captureOpenClawAgentDatabaseAliasPublication, l as getOpenClawAgentDatabaseValidationForTransfer, m as invalidateOpenClawAgentDatabaseValidation, n as adoptOpenClawAgentDatabaseValidation, t as adoptOpenClawAgentDatabaseSchema, w as assertCanonicalSessionValidationSchema, y as setOpenClawAgentDatabaseValidation } from "./openclaw-agent-db-validation-cache-lnjWuypr.mjs";
import { _ as revokePendingAgentDatabaseOpen, g as retainFailedAgentDatabaseClose, h as registerAgentDatabaseHandle, m as refreshAgentDatabaseIdleTimer, n as closeCachedOpenClawAgentDatabase, o as closeOpenClawAgentDatabaseByPathAsync, p as recordOpenClawAgentDatabaseOpenFailure, r as closeMaintenanceAgentDatabase, s as closeOpenClawAgentDatabases, t as cache, u as createAgentDatabaseScopeOwnedClose, y as startAgentDatabaseOpenTiming } from "./openclaw-agent-db-lifecycle-DqaZZnYh.mjs";
import { t as assertSqliteIntegrityInWorker } from "./sqlite-integrity-worker-D_lHVvZY.mjs";
import { c as revalidateAgentDatabaseTerminalOpenAsync, s as revalidateAgentDatabaseTerminalOpen } from "./openclaw-agent-db-readonly-open-BzFUagBt.mjs";
import { n as closeIdleOpenClawAgentDatabaseReadOnly } from "./openclaw-agent-db-readonly-scope-B8DxQsJ2.mjs";
import "./openclaw-agent-outbox-sequence-migration-ATXcQD7n.mjs";
import { t as runSqliteIntegrityOperationInWorker } from "./sqlite-integrity-operation-Cqe4C-U7.mjs";
import { i as runOpenClawAgentWorkerWrite, t as createSessionWorkerExecutionSource } from "./session-worker-execution-source-H3bdawqM.mjs";
import { n as ensureAgentSchema, o as ensureOpenClawAgentDatabasePermissions, t as agentDatabaseIntegrityBeforeMutationSteps } from "./openclaw-agent-db-schema-D-iWGl31.mjs";
import { t as registerOpenClawAgentDatabase } from "./openclaw-agent-db-registry-DobcJNwx.mjs";
import "./openclaw-agent-db-owner-read-BF5eClGm.mjs";
import path from "node:path";
import { isMainThread } from "node:worker_threads";
//#region src/state/openclaw-agent-db-worker-admission.ts
/** The existing executor owns cold admission; the native callback retains the SDK handle contract. */
async function withWorkerAdmission(e, t, n, r, i) {
const a = resolveOpenClawAgentSqlitePath(e);
assertAgentCreationClaimCurrent(e);
assertAgentCreationClaimAliases(e);
const o = captureAgentCreationClaim(e);
const s = i ? getSqliteDatabaseAdmissionIdentityForPath(a) : void 0;
const c = s ? {
...s,
canonicalPath: resolveDatabasePathKey(a)
} : readDatabasePathIdentitySync(a);
const l = normalizeAgentId(e.agentId);
if (i) {
i.assertCurrent();
if (i.agentId !== l || i.path !== a) throw new Error("Agent worker admission differs from its captured execution");
}
let u = c.canonicalPath !== a ? captureOpenClawAgentDatabaseAliasPublication({
agentId: l,
path: a
}) : void 0;
const d = createDeferredCore();
let f = false;
let releaseExecution;
const assertAdmission = () => {
if (f) throw new Error("Agent database admission closed during worker preparation");
t?.();
i?.assertCurrent();
o?.assertCurrent();
n?.throwIfAborted();
};
const p = registerOpenClawAgentDatabaseAsyncResource({
agentId: l,
path: a,
revoke: () => {
f = true;
},
close: () => d.promise
}, e);
try {
const t = await import("./openclaw-agent-execution-D8fPsYYC.mjs");
assertAdmission();
if (!t.supportsOpenClawAgentDatabaseExecution(e)) return await r("native");
let o;
if (i) o = i;
else {
const n = t.captureOpenClawAgentDatabaseExecution(e, c.key.startsWith("file:") ? { expectedIdentity: {
kind: "file",
physicalIdentity: c.key.slice(5),
nativeLocation: c.canonicalPath,
birthtime: c.birthtime
} } : {});
o = n;
releaseExecution = () => n.release();
}
const s = {
assertCurrent: assertAdmission,
createAdmission: (e) => () => ({
nativeLocations: e.nativeLocations,
admission: createSqliteWorkerOperationAdmission((t, n) => {
e.authorize(t);
assertAdmission();
if (u && t.stage === "prepare" && isRecord(t.facts) && t.facts.kind === "agent-validation-start") u = captureOpenClawAgentDatabaseAliasPublication({
agentId: l,
path: a
});
if (!n()) throw new Error("Agent database preparation lost its admission");
}, e.attachment)
})
};
await runOpenClawAgentWorkerWrite(e, () => o.prepare(s, n));
assertAdmission();
u?.(o.captureGenerationClaim().identity, getOpenClawAgentDatabaseValidationForTransfer({
agentId: l,
path: c.canonicalPath
}));
return await r("worker");
} finally {
try {
await releaseExecution?.();
} finally {
p();
d.resolve();
}
}
}
//#endregion
//#region src/state/openclaw-agent-db-admission.ts
/** Refusal must unwind ownership without entering corruption repair or changing its caller error. */
function assertAgentDatabaseOpenAuthority(e, t) {
try {
t?.();
} catch (t) {
const n = new Error("Agent database open authority was refused", { cause: t });
try {
e.throw(n);
} catch (e) {
if (e !== n) throw new AggregateError([t, e], `Agent database authority and cleanup failed: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
}
throw t;
}
}
function assertAgentDatabaseOperationCurrent(e, t, n, r) {
n.controller.signal.throwIfAborted();
assertAgentDatabaseAdmitted(e.agentId, { env: t.env });
if (cache.databases.get(n.path) !== e || !e.db.isOpen) throw new Error(`Agent database closed before its admitted operation: ${n.path}`);
assertAgentDeletionDatabaseCleanupAccess(e, t);
assertAgentCreationClaimAccess(e, t);
r?.();
}
function assertAgentDatabaseWriteAllowed(e) {
if (path.basename(e) === "incognito-openclaw-agent.sqlite") throw new Error("Incognito sessions use the memory session actor, not a SQLite database.");
if (isArtifactPreservingStateRead("agent", e)) throw new Error("Programming error: writable agent database open during read-only inspection.");
}
/** Bind admission drivers to the canonical private database-open generator. */
function createOpenClawAgentDatabaseAdmissionOwner(e) {
/** Open or return a cached per-agent database after schema and owner validation. */
function openOpenClawAgentDatabase(e, t, n) {
return openAgentDatabase(e, t, n);
}
function openAgentDatabase(t, n, r, i) {
assertAgentDatabaseWriteAllowed(resolveOpenClawAgentSqlitePath(t));
const run = () => {
const a = e(t, void 0, n, r, i);
const assertCurrent = () => {
i?.assertCurrent?.();
if (n && !isMainThread) requestSqliteWorkerOperationAdmission({
stage: "prepare",
facts: {
kind: "agent-open-resume",
lease: n.receipt
}
});
};
const o = n?.startupRepair;
return runSqliteIntegrityOperationSync(a, () => assertAgentDatabaseOpenAuthority(a, assertCurrent), o && !isMainThread ? (e, t) => o(e, t, assertCurrent) : void 0);
};
const a = getOpenClawDatabaseMaintenanceScope();
return a ? a.run(run) : run();
}
/** Startup keeps its lease while a killable reader performs the full integrity check. */
async function openOpenClawAgentDatabaseInWorker(t, n, r, i) {
assertAgentDatabaseWriteAllowed(resolveOpenClawAgentSqlitePath(t));
const a = e(t, void 0, n, r);
const assertCurrent = () => assertAgentDatabaseOpenAuthority(a, () => {
i.throwIfAborted();
requestSqliteWorkerOperationAdmission({
stage: "prepare",
facts: {
kind: "agent-open-resume",
lease: n.receipt
}
});
});
const o = n.startupRepair;
const s = await runSqliteIntegrityOperationInWorker(a, {
busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,
signal: i,
beforeResume: assertCurrent,
repairIntegrityError: o ? (e, t) => o(e, t, assertCurrent) : void 0
});
if (!s) throw new Error("Agent database opening ended without its native owner");
return s;
}
function runOpenClawAgentWriteTransaction(e, t, n = {}) {
const { repairAdmission: r, singleStatement: i, ...a } = n;
const o = openAgentDatabase(t, void 0, void 0, r);
const s = getAgentDeletionDatabaseCleanup(t)?.withCommit;
const c = r ? (e) => {
r.assertCurrent?.();
if (r.expectedIdentity) assertOpenClawAgentDatabaseIdentity(o, r.expectedIdentity);
if (s) s(e);
else e();
} : s;
const write = () => {
assertAgentDeletionDatabaseCleanupAccess(o, t);
assertAgentCreationClaimAccess(o, t);
return e(o);
};
if (i && !c && !isPostgresSqlConnection(o.db)) return runWithSqliteBusyTimeout(o.db, a.busyTimeoutMs ?? 5e3, () => runSqliteSingleStatementSync(o.db, write));
return withSqlitePostCommitPublications(o.db, () => runSqliteImmediateTransactionSync(o.db, write, {
busyTimeoutMs: a.busyTimeoutMs ?? 5e3,
databaseLabel: o.path,
...a,
operationLabel: a.operationLabel ?? "agent.write",
withCommit: c
}));
}
/** Released SDK guards may read SQLite; preserve their native open and integrity-resume checkpoints. */
function withOpenClawAgentDatabaseAsync(e, t, n, r) {
const run = () => runAgentDatabaseAsync(e, t, n, r, "native");
const i = getOpenClawDatabaseMaintenanceScope();
return i ? i.run(run) : run();
}
/** Runtime authority runs in worker grants: same-owner row predicates belong in the worker. */
function withOpenClawAgentDatabaseRuntime(e, t, n, r) {
const run = () => runAgentDatabaseAsync(e, t, n, r);
const i = getOpenClawDatabaseMaintenanceScope();
return i ? i.run(run) : run();
}
/** Core callers retain their original creating reference through native handle admission. */
function withOpenClawAgentDatabaseRuntimeFromExecution(e, t, n, r, i) {
const a = normalizeAgentId(e.agentId);
const o = resolveOpenClawAgentSqlitePath({
...e,
agentId: a
});
const assertExecutionCurrent = () => {
t.assertCurrent();
if (t.agentId !== a || t.path !== o) throw new Error("Agent runtime admission differs from its captured execution");
r?.();
};
const run = () => runAgentDatabaseAsync(e, n, assertExecutionCurrent, i, void 0, t);
const s = getOpenClawDatabaseMaintenanceScope();
return s ? s.run(run) : run();
}
async function runAgentDatabaseAsync(e, t, n, r, i, a) {
r?.throwIfAborted();
n?.();
const o = {
...e,
env: cloneEnvWithPlatformSemantics(e.env ?? process.env)
};
const s = normalizeAgentId(o.agentId);
const c = resolveOpenClawAgentSqlitePath({
...o,
agentId: s
});
assertAgentDatabaseWriteAllowed(c);
o.env.OPENCLAW_STATE_DIR = resolveStateDir(o.env);
o.path = c;
if (cache.terminal.peek(c)) await revalidateAgentDatabaseTerminalOpenAsync(c, n, r);
const l = cache.databases.get(c);
const u = getOpenClawAgentDatabaseValidationForTransfer({
agentId: s,
path: c
})?.schema;
if (!i && isMainThread && (!l?.db.isOpen || !u || Atomics.load(new Int32Array(u.valid), 0) !== 1) && !cache.pending.has(c)) return withWorkerAdmission(o, n, r, (e) => runAgentDatabaseAsync(o, t, n, r, e, a), a);
const d = cache.pending.get(c);
if (d?.agentId !== void 0 && d.agentId !== s) throw new Error(`Agent database ${c} is opening for ${d.agentId}`);
if (d?.controller.signal.aborted) return d.promise.then(() => runAgentDatabaseAsync(o, t, n, r, i, a), () => runAgentDatabaseAsync(o, t, n, r, i, a));
const f = d ?? startOpenClawAgentDatabaseAdmission(o, s, c, n, i === "worker");
f.operations += 1;
return racePromiseWithAbortSignal(f.promise, r).then((e) => {
r?.throwIfAborted();
assertAgentDatabaseOperationCurrent(e, o, f, n);
observeOpenClawDatabaseMaintenanceResource(e.db);
return t(e);
}).finally(() => {
f.operations -= 1;
if (!f.operations) {
if (!f.releaseBorrow) f.controller.abort(/* @__PURE__ */ new Error("Agent database admission has no waiting callers"));
f.releaseBorrow?.();
}
});
}
/** Run on a Worker to keep its same-connection integrity check outside the parent writer. */
function withOpenClawAgentDatabaseAdmission(e, t, n) {
const run = () => runAgentDatabaseAdmission(e, t, n);
const r = getOpenClawDatabaseMaintenanceScope();
return r ? r.run(() => r.track(run())) : run();
}
async function runAgentDatabaseAdmission(t, n, r) {
const i = {
...t,
env: cloneEnvWithPlatformSemantics(t.env ?? process.env)
};
const a = normalizeAgentId(i.agentId);
const o = resolveOpenClawAgentSqlitePath({
...i,
agentId: a
});
assertAgentDatabaseWriteAllowed(o);
if (cache.terminal.peek(o)) await revalidateAgentDatabaseTerminalOpenAsync(o);
const s = cache.pending.get(o);
if (s) {
if (s.agentId !== a) throw new Error(`Agent database ${o} is opening for ${s.agentId}`);
try {
await s.promise;
} catch (e) {
if (!s.controller.signal.aborted) throw e;
}
return withOpenClawAgentDatabaseAdmission(i, n, r);
}
const c = createOpenClawAgentDatabaseAdmission(a, o);
const { pending: l } = c;
l.promise.catch(() => {});
l.operations += 1;
const u = e(i, l);
let d;
let f;
let p = false;
try {
while (true) {
const e = await n(async (e, t, n) => {
p = false;
assertAgentDatabaseOpenAuthority(u, () => {
e();
assertOpenClawAgentDatabaseAdmissionCurrent(i, l);
});
l.validation = t;
l.integrityRevoked = n;
const a = f ? u.throw(f.error) : u.next();
if (!a.done) {
p = true;
return {
done: false,
check: a.value
};
}
l.releaseBorrow = retainAgentDatabase(a.value.db);
c.complete(a.value);
const assertOperationCurrent = () => assertAgentDatabaseOperationCurrent(a.value, i, l, e);
assertOperationCurrent();
const o = isMainThread || isPostgresSqlConnection(a.value.db) ? void 0 : registerDeferredSqliteWalWriteAdmission(a.value.db);
o?.(assertOperationCurrent);
const s = await r(a.value);
o?.(assertOperationCurrent);
return {
done: true,
result: s
};
});
if (e.done) return e.result;
d = e.check;
f = void 0;
try {
l.controller.signal.throwIfAborted();
runSqliteIntegrityCheckSync(d);
} catch (e) {
f = { error: e };
}
}
} catch (e) {
const t = [e];
if (p) {
const n = new Error(`Agent database admission failed: ${o}`, { cause: e });
try {
u.throw(n);
} catch (e) {
if (e !== n) t.push(e);
}
}
const n = t.length === 1 ? e : new AggregateError(t, "Agent database admission and cleanup failed", { cause: e });
c.fail(n);
throw n;
} finally {
l.operations -= 1;
if (!l.operations) l.releaseBorrow?.();
}
}
function createOpenClawAgentDatabaseAdmission(e, t) {
assertAgentDatabaseResourceAdmission({
agentId: e,
path: t
});
const n = createDeferredCore();
const r = {
agentId: e,
path: t,
controller: new AbortController(),
promise: n.promise,
operations: 0
};
cache.pending.set(t, r);
cache.activePending.add(r);
const retire = () => {
if (cache.pending.get(t) === r) cache.pending.delete(t);
cache.activePending.delete(r);
};
return {
pending: r,
complete: (e) => {
retire();
if (r.controller.signal.aborted || cache.databases.get(t) !== e || !e.db.isOpen) {
const e = r.controller.signal.reason ?? /* @__PURE__ */ new Error(`Agent database closed before admission completed: ${t}`);
n.reject(e);
throw e;
}
n.resolve(e);
},
fail: (e) => {
retire();
n.reject(e);
}
};
}
function assertOpenClawAgentDatabaseAdmissionCurrent(e, t) {
const n = t.path;
t.controller.signal.throwIfAborted();
assertAgentDatabaseAdmitted(t.agentId, { env: e.env });
if (cache.pending.get(n) !== t) throw new Error(`Agent database open was replaced: ${n}`);
assertAgentCreationClaimCurrent(e);
getAgentDeletionDatabaseCleanup(e)?.assertCurrent();
t.assertHeld?.();
}
function startOpenClawAgentDatabaseAdmission(t, n, r, i, a = false) {
const o = createOpenClawAgentDatabaseAdmission(n, r);
const { pending: s } = o;
s.workerPrepared = a;
const c = e(t, s);
(async () => {
assertAgentDatabaseOpenAuthority(c, i);
let e = c.next();
while (!e.done) {
let n;
let a = false;
try {
await assertSqliteIntegrityInWorker(r, OPENCLAW_SQLITE_BUSY_TIMEOUT_MS, s.controller.signal, void 0, e.value.timing, {
check: e.value.check,
tables: e.value.tables
});
} catch (e) {
n = e;
a = true;
}
assertAgentDatabaseOpenAuthority(c, () => {
assertOpenClawAgentDatabaseAdmissionCurrent(t, s);
i?.();
});
e = a ? c.throw(n) : c.next();
}
s.releaseBorrow = retainAgentDatabase(e.value.db);
return e.value;
})().then(o.complete, o.fail).catch(o.fail);
return s;
}
return {
openOpenClawAgentDatabase,
openOpenClawAgentDatabaseInWorker,
runOpenClawAgentWriteTransaction,
withOpenClawAgentDatabaseAsync,
withOpenClawAgentDatabaseRuntime,
withOpenClawAgentDatabaseRuntimeFromExecution,
withOpenClawAgentDatabaseAdmission
};
}
//#endregion
//#region src/state/openclaw-agent-db.wal.ts
/** Keep the published timer's exact native owner pinned through worker settlement. */
function registerOpenClawAgentWalMaintenance(e, t) {
if (isPostgresSqlConnection(e.db)) return;
const n = {
agentId: e.agentId,
path: e.path,
env: t
};
const r = readOpenClawAgentDatabaseIdentity(e);
const i = {
kind: "file",
physicalIdentity: r.identity,
birthtime: r.birthtime,
nativeLocation: r.filename
};
const a = new AbortController();
let o;
let s;
const cancel = () => {
a.abort();
};
const assertCurrent = () => {
a.signal.throwIfAborted();
if (cache.databases.get(e.path) !== e || !e.db.isOpen) throw new Error("Agent WAL maintenance owner changed");
};
registerSqliteWalWorkerMaintenance(e.db, async (t) => {
if (a.signal.aborted) return;
const r = retainAgentDatabase(e.db);
const c = runOpenClawAgentWorkerWrite(n, async () => {
assertCurrent();
s = registerOpenClawAgentDatabaseAsyncResource({
...n,
revoke: cancel,
async close() {
cancel();
await o?.catch(() => {});
}
});
const { captureOpenClawAgentDatabaseExecution: e } = await import("./openclaw-agent-execution-D8fPsYYC.mjs");
assertCurrent();
const r = e(n, { expectedIdentity: i });
try {
const e = await r.runExisting(createSessionWorkerExecutionSource(assertCurrent, "Agent WAL maintenance authority expired"), (e) => e.execute({
type: "database.walMaintenance",
input: t
}));
assertCurrent();
r.assertCurrent();
return e;
} finally {
await r.release();
}
}, void 0, a.signal);
o = c;
try {
return await c;
} finally {
r();
o = void 0;
s?.();
s = void 0;
}
}, cancel);
}
//#endregion
//#region src/state/openclaw-agent-db.ts
/**
* Clear a terminal open failure after doctor rewrites the database file.
* Returns false when the persisted quarantine row survived; callers must
* surface that, or the next open re-quarantines the repaired file.
*/
function clearOpenClawAgentDatabaseOpenFailure(e, t = {}) {
const n = path.resolve(e);
const r = clearOpenClawDatabaseQuarantine(n, { env: t.env });
cache.terminal.clear(n);
return r;
}
const { openOpenClawAgentDatabase, openOpenClawAgentDatabaseInWorker, runOpenClawAgentWriteTransaction, withOpenClawAgentDatabaseAsync, withOpenClawAgentDatabaseRuntime, withOpenClawAgentDatabaseRuntimeFromExecution, withOpenClawAgentDatabaseAdmission } = createOpenClawAgentDatabaseAdmissionOwner(openOpenClawAgentDatabaseSteps);
function* openOpenClawAgentDatabaseSteps(e, t, n, r, i) {
const a = agentEngineInput();
const o = a ? void 0 : i?.integrityCheck ?? getOpenClawDatabaseMaintenanceScope()?.sqliteIntegrityCheck;
if (a) assertEngineStoreExecutionAllowed();
const s = normalizeAgentId(e.agentId);
assertAgentDatabaseAdmitted(s, { env: e.env });
const c = {
...e,
agentId: s
};
const l = resolveOpenClawAgentSqlitePath(c);
const assertCurrent = (e) => {
i?.assertCurrent?.();
if (i?.expectedIdentity) {
if (e) assertOpenClawAgentDatabaseIdentity(e, i.expectedIdentity);
else assertExistingDatabaseIdentity(l, i.expectedIdentity.key, i.expectedIdentity.birthtime);
}
};
assertCurrent();
assertAgentCreationClaimCurrent(c);
getAgentDeletionDatabaseCleanup(c)?.assertCurrent();
const u = getOpenClawAgentDatabaseIfOpen(c);
if (u) {
assertCurrent(u);
if (n) throw new Error("A prepared Worker lease cannot adopt an existing agent database handle");
if (t?.workerPrepared) adoptOpenClawAgentDatabaseSchema(u, true, true);
return u;
}
assertAgentDatabaseResourceAdmission({
agentId: s,
path: l
});
if (!t) revokePendingAgentDatabaseOpen(l);
const d = cache.databases.get(l);
const f = !process.permission && supportsNodeSqliteExtensionLoading();
if (!i?.expectedIdentity) quarantineOrphanedSqliteSidecars(l);
revalidateAgentDatabaseTerminalOpen(l);
const p = readOpenClawDatabaseQuarantineFailure("agent", l, { env: c.env });
if (p) {
recordOpenClawAgentDatabaseOpenFailure(l, p);
throw p;
}
if (d) {
closeCachedOpenClawAgentDatabase(d);
cache.databases.delete(l);
cache.failures.delete(l);
}
const m = {
...e.env ?? process.env,
OPENCLAW_STATE_DIR: resolveStateDir(e.env ?? process.env),
...isGatewayExternallySupervised(e.env ?? process.env) ? { OPENCLAW_SUPERVISOR_MODE: "external" } : {}
};
if (n && (n.receipt.agentId !== s || n.receipt.path !== l)) throw new Error("Prepared agent database lease belongs to another store");
let h = false;
let g;
let _ = false;
let v = false;
const y = {};
const b = t?.validation ?? n?.validation;
const x = n?.integrityRevoked === true || t?.integrityRevoked === true || hasRevokedOpenClawAgentDatabaseValidation(l, b);
const S = n ? n.provenance : readAgentDatabaseLeaseProvenance(l);
const captureVerification = (e, r, i, a) => {
h = e;
g = a;
v = r && e && !x && i === void 0;
_ = r || n?.integrityRevoked === true || t?.integrityRevoked === true;
y.because = r ? i : void 0;
if (r && b) Atomics.store(new Int32Array(b.valid), 0, 0);
};
const C = {
env: m,
initializationAgentPaths: [l]
};
assertCurrent();
const w = n ? n.claim(captureVerification) : claimOpenClawAgentDatabaseLease({
agentId: s,
path: l,
env: m
}, void 0, captureVerification);
if (t) t.assertHeld = () => assertOpenClawAgentDatabaseLease(w, {
agentId: s,
path: l,
env: m
});
const T = startAgentDatabaseOpenTiming(s, l, t ? "async" : "sync", y);
let E;
let D;
let O;
let k;
try {
assertCurrent();
if (n && !isMainThread) try {
requestSqliteWorkerOperationAdmission({
stage: "prepare",
facts: {
kind: "agent-validation-start",
lease: n.receipt
}
});
} catch (e) {
throw new SqliteWorkerOpenRefusedError(e);
}
if (!i?.expectedIdentity) {
ensureOpenClawAgentDatabasePermissions(l, c);
prepareSqliteDatabaseDirectory(l);
}
closeIdleOpenClawAgentDatabaseReadOnly(l);
const u = openNodeSqliteDatabase(i?.expectedIdentity ? resolveExistingSqliteFileUri(l) : l, {
allowExtension: f,
timeout: a ? void 0 : OPENCLAW_SQLITE_BUSY_TIMEOUT_MS
});
E = u;
let d = u;
registerOpenClawAgentDatabaseIdentity(u, resolveOpenClawStateSqlitePath(m));
assertCurrent({
db: u,
path: l
});
if (i?.expectedIdentity) ensureOpenClawAgentDatabasePermissions(l, c);
u.enableLoadExtension(false);
enableNodeSqliteKyselyStatementCache(u);
if (n) u.exec("PRAGMA temp_store = FILE");
T("open");
const p = {
db: u,
path: l,
agentId: s
};
if (b && !a) adoptOpenClawAgentDatabaseValidation(p, b);
let x = Boolean(getOpenClawAgentDatabaseValidation(p));
const C = x || h || t?.workerPrepared === true && !_;
let A = false;
let j;
try {
if (a) {
if (t) k = reserveAgentCreationClaimAdmission(t, c, async () => {
await closeOpenClawAgentDatabaseByPathAsync(l, s);
});
d = openAgentEngineStore(u, s, l, false, (e, t) => {
d = E = e;
throw t;
});
E = d;
j = {
checkpoint: () => false,
stop: async () => {},
reclaimFreePages: createSqliteWalReclamationResult,
close: () => true
};
setOpenClawAgentDatabaseValidation({
db: d,
path: l,
agentId: s
});
x = true;
A = true;
} else {
A = adoptOpenClawAgentDatabaseSchema(p, C, t?.workerPrepared);
if (!A) admitSqliteSchema(u, (e) => {
assertSupportedAgentSchemaVersion(u, l, e);
});
const e = readExistingAgentSchemaMeta(u);
assertExistingAgentSchemaOwner(e, s, l);
if (A) assertCurrentAgentSchemaMetadata(e, s, l);
if (t) k = reserveAgentCreationClaimAdmission(t, c, async () => {
await closeOpenClawAgentDatabaseByPathAsync(l, s);
});
y.integrityGateReason = _ ? v && S !== null && readAgentDatabaseLeaseProvenance(l) === S ? "process-death" : "stale-lease-full" : hasRevokedOpenClawAgentDatabaseValidation(l, b) ? "revoked" : h ? readSqliteDatabaseCleanCloseRefusal(u) ?? "no-proof" : "lease-class";
y.because ??= y.integrityGateReason === "stale-lease-full" ? agentDatabaseAdmissionProvenanceRefusal(n?.provenance, l) : void 0;
let r;
if (y.integrityGateReason === "revoked" || y.integrityGateReason === "process-death" || y.integrityGateReason === "stale-lease-full") {
x = false;
A = false;
} else if (h) r = readSqliteDatabaseIntegrityVerification(u);
if (o !== "quick" && (o === "full" || ![
"process-death",
"lease-class",
"no-proof"
].includes(y.integrityGateReason))) recordOpenClawAgentDatabaseAdmission(w, {
agentId: s,
path: l,
env: m
}, "full-required");
const a = yield* agentDatabaseIntegrityBeforeMutationSteps(u, s, l, y, r, x && C || y.integrityGateReason === "lease-class" && g !== void 0 && readAgentDatabaseLeaseProvenance(l) === g, A, o, i?.integrityTables ?? []);
assertCurrent(p);
if (!y.integrityGateOutcome || y.integrityGateOutcome === "cached") delete y.integrityGateReason;
if (x && (!e || a)) {
invalidateOpenClawAgentDatabaseValidation(l);
x = false;
}
assertCanonicalAgentPersistenceVersion(u, l);
T("validation");
configureSqlitePreSchemaPragmas(u, { busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS });
j = configureSqliteConnectionPragmas(u, {
busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,
autoCheckpointPages: 0,
databaseLabel: `openclaw-agent:${s}`,
databasePath: l,
foreignKeys: true,
synchronous: "NORMAL"
});
O = j;
T("configuration");
assertCurrent(p);
if (!e || a || !x && readSqliteWriterAppVersion(u) !== VERSION) ensureAgentSchema(u, s, l, void 0, void 0, void 0, false, o);
T("schema");
d = openAgentEngineStore(u, s, l);
}
} catch (e) {
if (y.integrityGateOutcome === "failed") T("validation");
O?.close();
if (d.isOpen) d.close();
if (isPostgresSqlConnection(d) && u.isOpen) u.close();
const t = cache.databases.get(l);
if (!t || t.db === u) invalidateOpenClawAgentDatabaseValidation(l);
if (e instanceof Error && (isSqliteSchemaVersionError(e) || isTerminalSqliteIntegrityError(e))) recordOpenClawAgentDatabaseOpenFailure(l, e);
throw e;
}
assertCurrent({
db: d,
path: l
});
ensureOpenClawAgentDatabasePermissions(l, c);
if (!A) {
admitSqliteSchema(u);
assertCanonicalSessionValidationSchema(u);
}
const M = {
agentId: s,
db: d,
path: l,
walMaintenance: j
};
D = M;
if (hasAgentDatabaseMaintenanceAuthority()) throw new Error("Agent database maintenance is in progress; retry after openclaw doctor --fix completes.");
registerAgentDeletionDatabaseCleanup(M, c)?.registerClose(createAgentDatabaseScopeOwnedClose(M, "Agent deletion cleanup"));
registerAgentCreationClaimHandle(M, c)?.registerClose(createAgentDatabaseScopeOwnedClose(M, "Agent creation claim"));
if (!x || !hasRegisteredOpenClawAgentDatabasePath(M, { env: e.env })) {
assertCurrent(M);
registerOpenClawAgentDatabase({
agentId: s,
path: l,
env: e.env,
admittedDb: o === "quick" ? void 0 : d
}, r);
} else if (!A) publishOpenClawAgentDatabaseSchema(M);
cache.terminal.clear(l);
cache.unregisterExitClose ??= registerSqliteCacheExitClose(closeOpenClawAgentDatabases);
T("registration");
registerAgentDatabaseHandle(M, w, m);
assertCurrent(M);
recordOpenClawAgentDatabaseAdmission(w, {
agentId: s,
path: l,
env: m
});
refreshAgentDatabaseIdleTimer(M);
if (isMainThread) registerOpenClawAgentWalMaintenance(M, m);
getOpenClawDatabaseMaintenanceScope()?.own(M.db, "agent-handles", () => closeMaintenanceAgentDatabase(M));
k?.();
return M;
} catch (e) {
const r = n !== void 0 && !isMainThread && e instanceof SqliteWorkerOpenRefusedError;
let i;
if (D) try {
closeCachedOpenClawAgentDatabase(D);
} catch (e) {
i = e;
}
if (E && (E.isOpen || sqlPublicationAnchor(E).isOpen)) {
const n = cache.databases.get(l);
if (t && n && n.db !== E) {
const t = E;
retainFailedAgentDatabaseClose(s, l, () => {
O?.close();
if (t.isOpen) t.close();
const e = sqlPublicationAnchor(t);
if (isPostgresSqlConnection(t) && e.isOpen) e.close();
releaseOpenClawAgentDatabaseLease(w, C);
});
throw e;
}
invalidateOpenClawAgentDatabaseValidation(l);
const r = D ?? {
agentId: s,
db: E,
path: l,
walMaintenance: O ?? {
checkpoint: () => false,
stop: async () => {},
reclaimFreePages: createSqliteWalReclamationResult,
close: () => false
}
};
cache.databases.set(l, r);
refreshAgentDatabaseIdleTimer(r);
cache.leases.set(l, {
leaseId: w,
env: m
});
cache.failures.set(l, i ?? e);
getOpenClawDatabaseMaintenanceScope()?.own(r.db, "agent-handles", () => closeMaintenanceAgentDatabase(r));
cache.unregisterExitClose ??= registerSqliteCacheExitClose(closeOpenClawAgentDatabases);
} else if (!r) {
const t = e instanceof SqliteWorkerOpenRefusedError ? "read-only" : void 0;
try {
releaseOpenClawAgentDatabaseLease(w, C, t);
} catch (e) {
retainFailedAgentDatabaseClose(s, l, () => releaseOpenClawAgentDatabaseLease(w, C, t));
throw e;
}
}
throw i ?? e;
}
}
/** Retain the exact verified connection across awaits; explicit disposal still revokes it. */
function borrowOpenClawAgentDatabase(e) {
const { db: t } = openOpenClawAgentDatabase(e);
return {
db: t,
release: retainAgentDatabase(t)
};
}
function isOpenClawAgentDatabaseOpen(e) {
return cache.databases.get(path.resolve(e))?.db.isOpen === true;
}
/** Pin only admitted native readers already present in captured discovery families. */
function retainOpenClawAgentDatabaseReadCandidates(e, t) {
const n = [];
const release = () => {
for (const e of n.toReversed()) e.release();
};
try {
for (const r of cache.databases.values()) {
if (!r.db.isOpen || r.db.isTransaction || !e.some((e) => matchesAgentDatabaseReadCandidatePath(e, r.path))) continue;
let i;
try {
i = getOpenClawAgentDatabaseIfOpen({
agentId: r.agentId,
path: r.path,
env: t
});
} catch {
continue;
}
if (i === r) n.push({
database: r,
release: retainAgentDatabase(r.db)
});
}
return {
databases: n.map(({ database: e }) => e),
release
};
} catch (e) {
release();
throw e;
}
}
//#endregion
export { openOpenClawAgentDatabaseInWorker as a, withOpenClawAgentDatabaseAdmission as c, withOpenClawAgentDatabaseRuntimeFromExecution as d, openOpenClawAgentDatabase as i, withOpenClawAgentDatabaseAsync as l, clearOpenClawAgentDatabaseOpenFailure as n, retainOpenClawAgentDatabaseReadCandidates as o, isOpenClawAgentDatabaseOpen as r, runOpenClawAgentWriteTransaction as s, borrowOpenClawAgentDatabase as t, withOpenClawAgentDatabaseRuntime as u };