openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,266 lines (1,265 loc) • 47.7 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs";
import { i as recordWorkerMessage } from "./worker-message-metrics-d3pS8muz.mjs";
import { n as coerceErrorMessage } from "./error-coercion-hDrHOSGy.mjs";
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { d as sleepWithAbort, o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { n as notifyListeners } from "./listeners-Cb2-CnP8.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { a as isSameOpenClawAgentDatabasePath, c as resolveOpenClawAgentSqlitePath, r as isIncognitoOpenClawAgentSqlitePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs";
import { n as runtimeProcessEntrypoints } from "./runtime-process-entrypoints-qiyJvDDT.mjs";
import { a as resolveRuntimeWorkerUrl } from "./runtime-worker-url-DRDkoS4J.mjs";
import { a as getOpenClawDatabaseMaintenanceScope, d as observeOpenClawDatabaseMaintenanceResource, p as runOutsideOpenClawDatabaseMaintenanceScope, s as isOpenClawDatabaseMaintenanceWorkerAccess } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import { i as assertExistingDatabaseIdentity, m as readDatabasePathIdentitySync, p as readDatabasePathIdentity, t as assertDatabaseFileIdentity } from "./sqlite-worker-identity-BH8ZkJU9.mjs";
import { o as isSqliteLockError } from "./sqlite-error-diagnostics-6_hREUnq.mjs";
import { a as retainSqliteWorkerErrorCode, i as isSqliteWorkerError, t as SqliteWorkerError } from "./sqlite-worker-error-DEIJgRIz.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { u as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-D8BU4VLa.mjs";
import { f as publishSqliteWalCheckpointObservation } from "./sqlite-wal-DGPrWPl6.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { M as parseGatewayLockPayload, d as resolveGatewayStateOwnerPath, o as captureGatewayStateOwnerAsync } from "./gateway-state-owner-Bnv5owvG.mjs";
import { l as resolveSqliteInspectionSignal } from "./sqlite-readonly-worker-D3pRJU7r.mjs";
import { d as AgentDatabaseExecutionAdmissionClosedError, f as AgentDatabaseSchemaAdmissionChangedError, g as assertAgentCreationClaimAliases, n as drainAgentDatabaseResources, o as registerOpenClawAgentDatabaseAsyncResource, v as captureAgentCreationClaim } from "./openclaw-agent-db-resources-Dp8HvLsg.mjs";
import { c as registerAgentDeletionExecutionCleanup, o as getAgentDeletionDatabaseCleanup, r as assertAgentDeletionExecutionCleanupAccess, t as assertAgentDeletionCleanupAliases } from "./agent-deletion-cleanup-BweMIhGD.mjs";
import "./sqlite-worker-contract--dxXkOty.mjs";
import { r as AgentDatabaseExecutionLifetime } from "./sqlite-worker-request-custody-ZC2aFr6n.mjs";
import { i as createSqliteWorkerOperationAdmission, n as bindSqliteWorkerExecutionAuthority } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs";
import { _ as publishOpenClawStateDatabaseWorkerAdmission, b as registerOpenClawStateDatabaseAsyncResource } from "./openclaw-state-db-cache-CkwtTqzF.mjs";
import { n as resolveAgentDatabaseIdleHandleTtlMs } from "./sqlite-handle-lifecycle-Dw0xPd8_.mjs";
import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs";
import { r as captureOpenClawStateWorkerContext, t as captureOpenClawStateReadContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { a as isSqliteWorkerStoreAvailable, d as runSqliteWorkerStoreOperation, o as openAgentDatabaseSqliteWorkerStore, t as closeUnclaimedSharedStateSqliteWorkers } from "./sqlite-worker-store-D51tD0Vp.mjs";
import { r as openOpenClawStateWorkerCleanupStore } from "./openclaw-state-worker-store-2LoAv_8B.mjs";
import { a as readOpenClawAgentDatabaseIdentity, i as isOpenClawAgentDatabasePathCurrent } from "./openclaw-agent-db-identity-C8MGU8lp.mjs";
import { t as LEASE_CONTENTION_RETRY_TIMEOUT_MS } from "./openclaw-state-lease-heartbeat-shared-BhW_9slj.mjs";
import { c as getGatewayShutdownCleanupSignal } from "./gateway-work-admission-79pid1hQ.mjs";
import { D as retainAgentDatabaseStartupWorker, T as recordAgentDatabaseStartupFtsRepair, a as captureAgentDatabaseAdmission, g as isAgentDatabaseStartupReadReady, s as captureAgentDatabasePreparationJournal } from "./agent-database-admission-CL6wHJ_N.mjs";
import { h as settleAgentRegistration, t as captureOpenClawAgentDatabaseRegistration } from "./openclaw-agent-db-registry-listing-CbXBL50a.mjs";
import { c as hasAgentDatabaseMaintenanceAuthority } from "./openclaw-agent-db-lease-BZhGt_sk.mjs";
import { d as hasRevokedOpenClawAgentDatabaseValidation, l as getOpenClawAgentDatabaseValidationForTransfer, m as invalidateOpenClawAgentDatabaseValidation, r as captureOpenClawAgentDatabaseAdmissionPublication, v as retireReplacedAgentValidation } from "./openclaw-agent-db-validation-cache-lnjWuypr.mjs";
import { t as cache } from "./openclaw-agent-db-lifecycle-DqaZZnYh.mjs";
import { i as runOpenClawAgentWorkerWrite, t as createSessionWorkerExecutionSource } from "./session-worker-execution-source-H3bdawqM.mjs";
import "./backoff-B-fIQi7C.mjs";
import { r as assertAgentSessionWriteAdmission } from "./session-agent-work-admission-DwGkLOZq.mjs";
import { n as createSharedAgentDatabasePreparation } from "./openclaw-agent-execution-preparation-BZ-eTVD7.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { readFile, stat } from "node:fs/promises";
import { MessagePort } from "node:worker_threads";
import { AsyncLocalStorage } from "node:async_hooks";
import { isDeepStrictEqual } from "node:util";
import { addAbortListener } from "node:events";
//#region src/state/agent-deletion-cleanup-admission.ts
/** Bind the request's cleanup owner, including accepted native work, before transferring a grant. */
function captureAgentDeletionCleanupAdmission(e, t, n) {
const r = getAgentDeletionDatabaseCleanup(e);
if (!r?.worker) return;
const i = r.worker;
r.assertCurrentHost();
return {
guard: i.guard,
assertCurrent: r.assertCurrentHost,
authorize(e) {
const a = e.facts;
if (e.stage !== "prepare" || !isRecord(a) || a.kind !== "agent-deletion-current" && a.kind !== "agent-deletion-lease") return false;
n();
r.assertCurrentHost();
if (!isDeepStrictEqual(a.guard, i.guard)) throw new Error("Agent deletion request differs from its live cleanup owner");
if (a.kind === "agent-deletion-lease") {
if (!(a.port instanceof MessagePort)) throw new Error("Agent deletion lost its lease admission handoff port");
const e = i.lease.createAdmission(t);
try {
a.port.postMessage(e.admission.port, [e.admission.port]);
recordWorkerMessage("admission", "to_worker");
t.settled.then(() => e.admission.finish());
} catch (t) {
e.admission.finish();
throw t;
} finally {
a.port.close();
}
}
return true;
}
};
}
//#endregion
//#region src/state/openclaw-agent-execution-cleanup.ts
/** Release only this owner's prepared lease after the broker certifies native retirement. */
async function cleanupRetiredAgentDatabaseLease(e) {
e.assertOwned();
await e.stopped;
e.assertOwned();
const t = e.readOpenRefused?.() === true;
if (e.closed?.()) return;
const n = await readDatabasePathIdentity(e.lease.sharedStatePath);
if (n.key !== e.lease.sharedStateIdentity) throw new Error("Retired agent cleanup cannot adopt a replacement shared database");
e.assertOwned();
if (!t) invalidateOpenClawAgentDatabaseValidation(e.lease.path);
const r = {
environment: e.context.environment,
existingSchemaPath: e.context.existingSchemaPath,
stateIntegrity: e.context.stateIntegrity
};
const i = await openOpenClawStateWorkerCleanupStore(e.lease.sharedStatePath, r, () => e.assertOwned(), n, e.context.maintenanceScope).catch((t) => {
if (t instanceof Error) {
t.message += ` (leaseId=${e.lease.leaseId}, path=${e.lease.path})`;
t.stack = `${t.name}: ${t.message}\n${t.stack ?? ""}`;
}
throw t;
});
if (!i) throw new Error("Retired agent cleanup lost its original shared database");
const a = [];
try {
await runSqliteWorkerStoreOperation(i, (n) => n.execute({
type: "agentDatabases.releaseExitedLease",
input: {
...e.lease,
outcome: t ? "refused-before-open" : "unknown"
}
}), r, () => e.assertOwned(), () => ({
nativeLocations: [e.lease.sharedStatePath],
admission: createSqliteWorkerOperationAdmission((t, n) => {
e.assertOwned();
if (t.stage === "prepare" && t.facts === "agent-integrity-invalidated") invalidateOpenClawAgentDatabaseValidation(e.lease.path);
n();
})
}));
} catch (e) {
a.push(e);
}
try {
await i.close();
} catch (e) {
a.push(e);
}
throwSqliteLifecycleErrors(a, "Retired agent lease cleanup and Worker close failed");
}
/** Native closure is reusable only for the exact incarnation and original worker lease. */
function readAgentDatabaseClosedReceipt(e, t, n) {
if (!e || !t || !n || e.incarnation !== t.incarnation || e.identity.key !== `file:${t.physicalIdentity}` || e.identity.canonicalPath !== t.nativeLocation) return;
return {
receipt: e,
identity: t,
lease: n
};
}
async function publishAgentDatabaseCloseCheckpoint(e, t, n) {
const r = t?.receipt.checkpoint;
if (!t || !r) return;
const { receipt: i, identity: a, lease: o } = t;
try {
n();
const [t, s, c] = await Promise.all([
stat(e, { bigint: true }),
stat(a.nativeLocation, { bigint: true }),
stat(o.sharedStatePath, { bigint: true })
]);
assertDatabaseFileIdentity(t, { key: i.identity.key });
assertDatabaseFileIdentity(s, { key: i.identity.key });
assertDatabaseFileIdentity(c, { key: o.sharedStateIdentity });
n();
publishSqliteWalCheckpointObservation(e, r);
} catch {}
}
/** Join native disposal before deciding whether the original lease can still be settled. */
async function closeAgentDatabaseNativeGeneration(e) {
const { pathname: t, context: n, processOwner: r, opening: i, readOpenedStore: a, assertCleanupOwned: o } = e;
const s = [];
try {
(await r?.prepareAccess())?.();
} catch (e) {
if (r?.signal.aborted) s.push(e);
}
let c = false;
if (i) try {
await i.then(async (e) => {
await e?.close();
c = e !== void 0;
}, () => a()?.close() ?? closeUnclaimedSharedStateSqliteWorkers(t));
} catch (e) {
s.push(e);
}
const l = e.readRetirement();
if (s.length === 0 && !r?.signal.aborted && l.stopped && l.lease) try {
await cleanupRetiredAgentDatabaseLease({
context: n,
stopped: l.stopped,
assertOwned: o,
lease: l.lease,
readOpenRefused: l.readOpenRefused,
closed: () => c ? l.closed : void 0
});
} catch (e) {
s.push(e);
}
if (r?.signal.aborted && l.stopped) {
await finishAgentDatabaseRetirementAfterOwnershipLoss(t, n.admission.databasePath, l.stopped, s);
return;
}
throwSqliteLifecycleErrors(s, "Agent native close and lease cleanup failed");
await publishAgentDatabaseCloseCheckpoint(t, l.closed, o);
}
/** Lost write authority cannot prevent disposal or authorize another lease cleanup write. */
async function finishAgentDatabaseRetirementAfterOwnershipLoss(e, t, n, r) {
await n;
invalidateOpenClawAgentDatabaseValidation(e);
const i = resolveGatewayStateOwnerPath(t);
const a = await readFile(i, "utf8").then((e) => {
const t = parseGatewayLockPayload(e);
return t ? {
pid: t.pid,
role: t.role
} : "unrecognized lock contents";
}, (e) => hasErrnoCode(e, "ENOENT") ? "lock removed" : "lock unreadable");
createSubsystemLogger("state/agent-db").warn("Agent database native handle retired after state ownership loss; lease cleanup deferred to recovery", {
path: e,
lockPath: i,
replacement: a,
errors: r.map((e) => coerceErrorMessage(e))
});
}
//#endregion
//#region src/state/openclaw-agent-execution-native.ts
/** A logical execution owner can replace this generation only after its native close settles. */
function createAgentDatabaseNativeGeneration(e, t, n, r, i, a, o, s, c, l, u, d, f = false, p) {
const m = AsyncLocalStorage.snapshot();
const h = f ? resolveSqliteInspectionSignal() : void 0;
const g = h ? new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)) : void 0;
const cancelStartup = () => {
if (g) {
Atomics.store(g, 0, 1);
Atomics.notify(g, 0);
}
};
const _ = h && addAbortListener(h, cancelStartup);
const v = {
leaseId: randomUUID(),
agentId: e,
databasePath: t,
stateDatabasePath: n.admission.databasePath,
environment: n.environment,
...s ? { expectedIdentity: s } : {},
...u ? { creatingIdentity: u } : {},
...d ? { creationClaim: d } : {}
};
const y = new AgentDatabaseExecutionLifetime();
let b;
let x;
let S;
let C;
let w;
let T;
let E;
let D;
let O;
let k;
let A;
let j = false;
let M;
const N = createSharedAgentDatabasePreparation(() => assertCurrent());
const onNativeLost = (e) => {
M ??= e;
y.retire();
if (A) invalidateOpenClawAgentDatabaseValidation(t);
if (j) l(e);
};
const assertCurrent = () => {
a();
if (x && !isSqliteWorkerStoreAvailable(x)) throw M ?? new SqliteWorkerError("Database unavailable. Check history, then retry.", "unavailable");
if (!y.open) throw new Error("Agent native generation is retiring");
};
const admission = (r, a, o) => (l) => {
let d = a ? captureOpenClawAgentDatabaseAdmissionPublication({
agentId: e,
path: t
}) : void 0;
if (a) a.nativeSettlement = l.settled;
const f = captureAgentDatabasePreparationJournal(e, { env: n.environment });
const p = [
t,
...E ? [E.nativeLocation] : [],
n.admission.databasePath,
n.admission.identity.canonicalPath
];
const assertSourceCurrent = (e) => {
r.assertCurrent();
assertCurrent();
o?.(e);
};
const m = captureAgentDeletionCleanupAdmission({
agentId: e,
path: t,
env: n.environment
}, l, assertSourceCurrent);
const observeNative = (e) => {
const n = e.facts;
if (e.stage === "prepare" && isRecord(n) && n.kind === "agent-registration-committed") {
const e = n.registration;
if (!a || !A || !isRecord(e)) throw new Error("Agent registration commit differs from its admitted native owner");
a.recordCommitted({
agentId: v.agentId,
agentPath: t,
stateDatabasePath: A.sharedStatePath,
stateDatabaseIdentity: A.sharedStateIdentity
});
}
};
const authorizeNative = (r) => {
const i = r.facts;
if (m?.authorize(r)) return;
assertCurrent();
m?.assertCurrent();
if (r.stage === "prepare" && isRecord(i) && i.kind === "agent-startup-fts") {
assertSourceCurrent();
if (!f || !A || i.message !== void 0 && typeof i.message !== "string") throw new Error("FTS repair requires live Gateway startup admission");
recordAgentDatabaseStartupFtsRepair([s?.physicalIdentity ?? t, s?.birthtime].join(":"), n.admission.databasePath, i.message);
return;
}
if (!E || u) o?.();
if (r.stage === "prepare" && isRecord(i) && i.kind === "agent-registration-start") {
assertSourceCurrent();
if (!a || !A) throw new Error("Agent registration start differs from its admitted native owner");
a.begin();
return;
}
if (r.stage === "prepare" && isRecord(i) && i.kind === "shared-owner") {
if (!(i.validationPort instanceof MessagePort)) throw new Error("Agent worker lost its validation handoff port");
try {
assertSourceCurrent();
publishOpenClawStateDatabaseWorkerAdmission(n.admission);
const r = i.lease;
if (!isRecord(r) || r.ownerStartTime !== null && typeof r.ownerStartTime !== "number") throw new Error("Agent worker lease differs from its captured native owner");
A = {
leaseId: v.leaseId,
agentId: v.agentId,
path: t,
ownerPid: process.pid,
ownerStartTime: r.ownerStartTime,
sharedStatePath: n.admission.databasePath,
sharedStateIdentity: n.admission.identity.key
};
d = captureOpenClawAgentDatabaseAdmissionPublication({
agentId: e,
path: t
});
const a = {
integrityRevoked: hasRevokedOpenClawAgentDatabaseValidation(t),
validation: getOpenClawAgentDatabaseValidationForTransfer({
agentId: e,
path: t
})
};
i.validationPort.postMessage(a, []);
recordWorkerMessage("admission", "to_worker");
} finally {
i.validationPort.close();
}
return;
}
if (r.stage === "prepare" && isRecord(i) && (i.kind === "agent-open-resume" || i.kind === "agent-validation-start")) {
assertSourceCurrent();
if (!A) throw new Error("Agent open notice differs from its captured native lease");
if (i.kind === "agent-validation-start") d = captureOpenClawAgentDatabaseAdmissionPublication({
agentId: e,
path: t
});
return;
}
if (r.stage !== "open") {
const e = isRecord(i) ? i.identity : void 0;
if (!isRecord(e) || e.kind !== "file" || typeof e.physicalIdentity !== "string" || typeof e.birthtime !== "string" || typeof e.incarnation !== "string" || typeof e.nativeLocation !== "string" || E && !isDeepStrictEqual(e, E)) throw new Error("Agent database operation belongs to another native owner");
const n = E ?? Object.freeze({
kind: "file",
physicalIdentity: e.physicalIdentity,
birthtime: e.birthtime,
incarnation: e.incarnation,
nativeLocation: e.nativeLocation
});
if (s && (n.physicalIdentity !== s.physicalIdentity || s.birthtime !== void 0 && n.birthtime !== s.birthtime)) throw new Error("Agent database operation differs from its expected physical file");
if (!E) assertExistingDatabaseIdentity(t, `file:${n.physicalIdentity}`, n.birthtime);
c({
kind: "file",
physicalIdentity: n.physicalIdentity,
birthtime: n.birthtime,
nativeLocation: n.nativeLocation
});
f?.(isRecord(i) ? i.agentDeletionJournalPresent : void 0);
E ??= n;
return E;
}
};
const h = r.createAdmission({
attachment: {
kind: "agent-execution",
startupJournal: f !== void 0,
...g ? { startupCancellation: g } : {},
...m ? { deletion: m.guard } : {}
},
nativeLocations: p,
assertCurrent,
authorize(n) {
if (n.stage === "prepare" && isRecord(n.facts) && n.facts.kind === "agent-registration-committed") return;
const r = authorizeNative(n);
if (n.stage === "open" && a) {
assertSourceCurrent();
if (!E && !s && readDatabasePathIdentitySync(t).key.startsWith("path:")) {
if (!A && getOpenClawAgentDatabaseValidationForTransfer({
agentId: e,
path: t
})) invalidateOpenClawAgentDatabaseValidation(t);
a.begin();
}
}
if (n.stage === "prepare" && r && d && isRecord(n.facts) && n.facts.validation !== void 0) {
assertSourceCurrent(r);
d(r.physicalIdentity, n.facts.validation);
d = void 0;
}
assertSourceCurrent(r);
}
})(l);
if (j && E && !u && !a) bindSqliteWorkerExecutionAuthority(h.admission, {
logical: i,
native: y.state,
physicalIdentity: E.physicalIdentity,
incarnation: E.incarnation,
...E.birthtime !== void 0 ? { birthtime: E.birthtime } : {}
});
h.admission.observeRequests(observeNative);
return h;
};
const captureOpeningAdmission = (...e) => (t) => {
const n = admission(...e)(t);
w = {
admission: n.admission,
settled: t.settled
};
return n;
};
const captureRegistration = (r) => {
const i = E ?? s;
return captureOpenClawAgentDatabaseRegistration({
agentId: e,
agentPath: t,
capturedIdentity: i ? {
key: `file:${i.physicalIdentity}`,
canonicalPath: i.nativeLocation,
birthtime: i.birthtime
} : u ?? p,
admission: n.admission,
assertPublicationCurrent: n.assertPublicationCurrent,
onRegistryChange: r.onRegistryChange
});
};
const open = (r, i, a = false, o) => {
assertCurrent();
r.assertCurrent();
i?.();
if (!b) {
const c = N.retain();
const l = N.beginNativeOpen();
b = (async () => {
const c = s !== void 0;
retireReplacedAgentValidation(e, t, s);
const u = a || c ? captureRegistration(c ? N.source : r) : void 0;
const openStore = async () => {
const assertOpening = () => {
assertCurrent();
r.assertCurrent();
i?.();
o?.throwIfAborted();
};
x = await openAgentDatabaseSqliteWorkerStore({
moduleUrl: resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.agentDatabaseExecution),
databasePath: t,
input: v,
existingOnly: c || !a
}, {
startupPreparation: f,
stateContext: n,
stateDatabasePath: n.admission.databasePath,
assertCurrent: c ? assertCurrent : assertOpening,
signal: c ? void 0 : o,
createAdmission: captureOpeningAdmission(c ? N.source : r, u, c ? void 0 : i),
onNativeStopped: (e, t, n) => {
D = e;
O = t;
k = n;
},
onNativeLost
});
const e = x;
l();
if (e && c && !E) await m(() => runSqliteWorkerStoreOperation(e, (e) => e.execute({
type: "database.prepareWrite",
input: void 0
}), void 0, assertCurrent, captureOpeningAdmission(N.source, u)));
return x;
};
const d = u ? await settleAgentRegistration(u, openStore) : await openStore();
if (!d) return;
try {
assertCurrent();
j ||= E !== void 0;
return d;
} catch (e) {
try {
await d.close();
} catch (t) {
throw new AggregateError([e, t], "Agent open and cleanup failed", { cause: t });
}
if (e instanceof AgentDatabaseExecutionAdmissionClosedError) C = e;
throw e;
}
})().catch(async (e) => {
S = e instanceof AgentDatabaseSchemaAdmissionChangedError || C !== void 0 && e === C ? "open-refused" : "native";
if (w) {
const { admission: t, settled: n } = w;
const r = await n;
if (t.failure !== void 0 && t.failureSource !== "protocol" && e === t.failure && r.kind !== "unknown" && !t.committed && t.cleanupFailures.length === 0) S = "open-refused";
}
throw e;
}).finally(() => {
w = void 0;
C = void 0;
l();
c();
});
}
const c = b;
return c.then((e) => {
if (!e && b === c) b = void 0;
if (!e && a && !s) return open(r, i, true, o);
return e;
});
};
async function run(n, r, i, a = false, o) {
const assertOperationCurrent = () => {
assertCurrent();
n.assertCurrent();
i?.();
o?.throwIfAborted();
};
const c = j ? void 0 : N.retain();
const l = c ? N.follow(n, assertOperationCurrent) : void 0;
let u;
try {
const r = j ? x : await racePromiseWithAbortSignal(open(n, i, a, o), o, (e) => e.reason);
l?.assertPublished();
assertOperationCurrent();
if (!r) {
if (a && s) throw new Error("Captured agent database file disappeared before writable preparation");
return;
}
const c = a ? getOpenClawAgentDatabaseValidationForTransfer({
agentId: e,
path: t
})?.schema : void 0;
if (!E || a && j && (!c || Atomics.load(new Int32Array(c.valid), 0) !== 1)) {
const e = captureRegistration(n);
await settleAgentRegistration(e, async () => {
await runSqliteWorkerStoreOperation(r, (e) => e.execute({
type: "database.prepareWrite",
input: void 0
}, { signal: o }), void 0, assertOperationCurrent, admission(n, e, i));
assertCurrent();
n.assertCurrent();
});
j = true;
}
u = r;
} finally {
l?.release();
c?.();
}
return runSqliteWorkerStoreOperation(u, r, void 0, assertOperationCurrent, admission(n, void 0, i));
}
return {
failure: () => S ?? (x && !isSqliteWorkerStoreAvailable(x) ? j ? "lost" : "native" : void 0),
isPrepared() {
assertCurrent();
return j;
},
getPendingNativeOpen: N.getPendingNativeOpen,
getPendingPreparation: N.getPendingPreparation,
captureClaim(e) {
assertCurrent();
const t = E;
if (!t) throw new Error("Agent database generation has not been admitted");
return {
identity: t.physicalIdentity,
incarnation: t.incarnation,
assertCurrent() {
e();
assertCurrent();
}
};
},
run,
close() {
y.retire();
cancelStartup();
_?.[Symbol.dispose]();
T ??= closeAgentDatabaseNativeGeneration({
pathname: t,
context: n,
processOwner: r,
opening: b,
readOpenedStore: () => x,
assertCleanupOwned: o,
readRetirement: () => ({
stopped: D,
lease: A,
readOpenRefused: k,
closed: readAgentDatabaseClosedReceipt(O?.(), E, A)
})
}).catch((e) => {
T = void 0;
throw e;
});
return T;
}
};
}
//#endregion
//#region src/state/openclaw-agent-execution-scope.ts
function toAgentExecutionConstraints(e) {
return e.key.startsWith("file:") ? { expectedIdentity: {
kind: "file",
physicalIdentity: e.key.slice(5),
nativeLocation: e.canonicalPath,
birthtime: e.birthtime
} } : { expectedCreationIdentity: e };
}
function assertAgentDatabaseExecutionSharedState(e, t) {
const n = process.platform === "win32" ? cloneEnvWithPlatformSemantics(e.env ?? process.env) : e.env;
if (t !== captureOpenClawStateReadContext(resolveOpenClawStateSqlitePath(n)).admission.identity.key) throw new Error("Agent database execution belongs to another shared-state database; drain its existing resources before changing the state directory.");
}
function supportsAgentDatabaseExecutionScope(e) {
const t = getAgentDeletionDatabaseCleanup(e);
return (isOpenClawDatabaseMaintenanceWorkerAccess() || getOpenClawDatabaseMaintenanceScope()?.ownsSchemaMaintenance !== true && !hasAgentDatabaseMaintenanceAuthority()) && (!t || t.worker !== void 0);
}
/** Memory sessions have no database; maintenance scopes retain their local durable owner. */
function supportsOpenClawAgentDatabaseExecution(e) {
return !isIncognitoOpenClawAgentSqlitePath(resolveOpenClawAgentSqlitePath(e), e) && supportsAgentDatabaseExecutionScope(e);
}
/** Bind native handoff to the admitted connection and recheck it after cleanup waits. */
function captureNativeAgentDatabaseExecutionIdentity(e, t, n, r) {
r();
const i = readOpenClawAgentDatabaseIdentity(e);
const assertCurrent = () => {
r();
if (e.agentId !== t || cache.databases.get(e.path) !== e || readOpenClawAgentDatabaseIdentity(e) !== i || i.canonicalPath !== n || !isOpenClawAgentDatabasePathCurrent(e)) throw new Error("Agent execution cannot adopt a different native database owner");
};
assertCurrent();
return {
fileIdentity: {
kind: "file",
physicalIdentity: i.identity,
birthtime: i.birthtime,
nativeLocation: i.canonicalPath
},
assertCurrent
};
}
function assertAgentDatabaseExecutionCreationIdentity(e, t, n, r) {
const i = t.key.startsWith("path:");
if (r || i && (cache.databases.has(e) || cache.pending.has(e)) || !i && (!t.key.startsWith("file:") || typeof t.birthtime !== "string") || n?.key !== t.key || n.canonicalPath !== t.canonicalPath || n.birthtime !== t.birthtime) throw new Error("Agent creation no longer owns its originally observed target");
}
/** Keep the borrower's captured file constraints bound to its native owner. */
function assertBorrowedAgentDatabaseFileIdentity({ borrowedPath: e, identity: t, creatingTarget: n, fileIdentity: r, expectedIdentity: i, nativeIdentity: a, observedIdentity: o }) {
if (!r) {
const r = o ?? readDatabasePathIdentitySync(e);
if (r.canonicalPath !== t.canonicalPath || n?.key.startsWith("file:") && (r.key !== n.key || r.birthtime !== n.birthtime)) throw new Error("Agent database borrower changed its originally observed target");
}
if (r && i && (r.physicalIdentity !== i.physicalIdentity || r.birthtime !== void 0 && i.birthtime !== void 0 && r.birthtime !== i.birthtime)) throw new Error("Agent database borrower belongs to another physical file");
const s = r ?? i;
const c = r?.birthtime ?? i?.birthtime;
if (s) {
if (a && (a.physicalIdentity !== s.physicalIdentity || c !== void 0 && a.birthtime !== c)) throw new Error("Agent database borrower belongs to another physical file");
}
}
/** Compare a prepared observation with custody; sync callers retain their immediate path check. */
function assertAgentDatabaseBorrowTarget(e, t, n) {
if (!t) return;
if (!n) assertExistingDatabaseIdentity(e, "file:" + t.physicalIdentity, t.birthtime);
else if (n.key !== "file:" + t.physicalIdentity || t.birthtime !== void 0 && n.birthtime !== t.birthtime) throw new Error("Agent database borrower belongs to another physical file");
}
//#endregion
//#region src/state/openclaw-agent-execution-work.ts
/** The executor keeps accepted work until its borrower or resource close joins settlement. */
function createAgentDatabaseAcceptedWork() {
const e = /* @__PURE__ */ new Map();
const t = /* @__PURE__ */ new Set();
return {
pending: e,
onTerminal: (e) => {
t.add(e);
return () => t.delete(e);
},
reportTerminal: (n) => {
if (t.size === 0) return;
const r = n instanceof Error ? n : new Error(formatErrorMessage(n));
const i = [...t];
t.clear();
Promise.resolve().then(async () => {
await Promise.allSettled(e.keys());
notifyListeners(i, r);
});
},
settleBorrower: (t) => Promise.allSettled([...e].flatMap(([e, n]) => n.borrower === t ? [e] : [])),
cancelReadAdmissions: (t) => {
for (const n of e.values()) if (t === void 0 || n.borrower === t) n.queuedReadAbort?.abort(new AgentDatabaseExecutionAdmissionClosedError("Agent database read admission is closed"));
},
closeAccepted: async (t) => {
const n = [...e].flatMap(([e, t]) => t.queuedReadAbort ? [e] : []);
const r = t();
await Promise.allSettled([r, ...n]);
await r;
}
};
}
//#endregion
//#region src/state/openclaw-agent-execution-owner.ts
const log = createSubsystemLogger("state/agent-db");
const MAX_IDLE_EXECUTORS = 4;
function createAgentDatabaseExecution(e, t, n) {
const r = n.owners;
const { agentId: i, pathname: a, identity: o, initialIdentity: s, expectedCreationIdentity: c } = t;
const l = captureOpenClawStateWorkerContext({ env: e.env });
const u = {
agentId: i,
path: a,
env: l.environment
};
const d = getAgentDeletionDatabaseCleanup(u);
const f = d?.ownsDatabase ? d : void 0;
const p = captureAgentCreationClaim(e);
const m = /* @__PURE__ */ new Map();
const h = captureAgentDatabaseAdmission(i, { env: l.environment });
const g = new AgentDatabaseExecutionLifetime();
let _ = 0;
const v = createAgentDatabaseAcceptedWork();
let y = c;
let b = 0;
let x;
let S;
let C;
let w;
let T;
let E;
let D;
const acceptFileIdentity = (e) => {
if (S && (S.physicalIdentity !== e.physicalIdentity || S.birthtime !== e.birthtime)) throw new Error("Agent database execution belongs to another physical file");
S ??= Object.freeze({ ...e });
};
const clearIdleTimer = () => {
clearTimeout(D);
D = void 0;
};
const reportCleanupFailure = (e) => {
try {
log.warn(`Agent database cleanup failed: ${formatErrorMessage(e)}`);
} catch {}
};
const finishRetirement = () => {
g.retire();
if (r.get(a) !== O) return;
unregisterAgent();
E?.();
};
const assertCurrent = () => {
if (!g.open || r.get(a) !== O || !supportsAgentDatabaseExecutionScope(u)) throw new AgentDatabaseExecutionAdmissionClosedError("Agent database execution admission is closed");
assertAgentDeletionExecutionCleanupAccess(O, u);
l.admission.assertCurrent();
h();
p?.assertCurrent();
};
const closeNative = (e) => {
if (e && x !== e) return Promise.resolve();
clearIdleTimer();
if (C) return C;
const t = x;
if (!t) return Promise.resolve();
const r = t.close().then(() => {
if (x === t) {
x = void 0;
w = void 0;
n.idle.delete(O);
}
}, (e) => {
materializeErrorStack(e);
w = { error: e };
throw e;
}).finally(() => {
if (C === r) C = void 0;
});
C = r;
return r;
};
function createGeneration(e, t, n) {
const s = createAgentDatabaseNativeGeneration(i, o.canonicalPath, l, e, g.state, assertCurrent, () => {
if (r.get(a) !== O || x !== s || !C) throw new Error("Agent cleanup no longer owns its original execution reference");
}, t ?? S ?? toAgentExecutionConstraints(o).expectedIdentity, acceptFileIdentity, v.reportTerminal, S ? void 0 : y ?? n, p?.witness, retainAgentDatabaseStartupWorker(i, { env: l.environment }, () => closeNative(s)), o);
return s;
}
async function run(e, t, n, r, o = false, s = false, c, u, d) {
const f = cache.pending.get(a);
if (f) {
if (c && !S) throw new Error("Agent creation cannot adopt another pending opener");
if (f.agentId !== i) throw new Error(`Agent database ${a} is opening for ${f.agentId}`);
await f.promise;
f.controller.signal.throwIfAborted();
n();
}
const p = x?.getPendingNativeOpen();
if (p) {
await racePromiseWithAbortSignal(p, u, (e) => e.reason);
n();
}
if (C) {
await C;
n();
}
if (w || x?.failure()) {
await closeNative();
assertCurrent();
e.assertCurrent();
n();
u?.throwIfAborted();
}
if (!x) {
const t = await captureGatewayStateOwnerAsync(l.admission);
assertCurrent();
e.assertCurrent();
n();
u?.throwIfAborted();
x ??= createGeneration(t, r, c);
}
const m = x;
let h = false;
try {
const r = await m.run(e, (e) => {
h = true;
return t(e);
}, n, s, u);
if (x === m && !C && (m.failure() || !S && !m.getPendingPreparation())) await closeNative(m).catch(reportCleanupFailure);
return r;
} catch (i) {
const a = m.failure();
const l = !h && isSqliteLockError(i);
if (x === m && (a || o)) try {
if (a === "native" && !l && !C) {
v.reportTerminal(i);
await O.close();
} else await closeNative(m);
} catch (e) {
reportCleanupFailure(e);
const t = i instanceof Error ? i : new Error(String(i));
const n = Object.assign(new Error(t.message, { cause: new AggregateError([i, e], "Agent operation and cleanup failed", { cause: i }) }), { name: t.name });
throw isSqliteWorkerError(i, "outcome-unknown") ? retainSqliteWorkerErrorCode(n, i) : n;
}
if (l) {
const a = d ?? performance.now() + 2e3;
if (d === void 0) log.warn("Agent database execution admission delayed by SQLite lock contention; retrying before execution.");
const l = a - performance.now();
if (l > 0) {
await sleepWithAbort(Math.min(25, l), u);
assertCurrent();
e.assertCurrent();
n();
if (performance.now() >= a) throw i;
return run(e, t, n, r, o, s, c, u, a);
}
}
throw i;
}
}
const releaseBorrower = async (e) => {
if (e && --b === 0 && !S && !C && !w) {
if (x) await closeNative(x).catch(reportCleanupFailure);
if (!b && !x && !C && !w) y = void 0;
}
_ -= 1;
if (_ !== 0 || !g.open || w || f) return;
const t = getGatewayShutdownCleanupSignal();
const canRetain = () => x && S && !C && !t.aborted;
try {
for (const e of n.idle) {
if (!canRetain() || n.idle.size < MAX_IDLE_EXECUTORS) break;
if (_ !== 0 || !g.open || n.idle.has(O)) return;
await e.closeIdle();
}
} catch (e) {
reportCleanupFailure(e);
}
if (_ !== 0 || !g.open || n.idle.has(O)) return;
if (canRetain() && n.idle.size < MAX_IDLE_EXECUTORS) {
n.idle.add(O);
const e = runInDetachedAsyncContext(() => setTimeout(() => {
if (D !== e || !n.idle.has(O)) return;
O.closeIdle().catch(reportCleanupFailure);
}, resolveAgentDatabaseIdleHandleTtlMs()));
D = e;
e.unref();
return;
}
await O.closeIdle().catch(reportCleanupFailure);
};
const retainBorrower = (e) => {
assertCurrent();
_ += 1;
clearIdleTimer();
if (!C && !w) n.idle.delete(O);
if (e) {
y ??= e;
b += 1;
}
return () => releaseBorrower(e);
};
const O = {
kind: "file",
agentId: i,
get sharedDatabaseKey() {
return l.admission.identity.key;
},
get creationIdentity() {
return y;
},
getPendingPreparation: () => x?.getPendingPreparation(),
retain: () => retainBorrower(y),
borrow(e, t, n, r, s) {
const c = getAgentDeletionDatabaseCleanup({
...u,
path: e
});
const l = t ? Object.freeze({ ...t }) : void 0;
const d = n ? Object.freeze({ ...n }) : void 0;
assertAgentDatabaseBorrowTarget(e, S, s);
const assertReferenceCurrent = (t) => {
assertCurrent();
assertBorrowedAgentDatabaseFileIdentity({
borrowedPath: e,
identity: o,
creatingTarget: d,
fileIdentity: S,
expectedIdentity: l,
nativeIdentity: t,
observedIdentity: s
});
};
assertReferenceCurrent();
if (d && !y && !S && x) throw new Error("Agent creation cannot capture another pending native opener");
retainAlias(e);
if (r !== void 0) retainAlias(path.resolve(r));
observeOpenClawDatabaseMaintenanceResource(m.get(a));
const f = retainBorrower(d);
const assertCreationReference = (e) => {
if (d && !S && !e) throw new Error("Originally observed agent target requires creating admission first");
if (b && !S && (!e || !d)) throw new Error("Originally observed agent target requires its captured creating reference");
};
const p = new AgentDatabaseExecutionLifetime();
let h;
const g = Symbol("agent database borrower");
const assertBorrowed = () => {
if (!p.open) throw new Error("Agent database execution reference is released");
c?.assertCurrentHost();
assertReferenceCurrent();
};
const captureGenerationClaim = () => {
assertBorrowed();
if (!x) throw new Error("Agent database execution has no admitted generation");
return x.captureClaim(assertBorrowed);
};
const _ = {
agentId: i,
path: e,
onTerminal: v.onTerminal,
get fileIdentity() {
assertBorrowed();
return S;
},
async adoptNativeDatabase(e) {
const t = (async () => {
const t = captureNativeAgentDatabaseExecutionIdentity(e, i, o.canonicalPath, assertBorrowed);
if (x && !S) {
await closeNative(x);
t.assertCurrent();
}
assertReferenceCurrent(t.fileIdentity);
acceptFileIdentity(t.fileIdentity);
})();
v.pending.set(t, { borrower: g });
try {
await t;
} finally {
v.pending.delete(t);
}
},
assertCurrent: assertBorrowed,
captureGenerationClaim,
capturePreparedGenerationClaim() {
if (cache.pending.has(a) || C || w || x?.failure() || !x?.isPrepared()) {
assertBorrowed();
return;
}
return captureGenerationClaim();
},
async prepare(e, t) {
assertBorrowed();
assertCreationReference(true);
const n = run(e, async () => void 0, (e) => {
assertReferenceCurrent(e);
assertCreationReference(true);
}, l, false, true, d, t);
v.pending.set(n, { borrower: g });
n.finally(() => v.pending.delete(n)).catch(() => void 0);
await n;
},
async runExisting(e, t, n) {
const r = p.open ? x : void 0;
const i = createDeferredCore();
v.pending.set(i.promise, { borrower: g });
try {
assertBorrowed();
assertCreationReference(false);
const execute = () => run(e, t, (e) => {
assertReferenceCurrent(e);
assertCreationReference(false);
}, l, n?.retireNativeOnFailure);
if (n?.withAdmission) {
const e = new AbortController();
v.pending.set(i.promise, {
borrower: g,
queuedReadAbort: e
});
return await n.withAdmission(execute, e.signal);
}
return await execute();
} catch (e) {
let t = n?.retireNativeOnFailure === true;
if (r && x === r && S) try {
assertExistingDatabaseIdentity(S.nativeLocation, `file:${S.physicalIdentity}`, S.birthtime);
} catch {
t = true;
}
if (t && r) try {
await closeNative(r);
} catch (t) {
throw retainSqliteWorkerErrorCode(new AggregateError([e, t], "Agent execution refusal and native cleanup failed", { cause: e }), e);
}
throw e;
} finally {
v.pending.delete(i.promise);
i.resolve();
}
},
release() {
p.retire();
v.cancelReadAdmissions(g);
return h ??= (async () => {
await v.settleBorrower(g);
await f();
})();
}
};
c?.registerClose(() => _.release());
return _;
},
async closeIdle() {
if (getGatewayShutdownCleanupSignal().aborted && n.idle.has(O)) return;
await closeNative();
if (_ === 0 && !x) finishRetirement();
},
async retireForCleanup() {
if (!f) {
while (v.pending.size > 0) await Promise.allSettled(v.pending.keys());
await O.close();
}
},
close() {
g.close();
v.cancelReadAdmissions();
T ??= (async () => {
await closeNative();
finishRetirement();
})().catch((e) => {
T = void 0;
g.reopen();
throw e;
});
return T;
}
};
const revoke = () => {
g.revoke();
v.cancelReadAdmissions();
clearIdleTimer();
v.reportTerminal(new AgentDatabaseExecutionAdmissionClosedError("Agent database execution admission revoked"));
};
const unregisterAgent = () => {
for (const [e, t] of m) {
if (r.get(e) === O) r.delete(e);
t();
}
m.clear();
};
const retainAlias = (t) => {
if (m.has(t)) return;
const register = () => registerOpenClawAgentDatabaseAsyncResource({
agentId: i,
path: t,
revoke,
close: () => v.closeAccepted(() => O.close()),
retireAfterResources: true
}, e);
const n = m.size === 0 ? register() : runOutsideOpenClawDatabaseMaintenanceScope(register);
m.set(t, n);
r.set(t, O);
};
try {
retainAlias(a);
retainAlias(o.canonicalPath);
registerAgentDeletionExecutionCleanup(O, u, () => drainAgentDatabaseResources({
path: a,
agentId: i
}, async () => {}, f));
E = registerOpenClawStateDatabaseAsyncResource({
admission: l.admission,
close: async () => {
v.reportTerminal(new AgentDatabaseExecutionAdmissionClosedError("Agent database state admission closed"));
await v.closeAccepted(() => O.close());
}
});
return O.borrow(a, s, c, t.requestedPath, t.observedIdentity);
} catch (e) {
g.retire();
unregisterAgent();
E?.();
throw e;
}
}
//#endregion
//#region src/state/openclaw-agent-execution.ts
const executionState = resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseExecutionOwners"), () => ({
owners: /* @__PURE__ */ new Map(),
idle: /* @__PURE__ */ new Set()
}));
const executions = executionState.owners;
/** Observe initial schema and registry publication through an already-captured physical path. */
function getPendingOpenClawAgentDatabasePreparation(e, t = "write") {
const n = executions.get(e)?.getPendingPreparation();
return n && t === "read" && isAgentDatabaseStartupReadReady(e) ? void 0 : n;
}
/** Explicit preparation joins the file owner's already-captured creation target. */
function captureOpenClawAgentDatabasePreparationExecution(e, t, n) {
return captureOpenClawAgentDatabaseExecution(e, {
expectedIdentity: t,
requestedPath: n
}, true);
}
/** Only the deleted agent's store needs a fresh, exclusive cleanup owner. */
async function captureAgentDeletionDatabaseExecution(e) {
const t = getAgentDeletionDatabaseCleanup(e);
if (t?.worker && t.ownsDatabase) {
t.assertCurrentHost();
const n = resolveOpenClawAgentSqlitePath(e);
const r = executions.get(n) ?? executions.get(readDatabasePathIdentitySync(n).canonicalPath);
if (r) {
assertAgentDatabaseExecutionSharedState(e, r.sharedDatabaseKey);
assertAgentDeletionExecutionCleanupAccess(r, e);
await r.retireForCleanup();
t.assertCurrentHost();
}
}
return captureOpenClawAgentDatabaseExecution(e);
}
/** Finish native initialization before publishing a newly available agent to readers. */
async function prepareOpenClawAgentDatabaseExecution(e, t, n) {
t();
let r;
try {
await runOpenClawAgentWorkerWrite(e, async () => {
t();
r = await captureOpenClawAgentDatabaseExecutionAsync(e, true);
t();
return r.prepare(createSessionWorkerExecutionSource(t, `Agent ${e.agentId} database preparation admission expired`), n);
}, void 0, n);
} finally {
await r?.release();
}
}
/** Observe filesystem identity asynchronously while retaining the current authority cohort. */
async function captureOpenClawAgentDatabaseExecutionAsync(e, t = false) {
assertAgentSessionWriteAdmission(e);
const n = resolveOpenClawAgentSqlitePath(e);
const r = captureOpenClawStateReadContext(resolveOpenClawStateSqlitePath(e.env));
const i = captureAgentDatabaseAdmission(e.agentId, { env: e.env });
const a = captureAgentCreationClaim(e);
const o = getAgentDeletionDatabaseCleanup(e);
const s = executions.get(n);
let c;
let l = false;
const u = registerOpenClawAgentDatabaseAsyncResource({
agentId: e.agentId,
path: n,
revoke: () => {
l = true;
},
close: async () => {}
}, e);
try {
c = s?.retain();
const u = await readDatabasePathIdentity(n);
r.admission.assertCurrent();
(o?.ownsDatabase ? o.assertCurrentHost : i)();
a?.assertCurrent();
o?.assertCurrentHost();
if (l || s && executions.get(n) !== s) throw new Error("Agent database execution owner retired during capture");
return Object.assign(captureAgentDatabaseExecution(e, t && u.key.startsWith("path:") ? {} : toAgentExecutionConstraints(u), t, u), { capturedIdentity: u });
} finally {
u();
await c?.();
}
}
/** Borrow before callers yield; native opening stays lazy and release joins owned work. */
function captureOpenClawAgentDatabaseExecution(e, t = {}, n = false) {
return captureAgentDatabaseExecution(e, t, n);
}
function captureAgentDatabaseExecution(e, t, n, r) {
assertAgentSessionWriteAdmission(e);
assertAgentDeletionCleanupAliases(e, isSameOpenClawAgentDatabasePath);
const i = normalizeAgentId(e.agentId);
const a = resolveOpenClawAgentSqlitePath(e);
assertAgentCreationClaimAliases(e);
if (!supportsOpenClawAgentDatabaseExecution(e)) throw new Error("This agent database scope still requires its existing native owner");
let o = executions.get(a);
const s = t.expectedCreationIdentity ? Object.freeze({ ...t.expectedCreationIdentity }) : void 0;
if (!o || s) {
const c = r ?? readDatabasePathIdentitySync(a);
o ??= executions.get(c.canonicalPath);
if (s) assertAgentDatabaseExecutionCreationIdentity(a, s, s.key.startsWith("path:") && o ? o.creationIdentity ?? c : c, t.expectedIdentity);
if (!o) return createAgentDatabaseExecution(e, {
agentId: i,
pathname: a,
identity: c,
initialIdentity: t.expectedIdentity,
expectedCreationIdentity: s ?? (n && c.key.startsWith("path:") ? c : void 0),
requestedPath: t.requestedPath,
observedIdentity: r
}, executionState);
}
if (o.agentId !== i) throw new Error(`OpenClaw agent database ${a} is already open for agent ${o.agentId}; requested agent ${i}.`);
assertAgentDatabaseExecutionSharedState(e, o.sharedDatabaseKey);
assertAgentDeletionExecutionCleanupAccess(o, e);
return o.borrow(a, t.expectedIdentity, s ?? (n ? o.creationIdentity : void 0), t.requestedPath, r);
}
//#endregion
export { getPendingOpenClawAgentDatabasePreparation as a, toAgentExecutionConstraints as c, captureOpenClawAgentDatabasePreparationExecution as i, cleanupRetiredAgentDatabaseLease as l, captureOpenClawAgentDatabaseExecution as n, prepareOpenClawAgentDatabaseExecution as o, captureOpenClawAgentDatabaseExecutionAsync as r, supportsOpenClawAgentDatabaseExecution as s, captureAgentDeletionDatabaseExecution as t };