-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
361 lines (361 loc) · 15.6 KB
/
Copy pathindex.js
File metadata and controls
361 lines (361 loc) · 15.6 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import { spawn, spawnSync } from "node:child_process";
import { platform } from "node:process";
import { tool } from "@opencode-ai/plugin";
const isWindows = platform === "win32";
/** UTF-8 严格解码器(非法序列抛错) */
const utf8Fatal = new TextDecoder("utf-8", { fatal: true });
/** GBK 严格解码器(Windows 回退) */
const gbkFatal = new TextDecoder("gbk", { fatal: true });
/** 每进程的跨 chunk 残余字节 */
const pendingBytes = new Map();
/** 每进程已确定的编码(避免每 chunk 反复探测) */
const encCache = new Map();
/**
* 解码一段输出字节。策略:
* 1. 拼接上一 chunk 残余字节;
* 2. 按缓存编码(首次探测)尝试严格解码,解码失败时逐步把尾部 1..N 字节
* 挪到残余区(N=4 覆盖 UTF-8 最长字符),直到剩余头部可完整解码;
* 3. UTF-8 探测失败则回退 GBK(仅 Windows),GBK 回溯最多 2 字节;
* 4. 仍失败则整块留作残余,等下一 chunk 拼接。
*/
function decodeOutput(id, data) {
let buf = data;
const pending = pendingBytes.get(id);
if (pending && pending.length > 0)
buf = Buffer.concat([pending, data]);
const enc = encCache.get(id);
if (enc === "utf8")
return decodeKnown(id, buf, utf8Fatal, 4);
if (enc === "gbk")
return decodeKnown(id, buf, gbkFatal, 2);
// 未知编码:先试 UTF-8(回溯 4 字节)
const utf8Result = trySplit(buf, utf8Fatal, 4);
if (utf8Result) {
encCache.set(id, "utf8");
pendingBytes.set(id, utf8Result.tail);
return utf8Result.head;
}
// 再试 GBK(Windows 控制台常见输出编码,回溯 2 字节)
if (isWindows) {
const gbkResult = trySplit(buf, gbkFatal, 2);
if (gbkResult) {
encCache.set(id, "gbk");
pendingBytes.set(id, gbkResult.tail);
return gbkResult.head;
}
}
// 整块无法解码:留待下一 chunk
pendingBytes.set(id, buf);
return "";
}
function decodeKnown(id, buf, decoder, maxKeep) {
const r = trySplit(buf, decoder, maxKeep);
if (r) {
pendingBytes.set(id, r.tail);
return r.head;
}
pendingBytes.set(id, buf);
return "";
}
/** 尝试把 buf 切成「可严格解码的 head」+「残余 tail」;切不出返回 null */
function trySplit(buf, decoder, maxKeep) {
for (let keep = 0; keep <= maxKeep && keep <= buf.length; keep++) {
const head = buf.subarray(0, buf.length - keep);
try {
return { head: decoder.decode(head), tail: buf.subarray(buf.length - keep) };
}
catch {
// head 含非法序列,尝试保留更多尾部字节
}
}
return null;
}
const DEFAULT_MAX_LINES = 500;
/** 单行超过该长度时截尾,防止单行撑爆缓冲 */
const MAX_TAIL = 60;
/** 进程 ID -> 状态 */
const procs = new Map();
/** 自动 ID 命名计数器:命令基名 -> 序号 */
const nameCounters = new Map();
/** 退出钩子只注册一次 */
let exitHookRegistered = false;
function nextId(command) {
const base = command.split(/\s+/)[0]?.trim() || "process";
const n = (nameCounters.get(base) ?? 0) + 1;
nameCounters.set(base, n);
return `${base}-${n}`;
}
function clampLine(line) {
return line.length > MAX_TAIL ? `…${line.slice(-MAX_TAIL)}` : line;
}
function pushLine(state, line) {
state.buffer.push(line);
if (state.buffer.length > state.maxLines) {
state.buffer.splice(0, state.buffer.length - state.maxLines);
}
}
function signalToCode(signal) {
switch (signal) {
case "SIGKILL":
return "SIGKILL";
case "SIGINT":
return "SIGINT";
default:
return "SIGTERM";
}
}
/** 同步终止进程树:退出钩子专用(进程销毁前必须跑完) */
function killTreeSync(pid) {
try {
if (isWindows) {
spawnSync("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore" });
}
else {
try {
process.kill(-pid, "SIGKILL");
}
catch {
process.kill(pid, "SIGKILL");
}
}
}
catch {
// 进程已不存在,忽略
}
}
/** 异步终止进程树:工具调用专用 */
async function killTree(pid, signal) {
if (isWindows) {
// Windows 无 POSIX 信号语义,taskkill /T /F 是唯一可靠的全树终止
spawnSync("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore" });
return;
}
const s = signalToCode(signal);
try {
process.kill(-pid, s);
}
catch {
try {
process.kill(pid, s);
}
catch {
// 已退出
}
}
}
/** OC 退出时终止所有存活进程(含子进程树),保证不留孤儿 */
function registerExitHook() {
if (exitHookRegistered)
return;
exitHookRegistered = true;
process.on("exit", () => {
for (const state of procs.values()) {
if (state.pid != null && state.status === "running") {
killTreeSync(state.pid);
}
}
});
}
/** 输出快照(列表与调试用) */
function summarize(state) {
const p = state.status === "exited" ? `exit=${state.exitCode ?? "-"}` : `pid=${state.pid}`;
return `- ${state.id} [${state.status} ${p}] ${state.command} (${state.buffer.length} lines)`;
}
export const BackgroundProcess = async () => {
registerExitHook();
return {
tool: {
background_process_launch: tool({
description: "当用户想启动一个需要持续运行的进程(dev server、构建、监听、监控、下载、测试等),或提到「后台 / 别阻塞 / 挂起 / 一直跑」时,优先使用本工具,不要用 bash(bash 会阻塞当前回合直到命令结束)。效果:立即返回,进程在后台运行;" +
"之后用 background_process_list 查看、background_process_read 读输出、background_process_write 向 stdin 发送输入、" +
"background_process_kill / background_process_cleanup 终止。进程随 OpenCode 退出而自动终止。",
args: {
command: tool.schema
.string()
.describe("要运行的 shell 命令,如 `python -m http.server 8000` 或 `npm run dev`"),
cwd: tool.schema
.string()
.optional()
.describe("工作目录(默认:当前会话目录)"),
id: tool.schema
.string()
.optional()
.describe("自定义进程 ID(默认自动生成,如 npm-1)"),
maxOutputLines: tool.schema
.number()
.int()
.min(10)
.max(10000)
.optional()
.describe(`输出环形缓冲行数上限(默认 ${DEFAULT_MAX_LINES})`),
},
async execute(args, context) {
const command = args.command.trim();
if (!command)
return `错误:command 不能为空`;
const cwd = args.cwd ?? context.directory;
const id = args.id ?? nextId(command);
if (procs.has(id)) {
return `错误:已存在 ID 为 ${id} 的进程,请换一个 id 或先 kill 它`;
}
const state = {
id,
command,
cwd,
startedAt: new Date().toISOString(),
pid: null,
status: "running",
exitCode: null,
signal: null,
buffer: [],
maxLines: args.maxOutputLines ?? DEFAULT_MAX_LINES,
stdin: null,
};
procs.set(id, state);
const child = spawn(command, { cwd, shell: true, windowsHide: true });
state.pid = child.pid ?? null;
child.stdout?.on("data", (d) => {
for (const line of decodeOutput(id, d).split(/\r?\n/)) {
if (line)
pushLine(state, clampLine(line));
}
});
child.stderr?.on("data", (d) => {
for (const line of decodeOutput(id, d).split(/\r?\n/)) {
if (line)
pushLine(state, clampLine(line));
}
});
child.on("error", (err) => {
state.status = "exited";
state.exitCode = -1;
pushLine(state, `[spawn error] ${err.message}`);
});
child.on("close", (code, signal) => {
state.status = "exited";
state.exitCode = code;
state.signal = signal;
pendingBytes.delete(id);
encCache.delete(id);
pushLine(state, `[exited code=${code ?? "-"} signal=${signal ?? "-"}]`);
});
state.stdin = child.stdin;
return [
`已启动后台进程:`,
` id: ${id}`,
` command: ${command}`,
` pid: ${state.pid}`,
` cwd: ${cwd}`,
``,
`用 background_process_list 查看状态,background_process_read 读取输出,background_process_kill 终止。`,
`进程将在 OpenCode 退出时被自动终止。`,
].join("\n");
},
}),
background_process_list: tool({
description: "列出本会话启动的全部后台进程及状态(运行中/已退出)。",
args: {},
async execute() {
if (procs.size === 0)
return "没有后台进程。";
return [`后台进程:`, ...[...procs.values()].map(summarize)].join("\n");
},
}),
background_process_read: tool({
description: "读取指定后台进程的环形输出缓冲(stdout+stderr 合并)。返回末尾 N 行;" +
"clear=true 时读完清空缓冲。已退出进程仍可读历史输出。",
args: {
id: tool.schema.string().describe("目标进程 ID(见 background_process_list)"),
lines: tool.schema
.number()
.int()
.min(1)
.max(10000)
.optional()
.describe("返回缓冲末尾的 N 行(默认 50)"),
clear: tool.schema.boolean().optional().describe("读取后清空缓冲(默认 false)"),
},
async execute(args) {
const state = procs.get(args.id);
if (!state)
return `未找到进程 ${args.id}`;
const n = args.lines ?? 50;
const lines = state.buffer.slice(-n);
if (args.clear)
state.buffer.length = 0;
const body = lines.length ? lines.join("\n") : "(空缓冲)";
return `进程 ${state.id}(${state.status}${state.exitCode != null ? ` exit=${state.exitCode}` : ""}):\n${body}`;
},
}),
background_process_write: tool({
description: "向运行中的后台进程 stdin 写入一行输入(相当于在终端里敲命令后回车)。",
args: {
id: tool.schema.string().describe("目标进程 ID"),
input: tool.schema.string().describe("要写入的内容"),
},
async execute(args) {
const state = procs.get(args.id);
if (!state)
return `错误:进程 ${args.id} 不存在`;
if (state.status !== "running" || !state.stdin?.writable) {
return `错误:进程 ${args.id} 已退出或不可写`;
}
state.stdin.write(`${args.input}\n`);
return `已向 ${args.id} 写入:${args.input}`;
},
}),
background_process_kill: tool({
description: "终止指定后台进程(含其子进程树;Windows 用 taskkill /T 递归终止)。" +
"remove=true 时同时移除记录(默认保留记录以便读退出前输出)。",
args: {
id: tool.schema.string().describe("目标进程 ID"),
signal: tool.schema
.enum(["SIGTERM", "SIGKILL", "SIGINT"])
.optional()
.describe("信号(默认 SIGTERM;Windows 下统一强制终止)"),
remove: tool.schema.boolean().optional().describe("终止后从列表移除(默认 false)"),
},
async execute(args) {
const state = procs.get(args.id);
if (!state)
return `错误:进程 ${args.id} 不存在`;
if (state.status === "exited") {
return `进程 ${args.id} 已退出(exit=${state.exitCode ?? "-"}),无需终止`;
}
if (state.pid != null)
await killTree(state.pid, args.signal ?? "SIGTERM");
state.status = "exited";
pushLine(state, `[killed signal=${args.signal ?? "SIGTERM"}]`);
if (args.remove)
procs.delete(args.id);
return `已终止 ${args.id}(pid=${state.pid ?? "-"})${args.remove ? "并移除记录" : ""}`;
},
}),
background_process_cleanup: tool({
description: "清理后台进程:默认只移除已退出进程的记录;killAll=true 时先终止所有运行中进程再清空。",
args: {
killAll: tool.schema.boolean().optional().describe("先终止所有运行中进程(默认 false)"),
},
async execute(args) {
let killed = 0;
if (args.killAll) {
for (const state of procs.values()) {
if (state.status === "running" && state.pid != null) {
await killTree(state.pid, "SIGTERM");
state.status = "exited";
killed++;
}
}
}
const removed = procs.size;
procs.clear();
return `已清理:移除 ${removed} 条记录${killed ? `,终止 ${killed} 个运行中进程` : ""}`;
},
}),
},
};
};
export default {
id: "background-process",
server: BackgroundProcess,
};