-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathrunner.ts
More file actions
185 lines (167 loc) · 4.89 KB
/
Copy pathrunner.ts
File metadata and controls
185 lines (167 loc) · 4.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
/**
* CLIRunner — spawn CLI 进程并流式解析输出。从 spike 迁移,加 abort 支持。
*/
import { spawn, type ChildProcess } from 'node:child_process';
import { PROCESS_TIMEOUT_MS } from '@slark/shared';
import type {
BuildCommandParams,
CLIAdapter,
CLIEvent,
RunnerOptions,
RunnerResult,
SpawnSpec,
} from './types.js';
export interface RunningProcess {
child: ChildProcess;
abort: () => void;
}
/**
* 统一入口(推荐):根据 adapter 类型自动选择 spawn-派 / api-direct 派路径。
*
* - adapter.runDirect 存在 → 直接调用(CursorSdkAdapter 等)
* - 否则 → buildCommand + spawn 子进程(CursorAdapter / CodexAdapter / ClaudeAdapter)
*
* 新代码统一用此函数,老代码渐进迁移。
*/
export async function runWithAdapter(
adapter: CLIAdapter,
params: BuildCommandParams,
options: RunnerOptions = {},
): Promise<RunnerResult> {
if (adapter.runDirect) {
return adapter.runDirect(params, options);
}
const spec = adapter.buildCommand(params);
return runCLI(adapter, spec, options);
}
export async function runCLI(
adapter: CLIAdapter,
spec: SpawnSpec,
options: RunnerOptions = {},
): Promise<RunnerResult> {
const timeoutMs = options.timeoutMs ?? PROCESS_TIMEOUT_MS;
const start = Date.now();
return new Promise((resolve) => {
const events: CLIEvent[] = [];
let fullText = '';
let deltaBuffer = '';
let completedBuffer = '';
let stdoutBuf = '';
let timedOut = false;
let aborted = false;
const child: ChildProcess = spawn(spec.command, spec.args, {
cwd: spec.cwd,
env: spec.env ? { ...process.env, ...spec.env } : process.env,
stdio: ['pipe', 'pipe', 'pipe'],
});
const timeoutHandle = setTimeout(() => {
timedOut = true;
try { child.kill('SIGTERM'); } catch { /* ignore */ }
setTimeout(() => {
try { child.kill('SIGKILL'); } catch { /* ignore */ }
}, 2000);
}, timeoutMs);
options.signal?.addEventListener('abort', () => {
aborted = true;
try { child.kill('SIGTERM'); } catch { /* ignore */ }
setTimeout(() => {
try { child.kill('SIGKILL'); } catch { /* ignore */ }
}, 2000);
});
if (spec.stdin !== undefined) {
child.stdin?.write(spec.stdin);
}
child.stdin?.end();
child.stdout?.on('data', (chunk: Buffer) => {
stdoutBuf += chunk.toString('utf8');
let idx: number;
while ((idx = stdoutBuf.indexOf('\n')) >= 0) {
const line = stdoutBuf.slice(0, idx);
stdoutBuf = stdoutBuf.slice(idx + 1);
processLine(line);
}
});
function processLine(line: string) {
if (!line.trim()) return;
options.onRawLine?.(line);
const parsed = adapter.parseLine(line);
for (const event of parsed) {
events.push(event);
if (event.type === 'text.delta') {
deltaBuffer += event.text;
fullText = deltaBuffer;
}
if (event.type === 'text.completed') {
if (adapter.capabilities.supportsTextDelta) {
fullText = event.text;
} else {
completedBuffer += (completedBuffer ? '\n\n' : '') + event.text;
fullText = completedBuffer;
}
}
options.onEvent?.(event);
}
}
child.stderr?.on('data', (chunk: Buffer) => {
const s = chunk.toString('utf8');
for (const line of s.split('\n')) {
if (line.trim()) options.onStderr?.(line);
}
});
child.on('error', (err) => {
clearTimeout(timeoutHandle);
const errEvent: CLIEvent = {
type: 'error',
message: err.message,
code: 'spawn_error',
};
events.push(errEvent);
options.onEvent?.(errEvent);
resolve({
exitCode: null,
fullText,
events,
duration_ms: Date.now() - start,
timedOut: false,
aborted,
});
});
child.on('close', (code) => {
clearTimeout(timeoutHandle);
if (stdoutBuf.trim()) processLine(stdoutBuf);
if (deltaBuffer && !events.some((e) => e.type === 'text.completed')) {
const ev: CLIEvent = { type: 'text.completed', text: deltaBuffer };
events.push(ev);
fullText = deltaBuffer;
options.onEvent?.(ev);
}
if (timedOut) {
const ev: CLIEvent = {
type: 'error',
message: `Process timed out after ${timeoutMs}ms`,
code: 'timeout',
};
events.push(ev);
options.onEvent?.(ev);
}
if (aborted) {
const ev: CLIEvent = {
type: 'error',
message: 'Process aborted by user',
code: 'aborted',
recoverable: true,
};
events.push(ev);
options.onEvent?.(ev);
}
resolve({
exitCode: code,
fullText,
events,
duration_ms: Date.now() - start,
timedOut,
aborted,
});
});
});
}