@echo-agent/coding 0.6.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/README.md +21 -8
- package/package.json +6 -5
- package/src/agent.ts +55 -32
- package/src/cli.ts +19 -7
- package/src/extensions.ts +6 -63
- package/src/index.ts +4 -6
- package/src/permission.ts +30 -48
- package/src/prompt.ts +2 -19
- package/src/tools/bash.ts +0 -275
- package/src/tools/fs.ts +0 -231
- package/src/tools/search.ts +0 -194
- package/src/tools/web.ts +0 -267
package/src/tools/bash.ts
DELETED
|
@@ -1,275 +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, 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
|
-
/**
|
|
16
|
-
* 前台命令最多收这么多字符(2026-11-02):不再在这里截到 30,000 丢掉后半——报错多在末尾。
|
|
17
|
-
* 收全了交给 core:超过内联上限时全文外存、对话里只留头尾预览(`@echo-agent/core` 的工具结果外存)。
|
|
18
|
-
* 这个上限只防内存失控。
|
|
19
|
-
*/
|
|
20
|
-
const CAPTURE_CAP = 8 * 1024 * 1024;
|
|
21
|
-
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
22
|
-
/** job_output 缺省回读的字符数:够看清最近的日志,又不至于一次把缓冲全倒进上下文。 */
|
|
23
|
-
const JOB_TAIL_DEFAULT = 4_000;
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* 工作目录跨调用保留(2026-09-03,照 Claude Code:cd 保留、shell 变量不保留)。
|
|
27
|
-
* 每次前台命令包一层——命令跑完打印 `$PWD` 标记再以原退出码退出;解析到的目录就是下一次的起点(后台命令也从那里起)。
|
|
28
|
-
* 标记用 RS(0x1e)包着,普通输出里不会出现;它只在末尾几百字节里找,输出再长也截不掉它。
|
|
29
|
-
*/
|
|
30
|
-
const CWD_TAIL_KEEP = 512;
|
|
31
|
-
const CWD_MARK_RE = /\u001e__ECHO_CWD__([^\u001e]*)\u001e\n?$/;
|
|
32
|
-
|
|
33
|
-
export type BashDeps = {
|
|
34
|
-
/** 给了才支持 background: true(接 agent.background);job_output / job_stop 也读同一张表。 */
|
|
35
|
-
background?: AgentBackground;
|
|
36
|
-
};
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* shell 一组共享的状态:当前工作目录,以及它是在哪个 workspace 下记的。`cwd` 为 `undefined` = 还没 cd 过,
|
|
40
|
-
* 用 session 的 workspace;workspace 变了(worktree 隔离切了目录)cwd 作废,从新 workspace 起。
|
|
41
|
-
*/
|
|
42
|
-
export type ShellState = { cwd: string | undefined; workspace: string | undefined };
|
|
43
|
-
|
|
44
|
-
/** shell 一组的全部工具。`echo:shell` 注册的与 `codingAgentIdentity()` 列的是**同一份**,不各写各的名单。 */
|
|
45
|
-
export function makeShellTools(deps: BashDeps = {}): ModelTool[] {
|
|
46
|
-
const state: ShellState = { cwd: undefined, workspace: undefined };
|
|
47
|
-
return [makeBashTool(deps, state), jobOutputTool(deps), jobStopTool(deps)] as ModelTool[];
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export function makeBashTool(
|
|
51
|
-
deps: BashDeps = {},
|
|
52
|
-
state: ShellState = { cwd: undefined, workspace: undefined },
|
|
53
|
-
): ModelTool<{ command: string; timeout_ms?: number; background?: boolean }> {
|
|
54
|
-
/** 本次命令从哪起:保留的目录还在就用它;workspace 换了或目录被删了就退回 workspace(后者要告诉模型)。 */
|
|
55
|
-
const startDir = (workspace: string): { cwd: string; note: string } => {
|
|
56
|
-
if (state.workspace !== workspace) {
|
|
57
|
-
state.workspace = workspace;
|
|
58
|
-
state.cwd = undefined;
|
|
59
|
-
}
|
|
60
|
-
if (state.cwd === undefined) return { cwd: workspace, note: "" };
|
|
61
|
-
if (existsSync(state.cwd)) return { cwd: state.cwd, note: "" };
|
|
62
|
-
const gone = state.cwd;
|
|
63
|
-
state.cwd = undefined;
|
|
64
|
-
return { cwd: workspace, note: `\n(previous working directory ${gone} no longer exists; back in the workspace root)` };
|
|
65
|
-
};
|
|
66
|
-
return {
|
|
67
|
-
kind: "model",
|
|
68
|
-
name: "bash",
|
|
69
|
-
label: "跑命令",
|
|
70
|
-
description:
|
|
71
|
-
"Run one bash command and return stdout and stderr (merged). The working directory carries over between calls " +
|
|
72
|
-
"(it starts at the workspace root; cd persists), shell variables and functions do not. " +
|
|
73
|
-
"Times out after 120 s by default; for long-running work (dev servers, watchers) pass background: true — " +
|
|
74
|
-
"read its output with job_output, stop it with job_stop, and you are notified when it ends.",
|
|
75
|
-
parameters: {
|
|
76
|
-
type: "object",
|
|
77
|
-
properties: {
|
|
78
|
-
command: { type: "string" },
|
|
79
|
-
timeout_ms: { type: "number", description: "Timeout in milliseconds, default 120000" },
|
|
80
|
-
background: { type: "boolean", description: "Run in the background (does not block this turn)" },
|
|
81
|
-
},
|
|
82
|
-
required: ["command"],
|
|
83
|
-
},
|
|
84
|
-
async execute({ command, timeout_ms, background }, ctx) {
|
|
85
|
-
if (background === true) {
|
|
86
|
-
if (deps.background === undefined) return toolError("This agent has no background queue; background: true is not supported");
|
|
87
|
-
const r = startBackground(deps.background, {
|
|
88
|
-
kind: "process",
|
|
89
|
-
label: command.slice(0, 60),
|
|
90
|
-
run: (bg) =>
|
|
91
|
-
new Promise<void>((resolvePromise, rejectPromise) => {
|
|
92
|
-
const child = spawnShell(command, startDir(ctx.workspace).cwd);
|
|
93
|
-
// 每条流一只流式 decoder:跨 chunk 的多字节字符不再被解成替换符(review 2026-09-07)
|
|
94
|
-
const outDec = new TextDecoder();
|
|
95
|
-
const errDec = new TextDecoder();
|
|
96
|
-
child.stdout!.on("data", (d: Buffer) => bg.write(outDec.decode(d, { stream: true })));
|
|
97
|
-
child.stderr!.on("data", (d: Buffer) => bg.write(errDec.decode(d, { stream: true })));
|
|
98
|
-
bg.signal.addEventListener("abort", () => killTree(child), { once: true });
|
|
99
|
-
child.on("error", rejectPromise);
|
|
100
|
-
child.on("close", (code) => {
|
|
101
|
-
bg.write(outDec.decode()); // 冲残余
|
|
102
|
-
bg.write(errDec.decode());
|
|
103
|
-
if (code === 0 || bg.signal.aborted) resolvePromise();
|
|
104
|
-
else rejectPromise(new Error(`exit code ${code}`));
|
|
105
|
-
});
|
|
106
|
-
}),
|
|
107
|
-
});
|
|
108
|
-
if (!r.ok) {
|
|
109
|
-
return toolError(
|
|
110
|
-
r.reason === "too_many_running"
|
|
111
|
-
? `${r.running}/${r.max} background jobs are already running; collect some first`
|
|
112
|
-
: `The background queue is full (${r.tasks}/${r.max})`,
|
|
113
|
-
);
|
|
114
|
-
}
|
|
115
|
-
return toolOk(
|
|
116
|
-
`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)`,
|
|
117
|
-
{ taskId: r.task.id },
|
|
118
|
-
);
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
const start = startDir(ctx.workspace);
|
|
122
|
-
const result = await runForeground(command, start.cwd, timeout_ms ?? DEFAULT_TIMEOUT_MS, ctx.signal);
|
|
123
|
-
// 命令跑到了末尾才有标记(exec / 被杀 / 语法错都没有):没有就保持原来的目录
|
|
124
|
-
const changed = result.cwd !== undefined && result.cwd !== start.cwd;
|
|
125
|
-
if (result.cwd !== undefined) state.cwd = result.cwd === ctx.workspace ? undefined : result.cwd;
|
|
126
|
-
const note = `${start.note}${changed ? `\n(working directory is now ${result.cwd})` : ""}`;
|
|
127
|
-
return note === "" ? result : { ...result, content: `${result.content}${note}` };
|
|
128
|
-
},
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/** 把命令包一层:跑完打印 `$PWD` 标记、再以命令自己的退出码退出。`{ … }` 分组让多行命令与末尾注释都成立。 */
|
|
133
|
-
function withCwdMarker(command: string): string {
|
|
134
|
-
return `{\n${command}\n}\n__echo_rc=$?\nprintf '\\n\\036__ECHO_CWD__%s\\036\\n' "$PWD"\nexit $__echo_rc`;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* 起 shell 时自成一个进程组(detached):杀的时候按组杀({@link killTree})。
|
|
139
|
-
* 不然 `sleep 10`、dev server 这类由 bash 再起的子进程会活过 bash,攥着输出管道不放——超时/中止要等它自己结束,job_stop 也留孤儿。
|
|
140
|
-
*/
|
|
141
|
-
function spawnShell(command: string, cwd: string): ChildProcess {
|
|
142
|
-
return spawn("bash", ["-lc", command], { cwd, stdio: ["ignore", "pipe", "pipe"], detached: true });
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
function killTree(child: ChildProcess): void {
|
|
146
|
-
if (child.pid === undefined) return;
|
|
147
|
-
try {
|
|
148
|
-
process.kill(-child.pid, "SIGKILL");
|
|
149
|
-
} catch {
|
|
150
|
-
child.kill("SIGKILL");
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/** 错误里把已知作业列出来:模型丢了 id(压缩之后常见)也能找回来,不用再多一件 job_list。 */
|
|
155
|
-
function knownJobs(bg: AgentBackground): string {
|
|
156
|
-
const all = listBackground(bg.tasks);
|
|
157
|
-
return all.length === 0 ? "there are no background jobs" : `known jobs: ${all.map((t) => `${t.id} [${t.status}] ${t.label}`).join("; ")}`;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
function jobOutputTool(deps: BashDeps): ModelTool<{ id: string; tail?: number }> {
|
|
161
|
-
return {
|
|
162
|
-
kind: "model",
|
|
163
|
-
name: "job_output",
|
|
164
|
-
label: "看后台输出",
|
|
165
|
-
description:
|
|
166
|
-
"Show the status and the most recent output of a background job started with bash background: true. " +
|
|
167
|
-
"The output is a bounded buffer; tail limits how many trailing characters come back (default 4000).",
|
|
168
|
-
parameters: {
|
|
169
|
-
type: "object",
|
|
170
|
-
properties: {
|
|
171
|
-
id: { type: "string", description: "The job id returned by bash" },
|
|
172
|
-
tail: { type: "number", description: "Trailing characters to return, default 4000" },
|
|
173
|
-
},
|
|
174
|
-
required: ["id"],
|
|
175
|
-
},
|
|
176
|
-
async execute({ id, tail }) {
|
|
177
|
-
if (deps.background === undefined) return toolError("This agent has no background queue");
|
|
178
|
-
const task = getBackground(deps.background.tasks, id);
|
|
179
|
-
if (task === undefined) return toolError(`No such job: ${id}; ${knownJobs(deps.background)}`);
|
|
180
|
-
// `tail()` 只看一眼不动游标:结束通知那条路走的是 readNew(),两边互不吃掉对方的增量
|
|
181
|
-
const text = task.buffer.tail(Math.max(1, tail ?? JOB_TAIL_DEFAULT));
|
|
182
|
-
const head = `${task.id} [${task.status}] ${task.label}${task.error === null ? "" : ` — ${task.error}`}`;
|
|
183
|
-
return toolOk(`${head}\n${text === "" ? "(no output yet)" : text}`, { id, status: task.status });
|
|
184
|
-
},
|
|
185
|
-
};
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
function jobStopTool(deps: BashDeps): ModelTool<{ id: string }> {
|
|
189
|
-
return {
|
|
190
|
-
kind: "model",
|
|
191
|
-
name: "job_stop",
|
|
192
|
-
label: "停后台作业",
|
|
193
|
-
description: "Stop a running background job (it is killed). A job that already ended is left as it is.",
|
|
194
|
-
parameters: {
|
|
195
|
-
type: "object",
|
|
196
|
-
properties: { id: { type: "string", description: "The job id returned by bash" } },
|
|
197
|
-
required: ["id"],
|
|
198
|
-
},
|
|
199
|
-
async execute({ id }) {
|
|
200
|
-
if (deps.background === undefined) return toolError("This agent has no background queue");
|
|
201
|
-
const task = getBackground(deps.background.tasks, id);
|
|
202
|
-
if (task === undefined) return toolError(`No such job: ${id}; ${knownJobs(deps.background)}`);
|
|
203
|
-
if (task.status !== "running") return toolOk(`${id} had already ended (${task.status})`, { id, status: task.status });
|
|
204
|
-
const stopped = await killBackground(deps.background.tasks, id);
|
|
205
|
-
return stopped
|
|
206
|
-
? toolOk(`Stopped ${id} (${task.label})`, { id, status: task.status })
|
|
207
|
-
: toolError(`Could not stop ${id}; it is ${task.status}`);
|
|
208
|
-
},
|
|
209
|
-
};
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
function runForeground(
|
|
213
|
-
command: string,
|
|
214
|
-
cwd: string,
|
|
215
|
-
timeoutMs: number,
|
|
216
|
-
signal?: AbortSignal,
|
|
217
|
-
): Promise<AgentToolResult & { cwd?: string }> {
|
|
218
|
-
return new Promise((resolvePromise) => {
|
|
219
|
-
const child = spawnShell(withCwdMarker(command), cwd);
|
|
220
|
-
let out = "";
|
|
221
|
-
let truncated = false;
|
|
222
|
-
let tail = ""; // 末尾几百字节单独留着:cwd 标记在这里找,输出被截断也丢不了
|
|
223
|
-
const append = (chunk: string): void => {
|
|
224
|
-
tail = (tail + chunk).slice(-CWD_TAIL_KEEP);
|
|
225
|
-
if (out.length >= CAPTURE_CAP) {
|
|
226
|
-
truncated = true;
|
|
227
|
-
return;
|
|
228
|
-
}
|
|
229
|
-
out += chunk;
|
|
230
|
-
};
|
|
231
|
-
// 每条流一只流式 decoder:跨 chunk 的多字节字符不再被解成替换符(review 2026-09-07:此前逐块 toString)
|
|
232
|
-
const outDec = new TextDecoder();
|
|
233
|
-
const errDec = new TextDecoder();
|
|
234
|
-
child.stdout!.on("data", (d: Buffer) => append(outDec.decode(d, { stream: true })));
|
|
235
|
-
child.stderr!.on("data", (d: Buffer) => append(errDec.decode(d, { stream: true })));
|
|
236
|
-
|
|
237
|
-
let timedOut = false;
|
|
238
|
-
const timer = setTimeout(() => {
|
|
239
|
-
timedOut = true;
|
|
240
|
-
killTree(child);
|
|
241
|
-
}, timeoutMs);
|
|
242
|
-
const onAbort = (): void => {
|
|
243
|
-
killTree(child);
|
|
244
|
-
};
|
|
245
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
246
|
-
|
|
247
|
-
const finish = (code: number | null, spawnError?: string): void => {
|
|
248
|
-
clearTimeout(timer);
|
|
249
|
-
signal?.removeEventListener("abort", onAbort);
|
|
250
|
-
append(outDec.decode()); // 冲残余
|
|
251
|
-
append(errDec.decode());
|
|
252
|
-
// 先把 cwd 标记摘出来(在 tail 里),再从正文里剥掉——正文没被截断时标记就在正文末尾
|
|
253
|
-
const marked = CWD_MARK_RE.exec(tail);
|
|
254
|
-
const newCwd = marked?.[1];
|
|
255
|
-
const body = marked === null ? out : out.replace(CWD_MARK_RE, "").replace(/\n$/, "");
|
|
256
|
-
let text = body.slice(0, CAPTURE_CAP);
|
|
257
|
-
if (truncated || body.length > CAPTURE_CAP) text += `\n…[output truncated: over ${CAPTURE_CAP} characters]`;
|
|
258
|
-
const withCwd = (r: AgentToolResult): AgentToolResult & { cwd?: string } => (newCwd === undefined ? r : { ...r, cwd: newCwd });
|
|
259
|
-
if (spawnError !== undefined) {
|
|
260
|
-
resolvePromise(toolError(`The command could not start: ${spawnError}`));
|
|
261
|
-
} else if (timedOut) {
|
|
262
|
-
resolvePromise(toolError(`Timed out after ${timeoutMs} ms and was killed. Output:\n${text}`));
|
|
263
|
-
} else if (signal?.aborted === true) {
|
|
264
|
-
resolvePromise(toolError(`Aborted. Output:\n${text}`));
|
|
265
|
-
} else if (code !== 0) {
|
|
266
|
-
// 非零退出是**结果**不是异常——模型要看到输出来决定下一步
|
|
267
|
-
resolvePromise(withCwd(toolError(`exit code ${code}\n${text}`, { exitCode: code })));
|
|
268
|
-
} else {
|
|
269
|
-
resolvePromise(withCwd(toolOk(text === "" ? "(no output)" : text, { exitCode: 0 })));
|
|
270
|
-
}
|
|
271
|
-
};
|
|
272
|
-
child.on("error", (e) => finish(null, String(e)));
|
|
273
|
-
child.on("close", (code) => finish(code));
|
|
274
|
-
});
|
|
275
|
-
}
|
package/src/tools/fs.ts
DELETED
|
@@ -1,231 +0,0 @@
|
|
|
1
|
-
// 文件三件套:read_file / write_file / edit_file。
|
|
2
|
-
//
|
|
3
|
-
// 这些是**产品层工具**(对外部世界动手),所以住这儿不住 core(判据 2026-08-04 拍定)。
|
|
4
|
-
// 路径纪律:相对路径以 ctx.workspace 解析,**解析结果必须落在 workspace 之内**——
|
|
5
|
-
// 越界一律拒绝(`../../etc/passwd` 这类,不管是模型手滑还是注入)。workspace 是 session 级事实(2026-09-01),
|
|
6
|
-
// 既是起点也是边界,一个字段。这道边界是**六件工作区工具共用的一条**(`resolveSafe`,search.ts 也走它),
|
|
7
|
-
// 解 symlink(review 2026-09-07:此前只比字符串前缀,工作区里一条软链就能读写外面)。bash 不在这道边界内——
|
|
8
|
-
// 它是有意留的出口,像 Claude Code 的 Bash 一样能 cd 到任何地方,看着它的是 permission 策略,不是路径。
|
|
9
|
-
//
|
|
10
|
-
// description 与结果文本是模型逐字读的资产(全英文,2026-09-01);跨工具的用法(先读后改、glob/grep 优先)
|
|
11
|
-
// 在 `prompt.ts` 的 `tool:workspace` 段,这里只讲单个工具自己的语义。
|
|
12
|
-
|
|
13
|
-
import { mkdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
|
|
14
|
-
import { dirname, isAbsolute, resolve, sep } from "node:path";
|
|
15
|
-
import { toolError, toolOk, type ModelTool, type ToolExecutionContext } from "@echo-agent/core";
|
|
16
|
-
import { isImagePath, loadImageFile } from "@echo-agent/base";
|
|
17
|
-
|
|
18
|
-
/** 读回显的上限:超过就截断并标注——一个 50MB 的日志不该挤爆上下文。 */
|
|
19
|
-
const READ_CAP = 50_000;
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* **改前必读、读后未变**(2026-09-01 用户拍板,照 Claude Code 的 Edit / Write 门):
|
|
23
|
-
* `edit_file` / `write_file` 只接受本会话用 `read_file` 读过、且盘上自那次读之后没被别人改过的文件
|
|
24
|
-
* (mtime 相等判据)。此前只在 description 里写了一句「先读」——那是纪律不是门:模型没读就改、
|
|
25
|
-
* 或者用户在编辑器里刚改过的文件被模型按旧内容覆盖,都不会被拦住。
|
|
26
|
-
*
|
|
27
|
-
* 一张表跟着一次 `makeFsTools()` 走(= 一个 agent):键是绝对路径,值是读到 / 我们自己写完时的 mtime。
|
|
28
|
-
* 新建文件(盘上不存在)不需要先读。
|
|
29
|
-
*/
|
|
30
|
-
type SeenFiles = Map<string, number>;
|
|
31
|
-
|
|
32
|
-
export function makeFsTools(): ModelTool[] {
|
|
33
|
-
const seen: SeenFiles = new Map();
|
|
34
|
-
return [readFileTool(seen), writeFileTool(seen), editFileTool(seen)] as ModelTool[];
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* 改之前的门。返回 null = 可以改;否则是给模型看的拒绝理由。
|
|
39
|
-
* `exists` 由调用方决定新建文件算不算(`write_file` 新建不用先读)。
|
|
40
|
-
*/
|
|
41
|
-
async function assertFreshlyRead(seen: SeenFiles, abs: string, path: string): Promise<string | null> {
|
|
42
|
-
const st = await stat(abs).catch(() => null);
|
|
43
|
-
if (st === null) return null; // 不存在:write_file 新建;edit_file 随后读文件时会报 File not found
|
|
44
|
-
const readAt = seen.get(abs);
|
|
45
|
-
if (readAt === undefined) return `Read ${path} with read_file before changing it`;
|
|
46
|
-
if (st.mtimeMs !== readAt) return `${path} changed on disk since you read it; read it again before changing it`;
|
|
47
|
-
return null;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/** 读完 / 写完之后记下盘上的 mtime。 */
|
|
51
|
-
async function markSeen(seen: SeenFiles, abs: string): Promise<void> {
|
|
52
|
-
const st = await stat(abs).catch(() => null);
|
|
53
|
-
if (st !== null) seen.set(abs, st.mtimeMs);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* 解析 + 越界守卫:六件工作区工具(read_file / write_file / edit_file / list_dir / glob / grep)共用的**唯一**边界。
|
|
58
|
-
* 返回 null = 越界。
|
|
59
|
-
*
|
|
60
|
-
* 两道判据(照 core `storage/file-dir.ts#resolveSafe`):先按字面比前缀(挡 `../` 与绝对路径),
|
|
61
|
-
* 再把**最近的已存在祖先** realpath 之后比一次——字面判据对 symlink 无话可说,工作区里一条
|
|
62
|
-
* `link -> /etc` 的软链,`link/passwd` 字面上完全在工作区内。用祖先是因为目标本身可能还不存在
|
|
63
|
-
* (write_file 正要创建它);祖先在工作区之内,那么在它下面新建的东西也在。
|
|
64
|
-
* **write_file 必须先过这一关再 mkdir**:`mkdir(..., {recursive:true})` 会顺着软链在外面把目录建出来。
|
|
65
|
-
*
|
|
66
|
-
* 返回的是字面路径(不是 realpath):后面的读写照常跟着软链走,结果仍在工作区内;结果文案里也不该
|
|
67
|
-
* 冒出 `/private/var/...` 这种展开后的路径。
|
|
68
|
-
*/
|
|
69
|
-
export async function resolveSafe(ctx: ToolExecutionContext, path: string): Promise<string | null> {
|
|
70
|
-
const abs = isAbsolute(path) ? resolve(path) : resolve(ctx.workspace, path);
|
|
71
|
-
const root = resolve(ctx.workspace);
|
|
72
|
-
if (abs !== root && !abs.startsWith(root + sep)) return null;
|
|
73
|
-
|
|
74
|
-
let realRoot: string;
|
|
75
|
-
try {
|
|
76
|
-
realRoot = await realpath(root);
|
|
77
|
-
} catch {
|
|
78
|
-
return abs; // 工作区目录本身不存在 → 里面不可能有软链;后面的读写会自己报 not found
|
|
79
|
-
}
|
|
80
|
-
let cursor = abs;
|
|
81
|
-
let real: string | null = null;
|
|
82
|
-
while (real === null) {
|
|
83
|
-
try {
|
|
84
|
-
real = await realpath(cursor);
|
|
85
|
-
} catch (e) {
|
|
86
|
-
if ((e as { code?: string }).code !== "ENOENT") return null; // 读不出来(权限、循环软链):按越界拒,不猜
|
|
87
|
-
const parent = dirname(cursor);
|
|
88
|
-
if (parent === cursor) return abs; // 一路到文件系统根都不存在
|
|
89
|
-
cursor = parent;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
return real === realRoot || real.startsWith(realRoot + sep) ? abs : null;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
function readFileTool(seen: SeenFiles): ModelTool<{ path: string; offset?: number; limit?: number }> {
|
|
96
|
-
return {
|
|
97
|
-
kind: "model",
|
|
98
|
-
name: "read_file",
|
|
99
|
-
label: "读文件",
|
|
100
|
-
// 只读:模型一口气读五个文件时同批同跑。`seen` 只按路径记一条 mtime,同批互不覆盖。
|
|
101
|
-
concurrent: true,
|
|
102
|
-
// 自己会分页(行数 + `READ_CAP` 截断并教 offset/limit),不走 core 的外存——外存再读一遍是绕路(2026-11-02,同 Claude Code 的 Read)
|
|
103
|
-
maxInlineTokens: Infinity,
|
|
104
|
-
description:
|
|
105
|
-
"Read a file with line numbers. Use offset/limit to read a large file in parts. Read a file before editing it. " +
|
|
106
|
-
"PNG, JPEG, GIF and WebP files are returned as images you can see; large ones are scaled down first.",
|
|
107
|
-
parameters: {
|
|
108
|
-
type: "object",
|
|
109
|
-
properties: {
|
|
110
|
-
path: { type: "string", description: "Path relative to the workspace" },
|
|
111
|
-
offset: { type: "number", description: "First line to read (1-based), default from the start" },
|
|
112
|
-
limit: { type: "number", description: "Maximum number of lines, default 2000" },
|
|
113
|
-
},
|
|
114
|
-
required: ["path"],
|
|
115
|
-
},
|
|
116
|
-
async execute({ path, offset, limit }, ctx) {
|
|
117
|
-
const abs = await resolveSafe(ctx, path);
|
|
118
|
-
if (abs === null) return toolError(`Path outside the workspace: '${path}'`);
|
|
119
|
-
// 图片按图片返回(2026-11-02,照 Claude Code 的 Read):大了先缩放。文件不存在、或扩展名是图片但内容不是,
|
|
120
|
-
// 落到下面照文本读(不存在就报 File not found)
|
|
121
|
-
if (isImagePath(abs)) {
|
|
122
|
-
const loaded = await loadImageFile(abs);
|
|
123
|
-
if (loaded.ok) {
|
|
124
|
-
const { width, height } = loaded.info;
|
|
125
|
-
const scaled = loaded.original === undefined ? "" : `, scaled down from ${loaded.original.width}×${loaded.original.height}`;
|
|
126
|
-
return toolOk(`Image file ${path} (${width}×${height}${scaled})`, { path, width, height }, [loaded.image]);
|
|
127
|
-
}
|
|
128
|
-
if (loaded.reason === "too_large") {
|
|
129
|
-
return toolError(`Cannot read ${path} as an image: ${loaded.message}. Make a smaller copy (for example with ImageMagick via bash) and read that.`);
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
let raw: string;
|
|
133
|
-
try {
|
|
134
|
-
raw = await readFile(abs, "utf8");
|
|
135
|
-
} catch (e) {
|
|
136
|
-
return toolError(readErrText(e, path));
|
|
137
|
-
}
|
|
138
|
-
await markSeen(seen, abs); // 从这一刻起它才算「读过」:edit_file / write_file 的门看这个
|
|
139
|
-
const lines = raw.split("\n");
|
|
140
|
-
const from = Math.max(1, offset ?? 1);
|
|
141
|
-
const take = Math.max(1, limit ?? 2000);
|
|
142
|
-
const slice = lines.slice(from - 1, from - 1 + take);
|
|
143
|
-
let text = slice.map((l, i) => `${from + i}\t${l}`).join("\n");
|
|
144
|
-
if (text.length > READ_CAP) text = `${text.slice(0, READ_CAP)}\n…[truncated: over ${READ_CAP} characters, read in parts with offset/limit]`;
|
|
145
|
-
const tail = from - 1 + take < lines.length ? `\n…(${lines.length} lines in total, ${lines.length - (from - 1 + take)} not shown)` : "";
|
|
146
|
-
return toolOk(text + tail, { path, lines: lines.length });
|
|
147
|
-
},
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
function writeFileTool(seen: SeenFiles): ModelTool<{ path: string; content: string }> {
|
|
152
|
-
return {
|
|
153
|
-
kind: "model",
|
|
154
|
-
name: "write_file",
|
|
155
|
-
label: "写文件",
|
|
156
|
-
description:
|
|
157
|
-
"Write a whole file (created if missing, parent directories created). To change an existing file prefer edit_file; overwriting loses whatever you did not notice. " +
|
|
158
|
-
"An existing file must have been read with read_file in this session and be unchanged on disk since.",
|
|
159
|
-
parameters: {
|
|
160
|
-
type: "object",
|
|
161
|
-
properties: {
|
|
162
|
-
path: { type: "string", description: "Path relative to the workspace" },
|
|
163
|
-
content: { type: "string", description: "The full file content" },
|
|
164
|
-
},
|
|
165
|
-
required: ["path", "content"],
|
|
166
|
-
},
|
|
167
|
-
async execute({ path, content }, ctx) {
|
|
168
|
-
const abs = await resolveSafe(ctx, path); // 必须在 mkdir 之前:递归建目录会顺着软链把目录建到外面
|
|
169
|
-
if (abs === null) return toolError(`Path outside the workspace: '${path}'`);
|
|
170
|
-
const refused = await assertFreshlyRead(seen, abs, path); // 新建不用先读;覆盖已有的必须
|
|
171
|
-
if (refused !== null) return toolError(refused);
|
|
172
|
-
await mkdir(dirname(abs), { recursive: true });
|
|
173
|
-
await writeFile(abs, content, "utf8");
|
|
174
|
-
await markSeen(seen, abs); // 自己写的算读过:接着 edit_file 不用再读一遍
|
|
175
|
-
return toolOk(`Wrote ${path} (${content.length} characters)`, { path, bytes: content.length });
|
|
176
|
-
},
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
function editFileTool(seen: SeenFiles): ModelTool<{ path: string; old_string: string; new_string: string; replace_all?: boolean }> {
|
|
181
|
-
return {
|
|
182
|
-
kind: "model",
|
|
183
|
-
name: "edit_file",
|
|
184
|
-
label: "改文件",
|
|
185
|
-
description:
|
|
186
|
-
"Exact replacement: old_string must match the file content byte for byte (including indentation) and occur exactly once. " +
|
|
187
|
-
"If it matches several places, give more surrounding context or set replace_all: true. " +
|
|
188
|
-
"The file must have been read with read_file in this session and be unchanged on disk since.",
|
|
189
|
-
parameters: {
|
|
190
|
-
type: "object",
|
|
191
|
-
properties: {
|
|
192
|
-
path: { type: "string" },
|
|
193
|
-
old_string: { type: "string", description: "The exact text to replace (byte for byte, including indentation)" },
|
|
194
|
-
new_string: { type: "string", description: "The replacement text" },
|
|
195
|
-
replace_all: { type: "boolean", description: "Replace every match; default false (the match must be unique)" },
|
|
196
|
-
},
|
|
197
|
-
required: ["path", "old_string", "new_string"],
|
|
198
|
-
},
|
|
199
|
-
async execute({ path, old_string, new_string, replace_all }, ctx) {
|
|
200
|
-
const abs = await resolveSafe(ctx, path);
|
|
201
|
-
if (abs === null) return toolError(`Path outside the workspace: '${path}'`);
|
|
202
|
-
if (old_string === new_string) return toolError("old_string and new_string are identical; nothing to change");
|
|
203
|
-
// 空 old_string 会在每个字符之间插入(split("") 匹配文件长度次),replace_all 时静默毁掉整个文件(review 2026-09-07)
|
|
204
|
-
if (old_string === "") {
|
|
205
|
-
return toolError("old_string must not be empty; to insert text, include the line you are inserting next to as context (or use write_file for a new file)");
|
|
206
|
-
}
|
|
207
|
-
const refused = await assertFreshlyRead(seen, abs, path);
|
|
208
|
-
if (refused !== null) return toolError(refused);
|
|
209
|
-
let raw: string;
|
|
210
|
-
try {
|
|
211
|
-
raw = await readFile(abs, "utf8");
|
|
212
|
-
} catch (e) {
|
|
213
|
-
return toolError(readErrText(e, path));
|
|
214
|
-
}
|
|
215
|
-
const count = raw.split(old_string).length - 1;
|
|
216
|
-
if (count === 0) return toolError("No match: old_string must equal the file content byte for byte (including indentation). Read the file with read_file and copy it exactly");
|
|
217
|
-
if (count > 1 && replace_all !== true) {
|
|
218
|
-
return toolError(`${count} matches: add surrounding context to make old_string unique, or set replace_all: true`);
|
|
219
|
-
}
|
|
220
|
-
// 替换文本用函数给:字符串形式会解释 `$&` / `$$` 这类模式,new_string 里带 `$` 的代码就会被替错
|
|
221
|
-
const next = replace_all === true ? raw.split(old_string).join(new_string) : raw.replace(old_string, () => new_string);
|
|
222
|
-
await writeFile(abs, next, "utf8");
|
|
223
|
-
await markSeen(seen, abs); // 连续几次 edit 不用中间重读
|
|
224
|
-
return toolOk(`Replaced ${replace_all === true ? count : 1} occurrence(s) in ${path}`, { path, replaced: count });
|
|
225
|
-
},
|
|
226
|
-
};
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
function readErrText(e: unknown, path: string): string {
|
|
230
|
-
return (e as { code?: string }).code === "ENOENT" ? `File not found: ${path}` : `Read failed: ${String(e)}`;
|
|
231
|
-
}
|