UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2,358 lines • 86.5 kB
import { d as isMissingPathError, y as toErrorObject } from "./paths-0xDagtub.mjs";
import "./utils-BclMknzT.mjs";
import { W as resolveGlobalSingleton } from "./path-guards-quCEQx1i.mjs";
import { i as retainSqliteWorkerErrorCode, t as SqliteWorkerError } from "./sqlite-worker-error-Q7g0aE9t.mjs";
import { i as raceWithTimeout, o as sleepWithAbort, r as racePromiseWithAbortSignal } from "./src-DIZdnDBl.mjs";
import { s as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "./openclaw-state-db-contract-DpFGI8ZZ.mjs";
import { _ as resolveIdentityPathViaExistingAncestor, v as resolveIdentityPathViaExistingAncestorSync } from "./redact-BRF0hr6G.mjs";
import { h as createStateWorkerMemoryPressureSubscription, m as createSqliteWorkerTransferReceiver, p as createSqliteWorkerTransferOwner } from "./sqlite-snapshot-staging-owner-D6iplEEs.mjs";
import { f as runWithMainThreadTask, h as AsyncContext, r as getChildLogger, t as createSubsystemLogger } from "./subsystem-CeOCPr4l.mjs";
import { i as runInDetachedAsyncContext } from "./plugin-instance-invocation-DLc0_aJ8.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { i as notifyListeners } from "./sql-connection-VmV9pnJI.mjs";
import { d as readDatabasePathIdentity } from "./sqlite-worker-identity-CiWdPbPl.mjs";
import { s as resolveQuarantineStorePath } from "./openclaw-state-db.paths-5PCLNGIM.mjs";
import { c as createSqliteLifecycleAggregateError, u as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-D4bxhyEQ.mjs";
import { A as trackSqliteDatabaseAdmissionWorker, R as installSqliteNativeRuntimeAdmission, dt as ensureSqliteLibrarySelected, h as prepareSqliteDatabaseAdmissionAsync, it as captureSqliteDatabaseAdmissions, lt as captureSqliteWorkerClosePolicy, rt as canShareSqliteDatabaseAdmissions, s as getSqliteDatabaseAdmissionIdentityForPath, st as createSqliteDatabaseAdmissionCursor, u as hasSqliteDatabaseSchemaAdmissionForIdentity } from "./sqlite-database-admission-DMm34jqt.mjs";
import "./node-sqlite-DrCtoYsd.mjs";
import { B as getExistingOpenClawStateSchemaPath, F as captureSqliteWorkerStateContext, V as isExistingOpenClawStateSchema, f as openClawStateDatabaseCache, g as registerOpenClawStateDatabaseLifecycleListener, h as registerOpenClawStateDatabaseAsyncResource, m as recordOpenClawStateDatabaseOpenFailure, p as publishOpenClawStateDatabaseWorkerAdmission, q as SQLITE_IDLE_HANDLE_TTL_MS, t as assertPublishedOpenClawStateDatabaseLifecycle, u as getOpenClawStateDatabaseTerminalFailureAsync, z as sqliteWorkerRequestBytes } from "./openclaw-state-db-cache-D7C7Hg5y.mjs";
import { a as runtimeNeedsTypeScriptLoader, r as resolveRuntimeWorkerThreadExecArgv } from "./runtime-worker-url-BEfqe_m6.mjs";
import { _ as isWorkerIdleForPressure, b as resolveNodeCompileCacheEnv, g as trackWorkerRequest, i as createPostgresPoolEndpoints, o as postgresPoolTransferList, p as resolveSqliteBrokerWorkerCount, r as runQueuedStoreWrite } from "./worker-task-pool-DBu8jMlX.mjs";
import { a as resolveRuntimeProcessEntrypointUrl } from "./runtime-process-url-sztU0Vcb.mjs";
import { m as resolveRuntimeWorkerGenerationUrl, n as createCpuTrackedWorker, o as receiveWorkerMemoryPort, p as captureRuntimeWorkerSource } from "./worker-cpu-sx0tpDpz.mjs";
import { d as INCOGNITO_AGENT_SQLITE_BASENAME } from "./openclaw-agent-db-resources-TIBz7nIz.mjs";
import { a as captureOpenClawDatabaseMaintenanceResource, s as getOpenClawDatabaseMaintenanceScope, t as StateDatabaseReadAdmissionInvalidatedError } from "./openclaw-state-db-async-lifecycle-DLH47xBr.mjs";
import { a as classifyWorkerRequest } from "./worker-message-metrics-DnNsI1Wf.mjs";
import { n as retainSqliteWriteAdmissionService } from "./sqlite-transaction-DYxlAnZ2.mjs";
import { n as acquireStateDatabaseSchemaLease, s as captureStateDatabaseAccess } from "./gateway-state-owner-CW5kvbov.mjs";
import { r as StateDatabaseAdmissionPendingError } from "./gateway-state-owner-errors-ccLhqQIq.mjs";
import { n as hydrateOpenClawStateWorkerError, o as findOpenClawStateDatabaseFailure, r as retainOpenClawStateWorkerErrorPayload } from "./openclaw-state-worker-error-Blekn2XA.mjs";
import { C as SqliteWorkerAdmissionTimeoutError, S as SQLITE_WORKER_MAX_MESSAGE_BYTES, b as readSqliteDatabaseAdmissionDeadline, f as SqliteWorkerSlotCustody, i as createSqliteWorkerOperationAdmission, o as readSqliteWorkerExecutionAuthority, p as readSqliteWorkerRequestCustody, t as bindSqliteWorkerDatabaseAdmissionCursor } from "./sqlite-worker-operation-admission-DjndFB3C.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
import { isDeepStrictEqual } from "node:util";
import { isPromise } from "node:util/types";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { createHash } from "node:crypto";
import { realpath, stat } from "node:fs/promises";
import { isMainThread, isMarkedAsUntransferable } from "node:worker_threads";
import { deserialize, serialize } from "node:v8";
import { setTimeout as setTimeout$1 } from "node:timers/promises";
//#region src/plugins/plugin-shared-state-admission.ts
const admission = resolveGlobalSingleton(Symbol.for("openclaw.pluginSharedStateAdmission"), () => ({}));
function getPluginSharedStateResourceHost() {
	return admission.resolveHost?.();
}
function runPluginSharedStateWork(e) {
	const t = getPluginSharedStateResourceHost();
	return t ? t.trackSharedStateWork(e) : e();
}
//#endregion
//#region src/infra/acquire-with-wait.ts
/** Retry only acquisition, keeping the deadline independent of wall-clock changes. */
async function acquireWithWait(e) {
	const t = e.now ?? performance.now.bind(performance);
	let n = e.pollIntervalMs;
	for (;;) try {
		return await e.acquire();
	} catch (r) {
		const i = e.shouldRetry(r);
		if (!i) throw r;
		const a = e.deadlineMs - t();
		if (a <= 0) throw r;
		await (e.sleep ?? setTimeout$1)(Math.min(i === true ? n : i.delayMs, a));
		n = Math.min(n * 2, e.maxPollIntervalMs ?? e.pollIntervalMs);
	}
}
//#endregion
//#region src/infra/sqlite-database-admission-turn.ts
const turns = resolveGlobalSingleton(Symbol.for("openclaw.sqliteDatabaseAdmissionTurns"), () => ({
	pending: /* @__PURE__ */ new Map(),
	discovery: Promise.resolve(),
	discovering: 0
}));
const current = new AsyncContext(Symbol.for("openclaw.sqliteDatabaseAdmissionTurnContext"));
function hasPublishedSchema(e) {
	const t = getSqliteDatabaseAdmissionIdentityForPath(e);
	return t !== void 0 && hasSqliteDatabaseSchemaAdmissionForIdentity(t);
}
function reserveAdmissionTurn(e) {
	if (e.size === 0) return;
	const t = new Set([...e].flatMap((e) => turns.pending.get(e) ?? []));
	const { promise: n, resolve: r } = createDeferredCore();
	for (const t of e) turns.pending.set(t, n);
	const release = () => {
		for (const t of e) if (turns.pending.get(t) === n) turns.pending.delete(t);
		r();
	};
	return {
		ready: Promise.all(t),
		release
	};
}
function prepareAdmissionTurn(e, t, n, r = () => {}) {
	turns.discovering++;
	const i = turns.discovery.then(async () => {
		try {
			r();
			const i = typeof n === "function" ? await n() : n;
			r();
			const a = /* @__PURE__ */ new Set();
			for (const e of t) {
				const t = i?.physicalFamilies ? e : await resolveIdentityPathViaExistingAncestor(e);
				r();
				a.add(`family:${t}`);
			}
			const o = new Map(i?.readIdentities);
			for (const t of e) {
				if ((typeof n === "function" || !i?.readIdentities?.has(t)) && hasPublishedSchema(t)) continue;
				let e;
				try {
					e = await prepareSqliteDatabaseAdmissionAsync({
						location: t,
						identity: i?.readIdentities?.get(t),
						assertCurrent: r
					});
				} catch (e) {
					if (!isMissingPathError(e)) throw e;
				}
				const s = e?.canonicalPath ?? await resolveIdentityPathViaExistingAncestor(t);
				r();
				a.add(`path:${s}`);
				if (e) {
					o.set(t, e);
					a.add(`${e.key}:${e.birthtime ?? ""}`);
				}
				if (!e || !hasSqliteDatabaseSchemaAdmissionForIdentity(e)) a.add(`family:${path.dirname(s)}`);
			}
			return {
				turn: reserveAdmissionTurn(a),
				prepared: { readIdentities: o }
			};
		} finally {
			turns.discovering--;
		}
	});
	turns.discovery = i.then(() => {}, () => {});
	return i;
}
/** Only cold dispatch waits here; native getters never block the host on a worker's publication. */
function acquireSqliteDatabaseAdmissionTurn(e, t = [], n, r) {
	const i = typeof e === "string" ? [e] : e;
	if (current.getStore()?.active || !canShareSqliteDatabaseAdmissions() || !turns.discovering && !n && !t.length && i.every(hasPublishedSchema)) return;
	return prepareAdmissionTurn(i, t, n, r).then(async ({ turn: e }) => {
		await e?.ready;
		return e?.release ?? (() => {});
	});
}
/** Known database locators are captured by their task owner before dispatch, never inferred from IPC. */
function runWithSqliteDatabaseAdmissionTurn(e, t, n = [], r, i, a) {
	if (current.getStore()?.active || !canShareSqliteDatabaseAdmissions()) return typeof i === "function" ? i().then(t) : t(i);
	const run = (e, n) => {
		const r = { active: true };
		return current.run(r, async () => {
			try {
				return await t(n);
			} finally {
				r.active = false;
				e?.release();
			}
		});
	};
	if (!turns.discovering && !i && !n.length && e.every(hasPublishedSchema)) return run(void 0, void 0);
	const assertPreparing = () => {
		r?.throwIfAborted();
		a?.();
	};
	return prepareAdmissionTurn(e, n, i, assertPreparing).then(({ turn: e, prepared: t }) => {
		if (!e) return run(void 0, t);
		return racePromiseWithAbortSignal(e.ready, r, (e) => e.reason).then(() => run(e, t), (t) => {
			e.ready.then(e.release);
			throw t;
		});
	});
}
//#endregion
//#region src/infra/sqlite-worker-broker-admission.ts
const SQLITE_WORKER_ADMISSION_TIMEOUT_MS = 1e4;
function createSqliteWorkerAdmissionWarning() {
	let e = 0;
	return (t, n) => {
		const r = Date.now();
		if (r >= e) {
			e = r + SQLITE_WORKER_ADMISSION_TIMEOUT_MS;
			getChildLogger({ subsystem: "infra/sqlite-worker" }).warn("SQLite worker admission delayed", {
				queueDepth: t,
				waitMs: n
			});
		}
	};
}
function validateSqliteWorkerDatabaseLocator(e) {
	const t = path.basename(e);
	if (!e || e.startsWith("file:") || t === ":memory:" || t === "incognito-openclaw-agent.sqlite") throw new Error("SQLite worker stores require a file-backed filesystem path; in-memory and incognito databases are not supported");
}
function reserveSqliteWorkerClient(e, t, n, r) {
	const i = e.size < n;
	if (!i && ![...t].some((e) => e.retireIdle)) throw new SqliteWorkerError("SQLite worker store capacity reached", "overloaded");
	if (i) e.add(r);
	return i;
}
function findReusableSqliteWorkerClient(e, t) {
	for (const n of e) if (!n.sealed && n.isAvailable() && n.actor.pathReferences.has(t)) return n;
}
async function reclaimSqliteWorkerClient(e, t, n, r) {
	const assertCurrent = () => {
		e.signal?.throwIfAborted();
		e.assertCurrent?.();
		if (r()) throw new SqliteWorkerError("SQLite worker host is closing", "closed");
	};
	assertCurrent();
	for (const r of t) {
		if (n()) return;
		if (r.actor.runtimeGeneration === e.runtimeGeneration) await r.retireIdle?.();
		assertCurrent();
	}
	if (!n()) throw new SqliteWorkerError("SQLite worker store capacity reached", "overloaded");
}
function captureSqliteWorkerOpen(e, t, n, r = {}) {
	const { createAdmission: i, preparation: a, retireIdle: o, ...s } = r;
	const c = AsyncLocalStorage.snapshot();
	const l = e.admission;
	const u = l ? () => {
		n?.();
		l.assertCurrent();
	} : n;
	const d = u ? () => c(u) : void 0;
	const f = path.resolve(e.databasePath);
	if (e.admission && (!e.existingOnly || !e.admission.identity.startsWith("file:"))) throw new Error("Owned SQLite Worker admission requires an existing physical identity");
	d?.();
	const p = resolveRuntimeProcessEntrypointUrl("sqliteStore");
	const m = resolveRuntimeWorkerGenerationUrl(p, e.runtimeGeneration);
	return {
		...s,
		carrierClass: r.carrierClass ?? e.isolation,
		retireIdle: o ? () => c(o) : void 0,
		maintenanceScope: r.cleanupAccess ? void 0 : r.maintenanceScope ?? getOpenClawDatabaseMaintenanceScope(),
		...a !== void 0 ? { preparation: serialize(a) } : {},
		runtimeGeneration: e.runtimeGeneration,
		carrierUrl: m,
		createAdmission: i ? (e) => c(i, e) : void 0,
		assertCurrent: d,
		...e.admission ? {
			expectedIdentity: e.admission.identity,
			expectedBirthtime: e.admission.birthtime,
			createOpenAdmission: () => {
				let e = false;
				return {
					nativeLocations: [f],
					admission: createSqliteWorkerOperationAdmission((t, n) => {
						if (e || t.stage !== "open") throw new Error("SQLite Worker open admission requested out of order");
						d();
						if (!n()) throw new Error("SQLite Worker open admission expired");
						e = true;
					})
				};
			}
		} : {},
		moduleUrl: new URL(e.moduleUrl),
		databasePath: f,
		input: serialize(e.input),
		existingOnly: e.existingOnly === true,
		...t ? { stateContext: captureSqliteWorkerStateContext(t) } : {}
	};
}
function validateSqliteWorkerModuleUrl(e) {
	if (e.protocol !== "file:" || e.search || e.hash) throw new Error("SQLite worker backend must be a static local module URL");
}
async function prepareSqliteWorkerDatabaseAdmission(e) {
	validateSqliteWorkerModuleUrl(e.moduleUrl);
	const t = path.resolve(e.databasePath);
	const n = createHash("sha256").update(e.input).digest("hex");
	const r = await readDatabasePathIdentity(t);
	e.assertCurrent?.();
	if (e.expectedIdentity && (r.key !== e.expectedIdentity || e.expectedBirthtime !== void 0 && r.birthtime !== e.expectedBirthtime)) throw new Error("SQLite Worker path no longer matches its borrowed native owner");
	return {
		databasePath: t,
		inputHash: n,
		identity: r,
		key: r.key
	};
}
function captureSqliteWorkerAdmissionPaths(e, t, n) {
	const r = /* @__PURE__ */ new Set([e, t.canonicalPath]);
	if ([...n].some((e) => e.key !== t.key && [...r].some((t) => e.pathReferences.has(t)))) throw new Error("SQLite database pathname changed while its worker owner is active; close the existing store first");
	return r;
}
function retainSqliteWorkerAdmissionCleanup(e, t, n) {
	t?.({
		get pending() {
			return e.references === 0 && e.cleanupState === "pending";
		},
		close: () => e.references === 0 ? n() : Promise.resolve()
	});
}
function retainSqliteWorkerAdmissionPathReferences(e, t) {
	for (const n of t) e.pathReferences.set(n, (e.pathReferences.get(n) ?? 0) + 1);
	return () => {
		for (const n of t) {
			const t = e.pathReferences.get(n) ?? 0;
			if (t > 1) e.pathReferences.set(n, t - 1);
			else e.pathReferences.delete(n);
		}
	};
}
/** All clients of one shared actor suspend its timer while maintenance retains it. */
function suspendSqliteWorkerScheduledMaintenance(e, t) {
	if (!e.stateContext) return;
	const n = e.stateContext.scheduledMaintenanceSuspension ??= new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);
	if (!t) return;
	const r = new Int32Array(n);
	Atomics.add(r, 0, 1);
	return () => {
		Atomics.sub(r, 0, 1);
	};
}
async function resolveOpenedSqliteWorkerIdentity(e, t, n) {
	const r = await readDatabasePathIdentity(e);
	const i = r.key;
	if (r.canonicalPath !== t.canonicalPath) throw new Error("SQLite database canonical pathname changed during open");
	if (!i.startsWith("file:")) throw new Error("SQLite worker backend did not establish its database file");
	if (n(i)) throw new Error("SQLite database identity collided with an existing worker owner during open");
	if (t.key.startsWith("file:") && i !== t.key) throw new Error("SQLite database file identity changed during open");
	return r;
}
function findUnclaimedSharedStateActors(e, t) {
	const n = path.resolve(t);
	return [...e].filter((e) => e.stateContext !== void 0 && e.references === 0 && e.cleanupState === "pending" && e.databasePath === n);
}
async function closeUnclaimedSharedStateActors(e, t, n) {
	const r = (await Promise.allSettled(findUnclaimedSharedStateActors(e, t).map(n))).flatMap((e) => e.status === "rejected" ? [e.reason] : []);
	if (r.length) throw new AggregateError(r, "SQLite worker unclaimed cleanup failed", { cause: r[0] });
}
async function resolveSqliteWorkerModuleUrl(e) {
	const t = await realpath(fileURLToPath(e));
	const n = pathToFileURL(t).href;
	if (!/\.[cm]?[jt]s$/.test(t) || !(await stat(t)).isFile()) throw new Error("SQLite worker backend must identify a JavaScript or TypeScript file");
	return {
		modulePath: t,
		moduleUrl: n
	};
}
function assertSqliteWorkerActorStateContext(e, t) {
	const n = t?.gatewayServiceInstallation;
	if (e.stateContext?.existingSchemaPath !== t?.existingSchemaPath || n !== void 0 && !isDeepStrictEqual(e.stateContext?.gatewayServiceInstallation, n)) throw new Error("Shared-state worker schema policy changed; close its actor first");
}
function assertSqliteWorkerActorReusable(e, t, n, r) {
	if (e.moduleUrl !== t || e.inputHash !== n) throw new Error("SQLite database already belongs to another worker backend");
	assertSqliteWorkerActorStateContext(e, r);
}
function prepareSqliteWorkerActorContext(e, t) {
	const { request: n } = t;
	const r = n.stateContext ?? e?.stateContext;
	if (e && r) {
		assertSqliteWorkerActorStateContext(e, r);
		n.stateDatabasePath = e.stateDatabasePath ?? e.databasePath;
		const t = {
			...r,
			gatewayServiceInstallation: e.stateContext?.gatewayServiceInstallation,
			...e.stateContext?.scheduledMaintenanceSuspension ? { scheduledMaintenanceSuspension: e.stateContext.scheduledMaintenanceSuspension } : {}
		};
		if (n.type !== "open") {
			const r = e.deliveredStateContext;
			n.stateContext = {
				...t,
				...t.scheduledMaintenanceSuspension && t.scheduledMaintenanceSuspension === r?.scheduledMaintenanceSuspension ? { scheduledMaintenanceSuspension: void 0 } : {},
				...Object.hasOwn(t, "stateIntegrity") && t.stateIntegrity === r?.stateIntegrity ? { stateIntegrity: void 0 } : {}
			};
		} else n.stateContext = t;
		return t;
	}
}
//#endregion
//#region src/infra/worker-transfer-bytes.ts
/** Only uniquely owned buffers can be transferred; pooled Buffers share unrelated bytes. */
function ownedWorkerBytes(e) {
	if (e.buffer instanceof ArrayBuffer && e.byteOffset === 0 && e.byteLength === e.buffer.byteLength && !isMarkedAsUntransferable(e.buffer)) return new Uint8Array(e.buffer);
	const t = new Uint8Array(e.byteLength);
	t.set(e);
	return t;
}
//#endregion
//#region src/infra/sqlite-worker-broker-reply.ts
async function dispatchSqliteWorkerJob(e, t, n) {
	const r = [...e.actors].find((e) => e.id === t.request.actor);
	const assertCurrentJob = () => {
		if (!readSqliteWorkerRequestCustody(t.custody.descriptor)) throw e.failed ?? new SqliteWorkerError("SQLite worker job is no longer current", "closed");
	};
	const assertDispatchable = () => {
		if (!t.custody.dispatched) t.signal?.throwIfAborted();
		t.assertCurrent?.();
		assertCurrentJob();
	};
	try {
		t.signal?.throwIfAborted();
		assertCurrentJob();
		const n = prepareSqliteWorkerActorContext(r, t);
		const i = r?.stateAccess;
		const a = i?.canonicalPath;
		let o;
		if (i && t.request.type !== "close") {
			const prepareAccess = async () => {
				t.signal?.throwIfAborted();
				assertCurrentJob();
				const e = await i.prepareAccess({
					maintenanceScope: t.maintenanceScope,
					schemaLease: t.cleanupAccess
				});
				t.signal?.throwIfAborted();
				assertCurrentJob();
				e();
				return e;
			};
			const isPending = (e) => e instanceof StateDatabaseAdmissionPendingError && e.databasePath === a;
			try {
				o = await prepareAccess();
			} catch (e) {
				if (!isPending(e)) throw e;
				o = await acquireWithWait({
					acquire: prepareAccess,
					shouldRetry: isPending,
					deadlineMs: performance.now() + OPENCLAW_SQLITE_BUSY_TIMEOUT_MS,
					pollIntervalMs: 10,
					sleep: (e) => sleepWithAbort(e, t.signal)
				});
			}
		}
		if (t.createAdmission || a) {
			const n = createDeferredCore();
			t.settleNative = n.resolve;
			const i = t.createAdmission ? t.createAdmission({
				settled: n.promise,
				nativeStopped: r?.nativeStopped ?? e.exit
			}) : {
				admission: createSqliteWorkerOperationAdmission(() => {
					throw new SqliteWorkerError("SQLite domain operation requires its own admission", "closed");
				}),
				nativeLocations: a ? [a] : []
			};
			try {
				i.admission.requestClass = t.observation.requestClass;
				if (i.databaseIdentity) {
					const e = t.request.databaseIdentity;
					if (e && (e.databasePath !== i.databaseIdentity.databasePath || e.key !== i.databaseIdentity.key || e.birthtime !== i.databaseIdentity.birthtime)) throw new SqliteWorkerError("SQLite request physical identities differ", "closed");
					t.request.databaseIdentity = i.databaseIdentity;
				}
				bindSqliteWorkerDatabaseAdmissionCursor(i.admission, e.databaseAdmissionCursor, () => e.databaseAdmissionCursor = createSqliteDatabaseAdmissionCursor());
				if (a) {
					const assertCreate = (e) => {
						const n = /* @__PURE__ */ new Set();
						if (t.request.type === "open" && !t.request.existingIdentity) {
							n.add(resolveIdentityPathViaExistingAncestorSync(t.request.databasePath));
							n.add(resolveIdentityPathViaExistingAncestorSync(a));
						}
						if (r?.stateContext) {
							const e = resolveIdentityPathViaExistingAncestorSync(r.databasePath);
							for (const t of [r.stateDatabasePath, resolveQuarantineStorePath(r.stateContext.environment)]) if (t) {
								const r = resolveIdentityPathViaExistingAncestorSync(t);
								if (r !== e) n.add(r);
							}
						}
						if (!n.has(resolveIdentityPathViaExistingAncestorSync(e))) throw new SqliteWorkerError("SQLite creation target differs from its captured database", "closed");
					};
					let e;
					const assertAccess = () => {
						assertCurrentJob();
						t.maintenanceScope?.assertAdmission();
						const n = {
							maintenanceScope: t.maintenanceScope,
							schemaLease: e ?? t.cleanupAccess
						};
						if (o) o(n);
						else r?.stateAccess.assertReadAllowed(n);
					};
					i.admission.bindDatabaseAuthority({
						databasePath: a,
						databaseIdentity: t.request.databaseIdentity,
						...t.request.type === "open" && !t.request.existingIdentity && resolveIdentityPathViaExistingAncestorSync(t.request.databasePath) === resolveIdentityPathViaExistingAncestorSync(a) ? { coldOpenPath: a } : {},
						assertRequest: assertDispatchable,
						assertAccess,
						...t.request.type === "close" ? {} : { assertCreate },
						acquireSchema() {
							assertAccess();
							const acquire = () => acquireStateDatabaseSchemaLease(a);
							const n = t.maintenanceScope ? t.maintenanceScope.run(acquire) : acquire();
							e = n;
							t.maintenanceScope?.own(n, "shared-resources", () => n.release());
							return n;
						}
					});
				}
			} catch (e) {
				i.admission.finish("not-entered");
				throw e;
			}
			t.operationAdmission = {
				admission: i.admission,
				releaseService: retainSqliteWriteAdmissionService([
					...i.nativeLocations,
					...a ? [a] : [],
					...r?.pathReferences.keys() ?? []
				], () => i.admission.service())
			};
			t.request.executionAuthority = readSqliteWorkerExecutionAuthority(i.admission);
			t.request.operationAttachment = i.admission.attachment;
			t.request.operationAdmission = i.admission.port;
		} else t.request.operationAdmission = void 0;
		const s = captureSqliteDatabaseAdmissions(e.databaseAdmissionCursor);
		if (s.length > 0) t.request.databaseAdmissions = s;
		t.request.timing = t.observation.timing;
		t.request.requestCustody = t.custody.descriptor;
		const c = prepareSqliteWorkerRequest(t);
		assertDispatchable();
		const l = c.stateContext?.databaseEngineSelection;
		if (!e.postgresPoolSent && l) c.postgresPool = createPostgresPoolEndpoints(l);
		o?.();
		t.custody.accept();
		t.detach();
		if (r && c.type !== "close") r.openDispatch.openRefused = false;
		t.custody.post();
		if (c.timing) c.timing.posted = performance.now();
		e.worker.postMessage(c, [
			...postgresPoolTransferList(c.postgresPool),
			...new Set(Object.values(c.transferredInput ?? {}).map((e) => e.buffer)),
			...c.operationAdmission ? [c.operationAdmission] : [],
			..."input" in c ? [c.input.buffer] : [],
			...c.type === "open" && c.preparation ? [c.preparation.buffer] : []
		]);
		if (c.postgresPool) e.postgresPoolSent = true;
		if (r && n) r.deliveredStateContext = n;
		if (c.timing) c.timing.postFinished = performance.now();
	} catch (r) {
		e.databaseAdmissionCursor = createSqliteDatabaseAdmissionCursor();
		n(r, t.custody.postAttempted);
	}
}
function prepareSqliteWorkerRequest(e) {
	if (e.request.type !== "execute" || e.request.input.byteLength <= 33554432) {
		if ("input" in e.request) e.request.input = ownedWorkerBytes(e.request.input);
		if (e.request.type === "open" && e.request.preparation) e.request.preparation = ownedWorkerBytes(e.request.preparation);
		return e.request;
	}
	const { input: t, ...n } = e.request;
	const r = createSqliteWorkerTransferOwner();
	const i = r.start([{
		kind: "command",
		serialized: t
	}].values(), { kinds: ["command"] });
	e.inputTransfer = {
		id: i.id,
		producer: r
	};
	e.request.input = /* @__PURE__ */ new Uint8Array();
	return {
		...n,
		type: "execute-start",
		transfer: i
	};
}
function decodeSqliteWorkerReplyError(e) {
	if (e.name === "SqliteWorkerAdmissionTimeoutError" && e.code === "admission-timeout") return new SqliteWorkerAdmissionTimeoutError();
	if (e.name === "SqliteWorkerError" && e.code === "outcome-unknown") return new SqliteWorkerError(e.message, "outcome-unknown");
	const t = Object.assign(new Error(e.message), {
		name: e.name,
		...e.code === void 0 ? {} : { code: e.code }
	});
	if (e.sharedState) {
		retainOpenClawStateWorkerErrorPayload(t, e.sharedState);
		return hydrateOpenClawStateWorkerError(t, { includeOrdinary: true });
	}
	return t;
}
function decodeSqliteWorkerCleanupError(e) {
	const t = /* @__PURE__ */ new Error("SQLite worker native cleanup failed");
	retainOpenClawStateWorkerErrorPayload(t, e);
	return hydrateOpenClawStateWorkerError(t, { includeOrdinary: true });
}
function receiveSqliteWorkerReply(e, t, n) {
	const r = e.current;
	if (!r || t.id !== r.request.id) {
		n.fail(/* @__PURE__ */ new Error("SQLite worker returned an unexpected response"));
		return;
	}
	if (t.transactionCount !== void 0) r.observation.recordTransactions?.(t.transactionCount);
	if (r.observation.timing && t.timing) Object.assign(r.observation.timing, t.timing, { replyReceived: performance.now() });
	if (!t.ok) {
		const i = r.operationAdmission?.admission;
		if (t.cleanupFailure && r.custody.dispatched && !t.retire) {
			const e = (i?.failureSource === "domain" && !t.admissionRefused ? void 0 : i?.failure) ?? decodeSqliteWorkerReplyError(t.error);
			n.fail(decodeSqliteWorkerCleanupError(t.cleanupFailure), void 0, void 0, { error: e });
			return;
		}
		if (t.openNotEntered && r.request.type === "open" && r.dispatchState) r.dispatchState.openNotEntered = true;
		const a = decodeSqliteWorkerReplyError(t.error);
		const o = t.openOutcome === "refused-before-agent-open";
		if (!t.retire && (o || r.request.type === "open" && t.openNotEntered)) {
			r.custody.retire();
			e.current = void 0;
			const s = i?.failure ?? a;
			n.finish(r, s, void 0, t.openNotEntered ? {
				kind: "not-entered",
				error: s
			} : { kind: "completed" });
			if (o) {
				const t = [...e.actors].find((e) => e.id === r.request.actor);
				if (t) t.openDispatch.openRefused = !i?.cleanupFailures.length;
			}
			n.dispatch();
			return;
		}
		if (r.request.type !== "execute" || t.retire) {
			const e = r.request.type === "open" && o;
			const s = e || t.admissionRefused ? toErrorObject(i?.failure ?? a, a.message) : a;
			n.fail(s, r.request.type !== "execute" || t.admissionRefused ? s : void 0, e ? "refused-before-agent-open" : void 0);
			return;
		}
		r.custody.retire();
		e.current = void 0;
		n.finish(r, i?.failure ?? a);
		n.dispatch();
		return;
	}
	let i;
	try {
		const n = runWithMainThreadTask("worker:sqlite", () => {
			if (t.input === "next") {
				const e = r.inputTransfer;
				if (!e || t.transfer) throw new Error("SQLite worker requested unexpected command input");
				const n = e.producer.next(e.id);
				const i = ownedWorkerBytes(serialize(n));
				if (i.byteLength > 33554432) throw new Error("SQLite worker input frame exceeds the transport byte limit");
				if (n.done) {
					e.producer.end(e.id);
					r.inputTransfer = void 0;
				}
				return {
					type: "execute-frame",
					id: r.request.id,
					actor: r.request.actor,
					input: i
				};
			}
			if (r.inputTransfer) throw new Error("SQLite worker completed before receiving its command input");
			if (t.transfer === "start") {
				const e = deserialize(t.value);
				if (r.request.type !== "execute" || r.transfer || e.kinds.length !== 1 || e.kinds[0] !== "result") throw new Error("SQLite worker returned an unexpected result transfer");
				const n = {
					id: e.id,
					value: void 0,
					receiver: createSqliteWorkerTransferReceiver(e, (e) => {
						n.value = e.value;
					})
				};
				r.transfer = n;
			} else if (t.transfer === "frame") {
				const e = r.transfer;
				if (!e) throw new Error("SQLite worker returned an unexpected result frame");
				const n = deserialize(t.value);
				const a = e.receiver.accept(n);
				if (a) {
					if (a.length !== 1 || a[0]?.[1] !== 1) throw new Error("SQLite worker returned an incomplete result transfer");
					i = e.value;
					r.transfer = void 0;
				}
			} else {
				if (r.transfer) throw new Error("SQLite worker ended its result transfer without completion");
				i = deserialize(t.value);
			}
			if (r.transfer) return {
				type: "result-next",
				id: r.request.id,
				actor: r.request.actor,
				transferId: r.transfer.id
			};
		}, "reply-decode");
		if (n) {
			e.worker.postMessage(n, n.type === "execute-frame" ? [n.input.buffer] : []);
			return;
		}
	} catch (e) {
		n.fail(e);
		return;
	}
	if (t.cleanupFailure) {
		const e = r.operationAdmission?.admission;
		const a = e?.failureSource === "domain" ? void 0 : e?.failure;
		n.fail(decodeSqliteWorkerCleanupError(t.cleanupFailure), void 0, void 0, a === void 0 ? { value: i } : { error: a });
		return;
	}
	if (t.nativeRuntimeAdmission !== void 0) installSqliteNativeRuntimeAdmission(t.nativeRuntimeAdmission);
	r.custody.retire();
	e.current = void 0;
	if (r.request.type === "close") {
		if (t.closeReceipt) {
			const n = [...e.actors].find((e) => e.id === r.request.actor);
			if (n) n.closeReceipt = t.closeReceipt;
		}
		n.finish(r, void 0, i);
	} else {
		const e = r.operationAdmission?.admission;
		n.finish(r, e?.failureSource === "domain" ? void 0 : e?.failure, i);
	}
	n.dispatch();
}
/** Keep the original failure and outcome classification when retirement also fails. */
function withSqliteWorkerCleanupFailure(e, t) {
	if (t === void 0) return e;
	const n = new AggregateError([e, t], "SQLite worker failure and cleanup failed", { cause: e });
	return retainSqliteWorkerErrorCode(n, e);
}
function failSqliteWorkerSlot(e, t, n) {
	if (e.failed) return;
	const r = toErrorObject(t, "SQLite worker failed");
	e.custody.retire();
	e.failed = new SqliteWorkerError(r.message, "unavailable");
	e.failed.cause = r;
	for (const t of e.actors) if (!t.backendClosed) notifyListeners(t.nativeLostObservers ?? [], e.failed);
	for (const t of n.waiters ?? []) t(e.failed);
	const i = e.current;
	i?.custody.retire();
	e.current = void 0;
	if (i) {
		i.inputTransfer?.producer.cancel();
		i.inputTransfer = void 0;
		i.transfer = void 0;
	}
	const { currentError: a, completed: o, openOutcome: s, retire: c, finish: l } = n;
	const u = e.failed;
	const d = e.queue.splice(0);
	const f = c();
	const finishFailed = (e, t) => {
		if (i && o) {
			process.emitWarning(new Error("SQLite worker operation completed before native cleanup failed", { cause: withSqliteWorkerCleanupFailure(r, t) }));
			l(i, "error" in o ? o.error : void 0, "value" in o ? o.value : void 0, e ? { kind: "completed" } : {
				kind: "unknown",
				error: t ?? r
			});
		} else if (i) {
			const n = a ?? new SqliteWorkerError(`SQLite worker stopped before its result was received: ${r.message}`, i.request.type === "execute" && i.custody.dispatched ? "outcome-unknown" : "unavailable");
			if (!a) n.cause = r;
			l(i, withSqliteWorkerCleanupFailure(n, t), void 0, i.custody.dispatched ? e && s === "refused-before-agent-open" ? { kind: "completed" } : {
				kind: "unknown",
				error: a ?? r,
				...e ? { nativeStopped: true } : {}
			} : {
				kind: "not-entered",
				error: r
			});
		}
		for (const e of d) l(e, withSqliteWorkerCleanupFailure(u, t));
	};
	f.then(() => finishFailed(!i?.operationAdmission?.admission.cleanupFailures.length), (e) => finishFailed(false, e));
}
function settleSqliteWorkerJob(e, t, n, r) {
	e.custody.retire();
	const i = r ?? (e.custody.dispatched ? { kind: "completed" } : {
		kind: "not-entered",
		error: t
	});
	e.settleNative?.(i);
	e.operationAdmission?.admission.finish(i.kind === "not-entered" ? "not-entered" : void 0);
	e.operationAdmission?.releaseService();
	const a = e.operationAdmission?.admission;
	let o = t ?? (a?.failureSource === "domain" ? void 0 : a?.failure);
	const s = e.operationAdmission?.admission.cleanupFailures ?? [];
	if (s.length > 0) {
		if (e.dispatchState) e.dispatchState.openRefused = false;
		const t = new AggregateError(s, "SQLite worker admission cleanup failed");
		if (o === void 0 && e.request.type === "execute") process.emitWarning(t);
		else o = o === void 0 ? t : withSqliteWorkerCleanupFailure(toErrorObject(o, "SQLite worker failed"), t);
	}
	e.inputTransfer?.producer.cancel();
	e.inputTransfer = void 0;
	e.transfer = void 0;
	e.detach();
	if (o !== void 0) e.reject(o);
	else e.resolve(n);
}
//#endregion
//#region src/infra/sqlite-worker-broker-lifecycle.ts
function cleanupFailures(e) {
	return e.flatMap((e) => e.status === "rejected" ? [e.reason] : []);
}
/** The broker retains these maps; this owner drains clients before native close custody. */
function createSqliteWorkerLifecycle({ explicitSqliteCloseReleasesNativeResources: e, actors: t, slots: n, stores: r, enqueueClose: i, fail: a }) {
	function sealClients(e, t = false) {
		for (const t of e) for (const e of t) e(new SqliteWorkerError("SQLite worker host is closing", "overloaded"));
		for (const e of r.values()) if (!t || !e.actor.stateContext) e.sealed = true;
	}
	async function closeHost({ inputAdmission: e, operations: i, waiters: a }) {
		sealClients(a);
		const o = [];
		try {
			await e.joinOpens();
			await Promise.allSettled(i);
			const n = await Promise.allSettled([...t.values()].map((e) => closeActor(e)));
			o.push(...cleanupFailures(n));
			await e.joinPreparations();
		} catch (e) {
			o.push(e);
		}
		o.push(...cleanupFailures(await Promise.allSettled([...n].map(retireEmpty))));
		if (o.length) throw new AggregateError(o, "SQLite worker host cleanup failed");
		r.clear();
	}
	async function acquireSlot(t, r, i) {
		t.signal?.throwIfAborted();
		t.assertCurrent?.();
		t.signal?.throwIfAborted();
		const a = e;
		const o = [...n].filter((e) => e.carrierClass === t.carrierClass);
		const s = t.carrierClass && t.carrierClass !== "agent" ? 1 : r.maxWorkers;
		const c = o.filter((e) => !e.failed && !e.retiring && e.runtimeGeneration === t.runtimeGeneration);
		const l = a && t.runtimeGeneration !== void 0 && c.length === 0 && o.length >= s && !o.some((e) => e.borrowedGenerationSlot);
		if (!l && (a ? o.length >= s : n.size >= r.maxStores)) {
			if (!c.length || !a) {
				const e = (a ? o : [...n]).filter((e) => Boolean(e.failed || e.retiring));
				if (e.length > 0) {
					await racePromiseWithAbortSignal(Promise.race(e.map(({ exit: e }) => e)), t.signal, (e) => e.reason);
					return acquireSlot(t, r, i);
				}
				throw new SqliteWorkerError(`SQLite worker ${a ? "runtime" : "store"} capacity reached`, "overloaded");
			}
			const e = c.filter((e) => !e.current);
			let s;
			if (e.length === 0) {
				s = await raceWithTimeout(Promise.race(c.map((e) => e.current.result.then(() => e, () => e))), SQLITE_WORKER_ADMISSION_TIMEOUT_MS, () => {
					throw new SqliteWorkerError("SQLite worker queue capacity reached", "overloaded");
				}, {
					signal: t.signal,
					onAbort: (e) => {
						throw e.reason;
					}
				});
				t.signal?.throwIfAborted();
				t.assertCurrent?.();
				t.signal?.throwIfAborted();
				if (s.failed || s.retiring || s.exited) return acquireSlot(t, r, i);
			} else s = e.reduce((e, t) => e.actors.size <= t.actors.size ? e : t);
			s.pendingOpens += 1;
			return s;
		}
		return createSlot(t, l, i);
	}
	function createSlot(e, t, r) {
		e.signal?.throwIfAborted();
		ensureSqliteLibrarySelected();
		e.assertCurrent?.();
		e.signal?.throwIfAborted();
		const { carrierUrl: i } = e;
		const o = createSqliteDatabaseAdmissionCursor();
		captureSqliteDatabaseAdmissions(o);
		const s = createPostgresPoolEndpoints();
		const { worker: c, exited: l } = runInDetachedAsyncContext(() => ({
			worker: createCpuTrackedWorker(i, {
				resourceLimits: {
					maxOldGenerationSizeMb: 512,
					maxYoungGenerationSizeMb: 32
				},
				env: resolveNodeCompileCacheEnv(),
				execArgv: resolveRuntimeWorkerThreadExecArgv(i),
				workerData: { postgresPool: s },
				transferList: postgresPoolTransferList(s)
			}, () => u.current?.observation.requestClass),
			exited: createDeferredCore()
		}));
		trackSqliteDatabaseAdmissionWorker(c);
		const u = {
			carrierClass: e.carrierClass,
			postgresPoolSent: s !== void 0,
			custody: new SqliteWorkerSlotCustody(),
			databaseAdmissionCursor: o,
			runtimeGeneration: e.runtimeGeneration,
			...t ? { borrowedGenerationSlot: true } : {},
			worker: c,
			receiveReply: (e) => receiveSqliteWorkerReply(u, e, d),
			actors: /* @__PURE__ */ new Set(),
			queue: [],
			exit: l.promise,
			exited: false,
			pendingOpens: 1
		};
		const d = r(u);
		n.add(u);
		c.on("message", (e) => {
			if (!receiveWorkerMemoryPort(c, e)) u.receiveReply(e);
		});
		c.on("error", (e) => a(u, e));
		c.on("messageerror", (e) => a(u, e));
		c.once("exit", (e) => {
			u.exited = true;
			a(u, /* @__PURE__ */ new Error(`SQLite worker exited with code ${e}`));
			for (const e of u.actors) {
				e.backendClosed = true;
				e.markNativeStopped();
			}
			n.delete(u);
			l.resolve();
		});
		c.unref();
		return u;
	}
	async function settleGeneration(e) {
		const r = [...t.values()].filter((t) => t.runtimeGeneration === e);
		const i = Promise.allSettled(r.map((e) => retireActor(e)));
		await Promise.all(r.map(async (e) => await e.settlement));
		return async () => {
			const t = cleanupFailures(await i);
			throwSqliteLifecycleErrors(t, "Retained SQLite worker cleanup failed");
			await Promise.all([...n].filter((t) => t.runtimeGeneration === e).map((e) => retireEmpty(e)));
		};
	}
	function releaseActorReference(e) {
		e.references -= 1;
		if (!e.references) e.onReferencesDrained?.();
	}
	async function rejectSlotAdmission(e, t) {
		e.pendingOpens -= 1;
		try {
			await retireEmpty(e);
		} catch (e) {
			throw createSqliteLifecycleAggregateError([t, e], "SQLite slot admission and cleanup failed", t);
		}
		throw t;
	}
	async function rejectActorAdmission(e, t, n) {
		releaseActorReference(e);
		if (!e.references) {
			const r = [t];
			try {
				if (e.initialized) await closeActor(e, n);
				else {
					const n = e.openDispatch.custody.postAttempted && !e.openDispatch.openNotEntered && !e.openDispatch.openRefused;
					if (!n && !e.slot.failed) {
						e.backendClosed = true;
						e.markNativeStopped();
						e.cleanupState = "pending";
					}
					if (n) {
						a(e.slot, t);
						await e.slot.exit;
					}
					forget(e);
					await retireEmpty(e.slot);
				}
			} catch (e) {
				r.push(e);
			}
			if (r.length > 1) throw new AggregateError(r, "SQLite worker admission and cleanup failed", { cause: t });
		}
		throw t;
	}
	function retireActor(e) {
		const n = [...t.values()].find((t) => t === e);
		if (!n) return Promise.resolve();
		if (n.retirement) return n.retirement;
		n.retirementRequested = true;
		const i = createDeferredCore();
		n.onReferencesDrained = i.resolve;
		if (!n.references) i.resolve();
		n.settlement = i.promise;
		const a = [...r.values()].filter((e) => e.actor === n);
		n.retirement = (async () => {
			const e = await Promise.allSettled(a.map((e) => e.close()));
			await n.settlement;
			const t = cleanupFailures(e);
			if (!t.length) try {
				await closeActor(n);
			} catch (e) {
				t.push(e);
			}
			if (t.length) throw new AggregateError(t, "SQLite actor retirement failed", { cause: t[0] });
		})().finally(() => {
			n.retirement = void 0;
			n.onReferencesDrained = void 0;
		});
		return n.retirement;
	}
	function closeActor(t, n) {
		if (t.cleanupState === "complete") return Promise.resolve();
		if (t.closing) return t.closing;
		t.cleanupState = "pending";
		t.closing = (async () => {
			const r = [];
			if (!t.backendClosed) try {
				await i(t, n);
				t.backendClosed = true;
				if (e) t.markNativeStopped();
			} catch (e) {
				if (e !== t.slot.failed) r.push(e);
				a(t.slot, e instanceof Error ? e : new Error(String(e)));
				await t.slot.exit;
			}
			try {
				if (!e || t.slot.failed || !t.slot.pendingOpens && [...t.slot.actors].every((e) => e.backendClosed)) await retire(t.slot);
			} catch (e) {
				r.push(e);
			} finally {
				forget(t);
			}
			throwSqliteLifecycleErrors(r, "SQLite worker actor cleanup failed");
		})().finally(() => {
			t.closing = void 0;
		});
		return t.closing;
	}
	function forget(e) {
		if (t.get(e.key) === e) t.delete(e.key);
		e.slot.actors.delete(e);
		e.cleanupState = "complete";
	}
	async function retireEmpty(e) {
		if (!e.actors.size && !e.pendingOpens) await retire(e);
	}
	function retire(e) {
		e.custody.retire();
		e.retiring ??= (async () => {
			const t = [];
			if (!e.exited) try {
				await e.worker.terminate();
			} catch (e) {
				t.push(e);
			}
			await e.exit;
			throwSqliteLifecycleErrors(t, "SQLite worker retirement cleanup failed");
		})().finally(() => {
			e.retiring = void 0;
		});
		return e.retiring;
	}
	return {
		sealClients,
		closeHost,
		acquireSlot,
		createSlot,
		settleGeneration,
		releaseActorReference,
		rejectSlotAdmission,
		rejectActorAdmission,
		retireActor,
		closeActor,
		retire
	};
}
//#endregion
//#region src/infra/sqlite-worker-client.ts
function runSqliteWorkerClientOperation(e, t, n, r, i, a) {
	if (!e || e.sealed) return Promise.reject(new SqliteWorkerError("SQLite worker store is closed", "closed"));
	const o = {
		maintenanceScope: getOpenClawDatabaseMaintenanceScope(),
		createAdmission: a,
		assertCurrent: i,
		active: true,
		pending: /* @__PURE__ */ new Set(),
		...n ? { stateContext: captureSqliteWorkerStateContext(n) } : {}
	};
	const s = createDeferredCore();
	e.scopes.add(s.promise);
	const c = r(s.promise);
	return (async () => {
		try {
			const n = t({ execute: (t, n = {}) => e.execute(t, n, o) });
			return isPromise(n) ? await n : n;
		} finally {
			o.active = false;
			await Promise.allSettled(o.pending);
			e.scopes.delete(s.promise);
			c();
			s.resolve();
		}
	})();
}
/** Charge backing allocations once; transferred bytes remain resident during command streaming. */
function sqliteWorkerTransferredInputBytes(e) {
	return [...new Set(Object.values(e ?? {}).map((e) => e.buffer))].reduce((e, t) => e + t.byteLength, 0);
}
function createSqliteWorkerClient(e) {
	let t;
	let n = false;
	const r = /* @__PURE__ */ new Set();
	const i = {
		actor: e.actor,
		close: () => a.close(),
		retireIdle: e.retireIdle ? () => {
			if (i.sealed || i.scopes.size || r.size) return;
			n = true;
			try {
				return e.retireIdle?.();
			} finally {
				n = false;
			}
		} : void 0,
		sealed: e.isDraining(),
		isAvailable: e.isAvailable,
		scopes: /* @__PURE__ */ new Set(),
		execute: (t, n, a) => {
			if (a ? !a.active : i.sealed || e.isDraining()) return Promise.reject(new SqliteWorkerError("SQLite worker store is closed", "closed"));
			if (n.signal?.aborted) return Promise.reject(toErrorObject(n.signal.reason, "SQLite worker operation canceled"));
			let o;
			let s;
			let c;
			let l;
			const u = a?.assertCurrent;
			const d = a?.createAdmission;
			const f = u || d ? AsyncLocalStorage.snapshot() : void 0;
			try {
				const e = t.type;
				c = classifyWorkerRequest(e, t.input);
				l = u && f ? () => f(u, e) : void 0;
				l?.();
				o = serialize({
					type: e,
					input: t.input
				});
				if (n.transferredInput) {
					const e = [...new Set(Object.values(n.transferredInput).map((e) => e.buffer))];
					s = structuredClone(n.transferredInput, { transfer: e });
				}
			} catch (e) {
				return Promise.reject(toErrorObject(e, "SQLite worker command could not be serialized"));
			}
			const p = e.dispatch({
				payload: o,
				transferredInput: s
			}, n.signal, a, l, d && f ? (e) => f(d, e) : void 0, c);
			r.add(p);
			a?.pending.add(p);
			const settled = () => {
				r.delete(p);
				a?.pending.delete(p);
			};
			p.then(settled, settled);
			return p;
		}
	};
	const a = {
		execute: (e, t = {}) => i.execute(e, t),
		close: () => {
			if (!t) {
				i.sealed = true;
				const a = n;
				t = (async () => {
					await Promise.allSettled(i.scopes);
					await Promise.allSettled(r);
					await e.release(a);
				})().catch((e) => {
					t = void 0;
					throw e;
				});
			}
			return t;
		}
	};
	return {
		store: a,
		client: i
	};
}
//#endregion
//#region src/infra/sqlite-worker-input-admission.ts
/** Retained inputs share the broker budget before they become queued jobs. */
var SqliteWorkerInputAdmission = class {
	constructor(e) {
		this.owner = e;
		this.bytes = 0;
		this.opens = /* @__PURE__ */ new Set();
		this.inputPreparations = /* @__PURE__ */ new Set();
		this.openQueue = /* @__PURE__ */ new Map();
	}
	get retainedBytes() {
		return this.bytes;
	}
	retain(e) {
		this.bytes += e;
		let t = false;
		return () => {
			if (!t) {
				t = true;
				this.bytes -= e;
			}
		};
	}
	async open(e, t, n, r, i, a) {
		if (this.opens.size >= this.owner.maxPendingOpens || e > this.owner.maxMessageBytes || this.owner.queuedBytes() + this.bytes + e > this.owner.maxQueuedBytes) throw new SqliteWorkerError("SQLite worker open input capacity reached", "overloaded");
		const o = createDeferredCore();
		this.opens.add(o.promise);
		const s = this.retain(e);
		const enqueue = () => runWithSqliteDatabaseAdmissionTurn([t], () => runQueuedStoreWrite({
			queues: this.openQueue,
			storePath: a ?? "generic",
			label: "SQLite worker open",
			fn: n,
			signal: r
		}), [], r);
		try {
			return await (i ? Promise.resolve().then(i).then((e) => e === void 0 ? enqueue() : e) : enqueue());
		} finally {
			this.opens.delete(o.promise);
			s();
			o.resolve();
		}
	}
	async joinOpens() {
		while (this.opens.size > 0) await Promise.allSettled(this.opens);
	}
	async joinPreparations() {
		await Promise.allSettled(this.inputPreparations);
	}
	reserveInputPreparation(e, t = "stream") {
		if (!Number.isSafeInteger(e) || e < 0) throw new RangeError("SQLite worker input bytes must be a non-negative safe integer");
		if (this.owner.isClosing()) throw new SqliteWorkerError("SQLite worker host is closing", "closed");
		const n = t === "stream" && e > this.owner.maxQueuedInputBytes ? this.owner.maxMessageBytes : e;
		if (this.owner.queuedBytes() + this.bytes + n > this.owner.maxQueuedBytes) throw new SqliteWorkerError("SQLite worker input preparation capacity reached", "overloaded");
		this.bytes += n;
		const r = createDeferredCore();
		this.inputPreparations.add(r.promise);
		let i = false;
		const release = () => {
			if (this.inputPreparations.delete(r.promise)) {
				this.bytes -= n;
				r.resolve();
			}
		};
		const assertCurrent = () => {
			if (!i && (!this.inputPreparations.has(r.promise) || this.owner.isClosing())) throw new SqliteWorkerError("SQLite worker input preparation is closed", "closed");
		};
		return {
			assertCurrent,
			handoff: (e) => {
				if (!this.inputPreparations.has(r.promise) || this.owner.isClosing()) {
					release();
					throw new SqliteWorkerError("SQLite worker input preparation is closed", "closed");
				}
				i = true;
				release();
				return e();
			},
			release
		};
	}
};
//#endregion
//#region src/infra/sqlite-worker-broker.ts
const MAX_STORES = 64;
const MAX_QUEUED_COMMAND_BYTES = 67108864;
const SQLITE_WORKER_MAX_REQUESTS_PER_WORKER = 128;
const SQLITE_WORKER_MAX_QUEUED_BYTES = 268435456;
function waitForSqliteOpen(e, t) {
	return racePromiseWithAbortSignal(e, t, (e) => e.reason);
}
var SqliteWorkerBroker = class {
	constructor() {
		this.explicitSqliteCloseReleasesNativeResources = captureSqliteWorkerClosePolicy();
		this.maxWorkers = resolveSqliteBrokerWorkerCount();
		this.waiters = /* @__PURE__ */ new Map();
		this.resuming = /* @__PURE__ */ new Set();
		this.warnAdmission = createSqliteWorkerAdmissionWarning();
		this.actors = /* @__PURE__ */ new Map();
		this.slots = /* @__PURE__ */ new Set();
		this.clients = /* @__PURE__ */ new Set();
		this.stores = /* @__PURE__ */ new Map();
		this.operations = /* @__PURE__ */ new Set();
		this.lifecycle = createSqliteWorkerLifecycle({
			explicitSqliteCloseReleasesNativeResources: this.explicitSqliteCloseReleasesNativeResources,
			actors: this.actors,
			slots: this.slots,
			stores: this.stores,
			enqueueClose: (e, t) => this.enqueue(e.slot, {
				type: "close",
				actor: e.id
			}, 0, { maintenanceScope: t }),
			fail: (e, t) => this.fail(e, t)
		});
		this.nextActor = 0;
		this.nextRequest = 0;
		this.requests = /* @__PURE__ */ new WeakMap();
		this.bytes = 0;
		this.inputAdmission = new SqliteWorkerInputAdmission({
			queuedBytes: () => this.bytes,
			isClosing: () => this.draining !== void 0,
			maxQueuedBytes: SQLITE_WORKER_MAX_QUEUED_BYTES,
			maxQueuedInputBytes: MAX_QUEUED_COMMAND_BYTES,
			maxMessageBytes: SQLITE_WORKER_MAX_MESSAGE_BYTES,
			maxPendingOpens: MAX_STORES
		});
	}
	reserveInputPreparation(e, t = "stream") {
		return this.inputAdmission.reserveInputPreparation(e, t);
	}
	open(e, t, n, r = {}) {
		try {
			validateSqliteWorkerDatabaseLocator(e.databasePath);
		} catch (e) {
			return Promise.reject(toErrorObject(e, "SQLite worker database locator is invalid"));
		}
		if (this.draining) return Promise.reject(new SqliteWorkerError("SQLite worker host is closing", "closed"));
		const i = {};
		let a;
		let o;
		try {
			a = reserveSqliteWorkerClient(this.clients, this.stores.values(), MAX_STORES, i);
			o = captureSqliteWorkerOpen(e, t, n, r);
			const s = e.runtimeGeneration;
			s?.retain(this, async () => {
				await this.inputAdmission.joinOpens();
				return await this.lifecycle.settleGeneration(s);
			});
		} catch (e) {
			this.clients.delete(i);
			return Promise.reject(toErrorObject(e, "SQLite worker input could not be serialized"));
		}
		const s = a ? findReusableSqliteWorkerClient(this.stores.values(), o.databasePath) : void 0;
		return this.inputAdmission.open(sqliteWorkerRequestBytes(o.input, o.stateContext, o.preparation), o.databasePath, async () => {
			if (!a) await reclaimSqliteWorkerClient(o, this.stores.values(), () => reserveSqliteWorkerClient(this.clients, this.stores.values(), MAX_STORES, i), () => this.draining !== void 0);
			return this.openAdmitted(o, i);
		}, o.signal, s ? () => this.openAdmitted(o, i, s) : void 0, o.carrierClass).catch((e) => {
			this.clients.delete(i);
			throw e;
		});
	}
	async openAdmitted(e, t, n) {
		const { maintenanceScope: r, cleanupAccess: i } = e;
		const a = e.expectedIdentity ? {
			databasePath: e.databasePath,
			key: e.expectedIdentity,
			birthtime: e.expectedBirthtime
		} : void 0;
		e.signal?.throwIfAborted();
		e.assertCurrent?.();
		const { databasePath: o, inputHash: s, identity: c, key: l } = await prepareSqliteWorkerDatabaseAdmission(e);
		e.assertCurrent?.();
		if (n && this.actors.get(l) !== n.actor) return;
		const u = await captureStateDatabaseAccess(e.stateDatabasePath ?? c.canonicalPath);
		const d = await u.prepareAccess({
			maintenanceScope: e.maintenanceScope,
			schemaLease: e.cleanupAccess
		});
		e.signal?.throwIfAborted();
		e.assertCurrent?.();
		d();
		const f = e.input;
		const p = captureSqliteWorkerAdmissionPaths(o, c, this.actors.values());
		if (e.existingOnly && !l.startsWith("file:")) {
			this.clients.delete(t);
			return;
		}
		const { modulePath: m, moduleUrl: h } = await resolveSqliteWorkerModuleUrl(e.moduleUrl);
		e.signal?.throwIfAborted();
		e.assertCurrent?.();
		let g = this.actors.get(l);
		if (n && (g !== n.actor || n.sealed || !n.isAvailable())) return;
		if (g?.slot.failed) {
			await waitForSqliteOpen(this.lifecycle.retireActor(g), e.signal);
			return this.openAdmitted(e, t);
		}
		let _;
		if (g?.retirementRequested || g?.cleanupState === "pending") {
			const n = g.retirementRequested ? g.retirement : g.closing;
			if (n) {
				await waitForSqliteOpen(n, e.signal);
				return this.openAdmitted(e, t);
			}
			throw new SqliteWorkerError(g.retirementRequested ? "SQLite actor retirement must finish before reopening" : "SQLite worker cleanup is pending; retry close before reopening", "closed");
		}
		if (g) {
			assertSqliteWorkerActorReusable(g, h, s, e.stateContext);
			if (e.onNativeLost) (g.nativeLostObservers ??= /* @__PURE__ */ new Set()).add(e.onNativeLost);
			g.references += 1;
			_ = suspendSqliteWorkerScheduledMaintenance(g, r);
		} else {
			const t = await this.lifecycle.acquireSlot(e, {
				maxWorkers: this.maxWorkers,
				maxStores: MAX_STORES
			}, (e) => this.createReplyOwner(e));
			try {
				e.assertCurrent?.();
				e.signal?.throwIfAborted();
				if (this.actors.has(l)) throw new SqliteWorkerError("SQLite database owner was admitted while acquiring a worker; retry open", "overloaded");
			} catch (e) {
				return this.lifecycle.rejectSlotAdmission(t, e);
			}
			const n = createDeferredCore();
			g = {
				...e.onNativeLost ? { nativeLostObservers: /* @__PURE__ */ new Set([e.onNativeLost]) } : {},
				runtimeGeneration: e.runtimeGeneration,
				nativeStopped: n.promise,
				markNativeStopped: n.resolve,
				id: ++this.nextActor,
				key: l,
				identity: c,
				pathReferences: new Map([...p].map((e) => [e, 1])),
				moduleUrl: h,
				inputHash: s,
				slot: t,
				references: 1,
				opened: Promise.resolve(),
				openDispatch: { custody: t.custody.createRequest() },
				initialized: false,
				backendClosed: false,
				databasePath: o,
				stateAccess: u,
				stateContext: e.stateContext,
				stateDatabasePath: e.stateDatabasePath
			};
			this.actors.set(l, g);
			_ = suspendSqliteWorkerScheduledMaintenance(g, r);
			t.actors.add(g);
			t.pendingOpens -= 1;
			const i = g;
			i.opened = this.enqueue(t, {
				type: "open",
				actor: g.id,
				databaseIdentity: a,
				moduleUrl: h,
				databasePath: o,
				...e.createAdmission ? { openAdmission: "input" } : e.createOpenAdmission ? { openAdmission: "identity" } : {},
				...e.existingOnly ? { existingIdentity: l } : {},
				input: f,
				...e.preparation ? { preparation: e.preparation } : {},
				...runtimeNeedsTypeScriptLoader(m) ? { sourceLoaderUrl: import.meta.resolve("tsx/esm/api") } : {}
			}, sqliteWorkerRequestBytes(f, e.stateContext, e.preparation), {
				dispatchState: i.openDispatch,
				signal: e.signal,
				assertCurrent: e.assertCurrent,
				maintenanceScope: e.maintenanceScope,
				cleanupAccess: e.cleanupAccess,
				createAdmission: e.createAdmission ?? e.createOpenAdmission
			}).then(async () => {
				i.initialized = true;
				const e = await resolveOpenedSqliteWorkerIdentity(o, c, (e) => {
					const t = this.actors.get(e);
					return t !== void 0 && t !== i;
				});
				i.identity = e;
				if (e.key !== l) {
					this.actors.delete(l);
					i.key = e.key;
					this.actors.set(e.key, i);
				}
			});
		}
		const v = g;
		try {
			retainSqliteWorkerAdmissionCleanup(v, e.retainCleanup, this.lifecycle.closeActor.bind(this.lifecycle, v, r));
			e.onNativeStopped?.(v.nativeStopped, () => v.closeReceipt, () => v.openDispatch.openRefused === true);
			await g.opened;
			e.assertCurrent?.();
			if (g.retirementRequested) throw new SqliteWorkerError("SQLite actor retired during client admission", "closed");
			if (g.slot.failed) throw g.slot.failed;
		} catch (t) {
			_?.();
			return this.lifecycle.rejectActorAdmission(g, t, e.maintenanceScope);
		}
		const y = retainSqliteWorkerAdmissionPathReferences(v, p);
		let b = false;
		const { store: x, client: S } = createSqliteWorkerClient({
			actor: v,
			isDraining: () => this.draining !== void 0,
			isAvailable: () => !v.slot.failed && !v.cleanupState && !v.retirementRequested,
			retireIdle: e.retireIdle,
			dispatch: (e, t, n, r, o, s) => this.enqueue(v.slot, {
				type: "execute",
				actor: v.id,
				databaseIdentity: a,
				input: e.payload,
				transferredInput: e.transferredInput,
				...n?.stateContext ? { stateContext: n.stateContext } : {}
			}, sqliteWorkerRequestBytes(e.payload, n?.stateContext), {
				signal: t,
				requestClass: s,
				scope: n,
				assertCurrent: r,
				createAdmission: o,
				cleanupAccess: i,
				maintenanceScope: i ? void 0 : n ? n.maintenanceScope : getOpenClawDatabaseMaintenanceScope()
			}),
			release: async (e) => {
				if (!b) {
					b = true;
					_?.();
					this.lifecycle.releaseActorReference(v);
					this.stores.delete(x);
					this.clients.delete(t);
					y();
				}
				if (this.draining && !e && !v.stateContext) await this.draining;
				else if (v.slot.failed) await v.slot.exit;
				if (!v.references) await this.lifecycle.closeActor(v, r);
			}
		});
		this.stores.set(x, S);
		return x;
	}
	runOperation(e, t, n, r, i) {
		return runSqliteWorkerClientOperation(this.draining ? void 0 : this.stores.get(e), t, n, (e) => {
			this.operations.add(e);
			return () => this.operations.delete(e);
		}, r, i);
	}
	isAvailable(e) {
		return this.stores.get(e)?.isAvailable() ?? false;
	}
	retireActor(e) {
		return this.lifecycle.retireActor(e);
	}
	getActorIdentity(e) {
		const t = this.stores.get(e);
		if (!t || t.sealed || !t.actor.stateContext) throw new SqliteWorkerError("SQLite shared actor binding is unavailable", "closed");
		return t.actor;
	}
	hasUnclaimedSharedStateCleanup(e) {
		return findUnclaimedSharedStateActors(this.actors.values(), e).length > 0;
	}
	async closeUnclaimedSharedState(e) {
		await this.inputAdmission.joinOpens();
		await closeUnclaimedSharedStateActors(this.actors.values(), e, (e) => this.lifecycle.closeActor(e));
	}
	createReplyOwner(e) {
		return {
			fail: (t, n, r, i) => this.fail(e, t, n, r, i),
			finish: (t, n, r, i) => this.finish(e, t, n, r, i),
			dispatch: () => this.dispatch(e)
		};
	}
	enqueue(e, t, n, r, i = false, a = trackWorkerRequest("sqlite_writer", r.requestClass ?? t.type)) {
		const { signal: o, dispatchState: s, scope: c, assertCurrent: l, createAdmission: u, maintenanceScope: d, cleanupAccess: f } = r;
		const reject = (e) => {
			a.completed();
			return Promise.reject(e);
		};
		if (this.draining && t.type !== "close" && !c?.active) return reject(new SqliteWorkerError("SQLite worker host is closing", "closed"));
		if (e.failed) return reject(e.failed);
		const p = t.type === "execute" && n > MAX_QUEUED_COMMAND_BYTES;
		const m = sqliteWorkerTransferredInputBytes(t.transferredInput);
		const h = (p ? SQLITE_WORKER_MAX_MESSAGE_BYTES : n) + m;
		if (t.type !== "close" && (t.type !== "execute" && n > 33554432 || p && (e.current || e.queue.length > 0 || e.pendingOpens > 0) || this.bytes + this.inputAdmission.retainedBytes + h > SQLITE_WORKER_MAX_QUEUED_BYTES)) return reject(new SqliteWorkerError("SQLite worker queue capacity reached", "overloaded"));
		if (t.type !== "close" && ((this.requests.get(e) ?? 0) >= 128 || !i && this.waiters.has(e))) {
			if (p || this.draining) return reject(new SqliteWorkerError("SQLite worker queue capacity reached", "overloaded"));
			return this.waitForCapacity(e, t, n, r, a);
		}
		const g = createDeferredCore();
		const _ = {
			custody: s?.custody ?? e.custody.createRequest(),
			observation: a,
			signal: o,
			maintenanceScope: d,
			cleanupAccess: f,
			createAdmission: u,
			assertCurrent: l,
			dispatchState: s,
			request: {
				...t,
				id: ++this.nextRequest,
				databaseAdmissionDeadlineAtMs: readSqliteDatabaseAdmissionDeadline()
			},
			bytes: h,
			result: g.promise,
			resolve: g.resolve,
			reject: g.reject,
			detach: () => o?.removeEventListener("abort", abort)
		};
		const abort = () => {
			_.custody.cancel();
			const t = e.queue.indexOf(_);
			if (t >= 0) {
				e.queue.splice(t, 1);
				this.finish(e, _, o?.reason ?? /* @__PURE__ */ new Error("SQLite worker operation canceled"));
			}
		};
		this.requests.set(e, (this.requests.get(e) ?? 0) + 1);
		this.bytes += h;
		if (p) {
			o?.addEventListener("abort", abort, { once: true });
			if (o?.aborted) this.finish(e, _, o.reason ?? /* @__PURE__ */ new Error("SQLite worker operation canceled"));
			else this.dispatchJob(e, _);
			return g.promise;
		}
		e.queue.push(_);
		o?.addEventListener("abort", abort, { once: true });
		if (o?.aborted) abort();
		this.dispatch(e);
		return g.promise;
	}
	waitForCapacity(e, t, n, r, i) {
		return new Promise((a, o) => {
			const s = Date.now();
			const c = r.signal;
			const l = this.waiters.get(e) ?? /* @__PURE__ */ new Set();
			const resume = (f) => {
				if (!l.delete(resume)) return;
				if (!l.size) this.waiters.delete(e);
				clearTimeout(u);
				c?.removeEventListener("abort", abort);
				d();
				let p = f;
				if (p === void 0 && Date.now() - s >= 1e4) {
					this.warnAdmission(this.waiters.get(e)?.size ?? 0, Date.now() - s);
					p = new SqliteWorkerError("SQLite worker queue capacity reached", "overloaded");
				}
				if (p !== void 0) {
					i.completed();
					o(toErrorObject(p, "SQLite worker admission failed"));
				} else a(this.enqueue(e, t, n, r, true, i));
			};
			const abort = () => resume(c?.reason ?? /* @__PURE__ */ new Error("SQLite worker operation canceled"));
			const u = setTimeout(() => {
				this.warnAdmission(this.waiters.get(e)?.size ?? 0, Date.now() - s);
				resume(new SqliteWorkerError("SQLite worker queue capacity reached", "overloaded"));
			}, SQLITE_WORKER_ADMISSION_TIMEOUT_MS);
			const d = this.inputAdmission.retain(n + sqliteWorkerTransferredInputBytes(t.transferredInput));
			l.add(resume);
			this.waiters.set(e, l);
			c?.addEventListener("abort", abort, { once: true });
			if (c?.aborted) abort();
			else if (l.size >= 128) this.warnAdmission(l.size, 0);
		});
	}
	dispatch(e) {
		if (e.current || e.failed) return;
		const t = e.queue.shift();
		if (!t) {
			e.worker.unref();
			return;
		}
		this.dispatchJob(e, t);
	}
	dispatchJob(e, t) {
		t.custody.activate();
		e.current = t;
		e.worker.ref();
		t.observation.started();
		dispatchSqliteWorkerJob(e, t, (n, r) => {
			if (e.current !== t) return;
			if (r) this.fail(e, n, toErrorObject(n, "SQLite worker transfer failed"));
			else {
				t.custody.retire();
				e.current = void 0;
				this.finish(e, t, n);
				this.dispatch(e);
			}
		});
	}
	finish(e, t, n, r, i) {
		t.observation.completed();
		this.requests.set(e, (this.requests.get(e) ?? 0) - 1);
		this.bytes -= t.bytes;
		settleSqliteWorkerJob(t, n, r, i);
		if (!this.resuming.has(e)) {
			this.resuming.add(e);
			while ((this.requests.get(e) ?? 0) < 128) {
				const t = this.waiters.get(e)?.values().next().value;
				if (!t) break;
				t();
			}
			this.resuming.delete(e);
		}
	}
	fail(e, t, n, r, i) {
		failSqliteWorkerSlot(e, t, {
			currentError: n,
			openOutcome: r,
			completed: i,
			waiters: this.waiters.get(e),
			retire: () => this.lifecycle.retire(e),
			finish: (t, n, r, i) => this.finish(e, t, n, r, i)
		});
	}
	close(e) {
		if (e) {
			this.lifecycle.sealClients(this.waiters.values(), true);
			return e().then(() => this.close());
		}
		this.draining ??= this.lifecycle.closeHost({
			inputAdmission: this.inputAdmission,
			operations: this.operations,
			waiters: this.waiters.values()
		}).then(() => this.clients.clear()).finally(() => {
			this.draining = void 0;
		});
		return this.draining;
	}
};
//#endregion
//#region src/infra/sqlite-worker-store.ts
function withCallerErrors(e) {
	return e.catch((e) => {
		if (e instanceof Error) throw hydrateOpenClawStateWorkerError(e);
		throw e;
	});
}
function bindCallerExecute(e) {
	return { execute: (t, n) => {
		const r = withCallerErrors(e.execute(t, n));
		r.catch(() => void 0);
		return r;
	} };
}
/** Retain one actor through local reconciliation; the callback must not await its own close. */
function runSqliteWorkerStoreOperation(e, t, n, r, i) {
	return withCallerErrors(resolveSqliteWorkerBroker().runOperation(e, (e) => t(bindCallerExecute(e)), n, r, i));
}
function resolveSqliteWorkerBroker() {
	return resolveGlobalSingleton(Symbol.for("openclaw.sqliteWorkerBroker"), () => new SqliteWorkerBroker(), (e) => withCallerErrors(e.close(async () => {
		const { closeOpenClawStateDatabaseAsync: e } = await import("./openclaw-state-db-cache-YCZ8z6gU.mjs");
		await e();
	})), "shared-state");
}
/** Charge captured input before actor preparation can yield, then hand it to normal dispatch. */
function reserveSqliteWorkerInputPreparation(e, t = "stream") {
	return resolveSqliteWorkerBroker().reserveInputPreparation(e, t);
}
/** Read the broker's recorded lifecycle state without probing native storage. */
function isSqliteWorkerStoreAvailable(e) {
	return resolveSqliteWorkerBroker().isAvailable(e);
}
/** Internal identity for the existing canonical actor, never a transferable authority. */
function getSqliteWorkerActorIdentity(e) {
	return resolveSqliteWorkerBroker().getActorIdentity(e);
}
function retireSqliteWorkerActor(e) {
	return withCallerErrors(resolveSqliteWorkerBroker().retireActor(e));
}
/** Recorded orphan custody at its original shared-state opening path. */
function hasUnclaimedSharedStateSqliteCleanup(e) {
	return resolveSqliteWorkerBroker().hasUnclaimedSharedStateCleanup(e);
}
/** Explicit cleanup only; referenced actors and other opening scopes are untouched. */
function closeUnclaimedSharedStateSqliteWorkers(e) {
	return withCallerErrors(resolveSqliteWorkerBroker().closeUnclaimedSharedState(e));
}
/** Host-internal admission for the canonical shared-state actor. */
function openSharedStateSqliteWorkerStore(e, t, n, r) {
	if (!isMainThread) return Promise.reject(new SqliteWorkerError("Shared-state admission requires the host broker", "unavailable"));
	return withCallerErrors(resolveSqliteWorkerBroker().open({
		...e,
		input: void 0
	}, t, n, {
		...r,
		carrierClass: "shared-state"
	})).then((e) => {
		if (e) {
			const t = e.execute.bind(e);
			const n = e.close.bind(e);
			e.execute = bindCallerExecute({ execute: t }).execute;
			e.close = () => withCallerErrors(n());
		}
		return e;
	});
}
//#endregion
//#region src/state/openclaw-state-worker-operation.ts
/** A live alias cannot authorize a worker still bound to a vanished opening path. */
function assertOpenClawStateWorkerActorPath(e) {
	if (openClawStateDatabaseCache.getKnownOpenClawStateDatabaseIdentity(e.databasePath)?.key !== e.key) throw new StateDatabaseReadAdmissionInvalidatedError("Shared-state worker opening path changed");
}
function runWithCapturedWorkerContext(e, t) {
	const n = e.maintenanceScope;
	const run = () => n ? n.run(() => n.track(t())) : t();
	return e.runInCapturedSchemaScope ? e.runInCapturedSchemaScope(run) : run();
}
function runWithOpenClawStateWorkerStore(e, t, n, r, i, a) {
	const { admission: o } = t;
	const s = getSqliteWorkerActorIdentity(e);
	return runSqliteWorkerStoreOperation(e, (e) => n(a ? { execute: (t, n) => e.execute(t, {
		...n,
		signal: n?.signal ? AbortSignal.any([a, n.signal]) : a
	}) } : e), t, (e) => {
		o.assertCurrent();
		assertOpenClawStateWorkerActorPath(s);
		r?.(e);
	}, i);
}
function assertOpenClawStateWorkerSchemaContext(e) {
	isExistingOpenClawStateSchema(e.admission.databasePath);
	if (getExistingOpenClawStateSchemaPath() !== e.existingSchemaPath) throw new Error("Shared-state worker schema context does not match its caller");
}
/** Native opening retains its physical admission, not an individual command's authority. */
function captureOpenClawStateWorkerOpeningGuard(e) {
	const t = e.admission;
	const n = t.identity;
	let r = AsyncLocalStorage.bind(() => t.assertCurrent());
	const assertCurrent = () => {
		if (!r) throw new Error("Shared-state worker opening admission is closed");
		r();
	};
	return {
		assertCurrent,
		createAdmission: () => {
			let e = false;
			return {
				nativeLocations: [t.databasePath],
				databaseIdentity: {
					databasePath: t.databasePath,
					key: n.key,
					birthtime: n.birthtime
				},
				admission: createSqliteWorkerOperationAdmission((t, n) => {
					if (e || t.stage !== "open") throw new Error("Shared-state worker open admission requested out of order");
					assertCurrent();
					if (!n()) throw new Error("Shared-state worker open admission expired");
					e = true;
				})
			};
		},
		async run(e) {
			try {
				return await e();
			} finally {
				r = void 0;
			}
		}
	};
}
//#endregion
//#region src/state/openclaw-state-worker-lease.ts
/** Retain a logical actor resource while tracking only acquisition and individual commands. */
function retainOpenClawStateWorkerLease(e, t, n, r) {
	const i = getPluginSharedStateResourceHost();
	i?.assertSharedStateAdmission();
	const a = e.maintenanceScope;
	e.admission.assertCurrent();
	a?.assertAdmission();
	const o = createDeferredCore();
	const s = createDeferredCore();
	const c = createDeferredCore();
	const l = /* @__PURE__ */ new Set();
	const u = /* @__PURE__ */ new Set();
	let d;
	let f;
	let p;
	let m;
	let h = false;
	let g = false;
	let _;
	let v;
	let y = false;
	o.promise.catch(() => void 0);
	const assertResourceCurrent = () => x?.assertCurrent();
	const assertInvocation = (t) => {
		if (t.phase === "closed" || g) throw new SqliteWorkerError("Shared-state worker operation is closed", "closed");
		e.admission.assertCurrent();
		assertResourceCurrent();
	};
	const assertCommandAdmission = (e) => {
		assertInvocation(e);
		if (e.phase !== "accepting") throw new SqliteWorkerError("Shared-state worker operation is closed", "closed");
	};
	const assertNewOperation = () => {
		if (h) throw new SqliteWorkerError("Shared-state worker lease is closed", "closed");
		e.admission.assertCurrent();
		a?.assertAdmission();
	};
	const retireNative = () => {
		p ??= (async () => {
			await s.promise.catch(() => void 0);
			c.resolve();
			const e = [];
			try {
				await d;
			} catch (t) {
				e.push(t);
			}
			try {
				await f?.();
			} catch (t) {
				e.push(t);
			}
			throwSqliteLifecycleErrors(e, "Shared-state worker lease retirement failed");
		})();
		p.catch(() => void 0);
		return p;
	};
	const retire = () => {
		h = true;
		g = true;
		for (const e of l) e.phase = "closed";
		return retireNative();
	};
	const createOperationScope = (e) => ({ execute: (t, n) => {
		try {
			assertCommandAdmission(e);
		} catch (e) {
			const t = createDeferredCore();
			t.reject(e);
			t.promise.catch(() => void 0);
			return t.promise;
		}
		const run = async () => {
			if (!y) await racePromiseWithAbortSignal(o.promise, n?.signal);
			assertInvocation(e);
			if (!v) throw new SqliteWorkerError("Shared-state worker lease is not ready", "closed");
			return v.execute(t, n);
		};
		const r = (x ? x.run(run) : run()).catch(async (e) => {
			if (_ && !h && !isSqliteWorkerStoreAvailable(_)) try {
				await retire();
			} catch (t) {
				throw new AggregateError([e, t], "Shared-state operation and retirement failed", { cause: t });
			}
			throw e;
		});
		e.pending.add(r);
		const settled = () => e.pending.delete(r);
		r.then(settled, settled);
		return a ? a.track(r) : r;
	} });
	const runOperation = (e) => {
		try {
			assertNewOperation();
		} catch (e) {
			const t = createDeferredCore();
			t.reject(e);
			t.promise.catch(() => void 0);
			return t.promise;
		}
		const t = {
			phase: "accepting",
			pending: /* @__PURE__ */ new Set()
		};
		l.add(t);
		const n = createDeferredCore();
		u.add(n.promise);
		n.promise.catch(() => void 0);
		const run = async () => {
			try {
				return await e(createOperationScope(t));
			} finally {
				if (t.phase === "accepting") t.phase = "draining";
				await Promise.allSettled(t.pending);
				t.phase = "closed";
				l.delete(t);
			}
		};
		run().then((e) => {
			u.delete(n.promise);
			n.resolve(e);
		}, (e) => {
			u.delete(n.promise);
			n.reject(e);
		});
		return n.promise;
	};
	const runWithAdmission = async (e) => i ? i.trackSharedStateWork(() => runOperation(e)) : runOperation(e);
	const release = () => {
		if (g) return retireNative();
		if (m) return m;
		h = true;
		m = (async () => {
			const e = [];
			const t = {
				phase: "accepting",
				pending: /* @__PURE__ */ new Set()
			};
			l.add(t);
			try {
				await o.promise;
				await n?.(createOperationScope(t));
			} catch (t) {
				e.push(t);
			} finally {
				if (t.phase === "accepting") t.phase = "draining";
				await Promise.allSettled(t.pending);
				t.phase = "closed";
				l.delete(t);
			}
			const r = await Promise.allSettled(u);
			e.push(...r.flatMap((e) => e.status === "rejected" ? [e.reason] : []));
			try {
				await retireNative();
			} catch (t) {
				e.push(t);
			}
			throwSqliteLifecycleErrors(e, "Shared-state worker lease cleanup failed");
		})();
		m.catch(() => void 0);
		return m;
	};
	const b = {
		ready: o.promise,
		execute: (e, t) => runWithAdmission((n) => n.execute(e, t)),
		runOperation: runWithAdmission,
		release,
		retire
	};
	a?.own(b, "shared-resources", release);
	const x = a ? captureOpenClawDatabaseMaintenanceResource(b, a) : void 0;
	const acquire = async () => {
		try {
			const n = await getOpenClawStateDatabaseTerminalFailureAsync(e);
			if (n) throw n;
			e.admission.assertCurrent();
			_ = await t.open(e);
			e.admission.assertCurrent();
			if (!_) throw new Error("Canonical shared-state worker did not open its database");
			f = t.retainOperation(_, () => {
				retire();
				r?.();
			});
			d = runWithOpenClawStateWorkerStore(_, e, async (e) => {
				v = e;
				s.resolve();
				await c.promise;
			}, assertResourceCurrent);
			d.catch(s.reject);
			await s.promise;
			e.admission.assertCurrent();
			if (g) throw new SqliteWorkerError("Shared-state worker lease is closed", "closed");
		} catch (e) {
			const t = e instanceof Error ? hydrateOpenClawStateWorkerError(e) : e;
			s.reject(t);
			try {
				await retire();
			} catch (e) {
				if (e !== t) throw new AggregateError([t, e], "Shared-state lease acquisition failed", { cause: e });
			}
			throw t;
		}
	};
	const acquireInContext = () => runWithCapturedWorkerContext(e, acquire);
	(i ? i.trackSharedStateWork(acquireInContext) : acquireInContext()).then(() => {
		y = true;
		o.resolve();
	}, o.reject);
	return b;
}
//#endregion
//#region src/state/openclaw-state-worker-owner.ts
const log = createSubsystemLogger("state/worker");
function createSharedStateWorkerOwner() {
	const e = resolveRuntimeProcessEntrypointUrl("sharedStateStore");
	const t = /* @__PURE__ */ new Set();
	const n = /* @__PURE__ */ new Set();
	const r = /* @__PURE__ */ new Map();
	const i = createStateWorkerMemoryPressureSubscription(() => t.size > 0 || r.size > 0 || n.size > 0, retireIdleWorkers);
	const matches = (e, t) => t === void 0 || e.context.admission.identity.key === t.key;
	const hasActiveActorOperations = (e) => [...n].some((t) => e.actor ? t.actor === e.actor : t === e);
	const clearIdleRetirement = (e) => {
		e.idleSince = void 0;
		clearTimeout(e.idleTimer);
		e.idleTimer = void 0;
	};
	const hasPendingCleanup = (e) => e.cleanup?.pending ?? (!e.context.maintenanceScope && hasUnclaimedSharedStateSqliteCleanup(e.context.admission.databasePath));
	const retire = (e) => {
		clearIdleRetirement(e);
		t.delete(e);
		let n = r.get(e);
		if (!n) {
			n = {};
			r.set(e, n);
		}
		i();
		if (n.pending) return n.pending;
		const a = e.store ? e.store.close() : e.opening.then((e) => e?.close(), () => e.cleanup ? e.cleanup.close() : e.context.maintenanceScope ? void 0 : closeUnclaimedSharedStateSqliteWorkers(e.context.admission.databasePath));
		n.pending = a;
		const settled = () => {
			n.pending = void 0;
			if (!hasPendingCleanup(e)) r.delete(e);
			i();
		};
		a.then(settled, settled);
		return a;
	};
	const scheduleIdleRetirement = (e) => {
		if (e.activeOperations !== 0 || e.idleTimer || e.context.maintenanceScope || !e.store || !t.has(e)) return;
		e.idleSince = performance.now();
		const n = runInDetachedAsyncContext(() => setTimeout(() => {
			if (e.idleTimer !== n || e.activeOperations !== 0 || !t.has(e)) return;
			e.idleTimer = void 0;
			retire(e).catch((t) => {
				log.warn("Idle shared-state worker retirement failed", {
					path: e.context.admission.databasePath,
					error: t
				});
			});
		}, SQLITE_IDLE_HANDLE_TTL_MS));
		e.idleTimer = n;
		n.unref?.();
	};
	const retireAfterFailure = async (e, t, n) => {
		try {
			await retire(e);
		} catch (e) {
			throw new AggregateError([t, e], `Shared-state worker ${n} and cleanup failed`, { cause: e });
		}
		throw t;
	};
	const retainOperation = (e, r) => {
		const a = [...t].find((t) => t.store === e);
		if (!a) throw new Error("Shared-state worker operation lost its actor owner");
		clearIdleRetirement(a);
		a.activeOperations += 1;
		n.add(a);
		if (r) {
			a.nativeLostListeners.add(r);
			if (!isSqliteWorkerStoreAvailable(e)) r();
		}
		let o = false;
		return () => {
			if (o) return;
			o = true;
			if (r) a.nativeLostListeners.delete(r);
			a.activeOperations -= 1;
			if (a.activeOperations === 0) n.delete(a);
			i();
			if (t.has(a) && !isSqliteWorkerStoreAvailable(e) && !hasActiveActorOperations(a)) {
				const e = a.actor ? retireActor(a.actor) : retire(a);
				e.catch((e) => {
					log.warn("Shared-state worker retirement failed", {
						path: a.context.admission.databasePath,
						error: e
					});
				});
				return e;
			}
			scheduleIdleRetirement(a);
		};
	};
	const retireActor = (e) => {
		const n = retireSqliteWorkerActor(e);
		for (const n of /* @__PURE__ */ new Set([...t, ...r.keys()])) if (n.actor === e) retire(n);
		return n;
	};
	async function close(e) {
		for (const n of t.values()) if (matches(n, e)) retire(n);
		const n = (await Promise.allSettled([...r.keys()].filter((t) => matches(t, e)).map(retire))).flatMap((e) => e.status === "rejected" ? [e.reason] : []);
		i();
		if (n.length) throw new AggregateError(n, "Failed to close shared-state SQLite workers");
	}
	registerOpenClawStateDatabaseAsyncResource({
		phase: "after-resources",
		close
	});
	registerOpenClawStateDatabaseLifecycleListener((e) => {
		if (e.kind !== "opened") {
			if (!e.identity) return;
			close(e.identity).catch((t) => {
				log.warn("Shared-state worker retirement failed", {
					path: e.path,
					error: t
				});
			});
		}
	});
	function retireIdleWorkers(e) {
		for (const n of t) {
			if (!isWorkerIdleForPressure(n.idleSince, e)) continue;
			runInDetachedAsyncContext(() => retireIdle(n))?.catch((e) => {
				log.warn("Idle shared-state worker retirement failed", {
					path: n.context.admission.databasePath,
					error: e
				});
			});
		}
	}
	const retireIdle = (e) => e.idleTimer && e.store && t.has(e) && !e.context.maintenanceScope && !hasActiveActorOperations(e) ? retire(e) : void 0;
	return {
		close,
		retainOperation,
		async openCleanup(i, a, o, s, c) {
			const l = { ...s };
			o();
			if (!l.key.startsWith("file:")) return;
			const assertCurrent = () => {
				o();
				for (const e of n) if (matches(e, l) && e.store && !isSqliteWorkerStoreAvailable(e.store)) throw new SqliteWorkerError("Shared-state cleanup is waiting for accepted operations to settle", "unavailable");
			};
			assertCurrent();
			for (const e of /* @__PURE__ */ new Set([...t, ...r.keys()])) if ((t.has(e) || r.has(e)) && matches(e, l) && e.store && !isSqliteWorkerStoreAvailable(e.store)) {
				assertCurrent();
				await (e.actor ? retireActor(e.actor) : retire(e));
				assertCurrent();
			}
			return openSharedStateSqliteWorkerStore({
				...captureRuntimeWorkerSource(e),
				databasePath: i,
				existingOnly: true,
				admission: {
					identity: l.key,
					birthtime: l.birthtime,
					assertCurrent
				}
			}, a, assertCurrent, { cleanupAccess: c && { assertDatabaseAccess: c.assertCleanupDatabaseAccess } });
		},
		async open(n, a = {}) {
			const { existingOnly: o = false, assertCurrent: s, signal: c } = a;
			const { admission: l } = n;
			const wait = (e) => racePromiseWithAbortSignal(e, c);
			const u = captureRuntimeWorkerSource(e);
			const assertAdmission = () => {
				c?.throwIfAborted();
				l.assertCurrent();
				s?.();
			};
			assertAdmission();
			assertOpenClawStateWorkerSchemaContext(n);
			for (const e of /* @__PURE__ */ new Set([...t, ...r.keys()])) {
				if (!matches(e, l.identity)) continue;
				if (t.has(e) && (e.context.existingSchemaPath !== n.existingSchemaPath || !isDeepStrictEqual(e.context.gatewayServiceInstallation, n.gatewayServiceInstallation) || e.source.moduleUrl.href !== u.moduleUrl.href)) {
					if (hasActiveActorOperations(e)) throw new Error("Shared-state worker policy changed while its actor is in use; close its leases first");
					await wait(e.actor ? retireActor(e.actor) : retire(e));
					assertAdmission();
				}
			}
			for (const [e, t] of r) if (matches(e, l.identity) && e.context.maintenanceScope === n.maintenanceScope) {
				if (hasActiveActorOperations(e)) throw new Error("Shared-state worker is retiring while its actor is in use; close its leases first");
				if (!t.pending) {
					if (!hasPendingCleanup(e)) {
						r.delete(e);
						i();
						continue;
					}
					throw new Error("Shared-state SQLite cleanup is pending; close the database before reopening");
				}
				try {
					await wait(t.pending);
				} catch (n) {
					if (r.get(e) === t) throw n;
				}
				assertAdmission();
			}
			assertAdmission();
			let d = [...t].find((e) => matches(e, l.identity) && e.context.maintenanceScope === n.maintenanceScope && e.context.existingSchemaPath === n.existingSchemaPath && isDeepStrictEqual(e.context.gatewayServiceInstallation, n.gatewayServiceInstallation));
			const f = !d;
			if (!d) {
				const e = captureOpenClawStateWorkerOpeningGuard(n);
				const a = /* @__PURE__ */ new Set();
				const open = () => e.run(() => openSharedStateSqliteWorkerStore({
					...u,
					databasePath: l.databasePath,
					existingOnly: o
				}, n, e.assertCurrent, {
					maintenanceScope: n.maintenanceScope,
					...o && l.identity.key.startsWith("file:") ? { createAdmission: e.createAdmission } : {},
					retireIdle: retireIdle.bind(void 0, s),
					retainCleanup: (e) => {
						s.cleanup = e;
					},
					onNativeLost: notifyListeners.bind(void 0, a, void 0, void 0)
				}));
				const s = {
					source: u,
					context: n,
					existingOnly: o,
					nativeLostListeners: a,
					activeOperations: 0,
					opening: Promise.resolve(void 0)
				};
				s.opening = n.maintenanceScope ? open() : runInDetachedAsyncContext(open);
				d = s;
				s.opening = s.opening.then((e) => {
					if (e) {
						s.store = e;
						s.actor = getSqliteWorkerActorIdentity(e);
						scheduleIdleRetirement(s);
					} else {
						t.delete(s);
						i();
					}
					return e;
				});
				t.add(d);
				i();
				n.maintenanceScope?.own(d, "shared-resources", () => retire(s));
				d.opening.catch(() => {
					t.delete(s);
					if (hasPendingCleanup(s) && !r.has(s)) r.set(s, {});
					i();
				});
			}
			const p = await (f ? d.opening : wait(d.opening));
			try {
				l.assertCurrent();
			} catch (e) {
				return retireAfterFailure(d, e, "admission");
			}
			c?.throwIfAborted();
			s?.();
			if (!p) return !o && d.existingOnly ? this.open(n, {
				...a,
				existingOnly: false
			}) : void 0;
			if (!t.has(d)) return this.open(n, a);
			clearIdleRetirement(d);
			if (!isSqliteWorkerStoreAvailable(p) && !hasActiveActorOperations(d)) {
				await wait(d.actor ? retireActor(d.actor) : retire(d));
				return this.open(n, a);
			}
			try {
				if (!d.bound) {
					publishOpenClawStateDatabaseWorkerAdmission(d.context.admission, getSqliteWorkerActorIdentity(p).identity);
					d.bound = true;
				}
			} catch (e) {
				return retireAfterFailure(d, e, "binding");
			}
			if (d.actor) assertOpenClawStateWorkerActorPath(d.actor);
			t.delete(d);
			t.add(d);
			return p;
		}
	};
}
function getOpenClawStateWorkerOwner() {
	assertPublishedOpenClawStateDatabaseLifecycle();
	return resolveGlobalSingleton(Symbol.for("openclaw.sharedStateWorkerOwner"), createSharedStateWorkerOwner);
}
//#endregion
//#region src/state/openclaw-state-worker-store.ts
/** Retain the canonical actor for capture callbacks and their terminal writes. */
function createOpenClawStateWorkerLease(e, t, n) {
	return retainOpenClawStateWorkerLease(e, {
		open: (e) => getOpenClawStateWorkerOwner().open(e),
		retainOperation: (e, t) => getOpenClawStateWorkerOwner().retainOperation(e, t)
	}, t, n);
}
async function runOpenClawStateWorkerOperation(e, t, n) {
	return runPluginSharedStateWork(() => runWithCapturedWorkerContext(e, async () => {
		try {
			n?.signal?.throwIfAborted();
			e.admission.assertCurrent();
			n?.assertCurrent?.();
			const r = await getOpenClawStateDatabaseTerminalFailureAsync(e, n?.signal);
			if (r) throw r;
			e.admission.assertCurrent();
			n?.assertCurrent?.();
			const i = await getOpenClawStateWorkerOwner().open(e, n);
			if (!i) {
				n?.signal?.throwIfAborted();
				e.admission.assertCurrent();
				if (n?.existingOnly) return;
				throw new Error("Canonical shared-state worker did not open its database");
			}
			const a = getOpenClawStateWorkerOwner().retainOperation(i);
			try {
				n?.signal?.throwIfAborted();
				e.admission.assertCurrent();
				n?.assertCurrent?.();
				return await runWithOpenClawStateWorkerStore(i, e, t, n?.assertCurrent, n?.createAdmission, n?.signal);
			} finally {
				a();
			}
		} catch (t) {
			const n = hydrateOpenClawStateWorkerError(t);
			const r = findOpenClawStateDatabaseFailure(n, e.admission.databasePath);
			if (r && !openClawStateDatabaseCache.getOpenClawStateDatabaseRecordedFailure(e.admission.databasePath)) {
				try {
					e.admission.assertCurrent();
				} catch {
					throw n;
				}
				recordOpenClawStateDatabaseOpenFailure(e.admission.databasePath, r);
			}
			throw n;
		}
	}));
}
//#endregion
export { acquireWithWait as a, acquireSqliteDatabaseAdmissionTurn as i, runOpenClawStateWorkerOperation as n, runPluginSharedStateWork as o, reserveSqliteWorkerInputPreparation as r, createOpenClawStateWorkerLease as t };