mocode-ai 1.10.1 → 1.11.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.
@@ -1,7 +1,8 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, rmdirSync, rmSync, symlinkSync, unlinkSync, writeFileSync, } from 'node:fs';
3
- import * as fsp from 'node:fs/promises';
2
+ import { chmodSync, existsSync, lstat, lstatSync, mkdirSync, readFile, readFileSync, readdir, readlinkSync, rmdirSync, rmSync, symlinkSync, unlinkSync, writeFileSync, } from 'node:fs';
3
+ import { readlink } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
+ import { promisify } from 'node:util';
5
6
  import { config } from '../config/index.js';
6
7
  import { MAX_SNAPSHOT_TURNS } from '../tools/constants.js';
7
8
  import { toText } from '../context/utils.js';
@@ -109,6 +110,10 @@ const SCAN_CONCURRENCY = 16;
109
110
  const YIELD_EVERY = 64;
110
111
  const YIELD_BYTES = 1024 * 1024;
111
112
  const FRESH_WINDOW_MS = 2000;
113
+ // 扫描会发出数千次 I/O。用开销更低的 fs 回调实现,仍异步等待,避免阻塞界面。
114
+ const statEntry = promisify(lstat);
115
+ const listDirectory = promisify(readdir);
116
+ const readEntry = promisify(readFile);
112
117
  /**
113
118
  * contentCache 的常驻字节上限(base64 后的长度和);0 = 不限。
114
119
  *
@@ -208,7 +213,7 @@ export class RollbackStore {
208
213
  const full = path.resolve(root, rel);
209
214
  return full !== root && this.isInside(root, full) ? full : null;
210
215
  }
211
- readState(full) {
216
+ readState(full, preparedFile) {
212
217
  try {
213
218
  const stat = lstatSync(full);
214
219
  const mode = stat.mode & 0o777;
@@ -217,7 +222,7 @@ export class RollbackStore {
217
222
  if (stat.isDirectory())
218
223
  return { kind: 'directory', mode };
219
224
  if (stat.isFile())
220
- return { kind: 'file', data: readFileSync(full).toString('base64'), mode };
225
+ return { kind: 'file', data: (preparedFile ?? readFileSync(full)).toString('base64'), mode };
221
226
  }
222
227
  catch {
223
228
  // 不存在或不可读均按 missing;工具若最终也不可读,不会产生伪变化。
@@ -317,12 +322,12 @@ export class RollbackStore {
317
322
  getCurrentTurnId() {
318
323
  return this.currentTurnId;
319
324
  }
320
- beginPathMutation(value) {
325
+ beginPathMutation(value, preparedFile) {
321
326
  const workspaceRoot = this.rootDir();
322
327
  const full = path.resolve(workspaceRoot, value);
323
328
  return {
324
329
  path: this.toRel(workspaceRoot, full),
325
- before: this.readState(full),
330
+ before: this.readState(full, preparedFile),
326
331
  sequence: ++this.sequenceCounter,
327
332
  createdParents: this.missingParents(workspaceRoot, full),
328
333
  turnId: this.currentTurnId,
@@ -367,7 +372,7 @@ export class RollbackStore {
367
372
  return (EXCLUDED_WORKSPACE_DIRS.has(lower) ||
368
373
  (lower === sessionName && path.relative(sessionsRoot, prefix + rel) === ''));
369
374
  };
370
- const readDir = (rel) => fsp.readdir(prefix + rel, { withFileTypes: true }).catch(() => []);
375
+ const readDir = (rel) => listDirectory(prefix + rel, { withFileTypes: true }).catch(() => []);
371
376
  // 仅读取本次扫描的目录。预取兄弟目录,仍按原来的深度优先顺序消费,保留条目上限的语义。
372
377
  const ahead = new Map();
373
378
  const walk = async (dir) => {
@@ -391,11 +396,12 @@ export class RollbackStore {
391
396
  if (excluded(child.name, rel))
392
397
  continue;
393
398
  paths.push(rel);
394
- if (child.isDirectory() && paths.length < CAPTURE_ENTRY_LIMIT)
399
+ if (child.isDirectory() && paths.length < CAPTURE_ENTRY_LIMIT) {
400
+ startWorkers();
395
401
  await walk(rel);
402
+ }
396
403
  }
397
404
  };
398
- await walk('');
399
405
  let budget = CAPTURE_TOTAL_LIMIT;
400
406
  let cursor = 0;
401
407
  let processed = 0;
@@ -410,10 +416,10 @@ export class RollbackStore {
410
416
  }
411
417
  let state;
412
418
  try {
413
- const stat = await fsp.lstat(full, { bigint: true });
419
+ const stat = await statEntry(full, { bigint: true });
414
420
  const mode = Number(stat.mode) & 0o777;
415
421
  if (stat.isSymbolicLink()) {
416
- const target = await fsp.readlink(full);
422
+ const target = await readlink(full);
417
423
  state = { kind: 'symlink', data: target, stamp: target, mode };
418
424
  }
419
425
  else if (stat.isDirectory()) {
@@ -432,7 +438,7 @@ export class RollbackStore {
432
438
  else if (size <= CAPTURE_FILE_LIMIT && budget - size >= 0) {
433
439
  budget -= size;
434
440
  bytesSinceYield += size;
435
- const data = (await fsp.readFile(full)).toString('base64');
441
+ const data = await readEntry(full, 'base64');
436
442
  state = { kind: 'file', data, stamp, mode };
437
443
  nextCache.set(full, { stamp, mode, data });
438
444
  }
@@ -451,7 +457,18 @@ export class RollbackStore {
451
457
  entries.set(rel, state);
452
458
  }
453
459
  };
454
- await Promise.all(Array.from({ length: Math.min(SCAN_CONCURRENCY, Math.max(1, paths.length)) }, worker));
460
+ // 深度优先枚举仍决定条目上限,同时让已发现的路径与后续目录读取并行。
461
+ const workers = new Set();
462
+ const startWorkers = () => {
463
+ const count = Math.min(SCAN_CONCURRENCY - workers.size, paths.length - cursor);
464
+ for (let i = 0; i < count; i++) {
465
+ const pending = worker().finally(() => workers.delete(pending));
466
+ workers.add(pending);
467
+ }
468
+ };
469
+ await walk('');
470
+ startWorkers();
471
+ await Promise.all(workers);
455
472
  this.contentCache = trimContentCache(nextCache);
456
473
  return entries;
457
474
  }
@@ -471,15 +488,20 @@ export class RollbackStore {
471
488
  }
472
489
  async endWorkspaceMutation(capture, op) {
473
490
  const after = await this.scanWorkspace(capture.workspaceRoot, capture.sessionsRoot);
474
- const paths = new Set([...capture.entries.keys(), ...after.keys()]);
491
+ const missing = { kind: 'missing' };
475
492
  let changed = false;
476
- for (const rel of paths) {
477
- const beforeState = capture.entries.get(rel) ?? { kind: 'missing' };
478
- const afterState = after.get(rel) ?? { kind: 'missing' };
493
+ const recordChange = (rel, beforeState, afterState) => {
479
494
  if (this.sameState(beforeState, afterState))
480
- continue;
495
+ return;
481
496
  changed = true;
482
497
  this.addSnapshot(this.snapshotFromState(capture.turnId, rel, beforeState, capture.sequence, op, [], afterState));
498
+ };
499
+ for (const [rel, beforeState] of capture.entries) {
500
+ recordChange(rel, beforeState, after.get(rel) ?? missing);
501
+ }
502
+ for (const [rel, afterState] of after) {
503
+ if (!capture.entries.has(rel))
504
+ recordChange(rel, missing, afterState);
483
505
  }
484
506
  if (changed)
485
507
  this.mutationVersion += 1;
@@ -4,21 +4,63 @@ import { unifiedFileDiff } from '../../changeset/unified-diff.js';
4
4
  import { jailResolve } from '../../sandbox/index.js';
5
5
  import { commitChangeSet, contentHash, createChangeSet, normalizeContentHash, summarizeChangeSet, } from '../../changeset/index.js';
6
6
  import { isProbablyBinary } from '../../attachments/image.js';
7
+ import { formatNumberedLines } from './read-file.js';
7
8
  /** 二进制嗅探只需文件头,与 read_file / write_file 同口径(16KB)。 */
