@hncode/hncode 0.5.1 → 0.5.2
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/bin/install.cjs +24 -44
- package/bin/preinstall.cjs +0 -14
- package/package.json +1 -1
- package/src/agent-task.js +12 -1
- package/src/agent.js +111 -33
- package/src/cell-buffer.js +5 -0
- package/src/clipboard.js +42 -6
- package/src/context-bar.js +46 -5
- package/src/doctor.js +7 -2
- package/src/git.js +35 -4
- package/src/llm.js +6 -0
- package/src/permissions.js +29 -7
- package/src/registry-browser.js +21 -6
- package/src/session-core.js +203 -0
- package/src/session-host.js +213 -0
- package/src/session-view.js +110 -0
- package/src/settings-schema.js +12 -9
- package/src/shell-safety.js +95 -6
- package/src/swarm-progress.js +348 -293
- package/src/tasks-browser.js +4 -1
- package/src/team/constants.js +20 -0
- package/src/team/context.js +89 -0
- package/src/team/mailbox.js +139 -0
- package/src/team/runner.js +347 -0
- package/src/team/spawn.js +247 -0
- package/src/team/store.js +145 -0
- package/src/team/tasks.js +164 -0
- package/src/team/team.js +311 -0
- package/src/team-panel.js +226 -0
- package/src/term.js +27 -0
- package/src/tool-result.js +20 -5
- package/src/tools/agent-swarm.js +114 -11
- package/src/tools/agent.js +53 -3
- package/src/tools/edit.js +591 -436
- package/src/tools/git.js +15 -3
- package/src/tools/index.js +2 -0
- package/src/tools/team.js +398 -0
- package/src/tools/web-search.js +88 -75
- package/src/tui.js +5805 -4862
- package/src/update.js +285 -115
- package/src/web-daemon.js +27 -4
- package/src/web-live.js +250 -0
package/src/tools/edit.js
CHANGED
|
@@ -1,436 +1,591 @@
|
|
|
1
|
-
// Edit tool — mirrors the hncode Edit tool schema & behavior.
|
|
2
|
-
// Snippet-based exact replacement (old_string -> new_string), NOT a whole-file rewrite,
|
|
3
|
-
// so edits stay token-cheap (unlike kimi-code-cli's whole-file Edit).
|
|
4
|
-
|
|
5
|
-
import fs from 'node:fs';
|
|
6
|
-
import path from 'node:path';
|
|
7
|
-
import { resolvePath, ensureDir, checkpointBeforeWrite } from './utils.js';
|
|
8
|
-
import { hashStr, normalizeText } from './read.js';
|
|
9
|
-
|
|
10
|
-
// Typographic quotes -> straight quotes. A model almost always emits ASCII
|
|
11
|
-
// quotes, but docs/blog/markdown often use curly ones; without this the edit
|
|
12
|
-
// fails with "old_string not found" even though the text is visibly there.
|
|
13
|
-
// Mirrors Claude Code's normalizeQuotes.
|
|
14
|
-
const CURLY = [
|
|
15
|
-
['\u2018', "'"], ['\u2019', "'"], // ‘ ’
|
|
16
|
-
['\u201c', '"'], ['\u201d', '"'], // “ ”
|
|
17
|
-
];
|
|
18
|
-
export function normalizeQuotes(s) {
|
|
19
|
-
let out = String(s);
|
|
20
|
-
for (const [from, to] of CURLY) out = out.split(from).join(to);
|
|
21
|
-
return out;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
// Re-exported from read.js so the staleness guard has ONE definition of the
|
|
25
|
-
// region hash. Previously read.js and edit.js each had their own copy; any
|
|
26
|
-
// drift between them would silently disable staleness detection.
|
|
27
|
-
import { hashRegion as hashLines } from './read.js';
|
|
28
|
-
|
|
29
|
-
export const spec = {
|
|
30
|
-
name: 'Edit',
|
|
31
|
-
description: 'Edit a file.
|
|
32
|
-
parameters: {
|
|
33
|
-
type: 'object',
|
|
34
|
-
properties: {
|
|
35
|
-
path: { type: 'string', description: 'Path to the file to edit.' },
|
|
36
|
-
old_string: { type: 'string', description: 'Exact text to replace, including whitespace and newlines. Omit
|
|
37
|
-
new_string: { type: 'string', description: 'Replacement text, written VERBATIM in BOTH modes — no indentation is added, removed, or re-derived. Write the leading spaces on EVERY line yourself, including the FIRST one, copying them from the Read output after its `N\\t` line-number prefix (Read prints `12\\t return x`, so you send ` return x`). In LINE-RANGE mode it must contain EXACTLY the lines being replaced: a line that sits outside [start_line, end_line] is not deleted, so restating it here leaves a duplicate. In SUBSTRING mode it replaces old_string, which is itself matched exactly including its own indentation.' },
|
|
38
|
-
|
|
39
|
-
replace_all: { type: 'boolean', default: false, description: 'Replace all occurrences of old_string.' },
|
|
40
|
-
start_line: { type: 'integer', minimum: 1, description: 'PREFERRED MODE. 1-based first line to replace (requires end_line and new_string).
|
|
41
|
-
end_line: { type: 'integer', minimum: 1, description: 'PREFERRED MODE. 1-based last line to replace (inclusive; requires start_line).' },
|
|
42
|
-
},
|
|
43
|
-
//
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
//
|
|
55
|
-
//
|
|
56
|
-
// the
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
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
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
//
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
//
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
//
|
|
268
|
-
//
|
|
269
|
-
//
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
//
|
|
305
|
-
//
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
//
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
//
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
}
|
|
1
|
+
// Edit tool — mirrors the hncode Edit tool schema & behavior.
|
|
2
|
+
// Snippet-based exact replacement (old_string -> new_string), NOT a whole-file rewrite,
|
|
3
|
+
// so edits stay token-cheap (unlike kimi-code-cli's whole-file Edit).
|
|
4
|
+
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { resolvePath, ensureDir, checkpointBeforeWrite } from './utils.js';
|
|
8
|
+
import { hashStr, normalizeText } from './read.js';
|
|
9
|
+
|
|
10
|
+
// Typographic quotes -> straight quotes. A model almost always emits ASCII
|
|
11
|
+
// quotes, but docs/blog/markdown often use curly ones; without this the edit
|
|
12
|
+
// fails with "old_string not found" even though the text is visibly there.
|
|
13
|
+
// Mirrors Claude Code's normalizeQuotes.
|
|
14
|
+
const CURLY = [
|
|
15
|
+
['\u2018', "'"], ['\u2019', "'"], // ‘ ’
|
|
16
|
+
['\u201c', '"'], ['\u201d', '"'], // “ ”
|
|
17
|
+
];
|
|
18
|
+
export function normalizeQuotes(s) {
|
|
19
|
+
let out = String(s);
|
|
20
|
+
for (const [from, to] of CURLY) out = out.split(from).join(to);
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Re-exported from read.js so the staleness guard has ONE definition of the
|
|
25
|
+
// region hash. Previously read.js and edit.js each had their own copy; any
|
|
26
|
+
// drift between them would silently disable staleness detection.
|
|
27
|
+
import { hashRegion as hashLines } from './read.js';
|
|
28
|
+
|
|
29
|
+
export const spec = {
|
|
30
|
+
name: 'Edit',
|
|
31
|
+
description: 'Edit a file. THREE shapes:\n- LINE-RANGE mode: path + start_line + end_line + new_string. Replaces lines [start_line, end_line] with new_string.\nPREFERRED — use it whenever you have Read the file and know the line numbers.\n- EXACT-SUBSTRING mode: path + old_string + new_string. Replaces text exactly matching old_string. Use when the exact text is known and a line range is not convenient.\n- RANGED SUBSTRING mode: path + start_line + end_line + old_string + new_string. Searches for old_string ONLY inside [start_line, end_line], and replaces only what it finds there. Use this when the same snippet appears several times and you need exactly one of them: replace_all changes every copy, while plain substring mode refuses an ambiguous match. The range says WHERE to look, old_string says WHAT to replace.\nLEADING WHITESPACE — SPELL IT OUT ON EVERY LINE, INCLUDING THE FIRST. new_string is written VERBATIM in both modes: nothing is re-indented, auto-indented, or trimmed, and there is no tolerance for a missing first-line indent. Reproduce the indentation the code SHOULD have; it need not match the surrounding block. Copy it from the Read output, after its `N\\t` line-number prefix (Read prints `12\\t return x`, so you send ` return x`).\nWRONG — nothing between the quote and `return`, so the line lands at column 0 inside an indented block. Look at the SHAPE as well: the quote touches the first character, and spaces only turn up after the first newline.\nnew_string: "return total;\n total += 1;"\nRIGHT — four spaces, then `return`. The opening quote is followed by the indent as well, so every line carries its own indentation INCLUDING the first:\nnew_string: " return total;\n total += 1;"\nSame call, same words. The only difference is the spaces at the START of the first line, and that is the whole point — in the RIGHT form the indent sits between the quote and the code, exactly where it sits in the file you copied it from.\nThe same applies to tabs, and to a line whose indentation changes partway through.\nRANGE HYGIENE — WRITE ONLY THE LINES YOU ARE REPLACING. Lines [start_line, end_line] are deleted and new_string is inserted in their place, so a line you leave OUTSIDE that range survives — and if you also restated it inside new_string you get TWO copies. Check what sits on end_line + 1 before deciding where the range ends. In RANGED SUBSTRING mode this does not apply: only the snippet is replaced, not the whole range.\nWRONG — end_line: 3 deletes lines 2-3, but line 4 is repeated because its content was also written into new_string:\nnew_string: "const a = 1;\\nconst b = 20;\\nconst c = 3;"\nRIGHT — the range covers exactly what is being replaced, and nothing beyond it is restated:\nnew_string: "const a = 1;\\nconst b = 20;"\nTo touch line 4 as well, set end_line: 4 and include its new content in new_string.\nIn SUBSTRING and RANGED SUBSTRING modes old_string is matched EXACTLY, including the indentation of its own first line.\nOmitting new_string is an error, not an empty replacement.\nMis-indented lines often still parse, so a green test run is not proof that an edit landed correctly — re-Read the region before editing it again.\',',
|
|
32
|
+
parameters: {
|
|
33
|
+
type: 'object',
|
|
34
|
+
properties: {
|
|
35
|
+
path: { type: 'string', description: 'Path to the file to edit.' },
|
|
36
|
+
old_string: { type: 'string', description: 'Exact text to replace, including whitespace and newlines. Omit for pure line-range mode. COMBINE it with start_line/end_line to replace only the occurrence inside that range.' },
|
|
37
|
+
new_string: { type: 'string', description: 'Replacement text, written VERBATIM in BOTH modes — no indentation is added, removed, or re-derived. Write the leading spaces on EVERY line yourself, including the FIRST one, copying them from the Read output after its `N\\t` line-number prefix (Read prints `12\\t return x`, so you send ` return x`). In LINE-RANGE mode it must contain EXACTLY the lines being replaced: a line that sits outside [start_line, end_line] is not deleted, so restating it here leaves a duplicate. In SUBSTRING mode it replaces old_string, which is itself matched exactly including its own indentation.' },
|
|
38
|
+
|
|
39
|
+
replace_all: { type: 'boolean', default: false, description: 'Replace all occurrences of old_string.' },
|
|
40
|
+
start_line: { type: 'integer', minimum: 1, description: 'PREFERRED MODE. 1-based first line to replace (requires end_line and new_string). With old_string too, it is the first line to SEARCH for it in.' },
|
|
41
|
+
end_line: { type: 'integer', minimum: 1, description: 'PREFERRED MODE. 1-based last line to replace (inclusive; requires start_line). With old_string too, it is the last line to search in.' },
|
|
42
|
+
},
|
|
43
|
+
// Three accepted shapes:
|
|
44
|
+
// line-range start_line + end_line + new_string
|
|
45
|
+
// exact-substring old_string + new_string
|
|
46
|
+
// rangedToWindow-substring start_line + end_line + old_string + new_string
|
|
47
|
+
// Line-range is the preferred route; the third exists for "one of several copies".
|
|
48
|
+
anyOf: [
|
|
49
|
+
{ required: ['path', 'start_line', 'end_line', 'new_string'] },
|
|
50
|
+
{ required: ['path', 'old_string', 'new_string'] },
|
|
51
|
+
],
|
|
52
|
+
},
|
|
53
|
+
async execute(args, ctx) {
|
|
54
|
+
// Validate BEFORE resolving the path. `resolvePath(undefined)` resolves to the
|
|
55
|
+
// workspace root rather than failing, so a truncated tool call (agent.js falls
|
|
56
|
+
// back to `{ raw, _rawLen }` when the streamed JSON will not parse) could
|
|
57
|
+
// target a DIRECTORY and produce a confusing EISDIR/ENOENT instead of "retry
|
|
58
|
+
// the call".
|
|
59
|
+
if (typeof args.path !== 'string' || !args.path.trim()) {
|
|
60
|
+
const truncated = args && args.raw
|
|
61
|
+
? ` The arguments did not parse as JSON${args._rawLen ? ` (${args._rawLen} characters received)` : ''} — the call was most likely truncated. Retry, and keep \`old_string\` / \`new_string\` small (edit in several passes rather than one large replacement).`
|
|
62
|
+
: '';
|
|
63
|
+
return `Error: \`path\` is required and must be a non-empty string.${truncated}`;
|
|
64
|
+
}
|
|
65
|
+
let p;
|
|
66
|
+
try { p = resolvePath(args.path, ctx); } catch (e) { return e.message; }
|
|
67
|
+
// A Jupyter notebook is JSON, not text: a snippet edit corrupts it. Point the
|
|
68
|
+
// model at the notebook-aware tool instead (mirrors Claude Code errorCode 5).
|
|
69
|
+
if (String(p).toLowerCase().endsWith('.ipynb')) {
|
|
70
|
+
return `Error: ${args.path} is a Jupyter notebook, and its .ipynb is JSON — a text replacement would corrupt it. Use NotebookEdit instead: \`{ path: ${JSON.stringify(args.path)}, action: "list" }\` to see the cells, then action "replace" with the cell index.`;
|
|
71
|
+
}
|
|
72
|
+
let content;
|
|
73
|
+
try {
|
|
74
|
+
content = fs.readFileSync(p, 'utf8');
|
|
75
|
+
} catch (e) {
|
|
76
|
+
if (e && e.code === 'ENOENT') {
|
|
77
|
+
return `Error reading ${args.path}: file does not exist.${similarFileHint(p)}`;
|
|
78
|
+
}
|
|
79
|
+
return `Error reading ${args.path}: ${e.message}`;
|
|
80
|
+
}
|
|
81
|
+
const { start_line, end_line } = args;
|
|
82
|
+
// THREE shapes, not two.
|
|
83
|
+
//
|
|
84
|
+
// line-range start_line + end_line + new_string
|
|
85
|
+
// substring old_string + new_string
|
|
86
|
+
// RANGED SUB start_line + end_line + old_string + new_string
|
|
87
|
+
//
|
|
88
|
+
// The third is what the first two cannot express: replace ONE occurrence of a snippet that
|
|
89
|
+
// appears several times, without `replace_all` (which would hit every copy) and without
|
|
90
|
+
// counting lines by hand. The range narrows WHERE to look; `old_string` says WHAT to replace
|
|
91
|
+
// inside it. Rejecting the combination sent callers to `replace_all` as their only option,
|
|
92
|
+
// which is how the wrong copy gets edited.
|
|
93
|
+
//
|
|
94
|
+
// `old_string` alongside a range is therefore not a mistake — but a range with NEITHER
|
|
95
|
+
// old_string nor new_string still is, and is reported below.
|
|
96
|
+
const hasRangeKeys = args.start_line != null || args.end_line != null;
|
|
97
|
+
const hasSubKeys = args.old_string != null;
|
|
98
|
+
const hasNewString = (args.new_string != null) || (args.new_content != null);
|
|
99
|
+
if (hasRangeKeys && hasSubKeys && !hasNewString) {
|
|
100
|
+
return 'Error: a rangedToWindow edit needs new_string as well as old_string.';
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---- RANGED SUBSTRING ---------------------------------------------------
|
|
104
|
+
// A range AND an old_string: search for the snippet only INSIDE the range. Handled here,
|
|
105
|
+
// before the pure line-range path, because that path replaces whole lines and would ignore
|
|
106
|
+
// the snippet entirely — the very ambiguity the old mutual-exclusion check was avoiding.
|
|
107
|
+
//
|
|
108
|
+
// The range is validated, then the substring path below does the matching with the search
|
|
109
|
+
// window clamped to it. Splitting the work this way keeps ONE implementation of matching
|
|
110
|
+
// (quote-normalized retry, staleness, whitespace tolerance) instead of a second, weaker copy.
|
|
111
|
+
// A HALF-GIVEN RANGE with an old_string is not a reason to refuse: the snippet locates the
|
|
112
|
+
// edit by itself, and the single bound is a hint that failed to pair. Callers add `start_line`
|
|
113
|
+
// from the schema's own wording ("1-based first line to replace") expecting it to help, so
|
|
114
|
+
// refusing rejected a request that was already complete.
|
|
115
|
+
//
|
|
116
|
+
// `rangedToWindow` is set even though no window is applied. It means "the range question has been
|
|
117
|
+
// settled", which is what the line-range guard below tests — leaving it false made that guard
|
|
118
|
+
// see the same unpaired bound and reject the call one block later.
|
|
119
|
+
let searchFrom = 0;
|
|
120
|
+
let searchTo = 0; // 0,0 = the whole file
|
|
121
|
+
// A real window was validated, so the search below is confined to it. Distinct from
|
|
122
|
+
// `rangeHandled`: this one means "clamp", and setting it for a snippet with no window made
|
|
123
|
+
// every search run inside 0..0 and find nothing.
|
|
124
|
+
let rangedToWindow = false;
|
|
125
|
+
// The range question is answered — either a window was applied, or the caller gave an
|
|
126
|
+
// `old_string` that locates the edit on its own and a half-given bound was ignored.
|
|
127
|
+
let rangeHandled = hasSubKeys;
|
|
128
|
+
if (hasRangeKeys && hasSubKeys && hasNewString) {
|
|
129
|
+
if ((start_line != null) !== (end_line != null)) {
|
|
130
|
+
// Ignore the unpaired bound; `searchFrom`/`searchTo` stay at the whole file and `rangedToWindow`
|
|
131
|
+
// was already set above.
|
|
132
|
+
searchFrom = 0;
|
|
133
|
+
searchTo = 0;
|
|
134
|
+
} else {
|
|
135
|
+
// The range was given in full: validate it, then confine the search to it.
|
|
136
|
+
const start = Number(start_line) | 0, end = Number(end_line) | 0;
|
|
137
|
+
if (!Number.isFinite(start) || !Number.isFinite(end) || start < 1 || end < start) {
|
|
138
|
+
return `Error: invalid line range ${start_line}-${end_line} (expected 1-based, start <= end).`;
|
|
139
|
+
}
|
|
140
|
+
{
|
|
141
|
+
const all = content.split(/\r\n|\r|\n/);
|
|
142
|
+
if (end > all.length) {
|
|
143
|
+
return `Error: end_line ${end_line} exceeds file length (${all.length} lines).`;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
rangedToWindow = true;
|
|
147
|
+
rangeHandled = true;
|
|
148
|
+
searchFrom = start;
|
|
149
|
+
searchTo = end;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// ---- LINE-RANGE mode ---------------------------------------------------
|
|
154
|
+
// `start_line`..`end_line` replace the lines at those 1-based positions,
|
|
155
|
+
// with NO old_string involved at all. This is the path for "change line 12"
|
|
156
|
+
// where spelling out the exact current text is awkward.
|
|
157
|
+
if (!rangeHandled && (start_line != null) !== (end_line != null)) {
|
|
158
|
+
return 'Error: line-range mode needs BOTH start_line and end_line.';
|
|
159
|
+
}
|
|
160
|
+
if (!rangeHandled && start_line != null && end_line != null) {
|
|
161
|
+
// Accept both spellings so old new_content callers keep working.
|
|
162
|
+
const new_string = args.new_string != null ? args.new_string : args.new_content;
|
|
163
|
+
// new_string is required — a missing one would put the literal string
|
|
164
|
+
// "undefined" in the file.
|
|
165
|
+
if (new_string == null) return `Error: new_string is required for line-range mode (pass an empty string to delete the lines).`;
|
|
166
|
+
if (typeof new_string !== 'string') {
|
|
167
|
+
return `Error: new_string must be a string (got ${new_string === null ? 'null' : typeof new_string}).`;
|
|
168
|
+
}
|
|
169
|
+
const start = Number(start_line) | 0, end = Number(end_line) | 0;
|
|
170
|
+
if (start < 1 || end < start) {
|
|
171
|
+
return `Error: invalid line range ${start_line}-${end_line} (expected 1-based, start <= end).`;
|
|
172
|
+
}
|
|
173
|
+
const eol = content.includes('\r\n') ? '\r\n' : '\n';
|
|
174
|
+
const lines = content.split(/\r\n|\r|\n/);
|
|
175
|
+
if (end > lines.length) {
|
|
176
|
+
return `Error: end_line ${end_line} exceeds file length (${lines.length} lines).`;
|
|
177
|
+
}
|
|
178
|
+
// STALENESS: the range must sit inside a region this turn actually Read and
|
|
179
|
+
// that still matches. Same guarantee as the substring path, checked here
|
|
180
|
+
// directly (no old_string to search for).
|
|
181
|
+
const stale = checkStaleRange(p, lines, start, end, ctx);
|
|
182
|
+
if (stale) return stale;
|
|
183
|
+
|
|
184
|
+
const inserted = normalizeText(new_string).split('\n');
|
|
185
|
+
// The lines being REPLACED, captured before the splice. The TUI renders an
|
|
186
|
+
// Edit's diff from the tool ARGUMENTS, and line-range mode has no
|
|
187
|
+
// `old_string` to diff against — so without reporting them here the edit
|
|
188
|
+
// drew NO diff at all (no +/- rows, no +N/-N counts). Reporting them lets
|
|
189
|
+
// the caller diff the replaced region -> `new_string`.
|
|
190
|
+
const replacedText = lines.slice(start - 1, end).join('\n');
|
|
191
|
+
const out = [...lines.slice(0, start - 1), ...inserted, ...lines.slice(end)];
|
|
192
|
+
const normUpdated = out.join('\n');
|
|
193
|
+
const updated = eol === '\r\n' ? normUpdated.split('\n').join('\r\n') : normUpdated;
|
|
194
|
+
// Checkpoint the pre-edit content so /undo can put it back (file-history.js).
|
|
195
|
+
checkpointBeforeWrite(p, ctx);
|
|
196
|
+
try {
|
|
197
|
+
ensureDir(p);
|
|
198
|
+
fs.writeFileSync(p, updated, 'utf8');
|
|
199
|
+
} catch (e) { return `Error writing ${args.path}: ${e.message}`; }
|
|
200
|
+
refreshReadPool(p, normUpdated, { start, end: start + inserted.length - 1 }, ctx);
|
|
201
|
+
const removed = end - start + 1;
|
|
202
|
+
// Publish the diff for the UI. The Edit line is drawn from these, so a
|
|
203
|
+
// line-range edit shows the same +/- rows and +N/-N counts as a substring
|
|
204
|
+
// edit instead of nothing. `ctx.lastEditDiff` is consumed (and cleared) by
|
|
205
|
+
// the agent loop right after this tool returns.
|
|
206
|
+
//
|
|
207
|
+
// `lines` is the pre-edit content, which is what `start` indexes into.
|
|
208
|
+
if (ctx) ctx.lastEditDiff = buildEditDiff({ fileLines: lines, oldText: replacedText, newText: new_string, startLine: start });
|
|
209
|
+
return `Edited ${args.path}: replaced lines ${start}-${end} (${removed} line${removed === 1 ? '' : 's'}) with ${inserted.length} line${inserted.length === 1 ? '' : 's'}.`;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
// ---- SUBSTRING mode (old_string -> new_string) --------------------------
|
|
214
|
+
let { old_string, new_string, replace_all = false } = args;
|
|
215
|
+
// Reaching here means neither mode was usable: line-range needs
|
|
216
|
+
// start_line+end_line (handled above) and substring needs old_string. When
|
|
217
|
+
// BOTH are absent, say so — "old_string must not be empty" sends the model
|
|
218
|
+
// hunting for a stray empty string it never sent.
|
|
219
|
+
if (old_string == null && new_string == null) {
|
|
220
|
+
return 'Error: no edit mode given. Pass EITHER (start_line, end_line, new_string) OR (old_string, new_string).';
|
|
221
|
+
}
|
|
222
|
+
if (old_string === '' || old_string == null) return `Error: old_string must not be empty.`;
|
|
223
|
+
if (new_string == null) return `Error: new_string is required for substring mode.`;
|
|
224
|
+
|
|
225
|
+
// --- Newline normalization (Windows CRLF) ---
|
|
226
|
+
// The Read tool normalizes \r\n -> \n, so an agent builds old_string/new_string
|
|
227
|
+
// with LF. But the file on disk may be CRLF, making a raw LF match fail. We
|
|
228
|
+
// normalize the FILE content to LF for matching, then restore the file's own
|
|
229
|
+
// line ending style when writing back, so we never corrupt or mix endings.
|
|
230
|
+
const eol = content.includes('\r\n') ? '\r\n' : '\n';
|
|
231
|
+
const normContent = content.split(/\r\n|\r|\n/).join('\n');
|
|
232
|
+
const normOld = normalizeText(old_string);
|
|
233
|
+
const normNew = normalizeText(new_string);
|
|
234
|
+
|
|
235
|
+
// A RANGED edit searches only inside the given lines. `windowStart` is the character offset of
|
|
236
|
+
// the range's first line in `normContent`, and `windowEnd` the end of its last line; the whole
|
|
237
|
+
// file is the window when no range was given. Every match, count and replacement below uses
|
|
238
|
+
// this window, so a snippet that appears elsewhere in the file is neither found nor touched —
|
|
239
|
+
// which is the entire point, and what `replace_all` cannot express.
|
|
240
|
+
let windowStart = 0;
|
|
241
|
+
let windowEnd = normContent.length;
|
|
242
|
+
if (rangedToWindow) {
|
|
243
|
+
const allLines = normContent.split('\n');
|
|
244
|
+
// Offset of line N's first character: the sum of the lengths of lines 1..N-1 plus their
|
|
245
|
+
// newlines. Computed by walking, because a single `indexOf` would find the wrong copy of a
|
|
246
|
+
// line that also occurs earlier in the file.
|
|
247
|
+
const offsetOfLine = (n) => {
|
|
248
|
+
let at = 0;
|
|
249
|
+
for (let i = 0; i < n - 1 && i < allLines.length; i++) at += allLines[i].length + 1;
|
|
250
|
+
return at;
|
|
251
|
+
};
|
|
252
|
+
windowStart = offsetOfLine(searchFrom);
|
|
253
|
+
const lastLineStart = offsetOfLine(searchTo);
|
|
254
|
+
windowEnd = Math.min(normContent.length, lastLineStart + (allLines[searchTo - 1] || '').length);
|
|
255
|
+
}
|
|
256
|
+
/** Occurrences of `needle` inside the window. */
|
|
257
|
+
const countInWindow = (needle) => {
|
|
258
|
+
if (!needle) return 0;
|
|
259
|
+
const seg = normContent.slice(windowStart, windowEnd);
|
|
260
|
+
return seg.split(needle).length - 1;
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
let matchOld = normOld; // the string that will actually be matched/replaced
|
|
264
|
+
let matchNew = normNew;
|
|
265
|
+
let count = countInWindow(matchOld);
|
|
266
|
+
if (count === 0) {
|
|
267
|
+
// Quote-normalized retry: the file may use curly quotes while the model sent
|
|
268
|
+
// straight ones. Match on the normalized forms, then replace the ACTUAL
|
|
269
|
+
// substring found in the file so typography is preserved. normalizeQuotes is
|
|
270
|
+
// 1 char -> 1 char, so indices line up between the two strings.
|
|
271
|
+
const normFileQ = normalizeQuotes(normContent);
|
|
272
|
+
if (normFileQ !== normContent) {
|
|
273
|
+
const normOldQ = normalizeQuotes(normOld);
|
|
274
|
+
// Search the NORMALIZED window for the normalized snippet, then take the real text at
|
|
275
|
+
// that place so the replacement keeps the file's own typography.
|
|
276
|
+
const idx = normFileQ.indexOf(normOldQ, windowStart);
|
|
277
|
+
if (idx >= 0 && idx + normOldQ.length <= windowEnd) {
|
|
278
|
+
matchOld = normContent.slice(idx, idx + normOldQ.length);
|
|
279
|
+
matchNew = normNew; // keep the model's new_string as written
|
|
280
|
+
count = countInWindow(matchOld);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (count === 0) {
|
|
285
|
+
if (rangedToWindow) {
|
|
286
|
+
// Say WHERE it was looked for, so a snippet that exists elsewhere is not reported as
|
|
287
|
+
// missing outright — that sends the caller hunting for a typo that is not there.
|
|
288
|
+
const elsewhere = normContent.split(normOld).length - 1;
|
|
289
|
+
const hint = elsewhere
|
|
290
|
+
? ` It appears ${elsewhere} time(s) elsewhere in the file, outside lines ${searchFrom}-${searchTo}. Broaden the range, or correct the range.`
|
|
291
|
+
: '';
|
|
292
|
+
return `Error: old_string not found within lines ${searchFrom}-${searchTo} of ${args.path}.${hint}`;
|
|
293
|
+
}
|
|
294
|
+
const near = nearestLineHint(normContent, normOld);
|
|
295
|
+
return `Error: old_string not found in ${args.path}.${near}`;
|
|
296
|
+
}
|
|
297
|
+
if (count > 1 && !replace_all) {
|
|
298
|
+
if (rangedToWindow) {
|
|
299
|
+
return `Error: old_string matched ${count} occurrences within lines ${searchFrom}-${searchTo} of ${args.path}. Narrow the range, or use replace_all=true to change all of them.`;
|
|
300
|
+
}
|
|
301
|
+
return `Error: old_string matched ${count} occurrences in ${args.path}. Use replace_all=true or make old_string unique.`;
|
|
302
|
+
}
|
|
303
|
+
// --- Staleness guard: the AI must edit against content it actually Read.
|
|
304
|
+
// We stored per-region + whole-file hashes in ctx.readPool when Read ran.
|
|
305
|
+
// If the file changed on disk since (external edit, stream, Ctrl-C side
|
|
306
|
+
// effect), reject so a snippet edit cannot silently corrupt the file. ---
|
|
307
|
+
const stale = checkStale(p, normContent, matchOld, ctx);
|
|
308
|
+
if (stale) return stale;
|
|
309
|
+
|
|
310
|
+
// Replace INSIDE the window only. A rangedToWindow edit must not touch an identical snippet sitting
|
|
311
|
+
// before or after the range — replacing across the whole file is the failure the range exists
|
|
312
|
+
// to prevent. With no range the window IS the whole file, so non-rangedToWindow callers are unchanged.
|
|
313
|
+
const normUpdated = (() => {
|
|
314
|
+
const head = normContent.slice(0, windowStart);
|
|
315
|
+
const body = normContent.slice(windowStart, windowEnd);
|
|
316
|
+
const tail = normContent.slice(windowEnd);
|
|
317
|
+
return head + (replace_all ? body.replaceAll(matchOld, matchNew) : body.replace(matchOld, matchNew)) + tail;
|
|
318
|
+
})();
|
|
319
|
+
const updated = eol === '\r\n' ? normUpdated.split('\n').join('\r\n') : normUpdated;
|
|
320
|
+
// Checkpoint the pre-edit content so /undo can put it back (file-history.js).
|
|
321
|
+
checkpointBeforeWrite(p, ctx);
|
|
322
|
+
try {
|
|
323
|
+
ensureDir(p);
|
|
324
|
+
fs.writeFileSync(p, updated, 'utf8');
|
|
325
|
+
} catch (e) { return `Error writing ${args.path}: ${e.message}`; }
|
|
326
|
+
// Silently re-arm the Read snapshot for the edited region so the AI can keep
|
|
327
|
+
// editing on top of its own change WITHOUT another Read: we recompute the
|
|
328
|
+
// affected line range + hash from the NEW content and refresh the pool. We
|
|
329
|
+
// also drop any previously-recorded region whose content no longer matches
|
|
330
|
+
// (those are genuinely stale now). Nothing here is told to the model.
|
|
331
|
+
if (ctx && ctx.readPool) {
|
|
332
|
+
const entry = ctx.readPool.get(p);
|
|
333
|
+
if (entry) {
|
|
334
|
+
const newLines = normUpdated.split('\n');
|
|
335
|
+
entry.fileHash = hashStr(normUpdated);
|
|
336
|
+
entry.lines = newLines.length;
|
|
337
|
+
// Locate the edit site in the NEW content: the first line of the new
|
|
338
|
+
// text if present, else fall back to the old target's location.
|
|
339
|
+
const anchor = String(matchNew).split('\n')[0];
|
|
340
|
+
let at = newLines.indexOf(anchor);
|
|
341
|
+
if (at < 0) at = newLines.indexOf(String(matchOld).split('\n')[0]);
|
|
342
|
+
if (at >= 0) {
|
|
343
|
+
const newSpan = String(matchNew).split('\n').length;
|
|
344
|
+
const start = at + 1;
|
|
345
|
+
const end = Math.min(newLines.length, at + Math.max(1, newSpan));
|
|
346
|
+
// Re-hash every surviving old region against the new content, and add
|
|
347
|
+
// the freshly-edited span. Regions that no longer match are dropped.
|
|
348
|
+
const kept = entry.regions.filter((r) => hashLines(newLines, r.start, r.end) === r.hash);
|
|
349
|
+
kept.push({ start, end, hash: hashLines(newLines, start, end) });
|
|
350
|
+
entry.regions = kept;
|
|
351
|
+
} else {
|
|
352
|
+
// Could not locate the site: drop stale regions so nothing false stays.
|
|
353
|
+
entry.regions = entry.regions.filter((r) => hashLines(newLines, r.start, r.end) === r.hash);
|
|
354
|
+
}
|
|
355
|
+
try { const st = fs.statSync(p); entry.size = st.size; entry.mtimeMs = st.mtimeMs; } catch {}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
const occurrences = replace_all ? count : 1;
|
|
359
|
+
// Publish the diff for the UI (same contract as the line-range path above).
|
|
360
|
+
if (ctx) {
|
|
361
|
+
const at = normContent.split('\n').indexOf(String(normOld).split('\n')[0]);
|
|
362
|
+
const startLine = at >= 0 ? at + 1 : 1;
|
|
363
|
+
ctx.lastEditDiff = buildEditDiff({
|
|
364
|
+
fileLines: normContent.split('\n'),
|
|
365
|
+
oldText: old_string,
|
|
366
|
+
newText: new_string,
|
|
367
|
+
startLine,
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
return `Edited ${args.path}: replaced ${occurrences} occurrence(s).`;
|
|
371
|
+
},
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
/** How many unchanged lines to show on each side of a changed region. */
|
|
375
|
+
|
|
376
|
+
/** How many unchanged lines to show on each side of a changed region. */
|
|
377
|
+
const DIFF_CONTEXT = 5;
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Build the diff payload, including the unchanged lines around the change.
|
|
381
|
+
*
|
|
382
|
+
* The replaced lines alone do not tell a reader WHERE the edit landed: a four-line block quoted
|
|
383
|
+
* with no surroundings could be anywhere in a 500-line file, so neither the model nor the user
|
|
384
|
+
* could tell a correct edit from one applied at the right text in the wrong place — and with
|
|
385
|
+
* repeated code (several similar blocks, two `}` in a row) the same text appears in many places.
|
|
386
|
+
* `context` carries the file's own lines so the renderer can draw them unmarked, above and below.
|
|
387
|
+
*
|
|
388
|
+
* `fileLines` is the content BEFORE the edit for the replaced region's START LINE to be
|
|
389
|
+
* meaningful: `startLine` is a line number in that same file.
|
|
390
|
+
*/
|
|
391
|
+
function buildEditDiff({ fileLines, oldText, newText, startLine }) {
|
|
392
|
+
const lines = Array.isArray(fileLines) ? fileLines : [];
|
|
393
|
+
const before = [];
|
|
394
|
+
const after = [];
|
|
395
|
+
const replacedCount = normalizeText(oldText).split('\n').length;
|
|
396
|
+
// `startLine` is 1-based; the replaced block occupies [startLine, startLine + n - 1].
|
|
397
|
+
const lastReplaced = startLine + replacedCount - 1;
|
|
398
|
+
for (let n = startLine - DIFF_CONTEXT; n < startLine; n++) {
|
|
399
|
+
if (n >= 1 && n <= lines.length) before.push({ n, text: lines[n - 1] });
|
|
400
|
+
}
|
|
401
|
+
for (let n = lastReplaced + 1; n <= lastReplaced + DIFF_CONTEXT; n++) {
|
|
402
|
+
if (n >= 1 && n <= lines.length) after.push({ n, text: lines[n - 1] });
|
|
403
|
+
}
|
|
404
|
+
return {
|
|
405
|
+
old: normalizeText(oldText),
|
|
406
|
+
new: normalizeText(newText),
|
|
407
|
+
startLine,
|
|
408
|
+
context: { before, after },
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// Suggest a near-miss filename when a path does not exist: same directory, an
|
|
413
|
+
// exact case-insensitive match, same stem with a different extension, or a
|
|
414
|
+
// prefix match. Saves the model a round-trip of guessing (Claude Code's
|
|
415
|
+
// "Did you mean X?").
|
|
416
|
+
function similarFileHint(missingPath) {
|
|
417
|
+
const dir = path.dirname(missingPath);
|
|
418
|
+
const base = path.basename(missingPath);
|
|
419
|
+
const stem = base.replace(/\.[^.]*$/, '').toLowerCase();
|
|
420
|
+
let entries;
|
|
421
|
+
try { entries = fs.readdirSync(dir); } catch { return ''; }
|
|
422
|
+
const lower = base.toLowerCase();
|
|
423
|
+
// Levenshtein distance, capped — enough to catch a typo (confg -> config).
|
|
424
|
+
const lev = (a, b) => {
|
|
425
|
+
const m = a.length, n = b.length;
|
|
426
|
+
if (Math.abs(m - n) > 2) return 3;
|
|
427
|
+
let prev = Array.from({ length: n + 1 }, (_, j) => j);
|
|
428
|
+
for (let i = 1; i <= m; i++) {
|
|
429
|
+
const cur = [i];
|
|
430
|
+
for (let j = 1; j <= n; j++) {
|
|
431
|
+
cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
432
|
+
}
|
|
433
|
+
prev = cur;
|
|
434
|
+
}
|
|
435
|
+
return prev[n];
|
|
436
|
+
};
|
|
437
|
+
let cand = entries.find((e) => e.toLowerCase() === lower);
|
|
438
|
+
if (!cand) {
|
|
439
|
+
let best = null, bestD = 3;
|
|
440
|
+
for (const e of entries) {
|
|
441
|
+
const d = lev(stem, e.replace(/\.[^.]*$/, '').toLowerCase());
|
|
442
|
+
if (d < bestD) { bestD = d; best = e; }
|
|
443
|
+
}
|
|
444
|
+
cand = best;
|
|
445
|
+
}
|
|
446
|
+
if (cand && cand !== base) return ` Did you mean "${path.join(dir, cand)}"?`;
|
|
447
|
+
return '';
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// When old_string is not found, look for the closest line in the file and name
|
|
451
|
+
// it, so the model can see what the text actually is instead of guessing.
|
|
452
|
+
function nearestLineHint(content, oldStr) {
|
|
453
|
+
const want = String(oldStr).split('\n')[0].trim();
|
|
454
|
+
if (!want || want.length < 3) return '';
|
|
455
|
+
const lines = String(content).split('\n');
|
|
456
|
+
// Character bigrams: robust to small differences and cheap on long lines.
|
|
457
|
+
const grams = (s) => {
|
|
458
|
+
const set = new Set();
|
|
459
|
+
for (let i = 0; i + 1 < s.length; i++) set.add(s.slice(i, i + 2));
|
|
460
|
+
return set;
|
|
461
|
+
};
|
|
462
|
+
const wantGrams = grams(want);
|
|
463
|
+
if (!wantGrams.size) return '';
|
|
464
|
+
let best = -1, bestScore = 0;
|
|
465
|
+
for (let i = 0; i < lines.length; i++) {
|
|
466
|
+
const g = grams(lines[i].trim());
|
|
467
|
+
if (!g.size) continue;
|
|
468
|
+
let hit = 0;
|
|
469
|
+
for (const t of wantGrams) if (g.has(t)) hit++;
|
|
470
|
+
const score = hit / wantGrams.size;
|
|
471
|
+
if (score > bestScore) { bestScore = score; best = i; }
|
|
472
|
+
}
|
|
473
|
+
if (best >= 0 && bestScore >= 0.5) {
|
|
474
|
+
return ` The closest line is line ${best + 1}: ${JSON.stringify(lines[best].trim().slice(0, 120))}`;
|
|
475
|
+
}
|
|
476
|
+
return '';
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// Returns an error message when the edit is stale, else null (safe to edit).
|
|
480
|
+
function checkStale(p, normContent, normOld, ctx) {
|
|
481
|
+
if (!ctx || !ctx.readPool) return null; // no Read happened; nothing to verify
|
|
482
|
+
const entry = ctx.readPool.get(p);
|
|
483
|
+
if (!entry) return null; // this file was never Read this turn; allow
|
|
484
|
+
|
|
485
|
+
const curLines = normContent.split('\n');
|
|
486
|
+
const curFileHash = hashStr(normContent);
|
|
487
|
+
|
|
488
|
+
// Locate the edit target's first line in the CURRENT file (1-based).
|
|
489
|
+
//
|
|
490
|
+
// An EXACT line match first, then a line that merely CONTAINS it. The exact match alone
|
|
491
|
+
// missed every edit whose `old_string` begins mid-line — `old_string: "return 1;"` against
|
|
492
|
+
// a line ` return 1;` found nothing, so `editLine` was -1 and step (1) below was skipped
|
|
493
|
+
// entirely: the edit was then reported as stale (branch 2) or, with the whole-file hash
|
|
494
|
+
// also differing, rejected as though the file had changed. Two-line `old_string`s are the
|
|
495
|
+
// common case for a range edit, and their first line usually IS whole, which is why this
|
|
496
|
+
// only showed up on single-line and indented-prefix edits.
|
|
497
|
+
const firstLine = String(normOld).split('\n')[0];
|
|
498
|
+
let idx = curLines.indexOf(firstLine);
|
|
499
|
+
if (idx < 0 && firstLine) idx = curLines.findIndex((l) => l.includes(firstLine));
|
|
500
|
+
const editLine = idx >= 0 ? idx + 1 : -1;
|
|
501
|
+
|
|
502
|
+
// (1) The edit target must sit inside a region the AI actually Read, and that
|
|
503
|
+
// region's content must still match what was Read. Reading the WHOLE file
|
|
504
|
+
// records a region covering every line, so this also covers "read full,
|
|
505
|
+
// edit a part". This is what rejects "read lines 1-3, edit line 7".
|
|
506
|
+
if (editLine > 0) {
|
|
507
|
+
const coveredByIntactRegion = entry.regions.some(
|
|
508
|
+
(r) => editLine >= r.start && editLine <= r.end && hashLines(curLines, r.start, r.end) === r.hash,
|
|
509
|
+
);
|
|
510
|
+
if (coveredByIntactRegion) return null;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// (2) Whole file unchanged since Read, but the edit target was never Read
|
|
514
|
+
// (no region covers it). Name the exact lines so the model reads the right
|
|
515
|
+
// window instead of guessing.
|
|
516
|
+
if (curFileHash === entry.fileHash) {
|
|
517
|
+
const span = String(normOld).split('\n').length;
|
|
518
|
+
const at = editLine > 0 ? editLine : 1;
|
|
519
|
+
return `Edit rejected: you have not read the lines you are editing in ${p}. The target is around line ${at} (${span} line${span === 1 ? '' : 's'}). Read it first — ${args_readHint(p, at, span)} — then Edit.`;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// (3) The file changed on disk since it was Read and the edit target is not in
|
|
523
|
+
// an intact Read region. Reject so a stale snippet cannot corrupt the file.
|
|
524
|
+
const at3 = editLine > 0 ? ` (target line ${editLine})` : '';
|
|
525
|
+
return `Edit rejected: ${p} changed since it was Read${at3}, and the edited region is not in an intact Read snapshot. Re-run ${args_readHint(p, editLine > 0 ? editLine : 1, String(normOld).split('\n').length)} to get the current content, then Edit.`;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// A ready-to-use Read call for the hint. Keeps the model from guessing line ranges.
|
|
529
|
+
function args_readHint(p, at, span) {
|
|
530
|
+
const from = Math.max(1, at - 3);
|
|
531
|
+
const n = Math.max(span + 6, 10);
|
|
532
|
+
return `Read { path: ${JSON.stringify(p)}, line_offset: ${from}, n_lines: ${n} }`;
|
|
533
|
+
}
|
|
534
|
+
// ---- helpers for the line-range path ---------------------------------------
|
|
535
|
+
|
|
536
|
+
// Same guarantee as checkStale, but for an explicit [start, end] line range:
|
|
537
|
+
// every line in the range must sit inside a region that was Read this turn and
|
|
538
|
+
// whose content still matches. Returns an error string, or null when safe.
|
|
539
|
+
function checkStaleRange(p, curLines, start, end, ctx) {
|
|
540
|
+
if (!ctx || !ctx.readPool) return null; // no Read happened; nothing to verify
|
|
541
|
+
const entry = ctx.readPool.get(p);
|
|
542
|
+
if (!entry) return null; // never Read this turn; allow
|
|
543
|
+
|
|
544
|
+
const normContent = curLines.join('\n');
|
|
545
|
+
const curFileHash = hashStr(normContent);
|
|
546
|
+
|
|
547
|
+
// A range is "read" when the regions the model has SEEN cover it — not only when
|
|
548
|
+
// a single region spans it. A file read in two passes (5-10 then 11-16) must
|
|
549
|
+
// allow editing 5-16: the two slices are contiguous, both still intact, so the
|
|
550
|
+
// written range is fully known. Requiring one enclosing region rejected that
|
|
551
|
+
// perfectly safe edit and forced a third Read.
|
|
552
|
+
//
|
|
553
|
+
// Only regions whose hash STILL matches count: a region whose text changed is no
|
|
554
|
+
// longer what the model saw, so it cannot vouch for anything. The cover must also
|
|
555
|
+
// be SEAMLESS — a gap (5-10 and 12-16 with 11 unread) leaves 11 unknown, so it
|
|
556
|
+
// does NOT count, and the edit is correctly refused.
|
|
557
|
+
const intact = entry.regions
|
|
558
|
+
.filter((r) => hashLines(curLines, r.start, r.end) === r.hash)
|
|
559
|
+
.sort((a, b) => a.start - b.start);
|
|
560
|
+
let reach = start - 1; // highest line known to be covered
|
|
561
|
+
for (const r of intact) {
|
|
562
|
+
if (r.end < start) continue; // entirely before the target
|
|
563
|
+
if (r.start > reach + 1) break; // a gap opens before this region: stop
|
|
564
|
+
if (r.end > reach) reach = r.end;
|
|
565
|
+
if (reach >= end) return null; // reached the end: fully covered
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
if (curFileHash === entry.fileHash) {
|
|
569
|
+
// No "(read so far: …)" listing: the range is what the model must act on, and
|
|
570
|
+
// echoing the regions it HAS read only invited it to reason about them instead
|
|
571
|
+
// of re-reading the target lines.
|
|
572
|
+
return `Edit rejected: lines ${start}-${end} were not read in ${p}. Read them first — ${args_readHint(p, start, end - start + 1)} — then Edit.`;
|
|
573
|
+
}
|
|
574
|
+
return `Edit rejected: ${p} changed since it was Read (lines ${start}-${end} are not in an intact Read snapshot). Re-run ${args_readHint(p, start, end - start + 1)} to get the current content, then Edit.`;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
// Refresh the region cache after a successful edit: drop regions that no longer
|
|
578
|
+
// match the NEW content, and record the freshly-written span. Mirrors the
|
|
579
|
+
// re-arm block used by the substring path.
|
|
580
|
+
function refreshReadPool(p, normUpdated, written, ctx) {
|
|
581
|
+
if (!ctx || !ctx.readPool) return;
|
|
582
|
+
const entry = ctx.readPool.get(p);
|
|
583
|
+
if (!entry) return;
|
|
584
|
+
const newLines = normUpdated.split('\n');
|
|
585
|
+
entry.fileHash = hashStr(normUpdated);
|
|
586
|
+
entry.lines = newLines.length;
|
|
587
|
+
const kept = entry.regions.filter((r) => hashLines(newLines, r.start, r.end) === r.hash);
|
|
588
|
+
kept.push({ start: written.start, end: Math.min(newLines.length, Math.max(written.start, written.end)), hash: hashLines(newLines, written.start, Math.min(newLines.length, Math.max(written.start, written.end))) });
|
|
589
|
+
entry.regions = kept;
|
|
590
|
+
try { const st = fs.statSync(p); entry.size = st.size; entry.mtimeMs = st.mtimeMs; } catch {}
|
|
591
|
+
}
|