@uncarved/jade 0.0.0-stage → 0.1.1

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.
Files changed (168) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +191 -2
  3. package/bin/jade.js +20 -0
  4. package/dist/commands.d.ts +30 -0
  5. package/dist/commands.js +106 -0
  6. package/dist/commands.js.map +1 -0
  7. package/dist/config.d.ts +34 -0
  8. package/dist/config.js +130 -0
  9. package/dist/config.js.map +1 -0
  10. package/dist/context.d.ts +17 -0
  11. package/dist/context.js +53 -0
  12. package/dist/context.js.map +1 -0
  13. package/dist/distro.d.ts +97 -0
  14. package/dist/distro.js +311 -0
  15. package/dist/distro.js.map +1 -0
  16. package/dist/history.d.ts +10 -0
  17. package/dist/history.js +47 -0
  18. package/dist/history.js.map +1 -0
  19. package/dist/index.d.ts +27 -0
  20. package/dist/index.js +28 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/main.d.ts +2 -0
  23. package/dist/main.js +1214 -0
  24. package/dist/main.js.map +1 -0
  25. package/dist/mcp.d.ts +114 -0
  26. package/dist/mcp.js +640 -0
  27. package/dist/mcp.js.map +1 -0
  28. package/dist/memory.d.ts +19 -0
  29. package/dist/memory.js +129 -0
  30. package/dist/memory.js.map +1 -0
  31. package/dist/mentions.d.ts +35 -0
  32. package/dist/mentions.js +130 -0
  33. package/dist/mentions.js.map +1 -0
  34. package/dist/plugin-cli.d.ts +16 -0
  35. package/dist/plugin-cli.js +251 -0
  36. package/dist/plugin-cli.js.map +1 -0
  37. package/dist/plugins/budget.d.ts +9 -0
  38. package/dist/plugins/budget.js +30 -0
  39. package/dist/plugins/budget.js.map +1 -0
  40. package/dist/plugins/builtins.d.ts +10 -0
  41. package/dist/plugins/builtins.js +22 -0
  42. package/dist/plugins/builtins.js.map +1 -0
  43. package/dist/plugins/checks.d.ts +70 -0
  44. package/dist/plugins/checks.js +335 -0
  45. package/dist/plugins/checks.js.map +1 -0
  46. package/dist/plugins/compact.d.ts +26 -0
  47. package/dist/plugins/compact.js +216 -0
  48. package/dist/plugins/compact.js.map +1 -0
  49. package/dist/plugins/core.d.ts +42 -0
  50. package/dist/plugins/core.js +190 -0
  51. package/dist/plugins/core.js.map +1 -0
  52. package/dist/plugins/install.d.ts +68 -0
  53. package/dist/plugins/install.js +377 -0
  54. package/dist/plugins/install.js.map +1 -0
  55. package/dist/plugins/loader.d.ts +182 -0
  56. package/dist/plugins/loader.js +253 -0
  57. package/dist/plugins/loader.js.map +1 -0
  58. package/dist/plugins/policy.d.ts +80 -0
  59. package/dist/plugins/policy.js +541 -0
  60. package/dist/plugins/policy.js.map +1 -0
  61. package/dist/plugins/prompts.d.ts +30 -0
  62. package/dist/plugins/prompts.js +182 -0
  63. package/dist/plugins/prompts.js.map +1 -0
  64. package/dist/plugins/repeats.d.ts +9 -0
  65. package/dist/plugins/repeats.js +90 -0
  66. package/dist/plugins/repeats.js.map +1 -0
  67. package/dist/plugins/schema.d.ts +2 -0
  68. package/dist/plugins/schema.js +64 -0
  69. package/dist/plugins/schema.js.map +1 -0
  70. package/dist/provider.d.ts +111 -0
  71. package/dist/provider.js +326 -0
  72. package/dist/provider.js.map +1 -0
  73. package/dist/sessions.d.ts +22 -0
  74. package/dist/sessions.js +53 -0
  75. package/dist/sessions.js.map +1 -0
  76. package/dist/skills.d.ts +37 -0
  77. package/dist/skills.js +179 -0
  78. package/dist/skills.js.map +1 -0
  79. package/dist/sys.d.ts +48 -0
  80. package/dist/sys.js +116 -0
  81. package/dist/sys.js.map +1 -0
  82. package/dist/tools/checkpoint.d.ts +43 -0
  83. package/dist/tools/checkpoint.js +144 -0
  84. package/dist/tools/checkpoint.js.map +1 -0
  85. package/dist/tools/fs.d.ts +35 -0
  86. package/dist/tools/fs.js +417 -0
  87. package/dist/tools/fs.js.map +1 -0
  88. package/dist/tools/grep.d.ts +6 -0
  89. package/dist/tools/grep.js +243 -0
  90. package/dist/tools/grep.js.map +1 -0
  91. package/dist/tools/screenshot.d.ts +15 -0
  92. package/dist/tools/screenshot.js +162 -0
  93. package/dist/tools/screenshot.js.map +1 -0
  94. package/dist/tools/shell.d.ts +55 -0
  95. package/dist/tools/shell.js +314 -0
  96. package/dist/tools/shell.js.map +1 -0
  97. package/dist/tools/task.d.ts +31 -0
  98. package/dist/tools/task.js +86 -0
  99. package/dist/tools/task.js.map +1 -0
  100. package/dist/tools/todo.d.ts +10 -0
  101. package/dist/tools/todo.js +55 -0
  102. package/dist/tools/todo.js.map +1 -0
  103. package/dist/tools/web.d.ts +23 -0
  104. package/dist/tools/web.js +426 -0
  105. package/dist/tools/web.js.map +1 -0
  106. package/dist/ui/configure.d.ts +20 -0
  107. package/dist/ui/configure.js +369 -0
  108. package/dist/ui/configure.js.map +1 -0
  109. package/dist/ui/diff.d.ts +20 -0
  110. package/dist/ui/diff.js +142 -0
  111. package/dist/ui/diff.js.map +1 -0
  112. package/dist/ui/editor.d.ts +33 -0
  113. package/dist/ui/editor.js +128 -0
  114. package/dist/ui/editor.js.map +1 -0
  115. package/dist/ui/render.d.ts +13 -0
  116. package/dist/ui/render.js +84 -0
  117. package/dist/ui/render.js.map +1 -0
  118. package/dist/ui/screen.d.ts +95 -0
  119. package/dist/ui/screen.js +105 -0
  120. package/dist/ui/screen.js.map +1 -0
  121. package/dist/ui/transcript.d.ts +33 -0
  122. package/dist/ui/transcript.js +372 -0
  123. package/dist/ui/transcript.js.map +1 -0
  124. package/dist/ui/tui.d.ts +45 -0
  125. package/dist/ui/tui.js +1107 -0
  126. package/dist/ui/tui.js.map +1 -0
  127. package/package.json +59 -4
  128. package/src/commands.ts +120 -0
  129. package/src/config.ts +146 -0
  130. package/src/context.ts +64 -0
  131. package/src/distro.ts +395 -0
  132. package/src/history.ts +55 -0
  133. package/src/index.ts +27 -0
  134. package/src/main.ts +1267 -0
  135. package/src/mcp.ts +693 -0
  136. package/src/memory.ts +135 -0
  137. package/src/mentions.ts +135 -0
  138. package/src/plugin-cli.ts +239 -0
  139. package/src/plugins/budget.ts +37 -0
  140. package/src/plugins/builtins.ts +31 -0
  141. package/src/plugins/checks.ts +390 -0
  142. package/src/plugins/compact.ts +257 -0
  143. package/src/plugins/core.ts +217 -0
  144. package/src/plugins/install.ts +429 -0
  145. package/src/plugins/loader.ts +386 -0
  146. package/src/plugins/policy.ts +578 -0
  147. package/src/plugins/prompts.ts +215 -0
  148. package/src/plugins/repeats.ts +96 -0
  149. package/src/plugins/schema.ts +67 -0
  150. package/src/provider.ts +363 -0
  151. package/src/sessions.ts +61 -0
  152. package/src/skills.ts +197 -0
  153. package/src/sys.ts +136 -0
  154. package/src/tools/checkpoint.ts +164 -0
  155. package/src/tools/fs.ts +432 -0
  156. package/src/tools/grep.ts +268 -0
  157. package/src/tools/screenshot.ts +171 -0
  158. package/src/tools/shell.ts +357 -0
  159. package/src/tools/task.ts +105 -0
  160. package/src/tools/todo.ts +67 -0
  161. package/src/tools/web.ts +451 -0
  162. package/src/ui/configure.ts +397 -0
  163. package/src/ui/diff.ts +136 -0
  164. package/src/ui/editor.ts +136 -0
  165. package/src/ui/render.ts +74 -0
  166. package/src/ui/screen.ts +166 -0
  167. package/src/ui/transcript.ts +377 -0
  168. package/src/ui/tui.tsx +1662 -0
