1- import { spawn } from 'child_process' ;
2- import { StringDecoder } from 'string_decoder' ;
31import { GlobalLoggerService } from '../../../Logger' ;
42import { createTextContent , MCPToolResult } from '../../Core' ;
5- import { getChildProcessEnv , getCurrentShell , killProcessTree , MAX_OUTPUT_BYTES } from './process' ;
3+ import {
4+ appendOutputBuffer ,
5+ createOutputBuffer ,
6+ drainOutputBuffer ,
7+ formatProcessExit ,
8+ getCurrentShell ,
9+ killProcessTree ,
10+ MAX_OUTPUT_BYTES ,
11+ ProcessShell ,
12+ spawnRuntimeProcess ,
13+ } from './process' ;
614
715const logger = GlobalLoggerService . getLogger ( 'Tools/Process/runtime/foreground' ) ;
816
@@ -15,39 +23,11 @@ interface RunOptions {
1523 timeout : number ;
1624 label : string ;
1725 /** 传字符串走 shell(解析 &&、管道、重定向等);传 false 直接 exec,args 不经 shell。 */
18- shell : string | false ;
26+ shell : ProcessShell ;
1927 /** 写入子进程 stdin 的字符串;写完即 end,子进程读到 EOF。未传则 stdin 关闭。 */
2028 stdin ?: string ;
2129}
2230
23- interface OutputBuffer {
24- chunks : Buffer [ ] ;
25- bytes : number ;
26- overflow : boolean ;
27- }
28-
29- function appendChunk ( buf : OutputBuffer , chunk : Buffer ) : void {
30- if ( buf . overflow ) return ;
31- const remain = MAX_OUTPUT_BYTES - buf . bytes ;
32- if ( chunk . length >= remain ) {
33- if ( remain > 0 ) buf . chunks . push ( chunk . subarray ( 0 , remain ) ) ;
34- buf . bytes = MAX_OUTPUT_BYTES ;
35- buf . overflow = true ;
36- return ;
37- }
38- buf . chunks . push ( chunk ) ;
39- buf . bytes += chunk . length ;
40- }
41-
42- // 累积阶段保留 Buffer 引用,避免反复 ConsString 拼接 / flatten 带来的 GC 压力;
43- // finish 时一次性 concat 后用 StringDecoder 解码全 buffer,多字节边界由 decoder 内部处理,
44- // 字节截断尾部不完整字符通过 decoder.end() 输出 replacement。
45- function decodeBuffer ( buf : OutputBuffer ) : string {
46- const merged = Buffer . concat ( buf . chunks , buf . bytes ) ;
47- const decoder = new StringDecoder ( 'utf8' ) ;
48- return decoder . write ( merged ) + decoder . end ( ) ;
49- }
50-
5131/**
5232 * 子进程通用执行器。stdout/stderr 用 Buffer 累积,finish 时一次性解码以正确处理多字节边界;
5333 * 超时、输出溢出、非 0 退出码、spawn error 都会以 isError=true 返回。
@@ -56,34 +36,21 @@ async function runProcess(file: string, args: string[], opts: RunOptions): Promi
5636 const { cwd, timeout, label, shell, stdin } = opts ;
5737
5838 return new Promise < MCPToolResult > ( ( resolve ) => {
59- const outBuf : OutputBuffer = { chunks : [ ] , bytes : 0 , overflow : false } ;
60- const errBuf : OutputBuffer = { chunks : [ ] , bytes : 0 , overflow : false } ;
39+ const outBuf = createOutputBuffer ( ) ;
40+ const errBuf = createOutputBuffer ( ) ;
6141 let timedOut = false ;
6242 let exited = false ;
6343 let settled = false ;
6444
6545 // detached: !win32 —— 让子进程成为新进程组组长,killTree 才能 kill -pgid 杀到孙子进程。
6646 // windowsHide: true —— Windows 下不弹出控制台窗口,静默执行。
67- const proc = spawn ( file , args , {
68- shell,
69- cwd,
70- env : getChildProcessEnv ( ) ,
71- stdio : [ stdin !== undefined ? 'pipe' : 'ignore' , 'pipe' , 'pipe' ] ,
72- detached : process . platform !== 'win32' ,
73- windowsHide : true ,
74- } ) ;
75-
76- if ( stdin !== undefined && proc . stdin ) {
77- // 子进程不读 stdin 时 write 会触发 EPIPE,吞掉避免 unhandledRejection。
78- proc . stdin . on ( 'error' , ( ) => { /* ignore EPIPE */ } ) ;
79- // end() 一次写完并关闭 fd,子进程读到 EOF;否则脚本可能一直等待更多输入。
80- proc . stdin . end ( stdin , 'utf8' ) ;
81- }
47+ // stdin 由 spawnRuntimeProcess 一次写完并关闭 fd;未传 stdin 时直接关闭输入端。
48+ const proc = spawnRuntimeProcess ( file , args , { cwd, shell, stdin } ) ;
8249
8350 const kill = ( ) => killProcessTree ( proc , ( ) => exited ) ;
8451
85- proc . stdout ?. on ( 'data' , ( chunk : Buffer ) => appendChunk ( outBuf , chunk ) ) ;
86- proc . stderr ?. on ( 'data' , ( chunk : Buffer ) => appendChunk ( errBuf , chunk ) ) ;
52+ proc . stdout ?. on ( 'data' , ( chunk : Buffer ) => appendOutputBuffer ( outBuf , chunk ) ) ;
53+ proc . stderr ?. on ( 'data' , ( chunk : Buffer ) => appendOutputBuffer ( errBuf , chunk ) ) ;
8754
8855 let exitCode : number | null = null ;
8956 let exitSignal : NodeJS . Signals | null = null ;
@@ -98,22 +65,24 @@ async function runProcess(file: string, args: string[], opts: RunOptions): Promi
9865 try { proc . stderr ?. destroy ( ) ; } catch { /* ignore */ }
9966
10067 const parts = [ ] ;
101- const out = decodeBuffer ( outBuf ) . trim ( ) ;
102- const err = decodeBuffer ( errBuf ) . trim ( ) ;
68+ const outDrain = drainOutputBuffer ( outBuf , true ) ;
69+ const errDrain = drainOutputBuffer ( errBuf , true ) ;
70+ const out = outDrain . text . trim ( ) ;
71+ const err = errDrain . text . trim ( ) ;
10372 if ( out ) parts . push ( createTextContent ( out ) ) ;
10473 if ( err ) parts . push ( createTextContent ( `stderr:\n${ err } ` ) ) ;
10574
106- const outOverflow = outBuf . overflow ;
107- const errOverflow = errBuf . overflow ;
75+ const outOverflow = outDrain . overflowed ;
76+ const errOverflow = errDrain . overflowed ;
10877
10978 const isError = timedOut || outOverflow || errOverflow || forcedDrainTimeout ||
11079 ( exitCode !== null && exitCode !== 0 ) ||
11180 exitSignal !== null ;
11281 if ( timedOut ) parts . push ( createTextContent ( `Command timed out after ${ timeout } ms` ) ) ;
11382 else if ( outOverflow || errOverflow ) parts . push ( createTextContent ( `Output exceeded ${ MAX_OUTPUT_BYTES } bytes; remaining output discarded` ) ) ;
11483 else if ( forcedDrainTimeout ) parts . push ( createTextContent ( `Output streams did not close within ${ IO_DRAIN_TIMEOUT_MS } ms; force-finished` ) ) ;
115- else if ( exitCode !== null && exitCode !== 0 ) parts . push ( createTextContent ( `Process exited with code ${ exitCode } ` ) ) ;
116- else if ( exitSignal !== null ) parts . push ( createTextContent ( `Process terminated by signal ${ exitSignal } ` ) ) ;
84+ else if ( exitCode !== null && exitCode !== 0 ) parts . push ( createTextContent ( formatProcessExit ( exitCode , null ) ) ) ;
85+ else if ( exitSignal !== null ) parts . push ( createTextContent ( formatProcessExit ( exitCode , exitSignal ) ) ) ;
11786
11887 resolve ( { content : parts , isError : isError || undefined } ) ;
11988 } ;
0 commit comments