mocode-ai 1.10.0 → 1.10.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 (50) hide show
  1. package/dist/agent/index.js +13 -3
  2. package/dist/agent/mentioned-files.js +71 -0
  3. package/dist/agent/model-turn.js +55 -11
  4. package/dist/agent/progress-guard.js +67 -0
  5. package/dist/agent/run-coordinator.js +140 -12
  6. package/dist/agent/short-path-completion.js +109 -0
  7. package/dist/agent/spawn.js +39 -0
  8. package/dist/agent/stages/history-manager.js +1 -0
  9. package/dist/agent/tool-helpers.js +2 -2
  10. package/dist/agent/tool-turn.js +49 -4
  11. package/dist/agent/work-discipline.js +9 -9
  12. package/dist/config/index.js +13 -10
  13. package/dist/context/relevance.js +2 -1
  14. package/dist/host/stdio.js +88 -27
  15. package/dist/i18n/index.js +26 -10
  16. package/dist/llm/index.js +27 -3
  17. package/dist/llm/message-shape.js +18 -0
  18. package/dist/llm/reasoning.js +17 -0
  19. package/dist/models/reasoning-cap.js +19 -2
  20. package/dist/orchestrator/lane-executor.js +7 -1
  21. package/dist/orchestrator/repl.js +30 -49
  22. package/dist/repl/commands/appearance.js +1 -2
  23. package/dist/repl/commands/compact.js +4 -0
  24. package/dist/repl/commands/model-actions.js +4 -3
  25. package/dist/repl/commands/model.js +2 -3
  26. package/dist/repl/message-format.js +7 -6
  27. package/dist/repl/running-input.js +27 -65
  28. package/dist/repl/runtime.js +118 -76
  29. package/dist/rollback/store.js +36 -23
  30. package/dist/runtime/runtime.js +1 -1
  31. package/dist/session/compact.js +41 -4
  32. package/dist/session/retention.js +4 -0
  33. package/dist/session/short-path-metrics.js +185 -0
  34. package/dist/session/store.js +78 -3
  35. package/dist/session/terminal-transcript.js +101 -0
  36. package/dist/tools/builtins/ask-human.js +2 -2
  37. package/dist/tools/builtins/edit-file.js +28 -5
  38. package/dist/tools/builtins/grep.js +85 -35
  39. package/dist/tools/builtins/plan-update.js +4 -2
  40. package/dist/tools/builtins/read-file.js +95 -44
  41. package/dist/tools/builtins/run-command.js +57 -9
  42. package/dist/tools/ripgrep-client.js +31 -11
  43. package/dist/tools/tool-runtime.js +29 -8
  44. package/dist/ui/layout-internal/content-write.js +7 -3
  45. package/dist/ui/layout-internal/core.js +1 -1
  46. package/dist/ui/layout-internal/state.js +0 -6
  47. package/dist/ui/layout-internal/statusbar.js +0 -30
  48. package/dist/ui/output-sink.js +24 -0
  49. package/dist/ui/spinner.js +3 -1
  50. package/package.json +4 -2
@@ -4,6 +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
8
  /**
8
9
  * grep 超时墙。
9
10
  *
@@ -18,6 +19,17 @@ const MAX_FILE_BYTES = 2 * 1024 * 1024;
18
19
  const MAX_BODY_LINE_CHARS = 400;
19
20
  /** context 参数上限:邻居行是 ×(1+2C) 放大,给到 10 已远超需要。 */
20
21
  const MAX_CONTEXT_LINES = 10;
