UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,122 lines (1,121 loc) • 36.1 kB
import { a as extractErrorCode, p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import { t as killProcessTree } from "./kill-tree-DlMFq2XA.mjs"; import { u as redactToolPayloadText } from "./redact-Mj7pppxC.mjs"; import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { n as materializeErrorStack, t as collectSynchronousErrors } from "./error-graph-internal-DdjdM90N.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { n as runtimeProcessEntrypoints } from "./runtime-process-entrypoints-qiyJvDDT.mjs"; import { a as resolveRuntimeWorkerUrl, n as resolveRuntimeWorkerArgv, o as runtimeNeedsTypeScriptLoader } from "./runtime-worker-url-DRDkoS4J.mjs"; import { a as isPidDefinitelyDead, n as getProcessInstanceStartTime } from "./pid-alive-D899x-ak.mjs"; import { n as classifyChildRuntimeFailure, t as assertChildRuntimeAvailable } from "./child-runtime-viability-DFyU3D5D.mjs"; import { n as truncateUtf8Suffix } from "./utf8-truncate-BH7Ecfuh.mjs"; import { t as SpawnBrokerError } from "./protocol-clIYsqHM.mjs"; import { i as restoreStdinPipe, n as holdPipe, t as brokerSpawnOptions } from "./pipe-Cmf7laig.mjs"; import { t as BrokerChild } from "./child-CJvs_oct.mjs"; import { i as isProcessGroupGone, r as isDeniedProcessGroupProbe } from "./child-process-tree-BHY5y2g3.mjs"; import { a as readProcessGroupMembers, n as isOwnProcfs } from "./service-child-group-ownership-BSRydAAE.mjs"; import { a as MAX_PENDING_MESSAGES, i as MAX_PENDING_BYTES, n as SPAWN_BROKER_STARTUP_TIMEOUT_MS, o as createBrokerReceiver, r as spawnBrokerStartupNowMs, s as createBrokerSender, t as BrokerNativeResourceCloseError } from "./resource-protocol-Cy9D5_Y7.mjs"; import { t as decodeNativeWorkerFailure } from "./worker-native-error-DQmZ8Unc.mjs"; import { fileURLToPath } from "node:url"; import { join } from "node:path"; import { randomBytes } from "node:crypto"; import { rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { deserialize, serialize } from "node:v8"; import { AsyncLocalStorage } from "node:async_hooks"; import { spawn } from "node:child_process"; import { Socket } from "node:net"; import { setTimeout as setTimeout$1 } from "node:timers/promises"; //#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/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/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/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/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 { GRACEFUL_CANCEL_TIMEOUT_MS as n, createSpawnBrokerHost as t };