@yanzc/claude-pro 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +342 -318
  2. package/package.json +1 -2
  3. package/src/agent.js +80 -14
  4. package/src/agents.js +3 -2
  5. package/src/api.js +39 -34
  6. package/src/browser/broker.js +367 -0
  7. package/src/browser/cdp.js +114 -0
  8. package/src/browser/render.js +242 -0
  9. package/src/browser/session.js +948 -0
  10. package/src/browser/snapshot.js +212 -0
  11. package/src/cache.js +1 -1
  12. package/src/checkpoints.js +1 -0
  13. package/src/commands.js +169 -67
  14. package/src/compaction.js +75 -0
  15. package/src/config.js +145 -144
  16. package/src/context.js +45 -18
  17. package/src/filestate.js +3 -2
  18. package/src/gateway.js +208 -164
  19. package/src/hooks.js +2 -2
  20. package/src/keepalive.js +1 -1
  21. package/src/main.js +52 -40
  22. package/src/mcp.js +2 -2
  23. package/src/peers.js +1 -10
  24. package/src/print.js +9 -3
  25. package/src/prompt-profiles.js +0 -6
  26. package/src/prompts.js +7 -63
  27. package/src/ratelimit.js +2 -4
  28. package/src/remote.js +76 -14
  29. package/src/runtime.js +33 -10
  30. package/src/selfcheck.js +3 -3
  31. package/src/session.js +93 -3
  32. package/src/supervisor.js +10 -1
  33. package/src/tools/bash.js +18 -17
  34. package/src/tools/browser.js +365 -0
  35. package/src/tools/code.js +430 -0
  36. package/src/tools/effort.js +3 -4
  37. package/src/tools/files.js +368 -45
  38. package/src/tools/index.js +9 -1
  39. package/src/tools/notebook.js +11 -4
  40. package/src/tools/processes.js +274 -0
  41. package/src/tools/search.js +33 -8
  42. package/src/tools/web.js +316 -46
  43. package/src/trace.js +0 -4
  44. package/src/ui/ansi.js +92 -13
  45. package/src/ui/dialogs.js +16 -54
  46. package/src/ui/editor.js +231 -34
  47. package/src/ui/markdown.js +1 -2
  48. package/src/ui/render.js +1 -2
  49. package/src/ui/repl.js +335 -101
  50. package/src/ui/screen.js +139 -31
  51. package/src/updater.js +135 -165
  52. package/src/utils/clipboard.js +5 -3
  53. package/src/utils/dirs.js +136 -0
  54. package/src/utils/encoding.js +23 -2
  55. package/src/utils/paths.js +15 -17
  56. package/src/utils/shell.js +66 -11
  57. package/.env.example +0 -29
@@ -3,6 +3,8 @@
3
3
 
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import { isUtf8 } from 'node:buffer';
6
8
  import { resolvePath, displayPath } from '../utils/paths.js';
7
9
  import { diffLines, makeHunks, countChanges, splitLines } from '../utils/diff.js';
8
10
  import { fitImage } from '../utils/images.js';
@@ -70,10 +72,13 @@ function unwritable(file, text, meta) {
70
72
  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;
71
73
  }
72
74
 
75
+ // 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
76
+ // 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
77
+ // result, which stays in the conversation and is sent again with every later request.
73
78
  export function numberLines(lines, start, maxLineChars = MAX_LINE_CHARS) {
74
79
  return lines.map((l, i) => {
75
80
  const line = l.length > maxLineChars ? l.slice(0, maxLineChars) + '… [line truncated]' : l;
76
- return `${String(start + i).padStart(6)}\t${line}`;
81
+ return `${start + i}\t${line}`;
77
82
  }).join('\n');
78
83
  }
79
84
 
@@ -102,10 +107,10 @@ Usage:
102
107
  - 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)
103
108
  - Any lines longer than ${MAX_LINE_CHARS} characters will be truncated
104
109
  - 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.
105
- - Results are returned using cat -n format, with line numbers starting at 1
110
+ - Results are returned as each line's number, a tab, then the line (numbers start at 1)
106
111
  - This tool can read images (PNG, JPG, GIF, WEBP) and Jupyter notebooks (.ipynb)
107
112
  - This tool can only read files, not directories. To list a directory, use ls via the Bash tool.
108
- - Do not read a file again just to check an edit you made to it: Edit and Write report an error when they fail.
113
+ - 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.
109
114
  - If you read a file that exists but has empty contents you will receive a warning in place of file contents.`,
110
115
  input_schema: {
111
116
  type: 'object',
@@ -150,37 +155,52 @@ Usage:
150
155
  }
151
156
  if (ext === '.ipynb') {
152
157
  try {
153
- const nb = JSON.parse(fs.readFileSync(file, 'utf8'));
158
+ const raw = fs.readFileSync(file);
159
+ const nb = JSON.parse(raw.toString('utf8').replace(/^\uFEFF/, ''));
154
160
  const rendered = renderNotebook(nb);
155
161
  if (rendered.length > MAX_OUTPUT_CHARS || tooManyTokens(rendered)) {
156
162
  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.` };
