openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
203 lines (202 loc) • 5.57 kB
JavaScript
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { existsSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { extname } from "node:path";
import { randomUUID } from "node:crypto";
import { spawn } from "node:child_process";
import { WindowsJob, isSupported } from "@openclaw/proc-safe/windows-job";
//#region scripts/lib/managed-windows-job-entrypoint.mts
const managedWindowsJobEntrypoint = {
currentModuleUrl: import.meta.url,
sourceWorkerName: "managed-windows-job-launcher",
sourceExtension: ".mts",
distWorkerPath: "tooling/managed-windows-job-launcher.js"
};
/** Tooling preflight has no application dependencies, including for worker resolution. */
function resolveManagedWindowsJobEntrypointUrl() {
const e = new URL(import.meta.url);
const t = e.pathname.lastIndexOf("/dist/");
return t < 0 ? new URL(`./${managedWindowsJobEntrypoint.sourceWorkerName}${extname(fileURLToPath(e))}`, e) : new URL(`${e.pathname.slice(0, t + 6)}${managedWindowsJobEntrypoint.distWorkerPath}`, e);
}
//#endregion
//#region scripts/lib/managed-windows-job.mts
var WindowsJobSetupError = class extends Error {
constructor(e, t) {
super(e, { cause: t });
this.reason = e;
}
};
/** One retained kernel Job owns the launcher and every command descendant. */
function spawnWindowsJobChild(e, t, n, r) {
if (process.platform !== "win32") return;
const i = resolveManagedWindowsJobEntrypointUrl();
if (!existsSync(i)) return;
if (!isSupported()) return;
const a = n.stdio;
const o = Array.isArray(a) ? [...a] : Array.from({ length: 3 }, () => a ?? "pipe");
while (o.length < 3) o.push("pipe");
const s = `Local\\OpenClawTooling-${randomUUID()}`;
let c;
try {
c = WindowsJob.create({ name: s });
} catch (e) {
throw new WindowsJobSetupError("job-create-failed", e);
}
const l = createDeferredCore();
l.promise.catch(() => {});
const u = createDeferredCore();
u.promise.catch(() => {});
let d;
let f = false;
let p = false;
let m = false;
let h = false;
let g;
let _;
let v;
let y = false;
let b;
const x = {
admission: l.promise,
ready: u.promise,
get commandPid() {
return g;
},
isControlMessage: (e) => Boolean(e && typeof e === "object" && "job" in e && e.job === s),
beginStop: () => {
m = true;
},
inspect: () => {
if (h) throw new Error("Windows command Job is closed");
return c.processIds();
},
stop: () => {
m = true;
_ ??= performance.now() + 4e3;
try {
if (h) return;
c.terminate(1);
if (!f) d?.kill("SIGKILL");
} finally {
observeExtinction();
}
},
close: () => {
m = true;
if (!h) {
c.close();
h = true;
}
},
certify: () => {
if (!v) {
v = createDeferredCore();
observeExtinction();
}
return v.promise;
}
};
function observeExtinction() {
if (!v || y) return;
clearTimeout(b);
let e;
try {
if (!p || x.inspect().length !== 0) {
if (_ !== void 0 && performance.now() >= _) throw new Error("Windows Job descendant extinction deadline expired");
if (p || _ !== void 0) b = setTimeout(observeExtinction, 25);
return;
}
x.close();
e = { status: "confirmed" };
} catch (t) {
try {
x.close();
} catch {}
e = {
status: "uncertain",
reason: "job-observation-failed",
cause: t instanceof Error ? t : new Error(String(t))
};
}
y = true;
v.resolve(e);
}
try {
const { stdio: a, signal: c, ...h } = n;
const _ = { ...n.env ?? process.env };
const v = {
command: e,
args: [...t],
options: {
...h,
cwd: n.cwd instanceof URL ? fileURLToPath(n.cwd) : n.cwd,
env: _
},
stdio: o.map((e, t) => e === "ipc" || e === "ignore" ? e : t)
};
if (!o.includes("ipc")) o.push("ipc");
const y = spawn(process.execPath, [fileURLToPath(i), s], {
cwd: v.options.cwd,
env: Object.fromEntries(Object.entries(_).filter(([e]) => e.toUpperCase() !== "NODE_OPTIONS")),
stdio: o,
windowsHide: n.windowsHide,
signal: n.signal
});
d = y;
const fail = (e) => {
l.reject(e);
u.reject(e);
try {
x.stop();
} catch {}
};
y.on("error", fail);
y.once("exit", () => {
p = true;
observeExtinction();
const e = /* @__PURE__ */ new Error("Windows Job launcher exited before command startup");
l.reject(new WindowsJobSetupError("job-admission-failed", e));
u.reject(e);
});
y.once("close", () => {
p = true;
observeExtinction();
const e = /* @__PURE__ */ new Error("Windows Job launcher closed before command startup");
l.reject(new WindowsJobSetupError("job-admission-failed", e));
u.reject(e);
});
y.on("message", (e) => {
if (!x.isControlMessage(e)) return;
const t = e;
if (t.type === "ready" && !f && !m) try {
l.resolve();
const launchCommand = () => {
if (!m) {
f = true;
y.send(v, (e) => e && y.emit("error", e));
}
};
if (r) r(launchCommand)?.catch((e) => y.emit("error", e));
else launchCommand();
} catch (e) {
y.emit("error", e instanceof Error ? e : new Error(String(e)));
}
else if (t.type === "spawned") {
g = t.pid;
u.resolve();
} else if (t.type === "job-error" && !f) y.emit("error", new WindowsJobSetupError("job-admission-failed", new Error(t.error)));
else if (t.type === "error") y.emit("error", Object.assign(new Error(t.error), { code: t.code }));
});
return {
child: y,
job: x
};
} catch (e) {
try {
x.close();
} catch {}
throw e;
}
}
//#endregion
export { spawnWindowsJobChild as n, WindowsJobSetupError as t };