@yanzc/claude-pro 0.7.8 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,40 +3,81 @@
3
3
 
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
+ import crypto from 'node:crypto';
6
7
  import { resolvePath, displayPath } from '../utils/paths.js';
7
8
  import { diffLines, makeHunks, countChanges, splitLines } from '../utils/diff.js';
8
9
  import { fitImage } from '../utils/images.js';
10
+ import { decodeText, encodeText, encodingName } from '../utils/encoding.js';
9
11
 
10
12
  const MAX_LINES = 10_000;
11
13
  const MAX_LINE_CHARS = 20_000;
12
14
  const MAX_OUTPUT_CHARS = 400_000; // a read without offset/limit bigger than this is refused
13
15
  const HARD_MAX_CHARS = 400_000; // never return more than this in one read (about 100k tokens), even with an explicit limit
16
+ // ... and never more than about this many tokens: 400k characters of Chinese text are some 320k tokens, more than a
17
+ // whole context window (Read is not cut down to a preview like other large tool results).
18
+ const MAX_OUTPUT_TOKENS = 100_000;
19
+
20
+ // Tokens of text as the program estimates them (agent.js estimateTokens): 4 ASCII characters or 1.25 others each.
21
+ // `limit`: the index where that many tokens are reached (text.length when they are not).
22
+ function tokensOf(text) {
23
+ let ascii = 0;
24
+ for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) < 128) ascii++;
25
+ return Math.ceil(ascii / 4 + (text.length - ascii) * 0.8);
26
+ }
27
+ function tokenLimitIndex(text, limit) {
28
+ let t = 0;
29
+ for (let i = 0; i < text.length; i++) {
30
+ t += text.charCodeAt(i) < 128 ? 0.25 : 0.8;
31
+ if (t > limit) return i;
32
+ }
33
+ return text.length;
34
+ }
35
+ const tooManyTokens = (text) => text.length > MAX_OUTPUT_TOKENS * 1.25 && tokensOf(text) > MAX_OUTPUT_TOKENS;
14
36
  const IMAGE_TYPES = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
15
37
 
16
38
  export function mtime(file) {
17
39
  try { return fs.statSync(file).mtimeMs; } catch { return null; }
18
40
  }
19
41
 
20
- function isBinary(buf) {
21
- const len = Math.min(buf.length, 8000);
22
- for (let i = 0; i < len; i++) if (buf[i] === 0) return true;
23
- return false;
24
- }
25
-
42
+ // The file as text: {text, crlf, bom, encoding, lossy} (see utils/encoding.js), or null for binary data.
26
43
  // `crlf` is true when CRLF is the file's main line ending. Editing rewrites every line ending, so a
27
44
  // mostly-LF file with one stray CRLF must stay LF instead of being converted wholesale.
28
45
  function readText(file, buf = fs.readFileSync(file)) {
29
- const raw = buf.toString('utf8');
30
- const text = raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw;
31
- const crlfCount = (text.match(/\r\n/g) || []).length;
32
- const bareLfCount = (text.match(/\n/g) || []).length - crlfCount;
33
- return { text, bom: text !== raw, crlf: crlfCount > 0 && crlfCount >= bareLfCount };
46
+ const decoded = decodeText(buf);
47
+ if (!decoded) return null;
48
+ const crlfCount = (decoded.text.match(/\r\n/g) || []).length;
49
+ const bareLfCount = (decoded.text.match(/\n/g) || []).length - crlfCount;
50
+ return { ...decoded, crlf: crlfCount > 0 && crlfCount >= bareLfCount };
51
+ }
52
+
53
+ const notText = (file) => `${file} appears to be a binary file, not text.`;
54
+ const notRewritable = (file, { encoding }) => (encoding === 'gbk'
55
+ ? `${file} is GB18030 text with characters GBK cannot write, so rewriting it here could change bytes you did not edit. Change it with a tool that knows its encoding (Bash: iconv, python).`
56
+ : `${file} is not valid UTF-8 or GBK as a whole (another encoding, or mixed), so rewriting it here would corrupt the bytes that could not be decoded. Change it with a tool that knows its encoding (Bash: iconv, python).`);
57
+
58
+ // What a Read says about a file that is not plain UTF-8.
59
+ function encodingNote(t) {
60
+ if (t.lossy) return t.encoding === 'gbk'
61
+ ? '\n\n(This file is GB18030 with characters GBK cannot write: Edit and Write refuse to rewrite it.)'
62
+ : '\n\n(This file is not valid UTF-8 or GBK as a whole: bytes that could not be decoded show as \ufffd, and Edit and Write refuse to rewrite it.)';
63
+ if (t.encoding !== 'utf8') return `\n\n(This file is ${encodingName(t.encoding)}${t.bom ? ' with a BOM' : ''}; Edit and Write keep that encoding.)`;
64
+ return '';
34
65
  }
35
66
 