22
+ const MAX_EDIT_CANDIDATES = 8;
23
+ function abortedResult(timedOut) {
24
+ if (!timedOut)
25
+ return '已中断';
26
+ return {
27
+ status: 'error',
28
+ code: 'TIMEOUT',
29
+ retryable: false,
30
+ output: `错误:grep 超过 ${GREP_TIMEOUT_MS / 1000}s 超时墙已被中止(收窄 glob 或确认无网络盘挂载后重试)`,
31
+ };
32
+ }
21
33
  function clipLine(line) {
22
34
  if (line.length <= MAX_BODY_LINE_CHARS)
23
35
  return line;
@@ -30,7 +42,7 @@ function clipLine(line) {
30
42
  * ` --` 不相邻分块之间的分隔
31
43
  * 原文不 trim:缩进是代码结构信息。
32
44
  */
33
- function renderFileBodies(file, maxPerFile) {
45
+ function renderFileBodies(file, maxPerFile, context) {
34
46
  const shown = file.matches.slice(0, maxPerFile);
35
47
  if (shown.length === 0)
36
48
  return [];
@@ -38,8 +50,12 @@ function renderFileBodies(file, maxPerFile) {
38
50
  const byLine = new Map();
39
51
  for (const e of shown)
40
52
  byLine.set(e.line, e);
41
- for (const e of file.contexts)
53
+ const lastContextLine = shown[shown.length - 1].line + context;
54
+ for (const e of file.contexts) {
55
+ if (e.line > lastContextLine)
56
+ break;
42
57
  byLine.set(e.line, e);
58
+ }
43
59
  const out = [];
44
60
  let previous = 0;
45
61
  for (const n of [...byLine.keys()].sort((a, b) => a - b)) {
@@ -53,28 +69,23 @@ function renderFileBodies(file, maxPerFile) {
53
69
  }
54
70
  /** 把聚合后的文件事件渲染成工具输出(配额/截断口径与旧实现一致)。 */
55
71
  function renderResults(files, maxPerFile, context, truncated) {
56
- const hits = [];
72
+ const out = [];
57
73
  let budgetTruncated = truncated;
74
+ let totalShown = 0;
58
75
  for (const file of files) {
59
76
  const bodyCost = Math.min(file.matches.length, maxPerFile) * (1 + 2 * context);
60
77
  const totalCost = file.matches.length + bodyCost;
61
- if (hits.length >= MAX_RESULTS || totalCost > MAX_RESULTS * 4) {
62
- if (hits.length < MAX_RESULTS)
63
- hits.push({ file, bodies: [] });
78
+ out.push(`${file.path}: ${file.matches.length} 处匹配,行号 [${file.matches.map((e) => e.line).join(', ')}]`);
79
+ totalShown += file.matches.length;
80
+ if (totalCost > MAX_RESULTS * 4) {
81
+ out.push(' (body 已折叠,见上方行号列表 → read_file 精读)');
64
82
  budgetTruncated = true;
65
- continue;
66
83
  }
67
- hits.push({ file, bodies: renderFileBodies(file, maxPerFile) });
68
- }
69
- const out = [];
70
- let totalShown = 0;
71
- for (const h of hits) {
72
- out.push(`${h.file.path}: ${h.file.matches.length} 处匹配,行号 [${h.file.matches.map((e) => e.line).join(', ')}]`);
73
- if (h.bodies.length > 0)
74
- out.push(...h.bodies);
75
- else
76
- out.push(' (body 已折叠,见上方行号列表 → read_file 精读)');
77
- totalShown += h.file.matches.length + h.bodies.length;
84
+ else {
85
+ const bodies = renderFileBodies(file, maxPerFile, context);
86
+ out.push(...bodies);
87
+ totalShown += bodies.length;
88
+ }
78
89
  if (totalShown >= MAX_RESULTS) {
79
90
  out.push(`...(结果达到 ${MAX_RESULTS} 条上限${context > 0 ? ',context 行同样计入;要更全就减小 context 或收窄 glob' : ''})`);
80
91
  break;
@@ -84,11 +95,44 @@ function renderResults(files, maxPerFile, context, truncated) {
84
95
  out.push('...(仍有更多匹配未展示,缩小 glob 或收窄正则)');
85
96
  return out.join('\n');
86
97
  }
98
+ function renderEditCandidates(files, truncated) {
99
+ const out = [];
100
+ for (const file of files) {
101
+ if (out.length === MAX_EDIT_CANDIDATES)
102
+ break;
103
+ for (const match of file.matches.slice(0, MAX_EDIT_CANDIDATES - out.length)) {
104
+ out.push(`${file.path}:${match.line}: ${clipLine(match.text)}`);
105
+ }
106
+ }
107
+ const omitted = truncated || files.reduce((total, file) => total + file.matches.length, 0) > out.length;
108
+ if (omitted)
109
+ out.push('...(还有更多候选)');
110
+ out.push('未提供编辑原文。请收窄搜索,或对选中的路径和行号使用 read_file。');
111
+ return out.join('\n');
112
+ }
113
+ async function renderEditContext(files, truncated, signal) {
114
+ const file = files[0];
115
+ if (!truncated && files.length === 1 && file.matches.length === 1) {
116
+ let absolutePath;
117
+ try {
118
+ absolutePath = jailResolve(file.path);
119
+ }
120
+ catch {
121
+ // 路径可能在搜索与读取之间变成越界链接。
122
+ }
123
+ if (absolutePath) {
124
+ const excerpt = await readSearchEditExcerpt(absolutePath, file.matches[0], signal);
125
+ if (excerpt)
126
+ return excerpt;
127
+ }
128
+ }
129
+ return renderEditCandidates(files, truncated);
130
+ }
87
131
  /**
88
132
  * Node 兜底:rg 二进制不可用(可选依赖缺失且 PATH 无 rg)时走旧路径。
89
133
  * 与旧实现的唯一差异——每两个文件之间检查 abort 信号,使 Ctrl+C / 超时墙能即时打断。
90
134
  */
91
- async function nodeFallback(pattern, glob, maxPerFile, context, signal, externalSignal) {
135
+ async function nodeFallback(pattern, glob, maxPerFile, editContext, signal, externalSignal) {
92
136
  let re;
93
137
  try {
94
138
  re = new RegExp(pattern);
@@ -152,7 +196,7 @@ async function nodeFallback(pattern, glob, maxPerFile, context, signal, external
152
196
  return `无匹配(扫描了 ${scanned} 个文件${note})`;
153
197
  }
154
198
  // 兜底路径无 context 事件来源(rg 缺失),context 参数退化为只给命中行。
155
- const out = renderResults(files, maxPerFile, 0, false);
199
+ const out = editContext ? renderEditCandidates(files, false) : renderResults(files, maxPerFile, 0, false);
156
200
  return skippedTooLarge ? `${out}\n...(跳过 ${skippedTooLarge} 个超过 2MiB 的文件)` : out;
157
201
  }
158
202
  // ---------- grep ----------
@@ -160,13 +204,17 @@ export const grepTool = {
160
204
  name: 'grep',
161
205
  description: 'Search file contents by regex (recursive; powered by ripgrep: respects .gitignore, skips binaries).\n' +
162
206
  'Output: per-file header "<path>: N matches, lines [l1, l2, ...]" plus rendered lines with ORIGINAL INDENTATION kept.\n' +
163
- 'Pass context=2..5 to include neighbouring lines inline (like ripgrep -C) instead of following each hit with a read_file round-trip. Hard wall 120s; narrow the glob if a tree contains network mounts. Use read_file when you need a whole region or exact edit text.\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' +
164
208
  '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/**".',
165
209
  parameters: {
166
210
  type: 'object',
167
211
  properties: {
168
212
  pattern: { type: 'string', description: 'Regular expression (ripgrep/Rust regex syntax)' },
169
213
  glob: { type: 'string', description: 'Optional, restrict to a file glob, e.g. *.ts' },
214
+ edit_context: {
215
+ type: 'boolean',
216
+ description: 'Return an exact edit excerpt for a unique match, or a short candidate list. Ignores context and max_per_file.',
217
+ },
170
218
  max_per_file: {
171
219
  type: 'integer',
172
220
  description: 'Max MATCHED lines rendered per file (default 15, cap 50); their context lines are extra. Line-number list is always full.',
@@ -182,6 +230,7 @@ export const grepTool = {
182
230
  async execute(args, ctx) {
183
231
  const pattern = String(args.pattern);
184
232
  const glob = String(args.glob ?? '**/*');
233
+ const editContext = args.edit_context === true;
185
234
  const maxPerFile = Math.min(Math.max(Number(args.max_per_file ?? 15), 1), 50);
186
235
  const contextRaw = Number(args.context ?? 0);
187
236
  const context = Number.isFinite(contextRaw) ? Math.min(Math.max(Math.trunc(contextRaw), 0), MAX_CONTEXT_LINES) : 0;
@@ -203,7 +252,13 @@ export const grepTool = {
203
252
  try {
204
253
  // glob 显式限定到 .mocode(gitignore 内)时放开 VCS ignore,否则 rg 零文件退出。
205
254
  const noIgnoreVcs = glob === '.mocode/**' || glob.startsWith('.mocode/');
206
- const result = await runRipgrep({ pattern, glob, context, noIgnoreVcs }, controller.signal);
255
+ const result = await runRipgrep({
256
+ pattern,
257
+ glob,
258
+ context: editContext ? 0 : context,
259
+ noIgnoreVcs,
260
+ maxMatches: editContext ? MAX_EDIT_CANDIDATES : MAX_RESULTS,
261
+ }, controller.signal);
207
262
  switch (result.status) {
208
263
  case 'regex_error':
209
264
  return `错误:非法正则 ${pattern}: ${result.message}`;
@@ -211,21 +266,16 @@ export const grepTool = {
211
266
  const trunc = result.truncated ? '\n...(输出截断,缩小 glob 或收窄正则后重试)' : '';
212
267
  return `无匹配(扫描了 ${result.scanned} 个文件)${trunc}`;
213
268
  }
214
- case 'ok':
215
- return renderResults(result.files, maxPerFile, context, result.truncated);
269
+ case 'ok': {
270
+ if (!editContext)
271
+ return renderResults(result.files, maxPerFile, context, result.truncated);
272
+ const output = await renderEditContext(result.files, result.truncated, controller.signal);
273
+ return controller.signal.aborted ? abortedResult(timedOut) : output;
274
+ }
216
275
  case 'unavailable':
217
- return nodeFallback(pattern, glob, maxPerFile, context, controller.signal, external);
276
+ return await nodeFallback(pattern, glob, maxPerFile, editContext, controller.signal, external);
218
277
  case 'aborted':
219
- if (timedOut) {
220
- return {
221
- status: 'error',
222
- code: 'TIMEOUT',
223
- retryable: false,
224
- output: `错误:grep 超过 ${GREP_TIMEOUT_MS / 1000}s 超时墙已被中止(收窄 glob 或确认无网络盘挂载后重试)`,
225
- };
226
- }
227
- // 外部 Ctrl+C:返回中断串,tool-runtime 见 signal.aborted 会归一为 aborted。
228
- return '已中断';
278
+ return abortedResult(timedOut);
229
279
  }
230
280
  }
231
281
  finally {
@@ -1,3 +1,4 @@
1
+ import { PLAN_USAGE_GUIDANCE } from '../../agent/work-discipline.js';
1
2
  import { PLAN_MAX_STEPS, readActivePlanTitle, renderPlanSection, writePlanToNotes, } from '../../session/notes.js';
2
3
  const VALID_STATUSES = ['pending', 'in_progress', 'completed'];
3
4
  function err(message) {
@@ -18,7 +19,8 @@ function normalizeStatus(raw) {
18
19
  }
19
20
  export const planUpdateTool = {
20
21
  name: 'plan_update',
21
- description: 'Record and update the session execution plan (the `## Plan:` block in notes.md). Use for any task with 3+ steps or context-loss risk. REPLACES the whole plan each call — always pass the full steps array. At most one step in_progress; mark a step completed as soon as its work is done, not batched to end of turn. Each step: short `title` (≤20 chars, shown in the status bar) + `content` self-contained enough to survive compaction (target file/symbol, change, verification). All steps completed → auto-settles to `## Done:`. Creates notes.md if missing. Safe in PLAN mode (writes only the session notepad).',
22
+ description: `Record and update the session execution plan in notes.md. ${PLAN_USAGE_GUIDANCE} ` +
23
+ 'REPLACES the whole plan each call — always pass the full steps array. At most one step in_progress; mark a step completed as soon as its work is done. Each step needs a short title (≤20 chars) and self-contained content. All steps completed → auto-settles to `## Done:`. Safe in PLAN mode (writes only the session notepad).',
22
24
  risk: 'safe',
23
25
  parameters: {
24
26
  type: 'object',
@@ -44,7 +46,7 @@ export const planUpdateTool = {
44
46
  },
45
47
  content: {
46
48
  type: 'string',
47
- description: 'Self-contained step: target file/symbol, the change, and how to verify it.',
49
+ description: 'Self-contained step: target file/symbol and the change. Add the check only when the step deserves one — small local edits need none.',
48
50
  },
49
51
  status: {
50
52
  type: 'string',
@@ -11,6 +11,7 @@ import { config, isMemoryEnabled } from '../../config/index.js';
11
11
  * 配合 description 中的 PAGINATION IS MANDATORY 引导。
12
12
  * 300 行 ≈ 一个屏幕的源码量,够定位一段逻辑而不至于吃光上下文。 */
13
13
  const DEFAULT_READ_LIMIT = 300;
14
+ const ANCHORED_READ_LIMIT = 80;
14
15
  /** 魔数嗅探只需文件头:16KB 足够覆盖 WebP(12 字节)/PNG(8)/GIF(6)/JPEG(SOF 位置不定)
15
16
  * 与二进制探测的 4KB 控制字符窗口。 */
16
17
  const SNIFF_BYTES = 16 * 1024;
@@ -36,21 +37,89 @@ function formatBytes(n) {
36
37
  function failure(code, message) {
37
38
  return { status: 'error', code, retryable: false, output: `错误:${message}` };
38
39
  }
40
+ async function loadReadableFile(path, signal) {
41
+ const absolute = resolve(path);
42
+ let info;
43
+ try {
44
+ info = await stat(absolute);
45
+ }
46
+ catch (error) {
47
+ const e = error;
48
+ if (e?.code === 'ENOENT')
49
+ return failure('EXECUTION_ERROR', `文件不存在: ${path}`);
50
+ return failure('EXECUTION_ERROR', `无法访问文件 ${path}: ${e?.message ?? String(error)}`);
51
+ }
52
+ if (info.isDirectory()) {
53
+ return failure('INVALID_ARGUMENTS', `${path} 是目录,不是文件。用 glob(pattern="${path}/**") 列目录内容,或用 grep 在目录下搜内容。`);
54
+ }
55
+ if (!info.isFile()) {
56
+ return failure('INVALID_ARGUMENTS', `${path} 不是普通文件(设备/套接字/特殊文件),无法读取。`);
57
+ }
58
+ if (info.size > MAX_FILE_BYTES) {
59
+ return failure('INVALID_ARGUMENTS', `${path} 有 ${formatBytes(info.size)},超过 read_file 的 ${formatBytes(MAX_FILE_BYTES)} 上限` +
60
+ '(行号分页需整文件载入内存)。先用 grep 定位行号,再用 run_command 配合系统工具按段取。');
61
+ }
62
+ try {
63
+ return { buffer: await readFile(absolute, { signal }), size: info.size };
64
+ }
65
+ catch (error) {
66
+ const e = error;
67
+ return failure(e?.code === 'EACCES' || e?.code === 'EPERM' ? 'SANDBOX_DENIED' : 'EXECUTION_ERROR', `读取 ${path} 失败: ${e?.message ?? String(error)}`);
68
+ }
69
+ }
70
+ function formatNumberedLines(lines, start, end) {
71
+ return lines
72
+ .slice(start, end)
73
+ .map((line, i) => `${String(start + i + 1).padStart(6, ' ')}\t${line}`)
74
+ .join('\n');
75
+ }
76
+ /** 只为已定位且已通过沙箱解析的命中返回未截断原文与同一份内容的版本。 */
77
+ export async function readSearchEditExcerpt(absolutePath, match, signal) {
78
+ const loaded = await loadReadableFile(absolutePath, signal);
79
+ if (!('buffer' in loaded) || signal.aborted)
80
+ return;
81
+ const { buffer } = loaded;
82
+ if (buffer.length > MAX_FILE_BYTES)
83
+ return;
84
+ const head = buffer.subarray(0, SNIFF_BYTES);
85
+ if (sniffImageMime(head) || isProbablyBinary(head))
86
+ return;
87
+ const data = buffer.toString('utf8');
88
+ if (!Buffer.from(data, 'utf8').equals(buffer))
89
+ 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}`;
100
+ }
39
101
  // ---------- read_file ----------
40
102
  export const readFileTool = {
41
103
  name: 'read_file',
42
104
  description: 'Read a file: text with line numbers, images as visual model input.\n' +
43
- 'Text — read before editing. For files >500 lines, grep first to locate, then read_file with offset+limit (e.g. offset=350, limit=120); never read a whole large file in one call. ' +
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. ' +
44
106
  'Images — PNG/JPEG/GIF/WebP detected by MAGIC BYTES (extension ignored), attached as visual input; detail=low|high controls resolution, oversized PNGs downscale automatically. ' +
45
107
  'Other binaries are REJECTED with an explanation — use run_command with a proper tool (`file`, `strings`, disassembler) if you need their content.',
46
108
  parameters: {
47
109
  type: 'object',
48
110
  properties: {
49
111
  path: { type: 'string', description: 'File path, relative to the working directory' },
50
- offset: { type: 'integer', description: 'Start line, 1-based (default 1). Text files only; ignored for images.' },
112
+ anchor: {
113
+ type: 'string',
114
+ description: 'Start the text read at the first line containing this exact, case-sensitive literal (e.g. "function parseConfig("). With offset, search from that line. Ignored for images.',
115
+ },
116
+ offset: {
117
+ type: 'integer',
118
+ description: 'First line to read or search for anchor, 1-based (default 1). Text only.',
119
+ },
51
120
  limit: {
52
121
  type: 'integer',
53
- description: 'Max lines to read (default 300, hard cap 2000). Size by OUTPUT, not lines: outputs are capped at ~32k chars per call, so a dense (CJK) file fits ~200-400 lines in one call while sparse code fits 1000+. If a range exceeds that, split it; the output tail always reports how many lines remain. Text only; ignored for images.',
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.',
54
123
  },
55
124
  detail: {
56
125
  type: 'string',
@@ -63,40 +132,15 @@ export const readFileTool = {
63
132
  async execute(args, toolCtx) {
64
133
  const path = String(args.path);
65
134
  const offset = Number(args.offset ?? 1);
135
+ const anchor = args.anchor;
66
136
  // 无论 LLM 传多大,单次硬钳到 MAX_FILE_LINES,杜绝「绕过分页引导一把全拿」。
67
- const limit = Math.min(Number(args.limit ?? DEFAULT_READ_LIMIT), MAX_FILE_LINES);
137
+ const limit = Math.min(Number(args.limit ?? (anchor === undefined ? DEFAULT_READ_LIMIT : ANCHORED_READ_LIMIT)), MAX_FILE_LINES);
68
138
  // enforceSandbox 已把 args.path 重写为牢内绝对路径(sandbox/policy.ts SANDBOX_PATH_TOOLS),
69
139
  // resolve 对绝对路径原样返回。
70
- const absolute = resolve(path);
71
- // ── 1. stat:目录 / 不存在 / 超大文件在这里分流,不把字节读进来再说 ────────
72
- let info;
73
- try {
74
- info = await stat(absolute);
75
- }
76
- catch (error) {
77
- const e = error;
78
- if (e?.code === 'ENOENT')
79
- return failure('EXECUTION_ERROR', `文件不存在: ${path}`);
80
- return failure('EXECUTION_ERROR', `无法访问文件 ${path}: ${e?.message ?? String(error)}`);
81
- }
82
- if (info.isDirectory()) {
83
- return failure('INVALID_ARGUMENTS', `${path} 是目录,不是文件。用 glob(pattern="${path}/**") 列目录内容,或用 grep 在目录下搜内容。`);
84
- }
85
- if (!info.isFile()) {
86
- return failure('INVALID_ARGUMENTS', `${path} 不是普通文件(设备/套接字/特殊文件),无法读取。`);
87
- }
88
- if (info.size > MAX_FILE_BYTES) {
89
- return failure('INVALID_ARGUMENTS', `${path} 有 ${formatBytes(info.size)},超过 read_file 的 ${formatBytes(MAX_FILE_BYTES)} 上限` +
90
- '(行号分页需整文件载入内存)。先用 grep 定位行号,再用 run_command 配合系统工具按段取。');
91
- }
92
- let buffer;
93
- try {
94
- buffer = await readFile(absolute);
95
- }
96
- catch (error) {
97
- const e = error;
98
- return failure(e?.code === 'EACCES' || e?.code === 'EPERM' ? 'SANDBOX_DENIED' : 'EXECUTION_ERROR', `读取 ${path} 失败: ${e?.message ?? String(error)}`);
99
- }
140
+ const loaded = await loadReadableFile(path);
141
+ if (!('buffer' in loaded))
142
+ return loaded;
143
+ const { buffer, size } = loaded;
100
144
  // ── 2. 魔数嗅探:图片走视觉通道,其余二进制明确拒绝 ──────────────────────
101
145
  // 为什么必须嗅探而不看扩展名:扩展名会说谎(截图缓存 / 构建产物常无扩展名或错扩展名),
102
146
  // 而把二进制当 UTF-8 解码的代价是实测一张 42KB PNG 产出 17862 个 U+FFFD(占 45%),
@@ -104,7 +148,7 @@ export const readFileTool = {
104
148
  const head = buffer.subarray(0, SNIFF_BYTES);
105
149
  const sniffed = sniffImageMime(head);
106
150
  if (sniffed)
107
- return await readAsImage(path, sniffed, args.detail, info.size);
151
+ return await readAsImage(path, sniffed, args.detail, size);
108
152
  if (isProbablyBinary(head)) {
109
153
  return failure('INVALID_ARGUMENTS', `${path} 是二进制文件(头部含控制字符),不能按文本读取 —— 强行解码只会得到乱码。` +
110
154
  '若它其实是图片,支持的格式为 png/jpg/jpeg/gif/webp;否则用 run_command 配合专用工具' +
@@ -114,14 +158,22 @@ export const readFileTool = {
114
158
  // hash 仍取「UTF-8 解码后字符串」的摘要(与改动前逐字节一致):会话里已持久化的
115
159
  // expected_hash 与 context/artifacts 的 parseReadHash 都依赖这个口径,不能顺手换。
116
160
  const data = buffer.toString('utf8');
117
- const artifactHeader = `[artifact source=read_file path=${path} hash=${contentHash(data)}]`;
118
161
  const lines = data.split(/\r?\n/);
119
- const start = Math.max(0, offset - 1);
162
+ let start = Math.max(0, offset - 1);
163
+ if (anchor !== undefined) {
164
+ if (typeof anchor !== 'string' || !anchor.length || /[\r\n]/.test(anchor)) {
165
+ return failure('INVALID_ARGUMENTS', 'anchor 需要单行非空原文。');
166
+ }
167
+ while (start < lines.length && !lines[start].includes(anchor))
168
+ start++;
169
+ if (start >= lines.length) {
170
+ return failure('EXECUTION_ERROR', `${path} 从第 ${Math.max(1, offset)} 行起未找到 anchor。请缩短原文片段或用 grep 搜索。`);
171
+ }
172
+ }
173
+ const fileHash = contentHash(data);
174
+ const artifactHeader = `[artifact source=read_file path=${path} hash=${fileHash}]`;
120
175
  const end = Math.min(lines.length, start + limit);
121
- const body = lines
122
- .slice(start, end)
123
- .map((l, i) => `${String(start + i + 1).padStart(6, ' ')}\t${l}`)
124
- .join('\n');
176
+ const body = formatNumberedLines(lines, start, end);
125
177
  // 空文件(0 字节)显式报「(空文件)」:''.split 得到 [''],行号分页会渲染成 ` 1\t`,
126
178
  // 让模型误以为读到了带一行空白的文件。data.length===0 才是真·空的判据。
127
179
  if (data.length === 0)
@@ -131,7 +183,7 @@ export const readFileTool = {
131
183
  const reqEnd = end;
132
184
  const dedup = toolCtx?.readDedup;
133
185
  if (config.readDedup && dedup) {
134
- const hit = dedup.findUnchanged(path, reqStart, reqEnd, contentHash(data));
186
+ const hit = dedup.findUnchanged(path, reqStart, reqEnd, fileHash);
135
187
  if (hit) {
136
188
  return {
137
189
  status: 'success',
@@ -158,13 +210,12 @@ export const readFileTool = {
158
210
  // 用 output(含回注段)判长度:最终进 history 的就是它,回注把长度顶过 cap 时
159
211
  // 必须按截断口径登记,否则会记成"完整保留"而制造幽灵命中。
160
212
  if (dedup && config.readDedup && output.length > MAX_HISTORY_RESULT) {
161
- const fileHash = contentHash(data);
162
213
  const truncated = truncatedOutputRanges(lines, start, end, output.length, MAX_HISTORY_RESULT);
163
214
  for (const r of truncated)
164
215
  dedup.record(path, r.start, r.end, fileHash);
165
216
  }
166
217
  else {
167
- dedup?.record(path, reqStart, reqEnd, contentHash(data));
218
+ dedup?.record(path, reqStart, reqEnd, fileHash);
168
219
  }
169
220
  return { status: 'success', code: 'OK', retryable: false, output };
170
221
  },
@@ -1,4 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { TextDecoder } from 'node:util';
2
3
  import { MAX_OUTPUT } from '../constants.js';
3
4
  import { getSandboxRoot, filterEnv, isCommandDenied, jailResolve } from '../../sandbox/index.js';
4
5
  import { t } from '../../i18n/index.js';
@@ -24,6 +25,22 @@ export function clampCommandTimeout(raw) {
24
25
  return DEFAULT_COMMAND_TIMEOUT_MS;
25
26
  return Math.min(Math.max(Math.trunc(value), MIN_COMMAND_TIMEOUT_MS), MAX_COMMAND_TIMEOUT_MS);
26
27
  }
28
+ /** 无编码标记的二进制或混合输出仍可包含诊断,只追加提示,保留正文。 */
29
+ function hasEncodingHint(text) {
30
+ const sample = text.slice(0, 4000);
31
+ if (!sample)
32
+ return false;
33
+ let nul = 0;
34
+ let replacement = 0;
35
+ for (let i = 0; i < sample.length; i++) {
36
+ const code = sample.charCodeAt(i);
37
+ if (code === 0)
38
+ nul++;
39
+ else if (code === 0xfffd)
40
+ replacement++;
41
+ }
42
+ return nul / sample.length > 0.1 || replacement / sample.length > 0.05;
43
+ }
27
44
  /** 有界采集:短输出逐字保留;超限后保留 head+tail,避免构建/测试错误只出现在尾部时被丢弃。 */
28
45
  class BoundedCommandOutput {
29
46
  head = '';
@@ -39,12 +56,44 @@ class BoundedCommandOutput {
39
56
  this.tail = (this.tail + rest).slice(-OUTPUT_TAIL_LIMIT);
40
57
  }
41
58
  render() {
42
- if (this.total <= MAX_OUTPUT)
43
- return this.head + this.tail;
44
- const removed = this.total - MAX_OUTPUT;
45
- return `${this.head}\n${t('command.outputTruncated', { count: removed })}\n${this.tail}`;
59
+ const body = this.total <= MAX_OUTPUT
60
+ ? this.head + this.tail
61
+ : `${this.head}\n${t('command.outputTruncated', { count: this.total - MAX_OUTPUT })}\n${this.tail}`;
62
+ return hasEncodingHint(body) ? `${body}\n${t('command.encodingHint')}` : body;
46
63
  }
47
64
  }
65
+ /** 每个管道自行识别 BOM,跨 chunk 保留不完整的字符。 */
66
+ function readCommandStream(stream, append) {
67
+ let decoder;
68
+ let prefix;
69
+ stream.on('data', (chunk) => {
70
+ if (!chunk.length)
71
+ return;
72
+ if (!decoder) {
73
+ if (prefix)
74
+ chunk = Buffer.concat([prefix, chunk]);
75
+ if (chunk.length === 1 && (chunk[0] === 0xff || chunk[0] === 0xfe)) {
76
+ prefix = chunk;
77
+ return;
78
+ }
79
+ prefix = undefined;
80
+ let encoding = 'utf-8';
81
+ if (chunk[0] === 0xff && chunk[1] === 0xfe)
82
+ encoding = 'utf-16le';
83
+ if (chunk[0] === 0xfe && chunk[1] === 0xff)
84
+ encoding = 'utf-16be';
85
+ decoder = new TextDecoder(encoding);
86
+ }
87
+ const text = decoder.decode(chunk, { stream: true });
88
+ if (text)
89
+ append(text);
90
+ });
91
+ stream.on('end', () => {
92
+ const tail = (decoder ?? new TextDecoder()).decode(prefix);
93
+ if (tail)
94
+ append(tail);
95
+ });
96
+ }
48
97
  /** Execute a command with the same sandbox, output cap and cancellation semantics as run_command. */
49
98
  export async function runCommandRaw(command, timeout = DEFAULT_COMMAND_TIMEOUT_MS, signal, cwd, shell, onOutput) {
50
99
  const startedAt = Date.now();
@@ -124,8 +173,7 @@ export async function runCommandRaw(command, timeout = DEFAULT_COMMAND_TIMEOUT_M
124
173
  const onAbort = () => {
125
174
  terminate('aborted');
126
175
  };
127
- const onChunk = (chunk) => {
128
- const text = chunk.toString('utf8');
176
+ const onText = (text) => {
129
177
  output.append(text);
130
178
  try {
131
179
  onOutput?.(text);
@@ -139,8 +187,8 @@ export async function runCommandRaw(command, timeout = DEFAULT_COMMAND_TIMEOUT_M
139
187
  const timer = setTimeout(() => {
140
188
  terminate('timed_out');
141
189
  }, effectiveTimeout);
142
- child.stdout.on('data', onChunk);
143
- child.stderr.on('data', onChunk);
190
+ readCommandStream(child.stdout, onText);
191
+ readCommandStream(child.stderr, onText);
144
192
  child.on('error', (error) => {
145
193
  if (!pendingTermination)
146
194
  finish({ status: 'spawn_error', exitCode: null, output: error.message });
@@ -198,7 +246,7 @@ export const runCommandTool = {
198
246
  name: 'run_command',
199
247
  description: 'Run a FOREGROUND shell command, merging stdout+stderr. Default timeout 120s, hard cap 10min; pass shell=cmd|powershell|bash to pick the interpreter (platform default and MOCODE_SHELL override are stated in the system prompt). Non-interactive cmd cannot run `timeout /t` — use shell=powershell (`Start-Sleep`) or shell=bash (`sleep`) for waits.\n' +
200
248
  'Anything that must keep running after this call returns — dev server, model service, watcher, log tail — belongs to dev_server (survives across calls; gives an id for incremental logs and process-tree kill). Do NOT detach via `start /b`, `nohup`, `&`: you lose both the logs and the handle.\n' +
201
- "Multiple independent calls may be issued in one response (they run serially, in order); do not depend one on another's output within the same message.",
249
+ 'Calls run serially and each captures workspace changes. For related verification checks with the same setup, prefer one bounded command that reports a result per check, e.g. one loop for a batch of read-only API probes. Use grep, glob and read_file for source lookup. Independent commands that need separate execution may share a tool-call response.',
202
250
  risk: 'dangerous',
203
251
  parameters: {
204
252
  type: 'object',
@@ -92,6 +92,7 @@ export function runRipgrep(params, signal) {
92
92
  let buffer = '';
93
93
  const byPath = new Map();
94
94
  let scanned = 0;
95
+ let completeMatches = 0;
95
96
  const finish = (result) => {
96
97
  if (settled)
97
98
  return;
@@ -103,6 +104,11 @@ export function runRipgrep(params, signal) {
103
104
  killTree(child);
104
105
  finish({ status: 'aborted' });
105
106
  };
107
+ const stopCollecting = () => {
108
+ truncated = true;
109
+ buffer = '';
110
+ killTree(child);
111
+ };
106
112
  const handleLine = (line) => {
107
113
  let evt;
108
114
  try {
@@ -114,22 +120,36 @@ export function runRipgrep(params, signal) {
114
120
  const data = evt.data;
115
121
  if (!data)
116
122
  return;
123
+ if (evt.type === 'summary') {
124
+ // end 事件只来自命中文件;零命中时由 summary 区分「搜过」和「没有文件可搜」。
125
+ const searches = data.stats?.searches;
126
+ if (typeof searches === 'number')
127
+ scanned = searches;
128
+ return;
129
+ }
130
+ const pathText = data.path?.text;
131
+ if (typeof pathText !== 'string')
132
+ return;
117
133
  if (evt.type === 'end') {
118
134
  scanned++;
135
+ completeMatches += byPath.get(normalizePath(pathText))?.matches.length ?? 0;
119
136
  return;
120
137
  }
121
138
  if (evt.type !== 'match' && evt.type !== 'context')
122
139
  return;
123
- const pathText = data.path?.text;
124
140
  const lineNo = data.line_number;
125
141
  const linesText = data.lines?.text;
126
- if (typeof pathText !== 'string' || typeof lineNo !== 'number' || typeof linesText !== 'string')
142
+ if (typeof lineNo !== 'number' || typeof linesText !== 'string')
127
143
  return;
128
144
  const path = normalizePath(pathText);
129
- if (!isInsideRoot(path))
130
- return; // 后置兜底:仅留牢内
131
145
  let bucket = byPath.get(path);
132
146
  if (!bucket) {
147
+ if (!isInsideRoot(path))
148
+ return;
149
+ if (params.maxMatches !== undefined && completeMatches >= params.maxMatches) {
150
+ stopCollecting();
151
+ return;
152
+ }
133
153
  bucket = { path, matches: [], contexts: [] };
134
154
  byPath.set(path, bucket);
135
155
  }
@@ -139,16 +159,16 @@ export function runRipgrep(params, signal) {
139
159
  else
140
160
  bucket.contexts.push(event);
141
161
  };
162
+ child.stdout.setEncoding('utf8');
142
163
  child.stdout.on('data', (chunk) => {
143
- if (settled)
164
+ if (settled || truncated)
144
165
  return;
145
- collected += chunk.length;
146
- if (collected > MAX_JSON_BYTES && !truncated) {
147
- truncated = true;
148
- killTree(child); // 输出已超预算,没必要继续
166
+ collected += Buffer.byteLength(chunk);
167
+ if (collected > MAX_JSON_BYTES) {
168
+ stopCollecting();
149
169
  return;
150
170
  }
151
- buffer += chunk.toString('utf8');
171
+ buffer += chunk;
152
172
  let idx;
153
173
  while ((idx = buffer.indexOf('\n')) >= 0) {
154
174
  const line = buffer.slice(0, idx);
@@ -186,7 +206,7 @@ export function runRipgrep(params, signal) {
186
206
  finish({ status: 'no-match', scanned, truncated });
187
207
  return;
188
208
  }
189
- finish({ status: 'ok', files: [...byPath.values()], scanned, truncated });
209
+ finish({ status: 'ok', files: [...byPath.values()], scanned, truncated: truncated || code !== 0 });
190
210
  });
191
211
  if (signal) {
192
212
  if (signal.aborted)