Skip to content

Commit 68fdd48

Browse files
author
linyuan.yang
committed
整理 shell 代码
1 parent d9e9931 commit 68fdd48

3 files changed

Lines changed: 130 additions & 128 deletions

File tree

‎packages/scorpio.ai/src/Tools/Process/runtime/foreground.ts‎

Lines changed: 26 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,16 @@
1-
import { spawn } from 'child_process';
2-
import { StringDecoder } from 'string_decoder';
31
import { GlobalLoggerService } from '../../../Logger';
42
import { 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

715
const 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
};

‎packages/scorpio.ai/src/Tools/Process/runtime/process.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import path from 'path';
33
import { execSync, spawn, type ChildProcess } from 'child_process';
44
import os from 'os';
55
import { setTimeout as sleep } from 'timers/promises';
6+
import { StringDecoder } from 'string_decoder';
67
import { GlobalLoggerService } from '../../../Logger';
78

89
const logger = GlobalLoggerService.getLogger('Tools/Process/runtime/process');
@@ -13,6 +14,20 @@ const SIGKILL_TIMEOUT_MS = 800;
1314
const SHELL_BLACKLIST = new Set(['fish', 'nu']);
1415
const PROBE_TIMEOUT_MS = 2_000;
1516

17+
export type ProcessShell = string | false;
18+
19+
export interface LimitedOutputBuffer {
20+
chunks: Buffer[];
21+
bytes: number;
22+
overflow: boolean;
23+
decoder: StringDecoder;
24+
}
25+
26+
export interface OutputDrain {
27+
text: string;
28+
overflowed: boolean;
29+
}
30+
1631
const QUIET_ENV = {
1732
CI: '1',
1833
NO_COLOR: '1',
@@ -98,6 +113,69 @@ export function getChildProcessEnv(): NodeJS.ProcessEnv {
98113
return safeEnv;
99114
}
100115

116+
export function spawnRuntimeProcess(
117+
file: string,
118+
args: string[],
119+
opts: { cwd: string; shell: ProcessShell; stdin?: string },
120+
): ChildProcess {
121+
const proc = spawn(file, args, {
122+
shell: opts.shell,
123+
cwd: opts.cwd,
124+
env: getChildProcessEnv(),
125+
stdio: [opts.stdin !== undefined ? 'pipe' : 'ignore', 'pipe', 'pipe'],
126+
detached: process.platform !== 'win32',
127+
windowsHide: true,
128+
});
129+
130+
writeProcessStdin(proc, opts.stdin);
131+
return proc;
132+
}
133+
134+
export function writeProcessStdin(proc: ChildProcess, stdin: string | undefined): void {
135+
if (stdin === undefined || !proc.stdin) return;
136+
proc.stdin.on('error', () => { /* ignore EPIPE */ });
137+
proc.stdin.end(stdin, 'utf8');
138+
}
139+
140+
export function createOutputBuffer(): LimitedOutputBuffer {
141+
return { chunks: [], bytes: 0, overflow: false, decoder: new StringDecoder('utf8') };
142+
}
143+
144+
export function hasBufferedOutput(buf: LimitedOutputBuffer): boolean {
145+
return buf.bytes > 0 || buf.overflow;
146+
}
147+
148+
export function appendOutputBuffer(buf: LimitedOutputBuffer, chunk: Buffer): void {
149+
if (buf.overflow) return;
150+
const remain = MAX_OUTPUT_BYTES - buf.bytes;
151+
if (chunk.length >= remain) {
152+
if (remain > 0) buf.chunks.push(chunk.subarray(0, remain));
153+
buf.bytes = MAX_OUTPUT_BYTES;
154+
buf.overflow = true;
155+
return;
156+
}
157+
buf.chunks.push(chunk);
158+
buf.bytes += chunk.length;
159+
}
160+
161+
export function drainOutputBuffer(buf: LimitedOutputBuffer, final: boolean): OutputDrain {
162+
const overflowed = buf.overflow;
163+
const merged = Buffer.concat(buf.chunks, buf.bytes);
164+
const text = buf.decoder.write(merged) + (final || overflowed ? buf.decoder.end() : '');
165+
166+
if (final || overflowed) buf.decoder = new StringDecoder('utf8');
167+
buf.chunks = [];
168+
buf.bytes = 0;
169+
buf.overflow = false;
170+
171+
return { text, overflowed };
172+
}
173+
174+
export function formatProcessExit(exitCode: number | null, signal: NodeJS.Signals | null): string {
175+
if (signal) return `Process terminated by signal ${signal}`;
176+
return `Process exited with code ${exitCode ?? -1}`;
177+
}
178+
101179
export function validatePath(filePath: string): { valid: boolean; error?: string; absolutePath?: string } {
102180
if (!filePath || typeof filePath !== 'string') {
103181
return { valid: false, error: 'Path is empty' };

0 commit comments

Comments
 (0)