67
+ // Why `text` cannot be written into a file in the encoding `meta` says, or null when it can.
68
+ function unwritable(file, text, meta) {
69
+ if (!meta?.encoding || meta.encoding === 'utf8') return null;
70
+ const { error } = encodeText(text, meta);
71
+ return error ? `${file} is ${encodingName(meta.encoding)}-encoded (kept so when it is edited), and the new text has ${error}. Use other characters, or convert the file to UTF-8 first if the user wants that.` : null;
72
+ }
73
+
74
+ // Each line as its number, a tab and the line. Not padded as cat -n pads it: the padding cost 2 tokens a line on
75
+ // GPT and 1 on Claude (measured 2026-10-26: 12% of a code Read on gpt-6.1-sol, 4% on Opus 5.5), in every Read
76
+ // result, which stays in the conversation and is sent again with every later request.
36
77
  export function numberLines(lines, start, maxLineChars = MAX_LINE_CHARS) {
37
78
  return lines.map((l, i) => {
38
79
  const line = l.length > maxLineChars ? l.slice(0, maxLineChars) + '… [line truncated]' : l;
39
- return `${String(start + i).padStart(6)}\t${line}`;
80
+ return `${start + i}\t${line}`;
40
81
  }).join('\n');
41
82
  }
42
83
 
@@ -64,11 +105,11 @@ Usage:
64
105
  - By default, it reads up to ${MAX_LINES} lines starting from the beginning of the file
65
106
  - Read a file whole when you need to understand it; when only a part of a long file matters, give offset and limit (find the place with Grep first if needed)
66
107
  - Any lines longer than ${MAX_LINE_CHARS} characters will be truncated
67
- - A file whose numbered text is longer than ${MAX_OUTPUT_CHARS} characters is refused (or cut there with offset/limit). When you need a large file whole, in one call, pass allow_large: true: then there is no line, character or line length limit, only the room left in the context, and a read that does not fit is refused.
68
- - Results are returned using cat -n format, with line numbers starting at 1
108
+ - A file whose numbered text is longer than ${MAX_OUTPUT_CHARS} characters or about ${MAX_OUTPUT_TOKENS / 1000}k tokens (Chinese text gets there sooner) is refused (or cut there with offset/limit). When you need a large file whole, in one call, pass allow_large: true: then there is no line, character or line length limit, only the room left in the context, and a read that does not fit is refused.
109
+ - Results are returned as each line's number, a tab, then the line (numbers start at 1)
69
110
  - This tool can read images (PNG, JPG, GIF, WEBP) and Jupyter notebooks (.ipynb)
70
111
  - This tool can only read files, not directories. To list a directory, use ls via the Bash tool.
