@uncarved/jade 0.3.0 → 0.4.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.
Files changed (207) hide show
  1. package/README.md +1 -0
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/host.d.ts +2 -0
  5. package/dist/host.js +39 -5
  6. package/dist/host.js.map +1 -1
  7. package/dist/remote.js +5 -0
  8. package/dist/remote.js.map +1 -1
  9. package/dist/session.d.ts +7 -0
  10. package/dist/session.js +482 -27
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +49 -24
  14. package/plugins/approval/policy.ts +48 -25
  15. package/plugins/approval/review.ts +9 -5
  16. package/plugins/checks/checks.ts +10 -7
  17. package/plugins/checks/index.ts +13 -13
  18. package/plugins/checks/plugin.json +1 -1
  19. package/plugins/checks/project.ts +37 -38
  20. package/plugins/commands/index.ts +27 -3
  21. package/plugins/compact/compact.ts +13 -5
  22. package/plugins/compact/index.ts +20 -3
  23. package/plugins/compact/style.ts +13 -14
  24. package/plugins/completions/index.ts +35 -0
  25. package/plugins/completions/plugin.json +7 -0
  26. package/plugins/copy/index.ts +46 -0
  27. package/plugins/copy/plugin.json +7 -0
  28. package/plugins/editor/index.ts +10 -4
  29. package/plugins/fs/diff.ts +7 -6
  30. package/plugins/fs/fs.ts +8 -4
  31. package/plugins/fs/grep.ts +55 -12
  32. package/plugins/fs/index.ts +2 -7
  33. package/plugins/fs/plugin.json +1 -1
  34. package/plugins/fs/renderers.ts +16 -15
  35. package/plugins/fs/style.ts +16 -15
  36. package/plugins/hooks/index.ts +3 -2
  37. package/plugins/keys/index.ts +5 -1
  38. package/plugins/mcp/index.ts +197 -78
  39. package/plugins/mcp/install.ts +5 -3
  40. package/plugins/mcp/mcp.ts +163 -11
  41. package/plugins/mcp/plugin.json +2 -1
  42. package/plugins/mcp/project.ts +47 -50
  43. package/plugins/memory/index.ts +4 -4
  44. package/plugins/memory/style.ts +13 -14
  45. package/plugins/mentions/candidates.ts +67 -0
  46. package/plugins/mentions/index.ts +12 -5
  47. package/plugins/mentions/plugin.json +1 -1
  48. package/plugins/mentions/style.ts +13 -14
  49. package/plugins/models/configure.ts +10 -9
  50. package/plugins/models/index.ts +31 -4
  51. package/plugins/models/provider.ts +12 -1
  52. package/plugins/modes/index.ts +13 -2
  53. package/plugins/print/index.ts +7 -4
  54. package/plugins/prompts/index.ts +0 -0
  55. package/plugins/renderers/index.ts +10 -5
  56. package/plugins/repeats/index.ts +39 -9
  57. package/plugins/schedule/index.ts +2 -0
  58. package/plugins/screenshot/browser.ts +231 -0
  59. package/plugins/screenshot/index.ts +3 -2
  60. package/plugins/screenshot/tool.ts +27 -51
  61. package/plugins/sessions/index.ts +48 -2
  62. package/plugins/shell/index.ts +75 -22
  63. package/plugins/shell/plugin.json +1 -2
  64. package/plugins/shell/renderers.ts +9 -7
  65. package/plugins/shell/shell.ts +93 -34
  66. package/plugins/skills/index.ts +28 -19
  67. package/plugins/skills/project.ts +12 -7
  68. package/plugins/steer/index.ts +5 -4
  69. package/plugins/task/index.ts +81 -81
  70. package/plugins/task/plugin.json +5 -2
  71. package/plugins/task/style.ts +13 -14
  72. package/plugins/task/subagent.ts +67 -184
  73. package/plugins/todo/index.ts +39 -9
  74. package/plugins/tools/index.ts +57 -0
  75. package/plugins/tools/plugin.json +7 -0
  76. package/plugins/tui/frontend.ts +161 -87
  77. package/plugins/tui/index.ts +2 -3
  78. package/plugins/tui/mascot.ts +8 -7
  79. package/plugins/tui/mentions.ts +11 -80
  80. package/plugins/tui/plugin.json +1 -1
  81. package/plugins/tui/screen.ts +55 -5
  82. package/plugins/tui/transcript.ts +17 -7
  83. package/plugins/tui/tui.ts +356 -104
  84. package/plugins/tui/vendor.ts +1 -1
  85. package/plugins/undo/checkpoint.ts +5 -3
  86. package/plugins/undo/index.ts +43 -14
  87. package/plugins/undo/style.ts +13 -14
  88. package/plugins/web/index.ts +7 -18
  89. package/plugins/web/plugin.json +1 -1
  90. package/plugins-dist/approval/index.js +363 -414
  91. package/plugins-dist/approval/policy.js +395 -497
  92. package/plugins-dist/approval/review.js +132 -158
  93. package/plugins-dist/approval/schema.js +50 -55
  94. package/plugins-dist/ask/index.js +115 -129
  95. package/plugins-dist/budget/index.js +27 -31
  96. package/plugins-dist/checks/checks.js +293 -329
  97. package/plugins-dist/checks/index.js +119 -139
  98. package/plugins-dist/checks/plugin.json +2 -1
  99. package/plugins-dist/checks/project.js +57 -65
  100. package/plugins-dist/commands/index.js +47 -29
  101. package/plugins-dist/compact/compact.js +233 -249
  102. package/plugins-dist/compact/index.js +98 -95
  103. package/plugins-dist/compact/style.js +9 -14
  104. package/plugins-dist/completions/index.js +30 -0
  105. package/plugins-dist/completions/plugin.json +9 -0
  106. package/plugins-dist/continue/index.js +40 -52
  107. package/plugins-dist/copy/index.js +40 -0
  108. package/plugins-dist/copy/plugin.json +9 -0
  109. package/plugins-dist/cost/index.js +98 -115
  110. package/plugins-dist/custom-commands/index.js +55 -72
  111. package/plugins-dist/editor/index.js +64 -72
  112. package/plugins-dist/fs/diff.js +111 -124
  113. package/plugins-dist/fs/fs.js +426 -469
  114. package/plugins-dist/fs/grep.js +262 -244
  115. package/plugins-dist/fs/index.js +20 -34
  116. package/plugins-dist/fs/plugin.json +1 -2
  117. package/plugins-dist/fs/renderers.js +100 -112
  118. package/plugins-dist/fs/style.js +11 -15
  119. package/plugins-dist/fs/sys.js +31 -43
  120. package/plugins-dist/hooks/index.js +107 -127
  121. package/plugins-dist/keys/index.js +27 -31
  122. package/plugins-dist/mcp/index.js +271 -199
  123. package/plugins-dist/mcp/install.js +123 -137
  124. package/plugins-dist/mcp/mcp.js +638 -577
  125. package/plugins-dist/mcp/plugin.json +3 -1
  126. package/plugins-dist/mcp/project.js +98 -115
  127. package/plugins-dist/memory/index.js +83 -88
  128. package/plugins-dist/memory/memory.js +111 -128
  129. package/plugins-dist/memory/style.js +9 -14
  130. package/plugins-dist/mentions/attach.js +91 -99
  131. package/plugins-dist/mentions/candidates.js +49 -0
  132. package/plugins-dist/mentions/index.js +71 -81
  133. package/plugins-dist/mentions/plugin.json +2 -1
  134. package/plugins-dist/mentions/style.js +9 -14
  135. package/plugins-dist/models/config.js +29 -43
  136. package/plugins-dist/models/configure.js +392 -473
  137. package/plugins-dist/models/context.js +14 -22
  138. package/plugins-dist/models/index.js +182 -188
  139. package/plugins-dist/models/provider.js +243 -295
  140. package/plugins-dist/models/saved.js +59 -71
  141. package/plugins-dist/modes/index.js +138 -165
  142. package/plugins-dist/plugins/index.js +34 -34
  143. package/plugins-dist/print/index.js +192 -175
  144. package/plugins-dist/prompts/index.js +81 -89
  145. package/plugins-dist/prompts/notes.js +31 -37
  146. package/plugins-dist/prompts/prompts.js +155 -193
  147. package/plugins-dist/prompts/results.js +40 -53
  148. package/plugins-dist/prompts/sys.js +39 -50
  149. package/plugins-dist/renderers/index.js +32 -32
  150. package/plugins-dist/repeats/index.js +134 -151
  151. package/plugins-dist/schedule/cron.js +49 -56
  152. package/plugins-dist/schedule/index.js +229 -247
  153. package/plugins-dist/schedule/store.js +93 -109
  154. package/plugins-dist/scratch/index.js +12 -18
  155. package/plugins-dist/screenshot/browser.js +169 -0
  156. package/plugins-dist/screenshot/index.js +37 -45
  157. package/plugins-dist/screenshot/sys.js +53 -65
  158. package/plugins-dist/screenshot/tool.js +101 -151
  159. package/plugins-dist/sessions/index.js +149 -117
  160. package/plugins-dist/shell/index.js +117 -74
  161. package/plugins-dist/shell/plugin.json +1 -2
  162. package/plugins-dist/shell/renderers.js +28 -33
  163. package/plugins-dist/shell/service.js +17 -23
  164. package/plugins-dist/shell/shell.js +317 -320
  165. package/plugins-dist/shell/sys.js +64 -79
  166. package/plugins-dist/skills/index.js +193 -211
  167. package/plugins-dist/skills/install.js +122 -149
  168. package/plugins-dist/skills/project.js +65 -73
  169. package/plugins-dist/skills/skills.js +135 -171
  170. package/plugins-dist/steer/index.js +108 -125
  171. package/plugins-dist/suggest/index.js +235 -259
  172. package/plugins-dist/task/index.js +130 -148
  173. package/plugins-dist/task/plugin.json +5 -4
  174. package/plugins-dist/task/style.js +9 -14
  175. package/plugins-dist/task/subagent.js +156 -279
  176. package/plugins-dist/todo/index.js +79 -63
  177. package/plugins-dist/tools/index.js +43 -0
  178. package/plugins-dist/tools/plugin.json +9 -0
  179. package/plugins-dist/tui/editor.js +145 -160
  180. package/plugins-dist/tui/frontend.js +641 -655
  181. package/plugins-dist/tui/history.js +34 -37
  182. package/plugins-dist/tui/index.js +16 -18
  183. package/plugins-dist/tui/markdown.js +203 -247
  184. package/plugins-dist/tui/mascot.js +266 -353
  185. package/plugins-dist/tui/mentions.js +67 -144
  186. package/plugins-dist/tui/plugin.json +1 -2
  187. package/plugins-dist/tui/render.js +35 -45
  188. package/plugins-dist/tui/screen.js +197 -180
  189. package/plugins-dist/tui/transcript.js +436 -468
  190. package/plugins-dist/tui/tui.js +1554 -1645
  191. package/plugins-dist/tui/vendor.js +1388 -1088
  192. package/plugins-dist/undo/checkpoint.js +95 -118
  193. package/plugins-dist/undo/index.js +185 -192
  194. package/plugins-dist/undo/snapshot.js +83 -99
  195. package/plugins-dist/undo/style.js +9 -14
  196. package/plugins-dist/update/index.js +26 -28
  197. package/plugins-dist/web/env.js +55 -68
  198. package/plugins-dist/web/index.js +80 -110
  199. package/plugins-dist/web/plugin.json +1 -2
  200. package/plugins-dist/web/renderers.js +4 -5
  201. package/plugins-dist/web/web.js +514 -593
  202. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  203. package/sdk/python/jade_plugin.py +9 -2
  204. package/src/api.ts +1 -1
  205. package/src/host.ts +39 -4
  206. package/src/remote.ts +6 -1
  207. package/src/session.ts +489 -34
