UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2,187 lines • 68.9 kB
import { c as hasErrnoCode, h as extractErrorCode, y as toErrorObject } from "./paths-0xDagtub.mjs";
import { i as sanitizeTerminalText } from "./utils-BclMknzT.mjs";
import { W as resolveGlobalSingleton } from "./path-guards-quCEQx1i.mjs";
import { i as isPidDefinitelyDead, n as getProcessInstanceStartTime } from "./pid-alive-TveEV-hP.mjs";
import { i as redactToolPayloadText } from "./redact-BRF0hr6G.mjs";
import { t as createSubsystemLogger } from "./subsystem-CeOCPr4l.mjs";
import { n as materializeErrorStack, t as collectSynchronousErrors } from "./error-graph-internal-G5_kmB_7.mjs";
import { i as runInDetachedAsyncContext } from "./plugin-instance-invocation-DLc0_aJ8.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { n as runtimeProcessEntrypoints } from "./runtime-process-entrypoints-EnWn_nGl.mjs";
import { a as runtimeNeedsTypeScriptLoader, i as resolveRuntimeWorkerUrl, n as resolveRuntimeWorkerArgv } from "./runtime-worker-url-BEfqe_m6.mjs";
import { n as isProcessGroupGoneByCensus, r as readProcessGroupMembers, t as isOwnProcfs } from "./service-child-group-ownership-BuaEYg2l.mjs";
import { AsyncLocalStorage, AsyncResource } from "node:async_hooks";
import { execFile, spawn, spawnSync } from "node:child_process";
import { accessSync, constants, opendirSync, readFileSync, statSync } from "node:fs";
import path, { join } from "node:path";
import { fileURLToPath } from "node:url";
import { randomBytes } from "node:crypto";
import fsPromises, { readFile, readdir, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { Buffer as Buffer$1 } from "node:buffer";
import { Socket } from "node:net";
import { deserialize, serialize } from "node:v8";
import { EventEmitter } from "node:events";
import { setTimeout as setTimeout$1 } from "node:timers/promises";
import { inspectChildWaitState, isSupported, reapChild } from "@openclaw/proc-safe/reaper";
//#region src/infra/child-runtime-viability.ts
const runtime = resolveGlobalSingleton(Symbol.for("openclaw.childRuntimeViability"), () => ({
	observations: /* @__PURE__ */ new Map(),
	initialPath: process.execPath,
	initialIdentity: executableIdentity(process.execPath)
}));
const loaderFailure = /(?:dyld[^\n]*:\s*Library not loaded:|error while loading shared libraries:)/i;
const ambiguousLoaderFailure = /(?:dyld[^\n]*:\s*Symbol not found:|symbol lookup error:|Error loading shared library|version [`'"][^`'"\r\n]+[`'"] not found)/i;
function executableIdentity(e) {
	try {
		return formatExecutableIdentity(statSync(e));
	} catch {
		return;
	}
}
function formatExecutableIdentity({ dev: e, ino: t, size: n, mtimeMs: r, mode: i }) {
	return `${e}:${t}:${n}:${r}:${i}`;
}
function publishRuntimeViability(e, t) {
	if (hasErrnoCode(t, "ENOENT") || hasErrnoCode(t, "ENOTDIR")) recordUnavailableRuntime(e, t);
	return {
		execPath: e,
		available: !(runtime.execPath === e && runtime.failure)
	};
}
/** Retained for existing synchronous OOM and SQLite callers. */
function readChildRuntimeViability(e) {
	const t = e?.execPath ?? process.execPath;
	if (runtime.execPath === t && runtime.failure) return {
		execPath: t,
		available: false
	};
	try {
		accessSync(t, constants.X_OK);
	} catch (e) {
		return publishRuntimeViability(t, e);
	}
	return publishRuntimeViability(t);
}
function recoverUnavailableRuntime() {
	if (runtime.execPath !== process.execPath || !runtime.failure || !runtime.recover || runtime.recoveryStarted) return;
	runtime.recoveryStarted = true;
	const e = runtime.recover;
	runInDetachedAsyncContext(() => Promise.resolve().then(e).catch(() => ({
		status: "report-only",
		reason: "Automatic runtime recovery is report-only: service or restart preparation failed. Inspect the service runtime and restart through its owner."
	})).then((e) => {
		createSubsystemLogger("gateway/runtime").warn(`${e.status}: ${e.reason}`);
	}));
}
function runtimeProbeOptions(e = {}) {
	return {
		encoding: "utf8",
		cwd: e.cwd ?? path.parse(process.execPath).root,
		env: e.env ?? {
			...process.env,
			NODE_OPTIONS: void 0
		},
		timeout: 1e3,
		maxBuffer: 8192
	};
}
function formatMissingChildRuntimeWarning(e) {
	return e.available ? void 0 : `The Node.js runtime this Gateway started with (${sanitizeTerminalText(e.execPath)}) can no longer start worker processes, likely because it was upgraded or removed. Restart the Gateway.`;
}
/** A permanent launch failure belongs to the runtime, not to any one worker pool. */
function assertChildRuntimeAvailable() {
	if (runtime.execPath === process.execPath && runtime.failure) throw runtime.failure;
}
function recordUnavailableRuntime(e, t, n) {
	if (runtime.execPath === e && runtime.failure) return runtime.failure;
	runtime.execPath = e;
	const r = formatMissingChildRuntimeWarning({
		execPath: e,
		available: false
	});
	const i = n?.trim();
	runtime.failure = Object.assign(new Error(i ? `${r}\n${i}` : r, { cause: t }), { code: "NODE_RUNTIME_UNAVAILABLE" });
	createSubsystemLogger("gateway/runtime").error(runtime.failure.message);
	recoverUnavailableRuntime();
	return runtime.failure;
}
function needsRuntimeProbe(e) {
	return Boolean(e.error || e.signal === "SIGABRT" || ambiguousLoaderFailure.test(e.stderr ?? ""));
}
function classifyRuntimeProbe(e, t, n, r) {
	if (runtime.execPath === e && runtime.failure) return runtime.failure;
	const i = e !== runtime.initialPath || n !== runtime.initialIdentity;
	return loaderFailure.test(t.stderr) || ambiguousLoaderFailure.test(t.stderr) || hasErrnoCode(t.error, "ENOENT") || hasErrnoCode(t.error, "ENOTDIR") || i && (t.signal === "SIGABRT" || hasErrnoCode(t.error, "ENOEXEC") || hasErrnoCode(t.error, "EACCES") || hasErrnoCode(t.error, "EPERM")) ? recordUnavailableRuntime(e, r, t.stderr) : void 0;
}
/** The public synchronous SQLite reader retains immediate failure classification. */
function classifyChildRuntimeFailure(e) {
	if (e.started) return;
	const t = e.execPath ?? process.execPath;
	if (runtime.execPath === t && runtime.failure) return runtime.failure;
	if (loaderFailure.test(e.stderr ?? "") || e.error && !readChildRuntimeViability({ execPath: t }).available) return recordUnavailableRuntime(t, e.error, e.stderr);
	if (!needsRuntimeProbe(e)) return;
	return classifyRuntimeProbe(t, spawnSync(t, ["--version"], runtimeProbeOptions()), t === runtime.initialPath ? executableIdentity(t) : void 0, e.error);
}
/** Capture startup evidence; the owner reads the diagnosis after native completion. */
function observeChildRuntime(e, t = process.execPath) {
	let n = false;
	let r;
	let i = "";
	e.once("message", () => {
		n = true;
		i = "";
	});
	e.on("error", (e) => {
		r ??= e;
	});
	const captureStderr = (e) => {
		if (!n) i = (i + e.toString()).slice(-8192);
	};
	e.stderr?.on("data", captureStderr);
	return () => e.exitCode === 0 && !r ? void 0 : classifyChildRuntimeFailure({
		execPath: t,
		error: r,
		stderr: i,
		signal: e.signalCode,
		started: n
	});
}
//#endregion
//#region src/process/spawn-broker/child-completion.ts
/** Observe immediately after spawn, before this owner can disconnect or transfer pipes. */
function waitForBrokerChildCompletion(e) {
	return new Promise((t) => {
		let n = e.exitCode != null || e.signalCode != null;
		let r = !e.connected;
		let i = 0;
		const finish = () => {
			if (!n || !r || i !== 0) return;
			e.removeListener("exit", onExit);
			e.removeListener("error", onError);
			e.removeListener("disconnect", onDisconnect);
			t();
		};
		const onExit = () => {
			n = true;
			finish();
		};
		const onError = () => {
			if (e.pid === void 0) {
				n = true;
				r = true;
				finish();
			}
		};
		const onDisconnect = () => {
			r = true;
			finish();
		};
		e.once("exit", onExit);
		e.on("error", onError);
		e.once("disconnect", onDisconnect);
		for (const t of e.stdio ?? []) {
			if (!t || t.closed) continue;
			i++;
			t.once("close", () => {
				i--;
				finish();
			});
		}
		finish();
	});
}
//#endregion
//#region src/utils/utf8-truncate.ts
function isContinuationByte(e) {
	return e !== void 0 && (e & 192) === 128;
}
/** Keeps the longest UTF-8 suffix that fits within the byte limit. */
function truncateUtf8Suffix(e, t) {
	if (t <= 0) return "";
	if (e.length <= t && Buffer$1.byteLength(e) <= t) return e;
	const n = Buffer$1.from(Number.isInteger(t) ? e.slice(-t - 1) : e);
	let r = n.byteLength - t;
	while (r < n.byteLength && isContinuationByte(n[r])) r += 1;
	return n.subarray(r).toString("utf8");
}
//#endregion
//#region src/process/spawn-broker/child-diagnostics.ts
/** Capture the final stderr tail before the owner reports the child's exit. */
function observeBrokerChildDiagnostics(e) {
	const t = process.execPath;
	let n = false;
	e.once("message", () => {
		n = true;
	});
	let r = "";
	e.stderr?.setEncoding("utf8").on("data", (e) => {
		r = truncateUtf8Suffix(r + e, 2048);
	});
	return () => {
		const i = redactToolPayloadText(r).trim();
		return classifyChildRuntimeFailure({
			execPath: t,
			stderr: r,
			signal: e.signalCode,
			started: n
		}) ?? /* @__PURE__ */ new Error(`exited with code=${e.exitCode ?? "null"} signal=${e.signalCode ?? "none"}${i ? `\nstderr:\n${i}` : ""}`);
	};
}
//#endregion
//#region src/process/spawn-broker/protocol.ts
var SpawnBrokerError = class extends Error {
	constructor(e, t) {
		super(e, t);
		this.code = "ERR_SPAWN_BROKER_UNAVAILABLE";
		this.name = "SpawnBrokerError";
	}
};
function serializeBrokerError(e) {
	return {
		message: e.message,
		code: e.code,
		errno: e.errno,
		syscall: e.syscall,
		path: e.path
	};
}
//#endregion
//#region src/process/spawn-broker/pipe.ts
function brokerSpawnOptions(e) {
	const t = e.stdio ?? "pipe";
	const n = typeof t === "string" ? [
		t,
		t,
		t
	] : [...t];
	const r = [];
	for (let e = 0; e < Math.max(3, n.length); e += 1) {
		const t = n[e] ?? (e < 3 ? "pipe" : "ignore");
		if (t === "inherit" && e !== 0) return;
		if (t !== "pipe" && t !== "ignore" && t !== "inherit" && t !== "ipc") return;
		r.push(t);
	}
	if (e.signal || e.timeout || e.killSignal) throw new Error("Unsupported spawn broker cancellation options");
	return {
		cwd: e.cwd instanceof URL ? fileURLToPath(e.cwd) : e.cwd,
		env: e.env ? { ...e.env } : { ...process.env },
		argv0: e.argv0,
		detached: e.detached,
		shell: e.shell,
		windowsHide: e.windowsHide,
		windowsVerbatimArguments: e.windowsVerbatimArguments,
		serialization: e.serialization,
		uid: e.uid,
		gid: e.gid,
		stdio: r
	};
}
const readers = /* @__PURE__ */ new WeakMap();
const holdReadable = () => {};
/** Defer consumption and EOF until the transferred socket is ready for its caller. */
function holdPipe(e) {
	const t = {
		read: e.read.bind(e),
		resumed: false,
		onResume: () => {
			t.resumed = true;
		}
	};
	readers.set(e, t);
	e.on("resume", t.onResume);
	e.on("readable", holdReadable);
	e.read = () => null;
}
/** Restore native stdin's write-only direction after Node's duplex IPC handoff. */
function restoreStdinPipe(e) {
	const t = Reflect.get(e, "_readableState");
	if (!t || typeof t !== "object" || [
		"ended",
		"endEmitted",
		"reading"
	].some((e) => typeof Reflect.get(t, e) !== "boolean")) throw new SpawnBrokerError("Spawn broker requires a Node readable state for stdin");
	stopPipeReads(e);
	Object.assign(t, {
		readable: false,
		ended: true,
		endEmitted: true,
		reading: false
	});
}
function stopPipeReads(e) {
	const t = Reflect.get(e, "_handle");
	if (!t || typeof t !== "object" || !("readStop" in t) || typeof t.readStop !== "function" || !("reading" in t) || typeof t.reading !== "boolean") throw new SpawnBrokerError("Spawn broker requires a transferable Node pipe handle");
	if (t.readStop() !== 0) throw new SpawnBrokerError("Spawn broker could not stop pipe reads");
	t.reading = false;
}
/** Publish stream data and EOF after the caller's readiness continuation. */
function releasePipe(e) {
	const t = restoreReader(e);
	if (!t) return;
	process.nextTick(() => {
		if (e.destroyed) return;
		e.emit("readable");
		if (t.resumed) e.resume();
	});
}
function restoreReader(e) {
	const t = readers.get(e);
	if (!t) return;
	e.read = t.read;
	readers.delete(e);
	e.removeListener("resume", t.onResume);
	e.removeListener("readable", holdReadable);
	return t;
}
//#endregion
//#region src/process/spawn-broker/child.ts
/** Native pipes remain native streams; only lifecycle and IPC cross the broker. */
var BrokerChild = class extends EventEmitter {
	constructor(e, t, n) {
		super();
		this.requestId = e;
		this.transmit = n;
		this.callbackContext = new AsyncResource("OpenClawSpawnBrokerChild");
		this.stdin = null;
		this.stdout = null;
		this.stderr = null;
		this.connected = false;
		this.killed = false;
		this.exitCode = null;
		this.signalCode = null;
		this.stdio = [
			null,
			null,
			null,
			null,
			null
		];
		this.opened = createDeferredCore();
		this.completion = createDeferredCore();
		this.pipes = /* @__PURE__ */ new Set();
		this.sends = /* @__PURE__ */ new Map();
		this.sendSequence = 0;
		this.spawnReceived = false;
		this.eventsReleased = false;
		this.pendingEventOverflow = false;
		this.pendingEvents = [];
		this.exited = false;
		this.closed = false;
		this.processNotStarted = false;
		this.spawnfile = t[0];
		this.spawnargs = [...t];
		this.opened.promise.catch(() => {});
		this.on("error", () => {});
	}
	/** Only the admission owner can establish that no native process was started. */
	markNotStarted() {
		this.processNotStarted = true;
	}
	get notStarted() {
		return this.processNotStarted;
	}
	ready() {
		return this.opened.promise;
	}
	emit(e, ...t) {
		return this.callbackContext.runInAsyncScope(() => super.emit(e, ...t));
	}
	/** Transport bookkeeping survives disposal of the caller's event listeners. */
	waitForClose() {
		return this.completion.promise;
	}
	attachPipe(e, t) {
		t.emit = this.callbackContext.bind(t.emit.bind(t));
		this.stdio[e] = t;
		if (e === 0) this.stdin = t;
		if (e === 1) this.stdout = t;
		if (e === 2) this.stderr = t;
		this.pipes.add(t);
		let n = false;
		const acknowledge = (t) => {
			if (n) return;
			n = true;
			this.transmit({
				type: "output-drained",
				id: this.requestId,
				fd: e,
				error: t ? serializeBrokerError(t) : void 0
			}).catch(() => {});
		};
		t.once(e === 0 ? "finish" : "end", () => acknowledge());
		t.on("error", acknowledge);
		t.once("close", () => {
			acknowledge();
			this.pipes.delete(t);
			this.finishClose();
		});
	}
	receive(e) {
		if (e.type === "spawned") {
			if (this.spawnReceived || this.closed) return;
			this.spawnReceived = true;
			this.pid = e.pid;
			this.spawnfile = e.spawnfile;
			this.spawnargs = e.spawnargs;
			this.connected = e.connected;
			this.stdio.splice(e.stdioLength);
			while (this.stdio.length < e.stdioLength) this.stdio.push(null);
			if (this.connected) this.channel = Object.assign(new EventEmitter(), {
				ref() {},
				unref() {}
			});
			this.opened.resolve();
			setImmediate(() => {
				if (this.closed) return;
				this.emit("spawn");
				setImmediate(() => {
					for (const [e, t] of this.stdio.entries()) if (e > 0 && t instanceof Socket && !t.destroyed) releasePipe(t);
					this.eventsReleased = true;
					for (const e of this.pendingEvents.splice(0)) e();
				});
			});
			return;
		}
		if (!this.eventsReleased && (this.spawnReceived || e.type !== "error")) {
			this.deferEvent(() => this.emitMessage(e));
			return;
		}
		this.emitMessage(e);
	}
	deferEvent(e) {
		if (this.pendingEventOverflow) return;
		if (this.pendingEvents.length >= 64) {
			this.pendingEventOverflow = true;
			this.pendingEvents.splice(0);
			this.pendingEvents.push(() => {
				this.kill("SIGKILL");
				this.failNow(new SpawnBrokerError("Spawn broker startup event capacity exceeded"));
			});
			return;
		}
		this.pendingEvents.push(e);
	}
	emitMessage(e) {
		switch (e.type) {
			case "error": {
				const t = Object.assign(new Error(e.error.message), e.error);
				this.opened.reject(t);
				this.emit("error", t);
				if (!this.pid) {
					this.exited = true;
					this.finishClose();
				}
				break;
			}
			case "exit":
				this.exited = true;
				this.exitCode = e.code;
				this.signalCode = e.signal;
				this.stdin?.destroy();
				this.emit("exit", e.code, e.signal);
				process.nextTick(() => {
					for (const e of this.pipes) if (e.readable) e.resume();
				});
				this.finishClose();
				break;
			case "ipc-sent":
				this.finishSend(e.sequence, e.error ? Object.assign(new Error(e.error.message), e.error) : null);
				break;
			case "disconnect":
				this.failSends(/* @__PURE__ */ new Error("Child process IPC channel is closed"));
				this.connected = false;
				this.channel = void 0;
				this.emit("disconnect");
				this.finishClose();
				break;
			case "ipc":
				this.emit("message", e.message);
				break;
			case "closed": this.finishClose();
		}
	}
	fail(e) {
		if (this.spawnReceived && !this.eventsReleased) {
			this.deferEvent(() => this.failNow(e));
			return;
		}
		this.failNow(e);
	}
	failNow(e) {
		if (this.closed) return;
		this.opened.reject(e);
		this.failSends(e);
		const t = this.connected;
		this.connected = false;
		this.channel = void 0;
		if (t) this.emit("disconnect");
		if (!this.exited) this.emit("error", e);
		for (const t of this.pipes) t.destroy(e);
		this.exited = true;
		this.finishClose();
	}
	finishClose() {
		if (!this.exited || this.channel || this.pipes.size > 0 || this.closed) return;
		this.closed = true;
		this.completion.resolve();
		this.emit("close", this.exitCode, this.signalCode);
	}
	kill(e = "SIGTERM") {
		if (this.exited) return false;
		this.killed = true;
		this.transmit({
			type: "kill",
			id: this.requestId,
			signal: e
		}).catch((e) => this.fail(toErrorObject(e, "Spawn broker signal delivery failed")));
		return true;
	}
	send(e, t, n, r, i) {
		const a = typeof t === "function" ? t : typeof n === "function" ? n : r;
		if (!this.connected || this.sends.size >= 1024) {
			const e = /* @__PURE__ */ new Error(this.connected ? "Child process IPC capacity exceeded" : "Child process IPC channel is closed");
			queueMicrotask(() => a ? a(e) : this.emit("error", e));
			return false;
		}
		const o = ++this.sendSequence;
		this.sends.set(o, AsyncResource.bind((e) => {
			if (a) a(e);
			else if (e) this.emit("error", e);
		}));
		const s = typeof t === "function" ? void 0 : t;
		this.transmit({
			type: "ipc",
			id: this.requestId,
			sequence: o,
			message: e
		}, s, i).catch((e) => this.finishSend(o, toErrorObject(e, "Spawn broker IPC delivery failed")));
		return true;
	}
	finishSend(e, t) {
		const n = this.sends.get(e);
		this.sends.delete(e);
		n?.(t);
	}
	failSends(e) {
		for (const t of this.sends.keys()) this.finishSend(t, e);
	}
	disconnect() {
		if (!this.connected) return;
		this.connected = false;
		this.transmit({
			type: "disconnect",
			id: this.requestId
		}).catch((e) => this.fail(toErrorObject(e, "Spawn broker disconnect failed")));
	}
	ref() {}
	unref() {}
	[Symbol.dispose]() {
		this.kill("SIGTERM");
	}
};
//#endregion
//#region packages/agent-core/src/harness/env/kill-tree.ts
const DEFAULT_GRACE_MS = 3e3;
const MAX_GRACE_MS = 6e4;
const TASKKILL_COMPLETION_TIMEOUT_MS = 3e3;
const UNIX_PROCESS_TREE_TIMEOUT_MS = 500;
const MAX_UNIX_PROCESS_TREE_PIDS = 4096;
const MAX_UNIX_PROCESS_TREE_DEPTH = 128;
/**
* Best-effort process-tree termination with graceful shutdown.
* - Windows: use taskkill /T to include descendants. Sends SIGTERM-equivalent
*   first (without /F), then force-kills if taskkill refuses or the process
*   survives the grace period.
* - Unix: send SIGTERM to the process group when ownership is known, wait the
*   grace period, then SIGKILL. Linux attached children are enumerated and
*   signaled descendants-first because their process group belongs to the gateway.
*
* Group kill (`process.kill(-pid, ...)`) is only used when the PID is verified
* as its own process group leader, unless `detached: true` is explicitly passed.
* This prevents accidentally signaling the gateway's process group when the
* child shares its parent's group.
*
* - `detached: false`: skip group kill unconditionally.
* - `detached: true`: use group kill unconditionally (trust caller).
* - `detached` omitted: use group kill only when PID is the group leader.
*
* `exited()` verifies that every retained escalation target is gone: the group,
* every captured Linux attached-tree identity, or otherwise the root. True latches,
* clears the grace timer, and prevents later `force()` calls from signaling recycled numbers.
*/
function killProcessTree(e, t) {
	if (!Number.isFinite(e) || e <= 0) return;
	if (process.platform === "win32") {
		if (t?.force === true) {
			signalProcessTreeWindowsAndWait(e, "SIGKILL");
			return;
		}
		killProcessTreeWindows(e, normalizeGraceMs(t?.graceMs));
		return;
	}
	const n = t?.detached === true || t?.detached !== false && isProcessGroupLeader(e);
	const r = t?.detached === false && !n && process.platform === "linux";
	const i = r ? collectUnixProcessTree(e) : void 0;
	if (r && !i) {
		signalProcessTreeUnix(e, t?.force === true ? "SIGKILL" : "SIGTERM", false);
		return;
	}
	let a = false;
	const force = () => {
		if (a) return;
		a = true;
		const t = i?.filter(verifiedProcessInstanceAlive) ?? [];
		if (!(n ? isProcessAlive(-e) : r ? t.length > 0 : isProcessAlive(e))) return;
		signalProcessTreeUnix(e, "SIGKILL", n, i ? t : void 0);
	};
	if (t?.force === true) {
		if (i) force();
		else signalProcessTreeUnix(e, "SIGKILL", n);
		return;
	}
	signalProcessTreeUnix(e, "SIGTERM", n, i);
	const o = normalizeGraceMs(t?.graceMs);
	const s = setTimeout(force, o);
	if (!r) s.unref();
	let c = false;
	const exited = () => {
		c ||= n ? !isProcessAlive(-e) : i ? !i.some(capturedProcessInstanceMayBeAlive) : !isProcessAlive(e);
		if (c) {
			a = true;
			clearTimeout(s);
		}
		return c;
	};
	return {
		force: () => {
			clearTimeout(s);
			force();
		},
		exited
	};
}
function normalizeGraceMs(e) {
	if (typeof e !== "number" || !Number.isFinite(e)) return DEFAULT_GRACE_MS;
	return Math.max(0, Math.min(MAX_GRACE_MS, Math.floor(e)));
}
function isProcessAlive(e) {
	try {
		process.kill(e, 0);
	} catch (e) {
		if ((typeof e === "object" && e !== null && "code" in e ? e.code : void 0) !== "EPERM") return false;
	}
	if (e < 0 || process.platform !== "linux") return true;
	try {
		const t = readFileSync(`/proc/${e}/status`, "utf8");
		return !(t.match(/^State:\s+(\S)/m)?.[1] === "Z" && /^Threads:[ \t]+1[ \t]*$/m.test(t));
	} catch {
		return true;
	}
}
function parseProcessGroupId(e) {
	if (typeof e !== "string" || !/^\d+$/.test(e.trim())) return;
	const t = Number(e.trim());
	return Number.isSafeInteger(t) && t > 0 ? t : void 0;
}
function readPsOutput(e) {
	try {
		const t = spawnSync("ps", e, {
			encoding: "utf8",
			timeout: 500
		});
		return t.error || t.status !== 0 ? void 0 : t.stdout;
	} catch {
		return;
	}
}
function readProcStatFields(e) {
	try {
		const t = readFileSync(`/proc/${e}/stat`, "utf8");
		const n = t.lastIndexOf(")");
		if (n < 0) return;
		return t.slice(n + 1).trim().split(/\s+/);
	} catch {
		return;
	}
}
/** Fail closed to direct-PID signaling when group ownership cannot be proved. */
function isProcessGroupLeader(e) {
	return ((process.platform === "linux" ? parseProcessGroupId(readProcStatFields(e)?.[2]) : void 0) ?? parseProcessGroupId(readPsOutput([
		"-p",
		String(e),
		"-o",
		"pgid="
	]))) === e;
}
function parsePositivePids(e) {
	if (typeof e !== "string") return [];
	return e.trim().split(/\s+/u).map((e) => Number(e)).filter((e) => Number.isSafeInteger(e) && e > 0);
}
function readUnixProcessIdentity(e, t) {
	return readUnixProcessInstance(e, t)?.identity;
}
/** Capture identity and parent together so a recycled child PID cannot authorize a foreign tree. */
function readUnixProcessInstance(e, t) {
	if (t !== void 0 && Date.now() >= t) return;
	if (process.platform !== "linux") return;
	const n = readProcStatFields(e);
	const r = Number(n?.[1]);
	const i = n?.[19];
	if (!i || !/^\d+$/u.test(i) || !Number.isSafeInteger(r)) return;
	return {
		identity: `${e}:${i}`,
		ppid: r
	};
}
/** Missing identities are never eligible for an attached-tree signal. */
function verifiedProcessInstanceAlive(e) {
	if (!e.identity || !isProcessAlive(e.pid)) return false;
	return readUnixProcessIdentity(e.pid) === e.identity;
}
/** Completion needs proof: an existing PID whose identity is unreadable may still be the captured instance. */
function capturedProcessInstanceMayBeAlive(e) {
	if (!e.identity || !isProcessAlive(e.pid)) return false;
	const t = readUnixProcessIdentity(e.pid);
	return t === void 0 || t === e.identity;
}
function* readUnixProcessChildren(e, t) {
	let n;
	try {
		n = opendirSync(`/proc/${e}/task`);
		while (t()) {
			const t = n.readSync();
			if (!t) return;
			const r = parseProcessGroupId(t.name);
			if (!r) continue;
			try {
				yield* parsePositivePids(readFileSync(`/proc/${e}/task/${r}/children`, "utf8"));
			} catch {}
		}
	} catch {} finally {
		try {
			n?.closeSync();
		} catch {}
	}
}
/** Capture verified descendants before their parents; an unverified subtree is omitted. */
function collectUnixProcessTree(e) {
	if (process.platform !== "linux") return;
	const t = [];
	const n = /* @__PURE__ */ new Set([e]);
	let r = 0;
	const i = Date.now() + UNIX_PROCESS_TREE_TIMEOUT_MS;
	const a = readUnixProcessIdentity(e, i);
	if (!a || Date.now() >= i) return;
	const withinBounds = (e) => Date.now() < i && e <= MAX_UNIX_PROCESS_TREE_DEPTH;
	const hasCapacity = () => n.size < MAX_UNIX_PROCESS_TREE_PIDS;
	const visit = (e, a, o) => {
		if (!withinBounds(o) || !hasCapacity()) return;
		if (readUnixProcessIdentity(e, i) !== a) return;
		const s = readUnixProcessChildren(e, () => withinBounds(o) && hasCapacity() && r++ < MAX_UNIX_PROCESS_TREE_PIDS && readUnixProcessIdentity(e, i) === a);
		for (const r of s) {
			if (!withinBounds(o + 1) || !hasCapacity()) return;
			if (n.has(r) || r === process.pid) continue;
			n.add(r);
			const a = readUnixProcessInstance(r, i);
			if (!a || a.ppid !== e || !withinBounds(o + 1)) continue;
			visit(r, a.identity, o + 1);
			t.push({
				pid: r,
				identity: a.identity
			});
		}
	};
	visit(e, a, 0);
	return [...t, {
		pid: e,
		identity: a
	}];
}
function signalProcessTreeUnix(e, t, n, r) {
	if (n) {
		signalUnixTarget(-e, t);
		return;
	}
	const i = r ?? [{ pid: e }];
	for (const e of i) {
		if (r && !verifiedProcessInstanceAlive(e)) continue;
		signalUnixTarget(e.pid, t);
	}
}
function signalUnixTarget(e, t) {
	try {
		process.kill(e, t);
	} catch {}
}
function runTaskkill(e, t) {
	return new Promise((n) => {
		let r = false;
		const finish = (e) => {
			if (r) return;
			r = true;
			clearTimeout(i);
			t?.(e);
			n();
		};
		const i = setTimeout(() => finish(null), TASKKILL_COMPLETION_TIMEOUT_MS);
		i.unref?.();
		try {
			const t = spawn("taskkill", e, {
				stdio: "ignore",
				detached: true,
				windowsHide: true
			});
			t.once("error", () => finish(null));
			t.once("close", (e) => finish(e));
		} catch {
			finish(null);
		}
	});
}
function killProcessTreeWindows(e, t) {
	let n = false;
	let r;
	const forceKill = () => {
		if (n) return;
		n = true;
		if (r !== void 0) {
			clearTimeout(r);
			r = void 0;
		}
		if (!isProcessAlive(e)) return;
		signalProcessTreeWindowsAndWait(e, "SIGKILL");
	};
	signalProcessTreeWindowsAndWait(e, "SIGTERM", (e) => {
		if (e !== null && e !== 0) forceKill();
	});
	r = setTimeout(forceKill, t);
	r.unref();
}
function signalProcessTreeWindowsAndWait(e, t, n) {
	return runTaskkill(t === "SIGKILL" ? [
		"/F",
		"/T",
		"/PID",
		String(e)
	] : [
		"/T",
		"/PID",
		String(e)
	], n);
}
//#endregion
//#region src/process/scoped-child-reaper.ts
const scheduledChildren = /* @__PURE__ */ new WeakSet();
const groups = /* @__PURE__ */ new Map();
const EXIT_DELAY_MS = 25;
const POLL_INTERVAL_MS = 1e3;
const CLEANUP_DEADLINE_MS = 3e4;
let timer;
let nextScanAt = 0;
let scanning = false;
function schedule(e) {
	const t = performance.now() + e;
	if (timer && nextScanAt <= t) return;
	clearTimeout(timer);
	nextScanAt = t;
	timer = setTimeout(() => void tick(), e).unref();
}
function onExit() {
	schedule(EXIT_DELAY_MS);
}
async function tick() {
	timer = void 0;
	if (scanning) {
		schedule(EXIT_DELAY_MS);
		return;
	}
	scanning = true;
	try {
		for (const [e, t] of groups) {
			if (performance.now() >= t) {
				groups.delete(e);
				continue;
			}
			try {
				process.kill(-e, 0);
			} catch (t) {
				if (hasErrnoCode(t, "ESRCH")) groups.delete(e);
			}
		}
		if (groups.size === 0) return;
		for (const e of await readdir("/proc/self/task")) {
			let t;
			try {
				t = await readFile(`/proc/self/task/${e}/children`, "utf8");
			} catch {
				continue;
			}
			for (const e of t.trim().split(/\s+/u).filter(Boolean)) {
				const t = Number(e);
				let n;
				try {
					n = await readFile(`/proc/${t}/stat`, "utf8");
				} catch {
					continue;
				}
				const [r, i, a] = n.slice(n.lastIndexOf(")") + 2).split(" ");
				if (!groups.has(Number(a)) || t === Number(a) || Number(i) !== process.pid || r !== "Z") continue;
				try {
					if (!isSupported()) {
						groups.clear();
						return;
					}
					if (inspectChildWaitState(t).kind === "exited") reapChild(t);
				} catch {}
			}
		}
	} catch {} finally {
		scanning = false;
		if (groups.size > 0) schedule(POLL_INTERVAL_MS);
		else {
			clearTimeout(timer);
			timer = void 0;
			process.off("SIGCHLD", onExit);
		}
	}
}
/** Retain only the terminated group's adopted children after libuv consumes root exit. */
function scheduleAdoptedChildZombieReapAfterExit(e, t, n = CLEANUP_DEADLINE_MS) {
	if (process.platform !== "linux" || !t || e.pid === void 0 || scheduledChildren.has(e)) return;
	const r = e.pid;
	scheduledChildren.add(e);
	const start = () => {
		if (groups.size === 0) process.on("SIGCHLD", onExit);
		groups.set(r, performance.now() + Math.max(CLEANUP_DEADLINE_MS, n));
		onExit();
	};
	if (e.exitCode !== null || e.signalCode !== null) start();
	else e.once("exit", start);
}
//#endregion
//#region src/process/child-process-tree.ts
function shouldDetachChildForProcessTree() {
	return process.platform !== "win32";
}
/**
* Linux hosts can deny negative-PID kill(2) (OpenShell's seccomp rule) with EPERM. A kernel EPERM
* (a member owned by another UID) proves the group has members, so the denial is only believed
* when a group that cannot exist is refused with EPERM too, for the same signal as the failing
* call (a filter can allow signal 0 and deny real signals). The kernel answers that group with
* ESRCH, so nothing is delivered. Not cached: the answer is per host call.
*/
function isDeniedProcessGroupProbe(e, t = 0) {
	if (process.platform !== "linux" || !hasErrnoCode(e, "EPERM")) return false;
	try {
		process.kill(-4194305, t);
		return false;
	} catch (e) {
		return hasErrnoCode(e, "EPERM");
	}
}
/** Decides group extinction for `isChildProcessTreeAlive` and spawn-broker cleanup; other probes keep their own EPERM policies. */
function isProcessGroupGone(e) {
	try {
		process.kill(-e, 0);
		return false;
	} catch (t) {
		if (hasErrnoCode(t, "ESRCH")) return true;
		return isDeniedProcessGroupProbe(t) ? isProcessGroupGoneByCensus(e) : false;
	}
}
function isChildProcessTreeAlive(e) {
	if (typeof e.pid !== "number" || e.pid <= 0) return false;
	if (shouldDetachChildForProcessTree()) return !isProcessGroupGone(e.pid);
	try {
		process.kill(e.pid, 0);
		return true;
	} catch (e) {
		return !hasErrnoCode(e, "ESRCH");
	}
}
//#endregion
//#region src/process/supervisor/cancellation-policy.ts
const GRACEFUL_CANCEL_TIMEOUT_MS = 5e3;
//#endregion
//#region src/process/spawn-broker/cleanup.ts
/** Once the original group is absent or its leader identity changes, never signal its number again. */
function isBrokerChildGroupAlive(e) {
	if (isProcessGroupGone(e.pid)) return false;
	const t = getProcessInstanceStartTime(e.pid);
	if (e.isLeaderAlive) {
		if (e.isLeaderAlive()) return e.startedAt === null || t === null || t === e.startedAt;
		if (!isPidDefinitelyDead(e.pid)) return false;
		return e.startedAt === null || t === null || t === e.startedAt;
	}
	if (e.startedAt === null || t === null && !isPidDefinitelyDead(e.pid)) throw new SpawnBrokerError(`Spawn broker group leader identity is unavailable for pid=${e.pid}`);
	return t === null || t === e.startedAt;
}
/**
* Signals group members by positive PID, for hosts that deny negative-PID kill(2). The caller
* reads the snapshot and owns `signaled`, which skips members already hit by this signal.
* Returns how many members of the group were still pending in the snapshot.
*/
function signalRevalidatedGroupMembers(e, t, { snapshot: n, signaled: r }) {
	if (!isOwnProcfs()) throw new SpawnBrokerError("Spawn broker cannot verify the process table belongs to its PID namespace");
	const i = n.filter((t) => t.pid !== process.pid && t.pgid === e && !isPidDefinitelyDead(t.pid));
	if (!i.length) return 0;
	const a = new Map(i.map((e) => [e.pid, getProcessInstanceStartTime(e.pid)]));
	let o;
	for (const n of readProcessGroupMembers(1e3)) {
		if (n.pid === process.pid || n.pgid !== e || !a.has(n.pid)) continue;
		const i = a.get(n.pid);
		if (i === null) {
			if (!isPidDefinitelyDead(n.pid)) throw new SpawnBrokerError(`Spawn broker cannot identify remaining group member pid=${n.pid}`);
			continue;
		}
		if (getProcessInstanceStartTime(n.pid) !== i) continue;
		const s = `${n.pid}:${i}`;
		if (r.get(s) === t) continue;
		try {
			process.kill(n.pid, t);
		} catch (e) {
			if (extractErrorCode(e) !== "ESRCH") {
				o ??= { error: e };
				continue;
			}
		}
		r.set(s, t);
	}
	if (o) throw o.error;
	return i.length;
}
function terminateRetainedBrokerChildGroup(e) {
	let t = false;
	let n = false;
	let r;
	let i;
	let a = "SIGTERM";
	const o = /* @__PURE__ */ new Map();
	const signalMembers = () => {
		try {
			signalRevalidatedGroupMembers(e.pid, a, {
				snapshot: [...readProcessGroupMembers(1e3)],
				signaled: o
			});
		} catch (e) {
			r = e;
		}
	};
	const signal = (n) => {
		if (t) return;
		if (!isBrokerChildGroupAlive(e)) {
			t = true;
			return;
		}
		a = n;
		try {
			process.kill(-e.pid, n);
		} catch (e) {
			if (isDeniedProcessGroupProbe(e, n)) {
				i = e;
				signalMembers();
			} else if (extractErrorCode(e) === "ESRCH") t = true;
			else throw e;
		}
	};
	const force = () => {
		if (t || n) return;
		n = true;
		signal("SIGKILL");
	};
	return {
		force,
		settled: (async () => {
			const n = performance.now() + GRACEFUL_CANCEL_TIMEOUT_MS;
			const a = n + 2e3;
			try {
				signal("SIGTERM");
				for (;;) {
					if (t || !isBrokerChildGroupAlive(e)) break;
					if (performance.now() >= n) force();
					if (i && !t) signalMembers();
					if (performance.now() >= a) throw new SpawnBrokerError(`Spawn broker child cleanup could not be confirmed for pid=${e.pid}`, { cause: r ?? i });
					await setTimeout$1(50);
				}
			} finally {
				t = true;
			}
		})()
	};
}
/** Preserve a lost broker's tree cleanup across host restart and process exit. */
function terminateLostBrokerChild(e, t, n) {
	if (t && n) {
		if (n.pid !== e) throw new SpawnBrokerError("Spawn broker cleanup identity changed");
		return terminateRetainedBrokerChildGroup(n);
	}
	const r = killProcessTree(e, {
		detached: t,
		graceMs: GRACEFUL_CANCEL_TIMEOUT_MS
	});
	const i = performance.now() + GRACEFUL_CANCEL_TIMEOUT_MS + 2e3;
	return {
		force: () => r?.force(),
		settled: (async () => {
			for (;;) {
				if (t) {
					r?.exited();
					if (isPidDefinitelyDead(e) && isProcessGroupGone(e)) break;
				} else if (isPidDefinitelyDead(e) && (r?.exited() ?? true)) break;
				if (performance.now() >= i) throw new SpawnBrokerError(`Spawn broker child cleanup could not be confirmed for pid=${e}`);
				await setTimeout$1(50);
			}
		})()
	};
}
/** A broker's private group retains non-detached children before PID publication. */
function terminateBrokerProcessGroup(e) {
	let t = false;
	let n;
	let r;
	let i = "SIGTERM";
	const a = /* @__PURE__ */ new Map();
	let o;
	const signalMembers = () => {
		try {
			signalRevalidatedGroupMembers(e, i, {
				snapshot: [...readProcessGroupMembers(1e3)],
				signaled: a
			});
		} catch (e) {
			n = e;
		}
	};
	const signal = (t) => {
		i = t;
		try {
			process.kill(-e, t);
		} catch (e) {
			if (isDeniedProcessGroupProbe(e, t)) {
				r = e;
				signalMembers();
			} else if (extractErrorCode(e) !== "ESRCH") n = e;
		}
	};
	const retire = () => {
		t = true;
		clearTimeout(o);
	};
	const force = () => {
		if (t) return;
		if (isProcessGroupGone(e)) {
			retire();
			return;
		}
		clearTimeout(o);
		signal("SIGKILL");
	};
	return {
		force,
		settled: (async () => {
			if (isProcessGroupGone(e)) {
				retire();
				return;
			}
			signal("SIGTERM");
			o = setTimeout(force, GRACEFUL_CANCEL_TIMEOUT_MS);
			const t = performance.now() + GRACEFUL_CANCEL_TIMEOUT_MS + 2e3;
			try {
				while (!isProcessGroupGone(e)) {
					if (performance.now() >= t) throw new SpawnBrokerError(`Spawn broker group cleanup could not be confirmed for pgid=${e}`, { cause: n ?? r });
					if (r) signalMembers();
					await setTimeout$1(50);
				}
			} finally {
				retire();
			}
		})()
	};
}
//#endregion
//#region src/process/spawn-broker/file-reads.ts
/** Request state only; the existing broker owns process startup, failure, and shutdown. */
var BrokerFileReads = class {
	constructor(e) {
		this.host = e;
		this.pending = /* @__PURE__ */ new Map();
		this.sequence = 0;
	}
	get size() {
		return this.pending.size;
	}
	async read(e, t) {
		return (await this.request({ filePath: e }, t)).buffer;
	}
	async readPage(e, t, n) {
		return this.request({
			filePath: e,
			page: t
		}, n);
	}
	async request(e, t) {
		t?.throwIfAborted();
		await this.host.ready();
		t?.throwIfAborted();
		if (!this.host.canAdmit()) throw new SpawnBrokerError("Spawn broker cannot admit a raw file read");
		const n = ++this.sequence;
		const r = createDeferredCore();
		this.pending.set(n, {
			chunks: [],
			result: r
		});
		const abort = () => {
			r.reject(t?.reason);
			this.host.send({
				type: "cancel-read-file",
				id: n
			}).catch(() => {});
		};
		t?.addEventListener("abort", abort, { once: true });
		this.host.send({
			type: "read-file",
			id: n,
			...e
		}).catch(r.reject);
		try {
			return await r.promise;
		} finally {
			t?.removeEventListener("abort", abort);
			this.pending.delete(n);
		}
	}
	receive(e) {
		if (e.type !== "file-read-chunk" && e.type !== "file-read-result") return false;
		const t = this.pending.get(e.id);
		if (t) {
			if (e.type === "file-read-chunk") t.chunks.push(e.bytes);
			else if (e.error) t.result.reject(Object.assign(e.error, { code: e.code }));
			else t.result.resolve(e.page ?? { buffer: Buffer.concat(t.chunks) });
		}
		return true;
	}
	fail(e) {
		for (const t of this.pending.values()) t.result.reject(e);
		this.pending.clear();
	}
};
//#endregion
//#region src/process/spawn-broker/ipc.ts
const FRAME_BYTES = 1048576;
const MAX_PENDING_BYTES = 268435456;
const MAX_PENDING_MESSAGES = 1024;
const FRAME_KIND = "openclaw-spawn-broker-frame";
/** Frame large inputs/results while bounding both native writes and retained payloads. */
function createBrokerSender(e) {
	let t = 0;
	let n = 0;
	let r = 0;
	let i = Promise.resolve();
	const write = (t, n, r) => new Promise((i, a) => {
		try {
			const launch = () => e(t, n, (e) => e ? a(e) : i());
			if (r) r(launch);
			else launch();
		} catch (e) {
			a(toErrorObject(e, "Spawn broker IPC write failed"));
		}
	});
	const enqueue = (e, r) => {
		if (t + e > 268435456 || n >= 1024) return Promise.reject(new SpawnBrokerError("Spawn broker IPC capacity exceeded"));
		t += e;
		n += 1;
		const a = i.then(r);
		i = a.then(() => {}, () => {});
		return a.finally(() => {
			t -= e;
			n -= 1;
		});
	};
	const sender = (e, t, n) => {
		const i = serialize(e);
		const a = i.byteLength;
		if (a > FRAME_BYTES && t) return Promise.reject(new SpawnBrokerError("Spawn broker handle metadata exceeds one IPC frame"));
		const o = ++r;
		const operation = async () => {
			if (a <= FRAME_BYTES) {
				await write(e, t, n);
				return;
			}
			for (let e = 0; e < a; e += FRAME_BYTES) {
				const t = {
					kind: FRAME_KIND,
					id: o,
					total: a,
					offset: e,
					bytes: i.subarray(e, e + FRAME_BYTES)
				};
				await write(t, void 0, e + FRAME_BYTES >= a ? n : void 0);
			}
		};
		return enqueue(a, operation);
	};
	return Object.assign(sender, { reserve(e) {
		return enqueue(FRAME_BYTES, () => e(async (e) => {
			if (serialize(e).byteLength > FRAME_BYTES) throw new SpawnBrokerError("Spawn broker reserved publication exceeds one IPC frame");
			await write(e);
		}));
	} });
}
/** Only the version-matched private peer can supply frames on this channel. */
function createBrokerReceiver() {
	let e;
	const clear = () => {
		e = void 0;
	};
	return {
		receive(t) {
			if (!t || typeof t !== "object" || !("kind" in t) || t.kind !== FRAME_KIND) {
				clear();
				return t;
			}
			const n = t;
			if (!Number.isSafeInteger(n.id) || !Number.isSafeInteger(n.total) || n.total <= FRAME_BYTES || n.total > 268435456 || !Number.isSafeInteger(n.offset) || !Buffer.isBuffer(n.bytes) || n.bytes.length === 0 || n.bytes.length > FRAME_BYTES) throw new SpawnBrokerError("Invalid spawn broker IPC frame");
			let r = e?.id === n.id ? e : void 0;
			if (!r) {
				if (n.offset !== 0) throw new SpawnBrokerError("Spawn broker receive capacity exceeded");
				e = r = {
					id: n.id,
					total: n.total,
					received: 0,
					chunks: []
				};
			}
			if (r.total !== n.total || r.received !== n.offset || r.received + n.bytes.length > r.total) throw new SpawnBrokerError("Out-of-order spawn broker IPC frame");
			r.chunks.push(n.bytes);
			r.received += n.bytes.length;
			if (r.received < r.total) return;
			clear();
			return deserialize(Buffer.concat(r.chunks, r.total));
		},
		clear
	};
}
//#endregion
//#region src/process/spawn-broker/resource-authority.ts
const UNIX_SOCKET_PATH_BYTES = 103;
/**
* Allocate authority without touching disk. Whether the endpoint has a private socket directory
* is decided only here and forwarded whole to the broker, which creates and removes it. The host
* removes it again after readiness in case the broker could not.
*/
function createNativeResourceAuthority() {
	const e = `oc-br-${randomBytes(16).toString("hex")}`;
	const t = join(tmpdir(), e);
	const n = process.platform === "win32" ? void 0 : Buffer.byteLength(join(t, "resource.sock")) <= UNIX_SOCKET_PATH_BYTES ? t : join("/tmp", e);
	const r = randomBytes(32).toString("hex");
	return {
		directory: n,
		secret: r,
		endpoint: n ? join(n, "resource.sock") : `\\\\.\\pipe\\oc-br-${r}`
	};
}
//#endregion
//#region src/infra/worker-native-error.ts
const errorConstructors = new Map([
	EvalError,
	RangeError,
	ReferenceError,
	SyntaxError,
	TypeError,
	URIError,
	Error
].map((e) => [e.name, e]));
function decodeNativeWorkerFailure(e) {
	const t = /* @__PURE__ */ new Map();
	const decode = (e) => {
		if (e.kind === "value") return e.value;
		const n = t.get(e);
		if (n) return n;
		const r = errorConstructors.get(e.constructorName) ?? Error;
		const i = e.constructorName === "AggregateError" ? new AggregateError([], e.message) : e.constructorName === "SuppressedError" ? new SuppressedError(void 0, void 0, e.message) : new r(e.message);
		t.set(e, i);
		i.name = e.name;
		i.stack = e.stack;
		const defineField = (e, t, n = false) => {
			Object.defineProperty(i, e, {
				value: t,
				writable: true,
				configurable: true,
				enumerable: n
			});
		};
		for (const t of [
			"code",
			"errcode",
			"errno"
		]) if (e[t] !== void 0) defineField(t, e[t], true);
		if (e.cause) defineField("cause", decode(e.cause));
		if (e.errors) defineField("errors", e.errors.map(decode));
		for (const t of ["error", "suppressed"]) {
			const n = e[t];
			if (n) defineField(t, decode(n));
		}
		return i;
	};
	return decode(e);
}
//#endregion
//#region src/process/spawn-broker/resource-protocol.ts
const SPAWN_BROKER_STARTUP_TIMEOUT_MS = 15e3;
const monotonic = process.hrtime.bigint.bind(process.hrtime);
/** Native startup shares the host's monotonic clock across Node contexts. */
function spawnBrokerStartupNowMs() {
	return Number(monotonic() / 1000000n);
}
/** The domain decoder, not a transport adapter, restores this original cleanup payload. */
var BrokerNativeResourceCloseError = class extends Error {
	constructor(e) {
		super("Native resource cleanup failed");
		this.payload = e;
		this.name = "BrokerNativeResourceCloseError";
	}
};
//#endregion
//#region src/process/spawn-broker/resource-host.ts
/** Captured claims are part of SpawnBrokerHost; transport loss never retires their custody. */
var BrokerResourceClaims = class {
	constructor(e) {
		this.host = e;
		this.claims = /* @__PURE__ */ new Map();
		this.bufferedBytes = 0;
		this.bufferedMessages = 0;
		this.closeSequence = 0;
		this.sealed = false;
	}
	get size() {
		return this.claims.size;
	}
	get hasOpenClaims() {
		return [...this.claims.values()].some((e) => !e.closed);
	}
	get hasReferencedClaims() {
		return [...this.claims.values()].some((e) => !e.closed && (e.referenced || !e.ready || !e.created || e.settling || e.ownerMessages.size > 0));
	}
	get admissionClosed() {
		return this.failure !== void 0 || this.sealed;
	}
	capture(e, t) {
		if (this.admissionClosed) throw this.failure ?? new SpawnBrokerError("Native resource source is sealed");
		const n = serialize(e);
		if (n.length > 268435456) throw new SpawnBrokerError("Native resource input exceeds IPC capacity");
		const r = deserialize(n);
		const i = {
			attachment: r,
			callbacks: t,
			inContext: AsyncLocalStorage.snapshot(),
			attached: createDeferredCore(),
			ready: false,
			created: false,
			closed: false,
			referenced: true,
			settling: false,
			lastSequence: 0,
			ownerSequence: 0,
			ownerMessages: /* @__PURE__ */ new Map()
		};
		i.attached.promise.catch(() => {});
		this.claims.set(r.id, i);
		this.host.refreshReference();
		const active = () => {
			if (this.claims.get(r.id) !== i) throw new SpawnBrokerError("Native resource claim is released");
			if (i.failure) throw i.failure;
		};
		return {
			attachment: r,
			setReferenced: (e) => {
				if (i.referenced !== e) {
					i.referenced = e;
					this.host.refreshReference();
				}
			},
			receive: (e) => {
				if (e.id !== r.id) throw new SpawnBrokerError("Native resource response belongs to another claim");
				this.receive(e);
			},
			ownerMessage: (e) => {
				active();
				if (i.closed) throw new SpawnBrokerError("Native resource is closed");
				const t = i.ownerSequence + 1;
				const n = serialize({
					type: "resource-owner",
					id: r.id,
					sequence: t,
					value: e
				});
				if (this.bufferedBytes + n.length > 268435456 || this.bufferedMessages >= 1024) throw new SpawnBrokerError("Native resource owner delivery capacity exceeded");
				i.ownerSequence = t;
				const a = deserialize(n);
				i.ownerMessages.set(t, {
					request: a,
					size: n.length
				});
				this.bufferedBytes += n.length;
				this.bufferedMessages++;
				this.host.refreshReference();
				(async () => {
					await i.attached.promise;
					active();
					const e = i.ownerMessages.get(t);
					if (!i.closed && e) await this.host.transmit(e.request);
				})().catch((e) => {
					const t = toErrorObject(e, "Native resource owner delivery failed");
					if (this.claims.get(r.id) === i && !i.closed && !i.failure) i.inContext(() => i.callbacks.failed(t));
				});
				return { sequence: t };
			},
			close: () => {
				if (i.closed) return Promise.resolve();
				try {
					active();
				} catch (e) {
					return Promise.reject(toErrorObject(e, "Native resource is unavailable"));
				}
				if (i.pending) return i.pending.completion.promise;
				const e = --this.closeSequence;
				const t = createDeferredCore();
				t.promise.catch(() => {});
				i.pending = {
					requestId: e,
					completion: t
				};
				i.settling = true;
				this.host.refreshReference();
				(async () => {
					await i.attached.promise;
					active();
					if (!i.closed && i.pending?.requestId === e) await this.host.transmit({
						type: "resource-close",
						id: r.id,
						requestId: e
					});
				})().catch((n) => {
					if (i.pending?.requestId === e) {
						i.pending = void 0;
						t.reject(toErrorObject(n, "Native resource close delivery failed"));
					}
				});
				return t.promise;
			},
			release: () => {
				if (this.claims.get(r.id) !== i) return;
				if (!i.closed) throw new SpawnBrokerError("Native resource must close before release");
				this.host.transmit({
					type: "resource-release",
					id: r.id
				}).catch(() => {});
				this.remove(i);
			},
			abandonUnattached: () => {
				if (this.claims.get(r.id) !== i) return;
				if (i.ready || i.created) throw new SpawnBrokerError("Attached native resource cannot be abandoned");
				const e = new SpawnBrokerError("Native resource was never dispatched");
				i.attached.reject(e);
				i.pending?.completion.reject(e);
				this.remove(i);
			}
		};
	}
	receive(e) {
		const t = this.claims.get(e.id);
		if (!t || t.failure && e.type !== "resource-closed") return;
		if (e.type === "resource-ready") {
			this.host.markReady(e.pid, e.generation);
			if (t.ready) return;
			t.ready = true;
			t.attached.resolve();
		} else if (e.type === "resource-created") {
			if (t.created) return;
			t.created = true;
		} else if (e.type === "resource-owner-received" || e.type === "resource-owner-rejected") {
			const n = t.ownerMessages.get(e.sequence);
			if (n) {
				t.ownerMessages.delete(e.sequence);
				this.bufferedBytes -= n.size;
				this.bufferedMessages--;
				if (e.type === "resource-owner-rejected") {
					const n = toErrorObject(decodeNativeWorkerFailure(e.error), "Native resource owner callback failed");
					t.settling = true;
					this.host.refreshReference();
					t.inContext(() => t.callbacks.failed(n));
				}
				this.host.refreshReference();
			}
			return;
		} else if (e.type === "resource-owner") {
			if (e.sequence <= t.lastSequence) return;
			t.lastSequence = e.sequence;
			t.inContext(() => t.callbacks.message(e));
			return;
		} else if (e.type === "resource-closed") {
			if (t.closed) return;
			t.closed = true;
			this.clearOwnerMessages(t);
			t.pending?.completion.resolve();
			t.pending = void 0;
		} else if (e.type === "resource-close-error") {
			if (t.pending?.requestId === e.requestId) {
				const n = t.pending;
				t.pending = void 0;
				n.completion.reject(e.resourceError ? new BrokerNativeResourceCloseError(e.error) : toErrorObject(decodeNativeWorkerFailure(e.error), "Native resource cleanup failed"));
			}
		} else if (e.type === "resource-failed") {
			const n = toErrorObject(decodeNativeWorkerFailure(e.error), "Native resource failed");
			t.settling = true;
			this.host.refreshReference();
			t.inContext(() => t.callbacks.failed(n));
			return;
		}
		this.host.refreshReference();
		t.inContext(() => t.callbacks.message(e));
	}
	/** Reject new claims without settling retained native resources. */
	closeAdmission() {
		this.sealed = true;
	}
	seal() {
		if (this.sealPromise) return this.sealPromise;
		this.closeAdmission();
		this.sealPromise = this.host.transmit({ type: "resource-seal" }).then(() => {
			for (const e of this.claims.values()) e.attached.resolve();
		}, (e) => {
			materializeErrorStack(e);
			throw e;
		});
		return this.sealPromise;
	}
	/** The broker reported refused initialization and its process and pipes have joined. */
	closeBeforeStartup() {
		for (const e of this.claims.values()) this.receive({
			type: "resource-closed",
			id: e.attachment.id,
			requestId: 0
		});
	}
	fail(e) {
		materializeErrorStack(e);
		this.failure ??= e;
		const t = [...this.claims.values()].filter((t) => this.rejectClaim(t, e));
		const n = collectSynchronousErrors(t, (t) => t.inContext(() => t.callbacks.failed(e)));
		if (n.length) throw new AggregateError(n, "Native resource failure callback failed");
	}
	rejectClaim(e, t) {
		if (e.failure || e.closed) return false;
		e.failure = t;
		e.settling = true;
		this.host.refreshReference();
		e.attached.reject(t);
		e.pending?.completion.reject(t);
		e.pending = void 0;
		return true;
	}
	clearOwnerMessages(e) {
		for (const t of e.ownerMessages.values()) {
			this.bufferedBytes -= t.size;
			this.bufferedMessages--;
		}
		e.ownerMessages.clear();
	}
	remove(e) {
		this.clearOwnerMessages(e);
		this.claims.delete(e.attachment.id);
		this.host.refreshReference();
	}
};
//#endregion
//#region src/process/spawn-broker/host.ts
const MAX_REQUESTS = 256;
const RESTART_DELAYS = [
	100,
	250,
	500,
	1e3,
	2e3
];
const MAX_BOOTSTRAP_BYTES = 1024;
var SpawnBrokerHost = class {
	constructor(e = {}) {
		this.options = e;
		this.runInContext = AsyncLocalStorage.snapshot();
		this.readiness = createDeferredCore();
		this.available = false;
		this.hasBeenReady = false;
		this.closing = false;
		this.generation = 0;
		this.consecutiveFailures = 0;
		this.sequence = 0;
		this.requests = /* @__PURE__ */ new Map();
		this.fileReads = new BrokerFileReads({
			ready: () => this.ready(),
			send: (e) => this.transmit(e),
			canAdmit: () => !this.resourceClaims && !this.closing && this.requests.size + this.fileReads.size < MAX_REQUESTS
		});
		this.cleanups = /* @__PURE__ */ new Set();
		this.cleanupErrors = [];
		this.startupDeadline = 0;
		this.onParentExit = () => {
			if (this.process?.connected) this.process.disconnect();
			for (const e of this.cleanups) e.force();
		};
		this.readFilePage = this.fileReads.readPage.bind(this.fileReads);
		this.workerUrl = e.workerUrl ?? resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.spawnBroker);
		this.entryPath = fileURLToPath(this.workerUrl);
		if (e.nativeResources) {
			this.resourceAuthority = createNativeResourceAuthority();
			this.resourceClaims = new BrokerResourceClaims({
				transmit: async (e) => {
					if (!this.available) await this.ready();
					await this.transmit(e);
				},
				markReady: (e, t) => {
					if (!this.markNativeReady) throw new SpawnBrokerError("Native resource broker unavailable");
					this.markNativeReady(e, t);
				},
				refreshReference: () => this.refreshNativeReference()
			});
		}
		this.readiness.promise.catch(() => {});
		this.start();
		process.once("exit", this.onParentExit);
	}
	get pid() {
		return this.process?.pid;
	}
	get hasOpenNativeResourceClaims() {
		return this.resourceClaims?.hasOpenClaims ?? false;
	}
	get nativeResourceAdmissionClosed() {
		return (this.resourceClaims?.admissionClosed ?? false) || this.process?.connected === false;
	}
	ready() {
		return this.closing ? Promise.reject(new SpawnBrokerError("Spawn broker is closing")) : this.readiness.promise;
	}
	readFile(e, t) {
		return this.fileReads.read(e, t);
	}
	captureNativeResource(e, t) {
		if (!this.resourceClaims || !this.resourceAuthority || this.closing || this.requests.size + this.resourceClaims.size >= MAX_REQUESTS) throw new SpawnBrokerError("Native resource broker is unavailable or at capacity");
		return this.resourceClaims.capture({
			...e,
			...e.moduleUrl.startsWith("file:") && runtimeNeedsTypeScriptLoader(fileURLToPath(e.moduleUrl)) ? { sourceLoaderUrl: import.meta.resolve("tsx/esm/api") } : {},
			endpoint: this.resourceAuthority.endpoint,
			secret: this.resourceAuthority.secret,
			generation: this.generation - 1,
			startupDeadline: this.available ? void 0 : this.startupDeadline,
			id: ++this.sequence
		}, t);
	}
	sealNativeResources() {
		if (this.resourceClaims && !this.available) return Promise.reject(new SpawnBrokerError("Native resource broker is not ready for cleanup"));
		return this.resourceClaims?.seal() ?? Promise.reject(new SpawnBrokerError("Native resources are disabled"));
	}
	serviceNativeResources() {
		this.serviceStartup?.();
	}
	refreshNativeReference() {
		if (!this.resourceClaims || !this.process) return;
		if (this.closing || this.resourceClaims.hasReferencedClaims || this.requests.size > 0) {
			this.process.ref();
			process.ref(this.process.stderr);
			this.process.channel?.ref?.();
		} else {
			this.process.unref();
			process.unref(this.process.stderr);
			this.process.channel?.unref?.();
		}
	}
	spawn(e, t, n, r) {
		const i = brokerSpawnOptions(n);
		if (!i) throw new Error("Unsupported spawn broker stdio or process options");
		return this.admit({
			type: r ? "prepare-spawn" : "spawn",
			id: ++this.sequence,
			argv: [e, ...t],
			options: i
		}, r).child;
	}
	spawnExeca(e, t) {
		const n = ++this.sequence;
		const r = this.admit({
			type: "spawn-execa",
			id: n,
			argv: e,
			options: t
		});
		return {
			child: r.child,
			result: r.result.promise,
			cancel: () => {
				this.transmit({
					type: "cancel",
					id: n
				}).catch((e) => r.child.fail(toErrorObject(e, "Spawn broker cancellation delivery failed")));
			}
		};
	}
	admit(e, t) {
		const n = new BrokerChild(e.id, e.argv, (e, t, n) => this.transmit(e, t, n));
		const r = e.type === "spawn-execa" ? createDeferredCore() : void 0;
		if (r) r.promise.catch(() => {});
		const i = {
			child: n,
			initiateSpawn: t,
			result: r,
			childClosed: false,
			resultSettled: !r,
			detached: e.options.detached === true || e.type === "spawn-execa" && e.options.killDescendants === true
		};
		const fail = (e) => {
			r?.reject(e);
			n.fail(e);
		};
		if (!this.available || this.closing || this.requests.size + this.fileReads.size + (this.resourceClaims?.size ?? 0) >= MAX_REQUESTS) {
			n.markNotStarted();
			queueMicrotask(() => fail(new SpawnBrokerError("Spawn broker is unavailable")));
			return i;
		}
		this.requests.set(e.id, i);
		this.refreshNativeReference();
		n.waitForClose().then(() => {
			i.childClosed = true;
			this.retire(e.id, i);
		});
		this.transmit(e).catch((t) => {
			if (!i.nativeInitiated) {
				if (e.type === "prepare-spawn") n.markNotStarted();
				this.requests.delete(e.id);
				this.refreshNativeReference();
			}
			fail(new SpawnBrokerError("Spawn broker request delivery failed", { cause: t }));
		});
		return i;
	}
	retire(e, t) {
		if (t.childClosed && t.resultSettled && !t.nativeInitiated) {
			this.requests.delete(e);
			this.refreshNativeReference();
		}
	}
	retainCleanup(e) {
		this.cleanups.add(e);
		e.settled.then(() => this.cleanups.delete(e), (t) => {
			this.cleanupErrors.push(toErrorObject(t, "Spawn broker cleanup failed"));
			this.cleanups.delete(e);
		});
	}
	transmit(e, t, n) {
		if (!this.available || !this.sendMessage) return Promise.reject(new SpawnBrokerError("Spawn broker is unavailable"));
		return this.sendMessage(e, t, n);
	}
	start() {
		if (this.closing) return;
		try {
			assertChildRuntimeAvailable();
		} catch (e) {
			this.readiness.reject(e);
			return;
		}
		const e = this.generation++;
		const t = {
			type: "bootstrap",
			...this.resourceAuthority ? { nativeResource: {
				...this.resourceAuthority,
				generation: e
			} } : {}
		};
		if (serialize(t).byteLength > MAX_BOOTSTRAP_BYTES) throw new SpawnBrokerError("Spawn broker bootstrap exceeds its IPC bound");
		const n = spawn(process.execPath, resolveRuntimeWorkerArgv(this.workerUrl), {
			stdio: [
				"inherit",
				"ignore",
				"pipe",
				"ipc"
			],
			detached: true,
			serialization: "advanced"
		});
		this.process = n;
		const r = observeBrokerChildDiagnostics(n);
		let i = false;
		const a = this.brokerClosed = waitForBrokerChildCompletion(n).then(() => {
			if (i && n.pid && (n.exitCode !== 0 || n.signalCode !== null)) this.cleanupErrors.push(new SpawnBrokerError("Spawn broker shutdown failed", { cause: r() }));
		});
		const o = createBrokerReceiver();
		const s = createDeferredCore();
		let c = false;
		let l = false;
		this.startupDeadline = spawnBrokerStartupNowMs() + SPAWN_BROKER_STARTUP_TIMEOUT_MS;
		const checkStartup = () => {
			if (!c && !l && spawnBrokerStartupNowMs() >= this.startupDeadline) fail(/* @__PURE__ */ new Error("readiness deadline exceeded after 15000ms"));
		};
		const u = this.resourceClaims ? void 0 : setTimeout(checkStartup, SPAWN_BROKER_STARTUP_TIMEOUT_MS);
		this.serviceStartup = checkStartup;
		const fail = (e) => {
			if (c) return;
			const t = classifyChildRuntimeFailure({
				error: e,
				started: l
			}) ?? e;
			i = this.closing;
			c = true;
			clearTimeout(u);
			this.markNativeReady = void 0;
			o.clear();
			this.available = false;
			this.resourceClaims?.closeAdmission();
			this.sendMessage = void 0;
			if (n.connected) n.disconnect();
			const r = new SpawnBrokerError(t && hasErrnoCode(t, "NODE_RUNTIME_UNAVAILABLE") ? t.message : this.hasBeenReady ? "Spawn broker exited; command outcome is unavailable" : `Spawn broker failed before readiness: ${t?.message ?? "channel lost"}`, { cause: t });
			const a = this.readiness;
			this.readiness = createDeferredCore();
			this.readiness.promise.catch(() => {});
			a.reject(r);
			this.fileReads.fail(r);
			for (const e of this.requests.values()) {
				if (e.pid && !e.childClosed) {
					const t = e.pid;
					if (this.closing) {
						let r;
						this.retainCleanup({
							force: () => r?.force(),
							settled: s.promise.then(async () => {
								if (n.exitCode === 0 && n.signalCode === null) return;
								r = terminateLostBrokerChild(t, e.detached);
								await r.settled;
							})
						});
					} else this.retainCleanup(terminateLostBrokerChild(t, e.detached));
				}
				e.result?.reject(r);
				e.child.fail(r);
			}
			this.requests.clear();
			this.refreshNativeReference();
			if (n.pid && process.platform !== "win32") {
				const e = n.pid;
				let t;
				this.retainCleanup({
					force: () => t?.force(),
					settled: s.promise.then(async () => {
						t = terminateBrokerProcessGroup(e);
						await t.settled;
					})
				});
			}
			if (this.resourceClaims || this.closing || !this.hasBeenReady || hasErrnoCode(t, "NODE_RUNTIME_UNAVAILABLE")) {
				this.readiness.reject(r);
				this.resourceClaims?.fail(r);
				return;
			}
			const d = RESTART_DELAYS[this.consecutiveFailures++];
			if (d === void 0) {
				this.readiness.reject(r);
				return;
			}
			this.restartTimer = setTimeout(() => this.start(), d);
		};
		const markReady = (t, r) => {
			if (c || t !== n.pid || r !== e) throw new SpawnBrokerError("Native resource readiness does not match the captured broker");
			if (l) return;
			l = true;
			clearTimeout(u);
			this.hasBeenReady = true;
			this.consecutiveFailures = 0;
			this.available = true;
			this.readiness.resolve();
			this.runInContext(() => this.options.onReady?.(t, e > 0));
		};
		this.markNativeReady = markReady;
		n.once("error", fail);
		n.once("exit", () => {
			if (!c) i = this.closing;
			s.resolve();
			if (l) fail(r());
			else a.then(() => fail(r()));
		});
		n.once("disconnect", () => {
			if (l) fail(/* @__PURE__ */ new Error("IPC channel disconnected"));
		});
		n.on("message", (t, n) => {
			if (c || this.closing) {
				if (n instanceof Socket) n.destroy();
				return;
			}
			let r;
			try {
				r = o.receive(t);
			} catch (e) {
				fail(toErrorObject(e, "Spawn broker receive failed"));
				return;
			}
			if (r === void 0) return;
			const i = r;
			if (i.type === "startup-failed") {
				if (!l && this.resourceClaims) {
					const e = this.resourceClaims;
					this.brokerClosed?.then(() => e.closeBeforeStartup()).catch((e) => {
						this.cleanupErrors.push(toErrorObject(e, "Spawn broker startup cleanup failed"));
					});
				}
				fail(Object.assign(new Error(i.error.message), i.error));
				return;
			}
			if (i.type === "ready") {
				try {
					markReady(i.pid, e);
				} catch (e) {
					fail(toErrorObject(e, "Spawn broker readiness failed"));
				}
				return;
			}
			if (i.type === "resource-ready" || i.type === "resource-created" || i.type === "resource-target" || i.type === "resource-owner" || i.type === "resource-owner-received" || i.type === "resource-owner-rejected" || i.type === "resource-closed" || i.type === "resource-close-error" || i.type === "resource-failed") {
				try {
					this.resourceClaims?.receive(i);
				} catch (e) {
					fail(toErrorObject(e, "Spawn broker native resource receive failed"));
				}
				return;
			}
			if (this.fileReads.receive(i)) return;
			const a = this.requests.get(i.id);
			if (!a) {
				if (n instanceof Socket) n.destroy();
				if (i.type === "pipe") this.transmit({
					type: "pipe-received",
					id: i.id,
					fd: i.fd
				}).catch(fail);
				else if (i.type === "prepared") this.transmit({
					type: "launch",
					id: i.id,
					allowed: false
				}).catch(fail);
				return;
			}
			if (i.type === "owned" || i.type === "error") {
				a.nativeInitiated?.resolve();
				a.nativeInitiated = void 0;
			}
			if (i.type === "prepared") {
				const e = a.initiateSpawn;
				a.initiateSpawn = void 0;
				const t = this.brokerClosed;
				const n = e ? a.nativeInitiated ??= createDeferredCore() : void 0;
				const r = t && n ? Promise.race([n.promise, t]) : Promise.reject(/* @__PURE__ */ new Error("Spawn broker retirement is unavailable"));
				r.catch(() => {});
				this.transmit({
					type: "launch",
					id: i.id,
					allowed: true
				}, void 0, (t) => {
					if (!e || !n || a.childClosed) throw new SpawnBrokerError("Spawn broker launch grant is unavailable");
					return e(t, r);
				}).catch(() => {
					this.transmit({
						type: "launch",
						id: i.id,
						allowed: false
					}).catch(fail);
				});
			} else if (i.type === "owned") {
				a.pid = i.pid;
				if (a.childClosed) {
					this.retainCleanup(terminateLostBrokerChild(i.pid, a.detached));
					this.retire(i.id, a);
				}
			} else if (i.type === "pipe") {
				try {
					if (i.closed && i.fd === 0) {
						const e = new Socket();
						a.child.attachPipe(i.fd, e);
						e.destroy();
					} else if (n instanceof Socket) {
						if (i.fd === 0) restoreStdinPipe(n);
						else holdPipe(n);
						a.child.attachPipe(i.fd, n);
					} else throw new SpawnBrokerError("Spawn broker pipe transfer failed");
				} catch (e) {
					if (n instanceof Socket) n.destroy();
					fail(toErrorObject(e, "Spawn broker pipe setup failed"));
					return;
				}
				this.transmit({
					type: "pipe-received",
					id: i.id,
					fd: i.fd
				}).catch(fail);
			} else if (i.type === "pipe-prefix") {
				const e = a.child.stdio[i.fd];
				if (e instanceof Socket && i.bytes.length > 0) e.unshift(i.bytes);
			} else if (i.type === "execa-result") {
				if (a.pid === void 0 && i.result.failed) a.child.markNotStarted();
				a.result?.resolve(i.result);
				a.resultSettled = true;
				this.retire(i.id, a);
			} else {
				if (i.type === "error" && i.resultUnavailable && a.result) {
					a.result.reject(Object.assign(new Error(i.error.message), i.error));
					a.resultSettled = true;
				}
				a.child.receive(i);
				this.retire(i.id, a);
			}
		});
		try {
			n.send(t, (e) => {
				if (e) fail(e);
			});
		} catch (e) {
			fail(toErrorObject(e, "Spawn broker bootstrap delivery failed"));
		}
		if (!c) this.sendMessage = createBrokerSender((e, t, r) => n.send(e, t, { keepOpen: true }, r));
		this.refreshNativeReference();
	}
	/** Join cleanup already retained by this host, including recorded failures. */
	async waitForCleanup() {
		await Promise.allSettled([...this.cleanups].map((e) => e.settled));
		if (this.cleanupErrors.length) throw new AggregateError(this.cleanupErrors, "Spawn broker cleanup did not complete");
	}
	close() {
		if (this.resourceClaims?.hasOpenClaims) return Promise.reject(new SpawnBrokerError("Native resource claims must close before broker shutdown"));
		return this.closePromise ??= this.closeInternal();
	}
	async closeInternal() {
		this.closing = true;
		this.refreshNativeReference();
		this.readiness.reject(new SpawnBrokerError("Spawn broker is closing"));
		this.fileReads.fail(new SpawnBrokerError("Spawn broker is closing"));
		clearTimeout(this.restartTimer);
		try {
			const e = this.process;
			if (e && e.exitCode === null && e.signalCode === null) {
				if (this.resourceClaims) this.transmit({ type: "shutdown" }).catch(() => {
					if (e.connected) e.disconnect();
				});
				else if (e.connected) e.disconnect();
			}
			await this.brokerClosed;
			try {
				await this.waitForCleanup();
			} finally {
				if (this.resourceAuthority?.directory && this.hasBeenReady) await rm(this.resourceAuthority.directory, {
					recursive: true,
					force: true
				});
			}
		} finally {
			process.removeListener("exit", this.onParentExit);
		}
	}
};
function createSpawnBrokerHost(e) {
	return new SpawnBrokerHost(e);
}
//#endregion
export { MAX_PENDING_BYTES as a, isChildProcessTreeAlive as c, BrokerChild as d, SpawnBrokerError as f, observeChildRuntime as g, classifyChildRuntimeFailure as h, decodeNativeWorkerFailure as i, scheduleAdoptedChildZombieReapAfterExit as l, assertChildRuntimeAvailable as m, BrokerNativeResourceCloseError as n, createBrokerReceiver as o, truncateUtf8Suffix as p, spawnBrokerStartupNowMs as r, createBrokerSender as s, createSpawnBrokerHost as t, killProcessTree as u };