UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,419 lines (1,418 loc) • 47.2 kB
import { c as hasErrnoCode, m as collectNestedErrorCandidates, y as toErrorObject } from "./paths-0xDagtub.mjs"; import { s as sleep } from "./utils-BclMknzT.mjs"; import { E as clampPositiveTimerTimeoutMs, F as resolveTimerTimeoutMs, L as normalizeLowercaseStringOrEmpty, N as resolveOptionalIntegerOption, S as asPositiveFiniteNumber, j as resolveIntegerOption } from "./path-guards-quCEQx1i.mjs"; import { n as resolveDiagnosticProcessEnv, r as resolveEnvironmentValue, t as mergeProcessEnv } from "./process-env-Bx8i77R6.mjs"; import { n as getProcessInstanceStartTime, t as getFileLockProcessStartTime } from "./pid-alive-TveEV-hP.mjs"; import { Z as expectDefined } from "./redact-BRF0hr6G.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import "./runtime-process-manifest-BxvHhnYN.mjs"; import { t as isPromiseLike } from "./promise-like-aMoWEh5w.mjs"; import "./cli-invocation-CSfpG5sl.mjs"; import { n as markOpenClawExecEnv } from "./openclaw-exec-env-6zVPuy1n.mjs"; import { c as isChildProcessTreeAlive, d as BrokerChild, l as scheduleAdoptedChildZombieReapAfterExit, p as truncateUtf8Suffix, u as killProcessTree } from "./host-CAR9TGXT.mjs"; import { o as resolveRuntimeDependencyEntrypointUrlFromDirectory } from "./runtime-worker-url-BEfqe_m6.mjs"; import { n as getSpawnBroker, t as recordChildProcessSpawn } from "./spawn-diagnostics-BSdNA2wW.mjs"; import { n as resolveExecutableFromPathEnv, r as resolveExecutablePathCandidate, t as isRegularFile } from "./executable-path-BtaxFk1u.mjs"; import { a as getWindowsSystem32ExePath, s as assertAppContainerSpawnSupported, t as getWindowsCmdExePath } from "./windows-install-roots-CNvr-0dO.mjs"; import { createRequire } from "node:module"; import process$1 from "node:process"; import { AsyncLocalStorage } from "node:async_hooks"; import { stripVTControlCharacters } from "node:util"; import { spawnSync } from "node:child_process"; import fsSync from "node:fs"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { constants as constants$1 } from "node:os"; import { isUtf8 } from "node:buffer"; import { once } from "node:events"; import { StringDecoder } from "node:string_decoder"; import { execa } from "execa"; //#region node-runtime-env.mjs /** Keep lifecycle children on the explicitly selected runtime without changing npm config. */ function withNodeRuntimePath(e, t, n = process.platform) { const r = n === "win32" ? path.win32 : path.posix; const i = Object.keys(e).toSorted().filter((e) => n === "win32" ? e.toUpperCase() === "PATH" : e === "PATH"); const a = i[0] ?? "PATH"; const o = r.dirname(t); const s = (e[a] ? e[a].split(r.delimiter) : []).filter((e) => e !== o); const c = { ...e }; for (const e of i.length ? i : [a]) c[e] = [o, ...s].join(r.delimiter); return c; } //#endregion //#region src/process/exec-result.ts const commandCleanupUncertain = Symbol.for("openclaw.command-cleanup-uncertain"); const commandCleanupMessage = "Command cleanup could not confirm that owned work stopped"; function isCanonicalCommandProcessCleanupError(e) { try { return Object.getOwnPropertyDescriptor(e, commandCleanupUncertain)?.value === true; } catch { return false; } } /** An admitted command may still write; callers must retain its artifacts for recovery. */ var CommandProcessCleanupError = class extends Error { constructor(e) { let t = commandCleanupMessage; for (const n of collectNestedErrorCandidates(e?.cause)) { if (!isCanonicalCommandProcessCleanupError(n)) continue; try { const e = Object.getOwnPropertyDescriptor(n, "message")?.value; if (typeof e === "string" && e.trim() && e !== commandCleanupMessage) { t = e; break; } } catch {} } super(t, e); this.code = "ERR_COMMAND_PROCESS_CLEANUP_UNCERTAIN"; this.cleanup = "uncertain"; this.name = "CommandProcessCleanupError"; Object.defineProperty(this, commandCleanupUncertain, { value: true }); } }; const commandProcessCleanup = Symbol.for("openclaw.command-process-cleanup"); /** Carry the existing cleanup owner without putting a Promise in public result payloads. */ function recordCommandProcessCleanup(e, t) { return t ? Object.defineProperty(e, commandProcessCleanup, { value: t }) : e; } const commandFailureOutcome = Symbol.for("openclaw.command-process-outcome"); /** Lifecycle facts stay private; callers retain the original error and its diagnostics. */ function recordCommandProcessFailure(e, t) { const n = toErrorObject(e, "Command failed"); const r = Object.isExtensible(n) ? n : new Error(n.message, { cause: n }); return Object.defineProperty(r, commandFailureOutcome, { value: Object.freeze({ ...t }), configurable: true }); } function createSanitizedCommandError(e) { const t = typeof e.code === "string" ? e.code : void 0; const n = typeof e.exitCode === "number" ? e.exitCode : void 0; const r = typeof e.signal === "string" ? e.signal : void 0; const i = e.timedOut ? "Command timed out" : e.isMaxBuffer ? "Command output exceeded its capture limit" : e.isCanceled ? "Command was canceled" : e.isTerminated ? `Command was terminated${r ? ` by ${r}` : ""}` : n !== void 0 && n !== 0 ? `Command exited with code ${n}` : `Command failed during launch or output capture${t ? ` (${t})` : ""}`; return Object.assign(new Error(i), { ...t ? { code: t } : {}, ...n !== void 0 ? { exitCode: n } : {}, ...r ? { signal: r } : {} }); } function isPlainCommandExitFailure(e) { return e.failed && typeof e.exitCode === "number" && e.exitCode !== 0 && e.signal === void 0 && e.cause === void 0 && !e.timedOut && !e.isCanceled && !e.isMaxBuffer && !e.isTerminated; } function isPlainCommandSignalFailure(e) { return e.failed && e.exitCode === void 0 && typeof e.signal === "string" && e.cause === void 0 && !e.timedOut && !e.isCanceled && !e.isMaxBuffer && e.isTerminated === true; } function resolveProcessExitCode(e) { return e.explicitCode ?? e.childExitCode ?? (e.usesWindowsExitCodeShim && e.resolvedSignal == null && !e.timedOut && !e.noOutputTimedOut && !e.killIssuedByTimeout && !e.killIssuedByAbort ? 0 : null); } //#endregion //#region src/infra/windows-encoding.ts const WINDOWS_CODEPAGE_ENCODING_MAP = { 65001: "utf-8", 54936: "gb18030", 874: "windows-874", 936: "gbk", 950: "big5", 932: "shift_jis", 949: "euc-kr", 1250: "windows-1250", 1251: "windows-1251", 1252: "windows-1252", 1253: "windows-1253", 1254: "windows-1254", 1255: "windows-1255", 1256: "windows-1256", 1257: "windows-1257", 1258: "windows-1258" }; const WINDOWS_ENCODING_PROBE_TIMEOUT_MS = 5e3; const WINDOWS_OEM_CODEPAGE_ENCODING_MAP = { 65001: "utf-8", 874: "windows-874", 932: "shift_jis", 936: "gbk", 949: "euc-kr", 950: "big5", 1258: "windows-1258", 437: "cp437", 720: "cp720", 737: "cp737", 775: "cp775", 850: "cp850", 852: "cp852", 855: "cp855", 857: "cp857", 858: "cp858", 860: "cp860", 861: "cp861", 862: "cp862", 863: "cp863", 865: "cp865", 866: "cp866", 869: "cp869" }; const WINDOWS_OEM_ENCODING_CODEPAGE_MAP = new Map(Object.entries(WINDOWS_OEM_CODEPAGE_ENCODING_MAP).map(([e, t]) => [t, Number.parseInt(e, 10)])); let cachedWindowsConsoleEncoding; /** Extracts a Windows console code page number from localized `chcp` output. */ function parseWindowsCodePage(e) { const t = Number(e.match(/\b(\d{3,5})\b/)?.[1]); return t > 0 ? t : null; } /** Resolves and caches the current Windows console encoding for subprocess output. */ function resolveWindowsConsoleEncoding() { if (process.platform !== "win32") return null; if (cachedWindowsConsoleEncoding !== void 0) return cachedWindowsConsoleEncoding; cachedWindowsConsoleEncoding = probeWindowsEncoding(getWindowsCmdExePath, [ "/d", "/s", "/c", "chcp" ]); return cachedWindowsConsoleEncoding; } function probeWindowsEncoding(e, t) { assertAppContainerSpawnSupported(); try { const n = spawnSync(e(), t, { env: resolveDiagnosticProcessEnv(), windowsHide: true, encoding: "utf8", killSignal: "SIGKILL", stdio: [ "ignore", "pipe", "pipe" ], timeout: WINDOWS_ENCODING_PROBE_TIMEOUT_MS }); const r = parseWindowsCodePage(`${n.stdout ?? ""}\n${n.stderr ?? ""}`); return r !== null ? WINDOWS_CODEPAGE_ENCODING_MAP[r] ?? null : null; } catch { return null; } } /** Decodes one complete subprocess output buffer, preferring valid UTF-8 before legacy code pages. */ function decodeWindowsOutputBuffer(e) { return decodeWindowsBufferWithFallback({ ...e, resolveFallbackEncoding: () => e.windowsEncoding ?? resolveWindowsConsoleEncoding() }); } function decodeUtf16BomBuffer(e) { const [t, n] = e; return t === 255 && n === 254 || t === 254 && n === 255 ? new TextDecoder(t === 255 ? "utf-16le" : "utf-16be").decode(e) : void 0; } function decodeWindowsBufferWithFallback(e) { if ((e.platform ?? process.platform) !== "win32") return e.buffer.toString("utf8"); const t = decodeUtf16BomBuffer(e.buffer); if (t !== void 0) return t; const n = decodeStrictUtf8(e.buffer); if (n !== null) return n; const r = e.resolveFallbackEncoding(); if (!r || normalizeLowercaseStringOrEmpty(r) === "utf-8") return e.buffer.toString("utf8"); try { return new TextDecoder(r).decode(e.buffer); } catch { return e.buffer.toString("utf8"); } } function decodeStrictUtf8(e) { try { return new TextDecoder("utf-8", { fatal: true }).decode(e); } catch { return null; } } //#endregion //#region src/shared/owned-buffer.ts /** Retained bytes must not pin unrelated allocations in Node's shared Buffer pool. */ function encodeOwnedBuffer(e, t = "utf8") { const n = Buffer.allocUnsafeSlow(Buffer.byteLength(e, t)); n.write(e, t); return n; } /** Copy recycled producer views into storage owned only by the retained value. */ function copyOwnedBuffer(e) { const t = Buffer.allocUnsafeSlow(e.byteLength); t.set(e); return t; } //#endregion //#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-output.ts const DEFAULT_COMMAND_OUTPUT_MAX_BYTES = 16777216; const MAX_PRESERVED_PENDING_LINE_BYTES = 8192; function createCapturedOutputBuffers() { return { chunks: [], bytes: 0, truncatedBytes: 0, preservedLines: [], decoder: new StringDecoder("utf8"), pendingLine: "" }; } function resolveMaxOutputBytes(e, t) { return resolveIntegerOption(asPositiveFiniteNumber(typeof e === "number" ? e : e?.[t]), DEFAULT_COMMAND_OUTPUT_MAX_BYTES, { min: 1 }); } function resolveOutputCapture(e, t) { return (typeof e === "string" ? e : e?.[t]) ?? "tail"; } function shouldTerminateOnOutput(e, t) { return typeof e === "boolean" ? e : e?.[t] === true; } function appendCapturedOutput(e, t, n, r) { if (r === "discard") { e.truncatedBytes += Buffer.byteLength(t); return; } const i = Buffer.isBuffer(t) ? t : encodeOwnedBuffer(t); if (r === "head") { const t = Math.max(0, n - e.bytes); if (t > 0) { const n = i.subarray(0, t); e.chunks.push(n.byteLength < i.byteLength ? copyOwnedBuffer(n) : n); e.bytes += n.byteLength; } e.truncatedBytes += Math.max(0, i.byteLength - t); return; } if (i.byteLength >= n) { e.chunks = [copyOwnedBuffer(i.subarray(i.byteLength - n))]; e.truncatedBytes += e.bytes + i.byteLength - n; e.bytes = n; return; } e.chunks.push(i); e.bytes += i.byteLength; while (e.bytes > n && e.chunks.length > 0) { const t = expectDefined(e.chunks[0], "chunks entry at 0"); const r = e.bytes - n; if (t.byteLength <= r) { e.chunks.shift(); e.bytes -= t.byteLength; e.truncatedBytes += t.byteLength; } else { e.chunks[0] = copyOwnedBuffer(t.subarray(r)); e.bytes -= r; e.truncatedBytes += r; } } } function trimTruncatedUtf8Boundary(e, t, n, r) { if (n === 0 || e.length === 0 || process$1.platform === "win32" && !r) return e; if (t === "tail") { let t = 0; while (t < e.length && (expectDefined(e[t], "buffer byte") & 192) === 128) t += 1; return e.subarray(t); } for (let t = 0; t <= 3 && t <= e.length; t += 1) { const n = e.length - t; if (isUtf8(e.subarray(0, n))) return e.subarray(0, n); } return e; } function finalizeCapturedOutput(e, t, n = false) { const r = Buffer.concat(e.chunks, e.bytes); const i = trimTruncatedUtf8Boundary(r, t, e.truncatedBytes, n); e.truncatedBytes += r.byteLength - i.byteLength; return i; } function appendPreservedOutputLines(e) { const { capture: t, maxPreservedOutputLines: n, preserveOutputLine: r } = e; if (!r || t.preservedLines.length >= n) return; const i = Buffer.isBuffer(e.chunk) ? t.decoder.write(e.chunk) : e.chunk; if (!i) return; const a = (t.pendingLine + i).split(/\r?\n/); t.pendingLine = truncateUtf8Suffix(a.pop() ?? "", e.maxPendingLineBytes); for (const i of a) if (t.preservedLines.length < n && r(i, e.stream)) t.preservedLines.push(i); } function flushPreservedOutputLine(e) { const { capture: t, maxPreservedOutputLines: n, preserveOutputLine: r } = e; if (!r || n <= 0) return; const i = truncateUtf8Suffix(t.pendingLine + t.decoder.end(), e.maxPendingLineBytes); t.pendingLine = ""; if (i && t.preservedLines.length < n && r(i, e.stream)) t.preservedLines.push(i); } //#endregion //#region src/process/spawn-broker/execa-protocol.ts const decoder = new TextDecoder(); const commonEscapes = /* @__PURE__ */ new Map([ [" ", " "], ["\n", "\n"], ["\b", "\\b"], ["\f", "\\f"], ["\r", "\\r"], [" ", "\\t"] ]); function renderOutput(e) { let t = typeof e === "string" ? e : decoder.decode(e); if (t.endsWith("\n")) t = t.slice(0, t.endsWith("\r\n") ? -2 : -1); return stripVTControlCharacters(t).replace(/[\p{Separator}\p{Other}]/gu, (e) => { const t = commonEscapes.get(e); if (t !== void 0) return t; const n = e.codePointAt(0); const r = n.toString(16); return n <= 65535 ? `\\u${r.padStart(4, "0")}` : `\\U${r}`; }); } function decodeExecaMessage(e, t) { return e.messageOutputs ? [e.message, ...e.messageOutputs.map((e) => renderOutput(t[e]))].join("\n\n") : e.message; } function restoreError(e, t) { const n = new Error(decodeExecaMessage(e, t), { cause: e.cause ? restoreError(e.cause, t) : void 0 }); return Object.assign(n, { name: e.name, code: e.code }); } /** Failed reject:false results are still Errors, as they are with local execa. */ function restoreExecaResult(e) { const { error: t, ...n } = e; const r = { ...n, stdout: n.stdout, stderr: n.stderr, shortMessage: n.shortMessage, code: n.code }; if (t) { const e = restoreError(t, r); return Object.assign(e, r, { cause: e.cause }); } return { ...r, cause: void 0 }; } //#endregion //#region src/process/windows-command.ts const WINDOWS_UNSAFE_CMD_CHARS_RE = /[&|<>%\r\n]/; function resolveNpmArgvForWindows(e) { if (process$1.platform !== "win32" || e.length === 0) return null; const t = normalizeLowercaseStringOrEmpty(path.basename(expectDefined(e[0], "argv entry at 0"))).replace(/\.(cmd|exe|bat)$/, ""); const n = t === "npx" ? "npx" : t === "npm" ? "npm" : null; if (!n) return null; const r = fileURLToPath(resolveRuntimeDependencyEntrypointUrlFromDirectory(n, path.join(path.dirname(process$1.execPath), "node_modules", "npm", "bin"))); if (fsSync.existsSync(r)) return [ process$1.execPath, r, ...e.slice(1) ]; const i = e[0] ?? ""; return [normalizeLowercaseStringOrEmpty(path.extname(i)) ? i : `${i}.cmd`, ...e.slice(1)]; } function createWindowsCommandNotFoundError(e) { const t = /* @__PURE__ */ new Error(`spawn ${e} ENOENT`); t.code = "ENOENT"; t.path = e; t.syscall = `spawn ${e}`; return t; } function resolveWindowsCommandFromCwdOrPath(e) { if (e.command.includes("/") || e.command.includes("\\")) { const t = resolveExecutablePathCandidate(e.command, { cwd: e.cwd, env: e.env }); if (!t) return; if (path.extname(t)) return isRegularFile(t) ? t : void 0; return resolveExecutableFromPathEnv(path.basename(t), path.dirname(t), e.env, { includeExtensionless: false }); } const t = e.cwd && e.cwd.trim() ? e.cwd : process$1.cwd(); const n = (resolveEnvironmentValue(e.env, "PATH") ?? resolveEnvironmentValue(process$1.env, "PATH") ?? "").split(";").map((e) => e.replace(/^"(.*)"$/, "$1").trim()).filter(Boolean).map((e) => path.isAbsolute(e) ? e : path.resolve(t, e)); return resolveExecutableFromPathEnv(e.command, n.join(";"), e.env, { includeExtensionless: false }); } function resolveSupportedWindowsCommand(e) { if (process$1.platform !== "win32") return e.command; let t = resolveWindowsCommandFromCwdOrPath(e); const n = resolveWindowsCommandShim({ command: e.command, cmdCommands: [ "corepack", "pnpm", "yarn" ] }); if (!t && n !== e.command) t = resolveWindowsCommandFromCwdOrPath({ ...e, command: n }); if (!t) throw createWindowsCommandNotFoundError(e.command); const r = normalizeLowercaseStringOrEmpty(path.extname(t)); if ([ ".exe", ".com", ".cmd", ".bat" ].includes(r)) return t; throw new Error(`Unsupported Windows command extension ${JSON.stringify(r || "<none>")} for ${JSON.stringify(e.command)}; use an explicit executable or shell wrapper.`); } /** Resolve one shell-free invocation before Execa can apply Windows fallbacks. */ function resolveSafeChildProcessInvocation(e) { const t = resolveNpmArgvForWindows(e.argv) ?? e.argv; const n = e.cwd instanceof URL ? fileURLToPath(e.cwd) : e.cwd; const r = resolveSupportedWindowsCommand({ command: t[0] ?? "", cwd: n, env: e.env }); const i = isWindowsBatchCommand(r); return { command: i ? resolveSupportedWindowsCommand({ command: resolveTrustedWindowsCmdExe(), cwd: n, env: e.env }) : r, args: i ? [ "/d", "/s", "/c", buildWindowsCmdExeCommandLine(r, t.slice(1)) ] : t.slice(1), usesWindowsExitCodeShim: process$1.platform === "win32" && (i || t !== e.argv), windowsHide: true, windowsVerbatimArguments: i ? true : e.windowsVerbatimArguments }; } function isWindowsBatchCommand(e, t = process$1.platform) { if (t !== "win32") return false; const n = normalizeLowercaseStringOrEmpty(path.extname(e)); return n === ".cmd" || n === ".bat"; } function buildWindowsCmdExeCommandLine(e, t) { return `"${[e, ...t].map((e) => { if (WINDOWS_UNSAFE_CMD_CHARS_RE.test(e)) throw new Error(`Unsafe Windows cmd.exe argument detected: ${JSON.stringify(e)}. Pass an explicit shell-wrapper argv at the call site instead.`); return `"${e.replace(/\\+/g, (t, n) => { const r = e[n + t.length]; return r === "\"" || r === void 0 ? t.repeat(2) : t; }).replace(/"/g, "\"\"")}"`; }).join(" ")}"`; } function resolveTrustedWindowsCmdExe(e = process$1.platform) { if (e !== "win32") return "cmd.exe"; return getWindowsCmdExePath(); } /** * Resolve package-manager commands that Windows exposes through .cmd shims. * Explicit extensions are preserved so callers can pass already-resolved tools. */ function resolveWindowsCommandShim(e) { if (process$1.platform !== "win32") return e.command; const t = normalizeLowercaseStringOrEmpty(path.basename(e.command)); if (path.extname(t)) return e.command; if (e.cmdCommands.includes(t)) return `${e.command}.cmd`; return e.command; } //#endregion //#region src/process/exec-spawn.ts function isOutputOption(e) { return e === void 0 || e === "pipe" || e === "ignore" || e === "inherit" || typeof e === "object" && e !== null && "file" in e && typeof e.file === "string" && Object.keys(e).length === 1; } /** Unsupported native descriptors and independent-lifetime commands remain explicit local paths. */ function brokerExecaOptions(e) { if (e.ipc || e.cleanup === false || typeof e.stdin === "number") return; if (e.stdout === "inherit" || e.stderr === "inherit" || e.stdio === "inherit" || typeof e.stdout === "number" || typeof e.stderr === "number") return; if (e.stdio && typeof e.stdio !== "string" && e.stdio.some((e, t) => typeof e === "number" || t > 0 && e === "inherit")) return; if (e.cwd !== void 0 && typeof e.cwd !== "string" || e.input !== void 0 && typeof e.input !== "string" && !(e.input instanceof Uint8Array) || e.stdin !== void 0 && e.stdin !== "pipe" && e.stdin !== "ignore" && e.stdin !== "inherit" || !isOutputOption(e.stdout) || !isOutputOption(e.stderr) || e.shell !== void 0 && e.shell !== false) throw new TypeError("Unsupported spawn broker execa stream or invocation options"); if (Array.isArray(e.stdio) && (e.stdio.length !== 3 || ![ "pipe", "ignore", "inherit" ].includes(String(e.stdio[0])) || !isOutputOption(e.stdio[1]) || !isOutputOption(e.stdio[2]))) throw new TypeError("Unsupported spawn broker execa stdio"); const { cancelSignal: t, ...n } = e; return n; } function spawnBrokerCommand(e, t, n, r) { const i = e.spawnExeca(t, r); const a = i.child; const o = a.waitForClose(); const onAbort = () => { a.killed = true; i.cancel(); }; n.cancelSignal?.addEventListener("abort", onAbort, { once: true }); if (n.cancelSignal?.aborted) onAbort(); const s = i.result.then(async (e) => { if (e.timedOut) a.killed = true; await o; const t = restoreExecaResult(e); if (t instanceof Error && (n.reject !== false || t.code === "ERR_SPAWN_BROKER_UNAVAILABLE")) throw t; return t; }).finally(() => n.cancelSignal?.removeEventListener("abort", onAbort)); s.catch(() => {}); once(a, "spawn").then(() => { setImmediate(() => { for (const e of [a.stdout, a.stderr]) if (e?.readableFlowing === null) e.resume(); }); }, () => {}); const c = { nodeChildProcess: a, get pid() { return a.pid; }, get stdin() { return a.stdin; }, get stdout() { return a.stdout; }, get stderr() { return a.stderr; }, kill: (e) => a.kill(e ?? n.killSignal) }; const l = Object.assign(s, c); return Object.defineProperties(l, Object.getOwnPropertyDescriptors(c)); } /** * Post-SIGKILL teardown and orphan reaping, not cooperative grace. macOS reports * EPERM, not ESRCH, while only unreaped zombies remain, and loaded hosts have * exceeded 300 ms. Polling ends at extinction, so only surviving groups wait. */ const COMMAND_PROCESS_GROUP_EXIT_CONFIRMATION_MS = 1e4; /** The single owner for confirming that a force-killed command group is gone. */ async function waitForCommandProcessGroupExit(e, t) { const n = performance.now() + COMMAND_PROCESS_GROUP_EXIT_CONFIRMATION_MS; while (isChildProcessTreeAlive({ pid: e })) { if (!t()) return "replaced"; const r = n - performance.now(); if (r <= 0) return isChildProcessTreeAlive({ pid: e }) ? "alive" : "exited"; await sleep(Math.min(25, r)); } return "exited"; } const commandAdmissions = /* @__PURE__ */ new WeakMap(); /** Remote PID and pipes arrive together before admission or stream subscription. */ async function waitForCommandSpawn(e) { if (e.nodeChildProcess instanceof BrokerChild) try { await e.nodeChildProcess.ready(); } catch { await e; } await commandAdmissions.get(e.nodeChildProcess); } const commandProcessScope = new AsyncLocalStorage(); function resolveCommandProcessSignal(e) { const t = commandProcessScope.getStore()?.signal; return t && e ? AbortSignal.any([t, e]) : t ?? e; } /** Cleanup helpers must outlive cancellation of the commands they are settling. */ function runOutsideCommandProcessScope(e) { return commandProcessScope.exit(e); } /** Join the command owner's cleanup separately from its bounded caller result. */ function retainCommandProcessCleanup(e) { const t = commandProcessScope.getStore(); if (!t) return; const n = e.then((e) => { if (e === "uncertain") t.failure ??= { error: new CommandProcessCleanupError() }; }, (e) => { t.failure ??= { error: e }; }); t.cleanups.add(n); n.then(() => t.cleanups.delete(n)); } function retainCommandProcess(e, t, n) { let r; let i = null; let a = false; let o = false; let s = false; let c = false; const settleCustody = () => { if (!n || s || c) return; try { n.settled(); c = true; } catch (e) { s = true; throw e; } }; const l = t.nodeChildProcess; let u = l.exitCode != null || l.signalCode != null; const onExit = () => { u = true; }; l.once("exit", onExit); const d = l instanceof BrokerChild ? l.waitForClose() : void 0; const stop = () => { if (a || r === void 0 || process$1.platform === "win32") return; a = true; if (l.exitCode !== null || l.signalCode !== null) { if (!isChildProcessTreeAlive({ pid: r })) { o = true; return; } const e = getFileLockProcessStartTime(r); if (e !== null && e !== i) throw new CommandProcessCleanupError(); } killProcessTree(r, { detached: true, force: true }); scheduleAdoptedChildZombieReapAfterExit(l, true); }; const initialize = () => { r = t.pid; if (r !== void 0) try { if (process$1.platform !== "win32") i = getFileLockProcessStartTime(r); n?.spawned({ pid: r, startedAt: getProcessInstanceStartTime(r) }); if (e.signal.aborted) stop(); } catch (t) { e.failure ??= { error: t }; stop(); throw t; } }; let f; let p; if (l instanceof BrokerChild && t.pid === void 0) p = l.ready().then(initialize); else try { initialize(); p = Promise.resolve(); } catch (e) { f = { error: e }; p = Promise.reject(toErrorObject(e, "Command process custody admission failed")); } commandAdmissions.set(l, p); const m = Promise.resolve(t).then(() => void 0, () => void 0).then(async () => { await d; l.removeListener("exit", onExit); }); const h = p.catch((t) => { if (!(l instanceof BrokerChild && l.notStarted)) e.failure ??= { error: t }; }); const g = { stop, async settle() { await h; await m; if (o) { settleCustody(); return; } if (r === void 0) { if (l instanceof BrokerChild && !l.notStarted) throw new CommandProcessCleanupError(); settleCustody(); return; } if (process$1.platform === "win32") { if (!u) throw new CommandProcessCleanupError(); settleCustody(); return; } const e = r; if (await waitForCommandProcessGroupExit(e, () => { const t = getFileLockProcessStartTime(e); return t === null || t === i; }) !== "exited") throw new CommandProcessCleanupError(); settleCustody(); } }; e.children.add(g); m.then(() => { if (r === void 0 && (!(l instanceof BrokerChild) || l.notStarted) || r !== void 0 && process$1.platform !== "win32" && !isChildProcessTreeAlive({ pid: r })) try { settleCustody(); e.children.delete(g); } catch (t) { e.failure ??= { error: t }; } }); if (f) throw f.error; } function commandCreatesChildPipes(e) { if ((e.ipc ?? (e.node === true || e.ipcInput !== void 0 || e.gracefulCancel === true)) || e.input !== void 0 || e.inputFile !== void 0) return true; const t = typeof e.stdio === "string" || e.stdio === void 0 ? [ e.stdio, e.stdio, e.stdio ] : e.stdio; return [ e.stdin ?? t[0], e.stdout ?? t[1], e.stderr ?? t[2], ...t.slice(3).filter((e) => e !== void 0) ].some((e) => e !== "ignore" && e !== "inherit" && !(typeof e === "number" && e >= 0)); } function spawnCommandWithInvocation(e, t = {}) { if (process$1.platform === "win32" && commandCreatesChildPipes(t)) assertAppContainerSpawnSupported(); const n = commandProcessScope.getStore(); if (n?.signal.aborted) throw new Error("Command process scope is closed"); const { baseEnv: r, env: i, windowsVerbatimArguments: a, cancelSignal: o, executionTimeoutMs: s, inheritScopeCancellation: c = true, ...l } = t; const u = resolveCommandEnv({ argv: e, baseEnv: r, env: i }); const d = resolveSafeChildProcessInvocation({ argv: e, cwd: l.cwd, env: u, windowsVerbatimArguments: a }); const f = { ...l, cancelSignal: c ? resolveCommandProcessSignal(o) : o, ...n ? { killDescendants: true } : {}, env: u, extendEnv: false, shell: false, windowsHide: d.windowsHide, windowsVerbatimArguments: d.windowsVerbatimArguments }; const p = getSpawnBroker(); const m = p ? brokerExecaOptions(f) : void 0; if (m && s !== void 0) m.executionDeadlineMs = s + 1e3; const h = n?.custody?.reserve([d.command, ...d.args]); const g = p && m ? spawnBrokerCommand(p, [d.command, ...d.args], f, m) : execa(d.command, d.args, f); const _ = e[0] === "nice" && e[1] === "-n" && e[2] === "10" && e[3] === "git"; recordChildProcessSpawn(_ ? "git" : d.command, g.nodeChildProcess, void 0, _ ? e.slice(4) : d.args); if (n) retainCommandProcess(n, g, h); return { child: g, invocation: d }; } /** Spawn through the canonical argv, environment, and Windows safety boundary. */ function spawnCommand(e, t = {}) { return spawnCommandWithInvocation(e, t).child; } function resolveCommandEnv(e) { const t = e.baseEnv ?? process$1.env; const n = e.platform ?? process$1.platform; const r = path.basename(e.argv[0] ?? ""); const i = r === "npm" || r === "npm.cmd" || r === "npm.exe" || (r === "node" || r === "node.exe") && (e.argv[1] ?? "").includes("npm-cli.js"); const a = e.argv[0] ?? ""; const o = n === "win32" ? path.win32 : path.posix; const s = o.isAbsolute(a) && /^(?:node|node\.exe)$/iu.test(o.basename(a)) && /^(?:npm-cli\.js|npx-cli\.js|pnpm\.(?:cjs|js))$/iu.test(o.basename(e.argv[1] ?? "")); const c = mergeProcessEnv([t, e.env], n); const l = s ? withNodeRuntimePath(c, a, n) : c; if (i) { l.NPM_CONFIG_FUND ??= "false"; l.npm_config_fund ??= "false"; } return markOpenClawExecEnv(l); } //#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$1.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$1.platform === "win32" && !s) return false; if (e.processTree && typeof o === "number") { if (process$1.platform === "win32") { startWindowsTermination(o, e.processTree.mode !== "force"); return true; } const r = e.processTree.mode === "force" || e.killSignal === "SIGKILL" || e.killSignal === constants$1.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$1.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$1.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/process-deadline.ts /** Let pending child exit and output notifications run before accepting a deadline. */ function setProcessTimeout(e, t) { let n; const r = setTimeout(() => { n = setTimeout(e, 0); }, t); return { clear() { clearTimeout(r); clearTimeout(n); }, refresh() { clearTimeout(n); n = void 0; r.refresh(); } }; } //#endregion //#region src/process/exec-runner.ts async function runCommandWithTimeout(e, t) { return await runCommandWithOutputEncoding(e, t, false); } 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: l, env: u, noOutputTimeoutMs: d, killProcessTree: f, killSignal: p, killGraceMs: m } = i; const h = resolveCommandProcessSignal(i.signal); const g = typeof a === "number" ? resolveTimerTimeoutMs(a, 1) : void 0; if (i.requireProcessTreeExtinction && !f) throw new Error("Process-tree extinction requires process-tree ownership"); const _ = s !== void 0; if (c !== void 0) { if (!Number.isInteger(c) || c < 0) throw new Error("stdinFileDescriptor must be a nonnegative integer"); if (_) throw new Error("Command accepts either input or stdinFileDescriptor, not both"); } if (i.beforeInput && !_) throw new Error("Child input admission requires explicit input"); const ee = resolveTimerTimeoutMs(m, 300, 0); if (h?.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 v = createCapturedOutputBuffers(); const y = createCapturedOutputBuffers(); const te = resolveMaxOutputBytes(i.maxOutputBytes, "stdout"); const ne = resolveMaxOutputBytes(i.maxOutputBytes, "stderr"); const b = resolveOptionalIntegerOption(asPositiveFiniteNumber(i.maxCombinedOutputBytes), { min: 1 }); const x = resolveOutputCapture(i.outputCapture, "stdout"); const S = resolveOutputCapture(i.outputCapture, "stderr"); if (b !== void 0 && x !== S) throw new Error("maxCombinedOutputBytes requires matching stdout and stderr capture modes"); const re = b !== void 0 && x === "tail" && S === "tail"; const ie = Math.min(Math.max(te, ne), MAX_PRESERVED_PENDING_LINE_BYTES); const C = Math.max(0, Math.floor(i.maxPreservedOutputLines ?? 16)); const w = n ? null : resolveWindowsConsoleEncoding(); const T = new AbortController(); let E; let D; let O = false; let k = 0; let A = 0; const ae = { stdout: 0, stderr: 0 }; const j = { stdout: 0, stderr: 0 }; const M = []; let N; let P; let F; let I; let L; const { child: R, invocation: oe } = spawnCommandWithInvocation(e, { buffer: false, cancelSignal: T.signal, inheritScopeCancellation: false, cwd: o, detached: Boolean(f && process$1.platform !== "win32"), encoding: "buffer", executionTimeoutMs: g, baseEnv: l, env: u, forceKillAfterDelay: ee, killSignal: p, ..._ && !i.beforeInput ? { input: s } : {}, reject: false, stdio: [ i.stdinFileDescriptor ?? (_ ? "pipe" : "inherit"), "pipe", "pipe" ], stripFinalNewline: false, windowsVerbatimArguments: i.windowsVerbatimArguments }); const z = R.pid === void 0 ? waitForCommandSpawn(R) : void 0; let se = z !== void 0; const ce = createDeferredCore(); const B = R.nodeChildProcess; let le = i.beforeInput ? false : void 0; const failedProcess = (e, t = "uncertain") => { const n = recordCommandProcessFailure(e, { pid: B.pid, code: D?.code ?? B.exitCode ?? null, cleanup: t, inputReleased: le, termination: E === "output-limit" ? "signal" : E ?? (B.signalCode ? "signal" : "exit") }); return Object.assign(n, { cleanup: t }); }; const V = Boolean(f && process$1.platform !== "win32"); const H = clampPositiveTimerTimeoutMs(d); const U = V && (g !== void 0 || H !== void 0); let W; const G = createCommandTerminationController({ child: B, spawned: z, cancelController: T, baseEnv: l, env: u, processTree: f ? { mode: "graceful" } : void 0, isChildExited: () => D !== void 0, isCommandSettled: () => O, killGraceMs: ee, killSignal: p }); const K = (async () => { await R.then(() => void 0, () => void 0); O = true; await z?.catch(() => {}); return await G.settle(); })(); retainCommandProcessCleanup(K); K.catch(() => {}); B.once("exit", (e, t) => { D = { code: e, signal: t }; if (!U || e !== 0 || E) W = releaseChildProcessOutputAfterExit(B); if (f && !E && (e !== 0 || i.requireProcessTreeExtinction)) G.terminate(); }); const cancel = (e, t = false) => { if (E || O || D && e !== "output-limit" && (!V || D.code !== 0)) return; if ((e === "timeout" || e === "no-output-timeout") && (D || hasChildProcessExited(B))) { if (!U || (D?.code ?? B.exitCode) !== 0) return; if ((!B.stdout || B.stdout.readableEnded) && (!B.stderr || B.stderr.readableEnded)) return; if (!t) { P ??= setProcessTimeout(() => cancel(e, true), 100); return; } } P?.clear(); E = e; if (se) ce.resolve(e); if (D) W ??= releaseChildProcessOutputAfterExit(B); if (!G.terminate()) T.abort(); }; const armNoOutputTimer = () => { if (H === void 0 || O || E || D && !V) return; if (N) N.refresh(); else N = setProcessTimeout(() => cancel("no-output-timeout"), H); }; const ue = g === void 0 ? void 0 : setProcessTimeout(() => cancel("timeout"), g); const onAbort = () => cancel("signal"); h?.addEventListener("abort", onAbort, { once: true }); armNoOutputTimer(); const clearTimers = () => { ue?.clear(); N?.clear(); P?.clear(); N = void 0; h?.removeEventListener("abort", onAbort); }; if (z) { let e; try { e = await Promise.race([z.then(() => void 0), ce.promise]); } catch (e) { clearTimers(); throw failedProcess(e, B instanceof BrokerChild && B.notStarted ? "normal" : "uncertain"); } if (e) { clearTimers(); K.finally(() => W?.()).catch(() => {}); const t = { pid: B.pid, code: e === "timeout" || e === "no-output-timeout" ? 124 : null, signal: null, killed: B.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: w } : { ...t, stdout: "", stderr: "" }, K); } se = false; } const captureOutput = (e, t, n, r, a) => { ae[r] += t.byteLength; const o = ae[r] > n; if (b === void 0) { appendCapturedOutput(e, t, n, a); if (o && shouldTerminateOnOutput(i.terminateOnOutputLimit, r)) cancel("output-limit"); return; } const s = k; k += t.byteLength; const c = k > b; if (re) { M.push({ stream: r, buffer: t }); A += t.byteLength; j[r] += t.byteLength; const removeCapturedBytes = (e, t) => { const n = expectDefined(M[e], "combined tail chunk"); const r = Math.min(t, n.buffer.byteLength); if (r === n.buffer.byteLength) M.splice(e, 1); else n.buffer = copyOwnedBuffer(n.buffer.subarray(r)); A -= r; j[n.stream] -= r; (n.stream === "stdout" ? v : y).truncatedBytes += r; }; while (j[r] > n) { const e = M.findIndex((e) => e.stream === r); if (e < 0) break; removeCapturedBytes(e, j[r] - n); } let e = A - b; while (e > 0) { removeCapturedBytes(0, e); e = A - b; } } else { const r = Math.max(0, b - 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 (E || !i.onOutputChunk) return n; try { if (i.onOutputChunk(n, t) === false) cancel("output-limit"); } catch (e) { F = e; cancel("output-limit"); } return n; }; const onOutputError = (e, t) => { I ??= t; if (E || i.tolerateOutputError?.[t] === true || !shouldTerminateOnOutput(i.terminateOnOutputError, t)) return; L = toErrorObject(e, `Command ${t} stream failed`); Object.assign(L, { outputErrorStream: t }); cancel("signal"); }; R.stdout?.once("error", (e) => onOutputError(e, "stdout")); R.stderr?.once("error", (e) => onOutputError(e, "stderr")); const de = [{ stream: "stdout", capture: v, maxBytes: te, mode: x }, { stream: "stderr", capture: y, maxBytes: ne, mode: S }]; for (const { stream: e, capture: t, maxBytes: n, mode: r } of de) R[e]?.on("data", (a) => { const o = observeOutputChunk(a, e); appendPreservedOutputLines({ capture: t, chunk: o, stream: e, preserveOutputLine: i.preserveOutputLine, maxPreservedOutputLines: C, maxPendingLineBytes: ie }); captureOutput(t, o, n, e, r); armNoOutputTimer(); }); let q; if (i.beforeInput) { B.stdin?.once("error", (e) => { if (hasErrnoCode(e, "EPIPE")) return; q ??= toErrorObject(e, "Command input failed"); cancel("signal"); }); try { if (B.pid === void 0 || !B.stdin) throw new Error("Child input admission has no spawned process"); const e = i.beforeInput(B.pid, B.spawnargs); if (e !== void 0) { if (isPromiseLike(e)) Promise.resolve(e).catch(() => void 0); throw new TypeError("Child input admission must complete synchronously"); } le = true; B.stdin.end(s); } catch (e) { q = toErrorObject(e, "Child input admission failed"); cancel("signal"); } } const J = await R.finally(() => { O = true; clearTimers(); W?.(); }).catch((e) => { throw failedProcess(e); }); if (J.timedOut) E ??= "timeout"; let Y = await K.catch((e) => { throw failedProcess(e); }); const X = J.signal ?? D?.signal ?? B.signalCode ?? null; if (Y === "normal" && X && !(V && i.requireProcessTreeExtinction)) Y = "uncertain"; if (q) throw failedProcess(q, Y); if (L) throw failedProcess(L, Y); if (F !== void 0) throw failedProcess(toErrorObject(F, "Command output observer failed"), Y); const fe = !E && oe.usesWindowsExitCodeShim && typeof B.pid === "number" && J.code === void 0 && J.cause === void 0 && !J.timedOut && !J.isCanceled && !J.isMaxBuffer && !J.isTerminated; if (J.failed && !E && !isPlainCommandExitFailure(J) && !isPlainCommandSignalFailure(J) && !fe && !(J.exitCode === 0 && I !== void 0 && i.tolerateOutputError?.[I] === true)) { const e = createSanitizedCommandError(J); const t = typeof B.pid === "number" ? Y === "normal" ? "uncertain" : Y : "normal"; if (I) Object.assign(e, { outputErrorStream: I }); throw failedProcess(e, t); } const pe = E === "signal" || E === "output-limit"; const Z = resolveProcessExitCode({ explicitCode: J.exitCode ?? D?.code, childExitCode: B.exitCode, resolvedSignal: X, usesWindowsExitCodeShim: oe.usesWindowsExitCodeShim, timedOut: E === "timeout", noOutputTimedOut: E === "no-output-timeout", killIssuedByTimeout: E === "timeout" || E === "no-output-timeout", killIssuedByAbort: pe }); E ??= X != null || J.isTerminated ? "signal" : "exit"; const me = E === "timeout" || E === "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: C, maxPendingLineBytes: ie }); if (re) for (const e of M) { const t = e.stream === "stdout" ? v : y; t.chunks.push(e.buffer); t.bytes += e.buffer.byteLength; } const Q = finalizeCapturedOutput(v, x, n); const $ = finalizeCapturedOutput(y, S, n); const he = { pid: B.pid, stdoutTruncatedBytes: v.truncatedBytes || void 0, stderrTruncatedBytes: y.truncatedBytes || void 0, preservedStdoutLines: v.preservedLines.length > 0 ? v.preservedLines : void 0, preservedStderrLines: y.preservedLines.length > 0 ? y.preservedLines : void 0, code: me, signal: X, killed: B.killed, killIssuedByAbort: pe || void 0, cleanup: Y, termination: E === "output-limit" ? "signal" : E, noOutputTimedOut: E === "no-output-timeout", outputLimitExceeded: E === "output-limit" || void 0, ...I ? { outputErrorStream: I } : {} }; return r ? { ...he, stdout: Q, stderr: $, windowsEncoding: w } : { ...he, stdout: n ? Q.toString("utf8") : decodeWindowsOutputBuffer({ buffer: Q, windowsEncoding: w }), stderr: n ? $.toString("utf8") : decodeWindowsOutputBuffer({ buffer: $, windowsEncoding: w }) }; } //#endregion export { runCommandWithTimeout as t };