@echo-agent/coding 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tools/bash.ts DELETED
@@ -1,384 +0,0 @@
1
- // shell 一组:bash(前台跑命令;background: true 时挂进 agent.background)+ job_output / job_stop(后台作业的回读与停止)。
2
- //
3
- // **执行体在这层,队列在 core**——这正是「队列在 core,跑什么在产品」那句话的落地:
4
- // core 的 startBackground / getBackground / killBackground 管闸/缓冲/收摊,这里只填「怎么起一个进程」
5
- // 和「怎么把缓冲与取消口摆给模型」。
6
- //
7
- // job_output / job_stop 是 2026-09-01 补的:此前 background: true 起了 dev server / watcher 之后,
8
- // 结果「以后作为通知送达」,模型中途看不到输出、也停不掉——「跑起来看日志再改」这条最常见的循环走不通。
9
-
10
- import { getBackground, killBackground, listBackground, startBackground } from "@echo-agent/core/background";
11
- import { spawn, spawnSync, type ChildProcess } from "node:child_process";
12
- import { existsSync } from "node:fs";
13
- import { toolError, toolOk, type AgentBackground, type AgentToolResult, type ModelTool } from "@echo-agent/core";
14
-
15
- /** 命令跑在什么环境里:`tool:shell` 段据此写明平台与 bash 版本(macOS 的 BSD 工具链、bash 3.2 的缺口)。 */
16
- export type ShellEnvironment = { platform: NodeJS.Platform; bashVersion: string | null };
17
-
18
- /**
19
- * 取一次运行环境:平台读 `process.platform`,bash 版本问一次 `bash` 自己(`$BASH_VERSION` 去掉括号后缀)。
20
- * 装配时调(`echo:shell` 的 apply),不是每轮——段在 run 之间不变,前缀缓存才接得上。问不出来版本 = null。
21
- */
22
- export function detectShellEnvironment(): ShellEnvironment {
23
- let bashVersion: string | null = null;
24
- try {
25
- const r = spawnSync("bash", ["-c", 'printf %s "$BASH_VERSION"'], { encoding: "utf8", timeout: 2_000, stdio: ["ignore", "pipe", "ignore"] });
26
- const v = /^\d+(\.\d+)*/.exec(r.stdout ?? "")?.[0];
27
- if (r.status === 0 && v !== undefined) bashVersion = v;
28
- } catch {
29
- // 没有 bash:段里只写平台
30
- }
31
- return { platform: process.platform, bashVersion };
32
- }
33
-
34
- /**
35
- * 前台命令最多收这么多字符(2026-11-02):不再在这里截到 30,000 丢掉后半——报错多在末尾。
36
- * 收全了交给 core:超过内联上限时全文外存、对话里只留头尾预览(`@echo-agent/core` 的工具结果外存)。
37
- * 这个上限只防内存失控。
38
- */
39
- const CAPTURE_CAP = 8 * 1024 * 1024;
40
- const DEFAULT_TIMEOUT_MS = 120_000;
41
- /** job_output 缺省回读的字符数:够看清最近的日志,又不至于一次把缓冲全倒进上下文。 */
42
- const JOB_TAIL_DEFAULT = 4_000;
43
-
44
- /**
45
- * 工作目录跨调用保留(2026-09-03,照 Claude Code:cd 保留、shell 变量不保留)。
46
- * 每次前台命令包一层——命令跑完打印 `$PWD` 标记再以原退出码退出;解析到的目录就是下一次的起点(后台命令也从那里起)。
47
- * 标记用 RS(0x1e)包着,普通输出里不会出现。找**最后一个**标记、不要求它在末尾:`cmd &` 起的后台进程可能在标记之后
48
- * 还写了几行。正文被截断时标记在截断点之后,另在末尾几百字节里留了一份。
49
- */
50
- const CWD_TAIL_KEEP = 512;
51
- const CWD_MARK = "\u001e__ECHO_CWD__";
52
-
53
- /**
54
- * 主 shell 退出之后等输出管道关的时间:管道里剩下的输出读完就关(通常几毫秒);关不上说明命令起的后台进程
55
- * (`cmd &`)还攥着它——那就不等了,收尾返回已有输出并说明,后台进程不杀。窗口在有输出到达时顺延(主进程退出前
56
- * 写进管道的最后一截还在路上),但总共不超过 `DRAIN_MAX_MS`,一直在写的后台进程拖不住这一次调用。
57
- */
58
- // 500 而不是 100(2026-11-09):慢机器上起一个子进程就要一两百毫秒(macOS CI 实测 `(sleep 0.02; echo late) &` 的输出
59
- // 连着两次赶不上 100 ms),刚起的后台子进程写完的那几行会被当成「攥着输出」丢掉。只有留了后台进程的那次调用多等,封顶仍是 DRAIN_MAX_MS
60
- const DRAIN_IDLE_MS = 500;
61
- const DRAIN_MAX_MS = 1_000;
62
-
63
- /**
64
- * 子进程的环境:继承父进程(`bash -c`,不读 profile),再关掉会等人的东西——没有 TTY、stdin 已关,
65
- * 编辑器 / 分页器 / 凭据提示只会挂到超时、什么也不输出。取舍照 codex 给子进程设的非交互变量:
66
- * - `GIT_EDITOR=true`:commit / merge / rebase --continue 不开编辑器——带着现成的消息走,没有消息就因空消息中止;
67
- * - `GIT_PAGER` / `PAGER` / `GH_PAGER` = `cat`:输出直接出来,不进分页器;
68
- * - `GIT_TERMINAL_PROMPT=0`:要账号密码时直接失败,不等输入。
69
- * `EDITOR` / `VISUAL` 不动:git 先认 `GIT_EDITOR`,别的程序要编辑器时失败比被换成 `true` 静默「编辑成功」更好懂。
70
- */
71
- const NON_INTERACTIVE_ENV = {
72
- GIT_EDITOR: "true",
73
- GIT_PAGER: "cat",
74
- PAGER: "cat",
75
- GH_PAGER: "cat",
76
- GIT_TERMINAL_PROMPT: "0",
77
- } as const;
78
-
79
- export type BashDeps = {
80
- /** 给了才支持 background: true(接 agent.background);job_output / job_stop 也读同一张表。 */
81
- background?: AgentBackground;
82
- };
83
-
84
- /**
85
- * shell 一组共享的状态:当前工作目录,以及它是在哪个 workspace 下记的。`cwd` 为 `undefined` = 还没 cd 过,
86
- * 用 session 的 workspace;workspace 变了(worktree 隔离切了目录)cwd 作废,从新 workspace 起。
87
- */
88
- export type ShellState = { cwd: string | undefined; workspace: string | undefined };
89
-
90
- /** shell 一组的全部工具。`echo:shell` 注册的与 `codingAgentIdentity()` 列的是**同一份**,不各写各的名单。 */
91
- export function makeShellTools(deps: BashDeps = {}): ModelTool[] {
92
- const state: ShellState = { cwd: undefined, workspace: undefined };
93
- return [makeBashTool(deps, state), jobOutputTool(deps), jobStopTool(deps)] as ModelTool[];
94
- }
95
-
96
- export function makeBashTool(
97
- deps: BashDeps = {},
98
- state: ShellState = { cwd: undefined, workspace: undefined },
99
- ): ModelTool<{ command: string; timeout_ms?: number; background?: boolean }> {
100
- /** 本次命令从哪起:保留的目录还在就用它;workspace 换了或目录被删了就退回 workspace(后者要告诉模型)。 */
101
- const startDir = (workspace: string): { cwd: string; note: string } => {
102
- if (state.workspace !== workspace) {
103
- state.workspace = workspace;
104
- state.cwd = undefined;
105
- }
106
- if (state.cwd === undefined) return { cwd: workspace, note: "" };
107
- if (existsSync(state.cwd)) return { cwd: state.cwd, note: "" };
108
- const gone = state.cwd;
109
- state.cwd = undefined;
110
- return { cwd: workspace, note: `\n(previous working directory ${gone} no longer exists; back in the workspace root)` };
111
- };
112
- return {
113
- kind: "model",
114
- name: "bash",
115
- label: "跑命令",
116
- description:
117
- "Run one bash command (bash -c, not a login shell; it inherits this process's environment) and return stdout and stderr (merged). " +
118
- "There is no terminal and stdin is closed: use non-interactive flags (git commit -m, --yes); git's editor and pager are turned off. " +
119
- "The working directory carries over between calls (it starts at the workspace root; cd persists), shell variables and functions do not. " +
120
- "Times out after 120 s by default; for long-running work (dev servers, watchers) pass background: true — " +
121
- "read its output with job_output, stop it with job_stop, and you are notified when it ends. Do not use a trailing & for that: " +
122
- "the call returns once the command exits and the background process's later output is lost. " +
123
- "For files in the workspace use read_file, edit_file / write_file, grep and glob instead of cat, sed, echo >, find or rg.",
124
- parameters: {
125
- type: "object",
126
- properties: {
127
- command: { type: "string" },
128
- timeout_ms: { type: "number", description: "Timeout in milliseconds, default 120000" },
129
- background: { type: "boolean", description: "Run in the background (does not block this turn)" },
130
- },
131
- required: ["command"],
132
- },
133
- async execute({ command, timeout_ms, background }, ctx) {
134
- if (background === true) {
135
- if (deps.background === undefined) return toolError("This agent has no background queue; background: true is not supported");
136
- const r = startBackground(deps.background, {
137
- kind: "process",
138
- label: command.slice(0, 60),
139
- run: (bg) =>
140
- new Promise<void>((resolvePromise, rejectPromise) => {
141
- const child = spawnShell(command, startDir(ctx.workspace).cwd);
142
- // 每条流一只流式 decoder:跨 chunk 的多字节字符不再被解成替换符(review 2026-09-07)
143
- const outDec = new TextDecoder();
144
- const errDec = new TextDecoder();
145
- child.stdout!.on("data", (d: Buffer) => bg.write(outDec.decode(d, { stream: true })));
146
- child.stderr!.on("data", (d: Buffer) => bg.write(errDec.decode(d, { stream: true })));
147
- bg.signal.addEventListener("abort", () => killTree(child), { once: true });
148
- child.on("error", rejectPromise);
149
- child.on("close", (code) => {
150
- bg.write(outDec.decode()); // 冲残余
151
- bg.write(errDec.decode());
152
- if (code === 0 || bg.signal.aborted) resolvePromise();
153
- else rejectPromise(new Error(`exit code ${code}`));
154
- });
155
- }),
156
- });
157
- if (!r.ok) {
158
- return toolError(
159
- r.reason === "too_many_running"
160
- ? `${r.running}/${r.max} background jobs are already running; collect some first`
161
- : `The background queue is full (${r.tasks}/${r.max})`,
162
- );
163
- }
164
- return toolOk(
165
- `Started in the background: ${r.task.id} (job_output ${r.task.id} to read its output, job_stop to stop it; you will be notified when it finishes)`,
166
- { taskId: r.task.id },
167
- );
168
- }
169
-
170
- const start = startDir(ctx.workspace);
171
- const result = await runForeground(command, start.cwd, timeout_ms ?? DEFAULT_TIMEOUT_MS, ctx.signal);
172
- // 命令跑到了末尾才有标记(exec / 被杀 / 语法错都没有):没有就保持原来的目录
173
- const changed = result.cwd !== undefined && result.cwd !== start.cwd;
174
- if (result.cwd !== undefined) state.cwd = result.cwd === ctx.workspace ? undefined : result.cwd;
175
- const note = `${start.note}${changed ? `\n(working directory is now ${result.cwd})` : ""}`;
176
- return note === "" ? result : { ...result, content: `${result.content}${note}` };
177
- },
178
- };
179
- }
180
-
181
- /** 把命令包一层:跑完打印 `$PWD` 标记、再以命令自己的退出码退出。`{ … }` 分组让多行命令与末尾注释都成立。 */
182
- function withCwdMarker(command: string): string {
183
- return `{\n${command}\n}\n__echo_rc=$?\nprintf '\\n\\036__ECHO_CWD__%s\\036\\n' "$PWD"\nexit $__echo_rc`;
184
- }
185
-
186
- /**
187
- * 起 shell 时自成一个进程组(detached):杀的时候按组杀({@link killTree})。
188
- * 不然 `sleep 10`、dev server 这类由 bash 再起的子进程会活过 bash,攥着输出管道不放——超时/中止要等它自己结束,job_stop 也留孤儿。
189
- *
190
- * `bash -c`,不是登录 shell:登录 shell 会读 profile,macOS 上 `path_helper` 还会把系统目录排到 PATH 前面,
191
- * 用户装的 git / ruby / node 就变成了系统那一份。命令看到的环境与启动 echo-coding 的那个 shell 一致。
192
- * `PWD` 例外,设成本次的起点:继承来的是父进程的目录,bash 发现它不指向当前目录就改用物理路径——
193
- * 工作区经软链时(macOS 的 `/var` → `/private/var`)`$PWD` 成了展开后的路径,第一条命令就被当成「cd 过了」。
194
- */
195
- function spawnShell(command: string, cwd: string): ChildProcess {
196
- return spawn("bash", ["-c", command], {
197
- cwd,
198
- stdio: ["ignore", "pipe", "pipe"],
199
- detached: true,
200
- env: { ...process.env, ...NON_INTERACTIVE_ENV, PWD: cwd },
201
- });
202
- }
203
-
204
- /** 输出里摘掉最后一个 cwd 标记(连同它前后各一个换行),返回标记里的目录。没有标记 = 命令没跑到末尾(exec / 被杀 / 语法错)。 */
205
- function takeCwdMarker(text: string): { cwd?: string; body: string } {
206
- const at = text.lastIndexOf(CWD_MARK);
207
- if (at < 0) return { body: text };
208
- const end = text.indexOf("\u001e", at + CWD_MARK.length);
209
- if (end < 0) return { body: text };
210
- const before = text.slice(0, at);
211
- const after = text.slice(end + 1);
212
- return {
213
- cwd: text.slice(at + CWD_MARK.length, end),
214
- body: (before.endsWith("\n") ? before.slice(0, -1) : before) + (after.startsWith("\n") ? after.slice(1) : after),
215
- };
216
- }
217
-
218
- function killTree(child: ChildProcess): void {
219
- if (child.pid === undefined) return;
220
- try {
221
- process.kill(-child.pid, "SIGKILL");
222
- } catch {
223
- child.kill("SIGKILL");
224
- }
225
- }
226
-
227
- /** 错误里把已知作业列出来:模型丢了 id(压缩之后常见)也能找回来,不用再多一件 job_list。 */
228
- function knownJobs(bg: AgentBackground): string {
229
- const all = listBackground(bg.tasks);
230
- return all.length === 0 ? "there are no background jobs" : `known jobs: ${all.map((t) => `${t.id} [${t.status}] ${t.label}`).join("; ")}`;
231
- }
232
-
233
- function jobOutputTool(deps: BashDeps): ModelTool<{ id: string; tail?: number }> {
234
- return {
235
- kind: "model",
236
- name: "job_output",
237
- label: "看后台输出",
238
- description:
239
- "Show the status and the most recent output of a background job started with bash background: true. " +
240
- "The output is a bounded buffer; tail limits how many trailing characters come back (default 4000).",
241
- parameters: {
242
- type: "object",
243
- properties: {
244
- id: { type: "string", description: "The job id returned by bash" },
245
- tail: { type: "number", description: "Trailing characters to return, default 4000" },
246
- },
247
- required: ["id"],
248
- },
249
- async execute({ id, tail }) {
250
- if (deps.background === undefined) return toolError("This agent has no background queue");
251
- const task = getBackground(deps.background.tasks, id);
252
- if (task === undefined) return toolError(`No such job: ${id}; ${knownJobs(deps.background)}`);
253
- // `tail()` 只看一眼不动游标:结束通知那条路走的是 readNew(),两边互不吃掉对方的增量
254
- const text = task.buffer.tail(Math.max(1, tail ?? JOB_TAIL_DEFAULT));
255
- const head = `${task.id} [${task.status}] ${task.label}${task.error === null ? "" : ` — ${task.error}`}`;
256
- return toolOk(`${head}\n${text === "" ? "(no output yet)" : text}`, { id, status: task.status });
257
- },
258
- };
259
- }
260
-
261
- function jobStopTool(deps: BashDeps): ModelTool<{ id: string }> {
262
- return {
263
- kind: "model",
264
- name: "job_stop",
265
- label: "停后台作业",
266
- description: "Stop a running background job (it is killed). A job that already ended is left as it is.",
267
- parameters: {
268
- type: "object",
269
- properties: { id: { type: "string", description: "The job id returned by bash" } },
270
- required: ["id"],
271
- },
272
- async execute({ id }) {
273
- if (deps.background === undefined) return toolError("This agent has no background queue");
274
- const task = getBackground(deps.background.tasks, id);
275
- if (task === undefined) return toolError(`No such job: ${id}; ${knownJobs(deps.background)}`);
276
- if (task.status !== "running") return toolOk(`${id} had already ended (${task.status})`, { id, status: task.status });
277
- const stopped = await killBackground(deps.background.tasks, id);
278
- return stopped
279
- ? toolOk(`Stopped ${id} (${task.label})`, { id, status: task.status })
280
- : toolError(`Could not stop ${id}; it is ${task.status}`);
281
- },
282
- };
283
- }
284
-
285
- function runForeground(
286
- command: string,
287
- cwd: string,
288
- timeoutMs: number,
289
- signal?: AbortSignal,
290
- ): Promise<AgentToolResult & { cwd?: string }> {
291
- return new Promise((resolvePromise) => {
292
- const child = spawnShell(withCwdMarker(command), cwd);
293
- let out = "";
294
- let truncated = false;
295
- let tail = ""; // 末尾几百字节单独留着:cwd 标记在这里找,输出被截断也丢不了
296
- const append = (chunk: string): void => {
297
- tail = (tail + chunk).slice(-CWD_TAIL_KEEP);
298
- if (out.length >= CAPTURE_CAP) {
299
- truncated = true;
300
- return;
301
- }
302
- out += chunk;
303
- };
304
- // 主 shell 退出之后的排空窗口(见 `DRAIN_IDLE_MS`):有输出到达就顺延,总长封顶
305
- let exited = false;
306
- let exitCode: number | null = null;
307
- let drainIdle: ReturnType<typeof setTimeout> | undefined;
308
- let drainMax: ReturnType<typeof setTimeout> | undefined;
309
- const armDrain = (): void => {
310
- clearTimeout(drainIdle);
311
- drainIdle = setTimeout(() => finish(exitCode, { held: true }), DRAIN_IDLE_MS);
312
- };
313
- // 每条流一只流式 decoder:跨 chunk 的多字节字符不再被解成替换符(review 2026-09-07:此前逐块 toString)
314
- const outDec = new TextDecoder();
315
- const errDec = new TextDecoder();
316
- const onData = (dec: TextDecoder) => (d: Buffer): void => {
317
- append(dec.decode(d, { stream: true }));
318
- if (exited) armDrain();
319
- };
320
- child.stdout!.on("data", onData(outDec));
321
- child.stderr!.on("data", onData(errDec));
322
-
323
- let timedOut = false;
324
- const timer = setTimeout(() => {
325
- timedOut = true;
326
- killTree(child);
327
- }, timeoutMs);
328
- const onAbort = (): void => {
329
- killTree(child);
330
- };
331
- signal?.addEventListener("abort", onAbort, { once: true });
332
-
333
- let settled = false;
334
- const finish = (code: number | null, how: { spawnError?: string; held?: boolean } = {}): void => {
335
- if (settled) return;
336
- settled = true;
337
- clearTimeout(timer);
338
- clearTimeout(drainIdle);
339
- clearTimeout(drainMax);
340
- signal?.removeEventListener("abort", onAbort);
341
- if (how.held === true) {
342
- // 后台进程还攥着管道:我们这头不读了。进程本身不杀——它是命令有意起的
343
- child.stdout?.destroy();
344
- child.stderr?.destroy();
345
- }
346
- append(outDec.decode()); // 冲残余
347
- append(errDec.decode());
348
- // cwd 标记:正文里有就从正文摘(连同它前后各一个换行);正文被截断、标记落在截断点之后,就从末尾那份里找
349
- const taken = takeCwdMarker(out);
350
- const newCwd = taken.cwd ?? takeCwdMarker(tail).cwd;
351
- const body = taken.body;
352
- let text = body.slice(0, CAPTURE_CAP);
353
- if (truncated || body.length > CAPTURE_CAP) text += `\n…[output truncated: over ${CAPTURE_CAP} characters]`;
354
- if (how.held === true) {
355
- text +=
356
- "\n(a background process started by this command is still running and holding the output; what it prints from now on is not captured. " +
357
- "Use background: true for long-running processes.)";
358
- }
359
- const withCwd = (r: AgentToolResult): AgentToolResult & { cwd?: string } => (newCwd === undefined ? r : { ...r, cwd: newCwd });
360
- if (how.spawnError !== undefined) {
361
- resolvePromise(toolError(`The command could not start: ${how.spawnError}`));
362
- } else if (timedOut) {
363
- resolvePromise(toolError(`Timed out after ${timeoutMs} ms and was killed. Output:\n${text}`));
364
- } else if (signal?.aborted === true) {
365
- resolvePromise(toolError(`Aborted. Output:\n${text}`));
366
- } else if (code !== 0) {
367
- // 非零退出是**结果**不是异常——模型要看到输出来决定下一步
368
- resolvePromise(withCwd(toolError(`exit code ${code}\n${text}`, { exitCode: code })));
369
- } else {
370
- resolvePromise(withCwd(toolOk(text === "" ? "(no output)" : text, { exitCode: 0 })));
371
- }
372
- };
373
- child.on("error", (e) => finish(null, { spawnError: String(e) }));
374
- child.on("exit", (code) => {
375
- // 命令本身结束了:超时不再适用(剩下的只可能是它起的后台进程),进入排空窗口
376
- exited = true;
377
- exitCode = code;
378
- clearTimeout(timer);
379
- armDrain();
380
- drainMax = setTimeout(() => finish(code, { held: true }), DRAIN_MAX_MS);
381
- });
382
- child.on("close", (code) => finish(code ?? exitCode));
383
- });
384
- }