157
163
  }
158
- ctx.fileState.set(file, { mtimeMs: stat.mtimeMs });
164
+ ctx.fileState.set(file, { mtimeMs: stat.mtimeMs, hash: hashOf(raw) });
159
165
  return { content: rendered, display: { summary: `Read ${(nb.cells || []).length} cells` } };
160
166
  } catch (e) {
161
167
  return { isError: true, content: `Could not parse notebook: ${e.message}` };
162
168
  }
163
169
  }
164
- const decoded = readText(file, fs.readFileSync(file));
165
- if (!decoded) return { isError: true, content: `This appears to be a binary file (${stat.size} bytes) and cannot be displayed as text.` };
166
- const note = encodingNote(decoded);
167
- const lines = splitLines(decoded.text);
168
- // `partial` records that part of the file was not shown, so Write can refuse to overwrite it.
169
- const seen = (partial) => ctx.fileState.set(file, { mtimeMs: stat.mtimeMs, partial });
170
- if (lines.length === 0) {
170
+ const start = Math.max(1, Math.floor(input.offset || 1));
171
+ // allow_large: no line, character or line length limit, only the room left in the context (see Agent.takeContext).
172
+ const large = input.allow_large === true;
173
+ const limit = Math.max(1, Math.floor(input.limit || (large ? Infinity : MAX_LINES)));
174
+ // `total`: the file's lines; `slice`: those asked for; `hash` of its bytes. A big UTF-8 file is read in chunks for
175
+ // the lines asked for (see readLineRange); the rest is read whole, decoded and split.
176
+ let total, slice, hash, note = '';
177
+ const streamed = stat.size > STREAM_READ_BYTES && Number.isFinite(limit) ? await readLineRange(file, start, limit) : null;
178
+ if (streamed?.binary) return { isError: true, content: `This appears to be a binary file (${stat.size} bytes) and cannot be displayed as text.` };
179
+ if (streamed) ({ total, slice, hash } = streamed);
180
+ else {
181
+ const buf = fs.readFileSync(file);
182
+ const decoded = readText(file, buf);
183
+ if (!decoded) return { isError: true, content: `This appears to be a binary file (${stat.size} bytes) and cannot be displayed as text.` };
184
+ note = encodingNote(decoded);
185
+ const lines = splitLines(decoded.text);
186
+ total = lines.length;
187
+ slice = lines.slice(start - 1, start - 1 + limit);
188
+ hash = hashOf(buf);
189
+ }
190
+ // `partial` records that part of the file was not shown, so Write can refuse to overwrite it; `hash` tells a
191
+ // later change of its time without a change of its bytes from a real one (see fileStanding).
192
+ const seen = (partial) => ctx.fileState.set(file, { mtimeMs: stat.mtimeMs, partial, hash });
193
+ if (total === 0) {
171
194
  seen(false);
172
195
  return { content: '<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>', display: { summary: 'Read 0 lines (empty file)' } };
173
196
  }
174
- const start = Math.max(1, Math.floor(input.offset || 1));
175
- if (start > lines.length) {
197
+ if (start > total) {
176
198
  seen(true);
177
- return { content: `<system-reminder>Warning: the file exists but is shorter than the provided offset (${start}). The file has ${lines.length} lines.</system-reminder>`, display: { summary: 'Read 0 lines' } };
199
+ return { content: `<system-reminder>Warning: the file exists but is shorter than the provided offset (${start}). The file has ${total} lines.</system-reminder>`, display: { summary: 'Read 0 lines' } };
178
200
  }
179
- // allow_large: no line, character or line length limit, only the room left in the context (see Agent.takeContext).
180
- const large = input.allow_large === true;
181
- const limit = Math.max(1, Math.floor(input.limit || (large ? Infinity : MAX_LINES)));
182
- const slice = lines.slice(start - 1, start - 1 + limit);
183
201
  let content = numberLines(slice, start, large ? Infinity : MAX_LINE_CHARS);
202
+ // a line cut short is not seen whole either: a Write from what was shown would put "… [line truncated]" in the file
203
+ const longLines = !large && slice.some((l) => l.length > MAX_LINE_CHARS);
184
204
  if (large) {
185
205
  const fit = ctx.agent?.takeContext?.(content);
186
206
  if (fit && !fit.ok) {
@@ -201,35 +221,114 @@ Usage:
201
221
  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]`;
202
222
  cut = true;
203
223
  }
204
- seen(cut || start > 1 || end < lines.length);
205
- if (end < lines.length) content += `\n\n(File has ${lines.length} lines total; showing lines ${start}-${end}. Use offset/limit to read more.)`;
224
+ seen(cut || longLines || start > 1 || end < total);
225
+ if (end < total) content += `\n\n(File has ${total} lines total; showing lines ${start}-${end}. Use offset/limit to read more.)`;
206
226
  content += note;
207
227
  return { content, display: { summary: `Read ${slice.length} line${slice.length === 1 ? '' : 's'}` } };
208
228
  },
209
229
  };
210
230
 
231
+ export const hashOf = (buf) => crypto.createHash('sha1').update(buf).digest('hex');
232
+
233
+ const STREAM_READ_BYTES = 8 * 1024 * 1024;
234
+
235
+ // Lines [start, start + limit) of a big file, read in chunks without blocking and without the whole file in memory
236
+ // (a Read of 20 lines of a 183 MB log took 0.7 s, blocked, and 768 MB): {total, slice, hash}, as the whole read
237
+ // gives them (splitLines: \r\n is a line end, no line after the last end; the BOM is not text). {binary: true} for
238
+ // a binary file; null when the file is not UTF-8 as a whole (UTF-16, GBK): it is read whole then.
239
+ async function readLineRange(file, start, limit) {
240
+ const hash = crypto.createHash('sha1');
241
+ const slice = [];
242
+ const end = start + limit;
243
+ let ended = 0; // the lines ended so far (by a \n)
244
+ let parts = null; // the bytes of the line going on, when it is one asked for
245
+ let carry = null; // a character the last chunk did not finish, checked with the next one
246
+ let first = true;
247
+ let last = -1; // the file's last byte
248
+ for await (let chunk of fs.createReadStream(file, { highWaterMark: 1 << 20 })) {
249
+ hash.update(chunk);
250
+ if (first) {
251
+ first = false;
252
+ if ((chunk[0] === 0xff && chunk[1] === 0xfe) || (chunk[0] === 0xfe && chunk[1] === 0xff)) return null;
253
+ if (chunk[0] === 0xef && chunk[1] === 0xbb && chunk[2] === 0xbf) chunk = chunk.subarray(3);
254
+ if (chunk.subarray(0, 8000).includes(0)) return { binary: true };
255
+ }
256
+ if (!chunk.length) continue;
257
+ const data = carry ? Buffer.concat([carry, chunk]) : chunk;
258
+ const keep = unfinishedTail(data);
259
+ if (!isUtf8(data.subarray(0, data.length - keep))) return null;
260
+ carry = keep ? Buffer.from(data.subarray(data.length - keep)) : null;
261
+ let from = 0;
262
+ for (let nl = chunk.indexOf(10); nl >= 0; nl = chunk.indexOf(10, from)) {
263
+ const n = ++ended;
264
+ if (n >= start && n < end) {
265
+ let line = parts ? Buffer.concat([...parts, chunk.subarray(from, nl)]) : chunk.subarray(from, nl);
266
+ if (line[line.length - 1] === 13) line = line.subarray(0, -1);
267
+ slice.push(line.toString('utf8'));
268
+ }
269
+ parts = null;
270
+ from = nl + 1;
271
+ }
272
+ if (from < chunk.length && ended + 1 >= start && ended + 1 < end) (parts ??= []).push(Buffer.from(chunk.subarray(from)));
273
+ last = chunk[chunk.length - 1];
274
+ }
275
+ if (carry) return null; // a character cut off at the end
276
+ const total = ended + (last !== -1 && last !== 10 ? 1 : 0);
277
+ if (parts && total >= start && total < end) slice.push(Buffer.concat(parts).toString('utf8'));
278
+ return { total, slice, hash: hash.digest('hex') };
279
+ }
280
+
281
+ // How many bytes at the end of `buf` start a UTF-8 character it does not finish (0 to 3).
282
+ function unfinishedTail(buf) {
283
+ const n = buf.length;
284
+ for (let k = 1; k <= Math.min(3, n); k++) {
285
+ const b = buf[n - k];
286
+ if ((b & 0xc0) === 0x80) continue; // a continuation byte: its lead is further back
287
+ const need = b >= 0xf0 ? 4 : b >= 0xe0 ? 3 : b >= 0xc0 ? 2 : 1;
288
+ return need > k ? k : 0;
289
+ }
290
+ return 0;
291
+ }
292
+
293
+ // How a file stands against what the model has seen of it: null (read or written by it, unchanged since),
294
+ // 'unread', or 'modified' (changed on disk since). A time that moved while the bytes stayed the same (git, a
295
+ // formatter that changed nothing, an antivirus scan or a cloud sync on Windows) is no change: the content is
296
+ // compared as well, as Claude Code does.
297
+ export function fileStanding(file, ctx) {
298
+ const state = ctx.fileState.get(file);
299
+ if (!state) return 'unread';
300
+ const now = mtime(file);
301
+ if (now === null || state.mtimeMs === undefined || Math.abs(now - state.mtimeMs) <= 1) return null;
302
+ let same = false;
303
+ try { same = Boolean(state.hash) && hashOf(fs.readFileSync(file)) === state.hash; } catch { /* gone: changed */ }
304
+ if (!same) return 'modified';
305
+ state.mtimeMs = now;
306
+ return null;
307
+ }
308
+
211
309
  // Validate that a file may be written: it must have been read and be unchanged since. With
212
310
  // `full`, which Write needs because it replaces the whole file, the read must also have covered
213
- // all of it; Edit only replaces text it matched exactly, so a partial read is enough there.
311
+ // all of it. (Edit has its own rule, see EditTool.plan.)
214
312
  export function checkFreshness(file, ctx, { full = false } = {}) {
215
- const state = ctx.fileState.get(file);
216
- if (!state) return 'File has not been read yet. Read it first before writing to it.';
217
- if (full && state.partial) {
218
- 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.';
313
+ const standing = fileStanding(file, ctx);
314
+ if (standing === 'unread') return 'File has not been read yet. Read it first before writing to it.';
315
+ if (full && ctx.fileState.get(file).partial) {
316
+ return 'Only part of this file has been seen (a Read with offset/limit or one that cut long lines short, or edits without a whole Read), so Write would overwrite content you have not seen. Read the whole file first (allow_large: true shows long lines whole), or use Edit for targeted changes.';
219
317
  }
220
- const now = mtime(file);
221
- if (now !== null && state.mtimeMs !== undefined && Math.abs(now - state.mtimeMs) > 1) {
318
+ if (standing === 'modified') {
222
319
  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.';
223
320
  }
224
321
  return null;
225
322
  }
226
323
 
227
324
  // In the encoding, BOM and line endings the file had (`meta`, from readText); checked with unwritable() first.
325
+ // Returns the hash of what was written, for the file state.
228
326
  function writeText(file, text, { crlf, bom, encoding = 'utf8' }) {
229
327
  const { buffer, error } = encodeText(crlf ? text.replace(/\r?\n/g, '\r\n') : text, { encoding, bom });
230
328
  if (error) throw new Error(`${file}: ${error}`);
231
329
  fs.mkdirSync(path.dirname(file), { recursive: true });
232
330
  fs.writeFileSync(file, buffer);
331
+ return hashOf(buffer);
233
332
  }
234
333
 
235
334
  // Where the new text of an edit is, for its result: "lines 12-18", "line 12", or "text removed at line 12".
@@ -290,8 +389,8 @@ Usage:
290
389
  // The encoding, BOM and line endings of what was there stay (a binary file it replaces: plain UTF-8).
291
390
  const prev = (exists && readText(file)) || { text: '', crlf: false, bom: false, encoding: 'utf8' };
292
391
  const preview = this.preview(input, ctx);
293
- writeText(file, input.content, prev);
294
- ctx.fileState.set(file, { mtimeMs: mtime(file) });
392
+ const hash = writeText(file, input.content, prev);
393
+ ctx.fileState.set(file, { mtimeMs: mtime(file), hash });
295
394
  const n = splitLines(input.content).length;
296
395
  if (!exists) {
297
396
  return {
@@ -313,7 +412,8 @@ function changeSummary({ added, removed }) {
313
412
  return parts.length ? `Updated with ${parts.join(' and ')}` : 'No changes';
314
413
  }
315
414
 
316
- // Apply old->new replacement to text. Returns {result, count, index} or {error}.
415
+ // Apply old->new replacement to text. Returns {result, count, index} or {error, notFound}. The errors do not repeat
416
+ // old_string (the model has it in its own call): a miss shows where the most similar text is instead (see missed).
317
417
  export function applyEdit(text, oldStr, newStr, replaceAll) {
318
418
  if (oldStr === newStr) return { error: 'No changes to make: old_string and new_string are exactly the same.' };
319
419
  if (oldStr === '') {
@@ -326,7 +426,7 @@ export function applyEdit(text, oldStr, newStr, replaceAll) {
326
426
  // Tolerate trailing whitespace differences at line ends.
327
427
  const norm = (s) => s.replace(/[ \t]+\n/g, '\n');
328
428
  if (norm(text).includes(norm(oldStr)) && norm(text) !== text) {
329
- return { error: 'String to replace not found exactly (whitespace differs at line ends). Read the file again and copy the text exactly, including whitespace.' };
429
+ 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 };
330
430
  }
331
431
  // Curly quote normalisation.
332
432
  const straight = (s) => s.replace(/[‘’]/g, "'").replace(/[“”]/g, '"');
@@ -337,25 +437,130 @@ export function applyEdit(text, oldStr, newStr, replaceAll) {
337
437
  count = text.split(actualOld).length - 1;
338
438
  }
339
439
  }
340
- if (count === 0) return { error: `String to replace not found in file.\nString: ${oldStr}` };
440
+ if (count === 0) return { error: 'String to replace not found in file.', notFound: true };
341
441
  if (count > 1 && !replaceAll) {
342
- 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}` };
442
+ 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.` };
343
443
  }
344
444
  const index = text.indexOf(actualOld);
345
445
  const result = replaceAll ? text.split(actualOld).join(newStr) : text.slice(0, index) + newStr + text.slice(index + actualOld.length);
346
446
  return { result, count, index };
347
447
  }
348
448
 
449
+ // "at lines 12, 40 and 77": where `needle` starts in `text` (the first 10).
450
+ function matchLines(text, needle) {
451
+ const lines = [];
452
+ for (let i = text.indexOf(needle); i >= 0 && lines.length < 11; i = text.indexOf(needle, i + needle.length)) {
453
+ lines.push(text.slice(0, i).split('\n').length);
454
+ }
455
+ const shown = lines.slice(0, 10);
456
+ const list = shown.length > 1 ? `${shown.slice(0, -1).join(', ')} and ${shown.at(-1)}` : String(shown[0]);
457
+ return `at line${shown.length > 1 ? 's' : ''} ${list}${lines.length > 10 ? ' and more' : ''}`;
458
+ }
459
+
460
+ // Character bigrams of a string, for a similarity of two lines (Dice coefficient).
461
+ function bigrams(s) {
462
+ const m = new Map();
463
+ for (let i = 0; i < s.length - 1; i++) { const g = s.slice(i, i + 2); m.set(g, (m.get(g) || 0) + 1); }
464
+ return m;
465
+ }
466
+ function dice(a, b) {
467
+ let n = 0, total = 0;
468
+ for (const [g, c] of a) { total += c; n += Math.min(c, b.get(g) || 0); }
469
+ for (const c of b.values()) total += c;
470
+ return total ? (2 * n) / total : 0;
471
+ }
472
+
473
+ // The part of `text` most like `oldStr`, for an edit that missed: {from, to, text} (1-based lines, numbered as Read
474
+ // numbers them) or null when nothing is alike. Lines of old_string found whole (whitespace aside) vote for where
475
+ // it would start; without any, its longest line is looked for by similarity. Most misses are an old_string from
476
+ // memory or with other indentation: the right text in the error saves a Read and gets the retry right.
477
+ function similarRegion(text, oldStr, maxLines = 14) {
478
+ const lines = text.split('\n');
479
+ const want = oldStr.replace(/\n+$/, '').split('\n');
480
+ if (lines.length > 50_000 || lines.length * want.length > 5_000_000) return null;
481
+ const key = (s) => s.trim();
482
+ const at = new Map();
483
+ 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]); } });
484
+ const votes = new Map();
485
+ want.forEach((l, k) => {
486
+ const hits = at.get(key(l));
487
+ if (hits && hits.length <= 20) for (const i of hits) votes.set(i - k, (votes.get(i - k) || 0) + 1);
488
+ });
489
+ let start = null;
490
+ let best = 0;
491
+ for (const [s, v] of votes) if (v > best || (v === best && s < start)) { best = v; start = s; }
492
+ const meaningful = want.filter((l) => key(l).length >= 3).length;
493
+ if (start === null || best < Math.max(1, Math.ceil(meaningful * 0.3))) {
494
+ const probe = want.map(key).reduce((a, b) => (b.length > a.length ? b : a), '');
495
+ if (probe.length < 6) return null;
496
+ const k = want.findIndex((l) => key(l) === probe);
497
+ const pb = bigrams(probe);
498
+ let score = 0;
499
+ start = null;
500
+ lines.forEach((l, i) => {
501
+ const t = key(l);
502
+ if (!t || t.length > probe.length * 3 || probe.length > t.length * 3) return;
503
+ const s = dice(pb, bigrams(t));
504
+ if (s > score) { score = s; start = i - k; }
505
+ });
506
+ if (start === null || score < 0.5) return null;
507
+ }
508
+ const from = Math.max(0, start - 1);
509
+ const to = Math.min(lines.length - 1, Math.max(from, start + want.length), from + maxLines - 1);
510
+ return { from: from + 1, to: to + 1, text: numberLines(lines.slice(from, to + 1), from + 1, 300) };
511
+ }
512
+
513
+ // The error of an edit whose old_string was not used: where the most similar text is, when it missed, and what to
514
+ // do about a file it had not read or that changed since. `step`: "Edit 2 of 3: " in MultiEdit.
515
+ function missed(r, text, oldStr, unseen, step = '') {
516
+ let msg = step + r.error;
517
+ if (r.notFound) {
518
+ const near = similarRegion(text, oldStr);
519
+ if (near) {
520
+ 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.`;
521
+ if (unseen === 'modified') msg += ' (The file has changed since you last read it.)';
522
+ return msg;
523
+ }
524
+ return `${msg} ${unseen ? UNSEEN_HINT[unseen] : 'Read the file to get its exact text.'}`;
525
+ }
526
+ return unseen ? `${msg} ${UNSEEN_HINT[unseen]}` : msg;
527
+ }
528
+
529
+ // The lines an edit left changed in the new text, for its result: "lines 12-18, 40 and 77-80" (from the diff).
530
+ function changedRanges(ops, max = 8) {
531
+ const ranges = [];
532
+ let line = 0;
533
+ let removedAt = null;
534
+ for (const op of ops) {
535
+ if (op.op === '-') { removedAt ??= line + 1; continue; }
536
+ line++;
537
+ if (op.op === '+') {
538
+ const last = ranges.at(-1);
539
+ if (last && !last.removed && last.to === line - 1) last.to = line;
540
+ else ranges.push({ from: line, to: line });
541
+ removedAt = null;
542
+ } else if (removedAt !== null) {
543
+ ranges.push({ from: removedAt, to: removedAt, removed: true });
544
+ removedAt = null;
545
+ }
546
+ }
547
+ if (removedAt !== null) ranges.push({ from: removedAt, to: removedAt, removed: true });
548
+ 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}`));
549
+ if (ranges.length > max) text.push(`${ranges.length - max} more places`);
550
+ return text.length > 1 ? `${text.slice(0, -1).join(', ')} and ${text.at(-1)}` : text[0] || 'no lines changed';
551
+ }
552
+
349
553
  export const EditTool = {
350
554
  name: 'Edit',
351
555
  editsFiles: true,
352
556
  description: `Performs exact string replacements in files.