8
9
  const SNIFF_BYTES = 16 * 1024;
9
10
  // 复用已有 diff 渲染,只给模型回传完整的小补丁。大文件免去额外的全文拆行。
10
11
  const MAX_PREVIEW_INPUT_CHARS = 256 * 1024;
11
12
  const MAX_PREVIEW_CHARS = 2000;
12
- function conflict(path, details) {
13
+ const MAX_CONFLICT_CANDIDATES = 2;
14
+ const MAX_CONFLICT_EVIDENCE_CHARS = 2400;
15
+ function conflict(path, details, evidence) {
16
+ const recovery = evidence
17
+ ? `${evidence.next} If the target is still unclear, use read_file on the affected range.\n${evidence.excerpts}`
18
+ : 'Use read_file on the affected range of this exact path and copy the latest text and hash before editing again.';
13
19
  return {
14
20
  status: 'error',
15
21
  code: 'CHANGE_CONFLICT',
16
22
  retryable: false,
17
23
  changedFiles: [],
18
24
  staleFiles: [path],
19
- output: `CHANGE_CONFLICT: ${path} was not changed. ${details} Do not retry these arguments. Use read_file on the affected range of this exact path and copy the latest text and hash before editing again.`,
25
+ output: `CHANGE_CONFLICT: ${path} was not changed. ${details} Do not retry these arguments. ${recovery}`,
20
26
  };
21
27
  }
28
+ function findOccurrences(text, needle) {
29
+ const hits = [];
30
+ let from = 0;
31
+ while (hits.length <= MAX_CONFLICT_CANDIDATES) {
32
+ const hit = text.indexOf(needle, from);
33
+ if (hit < 0)
34
+ break;
35
+ hits.push(hit);
36
+ from = hit + needle.length;
37
+ }
38
+ return hits;
39
+ }
40
+ function ambiguousConflict(path, label, text, needle, hits, buffer, expectedHash) {
41
+ const capped = hits.length > MAX_CONFLICT_CANDIDATES;
42
+ const details = `${label} 出现 ${capped ? '至少 ' : ''}${hits.length} 次;请选定目标范围。`;
43
+ if (capped || buffer.length > MAX_PREVIEW_INPUT_CHARS || contentHash(buffer) !== expectedHash) {
44
+ return conflict(path, details);
45
+ }
46
+ if (!Buffer.from(buffer.toString('utf8')).equals(buffer))
47
+ return conflict(path, details);
48
+ const lines = text.split('\n');
49
+ const matchLineCount = needle.split('\n').length - Number(needle.endsWith('\n'));
50
+ const excerpts = hits.map((hit) => {
51
+ const matchLine = text.slice(0, hit).split('\n').length;
52
+ const start = Math.max(0, matchLine - 4);
53
+ const end = Math.min(lines.length, matchLine - 1 + matchLineCount + 3);
54
+ return `[edit_context path=${JSON.stringify(path)} hash=${expectedHash} lines=${start + 1}-${end} match=${matchLine}]\n${formatNumberedLines(lines, start, end)}`;
55
+ });
56
+ const evidence = excerpts.join('\n\n');
57
+ if (evidence.length > MAX_CONFLICT_EVIDENCE_CHARS)
58
+ return conflict(path, details);
59
+ const next = label === 'old_string'
60
+ ? "Use the candidate that matches the user's target. Copy its exact text or use the shown lines with its expected_hash."
61
+ : `Use the matching candidate to expand ${label} into unique exact text. Resubmit the complete replacements array with the shown expected_hash.`;
62
+ return conflict(path, details, { excerpts: evidence, next });
63
+ }
22
64
  export const editFileTool = {
23
65
  name: 'edit_file',
24
66
  description: `The DEFAULT tool for changing an EXISTING file: transactional, surgical edits — use this instead of re-writing the whole file with write_file. Pick ONE of three modes per call:
@@ -148,12 +190,14 @@ export const editFileTool = {
148
190
  // String replacement mode
149
191
  const newNormalized = toLf(String(args.new_string));
150
192
  const oldNormalized = toLf(String(args.old_string));
151
- const count = normalized.split(oldNormalized).length - 1;
152
- if (count === 0) {
193
+ if (!oldNormalized)
194
+ return conflict(file, 'old_string 不能为空。');
195
+ const hits = findOccurrences(normalized, oldNormalized);
196
+ if (hits.length === 0) {
153
197
  return conflict(file, 'old_string 未找到;请重新 read_file 并复制最新内容。');
154
198
  }
155
- if (count > 1) {
156
- return conflict(file, `old_string 出现 ${count} 次;请增加上下文使其唯一。`);
199
+ if (hits.length > 1) {
200
+ return ambiguousConflict(file, 'old_string', normalized, oldNormalized, hits, buffer, expectedHash);
157
201
  }
158
202
  updated = normalized.replace(oldNormalized, () => newNormalized);
159
203
  }
@@ -163,19 +207,12 @@ export const editFileTool = {
163
207
  const located = [];
164
208
  for (let i = 0; i < multiEdits.length; i++) {
165
209
  const edit = multiEdits[i];
166
- const hits = [];
167
- let from = 0;
168
- let hit;
169
- // 空串已在上面拒绝;indexOf 步进至少 1 不会死循环。
170
- while ((hit = normalized.indexOf(edit.old, from)) !== -1) {
171
- hits.push(hit);
172
- from = hit + edit.old.length;
173
- }
210
+ const hits = findOccurrences(normalized, edit.old);
174
211
  if (hits.length === 0) {
175
212
  return conflict(file, `replacements[${i}].old_string 未找到;请重新 read_file 并复制最新内容。`);
176
213
  }
177
214
  if (hits.length > 1) {
178
- return conflict(file, `replacements[${i}].old_string 出现 ${hits.length} 次;请增加上下文使其唯一。`);
215
+ return ambiguousConflict(file, `replacements[${i}].old_string`, normalized, edit.old, hits, buffer, expectedHash);
179
216
  }
180
217
  located.push({ start: hits[0], end: hits[0] + edit.old.length, next: edit.next });
181
218
  }
@@ -4,7 +4,7 @@ import { IGNORE, MAX_RESULTS } from '../constants.js';
4
4
  import { isProbablyBinary } from '../../attachments/image.js';
5
5
  import { getSandboxRoot, isInsideRoot, jailResolve } from '../../sandbox/index.js';
6
6
  import { runRipgrep } from '../ripgrep-client.js';
7
- import { readSearchEditExcerpt } from './read-file.js';
7
+ import { readSearchEditExcerpts } from './read-file.js';
8
8
  /**
9
9
  * grep 超时墙。
10
10
  *
@@ -20,6 +20,9 @@ const MAX_BODY_LINE_CHARS = 400;
20
20
  /** context 参数上限:邻居行是 ×(1+2C) 放大,给到 10 已远超需要。 */
21
21
  const MAX_CONTEXT_LINES = 10;
22
22
  const MAX_EDIT_CANDIDATES = 8;
23
+ const MAX_EDIT_EXCERPTS = 3;
24
+ const MAX_MULTI_EDIT_CONTEXT_CHARS = 4_000;
25
+ const MAX_PATH_OUTPUT_CHARS = 16_000;
23
26
  function abortedResult(timedOut) {
24
27
  if (!timedOut)
25
28
  return '已中断';
@@ -95,6 +98,23 @@ function renderResults(files, maxPerFile, context, truncated) {
95
98
  out.push('...(仍有更多匹配未展示,缩小 glob 或收窄正则)');
96
99
  return out.join('\n');
97
100
  }
101
+ function renderMatchedPaths(paths, truncated) {
102
+ const shown = [];
103
+ let chars = 0;
104
+ for (const path of paths) {
105
+ const line = /[\r\n]/.test(path) ? JSON.stringify(path) : path;
106
+ chars += line.length + 1;
107
+ if (chars > MAX_PATH_OUTPUT_CHARS) {
108
+ truncated = true;
109
+ break;
110
+ }
111
+ shown.push(line);
112
+ }
113
+ const output = shown.length > 0 ? [`[grep files=${shown.length}]`, ...shown] : ['无匹配文件'];
114
+ if (truncated)
115
+ output.push('...(文件列表不完整,缩小 glob 或收窄正则)');
116
+ return output.join('\n');
117
+ }
98
118
  function renderEditCandidates(files, truncated) {
99
119
  const out = [];
100
120
  for (const file of files) {
@@ -110,9 +130,12 @@ function renderEditCandidates(files, truncated) {
110
130
  out.push('未提供编辑原文。请收窄搜索,或对选中的路径和行号使用 read_file。');
111
131
  return out.join('\n');
112
132
  }
113
- async function renderEditContext(files, truncated, signal) {
114
- const file = files[0];
115
- if (!truncated && files.length === 1 && file.matches.length === 1) {
133
+ async function renderEditContext(files, truncated, maxCandidates, signal) {
134
+ const matchCount = files.reduce((total, file) => total + file.matches.length, 0);
135
+ if (truncated || matchCount === 0 || matchCount > maxCandidates)
136
+ return renderEditCandidates(files, truncated);
137
+ const excerpts = [];
138
+ for (const file of files) {
116
139
  let absolutePath;
117
140
  try {
118
141
  absolutePath = jailResolve(file.path);
@@ -120,19 +143,22 @@ async function renderEditContext(files, truncated, signal) {
120
143
  catch {
121
144
  // 路径可能在搜索与读取之间变成越界链接。
122
145
  }
123
- if (absolutePath) {
124
- const excerpt = await readSearchEditExcerpt(absolutePath, file.matches[0], signal);
125
- if (excerpt)
126
- return excerpt;
127
- }
146
+ if (!absolutePath)
147
+ return renderEditCandidates(files, truncated);
148
+ const excerpt = await readSearchEditExcerpts(absolutePath, file.matches, signal);
149
+ if (!excerpt)
150
+ return renderEditCandidates(files, truncated);
151
+ excerpts.push(excerpt);
128
152
  }
129
- return renderEditCandidates(files, truncated);
153
+ const output = excerpts.join('\n\n');
154
+ return matchCount > 1 && output.length > MAX_MULTI_EDIT_CONTEXT_CHARS
155
+ ? renderEditCandidates(files, truncated)
156
+ : output;
130
157
  }
131
158
  /**
132
- * Node 兜底:rg 二进制不可用(可选依赖缺失且 PATH 无 rg)时走旧路径。
133
- * 与旧实现的唯一差异——每两个文件之间检查 abort 信号,使 Ctrl+C / 超时墙能即时打断。
159
+ * Node 兜底:rg 二进制不可用时用 fast-glob 枚举,再按行查找。
134
160
  */
135
- async function nodeFallback(pattern, glob, maxPerFile, editContext, signal, externalSignal) {
161
+ async function nodeFallback(pattern, glob, maxPerFile, editContext, filesOnly, signal, externalSignal) {
136
162
  let re;
137
163
  try {
138
164
  re = new RegExp(pattern);
@@ -146,12 +172,14 @@ async function nodeFallback(pattern, glob, maxPerFile, editContext, signal, exte
146
172
  cwd,
147
173
  onlyFiles: true,
148
174
  dot: true,
149
- ignore: IGNORE,
175
+ ignore: glob.startsWith('.mocode/') ? IGNORE : [...IGNORE, '**/.mocode/**'],
150
176
  stats: true,
151
177
  followSymbolicLinks: false,
152
178
  throwErrorOnBrokenSymbolicLink: false,
153
179
  })).filter((entry) => isInsideRoot(entry.path)); // 后置兜底:仅留牢内
154
180
  const files = [];
181
+ const paths = [];
182
+ let truncated = false;
155
183
  let scanned = 0;
156
184
  let skippedTooLarge = 0;
157
185
  const abortNote = () => externalSignal?.aborted
@@ -162,9 +190,8 @@ async function nodeFallback(pattern, glob, maxPerFile, editContext, signal, exte
162
190
  retryable: false,
163
191
  output: `错误:grep 超过 ${GREP_TIMEOUT_MS / 1000}s 超时墙已被中止(收窄 glob 后重试)`,
164
192
  };
165
- for (let fi = 0; fi < entries.length; fi++) {
166
- const entry = entries[fi];
167
- if ((fi & 31) === 0 && signal.aborted)
193
+ for (const entry of entries) {
194
+ if (signal.aborted)
168
195
  return abortNote();
169
196
  if (entry.stats && entry.stats.size > MAX_FILE_BYTES) {
170
197
  skippedTooLarge++;
@@ -172,7 +199,7 @@ async function nodeFallback(pattern, glob, maxPerFile, editContext, signal, exte
172
199
  }
173
200
  let content;
174
201
  try {
175
- content = await readFile(jailResolve(entry.path), 'utf8');
202
+ content = await readFile(jailResolve(entry.path), { encoding: 'utf8', signal });
176
203
  }
177
204
  catch {
178
205
  continue;
@@ -181,6 +208,16 @@ async function nodeFallback(pattern, glob, maxPerFile, editContext, signal, exte
181
208
  if (isProbablyBinary(content))
182
209
  continue;
183
210
  const lines = content.split(/\r?\n/);
211
+ if (filesOnly) {
212
+ if (!lines.some((line) => re.test(line)))
213
+ continue;
214
+ if (paths.length === MAX_RESULTS) {
215
+ truncated = true;
216
+ break;
217
+ }
218
+ paths.push(entry.path);
219
+ continue;
220
+ }
184
221
  const matches = [];
185
222
  for (let i = 0; i < lines.length; i++) {
186
223
  if (re.test(lines[i]))
@@ -191,6 +228,10 @@ async function nodeFallback(pattern, glob, maxPerFile, editContext, signal, exte
191
228
  }
192
229
  if (signal.aborted)
193
230
  return abortNote();
231
+ if (filesOnly) {
232
+ const output = renderMatchedPaths(paths, truncated);
233
+ return skippedTooLarge ? `${output}\n...(跳过 ${skippedTooLarge} 个超过 2MiB 的文件)` : output;
234
+ }
194
235
  if (files.length === 0) {
195
236
  const note = skippedTooLarge ? `,跳过 ${skippedTooLarge} 个超过 2MiB 的文件` : '';
196
237
  return `无匹配(扫描了 ${scanned} 个文件${note})`;
@@ -204,16 +245,28 @@ export const grepTool = {
204
245
  name: 'grep',
205
246
  description: 'Search file contents by regex (recursive; powered by ripgrep: respects .gitignore, skips binaries).\n' +
206
247
  'Output: per-file header "<path>: N matches, lines [l1, l2, ...]" plus rendered lines with ORIGINAL INDENTATION kept.\n' +
207
- 'Pass context=2..5 for neighbouring lines. When locating an edit target in an unknown file, use edit_context=true with a narrow pattern. A unique hit can return an exact, bounded [edit_context ...] excerpt; use its path and hash as expected_hash in edit_file. Otherwise you get at most 8 candidate lines; use read_file for exact text. Hard wall 120s.\n' +
248
+ 'For tasks that only need to know which files contain a match, use mode="files" to list paths once per file.\n' +
249
+ 'Pass context=2..5 for neighbouring lines. For an edit in an unknown file, use edit_context=true with a narrow pattern. Use max_edit_candidates=3 when definitions, tests or other versions may share the same match. An [edit_context ...] block gives exact text; use the chosen block’s path and hash as expected_hash in edit_file. Searches over budget return locations only. Hard wall 120s.\n' +
208
250
  'Note: .mocode/ is gitignored; to search session data (e.g. .mocode/sessions/<id>/compacted archived history) you MUST narrow glob to that path, e.g. glob=".mocode/sessions/**".',
209
251
  parameters: {
210
252
  type: 'object',
211
253
  properties: {
212
254
  pattern: { type: 'string', description: 'Regular expression (ripgrep/Rust regex syntax)' },
213
255
  glob: { type: 'string', description: 'Optional, restrict to a file glob, e.g. *.ts' },
256
+ mode: {
257
+ type: 'string',
258
+ enum: ['matches', 'files'],
259
+ description: 'Default matches returns lines. Files lists paths only, ignores context and max_per_file, and cannot be combined with edit_context=true.',
260
+ },
214
261
  edit_context: {
215
262
  type: 'boolean',
216
- description: 'Return an exact edit excerpt for a unique match, or a short candidate list. Ignores context and max_per_file.',
263
+ description: 'Return exact edit excerpts within max_edit_candidates and a shared output budget, or a short candidate list. Ignores context and max_per_file.',
264
+ },
265
+ max_edit_candidates: {
266
+ type: 'integer',
267
+ minimum: 1,
268
+ maximum: MAX_EDIT_EXCERPTS,
269
+ description: 'Match limit for edit_context, default 1. Set 3 to request original text for a small set of candidates.',
217
270
  },
218
271
  max_per_file: {
219
272
  type: 'integer',
@@ -231,6 +284,19 @@ export const grepTool = {
231
284
  const pattern = String(args.pattern);
232
285
  const glob = String(args.glob ?? '**/*');
233
286
  const editContext = args.edit_context === true;
287
+ const filesOnly = args.mode === 'files';
288
+ if (filesOnly && editContext) {
289
+ return {
290
+ status: 'error',
291
+ code: 'INVALID_ARGUMENTS',
292
+ retryable: false,
293
+ output: '错误:mode="files" 只返回路径;获取可编辑原文时用 mode="matches" 与 edit_context=true。',
294
+ };
295
+ }
296
+ const requestedCandidates = Number(args.max_edit_candidates ?? 1);
297
+ const maxEditCandidates = Number.isInteger(requestedCandidates)
298
+ ? Math.max(1, Math.min(MAX_EDIT_EXCERPTS, requestedCandidates))
299
+ : 1;
234
300
  const maxPerFile = Math.min(Math.max(Number(args.max_per_file ?? 15), 1), 50);
235
301
  const contextRaw = Number(args.context ?? 0);
236
302
  const context = Number.isFinite(contextRaw) ? Math.min(Math.max(Math.trunc(contextRaw), 0), MAX_CONTEXT_LINES) : 0;
@@ -258,8 +324,11 @@ export const grepTool = {
258
324
  context: editContext ? 0 : context,
259
325
  noIgnoreVcs,
260
326
  maxMatches: editContext ? MAX_EDIT_CANDIDATES : MAX_RESULTS,
327
+ ...(filesOnly ? { maxFiles: MAX_RESULTS } : {}),
261
328
  }, controller.signal);
262
329
  switch (result.status) {
330
+ case 'paths':
331
+ return renderMatchedPaths(result.paths, result.truncated);
263
332
  case 'regex_error':
264
333
  return `错误:非法正则 ${pattern}: ${result.message}`;
265
334
  case 'no-match': {
@@ -269,11 +338,11 @@ export const grepTool = {
269
338
  case 'ok': {
270
339
  if (!editContext)
271
340
  return renderResults(result.files, maxPerFile, context, result.truncated);
272
- const output = await renderEditContext(result.files, result.truncated, controller.signal);
341
+ const output = await renderEditContext(result.files, result.truncated, maxEditCandidates, controller.signal);
273
342
  return controller.signal.aborted ? abortedResult(timedOut) : output;
274
343
  }
275
344
  case 'unavailable':
276
- return await nodeFallback(pattern, glob, maxPerFile, editContext, controller.signal, external);
345
+ return await nodeFallback(pattern, glob, maxPerFile, editContext, filesOnly, controller.signal, external);
277
346
  case 'aborted':
278
347
  return abortedResult(timedOut);
279
348
  }
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
1
2
  import { readFile, stat } from 'node:fs/promises';
2
3
  import { resolve } from 'node:path';
3
4
  import { contentHash } from '../../changeset/index.js';
@@ -67,14 +68,46 @@ async function loadReadableFile(path, signal) {
67
68
  return failure(e?.code === 'EACCES' || e?.code === 'EPERM' ? 'SANDBOX_DENIED' : 'EXECUTION_ERROR', `读取 ${path} 失败: ${e?.message ?? String(error)}`);
68
69
  }
69
70
  }
70
- function formatNumberedLines(lines, start, end) {
71
+ const pendingBatchReads = new AsyncLocalStorage();
72
+ /** 只在并行工具组内共享仍在进行的读取。等锁的后续调用会重新取文件。 */
73
+ export function withReadFileBatch(start) {
74
+ return pendingBatchReads.run(new Map(), start);
75
+ }
76
+ async function loadReadFileSnapshot(path) {
77
+ const loaded = await loadReadableFile(path);
78
+ if (!('buffer' in loaded))
79
+ return loaded;
80
+ const { buffer, size } = loaded;
81
+ // 图片与普通二进制都用实际字节识别,文件扩展名不参与判定。
82
+ const head = buffer.subarray(0, SNIFF_BYTES);
83
+ const mime = sniffImageMime(head);
84
+ if (mime)
85
+ return { kind: 'image', mime, size };
86
+ if (isProbablyBinary(head))
87
+ return { kind: 'binary' };
88
+ const data = buffer.toString('utf8');
89
+ return { kind: 'text', data, lines: data.split(/\r?\n/) };
90
+ }
91
+ function readFileSnapshot(path) {
92
+ const pending = pendingBatchReads.getStore();
93
+ if (!pending)
94
+ return loadReadFileSnapshot(path);
95
+ const key = resolve(path);
96
+ const existing = pending.get(key);
97
+ if (existing)
98
+ return existing;
99
+ const load = loadReadFileSnapshot(path).finally(() => pending.delete(key));
100
+ pending.set(key, load);
101
+ return load;
102
+ }
103
+ export function formatNumberedLines(lines, start, end) {
71
104
  return lines
72
105
  .slice(start, end)
73
106
  .map((line, i) => `${String(start + i + 1).padStart(6, ' ')}\t${line}`)
74
107
  .join('\n');
75
108
  }
76
109
  /** 只为已定位且已通过沙箱解析的命中返回未截断原文与同一份内容的版本。 */
77
- export async function readSearchEditExcerpt(absolutePath, match, signal) {
110
+ export async function readSearchEditExcerpts(absolutePath, matches, signal) {
78
111
  const loaded = await loadReadableFile(absolutePath, signal);
79
112
  if (!('buffer' in loaded) || signal.aborted)
80
113
  return;
@@ -87,22 +120,39 @@ export async function readSearchEditExcerpt(absolutePath, match, signal) {
87
120
  const data = buffer.toString('utf8');
88
121
  if (!Buffer.from(data, 'utf8').equals(buffer))
89
122
  return;
90
- const lines = data.split(/\r?\n/);
91
- if (lines[match.line - 1] !== match.text)
92
- return;
93
- const start = Math.max(0, match.line - 9);
94
- const end = Math.min(lines.length, match.line + 12);
95
- const body = formatNumberedLines(lines, start, end);
96
- // 超长行退回定位结果,避免向模型提供只能用于定位的截断源码。
97
- if (body.length > 4_000)
98
- return;
99
- return `[edit_context path=${JSON.stringify(absolutePath)} hash=${contentHash(buffer)} lines=${start + 1}-${end} match=${match.line}]\n${body}`;
123
+ // 版本仍取自完整文件。原文只需要拆到最后一个命中附近,避免为文件前部的命中拆出整个大文件。
124
+ const lastNeededLine = matches.reduce((last, match) => Math.max(last, match.line + 12), 0);
125
+ const lines = data.split(/\r?\n/, lastNeededLine);
126
+ const ranges = [];
127
+ for (const match of matches) {
128
+ if (lines[match.line - 1] !== match.text)
129
+ return;
130
+ const start = Math.max(0, match.line - 9);
131
+ const end = Math.min(lines.length, match.line + 12);
132
+ const previous = ranges.at(-1);
133
+ if (previous && start < previous.end) {
134
+ previous.end = Math.max(previous.end, end);
135
+ previous.matches.push(match.line);
136
+ }
137
+ else {
138
+ ranges.push({ start, end, matches: [match.line] });
139
+ }
140
+ }
141
+ const file = `path=${JSON.stringify(absolutePath)} hash=${contentHash(buffer)}`;
142
+ const excerpts = [];
143
+ for (const range of ranges) {
144
+ const body = formatNumberedLines(lines, range.start, range.end);
145
+ if (body.length > 4_000)
146
+ return;
147
+ excerpts.push(`[edit_context ${file} lines=${range.start + 1}-${range.end} match=${range.matches.join(',')}]\n${body}`);
148
+ }
149
+ return excerpts.join('\n\n');
100
150
  }
101
151
  // ---------- read_file ----------
102
152
  export const readFileTool = {
103
153
  name: 'read_file',
104
154
  description: 'Read a file: text with line numbers, images as visual model input.\n' +
105
- 'Text — read before editing. With a known path and declaration or snippet, pass anchor to locate it and read its code in one call. Use offset+limit for known line numbers, or grep to discover paths. ' +
155
+ 'Text — read before editing. Use anchor for a known declaration or literal, offset+limit for known line numbers, or grep to discover unknown paths. ' +
106
156
  'Images — PNG/JPEG/GIF/WebP detected by MAGIC BYTES (extension ignored), attached as visual input; detail=low|high controls resolution, oversized PNGs downscale automatically. ' +
107
157
  'Other binaries are REJECTED with an explanation — use run_command with a proper tool (`file`, `strings`, disassembler) if you need their content.',
108
158
  parameters: {
@@ -119,7 +169,7 @@ export const readFileTool = {
119
169
  },
120
170
  limit: {
121
171
  type: 'integer',
122
- description: 'Max text lines to read (default 80 with anchor, otherwise 300; hard cap 2000). Aim for ~32k output characters or less per call. Ignored for images.',
172
+ description: 'Max text lines (default 80 with anchor, otherwise 300; hard cap 2000). Match the limit to the code needed. Text only.',
123
173
  },
124
174
  detail: {
125
175
  type: 'string',
@@ -137,19 +187,12 @@ export const readFileTool = {
137
187
  const limit = Math.min(Number(args.limit ?? (anchor === undefined ? DEFAULT_READ_LIMIT : ANCHORED_READ_LIMIT)), MAX_FILE_LINES);
138
188
  // enforceSandbox 已把 args.path 重写为牢内绝对路径(sandbox/policy.ts SANDBOX_PATH_TOOLS),
139
189
  // resolve 对绝对路径原样返回。
140
- const loaded = await loadReadableFile(path);
141
- if (!('buffer' in loaded))
142
- return loaded;
143
- const { buffer, size } = loaded;
144
- // ── 2. 魔数嗅探:图片走视觉通道,其余二进制明确拒绝 ──────────────────────
145
- // 为什么必须嗅探而不看扩展名:扩展名会说谎(截图缓存 / 构建产物常无扩展名或错扩展名),
146
- // 而把二进制当 UTF-8 解码的代价是实测一张 42KB PNG 产出 17862 个 U+FFFD(占 45%),
147
- // 经 history 上限中截后仍有数千字符纯乱码进上下文 —— 既烧 token 又误导模型。
148
- const head = buffer.subarray(0, SNIFF_BYTES);
149
- const sniffed = sniffImageMime(head);
150
- if (sniffed)
151
- return await readAsImage(path, sniffed, args.detail, size);
152
- if (isProbablyBinary(head)) {
190
+ const snapshot = await readFileSnapshot(path);
191
+ if (!('kind' in snapshot))
192
+ return snapshot;
193
+ if (snapshot.kind === 'image')
194
+ return await readAsImage(path, snapshot.mime, args.detail, snapshot.size);
195
+ if (snapshot.kind === 'binary') {
153
196
  return failure('INVALID_ARGUMENTS', `${path} 是二进制文件(头部含控制字符),不能按文本读取 —— 强行解码只会得到乱码。` +
154
197
  '若它其实是图片,支持的格式为 png/jpg/jpeg/gif/webp;否则用 run_command 配合专用工具' +
155
198
  '(如 file / strings / 反汇编器)查看。');
@@ -157,8 +200,7 @@ export const readFileTool = {
157
200
  // ── 3. 文本:沿用既有 artifact header + 行号分页 ────────────────────────
158
201
  // hash 仍取「UTF-8 解码后字符串」的摘要(与改动前逐字节一致):会话里已持久化的
159
202
  // expected_hash 与 context/artifacts 的 parseReadHash 都依赖这个口径,不能顺手换。
160
- const data = buffer.toString('utf8');
161
- const lines = data.split(/\r?\n/);
203
+ const { data, lines } = snapshot;
162
204
  let start = Math.max(0, offset - 1);
163
205
  if (anchor !== undefined) {
164
206
  if (typeof anchor !== 'string' || !anchor.length || /[\r\n]/.test(anchor)) {
@@ -170,7 +212,7 @@ export const readFileTool = {
170
212
  return failure('EXECUTION_ERROR', `${path} 从第 ${Math.max(1, offset)} 行起未找到 anchor。请缩短原文片段或用 grep 搜索。`);
171
213
  }
172
214
  }
173
- const fileHash = contentHash(data);
215
+ const fileHash = (snapshot.hash ??= contentHash(data));
174
216
  const artifactHeader = `[artifact source=read_file path=${path} hash=${fileHash}]`;
175
217
  const end = Math.min(lines.length, start + limit);
176
218
  const body = formatNumberedLines(lines, start, end);
@@ -195,7 +237,7 @@ export const readFileTool = {
195
237
  }
196
238
  }
197
239
  const baseOutput = end < lines.length
198
- ? `${artifactHeader}\n${body}\n\n... (${lines.length - end} 行未显示,共 ${lines.length} 行)`
240
+ ? `${artifactHeader}\n${body}\n\n... (${lines.length - end} 行未显示,共 ${lines.length} 行,续读 offset=${end + 1})`
199
241
  : `${artifactHeader}\n${body}`;
200
242
  // R2.4:回注锚定本文件的记忆(最多 3 条,只回 fresh)。
201
243
  // 为什么放在 read_file 而不是 system prompt:prompt 每轮注入会撞 cache,而且