71
- - Do not read a file again just to check an edit you made to it: Edit and Write report an error when they fail.
112
+ - Do not read a file again just to check an edit you made to it: Edit, MultiEdit and Write report an error when they fail.
72
113
  - If you read a file that exists but has empty contents you will receive a warning in place of file contents.`,
73
114
  input_schema: {
74
115
  type: 'object',
@@ -113,20 +154,26 @@ Usage:
113
154
  }
114
155
  if (ext === '.ipynb') {
115
156
  try {
116
- const nb = JSON.parse(fs.readFileSync(file, 'utf8'));
117
- ctx.fileState.set(file, { mtimeMs: stat.mtimeMs });
118
- return { content: renderNotebook(nb), display: { summary: `Read ${(nb.cells || []).length} cells` } };
157
+ const raw = fs.readFileSync(file);
158
+ const nb = JSON.parse(raw.toString('utf8'));
159
+ const rendered = renderNotebook(nb);
160
+ if (rendered.length > MAX_OUTPUT_CHARS || tooManyTokens(rendered)) {
161
+ return { isError: true, content: `Notebook content (${Math.round(rendered.length / 1024)}KB, about ${tokensOf(rendered).toLocaleString('en-US')} tokens) exceeds the maximum allowed size. Look at parts of it with the Bash tool (python or jq on its JSON), or use Grep to search it.` };
162
+ }
163
+ ctx.fileState.set(file, { mtimeMs: stat.mtimeMs, hash: hashOf(raw) });
164
+ return { content: rendered, display: { summary: `Read ${(nb.cells || []).length} cells` } };
119
165
  } catch (e) {
120
166
  return { isError: true, content: `Could not parse notebook: ${e.message}` };
121
167
  }
122
168
  }
123
169
  const buf = fs.readFileSync(file);
124
- if (isBinary(buf)) return { isError: true, content: `This appears to be a binary file (${stat.size} bytes) and cannot be displayed as text.` };
125
-
126
- const { text } = readText(file, buf);
127
- const lines = splitLines(text);
128
- // `partial` records that part of the file was not shown, so Write can refuse to overwrite it.
129
- const seen = (partial) => ctx.fileState.set(file, { mtimeMs: stat.mtimeMs, partial });
170
+ const decoded = readText(file, buf);
171
+ if (!decoded) return { isError: true, content: `This appears to be a binary file (${stat.size} bytes) and cannot be displayed as text.` };
172
+ const note = encodingNote(decoded);
173
+ const lines = splitLines(decoded.text);
174
+ // `partial` records that part of the file was not shown, so Write can refuse to overwrite it; `hash` tells a
175
+ // later change of its time without a change of its bytes from a real one (see fileStanding).
176
+ const seen = (partial) => ctx.fileState.set(file, { mtimeMs: stat.mtimeMs, partial, hash: hashOf(buf) });
130
177
  if (lines.length === 0) {
131
178
  seen(false);
132
179
  return { content: '<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>', display: { summary: 'Read 0 lines (empty file)' } };
@@ -147,46 +194,68 @@ Usage:
147
194
  const n = (t) => t.toLocaleString('en-US');
148
195
  return { isError: true, content: `File content (about ${n(fit.tokens)} tokens) does not fit in the context left (about ${n(Math.max(0, fit.room))} tokens before auto-compaction). Read the parts you need with offset and limit, or use the Grep tool to search for specific content.` };
149
196
  }
150
- } else if (content.length > MAX_OUTPUT_CHARS && !input.limit) {
151
- return { isError: true, content: `File content (${Math.round(content.length / 1024)}KB) exceeds the maximum allowed size. Use the offset and limit parameters to read specific portions of the file, or use the Grep tool to search for specific content. If you need the whole file at once, pass allow_large: true.` };
197
+ } else if (!input.limit && (content.length > MAX_OUTPUT_CHARS || tooManyTokens(content))) {
198
+ return { isError: true, content: `File content (${Math.round(content.length / 1024)}KB, about ${tokensOf(content).toLocaleString('en-US')} tokens) exceeds the maximum allowed size. Use the offset and limit parameters to read specific portions of the file, or use the Grep tool to search for specific content. If you need the whole file at once, pass allow_large: true.` };
152
199
  }
153
200
  let cut = false;
154
201
  let end = start + slice.length - 1;
155
- if (!large && content.length > HARD_MAX_CHARS) {
156
- const kept = content.slice(0, HARD_MAX_CHARS);
202
+ const cutAt = large ? content.length : Math.min(HARD_MAX_CHARS, tokenLimitIndex(content, MAX_OUTPUT_TOKENS));
203
+ if (cutAt < content.length) {
204
+ const kept = content.slice(0, cutAt);
157
205
  const whole = kept.endsWith('\n'); // the cut fell between two lines
158
206
  end = start + (kept.match(/\n/g) || []).length - (whole ? 1 : 0); // the last line shown
159
- content = `${kept}${whole ? '' : '\n'}… [output cut at ${HARD_MAX_CHARS} characters: line ${end} is the last one shown${whole ? '' : ', and only in part'}; read on from there with offset/limit, or pass allow_large: true to read it all at once]`;
207
+ const why = cutAt === HARD_MAX_CHARS ? `${HARD_MAX_CHARS} characters` : `about ${MAX_OUTPUT_TOKENS / 1000}k tokens`;
208
+ content = `${kept}${whole ? '' : '\n'}… [output cut at ${why}: line ${end} is the last one shown${whole ? '' : ', and only in part'}; read on from there with offset/limit, or pass allow_large: true to read it all at once]`;
160
209
  cut = true;
161
210
  }
162
211
  seen(cut || start > 1 || end < lines.length);
163
212
  if (end < lines.length) content += `\n\n(File has ${lines.length} lines total; showing lines ${start}-${end}. Use offset/limit to read more.)`;
213
+ content += note;
164
214
  return { content, display: { summary: `Read ${slice.length} line${slice.length === 1 ? '' : 's'}` } };
165
215
  },
166
216
  };
167
217
 
218
+ const hashOf = (buf) => crypto.createHash('sha1').update(buf).digest('hex');
219
+
220
+ // How a file stands against what the model has seen of it: null (read or written by it, unchanged since),
221
+ // 'unread', or 'modified' (changed on disk since). A time that moved while the bytes stayed the same (git, a
222
+ // formatter that changed nothing, an antivirus scan or a cloud sync on Windows) is no change: the content is
223
+ // compared as well, as Claude Code does.
224
+ export function fileStanding(file, ctx) {
225
+ const state = ctx.fileState.get(file);
226
+ if (!state) return 'unread';
227
+ const now = mtime(file);
228
+ if (now === null || state.mtimeMs === undefined || Math.abs(now - state.mtimeMs) <= 1) return null;
229
+ let same = false;
230
+ try { same = Boolean(state.hash) && hashOf(fs.readFileSync(file)) === state.hash; } catch { /* gone: changed */ }
231
+ if (!same) return 'modified';
232
+ state.mtimeMs = now;
233
+ return null;
234
+ }
235
+
168
236
  // Validate that a file may be written: it must have been read and be unchanged since. With
169
237
  // `full`, which Write needs because it replaces the whole file, the read must also have covered
170
- // all of it; Edit only replaces text it matched exactly, so a partial read is enough there.
238
+ // all of it. (Edit has its own rule, see EditTool.plan.)
171
239
  export function checkFreshness(file, ctx, { full = false } = {}) {
172
- const state = ctx.fileState.get(file);
173
- if (!state) return 'File has not been read yet. Read it first before writing to it.';
174
- if (full && state.partial) {
175
- return 'File was only partly read (offset/limit), so Write would overwrite content you have not seen. Read the whole file first, or use Edit for targeted changes.';
240
+ const standing = fileStanding(file, ctx);
241
+ if (standing === 'unread') return 'File has not been read yet. Read it first before writing to it.';
242
+ if (full && ctx.fileState.get(file).partial) {
243
+ return 'Only part of this file has been seen (a Read with offset/limit, or edits without a whole Read), so Write would overwrite content you have not seen. Read the whole file first, or use Edit for targeted changes.';
176
244
  }
177
- const now = mtime(file);
178
- if (now !== null && state.mtimeMs !== undefined && Math.abs(now - state.mtimeMs) > 1) {
245
+ if (standing === 'modified') {
179
246
  return 'File has been modified since it was last read, either by the user or by a linter. Read it again before attempting to write it.';
180
247
  }
181
248
  return null;
182
249
  }
183
250
 
184
- function writeText(file, text, { crlf, bom }) {
185
- let out = text;
186
- if (crlf) out = out.replace(/\r?\n/g, '\r\n');
187
- if (bom) out = String.fromCharCode(0xfeff) + out;
251
+ // In the encoding, BOM and line endings the file had (`meta`, from readText); checked with unwritable() first.
252
+ // Returns the hash of what was written, for the file state.
253
+ function writeText(file, text, { crlf, bom, encoding = 'utf8' }) {
254
+ const { buffer, error } = encodeText(crlf ? text.replace(/\r?\n/g, '\r\n') : text, { encoding, bom });
255
+ if (error) throw new Error(`${file}: ${error}`);
188
256
  fs.mkdirSync(path.dirname(file), { recursive: true });
189
- fs.writeFileSync(file, out, 'utf8');
257
+ fs.writeFileSync(file, buffer);
258
+ return hashOf(buffer);
190
259
  }
191
260
 
192
261
  // Where the new text of an edit is, for its result: "lines 12-18", "line 12", or "text removed at line 12".
@@ -223,7 +292,11 @@ Usage:
223
292
  const file = resolvePath(input.file_path, ctx.cwd);
224
293
  if (fs.existsSync(file)) {
225
294
  if (fs.statSync(file).isDirectory()) return `${file} is a directory`;
226
- return checkFreshness(file, ctx, { full: true });
295
+ const fresh = checkFreshness(file, ctx, { full: true });
296
+ if (fresh) return fresh;
297
+ const prev = readText(file);
298
+ if (prev?.lossy) return notRewritable(file, prev);
299
+ return unwritable(file, input.content, prev);
227
300
  }
228
301
  return null;
229
302
  },
@@ -232,7 +305,7 @@ Usage:
232
305
  const exists = fs.existsSync(file);
233
306
  const newLines = splitLines(input.content);
234
307
  if (!exists) return { kind: 'create', path: file, lines: newLines };
235
- const ops = diffLines(splitLines(readText(file).text), newLines);
308
+ const ops = diffLines(splitLines(readText(file)?.text ?? ''), newLines);
236
309
  return { kind: 'diff', path: file, hunks: makeHunks(ops), ...countChanges(ops) };
237
310
  },
238
311
  async call(input, ctx) {
@@ -240,10 +313,11 @@ Usage:
240
313
  if (err) return { isError: true, content: err };
241
314
  const file = resolvePath(input.file_path, ctx.cwd);
242
315
  const exists = fs.existsSync(file);
243
- const prev = exists ? readText(file) : { text: '', crlf: false, bom: false };
316
+ // The encoding, BOM and line endings of what was there stay (a binary file it replaces: plain UTF-8).
317
+ const prev = (exists && readText(file)) || { text: '', crlf: false, bom: false, encoding: 'utf8' };
244
318
  const preview = this.preview(input, ctx);
245
- writeText(file, input.content, prev);
246
- ctx.fileState.set(file, { mtimeMs: mtime(file) });
319
+ const hash = writeText(file, input.content, prev);
320
+ ctx.fileState.set(file, { mtimeMs: mtime(file), hash });
247
321
  const n = splitLines(input.content).length;
248
322
  if (!exists) {
249
323
  return {
@@ -265,7 +339,8 @@ function changeSummary({ added, removed }) {
265
339
  return parts.length ? `Updated with ${parts.join(' and ')}` : 'No changes';
266
340
  }
267
341
 
268
- // Apply old->new replacement to text. Returns {result, count, index} or {error}.
342
+ // Apply old->new replacement to text. Returns {result, count, index} or {error, notFound}. The errors do not repeat
343
+ // old_string (the model has it in its own call): a miss shows where the most similar text is instead (see missed).
269
344
  export function applyEdit(text, oldStr, newStr, replaceAll) {
270
345
  if (oldStr === newStr) return { error: 'No changes to make: old_string and new_string are exactly the same.' };
271
346
  if (oldStr === '') {
@@ -278,7 +353,7 @@ export function applyEdit(text, oldStr, newStr, replaceAll) {
278
353
  // Tolerate trailing whitespace differences at line ends.
279
354
  const norm = (s) => s.replace(/[ \t]+\n/g, '\n');
280
355
  if (norm(text).includes(norm(oldStr)) && norm(text) !== text) {
281
- return { error: 'String to replace not found exactly (whitespace differs at line ends). Read the file again and copy the text exactly, including whitespace.' };
356
+ return { error: 'String to replace not found exactly (whitespace differs at line ends): copy the text exactly, including the whitespace at the ends of its lines.', notFound: true };
282
357
  }
283
358
  // Curly quote normalisation.
284
359
  const straight = (s) => s.replace(/[‘’]/g, "'").replace(/[“”]/g, '"');
@@ -289,25 +364,130 @@ export function applyEdit(text, oldStr, newStr, replaceAll) {
289
364
  count = text.split(actualOld).length - 1;
290
365
  }
291
366
  }
292
- if (count === 0) return { error: `String to replace not found in file.\nString: ${oldStr}` };
367
+ if (count === 0) return { error: 'String to replace not found in file.', notFound: true };
293
368
  if (count > 1 && !replaceAll) {
294
- return { error: `Found ${count} matches of the string to replace, but replace_all is false. To replace all occurrences, set replace_all to true. To replace only one occurrence, please provide more context to uniquely identify the instance.\nString: ${oldStr}` };
369
+ return { error: `Found ${count} matches of the string to replace (${matchLines(text, actualOld)}), but replace_all is false. To replace all occurrences, set replace_all to true. To replace only one, add the lines around it to old_string so that it matches that one only.` };
295
370
  }
296
371
  const index = text.indexOf(actualOld);
297
372
  const result = replaceAll ? text.split(actualOld).join(newStr) : text.slice(0, index) + newStr + text.slice(index + actualOld.length);
298
373
  return { result, count, index };
299
374
  }
300
375
 
376
+ // "at lines 12, 40 and 77": where `needle` starts in `text` (the first 10).
377
+ function matchLines(text, needle) {
378
+ const lines = [];
379
+ for (let i = text.indexOf(needle); i >= 0 && lines.length < 11; i = text.indexOf(needle, i + needle.length)) {
380
+ lines.push(text.slice(0, i).split('\n').length);
381
+ }
382
+ const shown = lines.slice(0, 10);
383
+ const list = shown.length > 1 ? `${shown.slice(0, -1).join(', ')} and ${shown.at(-1)}` : String(shown[0]);
384
+ return `at line${shown.length > 1 ? 's' : ''} ${list}${lines.length > 10 ? ' and more' : ''}`;
385
+ }
386
+
387
+ // Character bigrams of a string, for a similarity of two lines (Dice coefficient).
388
+ function bigrams(s) {
389
+ const m = new Map();
390
+ for (let i = 0; i < s.length - 1; i++) { const g = s.slice(i, i + 2); m.set(g, (m.get(g) || 0) + 1); }
391
+ return m;
392
+ }
393
+ function dice(a, b) {
394
+ let n = 0, total = 0;
395
+ for (const [g, c] of a) { total += c; n += Math.min(c, b.get(g) || 0); }
396
+ for (const c of b.values()) total += c;
397
+ return total ? (2 * n) / total : 0;
398
+ }
399
+
400
+ // The part of `text` most like `oldStr`, for an edit that missed: {from, to, text} (1-based lines, numbered as Read
401
+ // numbers them) or null when nothing is alike. Lines of old_string found whole (whitespace aside) vote for where
402
+ // it would start; without any, its longest line is looked for by similarity. Most misses are an old_string from
403
+ // memory or with other indentation: the right text in the error saves a Read and gets the retry right.
404
+ function similarRegion(text, oldStr, maxLines = 14) {
405
+ const lines = text.split('\n');
406
+ const want = oldStr.replace(/\n+$/, '').split('\n');
407
+ if (lines.length > 50_000 || lines.length * want.length > 5_000_000) return null;
408
+ const key = (s) => s.trim();
409
+ const at = new Map();
410
+ lines.forEach((l, i) => { const k = key(l); if (k.length >= 3) { const list = at.get(k); if (list) list.push(i); else at.set(k, [i]); } });
411
+ const votes = new Map();
412
+ want.forEach((l, k) => {
413
+ const hits = at.get(key(l));
414
+ if (hits && hits.length <= 20) for (const i of hits) votes.set(i - k, (votes.get(i - k) || 0) + 1);
415
+ });
416
+ let start = null;
417
+ let best = 0;
418
+ for (const [s, v] of votes) if (v > best || (v === best && s < start)) { best = v; start = s; }
419
+ const meaningful = want.filter((l) => key(l).length >= 3).length;
420
+ if (start === null || best < Math.max(1, Math.ceil(meaningful * 0.3))) {
421
+ const probe = want.map(key).reduce((a, b) => (b.length > a.length ? b : a), '');
422
+ if (probe.length < 6) return null;
423
+ const k = want.findIndex((l) => key(l) === probe);
424
+ const pb = bigrams(probe);
425
+ let score = 0;
426
+ start = null;
427
+ lines.forEach((l, i) => {
428
+ const t = key(l);
429
+ if (!t || t.length > probe.length * 3 || probe.length > t.length * 3) return;
430
+ const s = dice(pb, bigrams(t));
431
+ if (s > score) { score = s; start = i - k; }
432
+ });
433
+ if (start === null || score < 0.5) return null;
434
+ }
435
+ const from = Math.max(0, start - 1);
436
+ const to = Math.min(lines.length - 1, Math.max(from, start + want.length), from + maxLines - 1);
437
+ return { from: from + 1, to: to + 1, text: numberLines(lines.slice(from, to + 1), from + 1, 300) };
438
+ }
439
+
440
+ // The error of an edit whose old_string was not used: where the most similar text is, when it missed, and what to
441
+ // do about a file it had not read or that changed since. `step`: "Edit 2 of 3: " in MultiEdit.
442
+ function missed(r, text, oldStr, unseen, step = '') {
443
+ let msg = step + r.error;
444
+ if (r.notFound) {
445
+ const near = similarRegion(text, oldStr);
446
+ if (near) {
447
+ msg += ` The most similar text${step && !step.startsWith('Edit 1 ') ? ', in the file as the edits before this one left it,' : ''} is at lines ${near.from}-${near.to}:\n${near.text}\nIf that is the place, copy old_string from these lines exactly (without the line numbers); if not, Read the file.`;
448
+ if (unseen === 'modified') msg += ' (The file has changed since you last read it.)';
449
+ return msg;
450
+ }
451
+ return `${msg} ${unseen ? UNSEEN_HINT[unseen] : 'Read the file to get its exact text.'}`;
452
+ }
453
+ return unseen ? `${msg} ${UNSEEN_HINT[unseen]}` : msg;
454
+ }
455
+
456
+ // The lines an edit left changed in the new text, for its result: "lines 12-18, 40 and 77-80" (from the diff).
457
+ function changedRanges(ops, max = 8) {
458
+ const ranges = [];
459
+ let line = 0;
460
+ let removedAt = null;
461
+ for (const op of ops) {
462
+ if (op.op === '-') { removedAt ??= line + 1; continue; }
463
+ line++;
464
+ if (op.op === '+') {
465
+ const last = ranges.at(-1);
466
+ if (last && !last.removed && last.to === line - 1) last.to = line;
467
+ else ranges.push({ from: line, to: line });
468
+ removedAt = null;
469
+ } else if (removedAt !== null) {
470
+ ranges.push({ from: removedAt, to: removedAt, removed: true });
471
+ removedAt = null;
472
+ }
473
+ }
474
+ if (removedAt !== null) ranges.push({ from: removedAt, to: removedAt, removed: true });
475
+ const text = ranges.slice(0, max).map((r) => (r.removed ? `text removed at line ${r.from}` : r.from === r.to ? `line ${r.from}` : `lines ${r.from}-${r.to}`));
476
+ if (ranges.length > max) text.push(`${ranges.length - max} more places`);
477
+ return text.length > 1 ? `${text.slice(0, -1).join(', ')} and ${text.at(-1)}` : text[0] || 'no lines changed';
478
+ }
479
+
301
480
  export const EditTool = {
302
481
  name: 'Edit',
303
482
  editsFiles: true,
304
483
  description: `Performs exact string replacements in files.