353
557
 
354
558
  Usage:
355
- - 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.
356
- - 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.
357
- - 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\`.
559
+ - 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.
560
+ - 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.
561
+ - 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.
358
562
  - Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.
563
+ - 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.
359
564
  - To create a new file, pass an empty old_string with the full content as new_string (the file must not exist).`,
360
565
  input_schema: {
361
566
  type: 'object',
@@ -379,19 +584,27 @@ Usage:
379
584
  return { file, created: true, before: '', after: newStr, meta: { crlf: false, bom: false } };
380
585
  }
381
586
  if (fs.statSync(file).isDirectory()) return { error: `${file} is a directory` };
382
- const fresh = checkFreshness(file, ctx);
383
- if (fresh) return { error: fresh };
587
+ // A Read is what shows the model the text it replaces, but an old_string that occurs exactly once in the file
588
+ // as it is now shows it too: text from a Bash or Grep output, its own earlier edit, a Read whose result was
589
+ // cleared, a file one of its commands changed. Such an edit is made, with a note; refusing it cost a Read and a
590
+ // retry (in 70 sessions to 2026-10-26, 117 of 2,781 edits). replace_all has no such proof: it needs the read.
591
+ const unseen = fileStanding(file, ctx);
592
+ if (unseen && input.replace_all) {
593
+ return { error: unseen === 'unread'
594
+ ? 'File has not been read yet. Read it first before replacing every occurrence in it.'
595
+ : '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.' };
596
+ }
384
597
  const current = readText(file);
