mocode-ai 1.10.0 → 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.
Files changed (59) hide show
  1. package/dist/agent/index.js +18 -7
  2. package/dist/agent/mentioned-files.js +71 -0
  3. package/dist/agent/model-turn.js +68 -30
  4. package/dist/agent/progress-guard.js +67 -0
  5. package/dist/agent/run-coordinator.js +155 -24
  6. package/dist/agent/short-path-completion.js +109 -0
  7. package/dist/agent/spawn.js +43 -0
  8. package/dist/agent/stages/history-manager.js +1 -0
  9. package/dist/agent/stages/tool-dispatcher.js +6 -3
  10. package/dist/agent/tool-helpers.js +2 -2
  11. package/dist/agent/tool-turn.js +49 -4
  12. package/dist/agent/work-discipline.js +12 -9
  13. package/dist/changeset/index.js +2 -1
  14. package/dist/config/index.js +12 -10
  15. package/dist/context/overlapping-reads.js +66 -0
  16. package/dist/context/relevance.js +11 -2
  17. package/dist/context/usage-snapshot.js +9 -6
  18. package/dist/host/stdio.js +96 -42
  19. package/dist/i18n/index.js +26 -10
  20. package/dist/llm/index.js +27 -3
  21. package/dist/llm/message-shape.js +18 -0
  22. package/dist/llm/reasoning.js +17 -0
  23. package/dist/memory/index.js +1 -1
  24. package/dist/memory/tail.js +9 -26
  25. package/dist/models/reasoning-cap.js +19 -2
  26. package/dist/orchestrator/lane-executor.js +7 -1
  27. package/dist/orchestrator/repl.js +30 -49
  28. package/dist/repl/commands/appearance.js +1 -2
  29. package/dist/repl/commands/compact.js +4 -0
  30. package/dist/repl/commands/model-actions.js +4 -3
  31. package/dist/repl/commands/model.js +2 -3
  32. package/dist/repl/message-format.js +7 -6
  33. package/dist/repl/running-input.js +27 -65
  34. package/dist/repl/runtime.js +119 -77
  35. package/dist/rollback/index.js +2 -2
  36. package/dist/rollback/store.js +73 -38
  37. package/dist/runtime/runtime.js +1 -1
  38. package/dist/session/compact.js +41 -4
  39. package/dist/session/retention.js +4 -0
  40. package/dist/session/short-path-metrics.js +185 -0
  41. package/dist/session/store.js +78 -3
  42. package/dist/session/terminal-transcript.js +101 -0
  43. package/dist/tools/builtins/ask-human.js +2 -2
  44. package/dist/tools/builtins/edit-file.js +79 -19
  45. package/dist/tools/builtins/grep.js +161 -42
  46. package/dist/tools/builtins/plan-update.js +4 -2
  47. package/dist/tools/builtins/read-file.js +148 -55
  48. package/dist/tools/builtins/run-command.js +57 -9
  49. package/dist/tools/ripgrep-client.js +72 -26
  50. package/dist/tools/tool-runtime.js +29 -8
  51. package/dist/ui/layout-internal/content-write.js +7 -3
  52. package/dist/ui/layout-internal/core.js +1 -1
  53. package/dist/ui/layout-internal/state.js +0 -6
  54. package/dist/ui/layout-internal/statusbar.js +0 -30
  55. package/dist/ui/output-sink.js +24 -0
  56. package/dist/ui/render.js +3 -0
  57. package/dist/ui/spinner.js +3 -1
  58. package/dist/verification/evidence.js +52 -0
  59. package/package.json +4 -2
@@ -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';
@@ -11,6 +12,7 @@ import { config, isMemoryEnabled } from '../../config/index.js';
11
12
  * 配合 description 中的 PAGINATION IS MANDATORY 引导。
12
13
  * 300 行 ≈ 一个屏幕的源码量,够定位一段逻辑而不至于吃光上下文。 */
13
14
  const DEFAULT_READ_LIMIT = 300;
