UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

255 lines (254 loc) • 7.19 kB
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { n as serializeBrokerError, t as SpawnBrokerError } from "./protocol-clIYsqHM.mjs"; import { r as releasePipe } from "./pipe-Cmf7laig.mjs"; import { AsyncResource } from "node:async_hooks"; import { Socket } from "node:net"; import { EventEmitter } from "node:events"; //#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 export { BrokerChild as t };