@echo-agent/coding 0.7.0 → 0.9.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.
@@ -1,273 +0,0 @@
1
- // 搜索两件套:glob(找文件)/ grep(找内容)。用 Bun.Glob 与 git,零依赖。
2
- //
3
- // **候选文件从哪来**(`candidateFiles`):起点在 git 工作树里,就取 `git ls-files --cached --others --exclude-standard`
4
- // ——跟踪的文件加上没被忽略的新文件,与 ripgrep 的忽略语义一致:被 .gitignore 的 dist / build 不进来,
5
- // .github 这类点目录照进。不在 git 工作树里(或 git 不可用)就目录遍历,点目录同样照进。
6
- // git 列出来一个都没有(点名的目录整个被忽略)也退回目录遍历:点名了就是要搜它。
7
- // node_modules / .git 两种来源都恒排除——那里面的匹配对写代码没用,还会把结果挤爆。软链不跟(目录遍历本就不跟,
8
- // git 列出的软链也跳过):经软链可以出工作区,边界只在起点 `path` 上查过一次。
9
- // 结果**按路径排序之后再截**,截断时说出总数——按扫描顺序截,留下的是哪些全凭目录遍历的顺序。
10
- //
11
- // **`path` 指到文件就只搜这一个文件**(2026-09-01,实测 bug):模型把 grep 当 `grep <pattern> <file>` 用是常态,
12
- // 此前把文件当 cwd 交给 Bun.Glob,甩给模型一句 `ENOTDIR: not a directory`,相对、绝对路径都炸。
13
- // glob 拿到文件则明说「要目录」并指回 grep——静默返回 0 个匹配是「写了没生效」。
14
- //
15
- // **结果路径一律相对工作区**:read_file / edit_file 收的是工作区相对路径,搜索若按 `path` 相对报
16
- // (在 `packages/core/src` 里搜到 `agent.ts:260`),模型拿着 `agent.ts` 去读就找不到。
17
- //
18
- // **边界与文件三件套同一条**(review 2026-09-07):`path` 经 fs.ts 的 `resolveInWorkspace` 解析,越界(含经软链)一律拒。
19
- // 此前这三件没有任何边界,而 system 段对模型说的是「工作区之外的路径会被拒」——契约与实现两张皮,
20
- // 且凡是把 bash 设成 ask 的策略,grep 都是绕开那道门读整块盘的路。
21
-
22
- import { lstat, readdir, readFile, stat } from "node:fs/promises";
23
- import { relative, resolve } from "node:path";
24
- import { toolError, toolOk, type ModelTool, type ToolExecutionContext } from "@echo-agent/core";
25
- import { resolveInWorkspace } from "./fs.ts";
26
-
27
- const GLOB_CAP = 500;
28
- /** grep 最多回这么多条(content 是行,另两种是文件)。 */
29
- const GREP_CAP = 200;
30
- const GREP_FILE_MAX = 1_000_000; // >1MB 的文件跳过(多半是产物/数据,不是代码),跳过几个在结果尾部说
31
- const LINE_CAP = 250;
32
- const LIST_CAP = 500;
33
-
34
- const EXCLUDED = /(^|\/)(node_modules|\.git)(\/|$)/;
35
-
36
- const OUTPUT_MODES = ["content", "files_with_matches", "count"] as const;
37
- type OutputMode = (typeof OUTPUT_MODES)[number];
38
-
39
- /** 说明排除规则的那一句:glob 与 grep 的 description 共用。 */
40
- const SCOPE_TEXT =
41
- "Inside a git repository it searches the files git sees (tracked plus untracked, honoring .gitignore), otherwise every file under path; " +
42
- "dot-directories such as .github are included, .git and node_modules never are, symlinks are not followed. " +
43
- "Naming an ignored directory as path searches it.";
44
-
45
- /** 搜索三件:glob / grep / list_dir。`list_dir` 是 2026-09-02 补的——glob 只出文件,模型看不到目录结构,只能 `bash ls`。 */
46
- export function makeSearchTools(): ModelTool[] {
47
- return [globTool(), grepTool(), listDirTool()] as ModelTool[];
48
- }
49
-
50
- /** 结果里怎么报这个文件:相对工作区——起点已经过了越界守卫,结果只可能在工作区内。 */
51
- function display(ctx: ToolExecutionContext, abs: string): string {
52
- return relative(ctx.workspace, abs);
53
- }
54
-
55
- type Target = { ok: true; kind: "file" | "dir"; abs: string } | { ok: false; error: string };
56
-
57
- /** `path` → 搜索起点。越界、不存在、是文件、是目录分开说,错误文案要让模型知道下一步怎么办。 */
58
- async function resolveTarget(ctx: ToolExecutionContext, path?: string): Promise<Target> {
59
- const safe = path === undefined || path === "" ? { ok: true as const, abs: resolve(ctx.workspace) } : await resolveInWorkspace(ctx, path);
60
- if (!safe.ok) return { ok: false, error: safe.error };
61
- const abs = safe.abs;
62
- const st = await stat(abs).catch(() => null);
63
- if (st === null) return { ok: false, error: `path not found: ${path ?? abs}` };
64
- return { ok: true, kind: st.isFile() ? "file" : "dir", abs };
65
- }
66
-
67
- /**
68
- * 目录 `dir` 下匹配 `pattern` 的文件,绝对路径、按路径排好。来源见文件头:git 工作树里取 git 认的文件,否则目录遍历;
69
- * node_modules / .git 恒排除,软链不跟。
70
- */
71
- async function candidateFiles(dir: string, pattern: string): Promise<string[]> {
72
- const glob = new Bun.Glob(pattern);
73
- const rels: string[] = [];
74
- const listed = await gitListFiles(dir);
75
- if (listed !== null && listed.length > 0) {
76
- for (const p of listed) {
77
- if (EXCLUDED.test(p) || !glob.match(p)) continue;
78
- // 已删未提交(index 里还有)、子模块(目录)、软链:都不是这里要读的普通文件,与目录遍历同一口径
79
- const st = await lstat(resolve(dir, p)).catch(() => null);
80
- if (st?.isFile() === true) rels.push(p);
81
- }
82
- } else {
83
- for await (const p of glob.scan({ cwd: dir, onlyFiles: true, dot: true })) {
84
- if (!EXCLUDED.test(p)) rels.push(p);
85
- }
86
- }
87
- rels.sort();
88
- return rels.map((p) => resolve(dir, p));
89
- }
90
-
91
- /** `dir` 下 git 认的文件(相对 `dir`,去重)。不是 git 工作树、git 不可用 → null。 */
92
- async function gitListFiles(dir: string): Promise<string[] | null> {
93
- try {
94
- const proc = Bun.spawn(["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], {
95
- cwd: dir,
96
- stdin: "ignore",
97
- stdout: "pipe",
98
- stderr: "ignore",
99
- });
100
- const out = await new Response(proc.stdout).text();
101
- if ((await proc.exited) !== 0) return null;
102
- // 有冲突时 --cached 会把同一路径按 stage 列好几遍
103
- return [...new Set(out.split("\0").filter((p) => p !== ""))];
104
- } catch {
105
- return null;
106
- }
107
- }
108
-
109
- function globTool(): ModelTool<{ pattern: string; path?: string }> {
110
- return {
111
- kind: "model",
112
- name: "glob",
113
- label: "找文件",
114
- concurrent: true, // 只读
115
- description:
116
- `Find files by glob pattern, e.g. "**/*.ts" or "src/**/*.test.ts". Returns paths relative to the workspace, sorted, at most ${GLOB_CAP}. ` +
117
- SCOPE_TEXT,
118
- parameters: {
119
- type: "object",
120
- properties: {
121
- pattern: { type: "string" },
122
- path: { type: "string", description: "Directory to start from, default the workspace" },
123
- },
124
- required: ["pattern"],
125
- },
126
- async execute({ pattern, path }, ctx) {
127
- const target = await resolveTarget(ctx, path);
128
- if (!target.ok) return toolError(target.error);
129
- if (target.kind === "file") {
130
- return toolError(`path is a file, glob needs a directory: ${path}. To search inside one file, use grep with path=${path}.`);
131
- }
132
- let all: string[];
133
- try {
134
- all = await candidateFiles(target.abs, pattern);
135
- } catch (e) {
136
- return toolError(`glob failed: ${String(e)}`);
137
- }
138
- const shown = all.slice(0, GLOB_CAP).map((abs) => display(ctx, abs));
139
- const cap = all.length > GLOB_CAP ? `\n…[${all.length} files match; showing the first ${GLOB_CAP} by path. Narrow the pattern or path]` : "";
140
- return toolOk(shown.length === 0 ? "(no matches)" : shown.join("\n") + cap, { count: all.length });
141
- },
142
- };
143
- }
144
-
145
- function listDirTool(): ModelTool<{ path?: string }> {
146
- return {
147
- kind: "model",
148
- name: "list_dir",
149
- label: "列目录",
150
- concurrent: true, // 只读
151
- description:
152
- "List the entries of one directory, not recursive: subdirectories first and marked with a trailing '/'. Default the workspace root. To find files by pattern use glob.",
153
- parameters: {
154
- type: "object",
155
- properties: {
156
- path: { type: "string", description: "Directory to list, default the workspace" },
157
- },
158
- },
159
- async execute({ path }, ctx) {
160
- const target = await resolveTarget(ctx, path);
161
- if (!target.ok) return toolError(target.error);
162
- if (target.kind === "file") return toolError(`path is a file, list_dir needs a directory: ${path}. Use read_file to read it.`);
163
- let entries: { name: string; isDirectory(): boolean }[];
164
- try {
165
- entries = await readdir(target.abs, { withFileTypes: true });
166
- } catch (e) {
167
- return toolError(`list_dir failed: ${String(e)}`);
168
- }
169
- // 目录在前、各自按名排:一眼分得出结构。node_modules / .git 照列——这是目录的真相,不是搜索结果
170
- const dirs = entries.filter((e) => e.isDirectory()).map((e) => `${e.name}/`).sort();
171
- const files = entries.filter((e) => !e.isDirectory()).map((e) => e.name).sort();
172
- const all = [...dirs, ...files];
173
- const shown = all.slice(0, LIST_CAP);
174
- const cap = all.length > LIST_CAP ? `\n…[${all.length - LIST_CAP} more entries not shown]` : "";
175
- return toolOk(shown.length === 0 ? "(empty directory)" : shown.join("\n") + cap, { count: all.length });
176
- },
177
- };
178
- }
179
-
180
- type GrepParams = { pattern: string; path?: string; glob?: string; ignore_case?: boolean; output_mode?: string };
181
-
182
- /**
183
- * grep 的两个参数(2026-11-03 拍板,`docs/decisions/implemented/2026-11-03-grep-ignore-case-and-output-mode.md`):
184
- * `ignore_case`(JS 正则没有 `(?i)` 内联写法)与 `output_mode`——只要知道「哪些文件有」或「各有几处」时,
185
- * 不必把每一行都搬进上下文。缺省 `content`,与此前的输出逐字相同。
186
- */
187
- function grepTool(): ModelTool<GrepParams> {
188
- return {
189
- kind: "model",
190
- name: "grep",
191
- label: "找内容",
192
- concurrent: true, // 只读
193
- description:
194
- "Search file contents with a regular expression; paths in the results are relative to the workspace. " +
195
- "path may be a directory (searched recursively, narrowed by glob) or a single file (searched alone). " +
196
- `output_mode "content" (default) returns file:line:text, "files_with_matches" returns the matching files, "count" returns file:count. ` +
197
- `Results are sorted by path, at most ${GREP_CAP} entries; files over 1 MB are skipped and counted at the end. ${SCOPE_TEXT}`,
198
- parameters: {
199
- type: "object",
200
- properties: {
201
- pattern: { type: "string", description: "JavaScript regular expression (without slashes or inline flags)" },
202
- path: { type: "string", description: "Directory or file to search, default the workspace" },
203
- glob: { type: "string", description: 'Limit to these files when path is a directory, default "**/*"' },
204
- ignore_case: { type: "boolean", description: "Match case-insensitively, default false" },
205
- output_mode: { type: "string", enum: [...OUTPUT_MODES], description: 'What to return, default "content"' },
206
- },
207
- required: ["pattern"],
208
- },
209
- async execute({ pattern, path, glob, ignore_case, output_mode }, ctx) {
210
- const mode = (output_mode ?? "content") as OutputMode;
211
- if (!OUTPUT_MODES.includes(mode)) return toolError(`output_mode must be one of ${OUTPUT_MODES.join(", ")} (got '${output_mode}')`);
212
- let re: RegExp;
213
- try {
214
- re = new RegExp(pattern, ignore_case === true ? "i" : "");
215
- } catch (e) {
216
- const inline = /^\(\?[a-z]+\)/.test(pattern) ? " JavaScript regular expressions have no inline flags such as (?i); use ignore_case: true." : "";
217
- return toolError(`Invalid regular expression: ${String(e)}.${inline}`);
218
- }
219
- const target = await resolveTarget(ctx, path);
220
- if (!target.ok) return toolError(target.error);
221
- let files: string[];
222
- try {
223
- // 单文件:用户点名的那一个,不过 glob 也不过排除表——点名了就是要搜它
224
- files = target.kind === "file" ? [target.abs] : await candidateFiles(target.abs, glob ?? "**/*");
225
- } catch (e) {
226
- return toolError(`grep failed: ${String(e)}`);
227
- }
228
- const entries: string[] = [];
229
- let total = 0; // content = 匹配的行数;另两种 = 有匹配的文件数
230
- let scanned = 0;
231
- let tooLarge = 0;
232
- for (const abs of files) {
233
- const st = await stat(abs).catch(() => null);
234
- if (st === null) continue;
235
- if (st.size > GREP_FILE_MAX) {
236
- tooLarge += 1;
237
- continue;
238
- }
239
- let raw: string;
240
- try {
241
- raw = await readFile(abs, "utf8");
242
- } catch {
243
- continue; // 读不动的(权限)跳过
244
- }
245
- if (raw.includes("\u0000")) continue; // 二进制
246
- scanned += 1;
247
- const shown = display(ctx, abs);
248
- let inFile = 0;
249
- for (const [i, line] of raw.split("\n").entries()) {
250
- if (!re.test(line)) continue;
251
- inFile += 1;
252
- if (mode === "files_with_matches") break;
253
- if (mode === "content") {
254
- total += 1;
255
- if (entries.length < GREP_CAP) entries.push(`${shown}:${i + 1}:${line.length > LINE_CAP ? line.slice(0, LINE_CAP) + "…" : line}`);
256
- }
257
- }
258
- if (inFile > 0 && mode !== "content") {
259
- total += 1;
260
- if (entries.length < GREP_CAP) entries.push(mode === "count" ? `${shown}:${inFile}` : shown);
261
- }
262
- }
263
- const unit = mode === "content" ? "matching lines" : "files match";
264
- const cap = total > GREP_CAP ? `\n…[${total} ${unit} in total; showing the first ${GREP_CAP} by path. Narrow the pattern, path or glob]` : "";
265
- const skipped = tooLarge === 0 ? "" : `\n(${tooLarge} ${tooLarge === 1 ? "file" : "files"} over 1 MB not searched; search them with bash if you need to)`;
266
- return toolOk((entries.length === 0 ? `(no matches in ${scanned} files)` : entries.join("\n") + cap) + skipped, {
267
- matches: total,
268
- scanned,
269
- tooLarge,
270
- });
271
- },
272
- };
273
- }