305
484
 
306
485
  Usage:
307
- - You must use your \`Read\` tool at least once in the conversation before editing (a Grep result does not count). This tool will error if you attempt an edit without reading the file.
308
- - When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.
309
- - The edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`.
486
+ - old_string must be the file's exact current text, so Read the file first unless that text is already in this conversation (a Read, Bash or Grep output, an edit of yours). An edit whose old_string occurs exactly once is made even when the file was not read or has changed since (the result says so); replace_all needs a Read of the file as it is now.
487
+ - When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.
488
+ - The edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`. When it is not found, the error shows the most similar lines of the file.
310
489
  - Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.
490
+ - More than one change to a file: make them all in one MultiEdit call, not one Edit per response. Changes to several files: put their Edit or MultiEdit calls in the same response (they are made in the order given). Every response is a round trip that sends the whole conversation again and takes tens of seconds.
311
491
  - To create a new file, pass an empty old_string with the full content as new_string (the file must not exist).`,
312
492
  input_schema: {
313
493
  type: 'object',
@@ -331,13 +511,27 @@ Usage:
331
511
  return { file, created: true, before: '', after: newStr, meta: { crlf: false, bom: false } };
332
512
  }
333
513
  if (fs.statSync(file).isDirectory()) return { error: `${file} is a directory` };