385
598
  if (!current) return { error: notText(file) };
386
599
  if (current.lossy) return { error: notRewritable(file, current) };
387
600
  const { text, crlf, bom, encoding } = current;
388
601
  const before = text.replace(/\r\n/g, '\n');
389
602
  const r = applyEdit(before, oldStr, newStr, !!input.replace_all);
390
- if (r.error) return { error: r.error };
603
+ if (r.error) return { error: missed(r, before, oldStr, unseen) };
391
604
  const meta = { crlf, bom, encoding };
392
605
  const cannot = unwritable(file, r.result, meta);
393
606
  if (cannot) return { error: cannot };
394
- return { file, before, after: r.result, index: r.index, count: r.count, meta, newStr };
607
+ return { file, before, after: r.result, index: r.index, count: r.count, meta, newStr, unseen };
395
608
  },
396
609
  validate(input, ctx) { return this.plan(input, ctx).error || null; },
397
610
  // `p` is an already computed plan, so call() does not read the file and redo the edit a second time.
@@ -406,9 +619,10 @@ Usage:
406
619
  if (p.error) return { isError: true, content: p.error };
407
620
  const preview = this.preview(input, ctx, p);
408
621
  const prior = ctx.fileState.get(p.file);
409
- writeText(p.file, p.after, p.meta);
410
- // An edit does not show the rest of the file, so a partial read stays partial (a created file is all ours).
411
- ctx.fileState.set(p.file, { mtimeMs: mtime(p.file), partial: !p.created && !!prior?.partial });
622
+ const hash = writeText(p.file, p.after, p.meta);
623
+ // An edit does not show the rest of the file, so a partial read stays partial (a created file is all ours), and
624
+ // a file edited unread, or changed since it was read, counts as partly seen: Write wants a whole Read of it.
625
+ ctx.fileState.set(p.file, { mtimeMs: mtime(p.file), partial: !p.created && (!prior || Boolean(prior.partial) || p.unseen === 'modified'), hash });
412
626
  if (p.created) {
413
627
  return { content: `File created successfully at: ${p.file}`, display: { summary: `Created ${displayPath(p.file, ctx.cwd)}`, preview } };
414
628
  }
