UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

246 lines (245 loc) • 8.57 kB
import { I as resolveOptionalIntegerOption, R as resolveTimerTimeoutMs, d as asPositiveFiniteNumber } from "./number-coercion-D6u-4YD8.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { t as BrokerChild } from "./child-CJvs_oct.mjs"; import { i as hasCommandProcessCleanupError, l as readCommandProcessFailure, r as createSanitizedCommandError, t as CommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs"; import { r as decodeWindowsOutputBuffer } from "./windows-encoding-BGmFeZe1.mjs"; import { t as copyOwnedBuffer } from "./owned-buffer-C1_N0F1K.mjs"; import { n as runCommandWithTimeout, o as hasChildProcessExited, s as releaseChildProcessOutputAfterExit } from "./exec-runner-Br73vG-X.mjs"; import { s as resolveMaxOutputBytes } from "./exec-output-BYE24ROR.mjs"; import { a as retainCommandProcessCleanup, c as spawnCommand, d as waitForCommandSpawn, i as resolveCommandProcessSignal, n as COMMAND_PROCESS_TREE_KILL_GRACE_MS } from "./exec-spawn-DMKoejF-.mjs"; import { t as setProcessTimeout } from "./process-deadline-CTzOjEFJ.mjs"; //#region src/process/exec.ts const DEFAULT_EXEC_MAX_BUFFER_BYTES = 1048576; function decodeExecOutput(e) { return decodeWindowsOutputBuffer({ buffer: Buffer.from(e.buffer, e.byteOffset, e.byteLength) }); } async function runExec(e, t, n = 1e4) { const r = typeof n === "number" ? { timeoutMs: n } : n; const i = typeof r.timeoutMs === "number" ? resolveTimerTimeoutMs(r.timeoutMs, 1) : void 0; const a = r.maxBuffer ?? DEFAULT_EXEC_MAX_BUFFER_BYTES; if (r.input !== void 0 && r.stdinFileDescriptor !== void 0) throw new Error("runExec accepts either input or stdinFileDescriptor, not both"); let o = true; let s = true; let c = false; let releaseCancellation = () => {}; try { const n = spawnCommand([e, ...t], { baseEnv: r.baseEnv, cancelSignal: r.signal, cwd: r.cwd, encoding: "buffer", executionTimeoutMs: i, env: r.env, forceKillAfterDelay: 300, ...r.input !== void 0 ? { input: r.input } : {}, maxBuffer: a, reject: true, ...r.stdinFileDescriptor === void 0 ? { stdin: r.input === void 0 ? "ignore" : void 0 } : { stdin: r.stdinFileDescriptor }, stripFinalNewline: false }); const l = n.nodeChildProcess instanceof BrokerChild && n.pid === void 0 ? createDeferredCore() : void 0; const u = resolveCommandProcessSignal(r.signal); let d = true; let f; const stopCommand = (e) => { if (!d) return; releaseCancellation(); if (e === "timeout") { if (hasChildProcessExited(n.nodeChildProcess)) return; c = true; n.kill(); } if (!s || !l) return; o = false; const t = { failed: true, timedOut: e === "timeout", isCanceled: e === "signal", isMaxBuffer: false, isTerminated: false }; const r = createSanitizedCommandError(t); l.reject(Object.assign(r, t, { shortMessage: r.message, stdout: "", stderr: "", cleanup: "uncertain" })); }; const onAbort = () => stopCommand("signal"); releaseCancellation = () => { d = false; f?.clear(); u?.removeEventListener("abort", onAbort); }; u?.addEventListener("abort", onAbort, { once: true }); if (i !== void 0) f = setProcessTimeout(() => stopCommand("timeout"), i); if (u?.aborted) onAbort(); const p = (async () => { if (n.pid === void 0) await waitForCommandSpawn(n); s = false; const e = releaseChildProcessOutputAfterExit(n.nodeChildProcess); let t = o ? r.onOutputChunk : void 0; const observe = (e, n) => { try { t?.(e, n); } catch { t = void 0; } }; const onStdout = (e) => observe(e, "stdout"); const onStderr = (e) => observe(e, "stderr"); if (t) { n.nodeChildProcess.stdout?.on("data", onStdout); n.nodeChildProcess.stderr?.on("data", onStderr); } const i = await n.finally(() => { releaseCancellation(); e(); n.nodeChildProcess.stdout?.off("data", onStdout); n.nodeChildProcess.stderr?.off("data", onStderr); }); if (c) { const e = createSanitizedCommandError({ timedOut: true }); throw Object.assign(e, i, { failed: true, timedOut: true, shortMessage: e.message }); } const { stdout: a, stderr: l } = i; const u = decodeExecOutput(a); const d = decodeExecOutput(l); if (o && r.logOutput !== false) { const [{ shouldLogVerbose: e }, { logDebug: t, logError: n }] = await Promise.all([import("./globals-BfPgg0MS.mjs"), import("./logger-D98Tal9X.mjs")]); if (e()) { if (u.trim()) t(u.trim()); if (d.trim()) n(d.trim()); } } return { stdout: u, stderr: d }; })(); retainCommandProcessCleanup(p.then(() => void 0, () => void 0)); return await (l ? Promise.race([p, l.promise]) : p); } catch (t) { releaseCancellation(); if (t && typeof t === "object") { const e = t; if (c || e.timedOut) { const e = createSanitizedCommandError({ timedOut: true }).message; if (t instanceof Error) t.stack = t.stack?.replace(t.message, e); Object.assign(t, { failed: true, timedOut: true, message: e, shortMessage: e }); } if (e.code === void 0 && typeof e.exitCode === "number") e.code = e.exitCode; if (e.stdout instanceof Uint8Array) e.stdout = decodeExecOutput(e.stdout); if (e.stderr instanceof Uint8Array) e.stderr = decodeExecOutput(e.stderr); } if (r.logOutput !== false) { const t = await Promise.all([import("./globals-BfPgg0MS.mjs"), import("./logger-D98Tal9X.mjs")]).catch(() => void 0); if (t) { const [{ danger: n, shouldLogVerbose: r }, { logError: i }] = t; if (r()) i(n(`Command failed: ${e}`)); } } throw t; } finally { o = false; releaseCancellation(); } } /** Run a one-shot command with raw, independently capped stdout and stderr buffers. */ async function runCommandBuffered(e, t = {}) { if (t.signal?.aborted) return { stdout: Buffer.alloc(0), stderr: Buffer.alloc(0), code: null, signal: null, killed: false, termination: "signal", ...t.signal.reason instanceof Error ? { error: t.signal.reason } : {} }; const n = { stdout: [], stderr: [] }; const r = { stdout: 0, stderr: 0 }; const i = resolveOptionalIntegerOption(asPositiveFiniteNumber(t.maxCombinedOutputBytes), { min: 1 }); let a; const appendChunk = (e, o) => { if (t.discardOutput?.[o]) return true; const s = resolveMaxOutputBytes(t.maxOutputBytes, o); const c = r.stdout + r.stderr; const l = i === void 0 ? Number.POSITIVE_INFINITY : Math.max(0, i - c); const u = Math.max(0, Math.min(s - r[o], l)); if (u > 0) { const t = e.byteLength > u ? copyOwnedBuffer(e.subarray(0, u)) : e; n[o].push(t); r[o] += t.byteLength; } if (e.byteLength > u) { a ??= o; return false; } return true; }; const capturedOutput = (e) => Buffer.concat(n[e], r[e]); try { const n = await runCommandWithTimeout(e, { baseEnv: t.baseEnv, cwd: t.cwd, env: t.env, input: t.input, killProcessTree: t.killProcessTree ?? true, killGraceMs: t.killGraceMs, onOutputChunk: appendChunk, outputCapture: "discard", signal: t.signal, timeoutMs: t.timeoutMs, noOutputTimeoutMs: t.noOutputTimeoutMs, tolerateOutputError: { stdout: t.discardOutput?.stdout || t.tolerateOutputError?.stdout, stderr: t.discardOutput?.stderr || t.tolerateOutputError?.stderr }, terminateOnOutputError: t.terminateOnOutputError }); const r = n.outputLimitExceeded ? "output-limit" : n.termination; return { stdout: capturedOutput("stdout"), stderr: capturedOutput("stderr"), code: r === "exit" ? n.code : null, signal: n.signal, killed: n.killed, termination: r, ...a ? { outputLimitStream: a } : {}, ...n.outputErrorStream ? { errorStream: n.outputErrorStream } : {}, ...n.cleanup === "uncertain" ? { error: new CommandProcessCleanupError() } : {} }; } catch (e) { const t = e instanceof Error ? e : /* @__PURE__ */ new Error("Command execution failed"); const n = t; const r = n.outputErrorStream === "stdout" || n.outputErrorStream === "stderr" ? n.outputErrorStream : void 0; return { stdout: capturedOutput("stdout"), stderr: capturedOutput("stderr"), code: typeof n.exitCode === "number" ? n.exitCode : null, signal: null, killed: false, termination: "error", ...r ? { errorStream: r } : {}, error: readCommandProcessFailure(t)?.cleanup === "uncertain" && !hasCommandProcessCleanupError(t) ? new CommandProcessCleanupError({ cause: t }) : t }; } } //#endregion export { runExec as n, runCommandBuffered as t };