334
- const fresh = checkFreshness(file, ctx);
335
- if (fresh) return { error: fresh };
336
- const { text, crlf, bom } = readText(file);
514
+ // A Read is what shows the model the text it replaces, but an old_string that occurs exactly once in the file
515
+ // as it is now shows it too: text from a Bash or Grep output, its own earlier edit, a Read whose result was
516
+ // cleared, a file one of its commands changed. Such an edit is made, with a note; refusing it cost a Read and a
517
+ // retry (in 70 sessions to 2026-10-26, 117 of 2,781 edits). replace_all has no such proof: it needs the read.
518
+ const unseen = fileStanding(file, ctx);
519
+ if (unseen && input.replace_all) {
520
+ return { error: unseen === 'unread'
521
+ ? 'File has not been read yet. Read it first before replacing every occurrence in it.'
522
+ : 'File has been modified since it was last read, either by the user or by a command. Read it again before replacing every occurrence in it.' };
523
+ }
524
+ const current = readText(file);
525
+ if (!current) return { error: notText(file) };
526
+ if (current.lossy) return { error: notRewritable(file, current) };
527
+ const { text, crlf, bom, encoding } = current;
337
528
  const before = text.replace(/\r\n/g, '\n');
338
529
  const r = applyEdit(before, oldStr, newStr, !!input.replace_all);
