UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

333 lines (332 loc) • 8.17 kB
import { n as coerceErrorMessage } from "../../error-coercion-hDrHOSGy.mjs"; import { t as createDeferredCore } from "../../deferred-D0La5CRk.mjs"; import { i as resolveEnvironmentValue, n as mergeProcessEnv } from "../../process-env-DVJdcOcM.mjs"; import { t as getWindowsCmdExePath } from "../../windows-install-roots-Df6dQDK7.mjs"; import { t as createWindowsOutputDecoder } from "../../windows-encoding-BGmFeZe1.mjs"; import { WindowsJob } from "@openclaw/proc-safe/windows-job"; //#region src/process/supervisor/service-child-windows-job-anchor.ts const IDLE_OBSERVATION_MS = 10; const OUTPUT_BUFFER_BYTES = 65536; const OUTPUT_ROUNDS_PER_TURN = 2; function sendProcessMessage(e) { return new Promise((t, n) => { if (!process.connected || !process.send) { n(/* @__PURE__ */ new Error("Windows Job anchor IPC is closed")); return; } process.send(e, (e) => e ? n(e) : t()); }); } function runServiceChildWindowsJobAnchor() { const e = createDeferredCore(); let t; let n = "starting"; let r = 0; let i = 0; let a = Promise.resolve(); let o; let s; let c = false; let l = false; let u = false; let d; let f; let p; let m = false; let h = false; const g = []; const _ = createDeferredCore(); const v = createDeferredCore(); v.promise.catch(() => {}); const send = (e) => { if (!t) return Promise.reject(/* @__PURE__ */ new Error("Windows Job anchor has not started")); r += 1; const n = { ...e, generation: t.generation, sequence: r }; const i = a.then(() => sendProcessMessage(n)); a = i.catch(() => {}); return i; }; const deliver = async (e) => { if (!process.connected) { if (!d) requestCleanup("parent-lost"); return; } try { await send(e); } catch (e) { if (process.connected) throw e; if (!d) requestCleanup("parent-lost"); } }; const stopLifecycle = () => { clearTimeout(f); clearImmediate(p); f = void 0; p = void 0; }; const finishAnchor = (e) => { stopLifecycle(); process.exitCode = e; if (process.connected) process.disconnect?.(); }; const closeNativeHandles = () => { let e; for (const t of [s, o]) try { t?.close(); } catch (t) { e ??= t instanceof Error ? t : new Error(coerceErrorMessage(t)); } s = void 0; o = void 0; if (e) throw e; }; const closeAuthority = async (e) => { if (n === "closed") return; n = "closed"; stopLifecycle(); try { if (process.connected) await send({ type: "closing", reason: e }); closeNativeHandles(); v.resolve(); finishAnchor(0); } catch (e) { try { closeNativeHandles(); } catch {} v.reject(e); finishAnchor(1); } }; const failAuthority = async (e) => { if (n === "closed") return; n = "closed"; stopLifecycle(); try { if (process.connected && t) await send({ type: "result-error", error: coerceErrorMessage(e) }).catch(() => {}); closeNativeHandles(); } catch {} finally { v.reject(e); finishAnchor(1); } }; const finishOutput = async (e) => { if (e.ended) return; e.ended = true; const t = e.decoder?.flush(); if (t) await deliver({ type: "output", stream: e.name, chunk: t }); await deliver({ type: "output-end", stream: e.name }); }; const observeOutput = async (e) => { if (e.ended) return false; if (!s || !e.decoder) throw new Error(`${e.name} output ownership was not initialized`); const t = e.name === "stdout" ? s.readStdout(OUTPUT_BUFFER_BYTES) : s.readStderr(OUTPUT_BUFFER_BYTES); if (t === null) { await finishOutput(e); return true; } if (t.length === 0) return false; const n = e.decoder.decode(t); if (n) await deliver({ type: "output", stream: e.name, chunk: n }); return true; }; const observeRoot = async () => { if (c) return false; if (!s) throw new Error("Windows root process ownership was not initialized"); const e = s.exitCode(); if (e === null) return false; c = true; await deliver({ type: "root-result", code: e, signal: null }); return true; }; const observeJob = () => { if (l) return false; if (!o) throw new Error("Windows Job ownership was not initialized"); l = o.accounting().activeProcesses === 0; return l; }; const runLifecycle = async () => { if (m || n === "closed" || !s) { h ||= m; return; } m = true; let e = false; try { e = await observeRoot() || e; e = c && observeJob() || e; for (let t = 0; t < OUTPUT_ROUNDS_PER_TURN; t += 1) { let t = false; for (const e of g) t = await observeOutput(e) || t; e ||= t; if (!t) break; } if (l && c && g.every((e) => e.ended)) { await closeAuthority(d ?? "lineage-closed"); return; } } catch (e) { await failAuthority(e); return; } finally { m = false; } const t = e || h; h = false; scheduleLifecycle(t); }; const scheduleLifecycle = (e) => { if (n === "closed" || !s) return; if (m) { h ||= e; return; } if (e && f) { clearTimeout(f); f = void 0; } if (f || p) return; if (e) { p = setImmediate(() => { p = void 0; runLifecycle(); }); return; } f = setTimeout(() => { f = void 0; runLifecycle(); }, IDLE_OBSERVATION_MS); if (n === "active" && process.connected) f.unref(); }; const requestCleanup = (e) => { if (n === "closed") return v.promise; d ??= e; n = "closing"; if (!s) { closeAuthority(e); return v.promise; } if (!u && !l) { u = true; try { if (!o) throw new Error("Windows Job cleanup authority was not initialized"); o.terminate(1); } catch (e) { failAuthority(e); return v.promise; } } scheduleLifecycle(true); return v.promise; }; const reportStartupError = async (e) => { if (!process.connected) return; await send({ type: "startup-error", error: coerceErrorMessage(e) }); await _.promise; }; const startCommand = async (r) => { t = r; if (typeof r.windowsShellCommand !== "string") { n = "closed"; finishAnchor(1); return; } try { o = WindowsJob.create(); if (r.type === "prepare") { await send({ type: "prepared" }); await Promise.race([e.promise, v.promise]); if (n !== "starting") return; } const t = resolveEnvironmentValue(r.env, "COMSPEC", "win32") || getWindowsCmdExePath(r.env); s = o.spawn({ executable: t, commandLine: `"${t}" /d /s /c "${r.windowsShellCommand}"`, cwd: r.cwd, env: r.env === void 0 ? void 0 : mergeProcessEnv([{ SystemRoot: resolveEnvironmentValue(process.env, "SystemRoot", "win32") }, r.env], "win32") }); const i = s.pid; g.push({ name: "stdout", ended: false }, { name: "stderr", ended: false }); for (const e of g) e.decoder = createWindowsOutputDecoder(); n = "active"; const a = send({ type: "ready", commandPid: i, anchorPid: process.pid }); scheduleLifecycle(true); await a; } catch (e) { if (n === "closed") return; if (n === "closing") { await v.promise.catch(() => {}); return; } if (s && g.some((e) => !e.decoder)) for (const e of g) e.ended = true; await reportStartupError(e); await (s ? requestCleanup("lineage-lost") : closeAuthority("lineage-lost")); } }; process.once("disconnect", () => { _.resolve(); if (!t) { n = "closed"; process.exitCode = 1; return; } requestCleanup("parent-lost"); }); process.once("SIGTERM", () => void requestCleanup("parent-lost")); process.once("SIGINT", () => void requestCleanup("parent-lost")); process.on("message", (r) => { if ((r.type === "start" || r.type === "prepare") && t === void 0 && n === "starting") { startCommand(r); return; } if (!t || n === "closed" || r.type !== "cancel" && r.type !== "startup-error-ack" && r.type !== "launch" || r.generation !== t.generation || r.sequence <= i) { if (t && n !== "closed") requestCleanup("lineage-lost"); return; } i = r.sequence; if (r.type === "launch") e.resolve(); else if (r.type === "startup-error-ack") _.resolve(); else requestCleanup("cancel"); }); } runServiceChildWindowsJobAnchor(); //#endregion export { runServiceChildWindowsJobAnchor };