@@ -416,6 +630,115 @@ Usage:
416
630
  const text = input.replace_all
417
631
  ? `The file ${p.file} has been updated successfully. All ${p.count} occurrences were replaced.`
418
632
  : `The file ${p.file} has been updated successfully (${changedLines(line, p.newStr)}).`;
419
- return { content: text, display: { summary: changeSummary(preview), preview } };
633
+ return { content: p.unseen ? `${text} ${UNSEEN_NOTE[p.unseen]}` : text, display: { summary: changeSummary(preview), preview } };
634
+ },
635
+ };
636
+
637
+ // Several replacements in one file in one call. GPT models make one Edit per response even when they know several
638
+ // 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;
639
+ // 561 times an edit response was followed by another one on the same file), and every response is a round trip of
640
+ // some 18 s on GPT that sends the whole conversation again. With all the changes in one call they are one response.
641
+ // The edits are applied in order to the text as the previous one left it, and all or none are made.
642
+ export const MultiEditTool = {
643
+ name: 'MultiEdit',
644
+ editsFiles: true,
645
+ 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).
646
+
647
+ Usage:
648
+ - 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.
649
+ - 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.
650
+ - Order the edits so that an earlier one does not change the text a later one looks for.
651
+ - To create a file, use Write (or a first edit with an empty old_string, for a file that does not exist).
652
+ - Changes to several files: one MultiEdit or Edit call per file, all in the same response.`,
653
+ input_schema: {
654
+ type: 'object',
655
+ properties: {
656
+ file_path: { type: 'string', description: 'The absolute path to the file to modify' },
657
+ edits: {
658
+ type: 'array',
659
+ minItems: 1,
660
+ description: 'The replacements, made in this order',
661
+ items: {
662
+ type: 'object',
663
+ properties: {
664
+ old_string: { type: 'string', description: 'The text to replace' },
665
+ new_string: { type: 'string', description: 'The text to replace it with' },
666
+ replace_all: { type: 'boolean', default: false, description: 'Replace all occurrences of old_string (default false)' },
667
+ },
668
+ required: ['old_string', 'new_string'],
669
+ },
670
+ },
671
+ },
672
+ required: ['file_path', 'edits'],
673
+ },
674
+ summarize(input, ctx) {
675
+ const n = Array.isArray(input.edits) ? input.edits.length : 0;
676
+ return `${displayPath(resolvePath(input.file_path, ctx.cwd), ctx.cwd)}${n ? `, ${n} edit${n === 1 ? '' : 's'}` : ''}`;
677
+ },
678
+ filePath(input, ctx) { return resolvePath(input.file_path, ctx.cwd); },
679
+ plan(input, ctx) {
680
+ const file = resolvePath(input.file_path, ctx.cwd);
681
+ const edits = Array.isArray(input.edits) ? input.edits : [];
682
+ if (!edits.length) return { error: 'edits must be a non-empty list of {old_string, new_string}.' };
683
+ const steps = edits.map((e) => ({
684
+ oldStr: String(e?.old_string ?? '').replace(/\r\n/g, '\n'),
685
+ newStr: String(e?.new_string ?? '').replace(/\r\n/g, '\n'),
686
+ all: Boolean(e?.replace_all),
687
+ }));
688
+ const exists = fs.existsSync(file);
689
+ let unseen = null;
690
+ let meta = { crlf: false, bom: false, encoding: 'utf8' };
691
+ let before = '';
692
+ if (exists) {
693
+ if (fs.statSync(file).isDirectory()) return { error: `${file} is a directory` };
694
+ unseen = fileStanding(file, ctx); // as in Edit: a unique old_string shows the model has the text it replaces
695
+ if (unseen && steps.some((s) => s.all)) {
696
+ return { error: unseen === 'unread'
697
+ ? 'File has not been read yet. Read it first before replacing every occurrence in it (replace_all).'
698
+ : '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).' };
699
+ }
700
+ const current = readText(file);
701
+ if (!current) return { error: notText(file) };
702
+ if (current.lossy) return { error: notRewritable(file, current) };
703
+ meta = { crlf: current.crlf, bom: current.bom, encoding: current.encoding };
704
+ before = current.text.replace(/\r\n/g, '\n');
705
+ } else if (steps[0].oldStr !== '') {
706
+ return { error: `File does not exist: ${file}. Create it with Write, or with a first edit whose old_string is empty.` };
707
+ }
708
+ let text = before;
709
+ for (let i = 0; i < steps.length; i++) {
710
+ const { oldStr, newStr, all } = steps[i];
711
+ const r = applyEdit(text, oldStr, newStr, all);
712
+ const step = steps.length > 1 ? `Edit ${i + 1} of ${steps.length}: ` : '';
713
+ if (r.error) return { error: `${missed(r, text, oldStr, unseen, step)}${steps.length > 1 ? ' No edit was made.' : ''}` };
714
+ text = r.result;
715
+ }
716
+ const cannot = unwritable(file, text, meta);
717
+ if (cannot) return { error: cannot };
718
+ return { file, before, after: text, meta, count: steps.length, unseen, created: !exists };
420
719
  },
720
+ validate(input, ctx) { return this.plan(input, ctx).error || null; },
721
+ preview(input, ctx, p = this.plan(input, ctx)) { return EditTool.preview(input, ctx, p); },
722
+ async call(input, ctx) {
723
+ const p = this.plan(input, ctx);
724
+ if (p.error) return { isError: true, content: p.error };
725
+ const ops = p.created ? null : diffLines(splitLines(p.before), splitLines(p.after));
726
+ const preview = p.created ? { kind: 'create', path: p.file, lines: splitLines(p.after) } : { kind: 'diff', path: p.file, hunks: makeHunks(ops), ...countChanges(ops) };
727
+ const prior = ctx.fileState.get(p.file);
728
+ const hash = writeText(p.file, p.after, p.meta);
729
+ ctx.fileState.set(p.file, { mtimeMs: mtime(p.file), partial: !p.created && (!prior || Boolean(prior.partial) || p.unseen === 'modified'), hash });
730
+ if (p.created) return { content: `File created successfully at: ${p.file}`, display: { summary: `Created ${displayPath(p.file, ctx.cwd)}`, preview } };
731
+ const text = `The file ${p.file} has been updated successfully: ${p.count} edit${p.count === 1 ? '' : 's'} (${changedRanges(ops)}).`;
732
+ return { content: p.unseen ? `${text} ${UNSEEN_NOTE[p.unseen]}` : text, display: { summary: changeSummary(preview), preview } };
733
+ },
734
+ };
735
+
736
+ // What an edit of a file the model had not read, or that changed since it read it, adds to its result or error.
737
+ const UNSEEN_NOTE = {
738
+ unread: '(The file had not been read in this conversation; old_string matched its current text once.)',
739
+ 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.)',
740
+ };
741
+ const UNSEEN_HINT = {
742
+ unread: 'The file has not been read in this conversation: Read it to get its exact text.',
743
+ modified: 'The file has changed since you last read it: Read it again.',
421
744
  };
@@ -1,7 +1,10 @@
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';
5
+ import { makeBrowserTool, browserToolEnabled } from './browser.js';
6
+ import { makeReplTool } from './code.js';
7
+ import { ProcessesTool } from './processes.js';
5
8
  import { TodoWriteTool, AskUserQuestionTool } from './interaction.js';
6
9
  import { makeTaskTool, TaskOutputTool, TaskStopTool } from './task.js';
7
10
  import { NotebookEditTool } from './notebook.js';
@@ -20,14 +23,18 @@ export function buildTools(config, { agents, skills, mcpTools = [], restart = fa
20
23
  TaskOutputTool,
21
24
  TaskStopTool,
22
25
  makeBashTool(config),
26
+ makeReplTool(config),
27
+ ProcessesTool,
23
28
  GlobTool,
24
29
  GrepTool,
25
30
  ReadTool,
26
31
  EditTool,
32
+ MultiEditTool,
27
33
  WriteTool,
28
34
  NotebookEditTool,
29
35
  makeWebFetchTool(config),
30
36
  WebSearchTool,
37
+ ...(browserToolEnabled(config) ? [makeBrowserTool()] : []),
31
38
  TodoWriteTool,
32
39
  BashOutputTool,
33
40
  KillShellTool,
@@ -47,5 +54,6 @@ export function toolsForSubagent(allTools, def, { allowTask = false } = {}) {
47
54
  const base = allTools.filter((t) => !NEVER_FOR_SUBAGENTS.has(t.name) && (allowTask || t.name !== 'Task'));
48
55
  if (def.tools === '*' || !def.tools) return base;
49
56
  const wanted = new Set(def.tools);
57
+ if (wanted.has('Edit')) wanted.add('MultiEdit'); // the same permission, several changes in one call
50
58
  return base.filter((t) => wanted.has(t.name) || [...wanted].some((w) => w.startsWith('mcp__') && t.name.startsWith(w)));
51
59
  }
@@ -3,7 +3,7 @@
3
3
 
4
4
  import fs from 'node:fs';
5
5
  import { resolvePath, displayPath } from '../utils/paths.js';
6
- import { checkFreshness, mtime } from './files.js';
6
+ import { checkFreshness, mtime, hashOf } from './files.js';
7
7
 
8
8
  // Jupyter stores cell source as an array of lines, each keeping its trailing newline.
9
9
  function toSource(text) {
@@ -52,7 +52,12 @@ export const NotebookEditTool = {
52
52
  if (err) return { isError: true, content: err };
53
53
  const file = resolvePath(input.notebook_path, ctx.cwd);
54
54
  let nb;
55
- try { nb = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { return { isError: true, content: `Could not parse notebook: ${e.message}` }; }
55
+ let bom = false; // a BOM in front made the notebook unreadable here; it is kept when the notebook is written
56
+ try {
57
+ const text = fs.readFileSync(file, 'utf8');
58
+ bom = text.startsWith('\uFEFF');
59
+ nb = JSON.parse(bom ? text.slice(1) : text);
60
+ } catch (e) { return { isError: true, content: `Could not parse notebook: ${e.message}` }; }
56
61
  nb.cells ||= [];
57
62
  const mode = input.edit_mode || 'replace';
58
63
  let summary;
@@ -84,8 +89,10 @@ export const NotebookEditTool = {
84
89
  summary = `Updated cell ${input.cell_id}`;
85
90
  }
86
91
  }
87
- fs.writeFileSync(file, JSON.stringify(nb, null, 1) + '\n', 'utf8');
88
- ctx.fileState.set(file, { mtimeMs: mtime(file) });
92
+ const out = Buffer.from(`${bom ? '\uFEFF' : ''}${JSON.stringify(nb, null, 1)}\n`, 'utf8');
93
+ fs.writeFileSync(file, out);
94
+ // with its hash, as after a Read: a later change of its time alone (a sync, a scan) is not taken for an edit
95
+ ctx.fileState.set(file, { mtimeMs: mtime(file), hash: hashOf(out) });
89
96
  return { content: summary, display: { summary } };
90
97
  },
91
98
  };