339
- if (r.error) return { error: r.error };
340
- return { file, before, after: r.result, index: r.index, count: r.count, meta: { crlf, bom }, newStr };
530
+ if (r.error) return { error: missed(r, before, oldStr, unseen) };
531
+ const meta = { crlf, bom, encoding };
532
+ const cannot = unwritable(file, r.result, meta);
533
+ if (cannot) return { error: cannot };
534
+ return { file, before, after: r.result, index: r.index, count: r.count, meta, newStr, unseen };
341
535
  },
342
536
  validate(input, ctx) { return this.plan(input, ctx).error || null; },
343
537
  // `p` is an already computed plan, so call() does not read the file and redo the edit a second time.
@@ -352,9 +546,10 @@ Usage:
352
546
  if (p.error) return { isError: true, content: p.error };
353
547
  const preview = this.preview(input, ctx, p);
354
548
  const prior = ctx.fileState.get(p.file);
355
- writeText(p.file, p.after, p.meta);
356
- // An edit does not show the rest of the file, so a partial read stays partial (a created file is all ours).
357
- ctx.fileState.set(p.file, { mtimeMs: mtime(p.file), partial: !p.created && !!prior?.partial });
549
+ const hash = writeText(p.file, p.after, p.meta);
550
+ // An edit does not show the rest of the file, so a partial read stays partial (a created file is all ours), and
551
+ // a file edited unread, or changed since it was read, counts as partly seen: Write wants a whole Read of it.
552
+ ctx.fileState.set(p.file, { mtimeMs: mtime(p.file), partial: !p.created && (!prior || Boolean(prior.partial) || p.unseen === 'modified'), hash });
358
553
  if (p.created) {
359
554
  return { content: `File created successfully at: ${p.file}`, display: { summary: `Created ${displayPath(p.file, ctx.cwd)}`, preview } };
360
555
  }