@@ -1,522 +1,479 @@
1
- // 文件工具:read_file / write_file / edit_file / list_dir / glob,以及 grep(见 grep.ts)。
2
- //
3
- // 路径可以是相对路径(相对于工作目录)或绝对路径。工具本身不做权限判断:那是审批插件的事。
4
- //
5
- // 修改已有文件之前必须先读过它,且读过之后文件没有被别人(用户、bash 命令)改过,
6
- // 否则模型是按过时的内容在改,会覆盖掉别人的修改。和修改在同一次回复里发出的读取不算:
7
- // 那次修改的内容是模型看到读取结果之前就写好的。
8
1
  import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
9
2
  import path from "node:path";
10
3
  import { grepTool } from "./grep.js";
11
4
  import { globMatcher, run } from "./sys.js";
12
5
  const MAX_LINES = 2000;
13
6
  const MAX_LINE_CHARS = 2000;
14
- /** 一次 read_file 返回的文本上限(约 25k token) */
15
- const MAX_READ_CHARS = 100_000;
7
+ const MAX_READ_CHARS = 1e5;
16
8
  const MAX_GLOB = 500;
17
- const MAX_IMAGE_BYTES = 5_000_000;
18
- const MAX_PDF_BYTES = 10_000_000;
9
+ const MAX_IMAGE_BYTES = 5000000;
10
+ const MAX_PDF_BYTES = 1e7;
19
11
  const IMAGE_TYPES = {
20
- ".png": "image/png",
21
- ".jpg": "image/jpeg",
22
- ".jpeg": "image/jpeg",
23
- ".gif": "image/gif",
24
- ".webp": "image/webp",
12
+ ".png": "image/png",
13
+ ".jpg": "image/jpeg",
14
+ ".jpeg": "image/jpeg",
15
+ ".gif": "image/gif",
16
+ ".webp": "image/webp"
25
17
  };
26
- /** 遍历目录时跳过 */
27
18
  export const SKIP_DIRS = new Set([".git", "node_modules"]);
28
19
  const str = { type: "string" };
29
20
  const int = { type: "integer" };
30
21
  export function resolveIn(cwd, p) {
31
- return path.resolve(cwd, p);
22
+ return path.resolve(cwd, p);
32
23
  }
33
- /** 显示用:工作目录内的路径用相对形式,统一为正斜杠 */
34
24
  export function display(cwd, full) {
35
- const rel = path.relative(cwd, full);
36
- const shown = rel && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) ? rel : full;
37
- return shown.split(path.sep).join("/");
25
+ const rel = path.relative(cwd, full);
26
+ const shown = rel && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) ? rel : full;
27
+ return shown.split(path.sep).join("/");
38
28
  }