15
+ const ANCHORED_READ_LIMIT = 80;
14
16
  /** 魔数嗅探只需文件头:16KB 足够覆盖 WebP(12 字节)/PNG(8)/GIF(6)/JPEG(SOF 位置不定)
15
17
  * 与二进制探测的 4KB 控制字符窗口。 */
16
18
  const SNIFF_BYTES = 16 * 1024;
@@ -36,21 +38,138 @@ function formatBytes(n) {
36
38
  function failure(code, message) {
37
39
  return { status: 'error', code, retryable: false, output: `错误:${message}` };
38
40
  }
41
+ async function loadReadableFile(path, signal) {
42
+ const absolute = resolve(path);
43
+ let info;
44
+ try {
45
+ info = await stat(absolute);
46
+ }
47
+ catch (error) {
48
+ const e = error;
49
+ if (e?.code === 'ENOENT')
50
+ return failure('EXECUTION_ERROR', `文件不存在: ${path}`);
51
+ return failure('EXECUTION_ERROR', `无法访问文件 ${path}: ${e?.message ?? String(error)}`);
52
+ }
53
+ if (info.isDirectory()) {
54
+ return failure('INVALID_ARGUMENTS', `${path} 是目录,不是文件。用 glob(pattern="${path}/**") 列目录内容,或用 grep 在目录下搜内容。`);
55
+ }
56
+ if (!info.isFile()) {
57
+ return failure('INVALID_ARGUMENTS', `${path} 不是普通文件(设备/套接字/特殊文件),无法读取。`);
58
+ }
59
+ if (info.size > MAX_FILE_BYTES) {
60
+ return failure('INVALID_ARGUMENTS', `${path} 有 ${formatBytes(info.size)},超过 read_file 的 ${formatBytes(MAX_FILE_BYTES)} 上限` +
61
+ '(行号分页需整文件载入内存)。先用 grep 定位行号,再用 run_command 配合系统工具按段取。');
62
+ }
63
+ try {
64
+ return { buffer: await readFile(absolute, { signal }), size: info.size };
65
+ }
66
+ catch (error) {
67
+ const e = error;
68
+ return failure(e?.code === 'EACCES' || e?.code === 'EPERM' ? 'SANDBOX_DENIED' : 'EXECUTION_ERROR', `读取 ${path} 失败: ${e?.message ?? String(error)}`);
69
+ }
70
+ }
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) {
104
+ return lines
105
+ .slice(start, end)
106
+ .map((line, i) => `${String(start + i + 1).padStart(6, ' ')}\t${line}`)
107
+ .join('\n');
108
+ }
109
+ /** 只为已定位且已通过沙箱解析的命中返回未截断原文与同一份内容的版本。 */
110
+ export async function readSearchEditExcerpts(absolutePath, matches, signal) {
111
+ const loaded = await loadReadableFile(absolutePath, signal);
112
+ if (!('buffer' in loaded) || signal.aborted)
113
+ return;
114
+ const { buffer } = loaded;
115
+ if (buffer.length > MAX_FILE_BYTES)
116
+ return;
117
+ const head = buffer.subarray(0, SNIFF_BYTES);
118
+ if (sniffImageMime(head) || isProbablyBinary(head))
119
+ return;
120
+ const data = buffer.toString('utf8');
121
+ if (!Buffer.from(data, 'utf8').equals(buffer))
122
+ return;
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');
150
+ }
39
151
  // ---------- read_file ----------