@@ -362,6 +557,115 @@ Usage:
362
557
  const text = input.replace_all
363
558
  ? `The file ${p.file} has been updated successfully. All ${p.count} occurrences were replaced.`
364
559
  : `The file ${p.file} has been updated successfully (${changedLines(line, p.newStr)}).`;
365
- return { content: text, display: { summary: changeSummary(preview), preview } };
560
+ return { content: p.unseen ? `${text} ${UNSEEN_NOTE[p.unseen]}` : text, display: { summary: changeSummary(preview), preview } };
561
+ },
562
+ };
563
+
564
+ // Several replacements in one file in one call. GPT models make one Edit per response even when they know several
565
+ // changes (2026-10-12..26: 2% of gpt-6.1-sol's responses with an edit had more than one, against 54% of Opus 5.5's;
566
+ // 561 times an edit response was followed by another one on the same file), and every response is a round trip of
567
+ // some 18 s on GPT that sends the whole conversation again. With all the changes in one call they are one response.
568
+ // The edits are applied in order to the text as the previous one left it, and all or none are made.
569
+ export const MultiEditTool = {
570
+ name: 'MultiEdit',
571
+ editsFiles: true,
572
+ description: `Makes several exact string replacements in one file in one call. The edits are applied in the order given, each to the text as the previous one left it, and either all of them are made or none (the error says which one failed and why).
573
+
574
+ Usage:
575
+ - Use it whenever you know more than one change to a file, instead of an Edit per change: every response is a round trip that sends the whole conversation again and takes tens of seconds.
576
+ - Each edit has old_string, new_string and optionally replace_all, with the rules of Edit: old_string is the exact text to replace (as the edits before it leave the file) and must occur once unless replace_all is set; never include the line number prefix of Read output.
577
+ - Order the edits so that an earlier one does not change the text a later one looks for.
578
+ - To create a file, use Write (or a first edit with an empty old_string, for a file that does not exist).
579
+ - Changes to several files: one MultiEdit or Edit call per file, all in the same response.`,
580
+ input_schema: {
581
+ type: 'object',
582
+ properties: {
583
+ file_path: { type: 'string', description: 'The absolute path to the file to modify' },
584
+ edits: {
585
+ type: 'array',
586
+ minItems: 1,
587
+ description: 'The replacements, made in this order',
588
+ items: {
589
+ type: 'object',
590
+ properties: {
591
+ old_string: { type: 'string', description: 'The text to replace' },
592
+ new_string: { type: 'string', description: 'The text to replace it with' },
593
+ replace_all: { type: 'boolean', default: false, description: 'Replace all occurrences of old_string (default false)' },
594
+ },
595
+ required: ['old_string', 'new_string'],
596
+ },
597
+ },
598
+ },
599
+ required: ['file_path', 'edits'],
600
+ },
601
+ summarize(input, ctx) {
602
+ const n = Array.isArray(input.edits) ? input.edits.length : 0;
603
+ return `${displayPath(resolvePath(input.file_path, ctx.cwd), ctx.cwd)}${n ? `, ${n} edit${n === 1 ? '' : 's'}` : ''}`;
366
604
  },
605
+ filePath(input, ctx) { return resolvePath(input.file_path, ctx.cwd); },
606
+ plan(input, ctx) {
607
+ const file = resolvePath(input.file_path, ctx.cwd);
608
+ const edits = Array.isArray(input.edits) ? input.edits : [];
609
+ if (!edits.length) return { error: 'edits must be a non-empty list of {old_string, new_string}.' };
610
+ const steps = edits.map((e) => ({
611
+ oldStr: String(e?.old_string ?? '').replace(/\r\n/g, '\n'),
612
+ newStr: String(e?.new_string ?? '').replace(/\r\n/g, '\n'),
613
+ all: Boolean(e?.replace_all),
614
+ }));
615
+ const exists = fs.existsSync(file);
616
+ let unseen = null;
617
+ let meta = { crlf: false, bom: false, encoding: 'utf8' };
618
+ let before = '';
619
+ if (exists) {
620
+ if (fs.statSync(file).isDirectory()) return { error: `${file} is a directory` };
621
+ unseen = fileStanding(file, ctx); // as in Edit: a unique old_string shows the model has the text it replaces
622
+ if (unseen && steps.some((s) => s.all)) {
623
+ return { error: unseen === 'unread'
624
+ ? 'File has not been read yet. Read it first before replacing every occurrence in it (replace_all).'
625
+ : 'File has been modified since it was last read, either by the user or by a command. Read it again before replacing every occurrence in it (replace_all).' };
626
+ }
627
+ const current = readText(file);
628
+ if (!current) return { error: notText(file) };
629
+ if (current.lossy) return { error: notRewritable(file, current) };
630
+ meta = { crlf: current.crlf, bom: current.bom, encoding: current.encoding };
631
+ before = current.text.replace(/\r\n/g, '\n');
632
+ } else if (steps[0].oldStr !== '') {
633
+ return { error: `File does not exist: ${file}. Create it with Write, or with a first edit whose old_string is empty.` };
634
+ }
635
+ let text = before;
636
+ for (let i = 0; i < steps.length; i++) {
637
+ const { oldStr, newStr, all } = steps[i];
638
+ const r = applyEdit(text, oldStr, newStr, all);
639
+ const step = steps.length > 1 ? `Edit ${i + 1} of ${steps.length}: ` : '';
640
+ if (r.error) return { error: `${missed(r, text, oldStr, unseen, step)}${steps.length > 1 ? ' No edit was made.' : ''}` };
641
+ text = r.result;
642
+ }
643
+ const cannot = unwritable(file, text, meta);
644
+ if (cannot) return { error: cannot };
645
+ return { file, before, after: text, meta, count: steps.length, unseen, created: !exists };
646
+ },
647
+ validate(input, ctx) { return this.plan(input, ctx).error || null; },
648
+ preview(input, ctx, p = this.plan(input, ctx)) { return EditTool.preview(input, ctx, p); },
649
+ async call(input, ctx) {
650
+ const p = this.plan(input, ctx);
651
+ if (p.error) return { isError: true, content: p.error };
652
+ const ops = p.created ? null : diffLines(splitLines(p.before), splitLines(p.after));
653
+ const preview = p.created ? { kind: 'create', path: p.file, lines: splitLines(p.after) } : { kind: 'diff', path: p.file, hunks: makeHunks(ops), ...countChanges(ops) };
654
+ const prior = ctx.fileState.get(p.file);
655
+ const hash = writeText(p.file, p.after, p.meta);
656
+ ctx.fileState.set(p.file, { mtimeMs: mtime(p.file), partial: !p.created && (!prior || Boolean(prior.partial) || p.unseen === 'modified'), hash });
657
+ if (p.created) return { content: `File created successfully at: ${p.file}`, display: { summary: `Created ${displayPath(p.file, ctx.cwd)}`, preview } };
658
+ const text = `The file ${p.file} has been updated successfully: ${p.count} edit${p.count === 1 ? '' : 's'} (${changedRanges(ops)}).`;
659
+ return { content: p.unseen ? `${text} ${UNSEEN_NOTE[p.unseen]}` : text, display: { summary: changeSummary(preview), preview } };
660
+ },
661
+ };
662
+
663
+ // What an edit of a file the model had not read, or that changed since it read it, adds to its result or error.
664
+ const UNSEEN_NOTE = {
665
+ unread: '(The file had not been read in this conversation; old_string matched its current text once.)',
666
+ modified: '(The file had changed since you last read it, by a command or someone else; the edit was made on its current text. Read it again if those changes matter.)',
667
+ };
668
+ const UNSEEN_HINT = {
669
+ unread: 'The file has not been read in this conversation: Read it to get its exact text.',
670
+ modified: 'The file has changed since you last read it: Read it again.',
367
671
  };