39
- /** 本会话读过、写过的文件 */
29
+
40
30
  export class SeenFiles {
41
- files = new Map();
42
- /** 因为压缩而失效的文件:再改时说明原因,而不是说"没读过" */
43
- dropped = new Set();
44
- /**
45
- * 压缩或清理之后,模型看不到当初读到(写入)的内容了,但 mtime 和 size 没变,修改仍会放行;
46
- * write_file 可能凭摘要里的记忆写出整个文件。这里按最终的投影检查:那次调用已被总结掉(投影里没有它的 tool_use),
47
- * 或者结果已被清理(tool_result 里没有工具自己给的内容,只剩插件的占位说明),就当作没读过
48
- */
49
- prune(projection) {
50
- const uses = new Set();
51
- const cleared = new Set();
52
- for (const m of projection) {
53
- for (const b of m.content) {
54
- if (b.kind === "tool_use")
55
- uses.add(b.id);
56
- else if (b.kind === "tool_result" && !b.content.some((c) => c.origin.by === "tool"))
57
- cleared.add(b.toolUseId);
58
- }
59
- }
60
- for (const [full, s] of this.files) {
61
- if (s.id === undefined || (uses.has(s.id) && !cleared.has(s.id)))
62
- continue;
63
- this.files.delete(full);
64
- this.dropped.add(full);
65
- }
31
+ files = new Map;
32
+ dropped = new Set;
33
+ prune(projection) {
34
+ const uses = new Set;
35
+ const cleared = new Set;
36
+ for (const m of projection) {
37
+ for (const b of m.content) {
38
+ if (b.kind === "tool_use")
39
+ uses.add(b.id);
40
+ else if (b.kind === "tool_result" && !b.content.some((c) => c.origin.by === "tool"))
41
+ cleared.add(b.toolUseId);
42
+ }
43
+ }
44
+ for (const [full, s] of this.files) {
45
+ if (s.id === undefined || uses.has(s.id) && !cleared.has(s.id))
46
+ continue;
47
+ this.files.delete(full);
48
+ this.dropped.add(full);
66
49
  }
50
+ }
67
51
  }
68
52
  export function fsTools(cwd, opts = {}) {
69
- const at = (p) => resolveIn(cwd, p);
70
- const tracked = opts.seen ?? new SeenFiles();
71
- const seen = tracked.files;
72
- /**
73
- * 文件没变时保留更早的 call:之前的回复里读过,这次回复里又读一遍,不影响修改。
74
- * id 为 undefined 表示沿用原来的(edit_file)
75
- */
76
- const remember = (full, info, call, id) => {
77
- const s = seen.get(full);
78
- const same = s !== undefined && s.mtimeMs === info.mtimeMs && s.size === info.size;
79
- seen.set(full, { mtimeMs: info.mtimeMs, size: info.size, call: same ? Math.min(s.call, call) : call, id: id ?? s?.id });
80
- tracked.dropped.delete(full);
81
- };
82
- /** 不能修改已有文件的原因;可以修改时返回 undefined。text 是文件现在的内容 */
83
- const staleness = (full, info) => {
84
- const shown = display(cwd, full);
85
- const modified = `${shown} has been modified since it was last read (by the user or a command). Read it again before changing it.`;
86
- const s = seen.get(full);
87
- if (s) {
88
- if (s.mtimeMs !== info.mtimeMs || s.size !== info.size)
89
- return modified;
90
- if (opts.responses && s.call === opts.responses.calls) {
91
- 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.`;
92
- }
93
- return undefined;
94
- }
95
- if (tracked.dropped.has(full)) {
96
- return `The earlier read of ${shown} was compacted out of the conversation, so its content is no longer in context. Read it again before changing it.`;
97
- }
98
- return `${shown} exists but has not been read in this session. Read it with read_file before changing it.`;
99
- };
100
- const readFileTool = {
101
- name: "read_file",
102
- description: "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. " +
103
- `At most ${MAX_LINES} lines (about ${MAX_READ_CHARS / 1000}k characters) are returned per call; use offset (1-based start line) and limit to page through larger files. ` +
104
- `Lines longer than ${MAX_LINE_CHARS} characters are cut and marked "[line truncated]"; do not copy a cut line into edit_file.`,
105
- inputSchema: {
106
- type: "object",
107
- properties: { path: str, offset: int, limit: int },
108
- required: ["path"],
109
- additionalProperties: false,
110
- },
111
- effect: "read",
112
- concurrency: "safe",
113
- idempotent: true,
114
- async execute(input, ctx) {
115
- const { path: p, offset = 1, limit = MAX_LINES } = input;
116
- if (limit < 1)
117
- return { content: "limit must be at least 1", isError: true };
118
- const full = at(p);
119
- const info = await stat(full);
120
- if (info.isDirectory())
121
- return { content: `${display(cwd, full)} is a directory; use list_dir`, isError: true };
122
- const mediaType = IMAGE_TYPES[path.extname(full).toLowerCase()];
123
- if (mediaType) {
124
- if (info.size > MAX_IMAGE_BYTES)
125
- return { content: `image is ${info.size} bytes; at most ${MAX_IMAGE_BYTES} can be read`, isError: true };
126
- const image = {
127
- kind: "image",
128
- source: { type: "base64", media_type: mediaType, data: (await readFile(full)).toString("base64") },
129
- origin: { by: "tool", name: "read_file" },
130
- trust: "untrusted",
131
- };
132
- return { content: [image] };
133
- }
134
- if (path.extname(full).toLowerCase() === ".pdf") {
135
- if (info.size > MAX_PDF_BYTES)
136
- return { content: `PDF is ${info.size} bytes; at most ${MAX_PDF_BYTES} can be read`, isError: true };
137
- const pdf = {
138
- kind: "document",
139
- source: { type: "base64", media_type: "application/pdf", data: (await readFile(full)).toString("base64") },
140
- origin: { by: "tool", name: "read_file" },
141
- trust: "untrusted",
142
- };
143
- return { content: [pdf] };
144
- }
145
- const buf = await readFile(full);
146
- if (buf.subarray(0, 8000).includes(0)) {
147
- return { content: `${display(cwd, full)} is a binary file (${buf.length} bytes) and cannot be shown as text`, isError: true };
148
- }
149
- // 不是 UTF-8 的文件(多半是 GBK)照样给模型看,但不算读过:改它会把原来的字节写坏
150
- const strict = utf8(buf);
151
- const text = strict ?? legacyText(buf);
152
- const note = strict === undefined ? `\n(${notUtf8(display(cwd, full))})` : "";
153
- if (strict !== undefined)
154
- remember(full, info, opts.responses?.calls ?? -1, ctx?.toolUseId);
155
- if (text.length === 0)
156
- return { content: "(empty file)" };
157
- const lines = text.split(/\r?\n/);
158
- if (lines.at(-1) === "")
159
- lines.pop();
160
- const start = Math.max(1, offset);
161
- const slice = lines.slice(start - 1, start - 1 + Math.min(limit, MAX_LINES));
162
- if (slice.length === 0)
163
- return { content: `(file has ${lines.length} lines; offset ${start} is past the end)`, isError: true };
164
- // 按整行截断到 MAX_READ_CHARS:压缩过的代码、lock 文件一次就能占掉大半个上下文
165
- const out = [];
166
- let size = 0;
167
- for (const [i, l] of slice.entries()) {
168
- const row = `${start + i}\t${l.length > MAX_LINE_CHARS ? `${l.slice(0, MAX_LINE_CHARS)}… [line truncated: ${l.length} characters]` : l}`;
169
- if (out.length > 0 && size + row.length + 1 > MAX_READ_CHARS)
170
- break;
171
- out.push(row);
172
- size += row.length + 1;
173
- }
174
- const body = out.join("\n");
175
- const end = start + out.length - 1;
176
- if (out.length < slice.length) {
177
- return { content: `${body}\n(output capped at about ${MAX_READ_CHARS} characters: showing lines ${start}-${end} of ${lines.length}; continue with offset ${end + 1})${note}` };
178
- }
179
- return { content: (end < lines.length ? `${body}\n(showing lines ${start}-${end} of ${lines.length})` : body) + note };
180
- },
181
- };
182
- const writeFileTool = {
183
- name: "write_file",
184
- description: "Create a file or overwrite it with the complete new content. Missing parent directories are created. " +
185
- "An existing file must have been read with read_file first. Prefer edit_file for changing part of an existing file.",
186
- inputSchema: {
53
+ const at = (p) => resolveIn(cwd, p);
54
+ const tracked = opts.seen ?? new SeenFiles;
55
+ const seen = tracked.files;
56
+ const remember = (full, info, call, id) => {
57
+ const s = seen.get(full);
58
+ const same = s !== undefined && s.mtimeMs === info.mtimeMs && s.size === info.size;
59
+ seen.set(full, { mtimeMs: info.mtimeMs, size: info.size, call: same ? Math.min(s.call, call) : call, id: id ?? s?.id });
60
+ tracked.dropped.delete(full);
61
+ };
62
+ const staleness = (full, info) => {
63
+ const shown = display(cwd, full);
64
+ const modified = `${shown} has been modified since it was last read (by the user or a command). Read it again before changing it.`;
65
+ const s = seen.get(full);
66
+ if (s) {
67
+ if (s.mtimeMs !== info.mtimeMs || s.size !== info.size)
68
+ return modified;
69
+ if (opts.responses && s.call === opts.responses.calls) {
70
+ 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.`;
71
+ }
72
+ return;
73
+ }
74
+ if (tracked.dropped.has(full)) {
75
+ return `The earlier read of ${shown} was compacted out of the conversation, so its content is no longer in context. Read it again before changing it.`;
76
+ }
77
+ return `${shown} exists but has not been read in this session. Read it with read_file before changing it.`;
78
+ };
79
+ const readFileTool = {
80
+ name: "read_file",
81
+ description: "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. " + `At most ${MAX_LINES} lines (about ${MAX_READ_CHARS / 1000}k characters) are returned per call; use offset (1-based start line) and limit to page through larger files. ` + `Lines longer than ${MAX_LINE_CHARS} characters are cut and marked "[line truncated]"; do not copy a cut line into edit_file.`,
82
+ inputSchema: {
83
+ type: "object",
84
+ properties: { path: str, offset: int, limit: int },
85
+ required: ["path"],
86
+ additionalProperties: false
87
+ },
88
+ effect: "read",
89
+ concurrency: "safe",
90
+ idempotent: true,
91
+ async execute(input, ctx) {
92
+ const { path: p, offset = 1, limit = MAX_LINES } = input;
93
+ if (limit < 1)
94
+ return { content: "limit must be at least 1", isError: true };
95
+ const full = at(p);
96
+ const info = await stat(full);
97
+ if (info.isDirectory())
98
+ return { content: `${display(cwd, full)} is a directory; use list_dir`, isError: true };
99
+ const mediaType = IMAGE_TYPES[path.extname(full).toLowerCase()];
100
+ if (mediaType) {
101
+ if (info.size > MAX_IMAGE_BYTES)
102
+ return { content: `image is ${info.size} bytes; at most ${MAX_IMAGE_BYTES} can be read`, isError: true };
103
+ const image = {
104
+ kind: "image",
105
+ source: { type: "base64", media_type: mediaType, data: (await readFile(full)).toString("base64") },
106
+ origin: { by: "tool", name: "read_file" },
107
+ trust: "untrusted"
108
+ };
109
+ return { content: [image] };
110
+ }
111
+ if (path.extname(full).toLowerCase() === ".pdf") {
112
+ if (info.size > MAX_PDF_BYTES)
113
+ return { content: `PDF is ${info.size} bytes; at most ${MAX_PDF_BYTES} can be read`, isError: true };
114
+ const pdf = {
115
+ kind: "document",
116
+ source: { type: "base64", media_type: "application/pdf", data: (await readFile(full)).toString("base64") },
117
+ origin: { by: "tool", name: "read_file" },
118
+ trust: "untrusted"
119
+ };
120
+ return { content: [pdf] };
121
+ }
122
+ const buf = await readFile(full);
123
+ if (buf.subarray(0, 8000).includes(0)) {
124
+ return { content: `${display(cwd, full)} is a binary file (${buf.length} bytes) and cannot be shown as text`, isError: true };
125
+ }
126
+ const strict = utf8(buf);
127
+ const text = strict ?? legacyText(buf);
128
+ const note = strict === undefined ? `
129
+ (${notUtf8(display(cwd, full))})` : "";
130
+ if (strict !== undefined)
131
+ remember(full, info, opts.responses?.calls ?? -1, ctx?.toolUseId);
132
+ if (text.length === 0)
133
+ return { content: "(empty file)" };
134
+ const lines = text.split(/\r?\n/);
135
+ if (lines.at(-1) === "")
136
+ lines.pop();
137
+ const start = Math.max(1, offset);
138
+ const slice = lines.slice(start - 1, start - 1 + Math.min(limit, MAX_LINES));
139
+ if (slice.length === 0)
140
+ return { content: `(file has ${lines.length} lines; offset ${start} is past the end)`, isError: true };
141
+ const out = [];
142
+ let size = 0;
143
+ for (const [i, l] of slice.entries()) {
144
+ const row = `${start + i} ${l.length > MAX_LINE_CHARS ? `${l.slice(0, MAX_LINE_CHARS)}… [line truncated: ${l.length} characters]` : l}`;
145
+ if (out.length > 0 && size + row.length + 1 > MAX_READ_CHARS)
146
+ break;
147
+ out.push(row);
148
+ size += row.length + 1;
149
+ }
150
+ const body = out.join(`
151
+ `);
152
+ const end = start + out.length - 1;
153
+ if (out.length < slice.length) {
154
+ return { content: `${body}
155
+ (output capped at about ${MAX_READ_CHARS} characters: showing lines ${start}-${end} of ${lines.length}; continue with offset ${end + 1})${note}` };
156
+ }
157
+ return { content: (end < lines.length ? `${body}
158
+ (showing lines ${start}-${end} of ${lines.length})` : body) + note };
159
+ }
160
+ };
161
+ const writeFileTool = {
162
+ name: "write_file",
163
+ meta: { writes: "path" },
164
+ description: "Create a file or overwrite it with the complete new content. Missing parent directories are created. " + "An existing file must have been read with read_file first. Prefer edit_file for changing part of an existing file.",
165
+ inputSchema: {
166
+ type: "object",
167
+ properties: { path: str, content: str },
168
+ required: ["path", "content"],
169
+ additionalProperties: false
170
+ },
171
+ effect: "write",
172
+ concurrency: "exclusive",
173
+ idempotent: true,
174
+ async execute(input, ctx) {
175
+ const { path: p, content: given } = input;
176
+ const full = at(p);
177
+ const info = await statOrUndefined(full);
178
+ if (info?.isDirectory())
179
+ return { content: `${display(cwd, full)} is a directory`, isError: true };
180
+ const before = info ? utf8(await readFile(full)) ?? undefined : null;
181
+ if (before === undefined)
182
+ return { content: notUtf8(display(cwd, full)), isError: true };
183
+ const content = before === null ? given : keepStyle(before, given);
184
+ const problem = info && before !== null && before !== content ? staleness(full, info) : undefined;
185
+ if (problem)
186
+ return { content: problem, isError: true };
187
+ await mkdir(path.dirname(full), { recursive: true });
188
+ await writeFile(full, content);
189
+ remember(full, await stat(full), -1, ctx?.toolUseId);
190
+ const lines = content === "" ? 0 : content.split(/\r?\n/).length - (/\r?\n$/.test(content) ? 1 : 0);
191
+ return { content: `Wrote ${lines} lines to ${display(cwd, full)}` };
192
+ }
193
+ };
194
+ const applyEdits = async (p, edits) => {
195
+ const full = at(p);
196
+ const shown = display(cwd, full);
197
+ const info = await statOrUndefined(full);
198
+ if (!info) {
199
+ return { content: seen.has(full) ? `${shown} no longer exists` : `${shown} does not exist; use write_file to create it`, isError: true };
200
+ }
201
+ const text = utf8(await readFile(full));
202
+ if (text === undefined)
203
+ return { content: notUtf8(shown), isError: true };
204
+ const problem = staleness(full, info);
205
+ if (problem)
206
+ return { content: problem, isError: true };
207
+ let next = text;
208
+ let total = 0;
209
+ for (const [i, e] of edits.entries()) {
210
+ const r = replaceIn(next, e, shown);
211
+ if (typeof r === "string")
212
+ return { content: edits.length > 1 ? `edit ${i + 1} of ${edits.length}: ${r}. No edits were applied.` : r, isError: true };
213
+ next = r.text;
214
+ total += r.count;
215
+ }
216
+ await writeFile(full, next);
217
+ remember(full, await stat(full), -1, undefined);
218
+ return { content: `Edited ${shown} (${total} replacement${total === 1 ? "" : "s"})` };
219
+ };
220
+ const editFileTool = {
221
+ name: "edit_file",
222
+ meta: { writes: "path" },
223
+ description: "Replace exact text in a file. old_string must match the file exactly (including whitespace and indentation) " + "and must be unique unless replace_all is true. The file must have been read with read_file first, " + "and is refused if it changed since then. Use multi_edit for several changes to one file.",
224
+ inputSchema: {
225
+ type: "object",
226
+ properties: { path: str, old_string: str, new_string: str, replace_all: { type: "boolean" } },
227
+ required: ["path", "old_string", "new_string"],
228
+ additionalProperties: false
229
+ },
230
+ effect: "write",
231
+ concurrency: "exclusive",
232
+ idempotent: false,
233
+ async execute(input) {
234
+ const { path: p, ...edit } = input;
235
+ return applyEdits(p, [edit]);
236
+ }
237
+ };
238
+ const multiEditTool = {
239
+ name: "multi_edit",
240
+ meta: { writes: "path" },
241
+ description: "Make several exact-text replacements in one file at once. The edits are applied in order, each to the result of the previous one, " + "with the same rules as edit_file. Either all edits succeed or the file is left unchanged.",
242
+ inputSchema: {
243
+ type: "object",
244
+ properties: {
245
+ path: str,
246
+ edits: {
247
+ type: "array",
248
+ items: {
187
249
  type: "object",
188
- properties: { path: str, content: str },
189
- required: ["path", "content"],
190
- additionalProperties: false,
191
- },
192
- effect: "write",
193
- concurrency: "exclusive",
194
- // 写入完整内容,重复执行结果相同
195
- idempotent: true,
196
- async execute(input, ctx) {
197
- const { path: p, content: given } = input;
198
- const full = at(p);
199
- const info = await statOrUndefined(full);
200
- if (info?.isDirectory())
201
- return { content: `${display(cwd, full)} is a directory`, isError: true };
202
- // 同样内容重复写入(崩溃后重跑)不算覆盖别人的修改
203
- const before = info ? utf8(await readFile(full)) ?? undefined : null;
204
- if (before === undefined)
205
- return { content: notUtf8(display(cwd, full)), isError: true };
206
- // read_file 不显示换行风格和 BOM:覆盖已有文件时沿用原来的,否则整个文件每一行都算改了
207
- const content = before === null ? given : keepStyle(before, given);
208
- const problem = info && before !== null && before !== content ? staleness(full, info) : undefined;
209
- if (problem)
210
- return { content: problem, isError: true };
211
- await mkdir(path.dirname(full), { recursive: true });
212
- await writeFile(full, content);
213
- remember(full, await stat(full), -1, ctx?.toolUseId);
214
- // 和 read_file 一样数行:末尾的换行不算多出一行
215
- const lines = content === "" ? 0 : content.split(/\r?\n/).length - (/\r?\n$/.test(content) ? 1 : 0);
216
- return { content: `Wrote ${lines} lines to ${display(cwd, full)}` };
217
- },
218
- };
219
- /** edit_file 和 multi_edit 共用:检查文件能否修改,按顺序应用全部替换,全部成功才写入 */
220
- const applyEdits = async (p, edits) => {
221
- const full = at(p);
222
- const shown = display(cwd, full);
223
- const info = await statOrUndefined(full);
224
- if (!info) {
225
- return { content: seen.has(full) ? `${shown} no longer exists` : `${shown} does not exist; use write_file to create it`, isError: true };
250
+ properties: { old_string: str, new_string: str, replace_all: { type: "boolean" } },
251
+ required: ["old_string", "new_string"],
252
+ additionalProperties: false
253
+ }
226
254
  }
227
- const text = utf8(await readFile(full));
228
- if (text === undefined)
229
- return { content: notUtf8(shown), isError: true };
230
- const problem = staleness(full, info);
231
- if (problem)
232
- return { content: problem, isError: true };
233
- let next = text;
234
- let total = 0;
235
- for (const [i, e] of edits.entries()) {
236
- const r = replaceIn(next, e, shown);
237
- if (typeof r === "string")
238
- return { content: edits.length > 1 ? `edit ${i + 1} of ${edits.length}: ${r}. No edits were applied.` : r, isError: true };
239
- next = r.text;
240
- total += r.count;
255
+ },
256
+ required: ["path", "edits"],
257
+ additionalProperties: false
258
+ },
259
+ effect: "write",
260
+ concurrency: "exclusive",
261
+ idempotent: false,
262
+ async execute(input) {
263
+ const { path: p, edits } = input;
264
+ if (edits.length === 0)
265
+ return { content: "edits must not be empty", isError: true };
266
+ return applyEdits(p, edits);
267
+ }
268
+ };
269
+ const listDirTool = {
270
+ name: "list_dir",
271
+ description: "List the entries of a directory. Directories end with '/'.",
272
+ inputSchema: { type: "object", properties: { path: str }, required: ["path"], additionalProperties: false },
273
+ effect: "read",
274
+ concurrency: "safe",
275
+ idempotent: true,
276
+ async execute(input) {
277
+ const entries = await readdir(at(input.path), { withFileTypes: true });
278
+ const names = entries.map((e) => e.name + (e.isDirectory() ? "/" : "")).sort();
279
+ return { content: names.length > 0 ? names.join(`
280
+ `) : "(empty directory)" };
281
+ }
282
+ };
283
+ const globTool = {
284
+ name: "glob",
285
+ description: `Find files by glob pattern (e.g. "src/**/*.ts"), relative to path (default: the working directory). ` + `Unlike grep's include, "*.ts" matches only directly under path; use "**/*.ts" for any depth. ` + `Skips files ignored by git, .git and node_modules. Returns at most ${MAX_GLOB} paths.`,
286
+ inputSchema: {
287
+ type: "object",
288
+ properties: { pattern: str, path: str },
289
+ required: ["pattern"],
290
+ additionalProperties: false
291
+ },
292
+ effect: "read",
293
+ concurrency: "safe",
294
+ idempotent: true,
295
+ async execute(input, { signal }) {
296
+ const { pattern, path: p = "." } = input;
297
+ const root = at(p);
298
+ const out = [];
299
+ let more = false;
300
+ const match = globMatcher(pattern);
301
+ const tracked = await gitFiles(root);
302
+ const candidates = tracked ? filterAsync(tracked, async (rel) => match(rel) && Boolean((await statOrUndefined(path.join(root, rel)))?.isFile())) : scanGlob(root, match, signal);
303
+ for await (const rel of candidates) {
304
+ signal.throwIfAborted();
305
+ if (rel.split(/[\\/]/).some((seg) => SKIP_DIRS.has(seg)))
306
+ continue;
307
+ if (out.length >= MAX_GLOB) {
308
+ more = true;
309
+ break;
241
310
  }
242
- await writeFile(full, next);
243
- remember(full, await stat(full), -1, undefined);
244
- return { content: `Edited ${shown} (${total} replacement${total === 1 ? "" : "s"})` };
245
- };
246
- const editFileTool = {
247
- name: "edit_file",
248
- description: "Replace exact text in a file. old_string must match the file exactly (including whitespace and indentation) " +
249
- "and must be unique unless replace_all is true. The file must have been read with read_file first, " +
250
- "and is refused if it changed since then. Use multi_edit for several changes to one file.",
251
- inputSchema: {
252
- type: "object",
253
- properties: { path: str, old_string: str, new_string: str, replace_all: { type: "boolean" } },
254
- required: ["path", "old_string", "new_string"],
255
- additionalProperties: false,
256
- },
257
- effect: "write",
258
- concurrency: "exclusive",
259
- // 第二次执行时 old_string 可能已经不存在,或者被替换两次
260
- idempotent: false,
261
- async execute(input) {
262
- const { path: p, ...edit } = input;
263
- return applyEdits(p, [edit]);
264
- },
265
- };
266
- const multiEditTool = {
267
- name: "multi_edit",
268
- description: "Make several exact-text replacements in one file at once. The edits are applied in order, each to the result of the previous one, " +
269
- "with the same rules as edit_file. Either all edits succeed or the file is left unchanged.",
270
- inputSchema: {
271
- type: "object",
272
- properties: {
273
- path: str,
274
- edits: {
275
- type: "array",
276
- items: {
277
- type: "object",
278
- properties: { old_string: str, new_string: str, replace_all: { type: "boolean" } },
279
- required: ["old_string", "new_string"],
280
- additionalProperties: false,
281
- },
282
- },
283
- },
284
- required: ["path", "edits"],
285
- additionalProperties: false,
286
- },
287
- effect: "write",
288
- concurrency: "exclusive",
289
- idempotent: false,
290
- async execute(input) {
291
- const { path: p, edits } = input;
292
- if (edits.length === 0)
293
- return { content: "edits must not be empty", isError: true };
294
- return applyEdits(p, edits);
295
- },
296
- };
297
- const listDirTool = {
298
- name: "list_dir",
299
- description: "List the entries of a directory. Directories end with '/'.",
300
- inputSchema: { type: "object", properties: { path: str }, required: ["path"], additionalProperties: false },
301
- effect: "read",
302
- concurrency: "safe",
303
- idempotent: true,
304
- async execute(input) {
305
- const entries = await readdir(at(input.path), { withFileTypes: true });
306
- const names = entries.map((e) => e.name + (e.isDirectory() ? "/" : "")).sort();
307
- return { content: names.length > 0 ? names.join("\n") : "(empty directory)" };
308
- },
309
- };
310
- const globTool = {
311
- name: "glob",
312
- description: `Find files by glob pattern (e.g. "src/**/*.ts"), relative to path (default: the working directory). ` +
313
- `Unlike grep's include, "*.ts" matches only directly under path; use "**/*.ts" for any depth. ` +
314
- `Skips files ignored by git, .git and node_modules. Returns at most ${MAX_GLOB} paths.`,
315
- inputSchema: {
316
- type: "object",
317
- properties: { pattern: str, path: str },
318
- required: ["pattern"],
319
- additionalProperties: false,
320
- },
321
- effect: "read",
322
- concurrency: "safe",
323
- idempotent: true,
324
- async execute(input, { signal }) {
325
- const { pattern, path: p = "." } = input;
326
- const root = at(p);
327
- const out = [];
328
- let more = false;
329
- const match = globMatcher(pattern);
330
- const tracked = await gitFiles(root);
331
- const candidates = tracked
332
- ? filterAsync(tracked, async (rel) => match(rel) && Boolean((await statOrUndefined(path.join(root, rel)))?.isFile()))
333
- : scanGlob(root, match, signal);
334
- for await (const rel of candidates) {
335
- signal.throwIfAborted();
336
- if (rel.split(/[\\/]/).some((seg) => SKIP_DIRS.has(seg)))
337
- continue;
338
- if (out.length >= MAX_GLOB) {
339
- more = true;
340
- break;
341
- }
342
- out.push(display(cwd, path.join(root, rel)));
343
- }
344
- out.sort();
345
- // 和 grep 的 include 不同,不含 / 的模式只匹配第一层:模型常按 grep 的习惯写
346
- if (out.length === 0)
347
- return { content: pattern.includes("/") || pattern.startsWith("**") ? "No files matched" : `No files matched. "${pattern}" only matches directly under ${p === "." ? "the working directory" : p}; use "**/${pattern}" to search at any depth.` };
348
- return { content: out.join("\n") + (more ? `\n(more than ${MAX_GLOB} matches; narrow the pattern)` : "") };
349
- },
350
- };
351
- return [readFileTool, writeFileTool, editFileTool, multiEditTool, listDirTool, globTool, grepTool(cwd, { rg: opts.rg })];
311
+ out.push(display(cwd, path.join(root, rel)));
312
+ }
313
+ out.sort();
314
+ if (out.length === 0)
315
+ return { content: pattern.includes("/") || pattern.startsWith("**") ? "No files matched" : `No files matched. "${pattern}" only matches directly under ${p === "." ? "the working directory" : p}; use "**/${pattern}" to search at any depth.` };
316
+ return { content: out.join(`
317
+ `) + (more ? `
318
+ (more than ${MAX_GLOB} matches; narrow the pattern)` : "") };
319
+ }
320
+ };
321
+ return [readFileTool, writeFileTool, editFileTool, multiEditTool, listDirTool, globTool, grepTool(cwd, { rg: opts.rg })];
352
322
  }
353
- /** 按 edit_file / multi_edit 的规则把 edits 依次应用到 text 上;失败时返回原因。审批预览用它算出修改后的内容 */
354
323
  export function applyEditsToText(text, edits, shown) {
355
- let next = text;
356
- for (const [i, e] of edits.entries()) {
357
- const r = replaceIn(next, e, shown);
358
- if (typeof r === "string")
359
- return edits.length > 1 ? `edit ${i + 1} of ${edits.length}: ${r}` : r;
360
- next = r.text;
361
- }
362
- return { text: next };
324
+ let next = text;
325
+ for (const [i, e] of edits.entries()) {
326
+ const r = replaceIn(next, e, shown);
327
+ if (typeof r === "string")
328
+ return edits.length > 1 ? `edit ${i + 1} of ${edits.length}: ${r}` : r;
329
+ next = r.text;
330
+ }
331
+ return { text: next };
363
332
  }
364
- /** 按 UTF-8 解码(BOM 留着);不是合法的 UTF-8 时 undefined */
365
333
  export function utf8(buf) {
366
- try {
367
- return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buf);
368
- }
369
- catch {
370
- return undefined;
371
- }
334
+ try {
335
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buf);
336
+ } catch {
337
+ return;
338
+ }
372
339
  }