@@ -0,0 +1,432 @@
1
+ // 文件工具:read_file / write_file / edit_file / list_dir / glob,以及 grep(见 grep.ts)。
2
+ //
3
+ // 路径可以是相对路径(相对于工作目录)或绝对路径。policy 插件在 tool.before 里把它们统一成绝对路径,
4
+ // 再由关卡判断是否在工作目录内;工具本身不做权限判断。
5
+ //
6
+ // 修改已有文件之前必须先读过它,且读过之后文件没有被别人(用户、bash 命令)改过,
7
+ // 否则模型是按过时的内容在改,会覆盖掉别人的修改。和修改在同一次回复里发出的读取不算:
8
+ // 那次修改的内容是模型看到读取结果之前就写好的。
9
+
10
+ import type { Stats } from "node:fs";
11
+ import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
12
+ import path from "node:path";
13
+ import type { Block, Tool } from "uncarved";
14
+ import { sha256, type Checkpoints } from "./checkpoint.ts";
15
+ import { grepTool } from "./grep.ts";
16
+ import { globMatcher, run } from "../sys.ts";
17
+
18
+ const MAX_LINES = 2000;
19
+ const MAX_LINE_CHARS = 2000;
20
+ const MAX_GLOB = 500;
21
+ const MAX_IMAGE_BYTES = 5_000_000;
22
+ const MAX_PDF_BYTES = 10_000_000;
23
+ const IMAGE_TYPES: Record<string, string> = {
24
+ ".png": "image/png",
25
+ ".jpg": "image/jpeg",
26
+ ".jpeg": "image/jpeg",
27
+ ".gif": "image/gif",
28
+ ".webp": "image/webp",
29
+ };
30
+ /** 遍历目录时跳过 */
31
+ export const SKIP_DIRS = new Set([".git", "node_modules"]);
32
+
33
+ const str = { type: "string" } as const;
34
+ const int = { type: "integer" } as const;
35
+
36
+ export function resolveIn(cwd: string, p: string): string {
37
+ return path.resolve(cwd, p);
38
+ }
39
+
40
+ /** 显示用:工作目录内的路径用相对形式,统一为正斜杠 */
41
+ export function display(cwd: string, full: string): string {
42
+ const rel = path.relative(cwd, full);
43
+ const shown = rel && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) ? rel : full;
44
+ return shown.split(path.sep).join("/");
45
+ }
46
+
47
+ export interface FsOptions {
48
+ /** 给了就在每次写入前保存原内容,供撤销;也用它记下读过的文件,恢复会话后不用重新读 */
49
+ checkpoints?: Checkpoints;
50
+ /** 模型调用的次数,每次调用模型前加一(见 distro 的 model.before hook)。不给就不检查同一次回复里的先读后改 */
51
+ responses?: { readonly calls: number };
52
+ /** grep 用的 ripgrep,默认 "rg";null 表示不用(测试) */
53
+ rg?: string | null;
54
+ }
55
+
56
+ /** 读过或写过的文件当时的样子;只在本进程内有效,恢复的会话靠 checkpoints 里记的 sha256 */
57
+ interface Seen {
58
+ mtimeMs: number;
59
+ size: number;
60
+ /** 读取时的 responses.calls;写入的文件模型知道内容,记为 -1 */
61
+ call: number;
62
+ }
63
+
64
+ export function fsTools(cwd: string, opts: FsOptions = {}): Tool[] {
65
+ const at = (p: unknown) => resolveIn(cwd, p as string);
66
+ const seen = new Map<string, Seen>();
67
+ /** 文件没变时保留更早的 call:之前的回复里读过,这次回复里又读一遍,不影响修改 */
68
+ const remember = async (ctx: { sessionId: string }, full: string, info: Stats, text: string, call: number) => {
69
+ const s = seen.get(full);
70
+ const same = s !== undefined && s.mtimeMs === info.mtimeMs && s.size === info.size;
71
+ seen.set(full, { mtimeMs: info.mtimeMs, size: info.size, call: same ? Math.min(s.call, call) : call });
72
+ await opts.checkpoints?.markSeen(ctx.sessionId, full, sha256(text));
73
+ };
74
+ /** 不能修改已有文件的原因;可以修改时返回 undefined。text 是文件现在的内容 */
75
+ const staleness = async (ctx: { sessionId: string }, full: string, info: Stats, text: string): Promise<string | undefined> => {
76
+ const shown = display(cwd, full);
77
+ const modified = `${shown} has been modified since it was last read (by the user or a command). Read it again before changing it.`;
78
+ const s = seen.get(full);
79
+ if (s) {
80
+ if (s.mtimeMs !== info.mtimeMs || s.size !== info.size) return modified;
81
+ if (opts.responses && s.call === opts.responses.calls) {
82
+ return `${shown} was read in the same response as this change, so the change was written before its content was seen. Check the read_file result, then make the change in your next response.`;
83
+ }
84
+ return undefined;
85
+ }
86
+ // 恢复的会话:之前的进程里读过或写过
87
+ const hash = await opts.checkpoints?.seenHash(ctx.sessionId, full);
88
+ if (hash === undefined) return `${shown} exists but has not been read in this session. Read it with read_file before changing it.`;
89
+ if (hash !== sha256(text)) return modified;
90
+ seen.set(full, { mtimeMs: info.mtimeMs, size: info.size, call: -1 });
91
+ return undefined;
92
+ };
93
+ const checkpoint = async (ctx: { sessionId: string; toolUseId: string }, tool: string, full: string, before: string | null, after: string) => {
94
+ await opts.checkpoints?.save(ctx.sessionId, { toolUseId: ctx.toolUseId, tool, path: full, before, afterHash: sha256(after) });
95
+ };
96
+
97
+ const readFileTool: Tool = {
98
+ name: "read_file",
99
+ description:
100
+ "Read a UTF-8 text file, an image (png, jpg, gif, webp) or a PDF. Text is returned as lines prefixed with their 1-based line number and a tab. " +
101
+ `At most ${MAX_LINES} lines are returned per call; use offset (1-based start line) and limit to page through larger files.`,
102
+ inputSchema: {
103
+ type: "object",
104
+ properties: { path: str, offset: int, limit: int },
105
+ required: ["path"],
106
+ additionalProperties: false,
107
+ },
108
+ effect: "read",
109
+ concurrency: "safe",
110
+ idempotent: true,
111
+ async execute(input, ctx) {
112
+ const { path: p, offset = 1, limit = MAX_LINES } = input as { path: string; offset?: number; limit?: number };
113
+ if (limit < 1) return { content: "limit must be at least 1", isError: true };
114
+ const full = at(p);
115
+ const info = await stat(full);
116
+ if (info.isDirectory()) return { content: `${display(cwd, full)} is a directory; use list_dir`, isError: true };
117
+ const mediaType = IMAGE_TYPES[path.extname(full).toLowerCase()];
118
+ if (mediaType) {
119
+ if (info.size > MAX_IMAGE_BYTES) return { content: `image is ${info.size} bytes; at most ${MAX_IMAGE_BYTES} can be read`, isError: true };
120
+ const image: Block = {
121
+ kind: "image",
122
+ source: { type: "base64", media_type: mediaType, data: (await readFile(full)).toString("base64") },
123
+ origin: { by: "tool", name: "read_file" },
124
+ trust: "untrusted",
125
+ };
126
+ return { content: [image] };
127
+ }
128
+ if (path.extname(full).toLowerCase() === ".pdf") {
129
+ if (info.size > MAX_PDF_BYTES) return { content: `PDF is ${info.size} bytes; at most ${MAX_PDF_BYTES} can be read`, isError: true };
130
+ const pdf: Block = {
131
+ kind: "document",
132
+ source: { type: "base64", media_type: "application/pdf", data: (await readFile(full)).toString("base64") },
133
+ origin: { by: "tool", name: "read_file" },
134
+ trust: "untrusted",
135
+ };
136
+ return { content: [pdf] };
137
+ }
138
+ const buf = await readFile(full);
139
+ if (buf.subarray(0, 8000).includes(0)) {
140
+ return { content: `${display(cwd, full)} is a binary file (${buf.length} bytes) and cannot be shown as text`, isError: true };
141
+ }
142
+ const text = buf.toString("utf8");
143
+ await remember(ctx, full, info, text, opts.responses?.calls ?? -1);
144
+ if (text.length === 0) return { content: "(empty file)" };
145
+ const lines = text.split(/\r?\n/);
146
+ if (lines.at(-1) === "") lines.pop();
147
+ const start = Math.max(1, offset);
148
+ const slice = lines.slice(start - 1, start - 1 + Math.min(limit, MAX_LINES));
149
+ if (slice.length === 0) return { content: `(file has ${lines.length} lines; offset ${start} is past the end)`, isError: true };
150
+ const body = slice
151
+ .map((l, i) => `${start + i}\t${l.length > MAX_LINE_CHARS ? l.slice(0, MAX_LINE_CHARS) + "…" : l}`)
152
+ .join("\n");
153
+ const end = start + slice.length - 1;
154
+ return { content: end < lines.length ? `${body}\n(showing lines ${start}-${end} of ${lines.length})` : body };
155
+ },
156
+ };
157
+
158
+ const writeFileTool: Tool = {
159
+ name: "write_file",
160
+ description:
161
+ "Create a file or overwrite it with the complete new content. Missing parent directories are created. " +
162
+ "An existing file must have been read with read_file first. Prefer edit_file for changing part of an existing file.",
163
+ inputSchema: {
164
+ type: "object",
165
+ properties: { path: str, content: str },
166
+ required: ["path", "content"],
167
+ additionalProperties: false,
168
+ },
169
+ effect: "write",
170
+ concurrency: "exclusive",
171
+ // 写入完整内容,重复执行结果相同
172
+ idempotent: true,
173
+ async execute(input, ctx) {
174
+ const { path: p, content } = input as { path: string; content: string };
175
+ const full = at(p);
176
+ const info = await statOrUndefined(full);
177
+ if (info?.isDirectory()) return { content: `${display(cwd, full)} is a directory`, isError: true };
178
+ // 同样内容重复写入(崩溃后重跑)不算覆盖别人的修改
179
+ const before = info ? await readFile(full, "utf8") : null;
180
+ const problem = info && before !== null && before !== content ? await staleness(ctx, full, info, before) : undefined;
181
+ if (problem) return { content: problem, isError: true };
182
+ await mkdir(path.dirname(full), { recursive: true });
183
+ await writeFile(full, content);
184
+ await remember(ctx, full, await stat(full), content, -1);
185
+ if (before !== content) await checkpoint(ctx, "write_file", full, before, content);
186
+ // 和 read_file 一样数行:末尾的换行不算多出一行
187
+ const lines = content === "" ? 0 : content.split(/\r?\n/).length - (/\r?\n$/.test(content) ? 1 : 0);
188
+ return { content: `Wrote ${lines} lines to ${display(cwd, full)}` };
189
+ },
190
+ };
191
+
192
+ /** edit_file 和 multi_edit 共用:检查文件能否修改,按顺序应用全部替换,全部成功才写入 */
193
+ const applyEdits = async (ctx: { sessionId: string; toolUseId: string }, tool: string, p: string, edits: Edit[]) => {
194
+ const full = at(p);
195
+ const shown = display(cwd, full);
196
+ const info = await statOrUndefined(full);
197
+ if (!info) {
198
+ return { content: seen.has(full) ? `${shown} no longer exists` : `${shown} does not exist; use write_file to create it`, isError: true };
199
+ }
200
+ const text = await readFile(full, "utf8");
201
+ const problem = await staleness(ctx, full, info, text);
202
+ if (problem) return { content: problem, isError: true };
203
+ let next = text;
204
+ let total = 0;
205
+ for (const [i, e] of edits.entries()) {
206
+ const r = replaceIn(next, e, shown);
207
+ if (typeof r === "string") return { content: edits.length > 1 ? `edit ${i + 1} of ${edits.length}: ${r}. No edits were applied.` : r, isError: true };
208
+ next = r.text;
209
+ total += r.count;
210
+ }
211
+ await writeFile(full, next);
212
+ await remember(ctx, full, await stat(full), next, -1);
213
+ await checkpoint(ctx, tool, full, text, next);
214
+ return { content: `Edited ${shown} (${total} replacement${total === 1 ? "" : "s"})` };
215
+ };
216
+
217
+ const editFileTool: Tool = {
218
+ name: "edit_file",
219
+ description:
220
+ "Replace exact text in a file. old_string must match the file exactly (including whitespace and indentation) " +
221
+ "and must be unique unless replace_all is true. The file must have been read with read_file first, " +
222
+ "and is refused if it changed since then. Use multi_edit for several changes to one file.",
223
+ inputSchema: {
224
+ type: "object",
225
+ properties: { path: str, old_string: str, new_string: str, replace_all: { type: "boolean" } },
226
+ required: ["path", "old_string", "new_string"],
227
+ additionalProperties: false,
228
+ },
229
+ effect: "write",
230
+ concurrency: "exclusive",
231
+ // 第二次执行时 old_string 可能已经不存在,或者被替换两次
232
+ idempotent: false,
233
+ async execute(input, ctx) {
234
+ const { path: p, ...edit } = input as { path: string } & Edit;
235
+ return applyEdits(ctx, "edit_file", p, [edit]);
236
+ },
237
+ };
238
+
239
+ const multiEditTool: Tool = {
240
+ name: "multi_edit",
241
+ description:
242
+ "Make several exact-text replacements in one file at once. The edits are applied in order, each to the result of the previous one, " +
243
+ "with the same rules as edit_file. Either all edits succeed or the file is left unchanged.",
244
+ inputSchema: {
245
+ type: "object",
246
+ properties: {
247
+ path: str,
248
+ edits: {
249
+ type: "array",
250
+ items: {
251
+ type: "object",
252
+ properties: { old_string: str, new_string: str, replace_all: { type: "boolean" } },
253
+ required: ["old_string", "new_string"],
254
+ additionalProperties: false,
255
+ },
256
+ },
257
+ },
258
+ required: ["path", "edits"],
259
+ additionalProperties: false,
260
+ },
261
+ effect: "write",
262
+ concurrency: "exclusive",
263
+ idempotent: false,
264
+ async execute(input, ctx) {
265
+ const { path: p, edits } = input as { path: string; edits: Edit[] };
266
+ if (edits.length === 0) return { content: "edits must not be empty", isError: true };
267
+ return applyEdits(ctx, "multi_edit", p, edits);
268
+ },
269
+ };
270
+
271
+ const listDirTool: Tool = {
272
+ name: "list_dir",
273
+ description: "List the entries of a directory. Directories end with '/'.",
274
+ inputSchema: { type: "object", properties: { path: str }, required: ["path"], additionalProperties: false },
275
+ effect: "read",
276
+ concurrency: "safe",
277
+ idempotent: true,
278
+ async execute(input) {
279
+ const entries = await readdir(at((input as { path: string }).path), { withFileTypes: true });
280
+ const names = entries.map((e) => e.name + (e.isDirectory() ? "/" : "")).sort();
281
+ return { content: names.length > 0 ? names.join("\n") : "(empty directory)" };
282
+ },
283
+ };
284
+
285
+ const globTool: Tool = {
286
+ name: "glob",
287
+ description:
288
+ `Find files by glob pattern (e.g. "src/**/*.ts"), relative to path (default: the working directory). ` +
289
+ `Skips files ignored by git, .git and node_modules. Returns at most ${MAX_GLOB} paths.`,
290
+ inputSchema: {
291
+ type: "object",
292
+ properties: { pattern: str, path: str },
293
+ required: ["pattern"],
294
+ additionalProperties: false,
295
+ },
296
+ effect: "read",
297
+ concurrency: "safe",
298
+ idempotent: true,
299
+ async execute(input, { signal }) {
300
+ const { pattern, path: p = "." } = input as { pattern: string; path?: string };
301
+ const root = at(p);
302
+ const out: string[] = [];
303
+ let more = false;
304
+ const match = globMatcher(pattern);
305
+ const tracked = await gitFiles(root);
306
+ const candidates = tracked
307
+ ? filterAsync(tracked, async (rel) => match(rel) && Boolean((await statOrUndefined(path.join(root, rel)))?.isFile()))
308
+ : scanGlob(root, match, signal);
309
+ for await (const rel of candidates) {
310
+ signal.throwIfAborted();
311
+ if (rel.split(/[\\/]/).some((seg) => SKIP_DIRS.has(seg))) continue;
312
+ if (out.length >= MAX_GLOB) {
313
+ more = true;
314
+ break;
315
+ }
316
+ out.push(display(cwd, path.join(root, rel)));
317
+ }
318
+ out.sort();
319
+ if (out.length === 0) return { content: "No files matched" };
320
+ return { content: out.join("\n") + (more ? `\n(more than ${MAX_GLOB} matches; narrow the pattern)` : "") };
321
+ },
322
+ };
323
+
324
+ return [readFileTool, writeFileTool, editFileTool, multiEditTool, listDirTool, globTool, grepTool(cwd, { rg: opts.rg })];
325
+ }
326
+
327
+ export interface Edit {
328
+ old_string: string;
329
+ new_string: string;
330
+ replace_all?: boolean;
331
+ }
332
+
333
+ /** 按 edit_file / multi_edit 的规则把 edits 依次应用到 text 上;失败时返回原因。审批预览用它算出修改后的内容 */
334
+ export function applyEditsToText(text: string, edits: Edit[], shown: string): string | { text: string } {
335
+ let next = text;
336
+ for (const [i, e] of edits.entries()) {
337
+ const r = replaceIn(next, e, shown);
338
+ if (typeof r === "string") return edits.length > 1 ? `edit ${i + 1} of ${edits.length}: ${r}` : r;
339
+ next = r.text;
340
+ }
341
+ return { text: next };
342
+ }
343
+
344
+ /** 在 text 上做一次替换;失败时返回原因 */
345
+ function replaceIn(text: string, { old_string, new_string, replace_all }: Edit, shown: string): { text: string; count: number } | string {
346
+ if (old_string === new_string) return "old_string and new_string are identical";
347
+ if (old_string === "") return "old_string must not be empty; use write_file to create a file";
348
+ // 文件是 CRLF 时,模型给的 LF 文本也能匹配
349
+ const crlf = text.includes("\r\n") && !old_string.includes("\r\n");
350
+ const from = crlf ? old_string.replaceAll("\n", "\r\n") : old_string;
351
+ const to = crlf ? new_string.replaceAll("\n", "\r\n") : new_string;
352
+ const count = text.split(from).length - 1;
353
+ if (count === 0) return `old_string not found in ${shown}${nearMiss(text, old_string)}`;
354
+ if (count > 1 && !replace_all) return `old_string occurs ${count} times in ${shown}; add context to make it unique or set replace_all`;
355
+ // 用函数作替换值,new_string 里的 $& $1 等不会被当成替换模式
356
+ return { text: replace_all ? text.replaceAll(from, () => to) : text.replace(from, () => to), count: replace_all ? count : 1 };
357
+ }
358
+
359
+ /**
360
+ * old_string 找不到时帮模型定位:忽略空白后能匹配到哪几行,或者第一行出现在哪里。
361
+ * 只给提示,不自动按模糊匹配修改:那样可能改错地方
362
+ */
363
+ export function nearMiss(text: string, needle: string): string {
364
+ const norm = (l: string) => l.trim().replace(/\s+/g, " ");
365
+ const lines = text.split(/\r?\n/).map(norm);
366
+ const want = needle.split(/\r?\n/).map(norm);
367
+ while (want.length > 1 && want.at(-1) === "") want.pop();
368
+ while (want.length > 1 && want[0] === "") want.shift();
369
+ if (want.every((l) => l === "")) return "";
370
+ const hits: number[] = [];
371
+ for (let i = 0; i + want.length <= lines.length && hits.length < 3; i++) {
372
+ if (want.every((l, k) => (k === 0 || k === want.length - 1 ? lines[i + k]!.includes(l) : lines[i + k] === l))) hits.push(i);
373
+ }
374
+ if (hits.length > 0) {
375
+ const where = hits.map((i) => (want.length > 1 ? `${i + 1}-${i + want.length}` : `${i + 1}`)).join(", ");
376
+ return `. It matches line${hits.length > 1 || want.length > 1 ? "s" : ""} ${where} if whitespace is ignored: indentation, tabs or trailing spaces differ. Copy the exact text from read_file`;
377
+ }
378
+ const first = want.find((l) => l !== "")!;
379
+ const at = lines.findIndex((l) => l.includes(first));
380
+ if (at >= 0 && want.length > 1) return `. Its first line "${first.slice(0, 80)}" appears at line ${at + 1}, but the lines after it differ; read that part of the file again`;
381
+ return "";
382
+ }
383
+
384
+ export const statOrUndefined = (full: string) => stat(full).catch(() => undefined);
385
+
386
+ /**
387
+ * root 在 git 仓库里时,用 git 列出未被忽略的文件(已跟踪的和未跟踪的),路径相对于 root、用正斜杠。
388
+ * 不在仓库里或没有 git 时返回 undefined
389
+ */
390
+ async function gitFiles(root: string): Promise<string[] | undefined> {
391
+ try {
392
+ const { code, stdout: out } = await run(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"], { cwd: root });
393
+ if (code !== 0) return undefined;
394
+ // 合并冲突中的文件会出现多次
395
+ return [...new Set(out.split("\0").filter(Boolean))];
396
+ } catch {
397
+ return undefined;
398
+ }
399
+ }
400
+
401
+ export async function listFiles(root: string, signal: AbortSignal): Promise<Iterable<string> | AsyncIterable<string>> {
402
+ const tracked = await gitFiles(root);
403
+ if (!tracked) return walk(root, signal);
404
+ return tracked.filter((rel) => !rel.split("/").some((seg) => SKIP_DIRS.has(seg))).map((rel) => path.join(root, rel));
405
+ }
406
+
407
+ /** 不在 git 仓库里时的 glob:遍历目录,跳过隐藏文件和目录(和原先 Bun.Glob#scan 的默认行为一致),产出相对路径 */
408
+ async function* scanGlob(root: string, match: (rel: string) => boolean, signal: AbortSignal): AsyncIterable<string> {
409
+ for await (const full of walk(root, signal)) {
410
+ const rel = path.relative(root, full).split(path.sep).join("/");
411
+ if (rel.split("/").some((seg) => seg.startsWith("."))) continue;
412
+ if (match(rel)) yield rel;
413
+ }
414
+ }
415
+
416
+ async function* filterAsync<T>(items: Iterable<T>, keep: (item: T) => Promise<boolean>): AsyncIterable<T> {
417
+ for (const item of items) if (await keep(item)) yield item;
418
+ }
419
+
420
+ async function* walk(dir: string, signal: AbortSignal): AsyncIterable<string> {
421
+ signal.throwIfAborted();
422
+ // readdir 的顺序随文件系统而定(APFS 不排序),按名字排好,结果在各平台一致
423
+ const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
424
+ for (const e of entries) {
425
+ const full = path.join(dir, e.name);
426
+ if (e.isDirectory()) {
427
+ if (!SKIP_DIRS.has(e.name)) yield* walk(full, signal);
428
+ } else if (e.isFile()) {
429
+ yield full;
430
+ }
431
+ }
432
+ }