40
152
  export const readFileTool = {
41
153
  name: 'read_file',
42
154
  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. ' +
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. ' +
44
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. ' +
45
157
  'Other binaries are REJECTED with an explanation — use run_command with a proper tool (`file`, `strings`, disassembler) if you need their content.',
46
158
  parameters: {
47
159
  type: 'object',
48
160
  properties: {
49
161
  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.' },
162
+ anchor: {
163
+ type: 'string',
164
+ 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.',
165
+ },
166
+ offset: {
167
+ type: 'integer',
168
+ description: 'First line to read or search for anchor, 1-based (default 1). Text only.',
169
+ },
51
170
  limit: {
52
171
  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.',
172
+ description: 'Max text lines (default 80 with anchor, otherwise 300; hard cap 2000). Match the limit to the code needed. Text only.',
54
173
  },
55
174
  detail: {
56
175
  type: 'string',
@@ -63,49 +182,17 @@ export const readFileTool = {
63
182
  async execute(args, toolCtx) {
64
183
  const path = String(args.path);
65
184
  const offset = Number(args.offset ?? 1);
185
+ const anchor = args.anchor;
66
186
  // 无论 LLM 传多大,单次硬钳到 MAX_FILE_LINES,杜绝「绕过分页引导一把全拿」。
67
- const limit = Math.min(Number(args.limit ?? DEFAULT_READ_LIMIT), MAX_FILE_LINES);
187
+ const limit = Math.min(Number(args.limit ?? (anchor === undefined ? DEFAULT_READ_LIMIT : ANCHORED_READ_LIMIT)), MAX_FILE_LINES);
68
188
  // enforceSandbox 已把 args.path 重写为牢内绝对路径(sandbox/policy.ts SANDBOX_PATH_TOOLS),
69
189
  // 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
- }
100
- // ── 2. 魔数嗅探:图片走视觉通道,其余二进制明确拒绝 ──────────────────────
101
- // 为什么必须嗅探而不看扩展名:扩展名会说谎(截图缓存 / 构建产物常无扩展名或错扩展名),
102
- // 而把二进制当 UTF-8 解码的代价是实测一张 42KB PNG 产出 17862 个 U+FFFD(占 45%),
103
- // 经 history 上限中截后仍有数千字符纯乱码进上下文 —— 既烧 token 又误导模型。
104
- const head = buffer.subarray(0, SNIFF_BYTES);
105
- const sniffed = sniffImageMime(head);
106
- if (sniffed)
107
- return await readAsImage(path, sniffed, args.detail, info.size);
108
- 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') {
109
196
  return failure('INVALID_ARGUMENTS', `${path} 是二进制文件(头部含控制字符),不能按文本读取 —— 强行解码只会得到乱码。` +
110
197
  '若它其实是图片,支持的格式为 png/jpg/jpeg/gif/webp;否则用 run_command 配合专用工具' +
111
198
  '(如 file / strings / 反汇编器)查看。');
@@ -113,15 +200,22 @@ export const readFileTool = {
113
200
  // ── 3. 文本:沿用既有 artifact header + 行号分页 ────────────────────────
114
201
  // hash 仍取「UTF-8 解码后字符串」的摘要(与改动前逐字节一致):会话里已持久化的
115
202
  // expected_hash 与 context/artifacts 的 parseReadHash 都依赖这个口径,不能顺手换。
116
- const data = buffer.toString('utf8');
117
- const artifactHeader = `[artifact source=read_file path=${path} hash=${contentHash(data)}]`;
118
- const lines = data.split(/\r?\n/);
119
- const start = Math.max(0, offset - 1);
203
+ const { data, lines } = snapshot;
204
+ let start = Math.max(0, offset - 1);
205
+ if (anchor !== undefined) {
206
+ if (typeof anchor !== 'string' || !anchor.length || /[\r\n]/.test(anchor)) {
207
+ return failure('INVALID_ARGUMENTS', 'anchor 需要单行非空原文。');
208
+ }
209
+ while (start < lines.length && !lines[start].includes(anchor))
210
+ start++;
211
+ if (start >= lines.length) {
212
+ return failure('EXECUTION_ERROR', `${path} 从第 ${Math.max(1, offset)} 行起未找到 anchor。请缩短原文片段或用 grep 搜索。`);
213
+ }
214
+ }
215
+ const fileHash = (snapshot.hash ??= contentHash(data));
216
+ const artifactHeader = `[artifact source=read_file path=${path} hash=${fileHash}]`;
120
217
  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');
218
+ const body = formatNumberedLines(lines, start, end);
125
219
  // 空文件(0 字节)显式报「(空文件)」:''.split 得到 [''],行号分页会渲染成 ` 1\t`,
126
220
  // 让模型误以为读到了带一行空白的文件。data.length===0 才是真·空的判据。
127
221
  if (data.length === 0)
@@ -131,7 +225,7 @@ export const readFileTool = {
131
225
  const reqEnd = end;
132
226
  const dedup = toolCtx?.readDedup;
133
227
  if (config.readDedup && dedup) {
134
- const hit = dedup.findUnchanged(path, reqStart, reqEnd, contentHash(data));
228
+ const hit = dedup.findUnchanged(path, reqStart, reqEnd, fileHash);
135
229
  if (hit) {
136
230
  return {
137
231
  status: 'success',
@@ -143,7 +237,7 @@ export const readFileTool = {
143
237
  }
144
238
  }
145
239
  const baseOutput = end < lines.length
146
- ? `${artifactHeader}\n${body}\n\n... (${lines.length - end} 行未显示,共 ${lines.length} 行)`
240
+ ? `${artifactHeader}\n${body}\n\n... (${lines.length - end} 行未显示,共 ${lines.length} 行,续读 offset=${end + 1})`
147
241
  : `${artifactHeader}\n${body}`;
148
242
  // R2.4:回注锚定本文件的记忆(最多 3 条,只回 fresh)。
149
243
  // 为什么放在 read_file 而不是 system prompt:prompt 每轮注入会撞 cache,而且
@@ -158,13 +252,12 @@ export const readFileTool = {
158
252
  // 用 output(含回注段)判长度:最终进 history 的就是它,回注把长度顶过 cap 时
159
253
  // 必须按截断口径登记,否则会记成"完整保留"而制造幽灵命中。
160
254
  if (dedup && config.readDedup && output.length > MAX_HISTORY_RESULT) {
161
- const fileHash = contentHash(data);
162
255
  const truncated = truncatedOutputRanges(lines, start, end, output.length, MAX_HISTORY_RESULT);
163
256
  for (const r of truncated)
164
257
  dedup.record(path, r.start, r.end, fileHash);
165
258
  }
166
259
  else {
167
- dedup?.record(path, reqStart, reqEnd, contentHash(data));
260
+ dedup?.record(path, reqStart, reqEnd, fileHash);
168
261
  }
169
262
  return { status: 'success', code: 'OK', retryable: false, output };
170
263
  },
@@ -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',
@@ -11,8 +11,8 @@ import { IGNORE } from './constants.js';
11
11
  import { getSandboxRoot, isInsideRoot } from '../sandbox/index.js';
12
12
  const require = createRequire(import.meta.url);
13
13
  const isWin = process.platform === 'win32';
14
- /** JSON 采集上限:约可容纳数万条命中,超出即杀进程并标 truncated。 */
15
- const MAX_JSON_BYTES = 8 * 1024 * 1024;
14
+ /** stdout 采集上限,超出即杀进程并标 truncated。 */
15
+ const MAX_RG_OUTPUT_BYTES = 8 * 1024 * 1024;
16
16
  /**
17
17
  * 定位 rg 可执行文件:MOCODE_RG_PATH 显式覆盖 → @vscode/ripgrep 随包二进制 → PATH 上的 rg。
18
18
  * 返 null = 三条路都没有,调用方应退 Node 兜底。
@@ -58,21 +58,31 @@ function normalizePath(p) {
58
58
  return p.replace(/^\.[\\/]/, '').replace(/\\/g, '/');
59
59
  }
60
60
  /**
61
- * 跑一次 ripgrep(--json NDJSON),聚合成每文件事件。永不抛错:
61
+ * 跑一次 ripgrep,收集每文件的行事件或 NUL 分隔的命中文件路径。
62
62
  * 进程起不来 → unavailable;非法正则 → regex_error;signal 中止 → aborted。
63
63
  */
64
64
  export function runRipgrep(params, signal) {
65
- const rgPath = resolveRgPath();
66
- if (!rgPath || signal?.aborted)
65
+ if (signal?.aborted)
67
66
  return Promise.resolve({ status: 'aborted' });
67
+ const rgPath = resolveRgPath();
68
+ if (!rgPath)
69
+ return Promise.resolve({ status: 'unavailable' });
68
70
  const cwd = getSandboxRoot() ?? process.cwd();
71
+ const maxFiles = params.maxFiles;
72
+ const pathsOnly = maxFiles !== undefined;
69
73
  // --no-require-git:rg 默认只在 git 仓库内才读 .gitignore;加上后非 git 项目的 .gitignore
70
74
  // 同样生效(实测不加时 ignored/ 会被扫到)。
71
- const args = ['--json', '--hidden', '--no-require-git', '--path-separator', '/'];
75
+ const args = [
76
+ ...(pathsOnly ? ['--no-json', '--files-with-matches', '--null', '--color', 'never'] : ['--json']),
77
+ '--hidden',
78
+ '--no-require-git',
79
+ '--path-separator',
80
+ '/',
81
+ ];
72
82
  // glob 显式指向 gitignore 内的 .mocode(回捞压缩归档等)时放开 VCS ignore。
73
83
  if (params.noIgnoreVcs)
74
84
  args.push('--no-ignore-vcs');
75
- if (params.context > 0)
85
+ if (!pathsOnly && params.context > 0)
76
86
  args.push('-C', String(params.context));
77
87
  if (params.glob && params.glob !== '**/*')
78
88
  args.push('-g', params.glob);
@@ -91,7 +101,9 @@ export function runRipgrep(params, signal) {
91
101
  let stderr = '';
92
102
  let buffer = '';
93
103
  const byPath = new Map();
104
+ const matchedPaths = new Set();
94
105
  let scanned = 0;
106
+ let completeMatches = 0;
95
107
  const finish = (result) => {
96
108
  if (settled)
97
109
  return;
@@ -103,7 +115,22 @@ export function runRipgrep(params, signal) {
103
115
  killTree(child);
104
116
  finish({ status: 'aborted' });
105
117
  };
106
- const handleLine = (line) => {
118
+ const stopCollecting = () => {
119
+ truncated = true;
120
+ buffer = '';
121
+ killTree(child);
122
+ };
123
+ const handleRecord = (line) => {
124
+ if (maxFiles !== undefined) {
125
+ const path = isWin ? normalizePath(line) : line.replace(/^\.\//, '');
126
+ if (!isInsideRoot(path) || matchedPaths.has(path))
127
+ return;
128
+ if (matchedPaths.size >= maxFiles)
129
+ stopCollecting();
130
+ else
131
+ matchedPaths.add(path);
132
+ return;
133
+ }
107
134
  let evt;
108
135
  try {
109
136
  evt = JSON.parse(line);
@@ -114,22 +141,36 @@ export function runRipgrep(params, signal) {
114
141
  const data = evt.data;
115
142
  if (!data)
116
143
  return;
144
+ if (evt.type === 'summary') {
145
+ // end 事件只来自命中文件;零命中时由 summary 区分「搜过」和「没有文件可搜」。
146
+ const searches = data.stats?.searches;
147
+ if (typeof searches === 'number')
148
+ scanned = searches;
149
+ return;
150
+ }
151
+ const pathText = data.path?.text;
152
+ if (typeof pathText !== 'string')
153
+ return;
117
154
  if (evt.type === 'end') {
118
155
  scanned++;
156
+ completeMatches += byPath.get(normalizePath(pathText))?.matches.length ?? 0;
119
157
  return;
120
158
  }
121
159
  if (evt.type !== 'match' && evt.type !== 'context')
122
160
  return;
123
- const pathText = data.path?.text;
124
161
  const lineNo = data.line_number;
125
162
  const linesText = data.lines?.text;
126
- if (typeof pathText !== 'string' || typeof lineNo !== 'number' || typeof linesText !== 'string')
163
+ if (typeof lineNo !== 'number' || typeof linesText !== 'string')
127
164
  return;
128
165
  const path = normalizePath(pathText);
129
- if (!isInsideRoot(path))
130
- return; // 后置兜底:仅留牢内
131
166
  let bucket = byPath.get(path);
132
167
  if (!bucket) {
168
+ if (!isInsideRoot(path))
169
+ return;
170
+ if (params.maxMatches !== undefined && completeMatches >= params.maxMatches) {
171
+ stopCollecting();
172
+ return;
173
+ }
133
174
  bucket = { path, matches: [], contexts: [] };
134
175
  byPath.set(path, bucket);
135
176
  }
@@ -139,22 +180,23 @@ export function runRipgrep(params, signal) {
139
180
  else
140
181
  bucket.contexts.push(event);
141
182
  };
183
+ child.stdout.setEncoding('utf8');
184
+ const separator = pathsOnly ? '\0' : '\n';
142
185
  child.stdout.on('data', (chunk) => {
143
- if (settled)
186
+ if (settled || truncated)
144
187
  return;
145
- collected += chunk.length;
146
- if (collected > MAX_JSON_BYTES && !truncated) {
147
- truncated = true;
148
- killTree(child); // 输出已超预算,没必要继续
188
+ collected += Buffer.byteLength(chunk);
189
+ if (collected > MAX_RG_OUTPUT_BYTES) {
190
+ stopCollecting();
149
191
  return;
150
192
  }
151
- buffer += chunk.toString('utf8');
193
+ buffer += chunk;
152
194
  let idx;
153
- while ((idx = buffer.indexOf('\n')) >= 0) {
195
+ while (!truncated && (idx = buffer.indexOf(separator)) >= 0) {
154
196
  const line = buffer.slice(0, idx);
155
197
  buffer = buffer.slice(idx + 1);
156
198
  if (line)
157
- handleLine(line);
199
+ handleRecord(line);
158
200
  }
159
201
  });
160
202
  child.stderr.on('data', (chunk) => {
@@ -165,28 +207,32 @@ export function runRipgrep(params, signal) {
165
207
  child.on('error', (error) => {
166
208
  // ENOENT / EACCES / exec 格式错误 = 二进制不可用,交给 Node 兜底。
167
209
  const code = error.code;
168
- finish({ status: code === 'ENOENT' || code === 'EACCES' ? 'unavailable' : 'aborted' });
210
+ finish({ status: code === 'ENOENT' || code === 'EACCES' || code === 'ENOEXEC' ? 'unavailable' : 'aborted' });
169
211
  });
170
212
  child.on('close', (code) => {
171
- if (buffer.trim())
172
- handleLine(buffer.trim());
213
+ if (!pathsOnly && buffer.trim())
214
+ handleRecord(buffer.trim());
173
215
  // exit 2 + stderr = 正则/参数错误;无命中事件时按 regex_error 上报。
174
- if (code === 2 && byPath.size === 0 && stderr.trim()) {
216
+ if (code === 2 && byPath.size === 0 && matchedPaths.size === 0 && stderr.trim()) {
175
217
  const message = stderr.trim();
176
218
  // 过滤器把所有文件排除(典型:glob 指向 .gitignore 内的 .mocode 却没放开 ignore)
177
219
  // 不是正则错误——按无匹配处理,避免误导模型去改 pattern。
178
220
  if (/No files were searched/i.test(message)) {
179
- finish({ status: 'no-match', scanned, truncated });
221
+ finish(pathsOnly ? { status: 'paths', paths: [], truncated } : { status: 'no-match', scanned, truncated });
180
222
  return;
181
223
  }
182
224
  finish({ status: 'regex_error', message });
183
225
  return;
184
226
  }
227
+ if (pathsOnly) {
228
+ finish({ status: 'paths', paths: [...matchedPaths], truncated: truncated || (code !== 0 && code !== 1) });
229
+ return;
230
+ }
185
231
  if (byPath.size === 0) {
186
232
  finish({ status: 'no-match', scanned, truncated });
187
233
  return;
188
234
  }
189
- finish({ status: 'ok', files: [...byPath.values()], scanned, truncated });
235
+ finish({ status: 'ok', files: [...byPath.values()], scanned, truncated: truncated || code !== 0 });
190
236
  });
191
237
  if (signal) {
192
238
  if (signal.aborted)
@@ -330,11 +330,25 @@ export class ToolRuntime {
330
330
  async executeToolOnce(tool, args, signal, opts) {
331
331
  const startedAt = Date.now();
332
332
  const capabilities = this.getToolCapabilities(tool);
333
+ const commandStartedAt = tool.name === 'run_command' ? performance.now() : undefined;
334
+ const commandTiming = commandStartedAt === undefined ? undefined : { totalMs: 0 };
335
+ const captureWorkspace = async (phase, capture) => {
336
+ if (!commandTiming)
337
+ return capture();
338
+ const captureStartedAt = performance.now();
339
+ try {
340
+ return await capture();
341
+ }
342
+ finally {
343
+ commandTiming[phase] = performance.now() - captureStartedAt;
344
+ }
345
+ };
333
346
  let mutationVersionBefore;
334
347
  let capturedPath;
348
+ let outcome;
335
349
  try {
336
350
  const requests = this.dependencies.resolveResourceLockRequests(capabilities, args);
337
- return await this.dependencies.resourceLockManager.withLocks(requests, signal, async () => {
351
+ outcome = await this.dependencies.resourceLockManager.withLocks(requests, signal, async () => {
338
352
  opts?.onLockAcquired?.(args);
339
353
  const mutationBefore = this.dependencies.getCurrentTurnMutationState();
340
354
  mutationVersionBefore = mutationBefore.version;
@@ -346,7 +360,7 @@ export class ToolRuntime {
346
360
  : null;
347
361
  capturedPath = pathCapture?.path;
348
362
  const workspaceCapture = capabilities.effect === 'process' || capabilities.effect === 'unknown'
349
- ? await this.dependencies.beginWorkspaceMutation()
363
+ ? await captureWorkspace('workspaceBeforeMs', () => this.dependencies.beginWorkspaceMutation())
350
364
  : null;
351
365
  let raw;
352
366
  try {
@@ -358,12 +372,15 @@ export class ToolRuntime {
358
372
  delegation: opts?.delegation,
359
373
  readDedup: opts?.readDedup,
360
374
  });
375
+ if (commandTiming && isStructuredOutcome(raw))
376
+ commandTiming.commandMs = raw.durationMs;
361
377
  }
362
378
  finally {
363
379
  if (pathCapture)
364
380
  this.dependencies.endPathMutation(pathCapture, tool.name);
365
- if (workspaceCapture)
366
- await this.dependencies.endWorkspaceMutation(workspaceCapture, tool.name);
381
+ if (workspaceCapture) {
382
+ await captureWorkspace('workspaceAfterMs', () => this.dependencies.endWorkspaceMutation(workspaceCapture, tool.name));
383
+ }
367
384
  }
368
385
  const mutationAfter = this.dependencies.getCurrentTurnMutationState();
369
386
  const changedFiles = mutationAfter.version !== mutationBefore.version
@@ -385,10 +402,14 @@ export class ToolRuntime {
385
402
  ? mutationAfter.changedFiles.filter((item) => item.path === capturedPath).map((item) => item.path)
386
403
  : mutationAfter.changedFiles.map((item) => item.path)
387
404
  : [];
388
- if (signal?.aborted || (error instanceof Error && error.name === 'AbortError')) {
389
- return terminalOutcome('aborted', 'ABORTED', t('command.interrupted'), startedAt, changedFiles);
390
- }
391
- return executionErrorOutcome(tool.name, error, startedAt, changedFiles);
405
+ outcome =
406
+ signal?.aborted || (error instanceof Error && error.name === 'AbortError')
407
+ ? terminalOutcome('aborted', 'ABORTED', t('command.interrupted'), startedAt, changedFiles)
408
+ : executionErrorOutcome(tool.name, error, startedAt, changedFiles);
392
409
  }
410
+ if (!commandTiming || commandStartedAt === undefined)
411
+ return outcome;
412
+ commandTiming.totalMs = performance.now() - commandStartedAt;
413
+ return { ...outcome, commandTiming };
393
414
  }
394
415
  }