373
- /** 不是 UTF-8 的文本只用来显示:按 GB18030(含 GBK)解码,运行时不支持时按 UTF-8 解码、坏的字节显示成 U+FFFD */
374
340
  function legacyText(buf) {
375
- try {
376
- return new TextDecoder("gb18030").decode(buf);
377
- }
378
- catch {
379
- return buf.toString("utf8");
380
- }
341
+ try {
342
+ return new TextDecoder("gb18030").decode(buf);
343
+ } catch {
344
+ return buf.toString("utf8");
345
+ }
381
346
  }
382
- const notUtf8 = (shown) => `${shown} is not valid UTF-8 (read_file shows it decoded as GB18030). write_file and edit_file only handle UTF-8 and would corrupt it, so they refuse it: ` +
383
- "change it with a command that keeps its encoding, or ask the user before converting it to UTF-8.";
384
- /** text 里多数换行是 CRLF 时返回 "\r\n",多数是 LF 时返回 "\n",一样多或没有换行时返回 fallback */
347
+ const notUtf8 = (shown) => `${shown} is not valid UTF-8 (read_file shows it decoded as GB18030). write_file and edit_file only handle UTF-8 and would corrupt it, so they refuse it: ` + "change it with a command that keeps its encoding, or ask the user before converting it to UTF-8.";
385
348
  function eolOf(text, fallback) {
386
- const crlf = text.split("\r\n").length - 1;
387
- const lf = text.split("\n").length - 1 - crlf;
388
- return crlf > lf ? "\r\n" : lf > crlf ? "\n" : fallback;
349
+ const crlf = text.split(`\r
350
+ `).length - 1;
351
+ const lf = text.split(`
352
+ `).length - 1 - crlf;
353
+ return crlf > lf ? `\r
354
+ ` : lf > crlf ? `
355
+ ` : fallback;
389
356
  }
