openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
631 lines (630 loc) • 20.7 kB
JavaScript
import { I as resolveOptionalIntegerOption, R as resolveTimerTimeoutMs, d as asPositiveFiniteNumber, h as clampPositiveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs";
import { t as isPromiseLike } from "./promise-like-aMoWEh5w.mjs";
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import "./src-H3RMXyFL.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { t as killProcessTree } from "./kill-tree-DlMFq2XA.mjs";
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { t as sleep } from "./sleep-CkI3nkiJ.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as getFileLockProcessStartTime } from "./pid-alive-D899x-ak.mjs";
import { t as BrokerChild } from "./child-CJvs_oct.mjs";
import { n as isChildProcessTreeAlive, s as scheduleAdoptedChildZombieReapAfterExit } from "./child-process-tree-BHY5y2g3.mjs";
import { d as recordCommandProcessFailure, f as resolveProcessExitCode, n as TIMEOUT_EXIT_CODE, o as isPlainCommandExitFailure, r as createSanitizedCommandError, s as isPlainCommandSignalFailure, u as recordCommandProcessCleanup } from "./exec-result-DJMhztYN.mjs";
import { a as getWindowsSystem32ExePath } from "./windows-install-roots-Df6dQDK7.mjs";
import { a as resolveWindowsConsoleEncoding, r as decodeWindowsOutputBuffer } from "./windows-encoding-BGmFeZe1.mjs";
import { t as copyOwnedBuffer } from "./owned-buffer-C1_N0F1K.mjs";
import { a as finalizeCapturedOutput, c as resolveOutputCapture, i as createCapturedOutputBuffers, l as shouldTerminateOnOutput, n as appendCapturedOutput, o as flushPreservedOutputLine, r as appendPreservedOutputLines, s as resolveMaxOutputBytes, t as MAX_PRESERVED_PENDING_LINE_BYTES } from "./exec-output-BYE24ROR.mjs";
import { a as retainCommandProcessCleanup, c as spawnCommand, d as waitForCommandSpawn, i as resolveCommandProcessSignal, l as spawnCommandWithInvocation, n as COMMAND_PROCESS_TREE_KILL_GRACE_MS, o as runOutsideCommandProcessScope, t as COMMAND_PROCESS_GROUP_EXIT_CONFIRMATION_MS, u as waitForCommandProcessGroupExit } from "./exec-spawn-DMKoejF-.mjs";
import { t as setProcessTimeout } from "./process-deadline-CTzOjEFJ.mjs";
import process from "node:process";
import { constants } from "node:os";
//#region src/process/child-process.ts
const EXIT_STDIO_GRACE_MS = 100;
const EXIT_STDIO_MAX_DRAIN_MS = 1e3;
/** Native and broker exit notifications can precede output EOF. */
function hasChildProcessExited(e) {
return e.exitCode != null || e.signalCode != null;
}
/**
* Execa waits for stdout/stderr after the direct child exits. Bound that wait
* when detached descendants keep inherited pipes open, while still draining
* short output tails. The returned cleanup must run after awaiting the child.
*/
function releaseChildProcessOutputAfterExit(e) {
let t;
let n;
let r;
const cleanup = () => {
clearTimeout(t);
clearTimeout(n);
clearTimeout(r);
e.removeListener("exit", onExit);
e.stdout?.removeListener("data", onData);
e.stderr?.removeListener("data", onData);
};
const release = () => {
cleanup();
e.stdout?.destroy();
e.stderr?.destroy();
};
const scheduleRelease = () => {
n ??= setTimeout(release, 0);
n.unref();
};
const armIdleTimer = () => {
clearTimeout(t);
clearTimeout(n);
n = void 0;
t = setTimeout(scheduleRelease, 100);
t.unref();
};
const onData = () => {
if (r) armIdleTimer();
};
const onExit = () => {
r = setTimeout(() => {
r = void 0;
scheduleRelease();
}, EXIT_STDIO_MAX_DRAIN_MS);
r.unref();
armIdleTimer();
};
e.stdout?.on("data", onData);
e.stderr?.on("data", onData);
if (hasChildProcessExited(e)) onExit();
else e.once("exit", onExit);
return cleanup;
}
//#endregion
//#region src/process/exec-termination.ts
const WINDOWS_TASKKILL_TIMEOUT_MS = 5e3;
function createCommandTerminationController(e) {
let t;
let n = "normal";
const readOriginalStart = () => e.processTree && e.child.pid && process.platform !== "win32" ? getFileLockProcessStartTime(e.child.pid) : null;
let r = e.spawned !== void 0;
let i = false;
let a = r ? null : readOriginalStart();
let o;
const isDirectChildAlive = () => !e.isChildExited() && e.child.exitCode == null && e.child.signalCode == null;
const spawnTaskkill = async (t) => {
try {
await runOutsideCommandProcessScope(() => spawnCommand([getWindowsSystem32ExePath("taskkill.exe"), ...t], {
baseEnv: e.baseEnv,
env: e.env,
forceKillAfterDelay: 300,
reject: false,
stdio: "ignore",
timeout: WINDOWS_TASKKILL_TIMEOUT_MS
}));
} catch {}
};
const startWindowsTermination = (t, n) => {
const r = [];
o = (async () => {
if (n) {
r.push(spawnTaskkill([
"/PID",
String(t),
"/T"
]));
await sleep(e.killGraceMs);
if (isDirectChildAlive()) r.push(spawnTaskkill([
"/PID",
String(t),
"/T",
"/F"
]));
} else r.push(spawnTaskkill([
"/PID",
String(t),
"/T",
"/F"
]));
await Promise.allSettled(r);
if (!e.isCommandSettled()) e.cancelController.abort();
})();
};
const terminate = () => {
if (r) {
i = true;
return false;
}
const o = e.child.pid;
const s = isDirectChildAlive();
if (process.platform === "win32" && !s) return false;
if (e.processTree && typeof o === "number") {
if (process.platform === "win32") {
startWindowsTermination(o, e.processTree.mode !== "force");
return true;
}
const r = e.processTree.mode === "force" || e.killSignal === "SIGKILL" || e.killSignal === constants.signals.SIGKILL;
if (t) return !r;
const groupAlive = () => isChildProcessTreeAlive({ pid: o });
const forceAndObserve = async () => {
const t = getFileLockProcessStartTime(o);
if (t !== null && t !== a) {
n = "uncertain";
if (isDirectChildAlive()) e.cancelController.abort();
return;
}
n = "forced";
killProcessTree(o, {
force: true,
detached: true
});
scheduleAdoptedChildZombieReapAfterExit(e.child, true);
n = await waitForCommandProcessGroupExit(o, () => {
const e = getFileLockProcessStartTime(o);
return e === null || e === a;
}) === "exited" ? "forced" : "uncertain";
};
if (!s && !groupAlive()) return false;
if (r) {
t = forceAndObserve();
return false;
}
n = "cooperative";
try {
process.kill(-o, e.killSignal ?? "SIGTERM");
} catch (e) {
if (e.code !== "ESRCH") n = "uncertain";
}
scheduleAdoptedChildZombieReapAfterExit(e.child, true, e.killGraceMs + COMMAND_PROCESS_GROUP_EXIT_CONFIRMATION_MS);
t = new Promise((t) => {
const r = performance.now() + e.killGraceMs;
const check = () => {
if (!groupAlive()) {
n = "cooperative";
t();
return;
}
if (performance.now() < r) {
setTimeout(check, Math.min(25, r - performance.now()));
return;
}
forceAndObserve().then(t);
};
check();
});
return true;
}
if (!s) return false;
if (process.platform === "win32" && typeof o === "number") {
startWindowsTermination(o, false);
return true;
}
return false;
};
const settle = async () => {
if (o) {
await o;
return "forced";
}
await t;
return n;
};
if (e.spawned) e.spawned.then(() => {
a = readOriginalStart();
r = false;
if (i && !terminate()) e.cancelController.abort();
}, () => {
r = false;
});
return {
terminate,
settle
};
}
//#endregion
//#region src/process/exec-runner.ts
async function runCommandWithTimeout(e, t) {
return await runCommandWithOutputEncoding(e, t, false);
}
/** Run a command whose stdout and stderr are defined to be UTF-8 on every platform. */
async function runUtf8CommandWithTimeout(e, t) {
return await runCommandWithOutputEncoding(e, t, true);
}
/** Preserve the ordinary process lifecycle while deferring decoding to its consumer. */
async function runCommandBuffersWithTimeout(e, t) {
return await runCommandWithOutputEncoding(e, t, false, true);
}
/** Retain raw bytes with UTF-8 capture boundaries, independent of the Windows console page. */
async function runUtf8CommandBuffersWithTimeout(e, t) {
return await runCommandWithOutputEncoding(e, t, true, true);
}
async function runCommandWithOutputEncoding(e, t, n, r = false) {
const i = typeof t === "number" ? { timeoutMs: t } : t;
const { timeoutMs: a, cwd: o, input: s, stdinFileDescriptor: c, baseEnv: ee, env: l, noOutputTimeoutMs: te, killProcessTree: u, killSignal: ne, killGraceMs: re } = i;
const d = resolveCommandProcessSignal(i.signal);
const f = typeof a === "number" ? resolveTimerTimeoutMs(a, 1) : void 0;
if (i.requireProcessTreeExtinction && !u) throw new Error("Process-tree extinction requires process-tree ownership");
const p = s !== void 0;
if (c !== void 0) {
if (!Number.isInteger(c) || c < 0) throw new Error("stdinFileDescriptor must be a nonnegative integer");
if (p) throw new Error("Command accepts either input or stdinFileDescriptor, not both");
}
if (i.beforeInput && !p) throw new Error("Child input admission requires explicit input");
const ie = resolveTimerTimeoutMs(re, 300, 0);
if (d?.aborted) {
const e = {
code: null,
signal: null,
killed: false,
termination: "signal",
cleanup: "normal",
noOutputTimedOut: false
};
return r ? {
...e,
stdout: Buffer.alloc(0),
stderr: Buffer.alloc(0),
windowsEncoding: null
} : {
...e,
stdout: "",
stderr: ""
};
}
const m = createCapturedOutputBuffers();
const h = createCapturedOutputBuffers();
const g = resolveMaxOutputBytes(i.maxOutputBytes, "stdout");
const _ = resolveMaxOutputBytes(i.maxOutputBytes, "stderr");
const v = resolveOptionalIntegerOption(asPositiveFiniteNumber(i.maxCombinedOutputBytes), { min: 1 });
const y = resolveOutputCapture(i.outputCapture, "stdout");
const b = resolveOutputCapture(i.outputCapture, "stderr");
if (v !== void 0 && y !== b) throw new Error("maxCombinedOutputBytes requires matching stdout and stderr capture modes");
const x = v !== void 0 && y === "tail" && b === "tail";
const ae = Math.min(Math.max(g, _), MAX_PRESERVED_PENDING_LINE_BYTES);
const oe = Math.max(0, Math.floor(i.maxPreservedOutputLines ?? 16));
const S = n ? null : resolveWindowsConsoleEncoding();
const C = new AbortController();
let w;
let T;
let E = false;
let D = 0;
let O = 0;
const se = {
stdout: 0,
stderr: 0
};
const k = {
stdout: 0,
stderr: 0
};
const A = [];
let j;
let M;
let N;
let P;
let F;
const { child: I, invocation: L } = spawnCommandWithInvocation(e, {
buffer: false,
cancelSignal: C.signal,
inheritScopeCancellation: false,
cwd: o,
detached: Boolean(u && process.platform !== "win32"),
encoding: "buffer",
executionTimeoutMs: f,
baseEnv: ee,
env: l,
forceKillAfterDelay: ie,
killSignal: ne,
...p && !i.beforeInput ? { input: s } : {},
reject: false,
stdio: [
i.stdinFileDescriptor ?? (p ? "pipe" : "inherit"),
"pipe",
"pipe"
],
stripFinalNewline: false,
windowsVerbatimArguments: i.windowsVerbatimArguments
});
const R = I.pid === void 0 ? waitForCommandSpawn(I) : void 0;
let ce = R !== void 0;
const le = createDeferredCore();
const z = I.nodeChildProcess;
let B = i.beforeInput ? false : void 0;
const failedProcess = (e, t = "uncertain") => {
const n = recordCommandProcessFailure(e, {
pid: z.pid,
code: T?.code ?? z.exitCode ?? null,
cleanup: t,
inputReleased: B,
termination: w === "output-limit" ? "signal" : w ?? (z.signalCode ? "signal" : "exit")
});
return Object.assign(n, { cleanup: t });
};
const V = Boolean(u && process.platform !== "win32");
const H = clampPositiveTimerTimeoutMs(te);
const U = V && (f !== void 0 || H !== void 0);
let W;
const G = createCommandTerminationController({
child: z,
spawned: R,
cancelController: C,
baseEnv: ee,
env: l,
processTree: u ? { mode: "graceful" } : void 0,
isChildExited: () => T !== void 0,
isCommandSettled: () => E,
killGraceMs: ie,
killSignal: ne
});
const K = (async () => {
await I.then(() => void 0, () => void 0);
E = true;
await R?.catch(() => {});
return await G.settle();
})();
retainCommandProcessCleanup(K);
K.catch(() => {});
z.once("exit", (e, t) => {
T = {
code: e,
signal: t
};
if (!U || e !== 0 || w) W = releaseChildProcessOutputAfterExit(z);
if (u && !w && (e !== 0 || i.requireProcessTreeExtinction)) G.terminate();
});
const cancel = (e, t = false) => {
if (w || E || T && e !== "output-limit" && (!V || T.code !== 0)) return;
if ((e === "timeout" || e === "no-output-timeout") && (T || hasChildProcessExited(z))) {
if (!U || (T?.code ?? z.exitCode) !== 0) return;
if ((!z.stdout || z.stdout.readableEnded) && (!z.stderr || z.stderr.readableEnded)) return;
if (!t) {
M ??= setProcessTimeout(() => cancel(e, true), 100);
return;
}
}
M?.clear();
w = e;
if (ce) le.resolve(e);
if (T) W ??= releaseChildProcessOutputAfterExit(z);
if (!G.terminate()) C.abort();
};
const armNoOutputTimer = () => {
if (H === void 0 || E || w || T && !V) return;
if (j) j.refresh();
else j = setProcessTimeout(() => cancel("no-output-timeout"), H);
};
const ue = f === void 0 ? void 0 : setProcessTimeout(() => cancel("timeout"), f);
const onAbort = () => cancel("signal");
d?.addEventListener("abort", onAbort, { once: true });
armNoOutputTimer();
const clearTimers = () => {
ue?.clear();
j?.clear();
M?.clear();
j = void 0;
d?.removeEventListener("abort", onAbort);
};
if (R) {
let e;
try {
e = await Promise.race([R.then(() => void 0), le.promise]);
} catch (e) {
clearTimers();
throw failedProcess(e, z instanceof BrokerChild && z.notStarted ? "normal" : "uncertain");
}
if (e) {
clearTimers();
K.finally(() => W?.()).catch(() => {});
const t = {
pid: z.pid,
code: e === "timeout" || e === "no-output-timeout" ? 124 : null,
signal: null,
killed: z.killed,
cleanup: "uncertain",
termination: e === "output-limit" ? "signal" : e,
noOutputTimedOut: e === "no-output-timeout",
outputLimitExceeded: e === "output-limit" || void 0
};
return recordCommandProcessCleanup(r ? {
...t,
stdout: Buffer.alloc(0),
stderr: Buffer.alloc(0),
windowsEncoding: S
} : {
...t,
stdout: "",
stderr: ""
}, K);
}
ce = false;
}
const captureOutput = (e, t, n, r, a) => {
se[r] += t.byteLength;
const o = se[r] > n;
if (v === void 0) {
appendCapturedOutput(e, t, n, a);
if (o && shouldTerminateOnOutput(i.terminateOnOutputLimit, r)) cancel("output-limit");
return;
}
const s = D;
D += t.byteLength;
const c = D > v;
if (x) {
A.push({
stream: r,
buffer: t
});
O += t.byteLength;
k[r] += t.byteLength;
const removeCapturedBytes = (e, t) => {
const n = expectDefined(A[e], "combined tail chunk");
const r = Math.min(t, n.buffer.byteLength);
if (r === n.buffer.byteLength) A.splice(e, 1);
else n.buffer = copyOwnedBuffer(n.buffer.subarray(r));
O -= r;
k[n.stream] -= r;
(n.stream === "stdout" ? m : h).truncatedBytes += r;
};
while (k[r] > n) {
const e = A.findIndex((e) => e.stream === r);
if (e < 0) break;
removeCapturedBytes(e, k[r] - n);
}
let e = O - v;
while (e > 0) {
removeCapturedBytes(0, e);
e = O - v;
}
} else {
const r = Math.max(0, v - s);
const i = Math.min(n, e.bytes + r);
appendCapturedOutput(e, t, i, a);
}
if (c && shouldTerminateOnOutput(i.terminateOnOutputLimit, "combined") || o && shouldTerminateOnOutput(i.terminateOnOutputLimit, r)) cancel("output-limit");
};
const observeOutputChunk = (e, t) => {
const n = Buffer.isBuffer(e) ? e : Buffer.from(e);
if (w || !i.onOutputChunk) return n;
try {
if (i.onOutputChunk(n, t) === false) cancel("output-limit");
} catch (e) {
N = e;
cancel("output-limit");
}
return n;
};
const onOutputError = (e, t) => {
P ??= t;
if (w || i.tolerateOutputError?.[t] === true || !shouldTerminateOnOutput(i.terminateOnOutputError, t)) return;
F = toErrorObject(e, `Command ${t} stream failed`);
Object.assign(F, { outputErrorStream: t });
cancel("signal");
};
I.stdout?.once("error", (e) => onOutputError(e, "stdout"));
I.stderr?.once("error", (e) => onOutputError(e, "stderr"));
const de = [{
stream: "stdout",
capture: m,
maxBytes: g,
mode: y
}, {
stream: "stderr",
capture: h,
maxBytes: _,
mode: b
}];
for (const { stream: e, capture: t, maxBytes: n, mode: r } of de) I[e]?.on("data", (a) => {
const o = observeOutputChunk(a, e);
appendPreservedOutputLines({
capture: t,
chunk: o,
stream: e,
preserveOutputLine: i.preserveOutputLine,
maxPreservedOutputLines: oe,
maxPendingLineBytes: ae
});
captureOutput(t, o, n, e, r);
armNoOutputTimer();
});
let q;
if (i.beforeInput) {
z.stdin?.once("error", (e) => {
if (hasErrnoCode(e, "EPIPE")) return;
q ??= toErrorObject(e, "Command input failed");
cancel("signal");
});
try {
if (z.pid === void 0 || !z.stdin) throw new Error("Child input admission has no spawned process");
const e = i.beforeInput(z.pid, z.spawnargs);
if (e !== void 0) {
if (isPromiseLike(e)) Promise.resolve(e).catch(() => void 0);
throw new TypeError("Child input admission must complete synchronously");
}
B = true;
z.stdin.end(s);
} catch (e) {
q = toErrorObject(e, "Child input admission failed");
cancel("signal");
}
}
const J = await I.finally(() => {
E = true;
clearTimers();
W?.();
}).catch((e) => {
throw failedProcess(e);
});
if (J.timedOut) w ??= "timeout";
let Y = await K.catch((e) => {
throw failedProcess(e);
});
const X = J.signal ?? T?.signal ?? z.signalCode ?? null;
if (Y === "normal" && X && !(V && i.requireProcessTreeExtinction)) Y = "uncertain";
if (q) throw failedProcess(q, Y);
if (F) throw failedProcess(F, Y);
if (N !== void 0) throw failedProcess(toErrorObject(N, "Command output observer failed"), Y);
const fe = !w && L.usesWindowsExitCodeShim && typeof z.pid === "number" && J.code === void 0 && J.cause === void 0 && !J.timedOut && !J.isCanceled && !J.isMaxBuffer && !J.isTerminated;
if (J.failed && !w && !isPlainCommandExitFailure(J) && !isPlainCommandSignalFailure(J) && !fe && !(J.exitCode === 0 && P !== void 0 && i.tolerateOutputError?.[P] === true)) {
const e = createSanitizedCommandError(J);
const t = typeof z.pid === "number" ? Y === "normal" ? "uncertain" : Y : "normal";
if (P) Object.assign(e, { outputErrorStream: P });
throw failedProcess(e, t);
}
const pe = w === "signal" || w === "output-limit";
const Z = resolveProcessExitCode({
explicitCode: J.exitCode ?? T?.code,
childExitCode: z.exitCode,
resolvedSignal: X,
usesWindowsExitCodeShim: L.usesWindowsExitCodeShim,
timedOut: w === "timeout",
noOutputTimedOut: w === "no-output-timeout",
killIssuedByTimeout: w === "timeout" || w === "no-output-timeout",
killIssuedByAbort: pe
});
w ??= X != null || J.isTerminated ? "signal" : "exit";
const me = w === "timeout" || w === "no-output-timeout" ? Z == null || Z === 0 ? 124 : Z : Z;
for (const { stream: e, capture: t } of de) flushPreservedOutputLine({
capture: t,
stream: e,
preserveOutputLine: i.preserveOutputLine,
maxPreservedOutputLines: oe,
maxPendingLineBytes: ae
});
if (x) for (const e of A) {
const t = e.stream === "stdout" ? m : h;
t.chunks.push(e.buffer);
t.bytes += e.buffer.byteLength;
}
const Q = finalizeCapturedOutput(m, y, n);
const $ = finalizeCapturedOutput(h, b, n);
const he = {
pid: z.pid,
stdoutTruncatedBytes: m.truncatedBytes || void 0,
stderrTruncatedBytes: h.truncatedBytes || void 0,
preservedStdoutLines: m.preservedLines.length > 0 ? m.preservedLines : void 0,
preservedStderrLines: h.preservedLines.length > 0 ? h.preservedLines : void 0,
code: me,
signal: X,
killed: z.killed,
killIssuedByAbort: pe || void 0,
cleanup: Y,
termination: w === "output-limit" ? "signal" : w,
noOutputTimedOut: w === "no-output-timeout",
outputLimitExceeded: w === "output-limit" || void 0,
...P ? { outputErrorStream: P } : {}
};
return r ? {
...he,
stdout: Q,
stderr: $,
windowsEncoding: S
} : {
...he,
stdout: n ? Q.toString("utf8") : decodeWindowsOutputBuffer({
buffer: Q,
windowsEncoding: S
}),
stderr: n ? $.toString("utf8") : decodeWindowsOutputBuffer({
buffer: $,
windowsEncoding: S
})
};
}
//#endregion
export { createCommandTerminationController as a, runUtf8CommandWithTimeout as i, runCommandWithTimeout as n, hasChildProcessExited as o, runUtf8CommandBuffersWithTimeout as r, releaseChildProcessOutputAfterExit as s, runCommandBuffersWithTimeout as t };