import { spawn } from 'node:child_process'; import { killTree } from '../tools/shared/killTree.js'; import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../tools/types.js'; import { appendFileSync, mkdtempSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; /** * stdout/stderr 即时缓冲上限(各自),同 `bash.ts`/`grep.ts` 的 `MAX_CAPTURE_CHARS` 取值 * 逻辑:最终展示阈值的 2 倍,防一个话痨脚本(workflow `wf.exec.file()`/`sh()` 或 * agent-browser 安装过程)把裸字符串拼接撑爆宿主进程堆内存——这不是限制脚本能做什么, * 是防止它把整个 agent 进程一起拖垮(OOM 崩溃比截断严重得多)。 */ const MAX_STREAM_BUFFER_CHARS = DEFAULT_MAX_RESULT_SIZE_CHARS * 2; export interface BoundedProcessResult { stdout: string; stderr: string; exitCode: number; timedOut: boolean; stdoutTruncated?: boolean; stderrTruncated?: boolean; stdoutPath?: string; stderrPath?: string; } export interface BoundedProcessOptions { cwd?: string; env?: NodeJS.ProcessEnv; input?: string; timeoutMs?: number; signal?: AbortSignal; /** Display-only callers may accept a prefix; machine-result callers fail on overflow. */ allowTruncatedOutput?: boolean; /** Display-only capture: keep a bounded prefix without spooling the rest to disk. */ prefixOnly?: boolean; } /** Trusted local process, bounded cancellation and inherited-pipe cleanup. */ export async function runBoundedProcess(executable: string, commandArgs: string[], options: BoundedProcessOptions = {}): Promise { if (options.timeoutMs !== undefined && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 2147483647)) throw new Error('Invalid process timeoutMs'); // 已提前中断走同一个友好错误形状(下面 finish(aborted) 分支同款),不用 throwIfAborted() // 裸抛 —— 那会把 AbortSignal 的原生英文 reason(如 "The operation was aborted")直接 // 甩给调用方,调用方(如 browserDaemon.ts::ensureDaemon)按 name:'AbortError' 识别中断, // 两条路径(提前中断 / 执行中中断)必须产出同一种可识别的错误对象。 if (options.signal?.aborted) throw Object.assign(new Error('进程执行已中断'), { name: 'AbortError' }); return new Promise((resolvePromise, reject) => { const child = spawn(executable, commandArgs, { cwd: options.cwd, env: { ...process.env, ...options.env }, stdio: 'pipe', detached: process.platform !== 'win32', windowsHide: true, }); let stdout = ''; let stderr = ''; let outputDir: string | undefined; const files: Partial> = {}; const clipped = new Set<'stdout' | 'stderr'>(); const capture = (stream: 'stdout' | 'stderr', previous: string, value: string): string => { if (options.prefixOnly) { if (previous.length + value.length > MAX_STREAM_BUFFER_CHARS) clipped.add(stream); return previous + value.slice(0, MAX_STREAM_BUFFER_CHARS - previous.length); } try { if (files[stream]) appendFileSync(files[stream]!, value); else if (previous.length + value.length > MAX_STREAM_BUFFER_CHARS) { outputDir ??= mkdtempSync(join(tmpdir(), 'minimal-process-')); files[stream] = join(outputDir, `${stream}.txt`); writeFileSync(files[stream]!, previous + value, { mode: 0o600 }); } } catch (error) { finish(null, error as Error); } return (previous + value).slice(0, MAX_STREAM_BUFFER_CHARS); }; child.stdout?.setEncoding('utf8').on('data', (value) => { stdout = capture('stdout', stdout, value); }); child.stderr?.setEncoding('utf8').on('data', (value) => { stderr = capture('stderr', stderr, value); }); let timer: NodeJS.Timeout | undefined; let cleanupTimer: NodeJS.Timeout | undefined; let stopped = false; let settled = false; let timedOut = false; let aborted = false; const finish = (code: number | null, error?: Error) => { if (settled) return; settled = true; clearTimeout(timer); clearTimeout(cleanupTimer); options.signal?.removeEventListener('abort', abort); if (error) killTree(child, 'SIGKILL'); child.stdin?.destroy(); child.stdout?.destroy(); child.stderr?.destroy(); const overflow = { stdoutTruncated: Boolean(files.stdout) || clipped.has('stdout'), stderrTruncated: Boolean(files.stderr) || clipped.has('stderr'), stdoutPath: files.stdout, stderrPath: files.stderr, }; if (aborted) reject( Object.assign(new Error('进程执行已中断'), { name: 'AbortError', stdout, stderr, ...overflow, }), ); else if (error) reject(error); else if (!timedOut && (files.stdout || files.stderr) && !options.allowTruncatedOutput) reject(Object.assign(new Error(`Process output exceeds inline limit; complete output: ${files.stdout ?? ''} ${files.stderr ?? ''}. Read the output file; do not parse the truncated prefix.`), { code: 'PROCESS_OUTPUT_TRUNCATED', stdout, stderr, exitCode: code, ...overflow })); else resolvePromise({ stdout, stderr: timedOut ? `${stderr}\n进程超过时限 ${options.timeoutMs}ms,已终止` : stderr, exitCode: timedOut ? 124 : (code ?? 1), timedOut, ...overflow, }); }; const stop = () => { if (settled || stopped) return; stopped = true; killTree(child); // A stubborn process or inherited pipe must not keep the workflow alive. clearTimeout(cleanupTimer); cleanupTimer = setTimeout(() => { killTree(child, 'SIGKILL'); finish(null); }, 500); }; const abort = () => { aborted = true; stop(); }; child.on('error', (error) => finish(null, error)); child.on('close', (code) => { if (stopped) killTree(child, 'SIGKILL'); finish(code); }); child.on('exit', (code) => { if (settled || stopped) return; cleanupTimer = setTimeout(() => { killTree(child, 'SIGKILL'); finish(code); }, 500); }); child.stdin?.on('error', (error: NodeJS.ErrnoException) => { if (error.code !== 'EPIPE') finish(null, error); }); child.stdin?.end(options.input); options.signal?.addEventListener('abort', abort, { once: true }); if (options.signal?.aborted) abort(); if (options.timeoutMs !== undefined) { timer = setTimeout(() => { timedOut = true; stop(); }, options.timeoutMs); timer.unref(); } }); }