UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2,587 lines • 114 kB
import { a as resolveGlobalSingleton } from "./global-singleton-0m-JziJW.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { c as isRecord } from "./record-coerce-TIsquoVR.mjs";
import { d as sleepWithAbort, o as racePromiseWithAbortSignal } from "./src-D1BHGNTj.mjs";
import "./abort-signal-QqAmLWTl.mjs";
import { i as resolveRuntimeWorkerUrl } from "./runtime-worker-url-CFqA9Dvi.mjs";
import { r as resolveStateDir } from "./state-dir-CYkBUd_G.mjs";
import "./paths-BP0DYpE8.mjs";
import { t as formatErrorMessage } from "./errors-BvOkmQM5.mjs";
import { d as readDatabasePathIdentitySync, r as assertExistingDatabaseIdentity, u as readDatabasePathIdentity } from "./sqlite-worker-identity-BRNRpRyc.mjs";
import { t as isPromiseLike } from "./promise-like-D7-l5Fsp.mjs";
import { a as createSqliteLifecycleAggregateError, s as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-DuOygjcn.mjs";
import { a as isSqliteLockError } from "./sqlite-error-diagnostics-CWRyv4lz.mjs";
import { t as createSubsystemLogger } from "./subsystem-4NzR43uz.mjs";
import { g as publishSqliteWalCheckpointObservation } from "./sqlite-wal-DfKCrDTQ.mjs";
import { c as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-CmKkMYdo.mjs";
import { h as runOutsideOpenClawDatabaseMaintenanceScope, m as observeOpenClawDatabaseMaintenanceResource, u as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-db-async-lifecycle-DwFy2ZTk.mjs";
import { n as runtimeProcessEntrypoints } from "./runtime-process-entrypoints-De68tE_W.mjs";
import { r as createSqliteWorkerTransferReceiver } from "./sqlite-worker-transfer-gbln6DQ8.mjs";
import { n as normalizeAgentId } from "./agent-id-D1-Q6vR4.mjs";
import "./session-key-DY3MOX4N.mjs";
import { i as listAgentIds } from "./agent-roster-DH6r_8f4.mjs";
import { c as resolveSessionStorePathCore } from "./paths-Bonddxfk.mjs";
import { _ as resolveEffectiveAgentDir } from "./agent-scope-config-BEk6-ThS.mjs";
import { a as readOpenClawAgentDatabaseIdentity, i as isOpenClawAgentDatabasePathCurrent } from "./openclaw-agent-db-identity-BlmER9-X.mjs";
import { t as SQLITE_IDLE_HANDLE_TTL_MS } from "./sqlite-handle-lifecycle-dWd9h3ii.mjs";
import { f as assertAgentCreationClaimAliases, m as captureAgentCreationClaim, o as registerOpenClawAgentDatabaseAsyncResource, r as drainAgentDatabaseResources, x as AgentDatabaseExecutionAdmissionClosedError } from "./openclaw-agent-db-resources-Cm-sH7kg.mjs";
import { b as retireReplacedAgentValidation, h as invalidateOpenClawAgentDatabaseValidation, l as getOpenClawAgentDatabaseValidationForTransfer, r as captureOpenClawAgentDatabaseAdmissionPublication } from "./openclaw-agent-db-validation-cache-CHrtutWN.mjs";
import { c as resolveIncognitoOpenClawAgentSqlitePath, i as isIncognitoOpenClawAgentSqlitePath, l as resolveOpenClawAgentSqlitePath, n as assertIncognitoAgentDatabasePathAvailable } from "./openclaw-agent-db.paths-BbmZlEP5.mjs";
import { c as SqliteWorkerError, d as retainSqliteWorkerErrorCode } from "./sqlite-worker-contract-C51cJHzg.mjs";
import { r as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-C5lBzzTk.mjs";
import { a as captureAgentDatabasePreparationCompletion, i as captureAgentDatabaseAdmission, s as captureAgentDatabasePreparationJournal } from "./agent-database-admission-CRwW7FsI.mjs";
import { i as sessionChanges } from "./session-row-changes-Dj2yVWo-.mjs";
import { h as publishOpenClawStateDatabaseWorkerAdmission, v as registerOpenClawStateDatabaseAsyncResource } from "./openclaw-state-db-cache-CmYLFRSt.mjs";
import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-BzUE_dOh.mjs";
import { C as registerAgentDeletionExecutionCleanup, x as getAgentDeletionDatabaseCleanup, y as assertAgentDeletionExecutionCleanupAccess } from "./agent-deletion-journal-DkfGlzu8.mjs";
import { n as captureOpenClawStateReadWorkerContext, r as captureOpenClawStateWorkerContext, t as captureOpenClawStateReadContext } from "./openclaw-state-worker-context-BvvgY6-t.mjs";
import { p as settleAgentRegistration, r as captureOpenClawAgentDatabaseRegistration } from "./openclaw-agent-db-registry-listing-DIA5wIwi.mjs";
import { l as getGatewayRestartDrainSignal } from "./gateway-work-admission-DAV5kkgV.mjs";
import { l as hasAgentDatabaseMaintenanceAuthority } from "./openclaw-agent-db-lease-zP0JO4hP.mjs";
import { t as cache, w as retainIncognitoSharedState } from "./openclaw-agent-db-lifecycle-C9dal1XJ.mjs";
import { t as runOpenClawAgentWorkerWrite } from "./openclaw-agent-write-admission-CXJiE5VB.mjs";
import { n as requestOpenClawAgentDatabaseIntegrityCheck, t as captureOpenClawDatabaseIntegrityVerifier } from "./openclaw-database-verify-CGIYTxWq.mjs";
import "./backoff-BrzXG7iD.mjs";
import { a as isSqliteWorkerStoreAvailable, o as openAgentDatabaseSqliteWorkerStore, p as runSqliteWorkerStoreOperation, s as openEphemeralAgentDatabaseSqliteWorkerStore, t as closeUnclaimedSharedStateSqliteWorkers } from "./sqlite-worker-store-C0QRqven.mjs";
import { i as openOpenClawStateWorkerCleanupStore } from "./openclaw-state-worker-store-BxZXTKna.mjs";
import { F as captureRuntimeConfigWithSource, o as getRuntimeConfigSnapshot } from "./runtime-snapshot-De_QxZI9.mjs";
import "./openclaw-state-lease-heartbeat-shared-BczGehzh.mjs";
import { n as forkCliSessionBindings } from "./cli-session-binding-Dx1VbkI8.mjs";
import { t as IncognitoSessionEndedError } from "./incognito-session-error-BUzgcwoZ.mjs";
import { t as createAgentDatabaseStartupFtsAdmission } from "./agent-database-startup-fts-DD7EI6Ln.mjs";
import path from "node:path";
import { AsyncLocalStorage } from "node:async_hooks";
import { isDeepStrictEqual } from "node:util";
import { randomUUID } from "node:crypto";
import { MessagePort } from "node:worker_threads";
import { addAbortListener } from "node:events";
//#region src/config/sessions/session-incognito-history-contract.ts
function isIncognitoHistoryCommand(command) {
	return command.type.startsWith("session.history.");
}
function incognitoHistoryKeys(command) {
	if (command.type === "session.history.search" || command.type === "session.history.memory-targets") {
		const keys = command.input.sessions.map((session) => session.sessionKey);
		if (new Set(keys).size !== keys.length) throw new Error("Incognito search must retain unique selected sessions");
		return keys;
	}
	if (command.type !== "session.history.memory-corpus") return [command.input.sessionKey];
	const keys = command.input.sessionKeys;
	if (!keys.includes(command.input.sessionKey) || new Set(keys).size !== keys.length) throw new Error("Incognito Memory corpus must retain its selected sessions");
	return keys;
}
//#endregion
//#region src/config/sessions/session-incognito-lifecycle-contract.ts
function isIncognitoLifecycleCommand(command) {
	return command.type.startsWith("session.lifecycle.");
}
function isIncognitoLifecycleWrite(type) {
	return type !== "session.lifecycle.reclaim.prepare" && type !== "session.lifecycle.fork.prepare" && type !== "session.lifecycle.parentFork.prepare" && type !== "session.lifecycle.parentFork.source";
}
function captureIncognitoLifecycleSettlement(input, capture) {
	const removedEntries = "target" in input ? input.target ? [input.target] : void 0 : "plan" in input ? input.plan.entries.flatMap(({ sessionKey, expectedEntry }) => expectedEntry ? [{
		sessionKey,
		entry: expectedEntry
	}] : []) : void 0;
	if (removedEntries && !capture) throw new Error("Incognito deletion requires its prepared lifecycle owner");
	return removedEntries ? capture?.(removedEntries) : void 0;
}
function incognitoLifecycleKeys(command, identity) {
	switch (command.type) {
		case "session.lifecycle.maintenance": return command.input.plan.entries.map(({ sessionKey }) => sessionKey);
		case "session.lifecycle.messageCut": return [.../* @__PURE__ */ new Set([command.input.intent.sourceKey, command.input.intent.targetKey])];
		case "session.lifecycle.parentFork.source": return [command.input.sessionKey];
		case "session.lifecycle.parentFork.prepare": return parentForkEntryKeys(command.input);
		case "session.lifecycle.parentFork.commit": {
			const input = command.input;
			return input.kind === "entry" ? parentForkEntryKeys(input.params) : [.../* @__PURE__ */ new Set([...input.source === void 0 ? [input.params.parentSessionKey] : [], input.params.sessionKey])];
		}
		case "session.lifecycle.delete": return [command.input.target.sessionKey];
		case "session.lifecycle.reclaim": return command.input.plan.entries.map(({ sessionKey }) => sessionKey);
		case "session.lifecycle.reclaim.prepare": return [];
		case "session.lifecycle.fork.prepare": return [command.input.parent.sessionKey];
		case "session.lifecycle.fork": return command.input.parent.identity.handle === identity.handle && command.input.parent.identity.incarnation === identity.incarnation ? [command.input.parent.sessionKey, command.input.child.sessionKey] : [command.input.child.sessionKey];
	}
	throw new Error("Unsupported incognito lifecycle operation");
}
function parentForkEntryKeys(params) {
	return [.../* @__PURE__ */ new Set([
		params.parentTarget.canonicalKey,
		...params.parentTarget.storeKeys,
		params.sessionTarget.canonicalKey,
		...params.sessionTarget.storeKeys
	])];
}
//#endregion
//#region src/config/sessions/session-incognito-manager-contract.ts
function isIncognitoManagerCommand(command) {
	return command.type.startsWith("session.manager.");
}
function isIncognitoManagerWrite(type) {
	return type !== "session.manager.metadata.mutation";
}
function toIncognitoManagerCommand(command) {
	return {
		type: `session.manager.${command.type.slice(8)}`,
		input: {
			sessionKey: command.input.scope.sessionKey,
			command
		}
	};
}
//#endregion
//#region src/config/sessions/session-incognito-transcript-contract.ts
function isIncognitoTranscriptCommand(command) {
	return isIncognitoManagerCommand(command) || command.type.startsWith("session.report.") || command.type.startsWith("session.lock.") || command.type.startsWith("session.manualCompact.") || command.type === "session.goal.mutate" || command.type.startsWith("session.correction.") || command.type.startsWith("session.rewrite.") || command.type === "session.runtimeTarget.read" || command.type === "session.keyById.read" || command.type === "session.goalReceipt.read" || command.type === "session.event.append" || command.type === "session.message.append" || command.type === "session.turn.read";
}
function isIncognitoTranscriptWrite(type) {
	const command = { type };
	if (isIncognitoManagerCommand(command)) return isIncognitoManagerWrite(command.type);
	return type !== "session.lock.events" && type !== "session.lock.facts" && type !== "session.manualCompact.prepare" && type !== "session.correction.prepare" && type !== "session.rewrite.prepare" && type !== "session.runtimeTarget.read" && type !== "session.keyById.read" && type !== "session.goalReceipt.read" && type !== "session.report.prepare" && type !== "session.report.latestCustomReport" && type !== "session.turn.read";
}
function isIncognitoTranscriptReceiptCommand(type) {
	return type === "session.lock.replace" || type === "session.goal.mutate" || type === "session.manualCompact.commit" || type === "session.rewrite.commit" || type === "session.event.append" || type === "session.correction.commit";
}
//#endregion
//#region src/config/sessions/session-incognito-admission.ts
function readIncognitoGrantFacts(received, identity, command, committedTargets) {
	if (!Array.isArray(received) || received.some((facts) => !isRecord(facts) || !isDeepStrictEqual(facts.identity, identity) || typeof facts.sessionKey !== "string" || !Number.isSafeInteger(facts.revision))) throw new Error("Incognito session grant differs from its captured target");
	const facts = received;
	const keys = facts.map((entry) => entry.sessionKey);
	const lifecycleKeys = isIncognitoLifecycleCommand(command) ? incognitoLifecycleKeys(command, identity) : void 0;
	const historyKeys = isIncognitoHistoryCommand(command) ? incognitoHistoryKeys(command) : void 0;
	if (new Set(keys).size !== keys.length || historyKeys && !isDeepStrictEqual(keys, historyKeys) || lifecycleKeys && !isDeepStrictEqual(keys, lifecycleKeys) || !historyKeys && "sessionKey" in command.input && (keys.length !== 1 || keys[0] !== command.input.sessionKey) || committedTargets && !isDeepStrictEqual(keys, [...committedTargets])) throw new Error("Incognito session grant changed its target set");
	return facts;
}
/** Entry receipts publish the paired kernel's acknowledged result without replay. */
function incognitoEntryPublication(type, authorizePrepared, authorizePublication) {
	let receiver;
	let transferId;
	let completed = false;
	let candidate;
	return {
		factsKey: "entry",
		prepare(facts) {
			if (isRecord(facts) && facts.kind === "session-entry-patch-transfer") {
				if (receiver || !isRecord(facts.handle) || typeof facts.handle.id !== "number" || !Number.isSafeInteger(facts.handle.id) || facts.handle.id < 1 || !Array.isArray(facts.handle.kinds) || facts.handle.kinds.length !== 1 || facts.handle.kinds[0] !== "patch") throw new Error("Incognito entry returned an invalid publication transfer");
				const handle = facts.handle;
				transferId = handle.id;
				receiver = createSqliteWorkerTransferReceiver(handle, (record) => {
					if (candidate || record.kind !== "patch" || !isRecord(record.value) || record.value.kind !== "incognito-entry" || !Array.isArray(record.value.facts) || !isRecord(record.value.value)) throw new Error("Incognito entry returned an invalid publication candidate");
					candidate = record.value;
				});
			} else if (isRecord(facts) && facts.kind === "session-entry-patch-frame" && receiver) completed = receiver.accept(facts.frame) !== void 0;
			else throw new Error("Incognito entry returned unexpected publication facts");
		},
		authorize(stage, facts) {
			const value = candidate?.value;
			if (value != null && "refusedSource" in value && value.refusedSource) {
				authorizePrepared?.(value.refusedSource);
				throw new Error("Session source refusal was not rejected");
			}
			if (isRecord(facts) && facts.guarded === true) authorizePrepared?.(void 0, facts.sourceValidation);
			const publication = stage === "commit" ? candidate?.value : isRecord(facts) ? facts.publication : void 0;
			if (publication !== void 0) authorizePublication?.(publication);
		},
		decodeReceipt(receipt) {
			if (!completed || !candidate || !isRecord(receipt) || receipt.kind !== "session-entry-patch-committed" || receipt.transferId !== transferId) throw new SqliteWorkerError(`Incognito ${type} omitted its committed receipt`, "outcome-unknown");
			return candidate;
		}
	};
}
function authorizeSessionFacts(authority, stage, facts) {
	const authorization = authority.authorize?.(stage, structuredClone(facts));
	if (isPromiseLike(authorization)) {
		Promise.resolve(authorization).catch(() => void 0);
		throw new Error("Incognito session grants must remain synchronous");
	}
}
/** A patch checks cancellation before its predicate, then guards the validated row before writing. */
function isIncognitoEntryValidationGrant(type, phase, request, previousGuarded) {
	return (type === "session.entry.patch.commit" || type === "session.turn.commit" || isIncognitoTranscriptReceiptCommand(type)) && phase === "transaction" && request.stage === "transaction" && (type !== "session.entry.patch.commit" || previousGuarded === false) && isRecord(request.facts) && isRecord(request.facts.entry) && request.facts.entry.guarded === true;
}
//#endregion
//#region src/config/sessions/session-incognito-authority.ts
/** Claims consume the actor's live projection; they never own a second copy of its state. */
function createIncognitoSessionClaims(owner) {
	const { identity, current, readTopologyRevision, withGrant } = owner;
	const claim = (sessionKey, assertBorrowed, absent) => {
		const observed = current(sessionKey)?.sharing?.entry;
		const capturedRevision = readTopologyRevision();
		const assertCurrent = () => {
			assertBorrowed();
			const entry = current(sessionKey)?.sharing?.entry;
			if (entry?.sessionId !== observed?.sessionId || entry?.lifecycleRevision !== observed?.lifecycleRevision || !observed && capturedRevision !== readTopologyRevision()) throw new Error("Incognito session generation is no longer current");
		};
		return {
			identity,
			sessionKey,
			assertCurrent,
			authorize(authority, stage) {
				withGrant(() => {
					authority.assertCurrent();
					assertCurrent();
					const facts = current(sessionKey) ?? (!observed ? absent : void 0);
					if (!facts) throw new Error("Incognito session facts are unavailable");
					authorizeSessionFacts(authority, stage, facts);
					authority.assertCurrent();
					assertCurrent();
				});
			}
		};
	};
	return {
		claim,
		captureStoreSnapshot(assertBorrowed, authority) {
			const observed = owner.readSnapshotRevision();
			return { assertCurrent() {
				assertBorrowed();
				authority.assertCurrent();
				if (owner.readSnapshotRevision() !== observed || owner.hasUnsettledFacts()) throw new Error("Incognito session snapshot changed; prepare it again");
			} };
		},
		captureRead(assertReadable) {
			return {
				captureCurrent(sessionKey) {
					assertReadable();
					return claim(sessionKey, assertReadable);
				},
				readSharing(sessionKey) {
					assertReadable();
					return structuredClone(current(sessionKey)?.sharing);
				},
				readChatMetadataRevision(sessionKey) {
					assertReadable();
					return current(sessionKey)?.chatMetadataRevision;
				},
				readEntryRevision(sessionKey) {
					assertReadable();
					return current(sessionKey)?.entryReadRevision;
				},
				readDelivery(sessionKey) {
					assertReadable();
					return structuredClone(current(sessionKey)?.delivery);
				},
				readMedia(sessionKey) {
					assertReadable();
					return structuredClone(current(sessionKey)?.media);
				},
				readSteering(sessionKey) {
					assertReadable();
					return structuredClone(current(sessionKey)?.steering);
				},
				readPolicy(sessionKey) {
					assertReadable();
					return structuredClone(current(sessionKey)?.policy);
				},
				readCliHistory(sessionKey) {
					assertReadable();
					return structuredClone(current(sessionKey)?.cliHistory);
				},
				readCapability(sessionKey) {
					assertReadable();
					return structuredClone(current(sessionKey)?.capability);
				}
			};
		},
		deadlines(assertBorrowed, assertAdmittedCurrent) {
			assertBorrowed();
			return [...owner.entries].flatMap(([sessionKey, facts]) => {
				const entry = facts.sharing?.entry;
				return entry && facts.expiresAt !== void 0 ? [{
					sessionKey,
					sessionId: entry.sessionId,
					expiresAt: facts.expiresAt,
					source: {
						identity: identity.incarnation,
						assertSettlingCurrent() {
							assertBorrowed();
							const currentId = owner.entries.get(sessionKey)?.sharing?.entry?.sessionId;
							if (currentId !== void 0 && currentId !== entry.sessionId) throw new Error("Incognito deadline no longer owns this session");
						},
						assertCurrent() {
							assertAdmittedCurrent();
							if (owner.entries.get(sessionKey)?.sharing?.entry?.sessionId !== entry.sessionId) throw new Error("Incognito deadline no longer owns this session");
						}
					}
				}] : [];
			});
		},
		captureSnapshot(sessionKey, assertBorrowed) {
			assertBorrowed();
			const observed = current(sessionKey)?.revision;
			const held = claim(sessionKey, assertBorrowed);
			const settled = claim(sessionKey, owner.assertReadable);
			const assertRevision = () => {
				if (current(sessionKey)?.revision !== observed) throw new Error("Incognito session snapshot changed; prepare it again");
			};
			return {
				assertCurrent() {
					held.assertCurrent();
					assertRevision();
				},
				/** Validate consumed facts after borrow cleanup; this grants no further reads. */
				assertSettledCurrent() {
					settled.assertCurrent();
					assertRevision();
				}
			};
		}
	};
}
/** Borrow authority remains live at every command grant; cleanup uses its settlement authority. */
function retainIncognitoSessionAuthority(assertAuthority, request) {
	return {
		entryCreation: request.entryCreation,
		assertCurrent() {
			assertAuthority();
			request.assertCurrent();
		},
		authorize: (stage, facts) => request.authorize?.(stage, facts)
	};
}
/** Grant-local facts never escape their command's synchronous authority callback. */
function createIncognitoSessionGrants(withGrant) {
	let creation;
	let preimage;
	let sourceFacts;
	return {
		command(type, entryCreation) {
			let commandCreation;
			let commandPreimage;
			return {
				run(operation) {
					return withGrant(() => {
						const previousCreation = creation;
						const previousPreimage = preimage;
						const previousSources = sourceFacts;
						creation = commandCreation;
						preimage = commandPreimage;
						sourceFacts = commandPreimage;
						try {
							return operation();
						} finally {
							creation = previousCreation;
							preimage = previousPreimage;
							sourceFacts = previousSources;
						}
					});
				},
				capture(stage, facts) {
					if (type === "session.entry.creation.commit" && stage === "transaction" && entryCreation && facts[0]) {
						commandCreation = {
							facts: facts[0],
							operation: entryCreation
						};
						creation = commandCreation;
					}
					if (stage !== "commit") {
						commandPreimage = facts;
						preimage = facts;
					}
					sourceFacts = facts;
				}
			};
		},
		readPreimage(sessionKey) {
			return preimage?.find((facts) => facts.sessionKey === sessionKey);
		},
		readSource(sessionKey) {
			return sourceFacts?.find((facts) => facts.sessionKey === sessionKey);
		},
		readCreation(sessionKey, operation) {
			return creation?.facts.sessionKey === sessionKey && creation.operation === operation ? structuredClone(creation.facts) : void 0;
		}
	};
}
/** Store-wide reads share FIFO acceptance and one retained snapshot fence. */
function bindIncognitoSessionStoreReads(read) {
	return {
		readById(authority, input, signal) {
			return read(authority, {
				type: "session.entry.readById",
				input
			}, signal);
		},
		readIdentities(authority, input) {
			return read(authority, {
				type: "session.identities.read",
				input
			});
		},
		list(authority, input, signal) {
			return read(authority, {
				type: "session.entries.read",
				input
			}, signal);
		}
	};
}
/** History reads and retained completion fences share the actor's FIFO publication owner. */
function bindIncognitoSessionHistory(owner) {
	return {
		retainCompletionSource(authority, target, signal) {
			owner.assertOutsideGrant();
			owner.assertBorrowed();
			const input = {
				...structuredClone(target),
				sourceId: randomUUID()
			};
			const done = createDeferredCore();
			const ready = createDeferredCore();
			let active = true;
			const work = owner.retain(async () => {
				try {
					await owner.execute(authority, {
						type: "session.history.completion-source.open",
						input
					}, signal);
					const assertCurrent = () => {
						authority.assertCurrent();
						owner.assertBorrowed();
						const facts = owner.current(input.sessionKey);
						if (!active || !facts?.completionSources?.some((source) => source.sourceId === input.sourceId && source.valid)) throw new Error("Incognito harness completion source is no longer current");
					};
					assertCurrent();
					ready.resolve({
						assertCurrent,
						release() {
							active = false;
							done.resolve();
							return work;
						}
					});
					await done.promise;
				} finally {
					active = false;
					await owner.execute({ assertCurrent: () => owner.assertActorCurrent() }, {
						type: "session.history.completion-source.release",
						input
					}, void 0, true);
				}
			});
			work.catch(ready.reject);
			return ready.promise;
		},
		history: (authority, command, signal, onRead) => owner.execute(authority, command, signal, false, onRead)
	};
}
//#endregion
//#region src/config/sessions/session-incognito-compute-contract.ts
function isIncognitoStoreComputeCommand(command) {
	return command.type.startsWith("session.compute.store.");
}
function isIncognitoComputeCommand(command) {
	return command.type.startsWith("session.compute.");
}
function isIncognitoComputeWrite(type) {
	return type.startsWith("session.compute.projection.") || type === "session.compute.source.release" || type === "session.compute.usage.writeRollup" || type === "session.compute.usage.prune" || type === "session.compute.usage.acquireLock" || type === "session.compute.usage.releaseLock" || type === "session.compute.store.preflight" || type === "session.compute.store.sweep" || type === "session.compute.store.writeRollup" || type === "session.compute.store.prune" || type === "session.compute.store.acquireLock" || type === "session.compute.store.releaseLock";
}
//#endregion
//#region src/config/sessions/session-incognito-compute.ts
/** Cleanup owns only resources captured before dispatch; it never grants data access. */
function withIncognitoCompute(params) {
	const target = structuredClone(params.target);
	const selected = /* @__PURE__ */ new Map();
	if (target) selected.set(target.sessionKey, params.captureClaim(target.sessionKey));
	const observeFacts = (facts) => {
		if (!target) {
			for (const fact of facts) if (!selected.has(fact.sessionKey)) selected.set(fact.sessionKey, params.captureClaim(fact.sessionKey, fact));
		}
	};
	const disclose = () => selected.forEach(params.authorize);
	const sources = /* @__PURE__ */ new Map();
	const locks = /* @__PURE__ */ new Set();
	const pending = /* @__PURE__ */ new Set();
	let active = true;
	const assertCurrent = () => {
		if (!active) throw new Error("Incognito compute scope is closed");
		params.assertAuthority();
		params.assertBorrowed();
		for (const source of selected.values()) source.assertCurrent();
	};
	const ownResources = (captured) => {
		if (captured.type === "session.compute.source.release" || captured.type === "session.compute.usage.releaseLock" || captured.type === "session.compute.store.releaseLock") throw new Error("Incognito compute cleanup belongs to its scope");
		if ("sourceId" in captured.input) {
			const key = captured.input.sourceId;
			if (captured.type === "session.compute.source.open" && !sources.has(key)) {
				const { sessionKey, sessionId, lifecycleRevision, historical } = captured.input;
				sources.set(key, {
					sourceId: randomUUID(),
					target: {
						sessionKey,
						sessionId,
						lifecycleRevision,
						historical
					}
				});
			}
			const owned = sources.get(key);
			if (!owned) throw new Error("Incognito compute source is not owned by this scope");
			captured.input.sourceId = owned.sourceId;
		}
		if (captured.type === "session.compute.usage.acquireLock" || captured.type === "session.compute.store.acquireLock") {
			const request = captured.input.request;
			request.lockJson = JSON.stringify({
				pid: process.pid,
				startedAt: request.startedAt,
				ownerNonce: randomUUID()
			});
			locks.add(request.lockJson);
		}
	};
	return (async () => {
		try {
			assertCurrent();
			const result = await params.operation({
				assertCurrent,
				execute(command, signal) {
					assertCurrent();
					signal?.throwIfAborted();
					const captured = structuredClone(command);
					const input = captured.input;
					if (target && (isIncognitoStoreComputeCommand(captured) || !("sessionKey" in input) || input.sessionKey !== target.sessionKey || input.sessionId !== target.sessionId || input.lifecycleRevision !== target.lifecycleRevision || input.historical !== target.historical)) throw new Error("Incognito compute request belongs to another session generation");
					if (isIncognitoComputeCommand(captured)) ownResources(captured);
					const work = params.execute(captured, observeFacts, signal).then((value) => {
						assertCurrent();
						disclose();
						assertCurrent();
						return value;
					});
					pending.add(work);
					work.finally(() => pending.delete(work)).catch(() => void 0);
					return work;
				}
			});
			assertCurrent();
			disclose();
			assertCurrent();
			return result;
		} finally {
			active = false;
			await Promise.allSettled(pending);
			for (const { sourceId, target: sourceTarget } of sources.values()) while (await params.cleanup({
				type: "session.compute.source.release",
				input: {
					...sourceTarget,
					sourceId
				}
			}));
			for (const lockJson of locks) await params.cleanup(target ? {
				type: "session.compute.usage.releaseLock",
				input: {
					...target,
					request: lockJson
				}
			} : {
				type: "session.compute.store.releaseLock",
				input: { request: lockJson }
			});
		}
	})();
}
//#endregion
//#region src/config/sessions/session-pending-input-operations.types.ts
/** Only the paired kernel's receipt for this exact accepted input may settle its custody. */
function readPendingInputMutationReceipt(facts, input) {
	if (!isRecord(facts) || facts.kind !== "pending-input-settlement" || facts.operation !== input.kind || facts.sessionKey !== input.sessionKey || facts.sessionId !== input.sessionId || facts.idempotencyKey !== input.idempotencyKey || facts.runId !== input.runId || facts.requestHash !== input.requestHash || facts.lifecycleGeneration !== input.lifecycleGeneration) return;
	return facts;
}
//#endregion
//#region src/config/sessions/session-incognito-pending-input-contract.ts
function createIncognitoPendingInputSettlement(input, admitCustody) {
	const matches = (receipt) => readPendingInputMutationReceipt(receipt, input);
	return {
		authorize(stage, facts) {
			if (!isRecord(facts) || facts.kind !== "pending-input-settlement-custody" || !matches(facts.receipt)) throw new Error("Incognito pending input omitted its exact custody grant");
			admitCustody(stage, facts);
		},
		decodeReceipt(receipt) {
			if (!isRecord(receipt) || !Array.isArray(receipt.facts) || !matches(receipt.value)) throw new SqliteWorkerError("Incognito pending input omitted its committed receipt", "outcome-unknown");
			return receipt;
		}
	};
}
function createIncognitoPendingInputHistorySettlement(input, admitCustody) {
	const ids = new Set(input.ids);
	return {
		authorize(stage, facts) {
			if (!isRecord(facts) || facts.kind !== "pending-input-history-custody" || !Array.isArray(facts.candidates) || facts.candidates.some((row) => !isRecord(row) || typeof row.input_id !== "string" || !ids.has(row.input_id) || row.session_key !== input.sessionKey || row.session_id !== input.sessionId)) throw new Error("Incognito pending input history omitted its custody facts");
			admitCustody(stage, facts);
		},
		decodeReceipt(receipt) {
			if (!isRecord(receipt) || !Array.isArray(receipt.facts) || !isRecord(receipt.value) || receipt.value.kind !== "pending-input-history-interrupted" || !Array.isArray(receipt.value.ids) || receipt.value.ids.some((id) => typeof id !== "string" || !ids.has(id))) throw new SqliteWorkerError("Incognito pending input history omitted its committed receipt", "outcome-unknown");
			return receipt;
		}
	};
}
//#endregion
//#region src/config/sessions/session-incognito-side-data-contract.ts
function isIncognitoSideDataWrite(type) {
	return type === "session.acp.entry" || type === "session.category.apply" || type === "session.reaction.set" || type === "session.messageToolOutcome.record" || type === "session.trajectory.append" || type === "session.trajectory.retention.delete" || type === "session.progressCard.put" || type === "session.boards.applyOps" || type === "session.boards.putWidget" || type === "session.boards.grant" || type.startsWith("session.sharing.") || type.startsWith("session.heartbeat.");
}
function incognitoSideDataKeys(command) {
	if (command.type === "session.heartbeat.persist" || command.type === "session.messageToolOutcome.record") return [command.input.session_key];
	if (command.type === "session.catalog.read") return command.input.sessionKeys ?? [];
	return "sessionKey" in command.input ? [command.input.sessionKey] : [];
}
//#endregion
//#region src/config/sessions/session-incognito-actor.ts
/** Actor-local projection owned by its lifetime, never a roster or full-entry cache. */
function createIncognitoSessionFacts(identity, assertActorCurrent, withGrant, assertOutsideGrant, assertAdmittedCurrent = assertActorCurrent) {
	const entries = /* @__PURE__ */ new Map();
	const pending = /* @__PURE__ */ new Set();
	const unavailable = /* @__PURE__ */ new Set();
	const grants = createIncognitoSessionGrants(withGrant);
	let topologyRevision = 0;
	let snapshotRevision = 0;
	const current = (sessionKey) => {
		assertActorCurrent();
		const admitted = grants.readPreimage(sessionKey);
		if (admitted) return admitted;
		if (pending.has(sessionKey) || unavailable.has(sessionKey)) throw new Error("Incognito session facts are pending or unavailable");
		return entries.get(sessionKey);
	};
	const install = (facts) => {
		assertActorCurrent();
		if (!isDeepStrictEqual(facts.identity, identity)) throw new Error("Incognito publication belongs to another actor");
		const previous = entries.get(facts.sessionKey);
		if (previous && previous.revision > facts.revision) throw new Error("Incognito publication is older than committed facts");
		const next = structuredClone(facts);
		snapshotRevision = Math.max(snapshotRevision, next.revision);
		if (previous?.sharing?.entry?.sessionId === next.sharing?.entry?.sessionId && previous) next.expiresAt = previous.expiresAt;
		if (previous?.sharing?.entry?.sessionId !== next.sharing?.entry?.sessionId || previous?.sharing?.entry?.lifecycleRevision !== next.sharing?.entry?.lifecycleRevision) topologyRevision += 1;
		if (next.sharing?.entry) entries.set(next.sessionKey, next);
		else entries.delete(next.sessionKey);
		unavailable.delete(facts.sessionKey);
	};
	const { claim, captureSnapshot, captureStoreSnapshot, captureRead, deadlines } = createIncognitoSessionClaims({
		identity,
		assertReadable: assertAdmittedCurrent,
		current,
		readTopologyRevision: () => topologyRevision,
		readSnapshotRevision: () => snapshotRevision,
		hasUnsettledFacts: () => pending.size > 0 || unavailable.size > 0,
		entries,
		withGrant
	});
	return {
		captureRead,
		clear() {
			entries.clear();
			pending.clear();
			unavailable.clear();
			topologyRevision += 1;
			snapshotRevision += 1;
		},
		bind(run, assertBorrowed, retain, assertAuthority) {
			const perform = (requestAuthority, command, changing, receive, signal, companion, cleanup = false, publication, restrict, onCommitted, onCommittedWithoutReply, attachment) => {
				const authority = cleanup ? requestAuthority : retainIncognitoSessionAuthority(assertAuthority, requestAuthority);
				const captured = structuredClone(command);
				const targets = /* @__PURE__ */ new Set();
				let native;
				let postimage;
				const commandGrant = grants.command(captured.type, authority.entryCreation);
				let commitGranted = false;
				function unknownOutcome(message) {
					for (const key of targets) unavailable.add(key);
					throw new SqliteWorkerError(message, "outcome-unknown");
				}
				return run(authority, async (scope) => {
					assertActorCurrent();
					let outcome;
					try {
						outcome = {
							ok: true,
							value: await scope.execute(captured)
						};
					} catch (error) {
						outcome = {
							ok: false,
							error
						};
					}
					try {
						if (native) {
							const settlement = await native.retained.settled;
							const committed = native.admission.committed?.facts;
							const recovered = committed !== void 0 ? publication?.decodeReceipt(committed) : void 0;
							const receipt = recovered?.facts ?? committed;
							const receiptMatches = receipt !== void 0 && postimage !== void 0 && isDeepStrictEqual(receipt, postimage);
							const companionOutcome = receiptMatches ? "committed" : receipt === void 0 && (settlement.kind === "not-entered" || native.admission.settlement?.kind === "completed" && !commitGranted && !outcome.ok) ? "rolled-back" : "unknown";
							try {
								if (receipt !== void 0) {
									if (!postimage || !isDeepStrictEqual(receipt, postimage)) unknownOutcome("Incognito commit receipt differs from its grant");
									postimage.forEach(install);
									for (const key of targets) pending.delete(key);
									if (native.admission.settlement?.kind === "completed") {
										const committedValue = recovered ?? (outcome.ok ? outcome.value : void 0);
										if (committedValue) onCommitted?.(committedValue);
										else onCommittedWithoutReply?.(postimage);
									}
								} else if (changing && (commitGranted || outcome.ok)) unknownOutcome("Incognito mutation has no confirmed commit receipt");
								if (settlement.kind !== "not-entered" && native.admission.settlement?.kind !== "completed") unknownOutcome("Incognito session native settlement is unknown");
								if (recovered && receiptMatches) outcome = {
									ok: true,
									value: recovered
								};
							} finally {
								companion?.settle(companionOutcome);
							}
						}
						if (!outcome.ok) throw outcome.error;
						const value = outcome.value;
						if (!changing) {
							withGrant(() => {
								authority.assertCurrent();
								assertActorCurrent();
								for (const facts of value.facts) authorizeSessionFacts(authority, "commit", facts);
								authority.assertCurrent();
								assertActorCurrent();
							});
							value.facts.forEach(install);
						}
						for (const key of targets) pending.delete(key);
						authority.assertCurrent();
						assertActorCurrent();
						return receive(value);
					} finally {
						for (const key of targets) pending.delete(key);
					}
				}, signal, (retained) => {
					let phase = "prepare";
					let entryGuarded;
					const authorize = (requested, grant) => commandGrant.run(() => {
						const request = restrict ? restrict(requested) : requested;
						authority.assertCurrent();
						assertActorCurrent();
						signal?.throwIfAborted();
						if (request.stage === "open" || !isRecord(request.facts) || !isDeepStrictEqual(request.facts.identity, identity)) throw new Error("Incognito session operation belongs to another actor");
						if (request.stage === "prepare" && request.facts.entry !== void 0) {
							if (phase !== "transaction" || !publication?.prepare) throw new Error("Incognito entry publication requested out of order");
							publication.prepare(request.facts.entry);
						}
						if (request.stage !== "prepare" || !changing && request.facts.sessions !== void 0) {
							if (changing ? !(phase === "prepare" && request.stage === "transaction" || phase === "transaction" && request.stage === "commit" || isIncognitoEntryValidationGrant(captured.type, phase, request, entryGuarded)) : request.stage !== "prepare") throw new Error("Incognito session authority requested out of order");
							const facts = readIncognitoGrantFacts(request.facts.sessions ?? (request.stage === "commit" && publication?.factsKey === "entry" ? publication.decodeReceipt(request.facts.entry).facts : void 0), identity, captured, request.stage === "commit" ? targets : void 0);
							commandGrant.capture(request.stage, facts);
							for (const entry of facts) {
								targets.add(entry.sessionKey);
								if (changing) pending.add(entry.sessionKey);
							}
							for (const entry of facts) authorizeSessionFacts(authority, request.stage === "prepare" ? "transaction" : request.stage, entry);
							publication?.authorize(request.stage === "prepare" ? "transaction" : request.stage, publication.factsKey === "entry" ? request.facts.entry : request.facts.pendingInput);
							if (request.stage === "commit") {
								postimage = facts;
								companion?.beforeCommit();
							}
							phase = request.stage;
							entryGuarded = isRecord(request.facts.entry) ? request.facts.entry.guarded : void 0;
						}
						authority.assertCurrent();
						assertActorCurrent();
						signal?.throwIfAborted();
						if (!grant()) throw new Error("Incognito session authority expired");
						commitGranted ||= request.stage === "commit";
					});
					const admission = createSqliteWorkerOperationAdmission(authorize, attachment);
					native = {
						retained,
						admission
					};
					return {
						nativeLocations: [],
						admission
					};
				}, cleanup);
			};
			return {
				...bindIncognitoSessionHistory({
					assertOutsideGrant,
					assertBorrowed,
					assertActorCurrent,
					retain,
					current: (key) => grants.readSource(key) ?? current(key),
					execute: (authority, command, signal, cleanup, onRead) => perform(authority, command, false, (result) => {
						onRead?.(result.value);
						return result.value;
					}, signal, void 0, cleanup)
				}),
				entry: (authority, command, signal, onCommitted, onRead, authorizePrepared, authorizePublication) => perform(authority, command, command.type.endsWith(".commit"), (result) => {
					onRead?.(result.value);
					return result.value;
				}, signal, void 0, false, incognitoEntryPublication(command.type, authorizePrepared, authorizePublication), void 0, onCommitted ? (result) => onCommitted(result.value) : void 0),
				/** Join a shared-owner composition without holding this actor's FIFO turn. */
				withSharedState(operation) {
					assertOutsideGrant();
					assertBorrowed();
					return retain(operation);
				},
				captureSnapshot: (sessionKey) => captureSnapshot(sessionKey, assertBorrowed),
				withCompute: (authority, target, operation, signal, onRead) => {
					assertOutsideGrant();
					assertBorrowed();
					const capturedTarget = structuredClone(target);
					return retain(() => withIncognitoCompute({
						target: capturedTarget,
						assertAuthority: () => authority.assertCurrent(),
						assertBorrowed,
						captureClaim: (sessionKey, facts) => claim(sessionKey, assertBorrowed, facts),
						authorize: (held) => held.authorize(authority, "commit"),
						operation,
						execute: (command, observeFacts, requestSignal) => perform(authority, command, isIncognitoComputeWrite(command.type), (result) => {
							observeFacts(result.facts);
							if (!isIncognitoComputeWrite(command.type)) onRead?.(result.facts);
							return result.value;
						}, signal && requestSignal ? AbortSignal.any([signal, requestSignal]) : requestSignal ?? signal),
						cleanup: (command) => perform({ assertCurrent: assertActorCurrent }, command, isIncognitoComputeWrite(command.type), (result) => result.value, void 0, void 0, true)
					}));
				},
				read: (authority, input, signal) => {
					const sessionKey = input.sessionKey;
					return perform(authority, {
						type: "session.entry.read",
						input
					}, false, (value) => ({
						entry: value.entry,
						claim: claim(sessionKey, assertBorrowed, value.facts[0]),
						snapshot: captureSnapshot(sessionKey, assertBorrowed)
					}), signal);
				},
				create: (authority, input, signal) => {
					const sessionKey = input.sessionKey;
					return perform(authority, {
						type: "session.entry.create",
						input
					}, true, (value) => ({
						entry: value.entry,
						claim: claim(sessionKey, assertBorrowed, value.facts[0])
					}), signal);
				},
				...bindIncognitoSessionStoreReads((authority, command, signal) => perform(authority, command, false, (result) => ({
					...result,
					snapshot: captureStoreSnapshot(assertBorrowed, authority)
				}), signal)),
				readRow(authority, sessionKey) {
					return perform(authority, {
						type: "session.row.read",
						input: { sessionKey }
					}, false, (result) => ({
						value: result.value,
						snapshot: captureStoreSnapshot(assertBorrowed, authority)
					}));
				},
				acpSource(authority, sessionKey) {
					return perform(authority, {
						type: "session.acp.source",
						input: { sessionKey }
					}, false, (result) => ({
						snapshot: result.value,
						claim: claim(sessionKey, assertBorrowed, result.facts[0])
					}));
				},
				sideData: (authority, command, signal, publish, invalidate, attachment) => perform(authority, command, isIncognitoSideDataWrite(command.type), (result) => result.value, signal, void 0, false, void 0, void 0, publish ? (result) => publish(result.value) : void 0, invalidate, attachment),
				readPendingInput(authority, input) {
					return perform(authority, {
						type: "session.pendingInputs.read",
						input
					}, false, (result) => result.value);
				},
				mutatePendingInput(authority, input, admitCustody, publish) {
					const captured = structuredClone(input);
					return perform(authority, {
						type: "session.pendingInputs.mutate",
						input: captured
					}, true, (result) => result.value, void 0, void 0, false, createIncognitoPendingInputSettlement(captured, admitCustody), void 0, publish);
				},
				interruptPendingInputHistory(authority, input, admitCustody) {
					const captured = structuredClone(input);
					return perform(authority, {
						type: "session.pendingInputs.interruptHistory",
						input: captured
					}, true, (result) => result.value, void 0, void 0, false, createIncognitoPendingInputHistorySettlement(captured, admitCustody));
				},
				transcript: (authority, command, signal, restrict, onCommitted, onRead, authorizePrepared) => perform(authority, command, isIncognitoTranscriptWrite(command.type), (result) => {
					onRead?.(result.value);
					return result.value;
				}, signal, void 0, false, isIncognitoTranscriptReceiptCommand(command.type) ? incognitoEntryPublication(command.type, authorizePrepared) : void 0, restrict, onCommitted ? (result) => onCommitted(result.value) : void 0),
				outbox: (authority, command, signal) => perform(authority, command, true, (result) => result.value, signal),
				lifecycle: (authority, command, signal, captureLifecycle, onCommitted) => {
					assertBorrowed();
					authority.assertCurrent();
					const captured = structuredClone(command);
					return perform(authority, captured, isIncognitoLifecycleWrite(command.type), (result) => result.value, signal, captureIncognitoLifecycleSettlement(captured.input, captureLifecycle), false, captured.type === "session.lifecycle.messageCut" || captured.type === "session.lifecycle.maintenance" ? incognitoEntryPublication(captured.type) : void 0, void 0, onCommitted ? (result) => onCommitted(result.value) : void 0);
				},
				...captureRead(assertBorrowed),
				/** Only this command's validated transaction preimage can authorize its own creation. */
				readCreationGrant(sessionKey, operation) {
					assertBorrowed();
					return grants.readCreation(sessionKey, operation);
				},
				deadlines: () => deadlines(assertBorrowed, assertAdmittedCurrent)
			};
		}
	};
}
//#endregion
//#region src/config/sessions/session-incognito-lifecycle.ts
/** Source preparation settles before reserving the destination actor, including cross-agent forks. */
async function forkIncognitoSessionFromParent(params) {
	const { source, destination, sourceAuthority, destinationAuthority, signal, forkFrom, buildEntry, supportsCliSessionFork } = params;
	source.assertCurrent();
	destination.assertCurrent();
	sourceAuthority.assertCurrent();
	destinationAuthority.assertCurrent();
	const parent = structuredClone(params.parent);
	const childSessionKey = params.childSessionKey;
	const sourceClaim = source.sessions.captureCurrent(parent.sessionKey);
	const sameActor = source.identity.handle === destination.identity.handle && source.identity.incarnation === destination.identity.incarnation;
	return source.sessions.withSharedState(() => destination.sessions.withSharedState(async () => {
		const prepared = await source.sessions.lifecycle(sourceAuthority, {
			type: "session.lifecycle.fork.prepare",
			input: {
				parent,
				forkFrom
			}
		}, signal);
		sourceClaim.assertCurrent();
		destination.assertCurrent();
		if (!prepared) return;
		const child = await destination.sessions.read(destinationAuthority, { sessionKey: childSessionKey }, signal);
		sourceClaim.assertCurrent();
		const entry = await buildEntry(structuredClone(parent.entry), structuredClone(child.entry));
		const cliSessionBindings = forkCliSessionBindings(parent.entry, supportsCliSessionFork);
		sourceClaim.assertCurrent();
		child.claim.assertCurrent();
		return destination.sessions.lifecycle({
			assertCurrent() {
				source.assertCurrent();
				destination.assertCurrent();
				sourceAuthority.assertCurrent();
				destinationAuthority.assertCurrent();
				if (!sameActor) sourceClaim.assertCurrent();
			},
			authorize(stage, facts) {
				if (!sameActor) sourceClaim.authorize(sourceAuthority, stage);
				if (sameActor && facts.sessionKey === parent.sessionKey) return sourceAuthority.authorize?.(stage, facts);
				return destinationAuthority.authorize?.(stage, facts);
			}
		}, {
			type: "session.lifecycle.fork",
			input: {
				parent: prepared,
				child: {
					sessionKey: childSessionKey,
					entry,
					expectedEntry: child.entry
				},
				cliSessionBindings
			}
		}, signal);
	}));
}
//#endregion
//#region src/state/openclaw-agent-execution-incognito-absence.ts
/** Only active consumer scopes are retained; the execution owner supplies namespace occupancy. */
function createIncognitoAbsenceScopes(isOccupied) {
	const sources = /* @__PURE__ */ new Set();
	return {
		revoke(pathname) {
			for (const source of sources) if (source.path === pathname) source.revoke();
		},
		capture(options, authority) {
			const agentId = normalizeAgentId(options.agentId);
			const env = {
				...options.env,
				OPENCLAW_STATE_DIR: resolveStateDir(options.env)
			};
			const pathname = resolveIncognitoOpenClawAgentSqlitePath({
				agentId,
				env
			});
			let active = true;
			const assertCurrent = () => {
				authority.assertCurrent();
				if (!active || isOccupied(pathname)) throw new Error("Incognito session absence changed; prepare the source again");
			};
			assertCurrent();
			const source = {
				path: pathname,
				revoke() {
					active = false;
				}
			};
			sources.add(source);
			return {
				agentId,
				path: pathname,
				env,
				assertCurrent,
				release() {
					source.revoke();
					sources.delete(source);
				}
			};
		}
	};
}
//#endregion
//#region src/state/openclaw-agent-execution-incognito.ts
/** Lifetime implementation for the existing executor's namespace map, never a second registry. */
function createIncognitoAgentExecutionOwner(options, authority, lifecycle, signal) {
	const context = captureOpenClawStateReadWorkerContext({ env: options.env });
	const assertAgent = captureAgentDatabaseAdmission(options.agentId, { env: context.environment });
	const identity = Object.freeze({
		kind: "ephemeral",
		handle: randomUUID(),
		incarnation: randomUUID()
	});
	const input = {
		kind: "ephemeral",
		identity,
		agentId: options.agentId,
		databasePath: options.path,
		environment: context.environment
	};
	let state = "opening";
	let published = false;
	let pendingBorrows = 0;
	let loss;
	let store;
	let opening;
	let openingFailed = false;
	let closing;
	let nativeStopped;
	let unregisterShared;
	let releaseShared;
	const pending = /* @__PURE__ */ new Set();
	const continuations = new AsyncLocalStorage();
	const assertRetainedCurrent = () => {
		if (loss || state === "closed") throw loss ?? new IncognitoSessionEndedError();
		lifecycle.assertOwned();
		context.admission.assertCurrent();
		assertAgent();
		if (cache.databases.has(options.path) || cache.pending.has(options.path)) throw new Error("Incognito namespace already belongs to the native owner");
		if (store && !isSqliteWorkerStoreAvailable(store)) throw new IncognitoSessionEndedError();
	};
	const assertCurrent = () => {
		if (state === "closing") throw new IncognitoSessionEndedError();
		assertRetainedCurrent();
	};
	let granting = false;
	const withGrant = (operation) => {
		const wasGranting = granting;
		granting = true;
		try {
			return operation();
		} finally {
			granting = wasGranting;
		}
	};
	const assertOutsideGrant = () => {
		if (granting) throw new Error("Incognito authority callbacks cannot call their actor");
	};
	const sessionFacts = createIncognitoSessionFacts(identity, assertRetainedCurrent, withGrant, assertOutsideGrant, assertCurrent);
	const admission = (source) => () => ({
		nativeLocations: [],
		admission: createSqliteWorkerOperationAdmission((request, grant) => withGrant(() => {
			source.assertCurrent();
			assertRetainedCurrent();
			const expected = request.stage === "open" ? input : { identity };
			if (!isDeepStrictEqual(request.facts, expected) || request.stage !== "open" && request.stage !== "prepare") throw new Error("Incognito operation differs from its admitted actor");
			if (!grant()) throw new Error("Incognito actor admission was refused");
		}))
	});
	const track = (work, collection = pending) => {
		collection.add(work);
		work.finally(() => collection.delete(work)).catch(() => void 0);
		return work;
	};
	const drain = async (collection) => {
		while (collection.size > 0) await Promise.allSettled(collection);
	};
	const open = () => {
		opening ??= Promise.resolve().then(async () => {
			authority.assertCurrent();
			assertCurrent();
			signal?.throwIfAborted();
			assertIncognitoAgentDatabasePathAvailable(options.path);
			const opened = await openEphemeralAgentDatabaseSqliteWorkerStore({
				moduleUrl: resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.agentDatabaseExecution),
				databasePath: options.path,
				target: identity,
				input
			}, {
				assertCurrent() {
					authority.assertCurrent();
					assertCurrent();
					signal?.throwIfAborted();
				},
				createAdmission: admission(authority),
				signal,
				onNativeLost(error) {
					loss ??= new IncognitoSessionEndedError({ cause: error });
					state = "lost";
					sessionFacts.clear();
				},
				onNativeStopped(stopped) {
					nativeStopped = stopped;
				}
			});
			if (!opened) throw new Error("Incognito actor was not created");
			store = opened;
			authority.assertCurrent();
			assertCurrent();
			signal?.throwIfAborted();
			return opened;
		}).catch((error) => {
			openingFailed = true;
			throw error;
		});
		return opening;
	};
	const owner = {
		kind: "ephemeral",
		agentId: options.agentId,
		identity,
		facts: sessionFacts.captureRead(assertCurrent),
		assertCurrent,
		get state() {
			return state;
		},
		canRetryOpening() {
			if (!openingFailed || state !== "closed") return false;
			let sourceRefused = signal?.aborted === true;
			if (!sourceRefused) try {
				authority.assertCurrent();
			} catch {
				sourceRefused = true;
			}
			if (!sourceRefused) return false;
			context.admission.assertCurrent();
			assertAgent();
			return true;
		},
		async borrow(source, borrowSignal) {
			pendingBorrows += 1;
			let opened;
			try {
				source.assertCurrent();
				borrowSignal?.throwIfAborted();
				opened = await open();
				source.assertCurrent();
				assertCurrent();
				borrowSignal?.throwIfAborted();
			} catch (error) {
				pendingBorrows -= 1;
				if (!published && (openingFailed || pendingBorrows === 0)) try {
					await owner.close();
				} catch (cleanupError) {
					throw createSqliteLifecycleAggregateError([error, cleanupError], "Incognito admission and cleanup failed", error);
				}
				throw error;
			}
			pendingBorrows -= 1;
			published = true;
			state = "live";
			let released = false;
			let releasing;
			const borrowedWork = /* @__PURE__ */ new Set();
			const borrow = {};
			const assertReferenceCurrent = () => {
				assertCurrent();
				source.assertCurrent();
				if (released) throw new Error("Incognito execution reference is released");
			};
			const assertBorrowed = () => {
				const current = continuations.getStore();
				if (current?.borrow === borrow && current.active) {
					assertRetainedCurrent();
					source.assertCurrent();
				} else assertReferenceCurrent();
			};
			const retain = (operation, kind = "composition") => {
				const parent = continuations.getStore();
				const continuation = {
					borrow,
					active: true
				};
				const completion = createDeferredCore();
				const work = track(track(completion.promise), borrowedWork);
				const execute = () => continuations.run(continuation, async () => {
					try {
						const result = await operation();
						if (kind === "cleanup" || parent?.borrow === borrow && parent.active) assertRetainedCurrent();
						else if (kind === "command") assertCurrent();
						else assertReferenceCurrent();
						return result;
					} finally {
						continuation.active = false;
					}
				});
				(kind === "composition" ? Promise.resolve().then(execute) : execute()).then(completion.resolve, completion.reject);
				return work;
			};
			const run = (currentAuthority, operation, operationSignal, createAdmission, cleanup = false) => {
				assertOutsideGrant();
				currentAuthority.assertCurrent();
				if (cleanup) assertRetainedCurrent();
				else assertBorrowed();
				const assertOperation = () => {
					if (!cleanup) source.assertCurrent();
					currentAuthority.assertCurrent();
					assertRetainedCurrent();
					operationSignal?.throwIfAborted();
				};
				return retain(() => runOpenClawAgentWorkerWrite({
					target: identity,
					assertCurrent: assertOperation
				}, async () => {
					try {
						const result = await runSqliteWorkerStoreOperation(opened, operation, void 0, assertOperation, createAdmission ?? admission({ assertCurrent: assertOperation }));
						assertOperation();
						return result;
					} catch (error) {
						if (loss || !isSqliteWorkerStoreAvailable(opened)) {
							await nativeStopped;
							throw loss ?? new IncognitoSessionEndedError({ cause: error });
						}
						throw error;
					}
				}, void 0, operationSignal), cleanup ? "cleanup" : "command");
			};
			const execution = {
				agentId: options.agentId,
				path: options.path,
				identity,
				sessions: sessionFacts.bind(run, assertBorrowed, retain, () => source.assertCurrent()),
				acp: {
					prepareEntryRead(params) {
						const readAuthority = params.authority;
						const env = cloneEnvWithPlatformSemantics(params.env);
						env.OPENCLAW_STATE_DIR = resolveStateDir(env);
						const shared = captureOpenClawStateReadWorkerContext({
							env,
							path: params.databasePath ? path.resolve(params.databasePath) : void 0
						});
						const readInput = {
							signal: params.signal,
							cfg: captureRuntimeConfigWithSource(params.cfg, params.cfg),
							sessionKey: params.sessionKey,
							env,
							databasePath: shared.admission.databasePath,
							storePath: resolveSessionStorePathCore(params.cfg.session?.store, {
								agentId: execution.agentId,
								env
							})
						};
						const assertReadCurrent = () => {
							execution.assertCurrent();
							readAuthority.assertCurrent();
							shared.maintenanceScope?.assertAdmission();
							shared.admission.assertCurrent();
						};
						assertReadCurrent();
						return execution.sessions.withSharedState(async () => {
							const { prepareIncognitoAcpSessionEntryRead } = await import("./session-meta-worker-mutation-DjqtW9NW.mjs");
							readInput.signal?.throwIfAborted();
							assertReadCurrent();
							return prepareIncognitoAcpSessionEntryRead({
								...readInput,
								actor: execution,
								authority: {
									assertCurrent: assertReadCurrent,
									authorize: (stage, facts) => readAuthority.authorize?.(stage, facts)
								}
							});
						});
					},
					readEntry(params) {
						return execution.sessions.withSharedState(async () => {
							const { readIncognitoAcpSessionEntry } = await import("./session-meta-worker-mutation-DjqtW9NW.mjs");
							return readIncognitoAcpSessionEntry({
								...params,
								actor: execution
							});
						}).then((entry) => {
							params.authority.assertCurrent();
							execution.assertReadable();
							return entry;
						});
					},
					upsertMeta(params) {
						return execution.sessions.withSharedState(async () => {
							const { upsertIncognitoAcpSessionMeta } = await import("./session-meta-worker-mutation-DjqtW9NW.mjs");
							return upsertIncognitoAcpSessionMeta({
								...params,
								actor: execution
							});
						}).then((entry) => {
							params.authority.assertCurrent();
							execution.assertReadable();
							return entry;
						});
					}
				},
				assertCurrent: assertBorrowed,
				assertReadable: assertReferenceCurrent,
				release() {
					released = true;
					releasing ??= drain(borrowedWork);
					return releasing;
				},
				close: () => owner.close()
			};
			return execution;
		},
		close() {
			if (state === "closed") return Promise.resolve();
			if (!loss) state = "closing";
			closing ??= (async () => {
				await drain(pending);
				await opening?.catch(() => void 0);
				sessionFacts.clear();
				await store?.close();
				await nativeStopped;
				continuations.disable();
				state = "closed";
				unregister();
				unregisterShared?.();
				releaseShared?.();
				lifecycle.retired();
			})().catch((error) => {
				closing = void 0;
				throw error;
			});
			return closing;
		}
	};
	const unregister = registerOpenClawAgentDatabaseAsyncResource({
		agentId: options.agentId,
		path: options.path,
		revoke() {
			if (!loss) state = "closing";
		},
		close: () => owner.close()
	});
	try {
		releaseShared = retainIncognitoSharedState(context.environment);
		unregisterShared = registerOpenClawStateDatabaseAsyncResource({ close: async (sharedIdentity) => {
			if (!sharedIdentity || sharedIdentity.key === context.admission.identity.key) await owner.close();
		} });
	} catch (error) {
		continuations.disable();
		releaseShared?.();
		unregister();
		throw error;
	}
	return owner;
}
/** Bind ephemeral lifetime to the canonical execution owner map, without a parallel registry. */
function createAgentDatabaseExecutionCapture(executions, captureFile) {
	const absentSources = createIncognitoAbsenceScopes((pathname) => executions.get(pathname) !== void 0);
	/** Inactive actor entry point. Production incognito routing stays native until P7. */
	async function openIncognitoAgentDatabaseExecution(options, authority, request = {}) {
		authority.assertCurrent();
		const { existingOnly, signal } = request;
		signal?.throwIfAborted();
		const capturedOptions = {
			...options,
			env: {
				...options.env ?? process.env,
				OPENCLAW_STATE_DIR: resolveStateDir(options.env ?? process.env)
			}
		};
		const agentId = normalizeAgentId(capturedOptions.agentId);
		const pathname = resolveIncognitoOpenClawAgentSqlitePath({
			...capturedOptions,
			agentId
		});
		let owner = executions.get(pathname);
		if (owner && owner.kind !== "ephemeral") throw new Error("Incognito namespace belongs to a file execution owner");
		if (existingOnly && (!owner || owner.state === "opening")) return;
		if (owner && (owner.state === "lost" || owner.state === "closed") && !existingOnly) {
			await owner.close();
			authority.assertCurrent();
			signal?.throwIfAborted();
			return openIncognitoAgentDatabaseExecution(capturedOptions, authority, {
				existingOnly,
				signal
			});
		}
		const joinedOpening = owner?.state === "opening";
		if (!owner) {
			const created = createIncognitoAgentExecutionOwner({
				...capturedOptions,
				agentId,
				path: pathname
			}, authority, {
				assertOwned() {
					if (executions.get(pathname) !== created) throw new Error("Incognito execution no longer owns its namespace");
				},
				retired() {
					if (executions.get(pathname) === created) executions.delete(pathname);
				}
			}, signal);
			absentSources.revoke(pathname);
			executions.set(pathname, created);
			owner = created;
		}
		try {
			return await owner.borrow(authority, signal);
		} catch (error) {
			if (!joinedOpening) throw error;
			authority.assertCurrent();
			signal?.throwIfAborted();
			if (!owner.canRetryOpening()) throw error;
			return openIncognitoAgentDatabaseExecution(capturedOptions, authority, request);
		}
	}
	function capture(target, constraints) {
		if (target.kind === "ephemeral") return openIncognitoAgentDatabaseExecution({
			agentId: target.agentId,
			env: target.env
		}, target.authority, {
			existingOnly: target.existingOnly,
			signal: target.signal
		});
		return captureFile(target, constraints);
	}
	return Object.assign(capture, {
		forkIncognitoSessionFromParent,
		captureIncognitoAbsence: absentSources.capture,
		/** Inactive topology view; production discovery continues to use the native owner. */
		listIncognito(env = process.env) {
			const capturedEnv = {
				...env,
				OPENCLAW_STATE_DIR: resolveStateDir(env)
			};
			return [...executions.entries()].flatMap(([pathname, owner]) => {
				if (owner.kind !== "ephemeral" || owner.state !== "live" || pathname !== resolveIncognitoOpenClawAgentSqlitePath({
					agentId: owner.agentId,
					env: capturedEnv
				})) return [];
				owner.assertCurrent();
				return [{
					agentId: owner.agentId,
					storePath: pathname,
					identity: owner.identity,
					facts: owner.facts,
					assertCurrent: owner.assertCurrent
				}];
			});
		}
	});
}
//#endregion
//#region src/state/openclaw-agent-execution-config.ts
/** Retire captured physical routing when the committed roster or storage locator changes. */
function watchAgentDatabaseExecutionConfig(agentId, env, retire) {
	const config = getRuntimeConfigSnapshot();
	if (!config || !listAgentIds(config).includes(agentId)) return () => {};
	const agentDir = resolveEffectiveAgentDir(config, agentId, { env });
	const storePath = resolveSessionStorePathCore(config.session?.store, {
		agentId,
		env
	});
	return sessionChanges.subscribeFacts((change) => {
		if (!("all" in change) || change.scope !== "config") return;
		const current = getRuntimeConfigSnapshot();
		if (current && (!listAgentIds(current).includes(agentId) || resolveEffectiveAgentDir(current, agentId, { env }) !== agentDir || resolveSessionStorePathCore(current.session?.store, {
			agentId,
			env
		}) !== storePath)) retire();
	});
}
//#endregion
//#region src/state/agent-deletion-cleanup-admission.ts
/** Bind the request's cleanup owner, including accepted native work, before transferring a grant. */
function captureAgentDeletionCleanupAdmission(options, operation, assertSourceCurrent) {
	const cleanup = getAgentDeletionDatabaseCleanup(options);
	if (!cleanup?.worker) return;
	const worker = cleanup.worker;
	cleanup.assertCurrentHost();
	return {
		guard: worker.guard,
		assertCurrent: cleanup.assertCurrentHost,
		authorize(request) {
			const facts = request.facts;
			if (request.stage !== "prepare" || !isRecord(facts) || facts.kind !== "agent-deletion-current" && facts.kind !== "agent-deletion-lease") return false;
			assertSourceCurrent();
			cleanup.assertCurrentHost();
			if (!isDeepStrictEqual(facts.guard, worker.guard)) throw new Error("Agent deletion request differs from its live cleanup owner");
			if (facts.kind === "agent-deletion-lease") {
				if (!(facts.port instanceof MessagePort)) throw new Error("Agent deletion lost its lease admission handoff port");
				const leased = worker.lease.createAdmission(operation);
				try {
					facts.port.postMessage(leased.admission.port, [leased.admission.port]);
					operation.settled.then(() => leased.admission.finish());
				} catch (error) {
					leased.admission.finish();
					throw error;
				} finally {
					facts.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(params) {
	params.assertOwned();
	await params.stopped;
	params.assertOwned();
	const refusedBeforeAgentOpen = params.readOpenRefused?.() === true;
	if (params.closed?.()) {
		assertExistingDatabaseIdentity(params.lease.sharedStatePath, params.lease.sharedStateIdentity);
		return;
	}
	const observed = await readDatabasePathIdentity(params.lease.sharedStatePath);
	if (observed.key !== params.lease.sharedStateIdentity) throw new Error("Retired agent cleanup cannot adopt a replacement shared database");
	params.assertOwned();
	if (!refusedBeforeAgentOpen) invalidateOpenClawAgentDatabaseValidation(params.lease.path);
	const context = {
		environment: params.context.environment,
		existingSchemaPath: params.context.existingSchemaPath,
		stateIntegrity: params.context.stateIntegrity
	};
	const store = await openOpenClawStateWorkerCleanupStore(params.lease.sharedStatePath, context, () => params.assertOwned(), observed, params.context.maintenanceScope).catch((error) => {
		if (error instanceof Error) {
			error.message += ` (leaseId=${params.lease.leaseId}, path=${params.lease.path})`;
			error.stack = `${error.name}: ${error.message}\n${error.stack ?? ""}`;
		}
		throw error;
	});
	if (!store) throw new Error("Retired agent cleanup lost its original shared database");
	const errors = [];
	try {
		await runSqliteWorkerStoreOperation(store, (scope) => scope.execute({
			type: "agentDatabases.releaseExitedLease",
			input: {
				...params.lease,
				outcome: refusedBeforeAgentOpen ? "refused-before-open" : "unknown"
			}
		}), context, () => params.assertOwned(), () => ({
			nativeLocations: [params.lease.sharedStatePath],
			admission: createSqliteWorkerOperationAdmission((request, grant) => {
				params.assertOwned();
				if (request.stage === "prepare" && request.facts === "agent-integrity-invalidated") invalidateOpenClawAgentDatabaseValidation(params.lease.path);
				grant();
			})
		}));
	} catch (error) {
		errors.push(error);
	}
	try {
		await store.close();
	} catch (error) {
		errors.push(error);
	}
	throwSqliteLifecycleErrors(errors, "Retired agent lease cleanup and Worker close failed");
}
/** Native closure is reusable only for the exact incarnation and original worker lease. */
function readAgentDatabaseClosedReceipt(receipt, identity, lease) {
	if (!receipt || !identity || !lease || receipt.incarnation !== identity.incarnation || receipt.identity.key !== `file:${identity.physicalIdentity}` || receipt.identity.canonicalPath !== identity.nativeLocation) return;
	return {
		receipt,
		identity,
		lease
	};
}
function publishAgentDatabaseCloseCheckpoint(pathname, closed, assertCleanupOwned) {
	if (!closed) return;
	const { receipt, identity, lease } = closed;
	try {
		assertCleanupOwned();
		assertExistingDatabaseIdentity(pathname, receipt.identity.key);
		assertExistingDatabaseIdentity(identity.nativeLocation, receipt.identity.key);
		assertExistingDatabaseIdentity(lease.sharedStatePath, lease.sharedStateIdentity);
		publishSqliteWalCheckpointObservation(pathname, receipt.checkpoint);
	} catch {}
}
//#endregion
//#region src/state/openclaw-agent-native-stop-observation.ts
function createAgentNativeStopObservation() {
	let stopped;
	let readCloseReceipt;
	let readOpenRefused;
	return {
		observe: (nextStopped, nextReadCloseReceipt, nextReadOpenRefused) => {
			stopped = nextStopped;
			readCloseReceipt = nextReadCloseReceipt;
			readOpenRefused = nextReadOpenRefused;
		},
		get stopped() {
			return stopped;
		},
		get readCloseReceipt() {
			return readCloseReceipt;
		},
		get readOpenRefused() {
			return readOpenRefused;
		}
	};
}
//#endregion
//#region src/state/openclaw-agent-registration-observer.ts
/** Observe a witnessed registration commit without reopening revoked admission. */
function createAgentRegistrationCommitObserver(context) {
	return (request) => {
		const registration = context.getRegistration();
		const lease = context.getLease();
		const facts = request.facts;
		if (request.stage === "prepare" && isRecord(facts) && facts.kind === "agent-registration-committed") {
			const received = facts.registration;
			if (!registration || !lease || !isRecord(received) || received.agentId !== context.agentId || received.agentPath !== context.pathname || received.stateDatabasePath !== lease.sharedStatePath || received.stateDatabaseIdentity !== lease.sharedStateIdentity) throw new Error("Agent registration commit differs from its admitted native owner");
			registration.recordCommitted({
				agentId: context.agentId,
				agentPath: context.pathname,
				stateDatabasePath: lease.sharedStatePath,
				stateDatabaseIdentity: lease.sharedStateIdentity
			});
		}
	};
}
//#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(agentId, pathname, context, assertLogicalCurrent, assertCleanupOwned, expectedIdentity, acceptFileIdentity, retainVerification, creatingIdentity, creationClaim) {
	const input = {
		leaseId: randomUUID(),
		agentId,
		databasePath: pathname,
		stateDatabasePath: context.admission.databasePath,
		environment: context.environment,
		...expectedIdentity ? { expectedIdentity } : {},
		...creatingIdentity ? { creatingIdentity } : {},
		...creationClaim ? { creationClaim } : {}
	};
	let retiring = false, preparationPublished = false;
	let opening;
	let openedStore;
	let openingFailure;
	let closedOpeningRefusal;
	let openingAdmission;
	let closing;
	let nativeIdentity;
	const nativeStop = createAgentNativeStopObservation();
	let lease;
	let integrityCheckPending;
	let assertIntegrityVerifierCurrent;
	const assertCurrent = () => {
		assertLogicalCurrent();
		if (retiring) throw new Error("Agent native generation is retiring");
		if (openedStore && !isSqliteWorkerStoreAvailable(openedStore)) throw new Error("Agent database execution lost its native owner");
	};
	const admission = (source, registration, assertCallerCurrent) => (operation) => {
		let receiveValidation = registration ? captureOpenClawAgentDatabaseAdmissionPublication({
			agentId,
			path: pathname
		}) : void 0;
		if (registration) registration.nativeSettlement = operation.settled;
		const assertPreparationJournal = captureAgentDatabasePreparationJournal(agentId, { env: context.environment });
		const nativeLocations = [
			pathname,
			...nativeIdentity ? [nativeIdentity.nativeLocation] : [],
			context.admission.databasePath,
			context.admission.identity.canonicalPath
		];
		const assertSourceCurrent = (identity) => {
			source.assertCurrent();
			assertCurrent();
			assertIntegrityVerifierCurrent?.();
			assertCallerCurrent?.(identity);
			if (identity) assertExistingDatabaseIdentity(pathname, `file:${identity.physicalIdentity}`, identity.birthtime);
		};
		const cleanup = captureAgentDeletionCleanupAdmission({
			agentId,
			path: pathname,
			env: context.environment
		}, operation, assertSourceCurrent);
		const authorizeStartupFts = createAgentDatabaseStartupFtsAdmission({
			pathname,
			sharedStatePath: context.admission.databasePath,
			expectedIdentity,
			assertCurrent: assertSourceCurrent,
			assertPreparationJournal,
			getLease: () => lease
		});
		const observeNative = createAgentRegistrationCommitObserver({
			agentId: input.agentId,
			pathname,
			getRegistration: () => registration,
			getLease: () => lease
		});
		const authorizeNative = (request) => {
			const facts = request.facts;
			if (cleanup?.authorize(request)) return;
			if (request.stage === "prepare" && isRecord(facts) && facts.kind === "agent-registration-committed") return;
			assertCurrent();
			cleanup?.assertCurrent();
			if (request.stage === "prepare" && authorizeStartupFts(facts)) return;
			if (!nativeIdentity || creatingIdentity) assertCallerCurrent?.();
			if (request.stage === "prepare" && isRecord(facts) && facts.kind === "agent-registration-start") {
				assertSourceCurrent();
				if (!registration || !lease || !isDeepStrictEqual(facts.lease, lease)) throw new Error("Agent registration start differs from its admitted native owner");
				registration.begin();
				return;
			}
			if (request.stage === "prepare" && isRecord(facts) && facts.kind === "shared-owner") {
				if (!(facts.validationPort instanceof MessagePort)) throw new Error("Agent worker lost its validation handoff port");
				try {
					assertSourceCurrent();
					publishOpenClawStateDatabaseWorkerAdmission(context.admission);
					const received = facts.lease;
					if (!isDeepStrictEqual(facts.identity, context.admission.identity) || !isRecord(received) || received.leaseId !== input.leaseId || received.agentId !== input.agentId || received.path !== pathname || received.ownerPid !== process.pid || received.ownerStartTime !== null && typeof received.ownerStartTime !== "number" || received.sharedStatePath !== context.admission.databasePath || received.sharedStateIdentity !== context.admission.identity.key) throw new Error("Agent worker lease differs from its captured native owner");
					lease = {
						leaseId: input.leaseId,
						agentId: input.agentId,
						path: pathname,
						ownerPid: process.pid,
						ownerStartTime: received.ownerStartTime,
						sharedStatePath: context.admission.databasePath,
						sharedStateIdentity: context.admission.identity.key
					};
					receiveValidation = captureOpenClawAgentDatabaseAdmissionPublication({
						agentId,
						path: pathname
					});
					assertIntegrityVerifierCurrent = captureOpenClawDatabaseIntegrityVerifier(input);
					const preparation = {
						validation: getOpenClawAgentDatabaseValidationForTransfer({
							agentId,
							path: pathname
						}),
						deferUnverifiedIntegrity: assertIntegrityVerifierCurrent !== void 0
					};
					facts.validationPort.postMessage(preparation, []);
				} finally {
					facts.validationPort.close();
				}
				return;
			}
			if (request.stage === "prepare" && isRecord(facts) && (facts.kind === "agent-integrity-check" || facts.kind === "agent-open-resume" || facts.kind === "agent-validation-start")) {
				assertSourceCurrent();
				if (!lease || !isDeepStrictEqual(facts.lease, lease)) throw new Error("Agent open notice differs from its captured native lease");
				if (facts.kind === "agent-validation-start") receiveValidation = captureOpenClawAgentDatabaseAdmissionPublication({
					agentId,
					path: pathname
				});
				if (facts.kind === "agent-integrity-check") {
					if (facts.check !== "quick" && facts.check !== "full") throw new Error("Agent integrity notice has an invalid check mode");
					integrityCheckPending = facts.check;
				}
				return;
			}
			if (request.stage === "open") {
				if (!isDeepStrictEqual(facts, input)) throw new Error("Agent database open differs from its captured owner");
			} else {
				const received = isRecord(facts) ? facts.identity : void 0;
				if (!isRecord(received) || received.kind !== "file" || typeof received.physicalIdentity !== "string" || typeof received.birthtime !== "string" || typeof received.incarnation !== "string" || typeof received.nativeLocation !== "string" || nativeIdentity && !isDeepStrictEqual(received, nativeIdentity)) throw new Error("Agent database operation belongs to another native owner");
				const receivedIdentity = nativeIdentity ?? Object.freeze({
					kind: "file",
					physicalIdentity: received.physicalIdentity,
					birthtime: received.birthtime,
					incarnation: received.incarnation,
					nativeLocation: received.nativeLocation
				});
				if (expectedIdentity && (receivedIdentity.physicalIdentity !== expectedIdentity.physicalIdentity || expectedIdentity.birthtime !== void 0 && receivedIdentity.birthtime !== expectedIdentity.birthtime)) throw new Error("Agent database operation differs from its expected physical file");
				if (!nativeIdentity) assertExistingDatabaseIdentity(pathname, `file:${receivedIdentity.physicalIdentity}`, receivedIdentity.birthtime);
				acceptFileIdentity({
					kind: "file",
					physicalIdentity: receivedIdentity.physicalIdentity,
					birthtime: receivedIdentity.birthtime,
					nativeLocation: receivedIdentity.nativeLocation
				});
				assertPreparationJournal?.(isRecord(facts) ? facts.agentDeletionJournalPresent : void 0);
				nativeIdentity ??= receivedIdentity;
				return nativeIdentity;
			}
		};
		const captured = source.createAdmission({
			attachment: {
				kind: "agent-execution",
				startupJournal: assertPreparationJournal !== void 0,
				...cleanup ? { deletion: cleanup.guard } : {}
			},
			nativeLocations,
			assertCurrent,
			authorize(request) {
				const identity = authorizeNative(request);
				if (request.stage === "open" && registration) {
					assertSourceCurrent();
					if (!nativeIdentity && (creatingIdentity ? creatingIdentity.key.startsWith("path:") : !expectedIdentity && readDatabasePathIdentitySync(pathname).key.startsWith("path:"))) {
						if (!lease && getOpenClawAgentDatabaseValidationForTransfer({
							agentId,
							path: pathname
						})) invalidateOpenClawAgentDatabaseValidation(pathname);
						registration.begin();
					}
				}
				if (request.stage === "prepare" && identity && receiveValidation && isRecord(request.facts) && request.facts.validation !== void 0) {
					assertSourceCurrent(identity);
					receiveValidation(identity.physicalIdentity, request.facts.validation);
					receiveValidation = void 0;
				}
				assertSourceCurrent(identity);
			}
		})(operation);
		captured.admission.observeRequests(observeNative);
		return captured;
	};
	const open = (source, assertCallerCurrent, createIfMissing = false, signal) => {
		assertCurrent();
		source.assertCurrent();
		assertCallerCurrent?.();
		opening ??= (async () => {
			retireReplacedAgentValidation(agentId, pathname, expectedIdentity);
			const registration = createIfMissing ? captureOpenClawAgentDatabaseRegistration({
				agentId,
				agentPath: pathname,
				admission: context.admission,
				assertPublicationCurrent: context.assertPublicationCurrent,
				onRegistryChange: source.onRegistryChange
			}) : void 0;
			const openStore = async () => {
				const assertOpening = () => {
					assertCurrent();
					source.assertCurrent();
					assertCallerCurrent?.();
					signal?.throwIfAborted();
				};
				const store = await openAgentDatabaseSqliteWorkerStore({
					moduleUrl: resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.agentDatabaseExecution),
					databasePath: pathname,
					input,
					existingOnly: !createIfMissing
				}, {
					stateContext: context,
					stateDatabasePath: context.admission.databasePath,
					assertCurrent: assertOpening,
					signal,
					createAdmission: (operation) => {
						const captured = admission(source, registration, assertCallerCurrent)(operation);
						openingAdmission = {
							admission: captured.admission,
							settled: operation.settled
						};
						return captured;
					},
					onNativeStopped: nativeStop.observe,
					onNativeLost: () => invalidateOpenClawAgentDatabaseValidation(pathname)
				});
				openedStore = store;
				return store;
			};
			const store = registration ? await settleAgentRegistration(registration, openStore) : await openStore();
			if (!store) return;
			try {
				assertCurrent();
				if (nativeIdentity) preparationPublished = true;
				return store;
			} catch (error) {
				try {
					await store.close();
				} catch (cleanupError) {
					throw new AggregateError([error, cleanupError], "Agent open and cleanup failed", { cause: cleanupError });
				}
				if (error instanceof AgentDatabaseExecutionAdmissionClosedError) closedOpeningRefusal = error;
				throw error;
			}
		})().catch(async (error) => {
			openingFailure = closedOpeningRefusal !== void 0 && error === closedOpeningRefusal ? "open-refused" : "native";
			if (openingAdmission) {
				const { admission: captured, settled } = openingAdmission;
				const outcome = await settled;
				if (captured.failure !== void 0 && captured.failureSource !== "protocol" && error === captured.failure && outcome.kind !== "unknown" && !captured.committed && captured.cleanupFailures.length === 0) openingFailure = "open-refused";
			}
			throw error;
		}).finally(() => {
			openingAdmission = void 0;
			closedOpeningRefusal = void 0;
		});
		const attempt = opening;
		return attempt.then((store) => {
			if (!store && opening === attempt) opening = void 0;
			if (!store && createIfMissing) return open(source, assertCallerCurrent, true, signal);
			return store;
		});
	};
	async function run(source, operation, assertCallerCurrent, createIfMissing = false, signal, readmitSchema = false) {
		const assertOperationCurrent = () => {
			assertCurrent();
			source.assertCurrent();
			assertCallerCurrent?.();
			signal?.throwIfAborted();
		};
		const wasPrepared = preparationPublished;
		const store = preparationPublished ? openedStore : await open(source, assertCallerCurrent, createIfMissing, signal);
		assertOperationCurrent();
		if (!store) return;
		const schema = createIfMissing ? getOpenClawAgentDatabaseValidationForTransfer({
			agentId,
			path: pathname
		})?.schema : void 0;
		const requiresReadmission = createIfMissing && wasPrepared && (readmitSchema || !schema || Atomics.load(new Int32Array(schema.valid), 0) !== 1 || captureAgentDatabasePreparationJournal(agentId, { env: input.environment }) !== void 0);
		if (!nativeIdentity || requiresReadmission) {
			const registration = captureOpenClawAgentDatabaseRegistration({
				agentId,
				agentPath: pathname,
				admission: context.admission,
				assertPublicationCurrent: context.assertPublicationCurrent,
				onRegistryChange: source.onRegistryChange
			});
			await settleAgentRegistration(registration, async () => {
				await runSqliteWorkerStoreOperation(store, (scope) => scope.execute({
					type: "database.prepareWrite",
					input: void 0
				}, { signal }), void 0, assertOperationCurrent, admission(source, registration, assertCallerCurrent));
				assertCurrent();
				source.assertCurrent();
			});
			preparationPublished = true;
		}
		assertIntegrityVerifierCurrent?.();
		if (integrityCheckPending) {
			const preparation = captureAgentDatabasePreparationCompletion(agentId, { env: input.environment });
			requestOpenClawAgentDatabaseIntegrityCheck({
				path: pathname,
				env: input.environment,
				check: integrityCheckPending,
				...integrityCheckPending === "full" && nativeIdentity ? {
					release: retainVerification(),
					proof: {
						identity: nativeIdentity.physicalIdentity,
						complete: async (assertVerifierCurrent, verifierSignal) => {
							if (preparation) await racePromiseWithAbortSignal(preparation, verifierSignal);
							const assert = () => {
								assertVerifierCurrent();
								context.admission.assertCurrent();
								assertCurrent();
							};
							const verifierSource = {
								assertCurrent: assert,
								createAdmission: (binding) => () => ({
									nativeLocations: binding.nativeLocations,
									admission: createSqliteWorkerOperationAdmission((request, grant) => {
										binding.authorize(request);
										assert();
										if (!grant()) throw new Error("Agent background verification authority expired");
									}, binding.attachment)
								})
							};
							return runOpenClawAgentWorkerWrite({
								agentId,
								path: pathname,
								env: input.environment
							}, () => runSqliteWorkerStoreOperation(store, (scope) => scope.execute({
								type: "database.recordIntegrity",
								input: void 0
							}), void 0, assert, admission(verifierSource)));
						}
					}
				} : {}
			});
			integrityCheckPending = void 0;
		}
		assertIntegrityVerifierCurrent = void 0;
		return runSqliteWorkerStoreOperation(store, operation, void 0, assertOperationCurrent, admission(source, void 0, assertCallerCurrent));
	}
	return {
		failure: () => openingFailure ?? (openedStore && !isSqliteWorkerStoreAvailable(openedStore) ? "native" : void 0),
		isPrepared() {
			assertCurrent();
			return preparationPublished;
		},
		captureClaim() {
			assertCurrent();
			const captured = nativeIdentity;
			if (!captured) throw new Error("Agent database generation has not been admitted");
			return {
				identity: captured.physicalIdentity,
				incarnation: captured.incarnation,
				assertCurrent() {
					assertCurrent();
					if (nativeIdentity !== captured) throw new Error("Agent database generation changed");
				}
			};
		},
		run,
		close() {
			retiring = true;
			closing ??= (async () => {
				const errors = [];
				let storeClosed = false;
				if (opening) try {
					await opening.then(async (store) => {
						await store?.close();
						storeClosed = store !== void 0;
					}, () => openedStore ? openedStore.close() : closeUnclaimedSharedStateSqliteWorkers(pathname));
				} catch (error) {
					errors.push(error);
				}
				if (nativeStop.stopped && lease) try {
					await cleanupRetiredAgentDatabaseLease({
						context,
						stopped: nativeStop.stopped,
						assertOwned: assertCleanupOwned,
						lease,
						readOpenRefused: nativeStop.readOpenRefused,
						closed: () => storeClosed ? readAgentDatabaseClosedReceipt(nativeStop.readCloseReceipt?.(), nativeIdentity, lease) : void 0
					});
				} catch (error) {
					errors.push(error);
				}
				throwSqliteLifecycleErrors(errors, "Agent native close and lease cleanup failed");
				publishAgentDatabaseCloseCheckpoint(pathname, readAgentDatabaseClosedReceipt(nativeStop.readCloseReceipt?.(), nativeIdentity, lease), assertCleanupOwned);
			})().catch((error) => {
				closing = void 0;
				throw error;
			});
			return closing;
		}
	};
}
//#endregion
//#region src/state/openclaw-agent-execution-scope.ts
/** A read can borrow an already-selected file owner only within its current storage scope. */
function borrowExistingAgentDatabaseExecution(owners, options, capture) {
	const pathname = path.resolve(options.path);
	const owner = owners.get(pathname) ?? owners.get(readDatabasePathIdentitySync(pathname).canonicalPath);
	if (!owner || owner.kind !== "file") return;
	const target = {
		...options,
		agentId: owner.agentId,
		path: pathname
	};
	if (!supportsAgentDatabaseExecutionScope(target)) return;
	try {
		assertAgentDatabaseExecutionSharedState(target, owner.sharedDatabaseKey);
		return capture ? capture(target) : owner.borrow(pathname);
	} catch {
		return;
	}
}
function assertAgentDatabaseExecutionSharedState(options, sharedDatabaseKey) {
	const env = process.platform === "win32" ? cloneEnvWithPlatformSemantics(options.env ?? process.env) : options.env;
	if (sharedDatabaseKey !== captureOpenClawStateReadContext(resolveOpenClawStateSqlitePath(env)).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(options) {
	const cleanup = getAgentDeletionDatabaseCleanup(options);
	return getOpenClawDatabaseMaintenanceScope()?.ownsSchemaMaintenance !== true && !hasAgentDatabaseMaintenanceAuthority() && (!cleanup || cleanup.worker !== void 0);
}
/** These native-only scopes still need their complete owning caller cutover. */
function supportsOpenClawAgentDatabaseExecution(options) {
	return !isIncognitoOpenClawAgentSqlitePath(resolveOpenClawAgentSqlitePath(options), options) && supportsAgentDatabaseExecutionScope(options);
}
/** Bind native handoff to the admitted connection and recheck it after cleanup waits. */
function captureNativeAgentDatabaseExecutionIdentity(database, agentId, canonicalPath, assertBorrowed) {
	assertBorrowed();
	const native = readOpenClawAgentDatabaseIdentity(database);
	const assertCurrent = () => {
		assertBorrowed();
		if (database.agentId !== agentId || cache.databases.get(database.path) !== database || readOpenClawAgentDatabaseIdentity(database) !== native || native.canonicalPath !== canonicalPath || !isOpenClawAgentDatabasePathCurrent(database)) throw new Error("Agent execution cannot adopt a different native database owner");
	};
	assertCurrent();
	if (typeof native.identity !== "string") throw new Error("Agent execution requires an admitted native file");
	return {
		fileIdentity: {
			kind: "file",
			physicalIdentity: native.identity,
			birthtime: native.birthtime,
			nativeLocation: native.canonicalPath
		},
		assertCurrent
	};
}
function assertAgentDatabaseExecutionCreationIdentity(pathname, expected, observed, expectedFile) {
	const capturesAbsence = expected.key.startsWith("path:");
	if (expectedFile || capturesAbsence && (cache.databases.has(pathname) || cache.pending.has(pathname)) || !capturesAbsence && (!expected.key.startsWith("file:") || typeof expected.birthtime !== "string") || observed?.key !== expected.key || observed.canonicalPath !== expected.canonicalPath || observed.birthtime !== expected.birthtime) throw new Error("Agent creation no longer owns its originally observed target");
}
/** Each alias and retained file receipt must still name the borrower's original store. */
function assertBorrowedAgentDatabaseFileIdentity({ borrowedPath, identity, creatingTarget, fileIdentity, expectedIdentity, nativeIdentity }) {
	if (!fileIdentity || creatingTarget) {
		const current = readDatabasePathIdentitySync(borrowedPath);
		if (current.canonicalPath !== identity.canonicalPath || creatingTarget?.key.startsWith("file:") && (current.key !== creatingTarget.key || current.birthtime !== creatingTarget.birthtime)) throw new Error("Agent database borrower changed its originally observed target");
	}
	if (fileIdentity && expectedIdentity && (fileIdentity.physicalIdentity !== expectedIdentity.physicalIdentity || fileIdentity.birthtime !== void 0 && expectedIdentity.birthtime !== void 0 && fileIdentity.birthtime !== expectedIdentity.birthtime)) throw new Error("Agent database borrower belongs to another physical file");
	const file = fileIdentity ?? expectedIdentity;
	const birthtime = fileIdentity?.birthtime ?? expectedIdentity?.birthtime;
	if (file) {
		if (nativeIdentity && (nativeIdentity.physicalIdentity !== file.physicalIdentity || birthtime !== void 0 && nativeIdentity.birthtime !== birthtime)) throw new Error("Agent database borrower belongs to another physical file");
		if (!nativeIdentity || borrowedPath !== nativeIdentity.nativeLocation) assertExistingDatabaseIdentity(borrowedPath, `file:${file.physicalIdentity}`, birthtime);
	}
}
/** Bind a native claim to the same borrower and logical generation that captured it. */
function captureBorrowedAgentDatabaseGenerationClaim(assertBorrowed, readGeneration) {
	assertBorrowed();
	const captured = readGeneration();
	if (!captured) throw new Error("Agent database execution has no admitted generation");
	const claim = captured.captureClaim();
	return {
		identity: claim.identity,
		incarnation: claim.incarnation,
		assertCurrent() {
			assertBorrowed();
			if (readGeneration() !== captured) throw new Error("Agent database execution generation was replaced");
			claim.assertCurrent();
		}
	};
}
//#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 pending = /* @__PURE__ */ new Map();
	return {
		pending,
		settleBorrower: (borrower) => Promise.allSettled([...pending].flatMap(([work, owner]) => owner.borrower === borrower ? [work] : [])),
		cancelReadAdmissions: (borrower) => {
			for (const work of pending.values()) if (borrower === void 0 || work.borrower === borrower) work.queuedReadAbort?.abort(new AgentDatabaseExecutionAdmissionClosedError("Agent database read admission is closed"));
		},
		closeAccepted: async (close) => {
			const reads = [...pending].flatMap(([work, owner]) => owner.queuedReadAbort ? [work] : []);
			const nativeClose = close();
			await Promise.allSettled([nativeClose, ...reads]);
			await nativeClose;
		}
	};
}
//#endregion
//#region src/state/openclaw-agent-execution-owner.ts
const log = createSubsystemLogger("state/agent-db");
const MAX_IDLE_EXECUTORS = 4;
const runInExecutionOwnerContext = AsyncLocalStorage.snapshot();
function createAgentDatabaseExecution(options, prepared, executionState) {
	const executions = executionState.owners;
	const { agentId, pathname, identity, initialIdentity, expectedCreationIdentity } = prepared;
	const context = captureOpenClawStateWorkerContext({ env: options.env });
	const executionOptions = {
		agentId,
		path: pathname,
		env: context.environment
	};
	const creationClaim = captureAgentCreationClaim(options);
	const aliases = /* @__PURE__ */ new Map();
	const assertAgentAdmitted = captureAgentDatabaseAdmission(agentId, { env: context.environment });
	let retired = false;
	let revoked = false;
	let retainIdle = true;
	let borrowers = 0;
	const acceptedWork = createAgentDatabaseAcceptedWork();
	let creationIdentity = expectedCreationIdentity;
	let creationBorrowers = 0;
	let generation;
	let fileIdentity;
	let nativeClosing;
	let cleanupFailure;
	let closing;
	let unregisterShared;
	let unregisterConfig;
	let idleTimer;
	let idleDrainListener;
	const acceptFileIdentity = (received) => {
		if (fileIdentity && (fileIdentity.physicalIdentity !== received.physicalIdentity || fileIdentity.birthtime !== received.birthtime)) throw new Error("Agent database execution belongs to another physical file");
		fileIdentity ??= Object.freeze({ ...received });
	};
	const clearIdleTimer = () => {
		idleDrainListener?.[Symbol.dispose]();
		idleDrainListener = void 0;
		clearTimeout(idleTimer);
		idleTimer = void 0;
	};
	const reportCleanupFailure = (error) => {
		try {
			log.warn(`Agent database idle cleanup failed: ${formatErrorMessage(error)}`);
		} catch {}
	};
	const finishRetirement = () => {
		retired = true;
		if (executions.get(pathname) !== owner) return;
		unregisterAgent();
		unregisterShared?.();
		unregisterConfig?.();
	};
	const assertCurrent = () => {
		if (retired || executions.get(pathname) !== owner || !supportsAgentDatabaseExecutionScope(executionOptions)) throw new AgentDatabaseExecutionAdmissionClosedError("Agent database execution admission is closed");
		assertAgentDeletionExecutionCleanupAccess(owner, executionOptions);
		context.admission.assertCurrent();
		assertAgentAdmitted();
		creationClaim?.assertCurrent();
	};
	const closeNative = (expected) => {
		if (expected && generation !== expected) return Promise.resolve();
		clearIdleTimer();
		if (nativeClosing) return nativeClosing;
		const captured = generation;
		if (!captured) return Promise.resolve();
		const result = captured.close().then(() => {
			if (generation === captured) {
				generation = void 0;
				cleanupFailure = void 0;
				executionState.idle.delete(owner);
			}
		}, (error) => {
			cleanupFailure = { error };
			throw error;
		}).finally(() => {
			if (nativeClosing === result) nativeClosing = void 0;
		});
		nativeClosing = result;
		return result;
	};
	async function run(source, operation, assertCallerCurrent, expectedIdentity, retireNativeOnFailure = false, createIfMissing = false, creatingTarget, signal, readmitSchema = false, contentionDeadline) {
		const pending = cache.pending.get(pathname);
		if (pending) {
			if (creatingTarget && !fileIdentity) throw new Error("Agent creation cannot adopt another pending opener");
			if (pending.agentId !== agentId) throw new Error(`Agent database ${pathname} is opening for ${pending.agentId}`);
			await pending.promise;
			pending.controller.signal.throwIfAborted();
			assertCallerCurrent();
		}
		if (nativeClosing) {
			await nativeClosing;
			assertCallerCurrent();
		}
		if (cleanupFailure || generation?.failure()) {
			await closeNative();
			assertCurrent();
			source.assertCurrent();
			assertCallerCurrent();
			signal?.throwIfAborted();
		}
		if (!generation) {
			const created = createAgentDatabaseNativeGeneration(agentId, identity.canonicalPath, context, assertCurrent, () => {
				if (executions.get(pathname) !== owner || generation !== created || !nativeClosing) throw new Error("Agent cleanup no longer owns its original execution reference");
			}, expectedIdentity ?? fileIdentity, acceptFileIdentity, () => {
				const retained = owner.borrow(pathname);
				return () => retained.release();
			}, fileIdentity ? void 0 : creationIdentity ?? creatingTarget, creationClaim?.witness);
			generation = created;
		}
		const current = generation;
		let entered = false;
		try {
			const result = await current.run(source, (scope) => {
				entered = true;
				return operation(scope);
			}, assertCallerCurrent, createIfMissing, signal, readmitSchema);
			if (generation === current && !nativeClosing && current.failure()) await owner.close().catch(reportCleanupFailure);
			return result;
		} catch (error) {
			const nativeFailure = current.failure();
			const contended = !entered && isSqliteLockError(error);
			if (generation === current && (nativeFailure || retireNativeOnFailure)) try {
				if (nativeFailure === "native" && !contended && !nativeClosing) await owner.close();
				else await closeNative(current);
			} catch (cleanupError) {
				throw retainSqliteWorkerErrorCode(new AggregateError([error, cleanupError], "Agent operation and cleanup failed", { cause: error }), error);
			}
			if (contended) {
				const deadline = contentionDeadline ?? performance.now() + 2e3;
				if (contentionDeadline === void 0) log.warn("Agent database execution admission delayed by SQLite lock contention; retrying before execution.");
				const remaining = deadline - performance.now();
				if (remaining > 0) {
					await sleepWithAbort(Math.min(25, remaining), signal);
					assertCurrent();
					source.assertCurrent();
					assertCallerCurrent();
					if (performance.now() >= deadline) throw error;
					return run(source, operation, assertCallerCurrent, expectedIdentity, retireNativeOnFailure, createIfMissing, creatingTarget, signal, readmitSchema, deadline);
				}
			}
			throw error;
		}
	}
	const owner = {
		kind: "file",
		agentId,
		get sharedDatabaseKey() {
			return context.admission.identity.key;
		},
		get creationIdentity() {
			return creationIdentity;
		},
		borrow(borrowedPath, expected, creating, requestedPath) {
			const cleanup = getAgentDeletionDatabaseCleanup({
				...executionOptions,
				path: borrowedPath
			});
			if (cleanup?.worker && !generation?.isPrepared()) registerAgentDeletionExecutionCleanup(owner, {
				...executionOptions,
				path: borrowedPath
			}, () => drainAgentDatabaseResources({
				path: borrowedPath,
				agentId
			}, async () => {}));
			const expectedIdentity = expected ? Object.freeze({ ...expected }) : void 0;
			const creatingTarget = creating ? Object.freeze({ ...creating }) : void 0;
			const assertReferenceCurrent = (nativeIdentity) => {
				assertCurrent();
				assertBorrowedAgentDatabaseFileIdentity({
					borrowedPath,
					identity,
					creatingTarget,
					fileIdentity,
					expectedIdentity,
					nativeIdentity
				});
			};
			assertReferenceCurrent();
			if (creatingTarget && !creationIdentity && !fileIdentity && generation) throw new Error("Agent creation cannot capture another pending native opener");
			retainAlias(borrowedPath);
			if (requestedPath !== void 0) retainAlias(path.resolve(requestedPath));
			observeOpenClawDatabaseMaintenanceResource(aliases.get(pathname));
			borrowers += 1;
			clearIdleTimer();
			if (!nativeClosing && !cleanupFailure) executionState.idle.delete(owner);
			if (creatingTarget) {
				creationIdentity ??= creatingTarget;
				creationBorrowers += 1;
			}
			const assertCreationReference = (create) => {
				if (creatingTarget && !fileIdentity && !create) throw new Error("Originally observed agent target requires creating admission first");
				if (creationBorrowers && !fileIdentity && (!create || !creatingTarget)) throw new Error("Originally observed agent target requires its captured creating reference");
			};
			let released = false;
			let release;
			const borrower = Symbol("agent database borrower");
			const assertBorrowed = () => {
				if (released) throw new Error("Agent database execution reference is released");
				cleanup?.assertCurrentHost();
				assertReferenceCurrent();
			};
			const captureGenerationClaim = () => captureBorrowedAgentDatabaseGenerationClaim(assertBorrowed, () => generation);
			const borrowed = {
				agentId,
				path: borrowedPath,
				get fileIdentity() {
					assertBorrowed();
					return fileIdentity;
				},
				async adoptNativeDatabase(database) {
					const adoption = (async () => {
						const native = captureNativeAgentDatabaseExecutionIdentity(database, agentId, identity.canonicalPath, assertBorrowed);
						if (generation && !fileIdentity) {
							await closeNative(generation);
							native.assertCurrent();
						}
						assertReferenceCurrent(native.fileIdentity);
						acceptFileIdentity(native.fileIdentity);
					})();
					acceptedWork.pending.set(adoption, { borrower });
					try {
						await adoption;
					} finally {
						acceptedWork.pending.delete(adoption);
					}
				},
				assertCurrent: assertBorrowed,
				captureGenerationClaim,
				capturePreparedGenerationClaim() {
					assertBorrowed();
					if (cache.pending.has(pathname) || nativeClosing || cleanupFailure || generation?.failure() || !generation?.isPrepared()) return;
					return captureGenerationClaim();
				},
				async prepare(source, signal, preparationOptions) {
					assertBorrowed();
					assertCreationReference(true);
					const result = run(source, async () => void 0, (nativeIdentity) => {
						assertReferenceCurrent(nativeIdentity);
						assertCreationReference(true);
					}, expectedIdentity, false, true, creatingTarget, signal, preparationOptions?.readmitSchema);
					acceptedWork.pending.set(result, { borrower });
					result.finally(() => acceptedWork.pending.delete(result)).catch(() => void 0);
					await result;
				},
				async runExisting(source, operation, runOptions) {
					const capturedGeneration = released ? void 0 : generation;
					const completion = createDeferredCore();
					acceptedWork.pending.set(completion.promise, { borrower });
					try {
						assertBorrowed();
						assertCreationReference(false);
						const execute = () => run(source, operation, (nativeIdentity) => {
							assertReferenceCurrent(nativeIdentity);
							assertCreationReference(false);
						}, expectedIdentity, runOptions?.retireNativeOnFailure);
						if (runOptions?.withAdmission) {
							const queuedReadAbort = new AbortController();
							acceptedWork.pending.set(completion.promise, {
								borrower,
								queuedReadAbort
							});
							return await runOptions.withAdmission(execute, queuedReadAbort.signal);
						}
						return await execute();
					} catch (error) {
						let retireNative = runOptions?.retireNativeOnFailure === true;
						if (capturedGeneration && generation === capturedGeneration && fileIdentity) try {
							assertExistingDatabaseIdentity(fileIdentity.nativeLocation, `file:${fileIdentity.physicalIdentity}`, fileIdentity.birthtime);
						} catch {
							retireNative = true;
						}
						if (retireNative && capturedGeneration) try {
							await closeNative(capturedGeneration);
						} catch (cleanupError) {
							throw retainSqliteWorkerErrorCode(new AggregateError([error, cleanupError], "Agent execution refusal and native cleanup failed", { cause: error }), error);
						}
						throw error;
					} finally {
						acceptedWork.pending.delete(completion.promise);
						completion.resolve();
					}
				},
				release() {
					released = true;
					acceptedWork.cancelReadAdmissions(borrower);
					return release ??= (async () => {
						await acceptedWork.settleBorrower(borrower);
						if (creatingTarget && --creationBorrowers === 0 && !fileIdentity && !nativeClosing && !cleanupFailure) {
							if (generation) await closeNative(generation).catch(reportCleanupFailure);
							if (!creationBorrowers && !generation && !nativeClosing && !cleanupFailure) creationIdentity = void 0;
						}
						borrowers -= 1;
						if (borrowers !== 0 || retired || cleanupFailure) return;
						const drainSignal = getGatewayRestartDrainSignal();
						const canRetain = () => retainIdle && generation && !nativeClosing && !drainSignal.aborted;
						try {
							for (const idle of executionState.idle) {
								if (!canRetain() || executionState.idle.size < MAX_IDLE_EXECUTORS) break;
								if (borrowers !== 0 || retired || executionState.idle.has(owner)) return;
								await idle.closeIdle();
							}
						} catch (error) {
							reportCleanupFailure(error);
						}
						if (borrowers !== 0 || retired || executionState.idle.has(owner)) return;
						if (canRetain() && executionState.idle.size < MAX_IDLE_EXECUTORS) {
							executionState.idle.add(owner);
							const timer = runInExecutionOwnerContext(() => setTimeout(() => {
								if (idleTimer !== timer || !executionState.idle.has(owner)) return;
								owner.closeIdle().catch(reportCleanupFailure);
							}, SQLITE_IDLE_HANDLE_TTL_MS));
							idleTimer = timer;
							timer.unref();
							idleDrainListener = addAbortListener(drainSignal, () => {
								runInExecutionOwnerContext(() => {
									owner.closeIdle().catch(reportCleanupFailure);
								});
							});
							return;
						}
						await owner.closeIdle().catch(reportCleanupFailure);
					})();
				}
			};
			cleanup?.registerClose(() => borrowed.release());
			return borrowed;
		},
		async closeIdle() {
			await closeNative();
			if (borrowers === 0 && !generation) finishRetirement();
		},
		close() {
			retired = true;
			acceptedWork.cancelReadAdmissions();
			closing ??= (async () => {
				await closeNative();
				finishRetirement();
			})().catch((error) => {
				closing = void 0;
				if (!revoked) retired = false;
				throw error;
			});
			return closing;
		}
	};
	const revoke = () => {
		revoked = true;
		retired = true;
		acceptedWork.cancelReadAdmissions();
		clearIdleTimer();
	};
	const unregisterAgent = () => {
		for (const [alias, unregister] of aliases) {
			if (executions.get(alias) === owner) executions.delete(alias);
			unregister();
		}
		aliases.clear();
	};
	const retainAlias = (alias) => {
		if (aliases.has(alias)) return;
		const register = () => registerOpenClawAgentDatabaseAsyncResource({
			agentId,
			path: alias,
			revoke,
			close: () => acceptedWork.closeAccepted(() => owner.close()),
			retireAfterResources: true
		}, options);
		const unregister = aliases.size === 0 ? register() : runOutsideOpenClawDatabaseMaintenanceScope(register);
		aliases.set(alias, unregister);
		executions.set(alias, owner);
	};
	try {
		retainAlias(pathname);
		retainAlias(identity.canonicalPath);
		unregisterConfig = watchAgentDatabaseExecutionConfig(agentId, context.environment, () => {
			retainIdle = false;
			if (borrowers === 0) owner.closeIdle().catch(reportCleanupFailure);
		});
		unregisterShared = registerOpenClawStateDatabaseAsyncResource({ close: async (sharedIdentity) => {
			if (!sharedIdentity || sharedIdentity.key === context.admission.identity.key) await acceptedWork.closeAccepted(() => owner.close());
		} });
		return owner.borrow(pathname, initialIdentity, expectedCreationIdentity, prepared.requestedPath);
	} catch (error) {
		unregisterAgent();
		unregisterShared?.();
		unregisterConfig?.();
		throw error;
	}
}
//#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;
/** File captures stay synchronous; explicit ephemeral targets await their pinned actor. */
const captureOpenClawAgentDatabaseExecution = createAgentDatabaseExecutionCapture(executions, captureFileAgentDatabaseExecution);
/** Borrow an existing physical owner without opening or preparing a writer. */
function captureExistingOpenClawAgentDatabaseExecution(options, constraints) {
	return borrowExistingAgentDatabaseExecution(executions, options, constraints ? (target) => captureFileAgentDatabaseExecution(target, constraints) : void 0);
}
/** Borrow before callers yield; native opening stays lazy and release joins owned work. */
function captureFileAgentDatabaseExecution(options, constraints = {}) {
	const agentId = normalizeAgentId(options.agentId);
	const pathname = resolveOpenClawAgentSqlitePath(options);
	assertAgentCreationClaimAliases(options);
	if (!supportsOpenClawAgentDatabaseExecution(options)) throw new Error("This agent database scope still requires its existing native owner");
	let existing = executions.get(pathname);
	const expectedCreationIdentity = constraints.expectedCreationIdentity ? Object.freeze({ ...constraints.expectedCreationIdentity }) : void 0;
	if (!existing || expectedCreationIdentity) {
		const identity = readDatabasePathIdentitySync(pathname);
		existing ??= executions.get(identity.canonicalPath);
		if (expectedCreationIdentity) assertAgentDatabaseExecutionCreationIdentity(pathname, expectedCreationIdentity, expectedCreationIdentity.key.startsWith("path:") && existing?.kind === "file" ? existing.creationIdentity : identity, constraints.expectedIdentity);
		if (!existing) return createAgentDatabaseExecution(options, {
			agentId,
			pathname,
			identity,
			initialIdentity: constraints.expectedIdentity,
			expectedCreationIdentity,
			requestedPath: constraints.requestedPath
		}, executionState);
	}
	if (existing.kind !== "file") throw new Error("Agent namespace belongs to an incognito execution owner");
	if (existing.agentId !== agentId) throw new Error(`OpenClaw agent database ${pathname} is already open for agent ${existing.agentId}; requested agent ${agentId}.`);
	assertAgentDatabaseExecutionSharedState(options, existing.sharedDatabaseKey);
	assertAgentDeletionExecutionCleanupAccess(existing, options);
	return existing.borrow(pathname, constraints.expectedIdentity, expectedCreationIdentity, constraints.requestedPath);
}
//#endregion
export { isIncognitoHistoryCommand as S, toIncognitoManagerCommand as _, incognitoSideDataKeys as a, isIncognitoLifecycleWrite as b, isIncognitoComputeCommand as c, authorizeSessionFacts as d, isIncognitoTranscriptCommand as f, isIncognitoManagerWrite as g, isIncognitoManagerCommand as h, cleanupRetiredAgentDatabaseLease as i, isIncognitoComputeWrite as l, isIncognitoTranscriptWrite as m, captureOpenClawAgentDatabaseExecution as n, isIncognitoSideDataWrite as o, isIncognitoTranscriptReceiptCommand as p, supportsOpenClawAgentDatabaseExecution as r, readPendingInputMutationReceipt as s, captureExistingOpenClawAgentDatabaseExecution as t, isIncognitoStoreComputeCommand as u, incognitoLifecycleKeys as v, incognitoHistoryKeys as x, isIncognitoLifecycleCommand as y };