@uncarved/jade 0.3.1 → 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.
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/host.d.ts +2 -0
- package/dist/host.js +39 -5
- package/dist/host.js.map +1 -1
- package/dist/remote.js +5 -0
- package/dist/remote.js.map +1 -1
- package/dist/session.d.ts +7 -0
- package/dist/session.js +482 -27
- package/dist/session.js.map +1 -1
- package/package.json +4 -4
- package/plugins/approval/index.ts +36 -14
- package/plugins/approval/policy.ts +15 -10
- package/plugins/approval/review.ts +9 -5
- package/plugins/checks/checks.ts +10 -7
- package/plugins/checks/index.ts +13 -13
- package/plugins/checks/plugin.json +1 -1
- package/plugins/checks/project.ts +37 -38
- package/plugins/commands/index.ts +27 -3
- package/plugins/compact/compact.ts +13 -5
- package/plugins/compact/index.ts +20 -3
- package/plugins/compact/style.ts +13 -14
- package/plugins/completions/index.ts +35 -0
- package/plugins/completions/plugin.json +7 -0
- package/plugins/copy/index.ts +46 -0
- package/plugins/copy/plugin.json +7 -0
- package/plugins/editor/index.ts +10 -4
- package/plugins/fs/diff.ts +7 -6
- package/plugins/fs/fs.ts +8 -4
- package/plugins/fs/grep.ts +42 -9
- package/plugins/fs/index.ts +2 -7
- package/plugins/fs/plugin.json +1 -1
- package/plugins/fs/renderers.ts +16 -15
- package/plugins/fs/style.ts +16 -15
- package/plugins/hooks/index.ts +3 -2
- package/plugins/keys/index.ts +5 -1
- package/plugins/mcp/index.ts +197 -78
- package/plugins/mcp/install.ts +5 -3
- package/plugins/mcp/mcp.ts +163 -11
- package/plugins/mcp/plugin.json +2 -1
- package/plugins/mcp/project.ts +47 -50
- package/plugins/memory/index.ts +4 -4
- package/plugins/memory/style.ts +13 -14
- package/plugins/mentions/candidates.ts +67 -0
- package/plugins/mentions/index.ts +12 -5
- package/plugins/mentions/plugin.json +1 -1
- package/plugins/mentions/style.ts +13 -14
- package/plugins/models/configure.ts +10 -9
- package/plugins/models/index.ts +27 -1
- package/plugins/modes/index.ts +13 -2
- package/plugins/print/index.ts +7 -4
- package/plugins/prompts/index.ts +0 -0
- package/plugins/renderers/index.ts +10 -5
- package/plugins/repeats/index.ts +8 -8
- package/plugins/schedule/index.ts +2 -0
- package/plugins/screenshot/browser.ts +10 -0
- package/plugins/sessions/index.ts +48 -2
- package/plugins/shell/index.ts +20 -25
- package/plugins/shell/plugin.json +1 -2
- package/plugins/shell/renderers.ts +9 -7
- package/plugins/shell/shell.ts +3 -1
- package/plugins/skills/index.ts +28 -19
- package/plugins/skills/project.ts +12 -7
- package/plugins/steer/index.ts +5 -4
- package/plugins/task/index.ts +80 -50
- package/plugins/task/plugin.json +6 -2
- package/plugins/task/style.ts +13 -14
- package/plugins/task/subagent.ts +67 -184
- package/plugins/todo/index.ts +39 -9
- package/plugins/tools/index.ts +9 -2
- package/plugins/tui/frontend.ts +139 -89
- package/plugins/tui/index.ts +2 -3
- package/plugins/tui/mentions.ts +11 -80
- package/plugins/tui/plugin.json +1 -1
- package/plugins/tui/screen.ts +55 -5
- package/plugins/tui/transcript.ts +17 -7
- package/plugins/tui/tui.ts +337 -101
- package/plugins/tui/vendor.ts +1 -1
- package/plugins/undo/checkpoint.ts +5 -3
- package/plugins/undo/index.ts +43 -14
- package/plugins/undo/style.ts +13 -14
- package/plugins/web/index.ts +7 -18
- package/plugins/web/plugin.json +1 -1
- package/plugins-dist/approval/index.js +363 -418
- package/plugins-dist/approval/policy.js +391 -508
- package/plugins-dist/approval/review.js +132 -158
- package/plugins-dist/approval/schema.js +50 -55
- package/plugins-dist/ask/index.js +115 -129
- package/plugins-dist/budget/index.js +27 -31
- package/plugins-dist/checks/checks.js +293 -329
- package/plugins-dist/checks/index.js +119 -139
- package/plugins-dist/checks/plugin.json +2 -1
- package/plugins-dist/checks/project.js +57 -65
- package/plugins-dist/commands/index.js +47 -29
- package/plugins-dist/compact/compact.js +233 -249
- package/plugins-dist/compact/index.js +98 -95
- package/plugins-dist/compact/style.js +9 -14
- package/plugins-dist/completions/index.js +30 -0
- package/plugins-dist/completions/plugin.json +9 -0
- package/plugins-dist/continue/index.js +40 -52
- package/plugins-dist/copy/index.js +40 -0
- package/plugins-dist/copy/plugin.json +9 -0
- package/plugins-dist/cost/index.js +98 -115
- package/plugins-dist/custom-commands/index.js +55 -72
- package/plugins-dist/editor/index.js +64 -72
- package/plugins-dist/fs/diff.js +111 -124
- package/plugins-dist/fs/fs.js +426 -469
- package/plugins-dist/fs/grep.js +262 -253
- package/plugins-dist/fs/index.js +20 -34
- package/plugins-dist/fs/plugin.json +1 -2
- package/plugins-dist/fs/renderers.js +100 -112
- package/plugins-dist/fs/style.js +11 -15
- package/plugins-dist/fs/sys.js +31 -43
- package/plugins-dist/hooks/index.js +107 -127
- package/plugins-dist/keys/index.js +27 -31
- package/plugins-dist/mcp/index.js +271 -199
- package/plugins-dist/mcp/install.js +123 -137
- package/plugins-dist/mcp/mcp.js +638 -577
- package/plugins-dist/mcp/plugin.json +3 -1
- package/plugins-dist/mcp/project.js +98 -115
- package/plugins-dist/memory/index.js +83 -88
- package/plugins-dist/memory/memory.js +111 -128
- package/plugins-dist/memory/style.js +9 -14
- package/plugins-dist/mentions/attach.js +91 -99
- package/plugins-dist/mentions/candidates.js +49 -0
- package/plugins-dist/mentions/index.js +71 -81
- package/plugins-dist/mentions/plugin.json +2 -1
- package/plugins-dist/mentions/style.js +9 -14
- package/plugins-dist/models/config.js +29 -43
- package/plugins-dist/models/configure.js +392 -473
- package/plugins-dist/models/context.js +14 -22
- package/plugins-dist/models/index.js +182 -189
- package/plugins-dist/models/provider.js +243 -307
- package/plugins-dist/models/saved.js +59 -71
- package/plugins-dist/modes/index.js +138 -165
- package/plugins-dist/plugins/index.js +34 -34
- package/plugins-dist/print/index.js +192 -175
- package/plugins-dist/prompts/index.js +81 -89
- package/plugins-dist/prompts/notes.js +31 -37
- package/plugins-dist/prompts/prompts.js +155 -193
- package/plugins-dist/prompts/results.js +40 -53
- package/plugins-dist/prompts/sys.js +39 -50
- package/plugins-dist/renderers/index.js +32 -32
- package/plugins-dist/repeats/index.js +131 -174
- package/plugins-dist/schedule/cron.js +49 -56
- package/plugins-dist/schedule/index.js +229 -247
- package/plugins-dist/schedule/store.js +93 -109
- package/plugins-dist/scratch/index.js +12 -18
- package/plugins-dist/screenshot/browser.js +136 -154
- package/plugins-dist/screenshot/index.js +37 -46
- package/plugins-dist/screenshot/sys.js +53 -65
- package/plugins-dist/screenshot/tool.js +98 -126
- package/plugins-dist/sessions/index.js +149 -117
- package/plugins-dist/shell/index.js +115 -135
- package/plugins-dist/shell/plugin.json +1 -2
- package/plugins-dist/shell/renderers.js +28 -33
- package/plugins-dist/shell/service.js +17 -23
- package/plugins-dist/shell/shell.js +307 -362
- package/plugins-dist/shell/sys.js +64 -79
- package/plugins-dist/skills/index.js +193 -211
- package/plugins-dist/skills/install.js +122 -149
- package/plugins-dist/skills/project.js +65 -73
- package/plugins-dist/skills/skills.js +135 -171
- package/plugins-dist/steer/index.js +108 -125
- package/plugins-dist/suggest/index.js +235 -259
- package/plugins-dist/task/index.js +130 -117
- package/plugins-dist/task/plugin.json +5 -2
- package/plugins-dist/task/style.js +9 -14
- package/plugins-dist/task/subagent.js +156 -279
- package/plugins-dist/todo/index.js +79 -63
- package/plugins-dist/tools/index.js +36 -42
- package/plugins-dist/tui/editor.js +145 -160
- package/plugins-dist/tui/frontend.js +639 -678
- package/plugins-dist/tui/history.js +34 -37
- package/plugins-dist/tui/index.js +16 -18
- package/plugins-dist/tui/markdown.js +203 -247
- package/plugins-dist/tui/mascot.js +266 -355
- package/plugins-dist/tui/mentions.js +67 -144
- package/plugins-dist/tui/plugin.json +1 -2
- package/plugins-dist/tui/render.js +35 -45
- package/plugins-dist/tui/screen.js +197 -180
- package/plugins-dist/tui/transcript.js +436 -468
- package/plugins-dist/tui/tui.js +1554 -1656
- package/plugins-dist/undo/checkpoint.js +95 -118
- package/plugins-dist/undo/index.js +185 -192
- package/plugins-dist/undo/snapshot.js +83 -99
- package/plugins-dist/undo/style.js +9 -14
- package/plugins-dist/update/index.js +26 -28
- package/plugins-dist/web/env.js +55 -68
- package/plugins-dist/web/index.js +80 -110
- package/plugins-dist/web/plugin.json +1 -2
- package/plugins-dist/web/renderers.js +4 -5
- package/plugins-dist/web/web.js +514 -593
- package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
- package/sdk/python/jade_plugin.py +9 -2
- package/src/api.ts +1 -1
- package/src/host.ts +39 -4
- package/src/remote.ts +6 -1
- package/src/session.ts +489 -34
package/plugins-dist/fs/fs.js
CHANGED
|
@@ -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
|
-
|
|
15
|
-
const MAX_READ_CHARS = 100_000;
|
|
7
|
+
const MAX_READ_CHARS = 1e5;
|
|
16
8
|
const MAX_GLOB = 500;
|
|
17
|
-
const MAX_IMAGE_BYTES =
|
|
18
|
-
const MAX_PDF_BYTES =
|
|
9
|
+
const MAX_IMAGE_BYTES = 5000000;
|
|
10
|
+
const MAX_PDF_BYTES = 1e7;
|
|
19
11
|
const IMAGE_TYPES = {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
-
|
|
22
|
+
return path.resolve(cwd, p);
|
|
32
23
|
}
|
|
33
|
-
/** 显示用:工作目录内的路径用相对形式,统一为正斜杠 */
|
|
34
24
|
export function display(cwd, full) {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
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
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
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
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
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: {
|
|
189
|
-
required: ["
|
|
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
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
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
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
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
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
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
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
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
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
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
|
-
|
|
387
|
-
|
|
388
|
-
|
|
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
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
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
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
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
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
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
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
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(() =>
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
* 不在仓库里或没有 git 时返回 undefined
|
|
474
|
-
*/
|
|
434
|
+
export const statOrUndefined = (full) => stat(full).catch(() => {
|
|
435
|
+
return;
|
|
436
|
+
});
|
|
475
437
|
async function gitFiles(root) {
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
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
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
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
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
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
|
-
|
|
505
|
-
|
|
506
|
-
|
|
463
|
+
for (const item of items)
|
|
464
|
+
if (await keep(item))
|
|
465
|
+
yield item;
|
|
507
466
|
}
|
|
508
467
|
async function* walk(dir, signal) {
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
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
|
}
|