390
- /** 原文件主要用 CRLF、新内容只有 LF 时换成 CRLF;原文件有 BOM、新内容没有时补上 */
391
357
  export function keepStyle(before, content) {
392
- let out = content;
393
- if (eolOf(before, "\n") === "\r\n" && !out.includes("\r\n"))
394
- out = out.replaceAll("\n", "\r\n");
395
- if (before.startsWith("") && !out.startsWith(""))
396
- out = `${out}`;
397
- return out;
358
+ let out = content;
359
+ if (eolOf(before, `
360
+ `) === `\r
361
+ ` && !out.includes(`\r
362
+ `))
363
+ out = out.replaceAll(`
364
+ `, `\r
365
+ `);
366
+ if (before.startsWith("\uFEFF") && !out.startsWith("\uFEFF"))
367
+ out = `\uFEFF${out}`;
368
+ return out;
398
369
  }
399
370
  const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
400
- /** 在 text 上做一次替换;失败时返回原因 */
401
371
  function replaceIn(text, { old_string, new_string, replace_all }, shown) {
402
- if (old_string === new_string)
403
- return "old_string and new_string are identical";
404
- if (old_string === "")
405
- return "old_string must not be empty; use write_file to create a file";
406
- // read_file 不显示换行风格:old_string 里的换行匹配 LF 和 CRLF,CRLF 文件、换行混用的文件都能对上
407
- const pattern = new RegExp(old_string.split(/\r?\n/).map(escapeRegExp).join("\\r?\\n"), "g");
408
- const count = text.match(pattern)?.length ?? 0;
409
- if (count === 0)
410
- return `old_string not found in ${shown}${nearMiss(text, old_string)}`;
411
- if (count > 1 && !replace_all) {
412
- return `old_string occurs ${count} times in ${shown} (${linesOf(text, pattern, 5)}); add context to make it unique or set replace_all`;
413
- }
414
- // new_string 的换行沿用被替换那段的;那段只有一行时沿用整个文件的,单行改成多行也不会混进 LF
415
- const fileEol = eolOf(text, "\n");
416
- const to = (matched) => (new_string.includes("\r\n") ? new_string : new_string.replaceAll("\n", eolOf(matched, fileEol)));
417
- // 用函数作替换值,new_string 里的 $& $1 等不会被当成替换模式
418
- return { text: text.replace(replace_all ? pattern : new RegExp(pattern.source), to), count: replace_all ? count : 1 };
372
+ if (old_string === new_string)
373
+ return "old_string and new_string are identical";
374
+ if (old_string === "")
375
+ return "old_string must not be empty; use write_file to create a file";
376
+ const pattern = new RegExp(old_string.split(/\r?\n/).map(escapeRegExp).join("\\r?\\n"), "g");
377
+ const count = text.match(pattern)?.length ?? 0;
378
+ if (count === 0)
379
+ return `old_string not found in ${shown}${nearMiss(text, old_string)}`;
380
+ if (count > 1 && !replace_all) {
381
+ return `old_string occurs ${count} times in ${shown} (${linesOf(text, pattern, 5)}); add context to make it unique or set replace_all`;
382
+ }
383
+ const fileEol = eolOf(text, `
384
+ `);
385
+ const to = (matched) => new_string.includes(`\r
386
+ `) ? new_string : new_string.replaceAll(`
387
+ `, eolOf(matched, fileEol));
388
+ return { text: text.replace(replace_all ? pattern : new RegExp(pattern.source), to), count: replace_all ? count : 1 };
419
389
  }