@@ -1,4 +1,4 @@
1
- import { ReadTool, WriteTool, EditTool } from './files.js';
1
+ import { ReadTool, WriteTool, EditTool, MultiEditTool } from './files.js';
2
2
  import { makeBashTool, BashOutputTool, KillShellTool } from './bash.js';
3
3
  import { GlobTool, GrepTool } from './search.js';
4
4
  import { makeWebFetchTool, WebSearchTool } from './web.js';
@@ -24,6 +24,7 @@ export function buildTools(config, { agents, skills, mcpTools = [], restart = fa
24
24
  GrepTool,
25
25
  ReadTool,
26
26
  EditTool,
27
+ MultiEditTool,
27
28
  WriteTool,
28
29
  NotebookEditTool,
29
30
  makeWebFetchTool(config),
@@ -47,5 +48,6 @@ export function toolsForSubagent(allTools, def, { allowTask = false } = {}) {
47
48
  const base = allTools.filter((t) => !NEVER_FOR_SUBAGENTS.has(t.name) && (allowTask || t.name !== 'Task'));
48
49
  if (def.tools === '*' || !def.tools) return base;
49
50
  const wanted = new Set(def.tools);
51
+ if (wanted.has('Edit')) wanted.add('MultiEdit'); // the same permission, several changes in one call
50
52
  return base.filter((t) => wanted.has(t.name) || [...wanted].some((w) => w.startsWith('mcp__') && t.name.startsWith(w)));
51
53
  }