UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3,549 lines • 109 kB
import { y as toErrorObject } from "./paths-0xDagtub.mjs";
import { p as isRecord } from "./utils-BclMknzT.mjs";
import { F as resolveTimerTimeoutMs, W as resolveGlobalSingleton } from "./path-guards-quCEQx1i.mjs";
import { d as workerScriptName, f as runWithMainThreadTask, g as hasInternalDiagnosticEventInterest, l as areDiagnosticsEnabledForProcess, p as isDiagnosticFlagEnabled, t as createSubsystemLogger, u as emitTrustedDiagnosticEvent } from "./subsystem-CeOCPr4l.mjs";
import { n as materializeErrorStack } from "./error-graph-internal-G5_kmB_7.mjs";
import { i as runInDetachedAsyncContext, r as runWithAsyncStore } from "./plugin-instance-invocation-DLc0_aJ8.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as isPromiseLike } from "./promise-like-aMoWEh5w.mjs";
import { A as trackSqliteDatabaseAdmissionWorker, it as captureSqliteDatabaseAdmissions, st as createSqliteDatabaseAdmissionCursor, ut as captureSqliteWorkerEnvironmentData } from "./sqlite-database-admission-DMm34jqt.mjs";
import { n as runtimeProcessEntrypoints } from "./runtime-process-entrypoints-EnWn_nGl.mjs";
import { a as MAX_PENDING_BYTES, f as SpawnBrokerError, i as decodeNativeWorkerFailure, n as BrokerNativeResourceCloseError, o as createBrokerReceiver, r as spawnBrokerStartupNowMs, s as createBrokerSender, t as createSpawnBrokerHost } from "./host-CAR9TGXT.mjs";
import { r as resolveRuntimeWorkerThreadExecArgv } from "./runtime-worker-url-BEfqe_m6.mjs";
import { a as resolveRuntimeProcessEntrypointUrl } from "./runtime-process-url-sztU0Vcb.mjs";
import { a as markWorkerRetirement, c as trackNativeWorkerForCpu, i as isWorkerGcObservationEnabled, l as createRetainedOperation, m as resolveRuntimeWorkerGenerationUrl, n as createCpuTrackedWorker, o as receiveWorkerMemoryPort, p as captureRuntimeWorkerSource, r as flushWorkerDiagnostics, s as recordPostgresPoolSelfRoot, t as attributeWorkerToPool } from "./worker-cpu-sx0tpDpz.mjs";
import { t as captureDeletedAgentDatabaseFences } from "./agent-database-readers-JO-3dg3f.mjs";
import { a as classifyWorkerRequest, i as workerMessagePayloadBytes, n as observeWorkerMessage, o as normalizeWorkerRequestClass, r as recordWorkerMessage } from "./worker-message-metrics-DnNsI1Wf.mjs";
import { b as readSqliteDatabaseAdmissionDeadline, r as createSqliteDatabaseAdmissionRelay } from "./sqlite-worker-operation-admission-DjndFB3C.mjs";
import { AsyncLocalStorage, AsyncResource } from "node:async_hooks";
import { readFileSync, statSync } from "node:fs";
import path, { basename } from "node:path";
import { fileURLToPath } from "node:url";
import { createHash } from "node:crypto";
import fsPromises from "node:fs/promises";
import os, { availableParallelism } from "node:os";
import { channel } from "node:diagnostics_channel";
import { performance as performance$1 } from "node:perf_hooks";
import { BroadcastChannel, MessageChannel, SHARE_ENV, Worker, isMainThread, receiveMessageOnPort, threadId, workerData } from "node:worker_threads";
import { connect } from "node:net";
import { deserialize, serialize } from "node:v8";
import { EventEmitter } from "node:events";
import { setImmediate as setImmediate$1 } from "node:timers/promises";
//#region node-compile-cache.mjs
if (isMainThread && process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED === "gateway") {
	delete process.env.NODE_DISABLE_COMPILE_CACHE;
	delete process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED;
}
const MAX_BYTES = 536870912;
const MAX_AGE_MS = 6048e5;
const MAINTENANCE_INTERVAL_MS = 36e5;
const MAX_FILES = 4096;
const MAX_VISITS = 16384;
const MAINTENANCE_BUDGET_MS = 3e4;
const BUILD_MARKER_RE = /^(?:[a-f0-9]{16}|\d+-\d+|no-package-json|build-[A-Za-z0-9._-]+)$/;
const sanitize = (e) => {
	const t = e.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
	return t && t !== "." && t !== ".." ? t : "unknown";
};
function resolveSafeNodeCompileCacheDirectory(e) {
	if (process.platform === "win32" && path.resolve(e).length > 200) {
		process.stderr.write("[openclaw] Compile cache disabled: Windows cache path exceeds 200 characters.\n");
		return;
	}
	return e;
}
async function maintain(e) {
	const t = path.dirname(path.dirname(e));
	const n = path.basename(path.dirname(e));
	if (path.basename(t) !== "openclaw" || sanitize(n) !== n || !BUILD_MARKER_RE.test(path.basename(e))) return;
	const r = Date.now();
	const i = await fsPromises.lstat(t).catch(() => void 0);
	for (const n of [
		t,
		path.dirname(e),
		e
	]) {
		const e = n === t ? i : await fsPromises.lstat(n).catch(() => void 0);
		if (e && !e.isDirectory()) return;
	}
	if (i && r - i.mtimeMs < MAINTENANCE_INTERVAL_MS) return;
	await fsPromises.mkdir(t, { recursive: true });
	const a = `${t}.maintenance`;
	const o = await fsPromises.lstat(a).catch(() => void 0);
	if (o && r - o.mtimeMs > 3e5) await fsPromises.rmdir(a).catch(() => {});
	if (!await fsPromises.mkdir(a).then(() => true, () => false)) return;
	const s = [];
	let c = 0;
	let l = 0;
	let u = false;
	async function prune() {
		s.sort((e, t) => t.mtimeMs - e.mtimeMs);
		while (s.length) {
			if (Date.now() - r > MAINTENANCE_BUDGET_MS) return false;
			const e = s[s.length - 1];
			if (c <= MAX_BYTES && s.length <= MAX_FILES && r - e.mtimeMs <= MAX_AGE_MS) break;
			await fsPromises.unlink(e.file).catch((e) => {
				if (e.code !== "ENOENT") throw e;
			});
			c -= e.size;
			s.pop();
		}
		return true;
	}
	async function visit(e) {
		for await (const t of await fsPromises.opendir(e)) {
			if (++l > MAX_VISITS || Date.now() - r > MAINTENANCE_BUDGET_MS) return false;
			const n = path.join(e, t.name);
			if (t.isDirectory()) {
				if (!await visit(n)) return false;
			} else if (t.isFile()) {
				const e = await fsPromises.lstat(n).catch((e) => {
					if (e.code !== "ENOENT") throw e;
				});
				if (!e) continue;
				c += e.size;
				s.push({
					file: n,
					size: e.size,
					mtimeMs: e.mtimeMs
				});
				if (s.length % 256 === 0 && !await prune()) return false;
			}
		}
		return true;
	}
	try {
		if (r - (await fsPromises.lstat(t)).mtimeMs < MAINTENANCE_INTERVAL_MS) {
			u = true;
			return;
		}
		const e = await visit(t);
		if (await prune() && e) {
			const e = /* @__PURE__ */ new Date();
			await fsPromises.utimes(t, e, e);
			u = true;
		}
	} finally {
		if (!u) await fsPromises.utimes(t, i?.atime ?? /* @__PURE__ */ new Date(0), i?.mtime ?? /* @__PURE__ */ new Date(0)).catch(() => {});
		await fsPromises.rmdir(a);
	}
}
if (process.argv[2] === "--maintain" && process.argv[1] === fileURLToPath(import.meta.url) && process.argv[3]) maintain(process.argv[3]).catch(() => {});
//#endregion
//#region src/infra/node-compile-cache-env.ts
const COMPILE_CACHE_BASE_KEY = Symbol.for("openclaw.nodeCompileCacheBase");
function resolveNodeCompileCacheEnv(e = process.env) {
	if (e.NODE_DISABLE_COMPILE_CACHE !== void 0) return e;
	const t = e.NODE_COMPILE_CACHE ?? resolveGlobalSingleton(COMPILE_CACHE_BASE_KEY, () => ({})).baseDirectory;
	if (t && !resolveSafeNodeCompileCacheDirectory(t)) {
		const t = {
			...e,
			NODE_DISABLE_COMPILE_CACHE: "1"
		};
		delete t.NODE_COMPILE_CACHE;
		return t;
	}
	if (e.NODE_COMPILE_CACHE !== void 0) return e;
	return t ? {
		...e,
		NODE_COMPILE_CACHE: t
	} : e;
}
//#endregion
//#region packages/worker-runtime/src/worker-task-capacity.ts
const DEFAULT_WORKER_PENDING_TASKS = 128;
const DEFAULT_WORKER_PENDING_BYTES = 268435456;
/** Shared compute admission; database and generation workers keep their own ordering. */
function createWorkerComputeCapacity(e) {
	if (!Number.isSafeInteger(e) || e < 1) throw new RangeError("compute capacity must be a positive safe integer");
	const t = /* @__PURE__ */ new Set();
	const n = /* @__PURE__ */ new Set();
	const r = /* @__PURE__ */ new Set();
	let i = 0;
	let a = 0;
	let o = false;
	const canAdmit = (e) => i < 128 && a + e <= 268435456;
	const requestCheckpoints = () => {
		let e = n.size;
		if (e) {
			for (const n of t) if (n.requestCheckpoint() && --e === 0) break;
		}
	};
	const drain = () => {
		if (o) return;
		o = true;
		try {
			while (t.size < e && n.size) {
				const e = n.values().next().value;
				n.delete(e);
				e();
			}
		} finally {
			o = false;
		}
		requestCheckpoints();
	};
	return {
		getSnapshot: () => ({
			limit: e,
			active: t.size,
			waitingPools: n.size,
			pendingTasks: i,
			pendingBytes: a
		}),
		canAdmit,
		subscribeAdmission(e) {
			r.add(e);
			return () => r.delete(e);
		},
		admit(e) {
			if (!canAdmit(e)) return false;
			i++;
			a += e;
			return true;
		},
		finish(e) {
			i--;
			a -= e;
			for (const e of r) e();
		},
		acquire(r, i) {
			if (t.size >= e || !o && n.size) {
				n.add(r);
				requestCheckpoints();
				return;
			}
			const a = { requestCheckpoint: i };
			t.add(a);
			return a;
		},
		release(e) {
			t.delete(e);
			drain();
		},
		remove(e) {
			n.delete(e);
		},
		requestCheckpoints
	};
}
//#endregion
//#region packages/worker-runtime/src/worker-task-error.ts
var WorkerTaskError = class extends Error {
	constructor(e, t, n) {
		super(e, n);
		this.code = t;
		this.name = "WorkerTaskError";
		this.capacityAvailable = n?.capacityAvailable;
	}
};
function workerTaskTimeoutError(e, t) {
	let n = e?.sent === false ? e.name : void 0;
	if (n === "unknown") n = t.protocol === "file:" ? t.pathname.split("/").at(-1)?.slice(0, 96) || "worker" : `${t.protocol} worker`;
	const r = new WorkerTaskError(n ? `worker task timed out waiting for host callback ${n}` : "worker task timed out", "timeout");
	if (n) process.emitWarning(r.message, { code: "WORKER_HOST_CALLBACK_TIMEOUT" });
	return r;
}
//#endregion
//#region packages/worker-runtime/src/worker-task-admission.ts
/** Class 0 (point reads) keeps its own arrival order ahead of every queued bulk task. */
function enqueueWorkerTask(e, t) {
	const n = t.options.pointRead ? e.findIndex((e) => !e.options.pointRead) : -1;
	e.splice(n === -1 ? e.length : n, 0, t);
}
/** Owns a pool's admitted inputs and notifies rejected callers when their budget can fit. */
var WorkerTaskAdmission = class {
	constructor(e, t, n) {
		this.maxPendingTasks = e;
		this.maxPendingBytes = t;
		this.shared = n;
		this.taskCount = 0;
		this.byteCount = 0;
		this.closed = false;
		this.waiters = /* @__PURE__ */ new Map();
		this.notify = () => {
			for (const [e, t] of this.waiters) if (this.closed || this.taskCount < this.maxPendingTasks && this.byteCount + e <= this.maxPendingBytes && (!this.shared || this.shared.canAdmit(e))) {
				this.waiters.delete(e);
				t.resolve();
			}
			if (!this.waiters.size) {
				this.stopWatchingCapacity?.();
				this.stopWatchingCapacity = void 0;
			}
		};
		for (const [n, r] of Object.entries({
			maxPendingTasks: e,
			maxPendingBytes: t
		})) if (!Number.isSafeInteger(r) || r < 1) throw new RangeError(`${n} must be a positive safe integer`);
	}
	get pendingTasks() {
		return this.taskCount;
	}
	get pendingBytes() {
		return this.byteCount;
	}
	/** Class 0 skips bulk admission but cannot request callbacks into the host. */
	admitTask(e) {
		const { pointRead: t, onRequest: n, onRequestSync: r } = e.options;
		if (t) return n || r ? /* @__PURE__ */ new TypeError("Point reads carry their facts and cannot call back into the host") : void 0;
		e.admitted = this.admit(e.inputBytes);
		return e.admitted ? void 0 : new WorkerTaskError("worker task capacity reached", "overloaded", { capacityAvailable: this.waitForCapacity(e.inputBytes) });
	}
	admit(e) {
		if (this.taskCount >= this.maxPendingTasks || this.byteCount + e > this.maxPendingBytes || this.shared && !this.shared.admit(e)) return false;
		this.taskCount++;
		this.byteCount += e;
		return true;
	}
	finish(e) {
		this.taskCount--;
		this.byteCount -= e;
		this.shared?.finish(e);
		this.notify();
	}
	close() {
		this.closed = true;
		this.notify();
	}
	waitForCapacity(e) {
		if (e > this.maxPendingBytes || this.shared && e > 268435456) return;
		const t = this.waiters.get(e);
		if (t) return t.promise;
		const n = Promise.withResolvers();
		this.waiters.set(e, n);
		this.stopWatchingCapacity ??= this.shared?.subscribeAdmission(this.notify);
		this.notify();
		return n.promise;
	}
};
//#endregion
//#region packages/worker-runtime/src/worker-task-context.ts
function captureWorkerTaskContext() {
	const e = new AsyncResource("OpenClaw.WorkerTask");
	return (t) => e.runInAsyncScope(t);
}
//#endregion
//#region packages/worker-runtime/src/worker-task-host.ts
/** Capture before callbacks so nested servicing advances a fresh set of owners. */
function serviceNativeWorkerPass(e, t) {
	const n = [];
	for (const e of t) if (e.native) n.push(e.native);
	e.serviceNativeWorkers(n);
}
//#endregion
//#region packages/worker-runtime/src/worker-task-native-sections.ts
const CANCELLED = 1;
const SECTION = 2;
const nativeSectionKey = Symbol.for("openclaw.workerTaskNativeSection");
const nativeSectionStore = globalThis;
const currentNativeSection = nativeSectionStore[nativeSectionKey] ??= new AsyncLocalStorage();
function createWorkerNativeSectionState() {
	return new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
}
function cancelWorkerNativeSections(e) {
	Atomics.or(e, 0, CANCELLED);
	Atomics.notify(e, 0);
}
function waitForWorkerNativeSections(e) {
	if (areWorkerNativeSectionsSettled(e)) return;
	return (async () => {
		for (;;) {
			const t = Atomics.load(e, 0);
			if (t < SECTION) return;
			await Atomics.waitAsync(e, 0, t).value;
		}
	})();
}
/** Cancellation must close admission before this fact permits native termination. */
function areWorkerNativeSectionsSettled(e) {
	return Atomics.load(e, 0) < SECTION;
}
function releaseWorkerNativeSectionsOnExit(e) {
	Atomics.store(e, 0, CANCELLED);
	Atomics.notify(e, 0);
}
//#endregion
//#region packages/worker-runtime/src/worker-task-pool-bootstrap.ts
/** A failed bootstrap stops new construction until its generation is rotated. */
function createWorkerTaskPoolBootstrap(e, t, n) {
	let r;
	const admissionError = () => r && ![...e].some((e) => e.ready === true && !e.retiring && !e.retirementFailed) ? r : void 0;
	const rejectQueued = () => {
		const e = admissionError();
		if (!e) return;
		const r = t.splice(0);
		for (const t of r) n(t, e);
	};
	return {
		error: () => r,
		get admissionError() {
			return admissionError();
		},
		fail(e) {
			r ??= e;
			rejectQueued();
		},
		rejectQueued,
		reset: () => {
			r = void 0;
		}
	};
}
//#endregion
//#region packages/worker-runtime/src/worker-task-pool-owned.ts
function createWorkerHostExchange(e, t) {
	const n = isRecord(t) ? t.kind ?? t.type : t;
	return e.exchange = {
		id: ++e.exchangeSequence,
		name: typeof n === "string" && /^[a-zA-Z][a-zA-Z0-9._:-]{0,95}$/.test(n) ? n : "unknown",
		pressure: new AbortController(),
		sent: false,
		onConsumed: void 0
	};
}
function dispatchOwnedWorkerRequest(e, t, n, r, i) {
	const a = {
		signal: (e.controller ??= new AbortController()).signal,
		yieldSignal: r.pressure.signal
	};
	const assertCurrent = () => {
		if (e.done || t.task !== e) throw new WorkerTaskError("worker task closed before host dispatch", "unavailable");
	};
	if (e.options.onRequestSync) {
		try {
			assertCurrent();
			i.accept(e.options.onRequestSync(n, a));
		} catch (e) {
			i.reject(e);
		}
		return;
	}
	Promise.resolve().then(() => {
		assertCurrent();
		return e.options.onRequest(n, a);
	}).then(i.accept).catch(i.reject);
}
async function joinOwnedWorkerTasks(e) {
	const t = (await Promise.allSettled(e)).flatMap((e) => e.status === "rejected" ? [e.reason] : []);
	if (t.length === 1) throw t[0];
	if (t.length > 1) throw new AggregateError(t, "Worker task cleanup failed");
}
function joinOwnedWorkerTask(e, t, n = false) {
	return startJoinOwnedWorkerTask(e, t, n).result;
}
function startJoinOwnedWorkerTask(e, t, n) {
	const r = startCloseOwnedWorkerTask(e, t, n);
	const observe = () => {
		const n = r.read();
		if (n.status === "pending") return n;
		if (n.status === "rejected" && e.owner?.closing === r) e.owner.closing = void 0;
		if (e.owner?.closed) {
			const n = e.slot;
			e.slot = void 0;
			t.release(e, n);
		}
		return n;
	};
	const i = r.result.then(() => {
		observe();
	}, (e) => {
		observe();
		throw e;
	});
	i.catch(() => void 0);
	return {
		result: i,
		read: observe,
		service() {
			r.service();
			observe();
		}
	};
}
function closeOwnedWorkerTask(e, t, n = false) {
	return startCloseOwnedWorkerTask(e, t, n).result;
}
function startCloseOwnedWorkerTask(e, t, n) {
	const r = e.owner;
	if (!r || r.closed) {
		if (r?.closing) return r.closing;
		const e = createRetainedOperation(() => {});
		e.resolve();
		return e.operation;
	}
	r.retire ||= n;
	if (r.closing) return r.closing;
	let i;
	let a;
	let o = false;
	const s = createRetainedOperation(() => {
		i?.service();
		advance();
	});
	const advance = () => {
		if (o || s.operation.read().status !== "pending") return;
		o = true;
		try {
			if (e.preparation) {
				if (a !== e.preparation.promise) {
					a = e.preparation.promise;
					a.then(advance, s.reject);
				}
				return;
			}
			const n = e.slot;
			if (n && r.retire) {
				if (!i) {
					i = t.retire(n);
					i.result.then(advance, advance);
				}
				const e = i.read();
				if (e.status === "pending") return;
				if (e.status === "rejected") throw e.error;
			}
			t.detach(e);
			try {
				r.complete?.();
			} finally {
				r.closed = true;
				r.complete = void 0;
				e.input = void 0;
				e.options = {};
				e.abort = () => {};
			}
			s.resolve();
		} catch (e) {
			s.reject(e);
		} finally {
			o = false;
		}
	};
	r.closing = s.operation;
	if (!e.done) t.cancel(e);
	advance();
	return s.operation;
}
function retainWorkerTask(e, t, n) {
	return {
		result: e.promise,
		read: () => e.read(),
		service: n,
		release: (r) => {
			const i = startJoinOwnedWorkerTask(e, t, r?.retire === true);
			return {
				result: i.result,
				read: () => i.read(),
				service: () => {
					n();
					i.service();
				}
			};
		}
	};
}
function prepareWorkerTaskInput(e, t, n, r) {
	const i = e.input;
	e.input = void 0;
	const a = Promise.withResolvers();
	e.preparation = a;
	const finishPreparation = () => {
		a.resolve();
		if (e.preparation === a) e.preparation = void 0;
	};
	const failed = (e) => {
		finishPreparation();
		n(e);
	};
	let o;
	try {
		o = typeof i === "function" ? i() : i;
	} catch (e) {
		failed(e);
		return;
	}
	if (r) o = Promise.resolve(o).then(async (e) => {
		await r();
		return e;
	});
	const ready = (e) => {
		finishPreparation();
		t(e);
	};
	if (isPromiseLike(o)) Promise.resolve(o).then(ready, failed);
	else ready(o);
}
function armWorkerTaskTimeout(e, t, n, r) {
	if (t === void 0 || r && (e.options.timeoutFrom ?? "enqueue") !== r) return;
	clearTimeout(e.timer);
	const i = performance.now();
	e.deadline = Math.min(e.options.hostTimeout !== "owner" && e.options.timeoutMs !== void 0 ? e.deadline ?? (e.options.timeoutFrom === "dispatch" ? i : e.enqueuedAt) + resolveTimerTimeoutMs(e.options.timeoutMs, 6e4) : Infinity, i + resolveTimerTimeoutMs(t, 6e4));
	e.timer = setTimeout(n, Math.max(0, e.deadline - i), e);
}
function expireWorkerTasks(e, t, n) {
	const r = performance.now();
	const i = [...e, ...[...t].flatMap((e) => e.task ? [e.task] : [])];
	for (const e of i) if (!e.done && e.deadline !== void 0 && r >= e.deadline) n(e);
}
//#endregion
//#region packages/worker-runtime/src/worker-task-pool-completion.ts
const taskDiagnostics = channel("openclaw.worker.task");
function joinWorkerTaskPreparationCleanups(e, t) {
	return joinOwnedWorkerTasks([...[...e.preparationCleanups].map(([t, n]) => n.finally(() => {
		if (e.preparationCleanups.delete(t)) e.releaseAdmission(t);
	})), t.then(() => void 0)]);
}
function notifyExecutionSettled(e) {
	try {
		if (!e.executionNotified) {
			e.executionNotified = true;
			e.options.onExecutionSettled?.({ retired: e.slot?.retired === true });
		}
	} catch (e) {
		return toErrorObject(e, "worker settlement receipt failed");
	}
}
function createWorkerTaskCompletion(e, t, n, r) {
	const i = e.owner ? void 0 : e.preparation;
	let a;
	const complete = () => {
		if (!e.owner && !i) t.releaseAdmission(e);
		return completeWorkerTask(e, t, n, r, a);
	};
	if (!i) return complete;
	const o = Promise.withResolvers();
	t.preparationCleanups.set(e, o.promise);
	o.promise.catch(() => void 0);
	return () => {
		a = e.runInContext(() => notifyExecutionSettled(e));
		if (n) e.reject(n);
		i.promise.then(() => {
			const n = complete();
			if (n) throw n;
			t.preparationCleanups.delete(e);
			t.releaseAdmission(e);
			o.resolve();
		}).catch(o.reject);
	};
}
function completeWorkerTask(e, t, n, r, i) {
	return e.runInContext(() => {
		let a = n ?? i;
		const o = i ? [i] : [];
		try {
			if (!e.inputConsumed) {
				e.inputConsumed = true;
				e.options.onInputConsumed?.();
			}
			const t = e.exchange?.onConsumed;
			e.exchange = void 0;
			t?.();
		} catch (e) {
			const t = toErrorObject(e, "worker input release failed");
			o.push(t);
			a ??= t;
		}
		const s = notifyExecutionSettled(e);
		if (s) {
			o.push(s);
			a ??= s;
		}
		const c = e.computePermit;
		e.computePermit = void 0;
		if (c) t.releaseCompute(c);
		if (taskDiagnostics.hasSubscribers) {
			const n = performance.now();
			taskDiagnostics.publish({
				...t.diagnostics(),
				outcome: a ? "failed" : "ok",
				queueMs: (e.startedAt ?? n) - e.enqueuedAt,
				preparationMs: e.startedAt === void 0 ? 0 : (e.preparedAt ?? n) - e.startedAt,
				runMs: e.preparedAt === void 0 ? 0 : n - e.preparedAt,
				transferMs: e.transferMs,
				hostWaitMs: e.hostWaitMs
			});
		}
		const l = o[0];
		const u = o.length > 1 ? new AggregateError(o, "Worker task cleanup failed", { cause: l }) : l;
		if (e.owner) {
			if (u) throw u;
		} else if (a) e.reject(a);
		else e.resolve(r);
		return u;
	});
}
//#endregion
//#region packages/worker-runtime/src/worker-task-pool-resources.ts
/** Each existing slot retains its cleanup receipt; no result Promise controls custody. */
function startCloseWorkerPoolResources(e, t, n, r, i, a) {
	const o = [...e].map((e) => {
		if (e.retiring) return e.retiring;
		if (e.native?.executionStopped) return n(e);
		const o = e.worker;
		if (!o) {
			const e = createRetainedOperation(() => {});
			e.resolve();
			return e.operation;
		}
		const s = t.get(o) ?? { pending: 0 };
		s.pending++;
		t.set(o, s);
		o.ref();
		return startCloseWorkerTaskResources(e, o, s, r, i, n, a);
	});
	const s = createRetainedOperation(() => {
		for (const e of o) e.service();
		advance();
	});
	const advance = () => {
		const e = o.map((e) => e.read());
		if (e.some((e) => e.status === "pending")) return;
		const t = e.flatMap((e) => e.status === "rejected" ? [e.error] : []);
		if (t.length) s.reject(new AggregateError(t, "Worker resource cleanup failed"));
		else s.resolve();
	};
	for (const e of o) e.result.then(advance, advance);
	advance();
	return s.operation;
}
/** Concurrent resource closes share one listener until their last real receipt. */
function observeResourceWorkerExit(e, t, n) {
	let r = t.exit;
	if (!r) {
		const n = /* @__PURE__ */ new Set();
		r = {
			waiters: n,
			receive: () => {
				for (const e of n) e();
			}
		};
		t.exit = r;
		e.once("exit", r.receive);
	}
	r.waiters.add(n);
	return () => {
		r.waiters.delete(n);
		if (!r.waiters.size) {
			e.removeListener("exit", r.receive);
			if (t.exit === r) t.exit = void 0;
		}
	};
}
function startCloseWorkerTaskResources(e, t, n, r, i, a, o) {
	const { port1: s, port2: c } = new MessageChannel();
	const l = AsyncLocalStorage.snapshot();
	let u = false;
	let d = false;
	let f;
	const p = createRetainedOperation(() => {
		if (u) return;
		e.native?.service();
		if (e.native?.executionStopped) {
			d = true;
			f ??= e.retiring ?? a(e);
		}
		for (;;) {
			const e = receiveMessageOnPort(s);
			if (!e || u) break;
			receive(e.message);
		}
		const t = f ?? e.retiring;
		if (d && t) {
			t.service();
			const e = t.read();
			if (e.status === "fulfilled") finish();
			else if (e.status === "rejected") finish(toErrorObject(e.error, "Worker resource cleanup retirement failed"));
		}
	});
	const finish = (r) => l(() => {
		if (u) return;
		u = true;
		m();
		s.close();
		c.close();
		n.pending--;
		if (!n.pending && !e.task && !e.retiring) t.unref();
		if (r) p.reject(r);
		else p.resolve();
	});
	const receive = (e) => {
		o?.();
		try {
			if (isRecord(e) && e.ok === true) {
				finish();
				return;
			}
			const t = isRecord(e) && e.detail !== void 0 && i?.decodeResourceError ? i.decodeResourceError(e.detail) : new Error(isRecord(e) && typeof e.error === "string" ? e.error : "Invalid worker resource cleanup receipt");
			finish(t);
		} catch (e) {
			finish(toErrorObject(e, "Worker resource cleanup receipt could not be decoded"));
		}
	};
	const m = observeResourceWorkerExit(t, n, () => finish());
	s.once("message", receive);
	s.once("messageerror", (e) => finish(toErrorObject(e, "Worker resource cleanup receipt could not be decoded")));
	s.once("close", () => {
		if (u) return;
		const t = e.retiring;
		if (!t) {
			finish(/* @__PURE__ */ new Error("Worker resource cleanup closed without a receipt"));
			return;
		}
		d = true;
		f = t;
		t.result.then(() => finish(), (e) => finish(toErrorObject(e, "Worker resource cleanup retirement failed")));
	});
	try {
		t.postMessage({
			closeResource: true,
			key: r,
			resourcePort: c
		}, [c]);
	} catch (e) {
		finish(toErrorObject(e, "Worker resource cleanup could not be sent"));
	}
	return p.operation;
}
//#endregion
//#region packages/worker-runtime/src/worker-task-pool-retirement.ts
const WORKER_WARM_WINDOW_MS = 3e5;
function isWorkerIdleForPressure(e, t = false) {
	return e !== void 0 && (t || performance.now() - e >= 1e3);
}
/** Repeated idle notifications preserve the deadline; only admitted work clears it. */
function createWorkerIdleTimers(e) {
	const t = setTimeout;
	const n = clearTimeout;
	return {
		clear(e) {
			n(e.idleTimer);
			e.idleTimer = void 0;
		},
		arm(n, r, i) {
			if (n.idleTimer) return;
			n.idleTimer = e(() => t(() => {
				n.idleTimer = void 0;
				i();
			}, r));
			n.idleTimer.unref();
		}
	};
}
function createWorkerTaskPoolRetirement({ slots: e, options: t, retainOneIdleWorker: n, runInContext: r, dispatch: i, onRotationComplete: a, serviceDeadlines: o, markWorkerRetirement: s, serviceHost: c }) {
	const l = /* @__PURE__ */ new Map();
	let u = -Infinity;
	let d;
	let f = -Infinity;
	let p;
	let m;
	let h = false;
	const g = createWorkerIdleTimers(r);
	const _ = performance.now.bind(performance);
	const v = n ? /* @__PURE__ */ new Set() : void 0;
	function newestIdle() {
		if (!v) return;
		let e;
		for (const t of v) e = t;
		return e;
	}
	function clearIdle(e) {
		e.idleSince = void 0;
		v?.delete(e);
		g.clear(e);
	}
	const isBurstSlot = (n) => {
		if (t.burstIdleTimeoutMs !== void 0) {
			for (const t of e) if (!t.retiring && !t.retirementFailed) return t !== n;
		}
		return false;
	};
	function startRotate() {
		if (m) return m;
		const t = AsyncLocalStorage.snapshot();
		let n;
		let r;
		let s = false;
		const l = createRetainedOperation(() => {
			serviceNativeWorkerPass(c, d);
			o();
			for (const e of n ?? []) e.service();
			r?.service();
			advance();
		});
		m = l.operation;
		h = false;
		const d = [...e];
		const p = d.flatMap((e) => e.task ? [e.task] : []);
		const advance = () => t(() => {
			if (s || l.operation.read().status !== "pending") return;
			s = true;
			try {
				if (p.some((e) => e.read().status === "pending")) return;
				if (!n) {
					n = d.map((e) => startRetire(e, "rotation"));
					for (const e of n) e.result.then(advance, advance);
				}
				for (const e of n) {
					const t = e.read();
					if (t.status === "rejected") throw t.error;
					if (t.status === "pending") return;
				}
				if (!r) {
					r = startJoinArtifacts();
					r.result.then(advance, advance);
				}
				const e = r.read();
				if (e.status === "pending") return;
				if (e.status === "rejected") throw e.error;
				u = -Infinity;
				f = -Infinity;
				m = void 0;
				a();
				l.resolve();
				i();
			} catch (e) {
				m = void 0;
				h = true;
				l.reject(e);
			} finally {
				s = false;
			}
		});
		for (const e of p) e.promise.then(advance, advance);
		advance();
		return l.operation;
	}
	function startRetire(n, a = "closed") {
		if (a === "idle_timeout") {
			if (isBurstSlot(n)) f = _();
			else u = _();
		}
		if (d === n) d = void 0;
		if (p === n) p = void 0;
		if (n.worker) s(n.worker, a);
		clearIdle(n);
		cancelWorkerNativeSections(n.nativeSections);
		if (n.retiring) return n.retiring;
		const o = AsyncLocalStorage.snapshot();
		let m;
		let h;
		let g = false;
		let v = false;
		const y = createRetainedOperation(() => {
			m?.service();
			advance();
		});
		const advance = () => o(() => {
			if (v || y.operation.read().status !== "pending") return;
			v = true;
			try {
				if (n.creating) return;
				if (!areWorkerNativeSectionsSettled(n.nativeSections)) {
					if (!g) {
						g = true;
						Promise.resolve(waitForWorkerNativeSections(n.nativeSections)).then(advance, y.reject);
					}
					return;
				}
				if (n.worker && !m) {
					s(n.worker, a);
					try {
						if (h === void 0) {
							h = c.flushWorkerDiagnostics?.(n.worker, a) ?? null;
							h?.result.then(advance, advance);
						}
						h?.service();
						if (h?.read().status === "pending") return;
					} catch {
						h = null;
					}
					if (n.native) m = n.native.stop();
					else {
						const e = createRetainedOperation(() => {});
						m = e.operation;
						Promise.resolve().then(() => n.worker.terminate()).then(() => e.resolve(), e.reject);
					}
					m.result.then(advance, advance);
				}
				const t = m?.read();
				if (t?.status === "pending") return;
				if (t?.status === "rejected") throw t.error;
				n.retired = true;
				const o = n.releaseResources;
				if (o) r(() => {
					const e = (async () => {
						try {
							await o();
						} catch (e) {
							try {
								process.emitWarning(`Worker task resource release failed: ${String(e)}`);
							} catch {}
						}
					})();
					const t = createRetainedOperation(() => {});
					l.set(e, t.operation);
					e.then(() => {
						l.delete(e);
						t.resolve();
					}, t.reject);
				});
				n.worker?.removeAllListeners();
				e.delete(n);
				for (const e of n.completions ?? []) e();
				n.completions = void 0;
				i();
				y.resolve();
			} catch (e) {
				try {
					Promise.resolve(t.onRetirementFailure?.(e)).catch(() => void 0);
				} catch {}
				n.retirementFailed = true;
				n.retiring = void 0;
				y.reject(e);
			} finally {
				v = false;
			}
		});
		n.retiring = y.operation;
		Promise.resolve().then(advance);
		return y.operation;
	}
	function retire(e, t) {
		return startRetire(e, t).result;
	}
	function startJoinArtifacts() {
		const e = [...l.values()];
		const t = createRetainedOperation(() => {
			for (const t of e) t.service();
			advance();
		});
		const advance = () => {
			const n = e.map((e) => e.read());
			const r = n.find((e) => e.status === "rejected");
			if (r?.status === "rejected") t.reject(r.error);
			else if (n.every((e) => e.status === "fulfilled")) t.resolve();
		};
		for (const t of e) t.result.then(advance, advance);
		advance();
		return t.operation;
	}
	/** Join failed native retirements without interrupting healthy tasks. */
	async function retryFailedRetirements() {
		const t = await Promise.allSettled([...e].filter((e) => e.retirementFailed).map((e) => retire(e)));
		t.push(...await Promise.allSettled(l.keys()));
		const n = t.flatMap((e) => e.status === "rejected" ? [toErrorObject(e.reason, "worker retirement retry failed")] : []);
		const r = n[0];
		if (r) throw n.length === 1 ? r : new AggregateError(n, "Worker retirement retries failed", { cause: r });
	}
	function idle(e, n = 0) {
		const r = isBurstSlot(e);
		const i = (r ? t.burstIdleTimeoutMs : t.idleTimeoutMs) ?? 6e4;
		if (i <= 0) return;
		e.idleSince ??= _() - n;
		if (v && !v.has(e)) {
			const t = newestIdle();
			v.add(e);
			if (t && !t.idleTimer) retire(t, "idle_timeout").catch(() => void 0);
		}
		if (!r && !d && _() - u < WORKER_WARM_WINDOW_MS) d = e;
		if (r && (!p || !isBurstSlot(p)) && _() - f < WORKER_WARM_WINDOW_MS) p = e;
		const a = r ? _() : 0;
		const o = r ? p === e ? i * 3 : i : d === e ? Math.max(i, WORKER_WARM_WINDOW_MS) : i;
		g.arm(e, Math.max(0, o - n), () => {
			if (newestIdle() === e) return;
			if (r && !isBurstSlot(e)) {
				idle(e, _() - a);
				return;
			}
			retire(e, "idle_timeout").catch(() => void 0);
		});
	}
	return {
		get preferredIdle() {
			return newestIdle();
		},
		get dispatchAllowed() {
			return m === void 0 && !h;
		},
		startRotate,
		retire,
		startRetire,
		service() {
			const t = [...e];
			for (const e of t) e.retiring?.service();
			m?.service();
		},
		clearIdle,
		idle,
		retireIdle(t, n = false) {
			for (const r of e) if (!r.task && !r.retiring && !r.retirementFailed && r.worker && isWorkerIdleForPressure(r.idleSince, n) && !t.get(r.worker)?.pending) retire(r, "memory_pressure").catch(() => void 0);
		},
		retryFailedRetirements,
		joinArtifacts: () => startJoinArtifacts().result
	};
}
//#endregion
//#region packages/worker-runtime/src/worker-task-pool-worker.ts
function sendWorkerTaskInput(e) {
	const { slot: t, task: n, input: r } = e;
	if (n.done) return;
	n.preparedAt = performance.now();
	const i = e.bootstrapError();
	if (i && !t.worker) {
		e.refuse(i);
		return;
	}
	try {
		let i = t.worker;
		if (!i) {
			t.creating = true;
			try {
				i = e.createWorker();
			} catch (t) {
				e.fail(t, true);
				return;
			} finally {
				t.creating = false;
			}
		}
		const a = n.options.transferList?.(r);
		if (!n.done) {
			const o = e.host.captureTaskContext(i);
			const s = [...a ?? [], ...e.host.taskContextTransferList?.(o) ?? []];
			const c = performance.now();
			const l = n.options.progressSignal;
			i.postMessage({
				input: r,
				taskId: n.id,
				interactive: Boolean(n.options.onRequest || n.options.onRequestSync || n.options.onNotification),
				nativeSections: t.nativeSections.buffer,
				...l ? { progressSignal: l } : {},
				taskContext: o,
				sampleMemory: true
			}, s);
			n.transferMs += performance.now() - c;
		}
	} catch (t) {
		e.fail(t);
	}
}
/** Physical construction and listeners share the pool's detached creation scope. */
function createWorkerTaskPoolWorker(e) {
	const { slot: t, options: n } = e;
	let r = e.host.captureWorkerStartObserver?.(n.workerUrl);
	const i = e.runInContext(() => {
		const r = n.prepareWorker?.();
		t.releaseResources = r?.releaseResources;
		const i = r?.temporaryDirectory;
		if (i) {
			const n = e.host.prepareResources();
			const r = t.releaseResources;
			t.releaseResources = async () => {
				try {
					await n;
					await e.host.releaseTemporaryDirectory(i);
				} finally {
					await r?.();
				}
			};
		}
		const a = n.workerUrl;
		const o = {
			...n.workerOptions,
			...r?.options
		};
		if (e.host.requiresReady) t.ready = false;
		const s = e.host.createWorker(a, o);
		t.native = s.native;
		return s.worker;
	});
	let a = false;
	const started = () => {
		if (a) return;
		a = true;
		e.onStarted(i);
		r?.();
		r = void 0;
	};
	if (t.native) {
		t.native.on("started", started);
		t.native.on("execution-exit", (n) => {
			releaseWorkerNativeSectionsOnExit(t.nativeSections);
			if (!t.retiring) e.onFailure(e.unavailableError(`worker exited with code ${n}`), true);
		});
	} else started();
	t.worker = i;
	i.on("message", (n) => {
		if (e.host.receiveMessage(i, n)) return;
		if (t.ready === false) {
			if (isRecord(n) && n.status === "ready") t.ready = true;
			else e.onFailure(e.unavailableError("worker task server did not become ready"), true);
			return;
		}
		const r = t.task;
		if (r) r.runInContext(() => e.onMessage(n));
		else e.onMessage(n);
	});
	i.on("error", (t) => e.onFailure(e.unavailableError(String(t), t), true));
	i.on("messageerror", (t) => e.onFailure(e.unavailableError(String(t), t)));
	i.once("exit", (n) => {
		releaseWorkerNativeSectionsOnExit(t.nativeSections);
		const r = a;
		a = false;
		e.onExit(n, r);
	});
	return i;
}
//#endregion
//#region packages/worker-runtime/src/worker-task-pool-core.ts
const runInWorkerPoolContext = AsyncLocalStorage.snapshot();
const memoryPressure = channel("openclaw.memory.critical");
/** Bounded execution workers; each worker accepts one task at a time. */
var WorkerTaskPoolCore = class {
	constructor(e, t, n, r = {}) {
		this.options = e;
		this.host = t;
		this.publicDispatch = n;
		this.ownerOptions = r;
		this.slots = /* @__PURE__ */ new Set();
		this.ownedTasks = /* @__PURE__ */ new Set();
		this.resourceClosures = /* @__PURE__ */ new WeakMap();
		this.ownedSettlement = {
			cancel: (e) => this.cancel(e, new WorkerTaskError("worker task closed", "unavailable")),
			detach: (e) => {
				if (e.slot?.task === e) {
					e.slot.task = void 0;
					this.activeTasks--;
				}
			},
			retire: (e) => this.retirement.startRetire(e),
			release: (e, t) => {
				if (!this.ownedTasks.delete(e)) return;
				this.releaseAdmission(e);
				e.runInContext = runInWorkerPoolContext;
				this.dispatch();
				if (t && !e.owner?.retire && !t.task && !t.retiring) this.idle(t);
			}
		};
		this.completion = {
			preparationCleanups: /* @__PURE__ */ new Map(),
			releaseAdmission: (e) => this.releaseAdmission(e),
			releaseCompute: (e) => this.computeCapacity.release(e),
			diagnostics: () => ({
				worker: this.options.workerUrl.pathname.split("/").at(-1),
				...this.publicDispatch?.getSnapshot() ?? this.getSnapshot(),
				pendingBytes: this.admission.pendingBytes
			})
		};
		this.queue = [];
		this.bootstrap = createWorkerTaskPoolBootstrap(this.slots, this.queue, (e, t) => this.finish(e, t));
		this.workers = 0;
		this.workersCreated = 0;
		this.activeTasks = 0;
		this.resumeCompute = () => this.dispatch();
		this.nextTaskId = 0;
		this.retireIdleOnPressure = (e) => this.retirement.retireIdle(this.resourceClosures, e === true);
		this.expireTasks = () => expireWorkerTasks(this.queue, this.slots, this.timeout);
		this.retryFailedRetirements = () => this.retirement.retryFailedRetirements();
		this.timeout = (e) => {
			if (e.done) return;
			this.cancel(e, workerTaskTimeoutError(e.exchange, this.options.workerUrl));
		};
		this.observeTask = t.createTaskObserver?.(e.workerUrl);
		this.maxWorkers = t.maxWorkers ?? e.maxWorkers ?? availableParallelism();
		if (!Number.isSafeInteger(this.maxWorkers) || this.maxWorkers < 1) throw new RangeError("maxWorkers must be a positive safe integer");
		this.computeCapacity = e.sharedCompute ? t.computeCapacity : void 0;
		this.admission = new WorkerTaskAdmission(e.maxPendingTasks ?? 128, e.maxPendingBytes ?? 268435456, this.computeCapacity);
		this.retirement = createWorkerTaskPoolRetirement({
			slots: this.slots,
			options: e,
			retainOneIdleWorker: r.retainOneIdleWorker,
			runInContext: runInWorkerPoolContext,
			dispatch: () => this.dispatch(),
			onRotationComplete: () => {
				this.bootstrap.reset();
				e.onRotationComplete?.();
			},
			serviceDeadlines: this.expireTasks,
			markWorkerRetirement: (e, n) => t.workerRetiring(e, n),
			serviceHost: t
		});
		t.pools.register(this);
	}
	run(e, t) {
		if (this.closedError) return Promise.reject(this.closedError);
		const n = t.inputBytes ?? 0;
		if (!Number.isSafeInteger(n) || n < 0) return Promise.reject(/* @__PURE__ */ new RangeError("inputBytes must be a nonnegative safe integer"));
		return this.enqueue(e, t, false, n).promise;
	}
	runTask(e, t) {
		const n = this.enqueue(e, t, true);
		return {
			result: n.promise,
			close: (e) => joinOwnedWorkerTask(n, this.ownedSettlement, e?.retire === true)
		};
	}
	startTask(e, t) {
		if (!this.ownerOptions.retainedTransport) throw new WorkerTaskError("Retained tasks require their native lifetime transport", "unavailable");
		const n = this.enqueue(e, t, true);
		return retainWorkerTask(n, this.ownedSettlement, () => this.service());
	}
	service() {
		serviceNativeWorkerPass(this.host, this.slots);
		this.expireTasks();
		this.retirement.service();
		const e = [...this.ownedTasks];
		for (const t of e) t.owner?.closing?.service();
		this.dispatch();
	}
	enqueue(e, t, n, r = t.inputBytes ?? 0) {
		const i = createRetainedOperation(() => this.service(), { observeRejection: this.ownerOptions.retainedTransport === true });
		const a = {
			promise: i.operation.result,
			resolve: i.resolve,
			reject: i.reject,
			read: () => i.operation.read(),
			id: ++this.nextTaskId,
			runInContext: captureWorkerTaskContext(),
			controller: void 0,
			inputConsumed: false,
			executionNotified: false,
			exchangeSequence: 0,
			input: e,
			options: { ...t },
			abort: () => this.cancel(a, toErrorObject(t.signal?.reason, "worker task aborted")),
			done: false,
			admitted: false,
			...n ? { owner: {
				closed: false,
				retire: false
			} } : {},
			inputBytes: r,
			enqueuedAt: performance.now(),
			transferMs: 0,
			hostWaitMs: 0
		};
		if (n) this.ownedTasks.add(a);
		const o = this.closedError ?? this.bootstrap.admissionError;
		if (o || !Number.isSafeInteger(r) || r < 0) {
			this.finish(a, o ?? /* @__PURE__ */ new RangeError("inputBytes must be a nonnegative safe integer"));
			return a;
		}
		const s = this.admission.admitTask(a);
		if (s) {
			this.finish(a, s);
			return a;
		}
		a.observation = this.observeTask?.(a.options.diagnosticOperation);
		armWorkerTaskTimeout(a, t.timeoutMs, this.timeout, "enqueue");
		t.signal?.addEventListener("abort", a.abort, { once: true });
		enqueueWorkerTask(this.queue, a);
		if (t.signal?.aborted) a.abort();
		else this.dispatch();
		return a;
	}
	get isClosed() {
		return this.closedError !== void 0;
	}
	getSnapshot() {
		return {
			maxWorkers: this.maxWorkers,
			workers: this.workers,
			workersCreated: this.workersCreated,
			activeTasks: this.activeTasks,
			pendingTasks: this.admission.pendingTasks
		};
	}
	startCloseResources(e) {
		return startCloseWorkerPoolResources(this.slots, this.resourceClosures, (e) => this.ownedSettlement.retire(e), e, this.ownerOptions, this.host.observeResourceReply);
	}
	/** Pause dispatch, settle current work and join native exit before restarting the queue. */
	rotate() {
		return this.startRotate().result;
	}
	startRotate() {
		this.computeCapacity?.remove(this.resumeCompute);
		return this.retirement.startRotate();
	}
	close(e = new WorkerTaskError("worker task pool closed", "unavailable"), t = "closed") {
		this.closedError ??= e;
		this.admission.close();
		memoryPressure.unsubscribe(this.retireIdleOnPressure);
		this.computeCapacity?.remove(this.resumeCompute);
		for (const e of this.queue.splice(0)) this.finish(e, this.closedError);
		for (const e of this.slots) {
			if (e.worker) this.host.workerRetiring(e.worker, t);
			if (e.task && !e.task.owner) this.finish(e.task, this.closedError, void 0, true);
		}
		const n = [...this.ownedTasks];
		const r = new Set(n.flatMap((e) => e.slot?.task === e ? [e.slot] : []));
		const i = n.map((e) => joinOwnedWorkerTask(e, this.ownedSettlement, true));
		const a = [...this.slots].filter((e) => !r.has(e));
		const o = [...i, ...a.map((e) => this.retirement.retire(e, t))];
		return this.host.pools.close(this, o, () => joinWorkerTaskPreparationCleanups(this.completion, this.retirement.joinArtifacts()));
	}
	dispatch() {
		if (!this.slots.size) memoryPressure.unsubscribe(this.retireIdleOnPressure);
		if (!this.queue.length || this.closedError || !this.retirement.dispatchAllowed) this.computeCapacity?.remove(this.resumeCompute);
		while (!this.closedError && this.retirement.dispatchAllowed && this.queue.length) {
			const e = this.queue[0];
			const t = this.maxWorkers + Number(e.options.pointRead === true);
			let n = this.activeTasks < t ? this.retirement.preferredIdle : void 0;
			n ??= [...this.slots].find((e) => this.activeTasks < t && !e.task && !e.retiring && !e.retirementFailed && (!this.bootstrap.error() || e.worker));
			if (!n) {
				const e = this.bootstrap.error();
				if (e) this.bootstrap.rejectQueued();
				if (e || this.slots.size >= t) {
					let e = this.queue.length;
					for (const t of this.slots) if (t.task?.exchange && !t.task.exchange.sent && !t.task.exchange.pressure.signal.aborted && e-- > 0) t.task.exchange.pressure.abort();
					return;
				}
			}
			if (this.computeCapacity && !e.options.pointRead) {
				const t = this.computeCapacity.acquire(this.resumeCompute, () => {
					if (e.exchange && !e.exchange.sent && !e.exchange.pressure.signal.aborted) {
						e.runInContext(() => e.exchange?.pressure.abort());
						return true;
					}
					return false;
				});
				if (!t) return;
				e.computePermit = t;
			}
			if (!n) {
				n = { nativeSections: createWorkerNativeSectionState() };
				this.slots.add(n);
			}
			this.retirement.clearIdle(n);
			const r = this.queue.shift();
			n.task = r;
			this.activeTasks++;
			r.slot = n;
			r.startedAt = performance.now();
			armWorkerTaskTimeout(r, r.options.timeoutMs, this.timeout, "dispatch");
			r.observation?.started();
			r.runInContext(() => {
				try {
					n.worker?.ref();
				} catch (e) {
					this.fail(n, toErrorObject(e, "worker reference failed"));
					return;
				}
				prepareWorkerTaskInput(r, (e) => {
					r.diagnosticLabel = this.host.describeTask?.(this.options.workerUrl, e);
					sendWorkerTaskInput({
						slot: n,
						task: r,
						input: e,
						host: this.host,
						bootstrapError: this.bootstrap.error,
						createWorker: () => this.createWorker(n),
						fail: (e, t) => this.fail(n, this.unavailableError(n, String(e), e), t),
						refuse: (e) => this.finish(r, e, void 0, true)
					});
				}, (e) => this.finish(r, toErrorObject(e, "worker task preparation failed")), !n.worker && this.options.prepareWorker ? () => runInWorkerPoolContext(() => this.host.prepareResources()) : void 0);
			});
		}
	}
	unavailableError(e, t, n) {
		const r = e.task;
		const i = e.ready === false ? "startup" : r?.exchange ? "exchange" : "running";
		const a = r?.diagnosticLabel ? ` [task=${r.diagnosticLabel} admittedInputBytes=${r.inputBytes} exchanges=${r.exchangeSequence} stage=${i}]` : "";
		return new WorkerTaskError(t + a, "unavailable", { cause: n });
	}
	createWorker(e) {
		if ((this.options.idleTimeoutMs ?? 6e4) > 0) {
			memoryPressure.unsubscribe(this.retireIdleOnPressure);
			memoryPressure.subscribe(this.retireIdleOnPressure);
		}
		return createWorkerTaskPoolWorker({
			slot: e,
			options: this.options,
			host: this.host,
			runInContext: runInWorkerPoolContext,
			unavailableError: (t, n) => this.unavailableError(e, t, n),
			onStarted: (e) => {
				this.workers++;
				this.workersCreated++;
				this.host.workerStarted(e, this);
			},
			onMessage: (t) => this.receive(e, t),
			onFailure: (t, n) => this.fail(e, t, n),
			onExit: (t, n) => {
				if (n) this.workers--;
				const r = this.unavailableError(e, `worker exited with code ${t}`);
				this.fail(e, r, true);
			}
		});
	}
	receive(e, t) {
		if (e.retiring) return;
		const n = e.task;
		if (n && isRecord(t) && (t.status === "request" || t.status === "consumed" || t.status === "notification")) {
			try {
				this.receiveExchange(e, n, t);
			} catch (t) {
				this.fail(e, toErrorObject(t, "worker consumption callback failed"));
			}
			return;
		}
		if (!n || !isRecord(t) || (n.options.onRequest || n.options.onRequestSync || t.taskId !== void 0) && t.taskId !== n.id || t.status !== "ok" && t.status !== "failed") {
			this.fail(e, new WorkerTaskError("invalid worker task response", "unavailable"));
			return;
		}
		const r = t;
		const i = Boolean(n.exchange || n.options.onInputConsumed && !n.inputConsumed);
		if (r.status === "failed") {
			this.finish(n, new WorkerTaskError(r.error, "failed"), void 0, i);
			return;
		}
		try {
			this.options.validateResult?.(r.value);
		} catch (t) {
			this.fail(e, toErrorObject(t, "worker result validation failed"));
			return;
		}
		this.finish(n, void 0, r.value, i);
	}
	receiveExchange(e, t, n) {
		if (n.taskId !== t.id) {
			this.fail(e, new WorkerTaskError("stale worker exchange", "unavailable"));
			return;
		}
		if (n.status === "notification") {
			t.options.onNotification?.(n.value);
			return;
		}
		if (n.status === "consumed") {
			if (n.id === 0 && !t.inputConsumed) {
				t.inputConsumed = true;
				const e = t.options.onInputConsumed;
				t.options.onInputConsumed = void 0;
				e?.();
			} else if (t.exchange?.sent && n.id === t.exchange.id) {
				const e = t.exchange.onConsumed;
				t.exchange = void 0;
				e?.();
			} else this.fail(e, new WorkerTaskError("invalid worker consumption receipt", "unavailable"));
			return;
		}
		if (!t.options.onRequest && !t.options.onRequestSync || t.exchange || !Number.isSafeInteger(n.id) || n.id !== t.exchangeSequence + 1) {
			this.fail(e, new WorkerTaskError("invalid worker exchange", "unavailable"));
			return;
		}
		if (t.options.hostTimeout === "owner") {
			clearTimeout(t.timer);
			t.deadline = void 0;
		}
		const r = createWorkerHostExchange(t, n.value);
		t.hostWaitStartedAt = performance.now();
		this.dispatch();
		this.computeCapacity?.requestCheckpoints();
		const accept = (n) => {
			if (!t.done && t.deadline !== void 0 && performance.now() >= t.deadline) this.timeout(t);
			if (t.done || e.task !== t || e.retiring) {
				const release = () => {
					try {
						t.runInContext(() => n.onConsumed?.());
					} catch {}
				};
				if (this.slots.has(e)) (e.completions ??= []).push(release);
				else release();
				return;
			}
			this.finishHostWait(t);
			r.onConsumed = n.onConsumed;
			r.sent = true;
			armWorkerTaskTimeout(t, n.timeoutMs, this.timeout);
			try {
				e.worker.postMessage({
					taskId: t.id,
					responseId: r.id,
					input: n.input
				}, n.transferList);
			} catch (t) {
				this.fail(e, toErrorObject(t, "worker response delivery failed"));
			}
		};
		const reject = (n) => {
			if (!t.done && e.task === t) this.fail(e, toErrorObject(n, "worker host exchange failed"));
		};
		dispatchOwnedWorkerRequest(t, e, n.value, r, {
			accept,
			reject
		});
	}
	cancel(e, t) {
		if (e.done) return;
		if (e.slot) {
			if (e.slot.worker) this.host.workerRetiring(e.slot.worker, "cancelled");
			if (e.owner) this.finish(e, t, void 0, true);
			else this.fail(e.slot, t);
		} else {
			this.queue.splice(this.queue.indexOf(e), 1);
			this.finish(e, t);
		}
	}
	fail(e, t, n) {
		if (e.retiring) return;
		if (n && e.ready === false) this.bootstrap.fail(t);
		if (e.worker) this.host.workerRetiring(e.worker, "failure");
		if (e.task?.owner) {
			if (e.task.done) {
				if (!e.task.owner.retire) closeOwnedWorkerTask(e.task, this.ownedSettlement, true).catch(() => void 0);
			} else this.finish(e.task, t, void 0, true);
		} else if (this.options.restartOnError === false) (this.publicDispatch?.close(t) ?? this.close(t)).catch(() => void 0);
		else if (e.task) this.finish(e.task, t, void 0, true);
		else this.retirement.retire(e).catch(() => void 0);
	}
	finishHostWait(e) {
		const t = e.hostWaitStartedAt;
		if (t !== void 0) {
			e.hostWaitStartedAt = void 0;
			e.hostWaitMs += performance.now() - t;
		}
	}
	finish(e, t, n, r = false) {
		if (e.done) return;
		this.finishHostWait(e);
		e.done = true;
		e.observation?.completed();
		e.observation = void 0;
		e.runInContext(() => e.controller?.abort(t));
		clearTimeout(e.timer);
		e.deadline = void 0;
		e.options.signal?.removeEventListener("abort", e.abort);
		const i = createWorkerTaskCompletion(e, this.completion, t, n);
		if (e.owner) {
			e.owner.complete = i;
			e.owner.retire ||= r || Boolean(t && e.slot && e.preparedAt !== void 0);
			if (t) e.reject(t);
			else e.resolve(n);
			if (t || r) closeOwnedWorkerTask(e, this.ownedSettlement).catch(() => void 0);
			return;
		}
		const a = e.slot;
		if (a) {
			a.task = void 0;
			this.activeTasks--;
			if (r) {
				(a.completions ??= []).push(i);
				this.retirement.retire(a, "failure").catch((n) => {
					e.reject(t ? new AggregateError([t, n], `Worker retirement failed: ${toErrorObject(n, "worker retirement failed").message}; task failed: ${t.message}`, { cause: n }) : n);
				});
				return;
			}
		}
		i();
		this.dispatch();
		if (a && !a.task && !a.retiring) this.idle(a);
	}
	releaseAdmission(e) {
		if (e.admitted) {
			e.admitted = false;
			this.admission.finish(e.inputBytes);
		}
	}
	idle(e) {
		if (e.worker && !this.resourceClosures.get(e.worker)?.pending) e.worker.unref();
		this.retirement.idle(e);
	}
};
//#endregion
//#region src/infra/worker-request-diagnostics.ts
const workerStarts = resolveGlobalSingleton(Symbol.for("openclaw.workerStartObservation"), () => new AsyncLocalStorage());
/** Carry only the diagnostic callback across the pool's detached construction boundary. */
function captureWorkerStartObserver(e) {
	const t = workerStarts.getStore();
	return t ? () => t(workerScriptName(e)) : void 0;
}
const metricsListeners = resolveGlobalSingleton(Symbol.for("openclaw.workerRequestMetricsListeners"), () => /* @__PURE__ */ new Set());
const reservations = resolveGlobalSingleton(Symbol.for("openclaw.sqliteWorkerReservationObservation"), () => new AsyncLocalStorage());
const detailedTiming = isDiagnosticFlagEnabled("sqlite.worker-timing");
const queued = resolveGlobalSingleton(Symbol.for("openclaw.workerRequestQueueDepth"), () => /* @__PURE__ */ new Map());
/** One observation follows a request across admission retries and cancellation. */
function trackWorkerRequest(e, t, n) {
	const r = normalizeWorkerRequestClass(t);
	const i = e === "sqlite_writer" ? reservations.getStore() : void 0;
	const a = performance.now();
	const o = e === "sqlite_writer" && (detailedTiming || metricsListeners.size > 0 || hasInternalDiagnosticEventInterest("worker.request", true)) ? { enqueued: a } : void 0;
	let s;
	let c = false;
	const emit = (t, n, i) => {
		if (!areDiagnosticsEnabledForProcess()) return;
		const a = queued.get(e) ?? 0;
		const s = t === "completed" ? o : void 0;
		for (const o of metricsListeners) try {
			o(e, r, t, a, n, i, s);
		} catch {}
		if (!hasInternalDiagnosticEventInterest("worker.request", true)) return;
		emitTrustedDiagnosticEvent({
			type: "worker.request",
			kind: e,
			requestClass: r,
			phase: t,
			queueDepth: a,
			...n === void 0 ? {} : { queueWaitMs: n },
			...i === void 0 ? {} : { durationMs: i },
			...s ? { timing: s } : {}
		});
	};
	const dequeue = () => queued.set(e, (queued.get(e) ?? 0) - 1);
	queued.set(e, (queued.get(e) ?? 0) + 1);
	emit("queued");
	const l = {
		requestClass: r,
		timing: o,
		...i ? { recordTransactions: (e) => {
			i.transactionCount = (i.transactionCount ?? 0) + e;
		} } : {},
		started: () => {
			if (c || s !== void 0) return;
			s = performance.now();
			if (i) i.operations.add(i.operations.has(r) || i.operations.size < 8 ? r : "other");
			if (o) o.dispatched = s;
			n?.removeEventListener("abort", l.completed);
			dequeue();
			emit("started", s - a);
		},
		completed: () => {
			if (c) return;
			c = true;
			n?.removeEventListener("abort", l.completed);
			if (s === void 0) dequeue();
			emit("completed", void 0, s === void 0 ? void 0 : performance.now() - s);
		}
	};
	n?.addEventListener("abort", l.completed, { once: true });
	if (n?.aborted) l.completed();
	return l;
}
//#endregion
//#region src/process/spawn-broker/resource-socket.ts
/** Byte transport only: socket closure says nothing about a resource's native lifetime. */
function createBrokerResourceSocket(e, t) {
	const n = createBrokerReceiver();
	const r = Buffer.alloc(4);
	let i = 0;
	let a;
	let o = 0;
	let s = false;
	let c;
	let l;
	const stop = (t) => {
		if (s) return;
		s = true;
		materializeErrorStack(t);
		c = t;
		n.clear();
		a = void 0;
		l?.(t ?? new SpawnBrokerError("Spawn broker resource socket closed"));
		e.destroy();
	};
	const u = createBrokerSender((t, n, r) => {
		if (s || e.destroyed) {
			r(c ?? new SpawnBrokerError("Spawn broker resource socket closed"));
			return;
		}
		const i = serialize(t);
		if (i.length > 268435456) {
			r(new SpawnBrokerError("Spawn broker resource frame exceeds capacity"));
			return;
		}
		const a = Buffer.allocUnsafe(4 + i.length);
		a.writeUInt32BE(i.length);
		i.copy(a, 4);
		const complete = (e) => {
			if (l !== complete) return;
			l = void 0;
			r(e);
			if (e) stop(e);
		};
		l = complete;
		try {
			e.write(a, (e) => complete(e ?? null));
		} catch (e) {
			complete(toErrorObject(e, "Spawn broker resource write failed"));
		}
	});
	e.on("data", (e) => {
		try {
			let c = 0;
			while (c < e.length) {
				if (s) break;
				if (!a) {
					const t = Math.min(4 - i, e.length - c);
					e.copy(r, i, c, c + t);
					i += t;
					c += t;
					if (i !== 4) continue;
					const n = r.readUInt32BE();
					if (n === 0 || n > 268435456) throw new SpawnBrokerError("Invalid spawn broker resource frame length");
					a = Buffer.allocUnsafe(n);
					i = 0;
				}
				const l = Math.min(a.length - o, e.length - c);
				e.copy(a, o, c, c + l);
				o += l;
				c += l;
				if (o !== a.length) continue;
				const u = n.receive(deserialize(a));
				a = void 0;
				o = 0;
				if (u !== void 0) {
					if (!u || typeof u !== "object" || !("value" in u)) throw new SpawnBrokerError("Invalid spawn broker resource message");
					t.message(u.value);
				}
			}
		} catch (e) {
			stop(toErrorObject(e, "Spawn broker resource read failed"));
		}
	});
	e.once("end", () => stop(a || i ? new SpawnBrokerError("Spawn broker resource socket ended during a frame") : void 0));
	e.once("error", stop);
	e.once("close", () => {
		stop();
		t.close(c);
	});
	return {
		async send(t) {
			if (s || e.destroyed) throw c ?? new SpawnBrokerError("Spawn broker resource socket closed");
			await u({ value: t });
		},
		close: () => stop()
	};
}
//#endregion
//#region src/process/spawn-broker/resource-client.ts
/** This attachment moves messages; its socket's lifetime is not native resource custody. */
function attachBrokerNativeResource(e, t, n, r) {
	const i = createDeferredCore();
	i.promise.catch(() => {});
	let a;
	let o;
	let s = 0;
	let c = false;
	let l = false;
	let u = false;
	let d = false;
	let f;
	let p = false;
	let m;
	const recordFailure = (e) => {
		if (d) return;
		const n = f === void 0;
		materializeErrorStack(e);
		f ??= e;
		clearTimeout(o);
		clearTimeout(h);
		i.reject(e);
		m?.completion.reject(e);
		m = void 0;
		t.close();
		if (n) r(e);
	};
	const lose = (e) => {
		if (d || p) return;
		p = true;
		recordFailure(e);
		a?.close();
	};
	const transmit = async (e, t = false) => {
		if (f && (!t || p)) throw f;
		if (!a || d) throw new Error("Native resource attachment is closed");
		await a.send(e);
	};
	const receive = (r) => {
		if (!isRecord(r) || r.id !== e.id || typeof r.type !== "string") {
			lose(/* @__PURE__ */ new Error("Invalid native resource response identity"));
			return;
		}
		const o = r;
		if (o.type === "resource-target") {
			t.postMessage(o.value, []);
			return;
		}
		n(o);
		if (o.type === "resource-ready") {
			c = true;
			clearTimeout(h);
		} else if (o.type === "resource-created") {
			l = true;
			i.resolve();
		} else if (o.type === "resource-closed") {
			d = true;
			clearTimeout(h);
			m?.completion.resolve();
			m = void 0;
			t.close();
			a?.close();
		} else if (o.type === "resource-close-error") {
			if (m?.id === o.requestId) {
				const e = m;
				m = void 0;
				e.completion.reject(o.resourceError ? new BrokerNativeResourceCloseError(o.error) : toErrorObject(decodeNativeWorkerFailure(o.error), "Native resource close failed"));
			}
		} else if (o.type === "resource-failed") recordFailure(toErrorObject(decodeNativeWorkerFailure(o.error), "Native resource failed"));
	};
	const start = () => {
		if (f || d) return;
		let t;
		try {
			t = connect(e.endpoint);
			t.unref();
		} catch (e) {
			queueMicrotask(() => lose(toErrorObject(e, "Native resource attachment failed")));
			return;
		}
		let n = false;
		let r;
		t.once("error", (e) => {
			r = e;
		});
		a = createBrokerResourceSocket(t, {
			message: receive,
			close(t) {
				if (d || p) return;
				if (!n && !c && e.startupDeadline !== void 0 && spawnBrokerStartupNowMs() < e.startupDeadline) {
					o = setTimeout(start, 10);
					return;
				}
				lose(t ?? r ?? /* @__PURE__ */ new Error("Native resource attachment lost"));
			}
		});
		t.once("connect", () => {
			n = true;
			u = true;
			transmit({
				type: "resource-attach",
				attachment: e
			}).catch((e) => lose(toErrorObject(e, "Native resource attachment failed")));
		});
	};
	const h = e.startupDeadline === void 0 ? void 0 : setTimeout(() => {
		if (!c) lose(/* @__PURE__ */ new Error("Spawn broker readiness deadline exceeded"));
	}, Math.max(0, e.startupDeadline - spawnBrokerStartupNowMs()));
	start();
	const assertCleanupAvailable = () => {
		if (p && f) throw f;
	};
	const failDelivery = (e, t) => {
		const n = toErrorObject(e, t);
		if (n !== f) lose(n);
	};
	i.promise.then(() => {
		t.on("message", (t) => {
			transmit({
				type: "resource-target",
				id: e.id,
				value: t
			}).catch((e) => failDelivery(e, "Native resource input delivery failed"));
		});
		t.unref();
	}, () => {});
	return {
		/** False is a no-dispatch receipt: the broker cannot have received this factory. */
		get dispatched() {
			return u;
		},
		ownerMessage(t, n) {
			i.promise.then(() => transmit({
				type: "resource-owner",
				id: e.id,
				sequence: n,
				value: t
			}, true)).catch((e) => failDelivery(e, "Native resource owner delivery failed"));
		},
		async close() {
			if (d) return;
			assertCleanupAvailable();
			if (!l) try {
				await i.promise;
			} catch (e) {
				if (!c || p) throw e;
			}
			if (d) return;
			assertCleanupAvailable();
			const t = m ?? {
				id: ++s,
				completion: createDeferredCore()
			};
			if (!m) {
				m = t;
				t.completion.promise.catch(() => {});
				transmit({
					type: "resource-close",
					id: e.id,
					requestId: t.id
				}, true).catch((e) => lose(toErrorObject(e, "Native resource close delivery failed")));
			}
			await t.completion.promise;
		},
		dispose() {
			clearTimeout(o);
			clearTimeout(h);
			a?.close();
		}
	};
}
//#endregion
//#region src/infra/worker-native-port.ts
const livePort = /* @__PURE__ */ new Error("Native worker port validation reached the live sentinel");
livePort.stack = void 0;
const portValidation = { get value() {
	throw livePort;
} };
function nativePortIsOpen(e) {
	if (process.versions.bun) {
		const t = e.hasRef();
		e.unref();
		e.ref();
		const n = e.hasRef();
		if (!t) e.unref();
		return n;
	}
	try {
		structuredClone(portValidation, { transfer: [e] });
	} catch (e) {
		if (e === livePort) return true;
		if (e instanceof DOMException && e.name === "DataCloneError") return false;
		throw e;
	}
	throw new Error("Native port validation did not abort serialization");
}
//#endregion
//#region src/infra/worker-native-task-port.ts
/** The task endpoint owns delivery only; its close never proves native execution stopped. */
var NativeWorkerTaskPort = class {
	constructor(e, t) {
		this.port = e;
		this.callbacks = t;
		this.pending = [];
		this.readMessage = () => receiveMessageOnPort(this.port);
		this.started = false;
		this.disposed = false;
		this.portClosed = false;
		this.receive = (e) => {
			observeWorkerMessage(e, "from_worker");
			this.pending.push({
				type: "message",
				value: e
			});
			this.drain();
		};
		this.receiveError = (e) => {
			this.pending.push({
				type: "messageerror",
				error: e
			});
			this.drain();
		};
		this.closed = () => {
			this.portClosed = true;
			this.drain();
			this.fail(/* @__PURE__ */ new Error("Native worker task channel closed"));
		};
		e.on("message", this.receive);
		e.on("messageerror", this.receiveError);
		e.on("close", this.closed);
		e.unref();
	}
	fail(e) {
		if (this.disposed || this.failure) return;
		materializeErrorStack(e);
		this.failure = e;
		this.callbacks.unavailable();
	}
	start() {
		this.started = true;
	}
	/** Startup admission gates data even when the control owner has already failed. */
	drain() {
		if (this.disposed || !this.started) return;
		for (;;) {
			const e = this.pending.shift();
			if (e) {
				if (e.type === "message") this.callbacks.message(e.value);
				else this.callbacks.messageerror(e.error);
			} else {
				if (this.portClosed || this.failure) return;
				let e;
				try {
					e = runWithMainThreadTask("worker:message-decode", this.readMessage);
				} catch (e) {
					this.fail(toErrorObject(e, "Native worker task channel observation failed"));
					return;
				}
				if (!e) return;
				observeWorkerMessage(e.message, "from_worker");
				this.callbacks.message(e.message);
			}
			if (this.disposed) return;
		}
	}
	service() {
		this.drain();
		if (this.disposed || this.failure) return;
		if (this.portClosed) {
			this.fail(/* @__PURE__ */ new Error("Native worker task channel closed"));
			return;
		}
		let e;
		try {
			e = nativePortIsOpen(this.port);
		} catch (e) {
			this.fail(toErrorObject(e, "Native worker task channel observation failed"));
			return;
		}
		if (!e) {
			this.portClosed = true;
			this.fail(/* @__PURE__ */ new Error("Native worker task channel closed"));
		}
	}
	assertAvailable() {
		if (this.failure) throw this.failure;
		if (this.disposed || this.portClosed) throw new Error("Native worker task channel is closed");
	}
	postMessage(e, t) {
		this.assertAvailable();
		const n = workerMessagePayloadBytes(e);
		this.port.postMessage(e, t);
		observeWorkerMessage(e, "to_worker", "other", n ?? null);
	}
	close() {
		if (this.disposed) return;
		this.disposed = true;
		this.pending.length = 0;
		this.port.off("message", this.receive);
		this.port.off("messageerror", this.receiveError);
		this.port.off("close", this.closed);
		this.port.close();
	}
};
//#endregion
//#region src/infra/worker-request-kind.ts
const standaloneKinds = {
	"catalog-page.worker.js": "catalog",
	"code-mode.worker.js": "codeMode",
	"disk-budget.worker.js": "diskBudget",
	"document-extractor.worker.js": "document",
	"manager-index.worker.js": "memoryIndex",
	"manager-search.worker.js": "memorySearch",
	"memory-index.worker.js": "memoryIndex",
	"memory-search.worker.js": "memorySearch",
	"run.worker.js": "teamReports",
	"session-history.worker.js": "sessionHistory"
};
const kinds = new Map([...Object.entries(runtimeProcessEntrypoints).map(([e, t]) => [basename(t.distWorkerPath), e]), ...Object.entries(standaloneKinds)]);
/** SDK callers may supply their own workers; never publish arbitrary paths as labels. */
function workerRequestKind(e) {
	return kinds.get(basename(e.pathname).replace(/\.(?:ts|mjs)$/, ".js")) ?? "extension";
}
//#endregion
//#region src/infra/worker-native-handle.ts
var NativeWorker = class extends EventEmitter {
	/** Where this worker's code lives; eval and non-file workers have no path. */
	get sourcePath() {
		if (this.evalSource) return;
		if (!(this.filename instanceof URL)) return this.filename;
		return this.filename.protocol === "file:" ? fileURLToPath(this.filename) : void 0;
	}
	constructor(e, t, n, r, i, a, o) {
		super();
		this.runtime = e;
		this.id = t;
		this.filename = n;
		this.evalSource = r;
		this.ownsNativeResource = i;
		this.resourceConnection = a;
		this.runInContext = AsyncLocalStorage.snapshot();
		this.threadId = 0;
		this.started = false;
		this.executionStopped = false;
		this.referenced = true;
		this.stopping = false;
		this.joined = false;
		this.servicingResource = false;
		this.resourceClosed = false;
		this.supervisorJoined = false;
		this.terminalObserved = false;
		this.taskPortLossReported = false;
		this.requestId = 0;
		this.stopCompletion = createRetainedOperation(() => this.service());
		this.cpuRequests = /* @__PURE__ */ new Map();
		this.heapRequests = /* @__PURE__ */ new Map();
		this.diagnosticName = `worker:${!r && n instanceof URL ? workerRequestKind(n) : "other"}`;
		if (o) this.taskPort = new NativeWorkerTaskPort(o, {
			message: (e) => this.runInContext(() => runWithMainThreadTask(this.diagnosticName, () => this.emit("message", e))),
			messageerror: (e) => this.runInContext(() => this.emit("messageerror", e)),
			unavailable: () => this.observeTaskPortLoss()
		});
	}
	get needsReference() {
		return this.referenced || this.stopping || this.executionStopped && this.ownsNativeResource && !this.joined || this.cpuRequests.size > 0 || this.heapRequests.size > 0;
	}
	refreshReference() {
		this.resourceBinding?.setReferenced(this.needsReference);
		this.runtime.refreshReference();
	}
	service() {
		this.runtime.service();
	}
	serviceTaskPort() {
		const e = this.taskPort;
		if (!e) return;
		runWithMainThreadTask(this.diagnosticName, () => e.service());
		this.observeTaskPortLoss();
	}
	observeTaskPortLoss() {
		const e = this.taskPort?.failure;
		if (!e || !this.started || !this.referenced || this.taskPortLossReported || this.terminalObserved || this.stopping || this.joined || this.executionStopped || this.runtime.failure) return;
		this.taskPortLossReported = true;
		this.runInContext(() => this.emit("error", e));
	}
	serviceResource() {
		if (!this.resourceBinding || this.servicingResource || this.joined) return;
		this.servicingResource = true;
		try {
			this.resourceBinding.service();
		} catch (e) {
			this.resourceFailed(e);
		} finally {
			this.servicingResource = false;
		}
	}
	attachResource(e) {
		this.resourceBinding = this.bindResource(e);
		return {
			workerDataKey: e.workerDataKey,
			attachment: this.resourceBinding.attachment
		};
	}
	/** Binds the host's original cleanup port to the same surviving spawn-owner claim. */
	bindResource(e) {
		const t = this.runtime.resourceBroker();
		const n = this.resourceConnection;
		let r = false;
		const i = t.captureNativeResource({
			moduleUrl: e.moduleUrl,
			input: e.input,
			ownerPort: Boolean(n)
		}, {
			message: (e) => {
				if (e.type === "resource-owner") n?.port.postMessage(e.value, []);
				else if (e.type === "resource-closed") this.runInContext(() => {
					this.resourceClosed = true;
					if (this.supervisorJoined || this.executionStopped) this.finishJoined(this.executionExitCode);
				});
			},
			failed: (e) => this.resourceFailed(e)
		});
		const forward = (e) => {
			if (r) return;
			try {
				const t = i.ownerMessage(e);
				if (!this.runtime.failure) this.runtime.post({
					type: "resource-owner",
					id: this.id,
					sequence: t.sequence,
					value: e
				});
			} catch (e) {
				this.resourceFailed(toErrorObject(e, "Native resource owner delivery failed"));
			}
		};
		n?.port.on("message", forward);
		n?.port.unref();
		const dispose = () => {
			if (r) return;
			r = true;
			n?.port.off("message", forward);
			n?.port.close();
			n?.dispose();
		};
		return {
			attachment: i.attachment,
			setReferenced: i.setReferenced,
			receive(e) {
				i.receive(e);
			},
			service() {
				if (r || !n) return;
				n.service();
				for (;;) {
					const e = receiveMessageOnPort(n.port);
					if (!e) break;
					forward(e.message);
				}
			},
			async closeAfterSupervisor() {
				try {
					await t.sealNativeResources();
					await i.close();
				} catch (e) {
					if (e instanceof BrokerNativeResourceCloseError && n?.decodeCloseError) throw n.decodeCloseError(e.payload);
					throw e;
				}
			},
			release() {
				i.release();
				dispose();
			},
			abandonUnattached() {
				i.abandonUnattached();
				dispose();
			}
		};
	}
	abandonResource() {
		this.taskPort?.close();
		if (this.resourceBinding) this.resourceBinding.abandonUnattached();
		else this.resourceConnection?.dispose();
	}
	resourceFailed(e) {
		this.runInContext(() => {
			this.rejectStopCompletion(e);
			this.emit("error", toErrorObject(e, "Native resource observation failed"));
		});
	}
	rejectStopCompletion(e) {
		materializeErrorStack(e);
		this.stopCompletion.reject(e);
	}
	recoverResource() {
		if (!this.resourceBinding || this.joined || this.resourceRecovery) return;
		const e = this.resourceBinding.closeAfterSupervisor();
		this.resourceRecovery = e;
		e.then(() => this.runInContext(() => {
			this.finishJoined(void 0);
		}), (e) => this.runInContext(() => {
			this.stopping = false;
			this.rejectStopCompletion(e);
		}));
	}
	postMessage(e, t = []) {
		if (this.joined || this.stopping || this.executionStopped) throw new Error("Native worker is closing");
		if (this.runtime.failure) throw this.runtime.failure;
		if (this.taskPort) {
			this.taskPort.postMessage(e, t);
			return;
		}
		this.runtime.post({
			type: "post",
			id: this.id,
			value: e,
			transferList: t
		}, t);
	}
	ref() {
		if (this.runtime.failure) throw this.runtime.failure;
		this.taskPort?.assertAvailable();
		this.referenced = true;
		this.refreshReference();
		return this;
	}
	unref() {
		this.referenced = false;
		if (!this.joined && this.runtime.failure) throw this.runtime.failure;
		this.refreshReference();
		return this;
	}
	stop() {
		if (this.joined) {
			if (this.stopCompletion.operation.read().status !== "fulfilled") {
				this.stopCompletion = createRetainedOperation(() => this.service());
				this.stopCompletion.resolve();
			}
			return this.stopCompletion.operation;
		}
		if (this.stopCompletion.operation.read().status === "rejected") this.stopCompletion = createRetainedOperation(() => this.service());
		if (this.supervisorJoined && this.resourceBinding) {
			this.rejectStopCompletion(new Error("Native resource cleanup is still retained after supervisor loss", { cause: this.runtime.failure }));
			this.recoverResource();
			return this.stopCompletion.operation;
		}
		if (!this.stopping) {
			this.stopping = true;
			try {
				this.runtime.post({
					type: "stop",
					id: this.id
				});
			} catch (e) {
				this.stopping = false;
				this.rejectStopCompletion(e);
			}
			this.refreshReference();
		}
		return this.stopCompletion.operation;
	}
	terminate() {
		return this.stop().result;
	}
	cpuUsage(e) {
		return this.requestSample(this.cpuRequests, {
			type: "cpu",
			previous: e
		});
	}
	getHeapStatistics() {
		return this.requestSample(this.heapRequests, { type: "heap" });
	}
	requestSample(e, t) {
		if (this.joined) return Promise.reject(/* @__PURE__ */ new Error("Native worker exited"));
		const n = createRetainedOperation(() => this.service());
		const r = ++this.requestId;
		e.set(r, n);
		try {
			this.runtime.post({
				...t,
				id: this.id,
				requestId: r
			});
		} catch (t) {
			e.delete(r);
			n.reject(t);
		}
		this.refreshReference();
		return n.operation.result;
	}
	rejectSamples(e) {
		for (const t of [...this.cpuRequests.values(), ...this.heapRequests.values()]) t.reject(e);
		this.cpuRequests.clear();
		this.heapRequests.clear();
	}
	ownerFailed(e) {
		this.runInContext(() => {
			this.taskPort?.close();
			this.stopping = false;
			this.rejectSamples(e);
			this.rejectStopCompletion(e);
			this.emit("error", e);
		});
	}
	ownerJoined(e) {
		this.runInContext(() => {
			this.stopping = false;
			this.supervisorJoined = true;
			this.rejectSamples(e);
			this.finishExecution(void 0);
			if (this.ownsNativeResource) {
				if (this.resourceClosed) {
					this.finishJoined(void 0);
					return;
				}
				this.rejectStopCompletion(new Error("Native resource cleanup outcome is unavailable after owner loss", { cause: e }));
				this.recoverResource();
				return;
			}
			this.finishJoined(void 0);
		});
	}
	finishJoined(e) {
		if (this.joined) return;
		this.joined = true;
		this.taskPort?.close();
		this.threadId = -1;
		this.stopping = false;
		this.referenced = false;
		this.rejectSamples(/* @__PURE__ */ new Error("Native worker exited"));
		this.stopCompletion.resolve();
		this.runtime.handles.delete(this.id);
		if (!this.runtime.failure) this.runtime.post({
			type: "release",
			id: this.id
		});
		this.refreshReference();
		if (this.resourceBinding) this.resourceBinding.release();
		else this.resourceConnection?.dispose();
		this.finishExecution(e);
		this.emit("exit", e);
	}
	finishExecution(e) {
		if (!this.executionStopped) {
			this.taskPort?.close();
			this.executionStopped = true;
			this.executionExitCode = e;
			this.emit("execution-exit", e);
		}
		if (this.resourceClosed && !this.joined) this.finishJoined(e);
	}
	receive(e) {
		this.runInContext(() => runWithMainThreadTask(this.diagnosticName, () => {
			if (e.type === "error" || e.type === "messageerror" || e.type === "create-error" || e.type === "execution-exit" || e.type === "stopped" || e.type === "stop-error") {
				this.terminalObserved = true;
				this.taskPort?.drain();
			}
			this.receiveOwned(e);
		}));
	}
	receiveOwned(e) {
		if (e.type === "created") {
			this.started = true;
			this.threadId = e.threadId;
			trackNativeWorkerForCpu(this, this.filename, this.evalSource);
			this.taskPort?.start();
			this.emit("started");
			this.taskPort?.drain();
			this.observeTaskPortLoss();
		} else if (e.type === "message") this.emit("message", e.value);
		else if (e.type === "resource-message") this.resourceBinding?.receive(e.response);
		else if (e.type === "error" || e.type === "messageerror") this.emit(e.type, toErrorObject(decodeNativeWorkerFailure(e.error), "Native worker failed"));
		else if (e.type === "create-error") {
			this.joined = true;
			this.threadId = -1;
			this.referenced = false;
			const t = toErrorObject(decodeNativeWorkerFailure(e.error), "Native worker creation failed");
			this.rejectSamples(t);
			this.stopCompletion.resolve();
			this.runtime.handles.delete(this.id);
			this.refreshReference();
			this.abandonResource();
			this.emit("error", t);
		} else if (e.type === "stopped") {
			this.finishExecution(e.code);
			this.finishJoined(e.code);
		} else if (e.type === "execution-exit") this.finishExecution(e.code);
		else if (e.type === "stop-error") {
			const t = this.stopping;
			this.stopping = false;
			let n;
			try {
				if (e.resourceError) {
					if (!this.resourceConnection?.decodeCloseError) throw new Error("Native resource cleanup error decoder is unavailable", { cause: e.error });
					n = this.resourceConnection.decodeCloseError(e.error);
				} else n = toErrorObject(decodeNativeWorkerFailure(e.error), "Native worker stop failed");
			} catch (e) {
				n = toErrorObject(e, "Native resource cleanup error decoding failed");
			}
			this.rejectStopCompletion(n);
			if (!t) this.emit("error", n);
		} else if (e.type === "cpu") {
			this.cpuRequests.get(e.requestId)?.resolve(e.value);
			this.cpuRequests.delete(e.requestId);
		} else if (e.type === "heap") {
			this.heapRequests.get(e.requestId)?.resolve(e.value);
			this.heapRequests.delete(e.requestId);
		} else if (e.type === "request-error") {
			const t = toErrorObject(decodeNativeWorkerFailure(e.error), "Native worker observation failed");
			this.cpuRequests.get(e.requestId)?.reject(t);
			this.heapRequests.get(e.requestId)?.reject(t);
			this.cpuRequests.delete(e.requestId);
			this.heapRequests.delete(e.requestId);
		}
		this.refreshReference();
	}
};
//#endregion
//#region src/infra/worker-native-lifecycle.ts
const lifetime = resolveGlobalSingleton(Symbol.for("openclaw.nativeWorkerLifetimes"), () => ({
	nextId: 0,
	sources: /* @__PURE__ */ new WeakMap(),
	defaultBroker: {}
}), closeDefaultRetainedNativeWorkerSource);
/** Terminal process cleanup joins the existing unbound owner without starting another. */
async function closeDefaultRetainedNativeWorkerSource() {
	await lifetime.defaultSource?.close();
}
function forgetNativeSource(e) {
	if (e.runtimeGeneration) {
		if (lifetime.sources.get(e.runtimeGeneration) === e) lifetime.sources.delete(e.runtimeGeneration);
	} else if (lifetime.defaultSource === e) lifetime.defaultSource = void 0;
}
function nativeCleanupFailures(e) {
	return e.flatMap((e) => e.status === "rejected" ? [e.reason] : []);
}
function nativeResourceBroker(e) {
	return e.broker.host ??= runInDetachedAsyncContext(() => createSpawnBrokerHost({
		nativeResources: true,
		workerUrl: e.brokerModuleUrl
	}));
}
async function retireNativeResourceBroker(e) {
	const t = e.broker;
	await t.closing;
	if (e.hasActiveWorkers || t.retainedUntilProcessExit || t.host?.hasOpenNativeResourceClaims) return false;
	const n = t.host;
	t.host = void 0;
	await (t.closing = n?.close());
	t.closing = void 0;
	return true;
}
function nativeRuntime(e) {
	if (e.closing) throw new Error("Native worker source is closing");
	const t = e.runtime;
	if (t) {
		if (t.failure) throw t.failure;
		return t;
	}
	return runInDetachedAsyncContext(() => {
		const { port1: t, port2: n } = new MessageChannel();
		const r = e.moduleUrl;
		const i = createSqliteDatabaseAdmissionCursor();
		captureSqliteDatabaseAdmissions(i);
		let a;
		try {
			a = createCpuTrackedWorker(r, {
				execArgv: resolveRuntimeWorkerThreadExecArgv(r),
				env: SHARE_ENV,
				workerData: { port: n },
				transferList: [n]
			});
		} catch (e) {
			t.close();
			n.close();
			throw e;
		}
		const o = /* @__PURE__ */ new Map();
		const s = createDeferredCore();
		s.promise.catch(() => void 0);
		let c = false;
		const terminateOwner = () => {
			if (c) return;
			c = true;
			a.ref();
			t.ref();
			try {
				a.terminate().catch(s.reject);
			} catch (e) {
				s.reject(e);
			}
		};
		const receive = (e) => {
			observeWorkerMessage(e, "from_worker", "lifecycle");
			o.get(e.id)?.receive(e);
		};
		const readControlMessage = () => receiveMessageOnPort(t);
		const l = {
			databaseAdmissionCursor: i,
			handles: o,
			service() {
				for (;;) {
					const e = runWithMainThreadTask("worker:control-decode", readControlMessage);
					if (!e) break;
					receive(e.message);
				}
				const n = [...o.values()];
				for (const e of n) {
					e.serviceTaskPort();
					e.serviceResource();
				}
				if (l.failure) return;
				let r;
				try {
					r = nativePortIsOpen(t);
				} catch (e) {
					fail(new Error("Native worker lifetime channel observation failed", { cause: e }));
					terminateOwner();
					return;
				}
				if (!r) {
					fail(/* @__PURE__ */ new Error("Native worker lifetime channel closed"));
					terminateOwner();
					return;
				}
				e.broker.host?.serviceNativeResources();
			},
			post(e, n = []) {
				if (l.failure) throw l.failure;
				const r = workerMessagePayloadBytes(e);
				t.postMessage(e, n);
				observeWorkerMessage(e, "to_worker", "lifecycle", r ?? null);
			},
			resourceBroker() {
				return nativeResourceBroker(e);
			},
			refreshReference() {
				if ([...o.values()].some((e) => e.needsReference)) {
					a.ref();
					t.ref();
				} else {
					a.unref();
					t.unref();
				}
			},
			close() {
				l.failure ??= /* @__PURE__ */ new Error("Native worker lifetime owner is closing");
				materializeErrorStack(l.failure);
				terminateOwner();
				return s.promise;
			}
		};
		const fail = (e) => {
			if (l.failure) return;
			l.failure = toErrorObject(e, "Native worker lifetime owner failed");
			materializeErrorStack(l.failure);
			for (const e of o.values()) e.ownerFailed(l.failure);
		};
		t.on("message", receive);
		t.on("messageerror", (e) => {
			try {
				fail(e);
			} finally {
				terminateOwner();
			}
		});
		a.on("message", (e) => receiveWorkerMemoryPort(a, e));
		a.on("error", fail);
		a.once("exit", () => {
			setImmediate(() => {
				const n = l.failure ?? /* @__PURE__ */ new Error("Native worker lifetime owner exited");
				materializeErrorStack(n);
				l.failure = n;
				e.closing = true;
				for (const e of o.values()) e.ownerJoined(n);
				t.close();
				s.resolve();
			});
		});
		e.runtime = l;
		l.refreshReference();
		return l;
	});
}
/** Capture before queues; explicit undefined preserves an intentionally unbound lifetime. */
function captureRetainedNativeWorkerSource(e) {
	const t = resolveRuntimeProcessEntrypointUrl("workerNativeLifecycle");
	const n = e === void 0 ? captureRuntimeWorkerSource(t) : {
		moduleUrl: resolveRuntimeWorkerGenerationUrl(t, e.runtimeGeneration),
		runtimeGeneration: e.runtimeGeneration
	};
	const r = n.runtimeGeneration ? lifetime.sources.get(n.runtimeGeneration) : lifetime.defaultSource;
	if (r) return r;
	if (!n.runtimeGeneration && lifetime.defaultBroker.host?.nativeResourceAdmissionClosed) lifetime.defaultBroker = {};
	const i = {
		...n,
		broker: n.runtimeGeneration ? {} : lifetime.defaultBroker,
		brokerModuleUrl: resolveRuntimeWorkerGenerationUrl(resolveRuntimeProcessEntrypointUrl("spawnBroker"), n.runtimeGeneration),
		closing: false,
		get hasActiveWorkers() {
			return Boolean(i.runtime?.handles.size);
		},
		activeWorkerPaths() {
			return [...i.runtime?.handles.values() ?? []].map((e) => e.sourcePath);
		},
		retireIdleBroker() {
			return retireNativeResourceBroker(i);
		},
		close() {
			return o ??= Promise.resolve().then(async () => {
				try {
					const e = nativeCleanupFailures(await Promise.allSettled([...a.values()].map((e) => e())));
					if (e.length) throw new AggregateError(e, "Native worker execution owner cleanup failed");
					if (i.hasActiveWorkers) throw new Error("Native worker execution owners have not joined");
					i.closing = true;
					await i.runtime?.close();
					await retireNativeResourceBroker(i);
					forgetNativeSource(i);
					a.clear();
				} catch (e) {
					if (!i.closing) o = void 0;
					materializeErrorStack(e);
					throw e;
				}
			});
		},
		create(e, t, n, r) {
			try {
				return startNativeWorker(nativeRuntime(i), e, t ?? {}, n, r);
			} catch (e) {
				r?.host.close();
				r?.worker.close();
				throw e;
			}
		},
		async captureIndependentResource(e, t) {
			await i.broker.closing;
			if (i.closing) throw new Error("Native worker source is closing");
			const r = nativeResourceBroker(i);
			const { port1: o, port2: s } = new MessageChannel();
			const c = createDeferredCore();
			const fail = (e) => {
				c.reject(e);
				s.close();
			};
			const l = r.captureNativeResource({
				moduleUrl: String(resolveRuntimeWorkerGenerationUrl(e, n.runtimeGeneration)),
				input: t,
				ownerPort: false
			}, {
				message(e) {
					if (e.type === "resource-created") c.resolve();
				},
				failed: fail
			});
			const u = attachBrokerNativeResource(l.attachment, o, (e) => l.receive(e), fail);
			let d = false;
			let f = false;
			const p = {
				port: s,
				ref() {
					l.setReferenced(true);
					s.ref();
				},
				unref() {
					if (f) return;
					l.setReferenced(false);
					s.unref();
				},
				retainBrokerUntilProcessExit() {
					i.broker.retainedUntilProcessExit = true;
				},
				async close() {
					if (d) return;
					f = true;
					p.ref();
					if (!u.dispatched) l.abandonUnattached();
					else {
						await u.close();
						await l.close();
						l.release();
					}
					u.dispose();
					o.close();
					s.close();
					d = true;
					a.delete(p);
					if (i.closing) await retireNativeResourceBroker(i);
				}
			};
			try {
				await c.promise;
				return p;
			} catch (e) {
				try {
					await p.close();
				} catch (t) {
					i.retain(p, () => p.close());
					throw new AggregateError([e, t], "Native resource creation cleanup failed", { cause: t });
				}
				throw e;
			}
		},
		captureResource(e, t, r, i) {
			const a = AsyncLocalStorage.snapshot();
			return Object.freeze({
				moduleUrl: String(resolveRuntimeWorkerGenerationUrl(e, n.runtimeGeneration)),
				workerDataKey: t,
				input: r === void 0 ? void 0 : structuredClone(r),
				connect: i ? () => a(() => {
					const e = i();
					const t = e.decodeCloseError?.bind(e);
					return {
						port: e.port,
						service: () => a(() => e.service()),
						dispose: () => a(() => e.dispose()),
						decodeCloseError: t ? (e) => a(() => t(e)) : void 0
					};
				}) : void 0
			});
		},
		retain(e, t) {
			a.set(e, t);
			n.runtimeGeneration?.retain(i, () => i.close());
		}
	};
	const a = /* @__PURE__ */ new Map();
	let o;
	if (n.runtimeGeneration) lifetime.sources.set(n.runtimeGeneration, i);
	else lifetime.defaultSource = i;
	return i;
}
/** Existing execution owners retain their queues; this capability owns only physical Worker lifetime. */
function createRetainedNativeWorker(e, t = {}, n, r, i) {
	try {
		return (n ?? captureRetainedNativeWorkerSource({ runtimeGeneration: void 0 })).create(e, t, r, i);
	} catch (e) {
		i?.host.close();
		i?.worker.close();
		throw e;
	}
}
function startNativeWorker(e, t, n, r, i) {
	const a = ++lifetime.nextId;
	let o;
	let s;
	let c = false;
	try {
		o = r?.connect?.();
		s = new NativeWorker(e, a, t, n.eval === true, r !== void 0, o, i?.host);
		const { env: l, transferList: u = [], ...d } = n;
		e.handles.set(a, s);
		const f = r ? s.attachResource(r) : void 0;
		const p = captureSqliteDatabaseAdmissions(e.databaseAdmissionCursor);
		c = true;
		e.post({
			type: "create",
			id: a,
			filename: {
				kind: t instanceof URL ? "url" : "path",
				value: String(t)
			},
			environmentData: captureSqliteWorkerEnvironmentData(p),
			options: {
				...d,
				environment: { ...l === SHARE_ENV ? process.env : l ?? process.env },
				shareEnvironment: l === SHARE_ENV
			},
			transferList: [...u],
			resource: f,
			taskPort: i?.worker
		}, i ? [...u, i.worker] : u);
	} catch (t) {
		if (c) e.databaseAdmissionCursor = createSqliteDatabaseAdmissionCursor();
		e.handles.delete(a);
		e.refreshReference();
		if (s) s.abandonResource();
		else {
			i?.host.close();
			o?.dispose();
		}
		i?.worker.close();
		throw t;
	}
	e.refreshReference();
	return s;
}
//#endregion
//#region src/infra/worker-pool-sizing.ts
function resolveWorkerComputeLimit() {
	return Math.max(1, availableParallelism() - 1);
}
/** Size once at pool creation; serial owners must never inherit host CPU fanout. */
function resolveWorkerPoolSize(e) {
	return Math.min(e === "reader" || e === "file-reader" ? 2 : e === "compute" ? 4 : 1, resolveWorkerComputeLimit());
}
function resolveStateReadWorkerCount() {
	return Math.max(2, resolveWorkerPoolSize("reader"));
}
function resolveSqliteBrokerWorkerCount() {
	return 2;
}
const SESSION_TRANSCRIPT_FOREGROUND_WORKERS = resolveWorkerPoolSize("reader");
//#endregion
//#region src/infra/worker-task-capacity.ts
/** All runtime chunks share the same host-owned computation budget. */
function getWorkerComputeCapacity() {
	return resolveGlobalSingleton(Symbol.for("openclaw.workerComputeCapacity"), () => createWorkerComputeCapacity(resolveWorkerComputeLimit()));
}
//#endregion
//#region src/shared/lazy-promise.ts
/** Returns the cached promise for a key, creating and storing it when absent. */
function getOrCreatePromise(e, t, n, r = {}) {
	const i = e.get(t);
	if (i) return i;
	const a = n();
	e.set(t, a);
	const evict = () => {
		if (e.get(t) === a) e.delete(t);
	};
	if (r.evictOnSettled === true) a.then(evict, evict);
	else if (r.cacheRejections === false) a.catch(evict);
	return a;
}
/**
* Creates a small promise cache that dedupes concurrent loads and can be cleared manually.
*
* Rejections are evicted by default so transient dynamic-import/runtime failures can recover.
*/
function createLazyPromiseLoader(e, t = {}) {
	let n;
	const createPromise = () => {
		const r = Promise.resolve().then(e);
		if (t.cacheRejections !== true) r.catch(() => {
			if (n === r) n = void 0;
		});
		return r;
	};
	return {
		load() {
			n ??= createPromise();
			return n;
		},
		peek() {
			return n;
		},
		clear() {
			n = void 0;
		}
	};
}
//#endregion
//#region src/shared/lazy-runtime.ts
function createLazyRuntimeSurface(e, t) {
	const n = createLazyPromiseLoader(() => e().then(t), { cacheRejections: true });
	return Object.assign(n.load, {
		peek: n.peek,
		clear: n.clear
	});
}
/** Cache the raw dynamically imported runtime module behind a stable loader. */
function createLazyRuntimeModule(e) {
	return createLazyRuntimeSurface(e, (e) => e);
}
//#endregion
//#region src/infra/database-engine/context.ts
const state = resolveGlobalSingleton(Symbol.for("openclaw.databaseEngineSelection"), () => ({}));
const maintenance = resolveGlobalSingleton(Symbol.for("openclaw.databaseEngineMaintenanceSelection"), () => new AsyncLocalStorage());
/** An explicit SQLite selection is distinct from an entry point awaiting config. */
function getDatabaseEngineSelection() {
	return maintenance.getStore() ?? state.selection;
}
/** Offline transitions keep source and target work scoped without changing the running Gateway. */
function withDatabaseEngineSelection(e, t) {
	return maintenance.run(e, t);
}
/** Each store consumes its boot-selected family without resolving configuration again. */
function getDatabaseEngineInput(e) {
	const t = getDatabaseEngineSelection();
	return t?.effectiveEngines[e] === "postgres" ? t.postgres : void 0;
}
//#endregion
//#region src/infra/postgres-sync/pool-state.ts
const inherited = workerData;
const postgresPoolState = resolveGlobalSingleton(Symbol.for("openclaw.postgresIoPool"), () => ({
	endpoints: inherited?.postgresPool,
	workers: void 0,
	nextStep: void 0,
	ready: [],
	refresh: void 0,
	failure: void 0
}));
/** A failed service invalidates this SQL host; its existing task owner retires it. */
function recordPostgresPoolFailure(e) {
	if (!postgresPoolState.nextStep && !postgresPoolState.endpoints?.nextStep) postgresPoolState.failure ??= e;
}
//#endregion
//#region src/infra/postgres-sync/pool.ts
const selfRootDiagnostic = channel("openclaw.postgres.pool.self-root");
function startPool() {
	if (!isMainThread && recordPostgresPoolSelfRoot()) {
		const e = {
			threadId,
			owner: workerScriptName(process.argv[1] ?? "")
		};
		selfRootDiagnostic.publish(e);
		const t = new BroadcastChannel("openclaw.postgres.pool.self-root");
		t.unref();
		t.postMessage(e);
		t.close();
		createSubsystemLogger("postgres").warn(`PostgreSQL worker ${e.owner} (thread ${threadId}) has no inherited pool; starting its own four I/O services.`);
	}
	const e = new SharedArrayBuffer(4);
	const t = Array.from({ length: 4 }, () => ({
		channel: new MessageChannel(),
		signal: new SharedArrayBuffer(8),
		peers: []
	}));
	for (let e = 0; e < t.length; e++) for (let n = e + 1; n < t.length; n++) {
		const { port1: r, port2: i } = new MessageChannel();
		t[e].peers.push({
			port: r,
			signal: t[n].signal
		});
		t[n].peers.push({
			port: i,
			signal: t[e].signal
		});
	}
	const n = {
		services: t.map(({ channel: e, signal: t }) => ({
			port: e.port1,
			signal: t
		})),
		allocation: e,
		nextStep: postgresPoolState.nextStep
	};
	const r = resolveRuntimeProcessEntrypointUrl("postgresBridge");
	const i = resolveRuntimeWorkerThreadExecArgv(r);
	const a = [];
	postgresPoolState.endpoints = n;
	postgresPoolState.workers = a;
	const launch = (e) => {
		const n = t[e];
		const s = new Int32Array(n.signal);
		let c = false;
		const l = new Worker(r, {
			workerData: {
				host: n.channel.port2,
				signal: n.signal,
				peers: n.peers
			},
			transferList: [n.channel.port2, ...n.peers.map(({ port: e }) => e)],
			execArgv: i
		});
		trackNativeWorkerForCpu(l, r);
		l.unref();
		n.channel.port1.unref();
		a[e] = l;
		const u = new Promise((e, t) => {
			l.once("error", t);
			l.once("exit", () => t(/* @__PURE__ */ new Error(`PostgreSQL I/O service exited before readiness.${postgresPoolState.nextStep ? ` Run ${postgresPoolState.nextStep}.` : ""}`)));
			l.once("message", () => e());
		});
		u.catch(() => {});
		postgresPoolState.ready[e] = u;
		l.on("error", () => {});
		l.once("exit", () => {
			c = true;
			Atomics.store(s, 1, 1);
			Atomics.notify(s, 1);
			o.add(e);
		});
		Promise.resolve(Atomics.waitAsync(s, 1, 0).value).then(async () => {
			if (!c) await l.terminate();
		});
	};
	const o = /* @__PURE__ */ new Set();
	postgresPoolState.refresh = () => {
		for (const e of o) {
			o.delete(e);
			const r = {
				channel: new MessageChannel(),
				signal: new SharedArrayBuffer(8),
				peers: []
			};
			t[e] = r;
			n.services[e] = {
				port: r.channel.port1,
				signal: r.signal
			};
			for (let n = 0; n < t.length; n++) {
				if (n === e) continue;
				const i = t[n];
				const { port1: o, port2: s } = new MessageChannel();
				r.peers.push({
					port: o,
					signal: i.signal
				});
				a[n].postMessage({ watch: {
					port: s,
					signal: r.signal
				} }, [s]);
			}
			launch(e);
		}
	};
	try {
		for (let e = 0; e < t.length; e++) launch(e);
	} catch (e) {
		closePostgresPool();
		throw e;
	}
	return n;
}
function getPostgresPool() {
	if (!postgresPoolState.nextStep) postgresPoolState.refresh?.();
	return postgresPoolState.endpoints ?? startPool();
}
/** A child inherits setup endpoints, never a forwarding hop for SQL requests. */
function createPostgresPoolEndpoints(e = getDatabaseEngineSelection()) {
	if (!postgresPoolState.endpoints && (!e || !Object.values(e.effectiveEngines).includes("postgres"))) return;
	const t = getPostgresPool();
	return {
		...t,
		services: t.services.map(({ port: e, signal: t }) => {
			const n = new MessageChannel();
			e.postMessage({ host: n.port2 }, [n.port2]);
			return {
				port: n.port1,
				signal: t
			};
		})
	};
}
function postgresPoolTransferList(e) {
	return e?.services.map(({ port: e }) => e) ?? [];
}
function selectPostgresPoolService() {
	const e = getPostgresPool();
	const t = (Atomics.add(new Uint32Array(e.allocation), 0, 1) >>> 0) % 4;
	return {
		...e.services[t],
		nextStep: e.nextStep
	};
}
/** Executable cleanup calls this after SQL hosts and native backend-close settlement. */
async function closePostgresPool() {
	const e = postgresPoolState.workers;
	postgresPoolState.workers = void 0;
	for (const { port: e } of postgresPoolState.endpoints?.services ?? []) e.close();
	postgresPoolState.endpoints = void 0;
	postgresPoolState.ready = [];
	postgresPoolState.refresh = void 0;
	postgresPoolState.failure = void 0;
	await Promise.all(e?.map((e) => e.terminate()) ?? []);
}
//#endregion
//#region src/shared/store-writer-queue.ts
const MAX_WRITERS_PER_TURN = 4;
const WRITER_TURN_BUDGET_MS = 4;
const activeStoreWriters = resolveGlobalSingleton(Symbol.for("openclaw.activeStoreWriters"), () => new AsyncLocalStorage());
const writerTurn = resolveGlobalSingleton(Symbol.for("openclaw.storeWriterTurn"), () => ({
	started: 0,
	startedAt: 0,
	reset: void 0,
	wait: void 0
}));
function claimStoreWriterTurn(e) {
	const t = performance$1.now();
	if (!writerTurn.reset) {
		writerTurn.started = 0;
		writerTurn.startedAt = t;
		writerTurn.reset = setImmediate$1().then(() => {
			writerTurn.reset = void 0;
		});
	}
	if (!e && (writerTurn.wait || writerTurn.started >= MAX_WRITERS_PER_TURN || t - writerTurn.startedAt >= WRITER_TURN_BUDGET_MS)) return writerTurn.wait ??= setImmediate$1().then(() => {
		writerTurn.wait = void 0;
	});
	writerTurn.started++;
}
function isActiveStoreWriter(e, t, n) {
	if (!e.has(t)) return false;
	let r = activeStoreWriters.getStore();
	while (r) {
		if (r.active && r.queues === e && r.storePath === t) {
			const e = r.keys;
			if (e && (!n || [...n].some((t) => !e.has(t)))) throw new Error("Cannot expand an active store writer's keys");
			return true;
		}
		r = r.parent;
	}
	return false;
}
async function runActiveStoreWriter(e, t, n, r, i) {
	const a = {
		active: true,
		parent: activeStoreWriters.getStore(),
		queues: e,
		storePath: t,
		keys: i
	};
	if (r) {
		r.reentrant = false;
		r.startedAt = performance$1.now();
	}
	try {
		return await runWithAsyncStore(activeStoreWriters, a, n);
	} finally {
		if (r) r.finishedAt = performance$1.now();
		a.active = false;
	}
}
async function drainStoreWriterQueue(e, t) {
	const n = e.get(t);
	if (!n || n.drainPromise) return;
	const r = createDeferredCore();
	n.drainPromise = r.promise;
	const i = /* @__PURE__ */ new Set();
	let a = 0;
	let o = createDeferredCore();
	n.wake = () => o.resolve();
	let s = true;
	try {
		while (n.pending.length > 0 || a > 0) {
			const e = /* @__PURE__ */ new Set();
			let t;
			for (const r of n.pending) {
				const n = r.keys;
				if (!n) {
					if (a === 0 && e.size === 0) t = r;
					break;
				}
				if (![...n].some((t) => i.has(t) || e.has(t))) {
					t = r;
					break;
				}
				for (const t of n) e.add(t);
			}
			if (!t) {
				await o.promise;
				o = createDeferredCore();
				continue;
			}
			let r;
			while (r = claimStoreWriterTurn(s)) await r;
			s = false;
			const c = n.pending.indexOf(t);
			if (c < 0) continue;
			n.pending.splice(c, 1);
			if (!t.keys) {
				await t.fn().then(t.resolve, t.reject);
				continue;
			}
			const l = t.keys;
			for (const e of l) i.add(e);
			a++;
			const finish = () => {
				for (const e of l) i.delete(e);
				a--;
				n.wake?.();
			};
			t.fn().then((e) => {
				finish();
				t.resolve(e);
			}, (e) => {
				finish();
				t.reject(e);
			});
		}
	} finally {
		n.drainPromise = null;
		n.wake = void 0;
		e.delete(t);
		r.resolve();
	}
}
async function runQueuedStoreWrite(e) {
	if (!e.storePath || typeof e.storePath !== "string") throw new Error(`${e.label}: storePath must be a non-empty string, got ${JSON.stringify(e.storePath)}`);
	e.signal?.throwIfAborted();
	const t = e.keys?.length ? new Set(e.keys) : void 0;
	if (e.reentrant === true && isActiveStoreWriter(e.queues, e.storePath, t)) {
		if (e.timing) {
			e.timing.reentrant = true;
			e.timing.startedAt = performance$1.now();
		}
		try {
			return await e.fn();
		} finally {
			if (e.timing) e.timing.finishedAt = performance$1.now();
		}
	}
	const n = AsyncLocalStorage.snapshot();
	let r = e.queues.get(e.storePath);
	if (!r) {
		r = {
			pending: [],
			drainPromise: null
		};
		e.queues.set(e.storePath, r);
	}
	const i = r;
	let detach = () => {};
	const a = new Promise((r, a) => {
		detach = () => e.signal?.removeEventListener("abort", abort);
		const abort = () => {
			const t = i.pending.indexOf(o);
			if (t !== -1) {
				i.pending.splice(t, 1);
				o.reject(e.signal?.reason);
				i.wake?.();
			}
		};
		const o = {
			keys: t,
			fn: async () => {
				detach();
				return await n(runActiveStoreWriter, e.queues, e.storePath, e.fn, e.timing, t);
			},
			resolve: (e) => r(e),
			reject: a
		};
		i.pending.push(o);
		i.wake?.();
		e.signal?.addEventListener("abort", abort, { once: true });
		runInDetachedAsyncContext(() => void drainStoreWriterQueue(e.queues, e.storePath));
	});
	if (e.signal) a.then(detach, detach);
	return await a;
}
//#endregion
//#region src/state/openclaw-agent-write-admission-state.ts
const agentDatabaseWriteAdmissionState = resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseWriteAdmission"), () => ({ queues: /* @__PURE__ */ new Map() }));
const SQLITE_SESSION_WRITER_QUEUES = agentDatabaseWriteAdmissionState.queues;
//#endregion
//#region src/infra/worker-task-pool-registry.ts
const livePools = resolveGlobalSingleton(Symbol.for("openclaw.workerTaskPools"), () => /* @__PURE__ */ new Set());
function* reachablePools() {
	for (const e of livePools) {
		const t = e.deref();
		if (t) yield {
			pool: t,
			reference: e
		};
		else livePools.delete(e);
	}
}
const liveWorkerTaskPools = {
	register(e) {
		for (const t of reachablePools()) if (t.pool === e) return e;
		livePools.add(new WeakRef(e));
		return e;
	},
	async close(e, t, n) {
		await joinOwnedWorkerTasks(t);
		await n();
		for (const t of reachablePools()) if (t.pool === e) livePools.delete(t.reference);
	}
};
//#endregion
//#region src/infra/worker-task-host.ts
const diagnosticTaskKinds = /* @__PURE__ */ new Set([
	"prepare",
	"prepare-session",
	"transcript-stats",
	"session-entries",
	"session-cleanup",
	"session-memory-capture",
	"history-page",
	"historical-eviction-candidates",
	"usage-cost",
	"model-context",
	"context-messages",
	"transcript-search"
]);
const prepareResources = createLazyRuntimeModule(() => import("./temp-artifact-cleanup-D_vB6Wiz.mjs"));
const admissions = resolveGlobalSingleton(Symbol.for("openclaw.workerTaskDatabaseAdmissionChannels"), () => /* @__PURE__ */ new Map());
function createWorkerTaskHost(e = {}, t) {
	const n = t && t !== "writer" && t !== "singleton";
	const r = e.retainedTransport ? e.nativeSource ?? captureRetainedNativeWorkerSource({ runtimeGeneration: void 0 }) : void 0;
	return {
		maxWorkers: t ? resolveWorkerPoolSize(t) : void 0,
		requiresReady: e.retainedTransport,
		createWorker(t, i) {
			const a = {
				execArgv: resolveRuntimeWorkerThreadExecArgv(t),
				...i
			};
			if (a.env === void 0) a.env = resolveNodeCompileCacheEnv();
			if (n) {
				const e = a.resourceLimits;
				a.resourceLimits = {
					maxOldGenerationSizeMb: e?.maxOldGenerationSizeMb ?? 512,
					maxYoungGenerationSizeMb: e?.maxYoungGenerationSizeMb,
					codeRangeSizeMb: e?.codeRangeSizeMb,
					stackSizeMb: e?.stackSizeMb
				};
			}
			if (e.retainedTransport) {
				const { port1: n, port2: i } = new MessageChannel();
				const o = createRetainedNativeWorker(t, a, r, e.nativeResource, {
					host: n,
					worker: i
				});
				return {
					worker: o,
					native: o
				};
			}
			return { worker: createCpuTrackedWorker(t, a) };
		},
		serviceNativeWorkers(e) {
			for (const { owner: e } of admissions.values()) e.service();
			e[0]?.service();
		},
		prepareResources,
		async releaseTemporaryDirectory(e) {
			const { removeTemporaryArtifacts: t } = await prepareResources();
			await t(e, "Worker task");
		},
		captureTaskContext(e) {
			let t = admissions.get(e);
			if (!t) {
				t = {
					owner: runInDetachedAsyncContext(() => createSqliteDatabaseAdmissionRelay(() => {
						if (admissions.get(e)?.retiring !== false) throw new Error("SQLite creation relay's task worker is retiring");
					})),
					sent: false,
					retiring: false
				};
				admissions.set(e, t);
				const n = t;
				e.once("exit", () => {
					n.owner.finish();
					admissions.delete(e);
				});
			}
			const n = getDatabaseEngineSelection();
			const r = {
				collectWorkerMetrics: isWorkerGcObservationEnabled(),
				...n ? { databaseEngineSelection: n } : {},
				deletedAgentDatabaseFences: captureDeletedAgentDatabaseFences(),
				databaseAdmissionDeadlineAtMs: readSqliteDatabaseAdmissionDeadline(),
				...!t.sent ? { databaseAdmissionPort: t.owner.port } : {}
			};
			if (!t.postgresSent) {
				r.postgresPool = createPostgresPoolEndpoints();
				t.postgresSent = r.postgresPool !== void 0;
			}
			t.sent = true;
			return r;
		},
		taskContextTransferList(e) {
			const t = e;
			const n = postgresPoolTransferList(t.postgresPool);
			return t.databaseAdmissionPort ? [t.databaseAdmissionPort, ...n] : n;
		},
		createTaskObserver(e) {
			const t = workerRequestKind(e);
			return (e) => trackWorkerRequest(t, e === void 0 ? "task" : classifyWorkerRequest(e));
		},
		describeTask(e, t) {
			const n = t !== null && typeof t === "object" ? Object.getOwnPropertyDescriptor(t, "kind")?.value : void 0;
			const r = typeof n === "string" && diagnosticTaskKinds.has(n) ? n : "task";
			return `${workerRequestKind(e)}.${r}`;
		},
		receiveMessage: receiveWorkerMemoryPort,
		observeResourceReply: () => recordWorkerMessage("resource", "from_worker"),
		captureWorkerStartObserver,
		workerStarted(e, n) {
			trackSqliteDatabaseAdmissionWorker(e);
			attributeWorkerToPool(e, n, t);
		},
		workerRetiring(e, t) {
			const n = admissions.get(e);
			if (n) n.retiring = true;
			markWorkerRetirement(e, t);
		},
		flushWorkerDiagnostics,
		computeCapacity: getWorkerComputeCapacity(),
		pools: liveWorkerTaskPools
	};
}
//#endregion
//#region src/infra/worker-task-pool.ts
/** Existing SDK surface; task custody remains an internal capability. */
var WorkerTaskPool = class {
	constructor(e) {
		this.core = new WorkerTaskPoolCore(e, createWorkerTaskHost(void 0, e.workerClass), {
			close: (e) => this.close(e),
			getSnapshot: () => this.getSnapshot()
		});
	}
	run(e, t) {
		return this.core.run(e, t);
	}
	get isClosed() {
		return this.core.isClosed;
	}
	getSnapshot() {
		return this.core.getSnapshot();
	}
	retryFailedRetirements() {
		return this.core.retryFailedRetirements();
	}
	rotate() {
		return this.core.rotate();
	}
	close(e, t) {
		return this.core.close(e, t);
	}
};
/** Internal resource owners can retain task custody or use settled ordinary reads. */
function createOwnedWorkerTaskPool(e, t) {
	const n = new WorkerTaskPoolCore(e, createWorkerTaskHost(t, e.workerClass), void 0, t);
	return {
		run: (e, t) => n.run(e, t),
		rotate: () => n.rotate(),
		runTask: (e, t) => n.runTask(e, t),
		startTask: (e, t) => n.startTask(e, t),
		closeResources: (e) => n.startCloseResources(e).result,
		startCloseResources: (e) => n.startCloseResources(e),
		startRotate: () => n.startRotate(),
		getSnapshot: () => n.getSnapshot(),
		close: (e) => n.close(e)
	};
}
//#endregion
export { isWorkerIdleForPressure as _, getPostgresPool as a, resolveNodeCompileCacheEnv as b, recordPostgresPoolFailure as c, withDatabaseEngineSelection as d, getOrCreatePromise as f, trackWorkerRequest as g, captureRetainedNativeWorkerSource as h, createPostgresPoolEndpoints as i, getDatabaseEngineInput as l, resolveStateReadWorkerCount as m, createOwnedWorkerTaskPool as n, postgresPoolTransferList as o, resolveSqliteBrokerWorkerCount as p, runQueuedStoreWrite as r, selectPostgresPoolService as s, WorkerTaskPool as t, getDatabaseEngineSelection as u, WorkerTaskError as v, DEFAULT_WORKER_PENDING_BYTES as y };