420
- /** pattern 前 max 处匹配所在的行号,例如 "lines 3, 17, 40" */
421
390
  function linesOf(text, pattern, max) {
422
- const found = [];
423
- let line = 1;
424
- let from = 0;
425
- for (const m of text.matchAll(new RegExp(pattern.source, "g"))) {
426
- for (let i = from; i < m.index; i++)
427
- if (text.charCodeAt(i) === 10)
428
- line++;
429
- from = m.index;
430
- found.push(line);
431
- if (found.length === max)
432
- break;
433
- }
434
- return `line${found.length > 1 ? "s" : ""} ${found.join(", ")}${found.length === max ? ", …" : ""}`;
391
+ const found = [];
392
+ let line = 1;
393
+ let from = 0;
394
+ for (const m of text.matchAll(new RegExp(pattern.source, "g"))) {
395
+ for (let i = from;i < m.index; i++)
396
+ if (text.charCodeAt(i) === 10)
397
+ line++;
398
+ from = m.index;
399
+ found.push(line);
400
+ if (found.length === max)
401
+ break;
402
+ }
403
+ return `line${found.length > 1 ? "s" : ""} ${found.join(", ")}${found.length === max ? ", …" : ""}`;
435
404
  }
436
- /**
437
- * old_string 找不到时帮模型定位:忽略空白后能匹配到哪几行,或者第一行出现在哪里。
438
- * 只给提示,不自动按模糊匹配修改:那样可能改错地方
439
- */
440
405
  export function nearMiss(text, needle) {
441
- // 最常见的一种:把 read_file 每行开头的行号和制表符一起抄进来了
442
- const raw = needle.split(/\r?\n/).filter((l) => l.trim() !== "");
443
- if (raw.length > 0 && raw.every((l) => /^\s*\d+\t/.test(l))) {
444
- return ". It seems to include read_file's line-number prefixes (the number and tab at the start of each line); they are not part of the file. Remove them and keep the rest exactly";
445
- }
446
- const norm = (l) => l.trim().replace(/\s+/g, " ");
447
- const lines = text.split(/\r?\n/).map(norm);
448
- const want = needle.split(/\r?\n/).map(norm);
449
- while (want.length > 1 && want.at(-1) === "")
450
- want.pop();
451
- while (want.length > 1 && want[0] === "")
452
- want.shift();
453
- if (want.every((l) => l === ""))
454
- return "";
455
- const hits = [];
456
- for (let i = 0; i + want.length <= lines.length && hits.length < 3; i++) {
457
- if (want.every((l, k) => (k === 0 || k === want.length - 1 ? lines[i + k].includes(l) : lines[i + k] === l)))
458
- hits.push(i);
459
- }
460
- if (hits.length > 0) {
461
- const where = hits.map((i) => (want.length > 1 ? `${i + 1}-${i + want.length}` : `${i + 1}`)).join(", ");
462
- 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`;
463
- }
464
- const first = want.find((l) => l !== "");
465
- const at = lines.findIndex((l) => l.includes(first));
466
- if (at >= 0 && want.length > 1)
467
- 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`;
406
+ const raw = needle.split(/\r?\n/).filter((l) => l.trim() !== "");
407
+ if (raw.length > 0 && raw.every((l) => /^\s*\d+\t/.test(l))) {
408
+ return ". It seems to include read_file's line-number prefixes (the number and tab at the start of each line); they are not part of the file. Remove them and keep the rest exactly";
409
+ }
410
+ const norm = (l) => l.trim().replace(/\s+/g, " ");
411
+ const lines = text.split(/\r?\n/).map(norm);
412
+ const want = needle.split(/\r?\n/).map(norm);
413
+ while (want.length > 1 && want.at(-1) === "")
414
+ want.pop();
415
+ while (want.length > 1 && want[0] === "")
416
+ want.shift();
417
+ if (want.every((l) => l === ""))
468
418
  return "";
419
+ const hits = [];
420
+ for (let i = 0;i + want.length <= lines.length && hits.length < 3; i++) {
421
+ if (want.every((l, k) => k === 0 || k === want.length - 1 ? lines[i + k].includes(l) : lines[i + k] === l))
422
+ hits.push(i);
423
+ }
424
+ if (hits.length > 0) {
425
+ const where = hits.map((i) => want.length > 1 ? `${i + 1}-${i + want.length}` : `${i + 1}`).join(", ");
426
+ 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`;
427
+ }
428
+ const first = want.find((l) => l !== "");
429
+ const at = lines.findIndex((l) => l.includes(first));
430
+ if (at >= 0 && want.length > 1)
431
+ 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`;
432
+ return "";
469
433
  }
470
- export const statOrUndefined = (full) => stat(full).catch(() => undefined);
471
- /**
472
- * root 在 git 仓库里时,用 git 列出未被忽略的文件(已跟踪的和未跟踪的),路径相对于 root、用正斜杠。
473
- * 不在仓库里或没有 git 时返回 undefined
474
- */
434
+ export const statOrUndefined = (full) => stat(full).catch(() => {
435
+ return;
436
+ });
475
437
  async function gitFiles(root) {
476
- try {
477
- const { code, stdout: out } = await run(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"], { cwd: root });
478
- if (code !== 0)
479
- return undefined;
480
- // 合并冲突中的文件会出现多次
481
- return [...new Set(out.split("\0").filter(Boolean))];
482
- }
483
- catch {
484
- return undefined;
485
- }
438
+ try {
439
+ const { code, stdout: out } = await run(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"], { cwd: root });
440
+ if (code !== 0)
441
+ return;
442
+ return [...new Set(out.split("\x00").filter(Boolean))];
443
+ } catch {
444
+ return;
445
+ }
486
446
  }
487
447
  export async function listFiles(root, signal) {
488
- const tracked = await gitFiles(root);
489
- if (!tracked)
490
- return walk(root, signal);
491
- return tracked.filter((rel) => !rel.split("/").some((seg) => SKIP_DIRS.has(seg))).map((rel) => path.join(root, rel));
448
+ const tracked = await gitFiles(root);
449
+ if (!tracked)
450
+ return walk(root, signal);
451
+ return tracked.filter((rel) => !rel.split("/").some((seg) => SKIP_DIRS.has(seg))).map((rel) => path.join(root, rel));
492
452
  }
493
- /** 不在 git 仓库里时的 glob:遍历目录,跳过隐藏文件和目录(和原先 Bun.Glob#scan 的默认行为一致),产出相对路径 */
494
453
  async function* scanGlob(root, match, signal) {
495
- for await (const full of walk(root, signal)) {
496
- const rel = path.relative(root, full).split(path.sep).join("/");
497
- if (rel.split("/").some((seg) => seg.startsWith(".")))
498
- continue;
499
- if (match(rel))
500
- yield rel;
501
- }
454
+ for await (const full of walk(root, signal)) {
455
+ const rel = path.relative(root, full).split(path.sep).join("/");
456
+ if (rel.split("/").some((seg) => seg.startsWith(".")))
457
+ continue;
458
+ if (match(rel))
459
+ yield rel;
460
+ }
502
461
  }
503
462
  async function* filterAsync(items, keep) {
504
- for (const item of items)
505
- if (await keep(item))
506
- yield item;
463
+ for (const item of items)
464
+ if (await keep(item))
465
+ yield item;
507
466
  }
508
467
  async function* walk(dir, signal) {
509
- signal.throwIfAborted();
510
- // readdir 的顺序随文件系统而定(APFS 不排序),按名字排好,结果在各平台一致
511
- const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
512
- for (const e of entries) {
513
- const full = path.join(dir, e.name);
514
- if (e.isDirectory()) {
515
- if (!SKIP_DIRS.has(e.name))
516
- yield* walk(full, signal);
517
- }
518
- else if (e.isFile()) {
519
- yield full;
520
- }
468
+ signal.throwIfAborted();
469
+ const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
470
+ for (const e of entries) {
471
+ const full = path.join(dir, e.name);
472
+ if (e.isDirectory()) {
473
+ if (!SKIP_DIRS.has(e.name))
474
+ yield* walk(full, signal);
475
+ } else if (e.isFile()) {
476
+ yield full;
521
477
  }
478
+ }
522
479
  }