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
@@ -23,10 +23,15 @@ export const defaultCompactionRuntime = {
23
23
  modelTransport: chat,
24
24
  rollbackStore: defaultRollbackStore,
25
25
  };
26
- export function createContextState() {
27
- return { lastEstimate: 0, correction: 1, calibrationSamples: 0 };
26
+ export function createContextState(options = {}) {
27
+ return {
28
+ lastEstimate: 0,
29
+ correction: 1,
30
+ calibrationSamples: 0,
31
+ ...(options.archiveHistory ? { archiveHistory: true } : {}),
32
+ };
28
33
  }
29
- export const contextState = createContextState();
34
+ export const contextState = createContextState({ archiveHistory: true });
30
35
  /** 中截:text 太长时保 head + 标记 + tail,总长 ≤ max。 */
31
36
  export function truncateMid(text, max) {
32
37
  if (text.length <= max)
@@ -719,8 +724,40 @@ function compactionLogLine(label, before, after, window) {
719
724
  /**
720
725
  * 压缩 history(原地)。手动 /compact 与自动 maybeCompact 都走这里。
721
726
  * 不检查阈值——调用方(maybeCompact)决定是否调;/compact 直接调以强制压缩。
727
+ *
728
+ * 这一层只做「进度广播 + 异常收口」:真正的压缩逻辑在 compactHistoryInner。
729
+ * done 事件在三类出口都发——成功/兜底返回、摘要抛错(failed)、abort(aborted)——
730
+ * 否则 GUI 的「正在压缩」状态行会在异常路径上永久挂着。
722
731
  */
723
732
  export async function compactHistory(history, opts) {
733
+ const notify = opts.runtime?.onCompactProgress;
734
+ if (!notify)
735
+ return compactHistoryInner(history, opts);
736
+ const manual = opts.manual === true;
737
+ const force = opts.force === true;
738
+ notify({ phase: 'start', manual, force, ...(opts.focus ? { focus: opts.focus } : {}) });
739
+ try {
740
+ const result = await compactHistoryInner(history, opts);
741
+ notify({
742
+ phase: 'done',
743
+ manual,
744
+ compacted: result.compacted,
745
+ summarized: result.summarized,
746
+ reason: result.reason,
747
+ estimateBefore: result.estimateBefore,
748
+ estimateAfter: result.estimateAfter,
749
+ historyRebuilt: result.historyRebuilt === true,
750
+ });
751
+ return result;
752
+ }
753
+ catch (cause) {
754
+ const aborted = opts.signal?.aborted === true ||
755
+ (cause instanceof Error && (cause.name === 'AbortError' || cause.name === 'APIUserAbortError'));
756
+ notify({ phase: 'done', manual, compacted: false, summarized: false, failed: true, aborted });
757
+ throw cause;
758
+ }
759
+ }
760
+ async function compactHistoryInner(history, opts) {
724
761
  const state = opts.contextState ?? contextState;
725
762
  const activeTools = opts.tools ?? chatTools;
726
763
  const estimateBefore = rawPromptTokens(history, activeTools);
@@ -950,7 +987,7 @@ export async function compactHistory(history, opts) {
950
987
  // 随后被覆盖——落盘 compacted/seg-NNN.md,模型事后靠 grep/read_file 回捞精确原文。
951
988
  // best-effort:失败只丢回捞能力,绝不阻塞压缩。
952
989
  let archivedPath = null;
953
- if (state === contextState) {
990
+ if (state.archiveHistory) {
954
991
  try {
955
992
  archivedPath = getActiveSessionStore().archiveCompactedMessages(getCurrentSessionId() ?? '', older);
956
993
  }
@@ -12,6 +12,7 @@
12
12
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
13
13
  import path from 'node:path';
14
14
  import { gzipSync, gunzipSync } from 'node:zlib';
15
+ import { readTerminalTranscriptFile } from './terminal-transcript.js';
15
16
  import { COMPACTED_DIRNAME, isCompactedAssetName } from './compact-archive.js';
16
17
  import { TextSearchIndex } from '../context/text-search.js';
17
18
  import { config } from '../config/index.js';
@@ -211,6 +212,9 @@ function archiveSession(sessionsRoot, id, now) {
211
212
  const assets = readCompactedAssets(sessionsRoot, id);
212
213
  if (Object.keys(assets).length > 0)
213
214
  record.compactedAssets = assets;
215
+ const terminalTranscript = readTerminalTranscriptFile(dir);
216
+ if (terminalTranscript)
217
+ record.terminalTranscript = terminalTranscript;
214
218
  mkdirSync(paths.archiveDir, { recursive: true });
215
219
  const gzPath = path.join(paths.archiveDir, `${id}.json.gz`);
216
220
  writeFileSync(gzPath + '.tmp', gzipSync(Buffer.from(JSON.stringify(record), 'utf8')));
@@ -0,0 +1,185 @@
1
+ /** 只读探索工具:重复执行相同调用视为纯浪费。 */
2
+ export const READ_ONLY_TOOLS = new Set(['read_file', 'grep', 'glob']);
3
+ function finiteNumber(value) {
4
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
5
+ }
6
+ export function reduceShortPathEfficiency(events) {
7
+ let toolCalls = 0;
8
+ let mutationCalls = 0;
9
+ let readOnlyCalls = 0;
10
+ let modelRequests = 0;
11
+ let firstEditSeen = false;
12
+ let requestsBeforeFirstEdit = null;
13
+ let readCallsBeforeFirstEdit = null;
14
+ let postEditReadOnlyCalls = 0;
15
+ let repeatedIdentical = 0;
16
+ const seenReadOnly = new Map();
17
+ let promptTokens = 0;
18
+ let completionTokens = 0;
19
+ let cachedTokens = 0;
20
+ let totalTokens = 0;
21
+ let hasTokens = false;
22
+ let hasCached = false;
23
+ let durationMs = 0;
24
+ const phases = {
25
+ routeDurationMs: null,
26
+ modelAttempts: 0,
27
+ modelDurationMs: 0,
28
+ uncachedPromptTokens: null,
29
+ postEditCommands: 0,
30
+ postEditCommandDurationMs: 0,
31
+ finalModelRequests: 0,
32
+ finalModelDurationMs: 0,
33
+ completion: null,
34
+ fallbackReason: null,
35
+ };
36
+ let uncachedPromptTokens = 0;
37
+ let requestsWithCacheUsage = 0;
38
+ const modelDurations = new Map();
39
+ const firstEdit = {
40
+ firstAttemptApplied: null,
41
+ requests: null,
42
+ toolOutputTokensEstimate: null,
43
+ uncachedInputTokens: null,
44
+ };
45
+ let firstEditCall;
46
+ let exploredToolTokens = 0;
47
+ let completeToolEstimates = true;
48
+ for (const event of events) {
49
+ if (event.type === 'tool_route') {
50
+ phases.routeDurationMs = finiteNumber(event.data.latencyMs);
51
+ continue;
52
+ }
53
+ if (event.type === 'short_path_completion') {
54
+ phases.completion = event.data.status === 'completed' ? 'automatic' : 'fallback';
55
+ phases.fallbackReason = typeof event.data.reason === 'string' ? event.data.reason : null;
56
+ continue;
57
+ }
58
+ if (event.type === 'model_retry') {
59
+ phases.modelAttempts += 1;
60
+ continue;
61
+ }
62
+ if (event.type === 'model_end') {
63
+ phases.modelAttempts += 1;
64
+ // 同一步的 overflow 重试复用起始时钟,取最大累计耗时。
65
+ const step = event.step ?? event.eventId;
66
+ const elapsed = finiteNumber(event.data.durationMs) ?? 0;
67
+ modelDurations.set(step, Math.max(elapsed, modelDurations.get(step) ?? 0));
68
+ if (String(event.data.status ?? '') !== 'success')
69
+ continue;
70
+ modelRequests += 1;
71
+ if (toolCalls > 0) {
72
+ phases.finalModelRequests += 1;
73
+ phases.finalModelDurationMs += elapsed;
74
+ }
75
+ const prompt = finiteNumber(event.data.promptTokens);
76
+ const completion = finiteNumber(event.data.completionTokens);
77
+ const total = finiteNumber(event.data.totalTokens);
78
+ if (prompt !== null || completion !== null || total !== null) {
79
+ hasTokens = true;
80
+ promptTokens += prompt ?? 0;
81
+ completionTokens += completion ?? 0;
82
+ totalTokens += total ?? (prompt ?? 0) + (completion ?? 0);
83
+ }
84
+ const cached = finiteNumber(event.data.cachedTokens);
85
+ if (cached !== null) {
86
+ hasCached = true;
87
+ cachedTokens += cached;
88
+ if (prompt !== null && cached <= prompt) {
89
+ requestsWithCacheUsage += 1;
90
+ uncachedPromptTokens += prompt - cached;
91
+ }
92
+ }
93
+ continue;
94
+ }
95
+ if (event.type === 'tool_call_start') {
96
+ toolCalls += 1;
97
+ phases.finalModelRequests = 0;
98
+ phases.finalModelDurationMs = 0;
99
+ const tool = typeof event.data.tool === 'string' ? event.data.tool : '';
100
+ if ((tool === 'edit_file' || tool === 'write_file') && !firstEditCall)
101
+ firstEditCall = event;
102
+ if (!READ_ONLY_TOOLS.has(tool))
103
+ continue;
104
+ readOnlyCalls += 1;
105
+ if (firstEditSeen)
106
+ postEditReadOnlyCalls += 1;
107
+ const fingerprint = typeof event.data.argumentHash === 'string' ? event.data.argumentHash : '';
108
+ const key = `${tool}:${fingerprint}`;
109
+ const seen = seenReadOnly.get(key) ?? 0;
110
+ if (seen > 0)
111
+ repeatedIdentical += 1;
112
+ seenReadOnly.set(key, seen + 1);
113
+ continue;
114
+ }
115
+ if (event.type === 'tool_call_end') {
116
+ if (firstEditSeen && event.data.tool === 'run_command') {
117
+ phases.postEditCommands += 1;
118
+ phases.postEditCommandDurationMs += finiteNumber(event.data.durationMs) ?? 0;
119
+ }
120
+ const changedFiles = event.data.changedFiles;
121
+ const changed = Array.isArray(changedFiles) && changedFiles.length > 0;
122
+ const tool = event.data.tool;
123
+ const isEdit = tool === 'edit_file' || tool === 'write_file';
124
+ const applied = event.data.status === 'success' && changed;
125
+ if (isEdit &&
126
+ firstEdit.firstAttemptApplied === null &&
127
+ (!firstEditCall ||
128
+ (firstEditCall.toolCallId ? firstEditCall.toolCallId === event.toolCallId : firstEditCall.data.tool === tool))) {
129
+ firstEdit.firstAttemptApplied = applied;
130
+ }
131
+ if (firstEdit.requests === null) {
132
+ if (isEdit && applied) {
133
+ firstEdit.requests = modelRequests;
134
+ firstEdit.toolOutputTokensEstimate = completeToolEstimates ? exploredToolTokens : null;
135
+ firstEdit.uncachedInputTokens =
136
+ modelRequests > 0 && requestsWithCacheUsage === modelRequests ? uncachedPromptTokens : null;
137
+ }
138
+ else {
139
+ const outputTokens = finiteNumber(event.data.outputTokensEstimate);
140
+ if (outputTokens === null)
141
+ completeToolEstimates = false;
142
+ else
143
+ exploredToolTokens += outputTokens;
144
+ }
145
+ }
146
+ if (!changed)
147
+ continue;
148
+ mutationCalls += 1;
149
+ if (!firstEditSeen) {
150
+ firstEditSeen = true;
151
+ requestsBeforeFirstEdit = modelRequests;
152
+ readCallsBeforeFirstEdit = readOnlyCalls;
153
+ }
154
+ continue;
155
+ }
156
+ if (event.type === 'turn_end') {
157
+ durationMs = finiteNumber(event.data.durationMs) ?? durationMs;
158
+ }
159
+ }
160
+ phases.modelDurationMs = [...modelDurations.values()].reduce((total, ms) => total + ms, 0);
161
+ if (modelRequests > 0 && requestsWithCacheUsage === modelRequests) {
162
+ phases.uncachedPromptTokens = uncachedPromptTokens;
163
+ }
164
+ return {
165
+ toolCalls,
166
+ mutationCalls,
167
+ readOnlyCalls,
168
+ modelRequests,
169
+ requestsBeforeFirstEdit,
170
+ readCallsBeforeFirstEdit,
171
+ repeatedIdenticalReadOnlyCalls: repeatedIdentical,
172
+ postEditReadOnlyCalls,
173
+ promptTokens: hasTokens ? promptTokens : null,
174
+ completionTokens: hasTokens ? completionTokens : null,
175
+ cachedTokens: hasCached ? cachedTokens : null,
176
+ totalTokens: hasTokens ? totalTokens : null,
177
+ durationMs,
178
+ firstEdit,
179
+ phases,
180
+ };
181
+ }
182
+ /** 任意一段 trace(如 warm 预热轮)里的只读调用数,用于判断预热轮是否真的建立了上下文。 */
183
+ export function countReadOnlyCalls(events) {
184
+ return events.filter((event) => event.type === 'tool_call_start' && READ_ONLY_TOOLS.has(String(event.data.tool ?? ''))).length;
185
+ }
@@ -5,6 +5,7 @@ import { gzipSync } from 'node:zlib';
5
5
  import path from 'node:path';
6
6
  import { MAX_TRACE_BYTES, MAX_TRACE_ROTATIONS, MAX_COMPACTED_ARCHIVE_BYTES } from '../tools/constants.js';
7
7
  import { loadArchivedSession, readArchiveIndex, retentionPaths } from './retention.js';
8
+ import { parseTerminalTranscript, readTerminalTranscriptFile, writeTerminalTranscriptFile, } from './terminal-transcript.js';
8
9
  import { COMPACTED_DIRNAME, isCompactedAssetName, parseSegmentMeta, renderArchiveIndex, renderCompactedSegment, resultBlobFileName, RESULT_BLOB_FILE_RE, SEGMENT_FILE_RE, } from './compact-archive.js';
9
10
  import { config, getActiveModel } from '../config/index.js';
10
11
  import { getWorkspaceRoot } from '../workspace/index.js';
@@ -24,11 +25,42 @@ function idToIso(id) {
24
25
  return id;
25
26
  return `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}${m[7] ? `.${m[7]}` : ''}`;
26
27
  }
28
+ /**
29
+ * 一条 user 消息的 content → 一行人读文本。
30
+ *
31
+ * 多模态 content(文字 + 图片)**不能**直接 JSON.stringify:那会把
32
+ * `[{"type":"text","text":"这是?"},{"type":"image_url","image_url":{…}}]` 整段塞进
33
+ * firstUser,会话列表里就显示成一串 JSON(实测仓库里 13 条会话如此,侧栏读到的是
34
+ * 截到 40 字符的半截 JSON,既不是人话也解析不了)。图片按 `[图片]` 占位 ——
35
+ * 标题要的是「我第一句说了什么」,不是 base64。
36
+ */
27
37
  function toText(content) {
28
38
  if (content == null)
29
39
  return '';
30
40
  if (typeof content === 'string')
31
41
  return content;
42
+ if (Array.isArray(content)) {
43
+ const texts = [];
44
+ let hasImage = false;
45
+ for (const part of content) {
46
+ if (typeof part === 'string') {
47
+ texts.push(part);
48
+ continue;
49
+ }
50
+ if (!part || typeof part !== 'object')
51
+ continue;
52
+ const piece = part;
53
+ if (piece.type === 'text' && typeof piece.text === 'string')
54
+ texts.push(piece.text);
55
+ else if (piece.type === 'image_url')
56
+ hasImage = true;
57
+ }
58
+ const joined = texts.join(' ').trim();
59
+ if (joined)
60
+ return joined;
61
+ if (hasImage)
62
+ return '[图片]';
63
+ }
32
64
  try {
33
65
  return JSON.stringify(content);
34
66
  }
@@ -43,10 +75,44 @@ function firstUserOf(history) {
43
75
  const text = toText(message.content)
44
76
  .replace(/\n/g, ' ')
45
77
  .trim();
78
+ if (!text)
79
+ continue;
46
80
  return truncateDisplay(text, 40);
47
81
  }
48
82
  return '';
49
83
  }
84
+ /**
85
+ * 读侧修正老的 firstUser:早期版本把多模态 content 直接 JSON.stringify 存进了这个字段,
86
+ * 于是一批会话在列表里永远显示成 `[{"type":"text","text":"这是?"},…]`(落盘值不会自愈,
87
+ * 只有该会话下次 save 才会重算)。以 `[` / `{` 开头即视为序列化产物,改从 history 重算;
88
+ * history 不可用时退回原值。
89
+ *
90
+ * 用户真的把一段 JSON 当第一句话粘贴时也安全:content 是字符串,重算结果与落盘值逐字相同。
91
+ */
92
+ function repairFirstUser(record) {
93
+ const stored = typeof record.firstUser === 'string' ? record.firstUser : '';
94
+ const head = stored.trimStart()[0];
95
+ if (head !== '[' && head !== '{')
96
+ return stored;
97
+ if (!Array.isArray(record.history))
98
+ return stored;
99
+ return firstUserOf(record.history) || stored;
100
+ }
101
+ /**
102
+ * 归档会话的 firstUser 修正:归档条目只有索引里的标题,内联 history 在 `archive/<id>.json.gz`。
103
+ *
104
+ * 只为「看起来是序列化产物」的条目解一次 gz —— 每个工作空间这类条目通常 0~1 条,
105
+ * 不值得为它给整个列表加一次全量解压。
106
+ */
107
+ function repairArchivedFirstUser(sessionsRoot, id, stored) {
108
+ const head = stored.trimStart()[0];
109
+ if (head !== '[' && head !== '{')
110
+ return stored;
111
+ const archived = loadArchivedSession(sessionsRoot, id);
112
+ if (!archived || !Array.isArray(archived.history))
113
+ return stored;
114
+ return firstUserOf(archived.history) || stored;
115
+ }
50
116
  /** compacted/ 总量上限:MOCODE_MAX_COMPACTED_BYTES 覆盖(供测试/小盘),非法值回退默认。 */
51
117
  function envMaxCompactedBytes() {
52
118
  const raw = process.env.MOCODE_MAX_COMPACTED_BYTES;
@@ -486,6 +552,15 @@ export class SessionStore {
486
552
  }
487
553
  }
488
554
  }
555
+ loadTerminalTranscript(id) {
556
+ return (readTerminalTranscriptFile(path.join(this.sessionsRoot, id)) ??
557
+ parseTerminalTranscript(loadArchivedSession(this.sessionsRoot, id)?.terminalTranscript));
558
+ }
559
+ saveTerminalTranscript(id, transcript) {
560
+ const dir = path.join(this.sessionsRoot, id);
561
+ this.ensureDir(dir);
562
+ writeTerminalTranscriptFile(dir, transcript);
563
+ }
489
564
  load(id, opts) {
490
565
  const currentPath = this.sessionPath(id);
491
566
  const legacyPath = path.join(this.sessionsRoot, `${id}.json`);
@@ -509,7 +584,7 @@ export class SessionStore {
509
584
  id: rec.id,
510
585
  createdAt: rec.createdAt ?? idToIso(rec.id ?? id),
511
586
  model: rec.model ?? '',
512
- firstUser: rec.firstUser ?? '',
587
+ firstUser: repairFirstUser(rec),
513
588
  history: rec.history,
514
589
  queryHistory: Array.isArray(rec.queryHistory)
515
590
  ? rec.queryHistory.filter((query) => typeof query === 'string')
@@ -632,7 +707,7 @@ export class SessionStore {
632
707
  id: rec.id,
633
708
  createdAt: rec.createdAt ?? idToIso(rec.id),
634
709
  model: rec.model ?? '',
635
- firstUser: rec.firstUser ?? '',
710
+ firstUser: repairFirstUser(rec),
636
711
  });
637
712
  }
638
713
  catch {
@@ -649,7 +724,7 @@ export class SessionStore {
649
724
  id: e.id,
650
725
  createdAt: e.createdAt ?? idToIso(e.id),
651
726
  model: e.model ?? '',
652
- firstUser: e.firstUser ?? '',
727
+ firstUser: repairArchivedFirstUser(root, e.id, e.firstUser ?? ''),
653
728
  archived: true,
654
729
  });
655
730
  }
@@ -0,0 +1,101 @@
1
+ import { readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ export const TERMINAL_TRANSCRIPT_FILE = 'terminal-transcript.json';
4
+ /** 仅为回放保存图片的类型,图像字节仍由模型会话自身管理。 */
5
+ function displayContent(content, imageNames = []) {
6
+ if (!Array.isArray(content))
7
+ return content;
8
+ let imageIndex = 0;
9
+ return content.map((part) => {
10
+ if (part.type !== 'image_url')
11
+ return { ...part };
12
+ const name = imageNames[imageIndex++];
13
+ return {
14
+ ...part,
15
+ ...(name ? { name } : {}),
16
+ image_url: { url: /^data:image\/[a-z0-9.+-]+;/i.exec(part.image_url.url)?.[0] ?? 'data:image/png;' },
17
+ };
18
+ });
19
+ }
20
+ export function createTerminalTranscript(history) {
21
+ const base = history.map((message, index) => {
22
+ if (message.role === 'system' && index === 0)
23
+ return { role: 'system', content: '' };
24
+ if (message.role === 'user')
25
+ return { ...message, content: displayContent(message.content) };
26
+ if (message.role === 'assistant')
27
+ return {
28
+ role: 'assistant',
29
+ content: message.content,
30
+ ...(message.tool_calls ? { tool_calls: structuredClone(message.tool_calls) } : {}),
31
+ };
32
+ return { ...message };
33
+ });
34
+ if (base[0]?.role !== 'system')
35
+ base.unshift({ role: 'system', content: '' });
36
+ return { base, turns: [] };
37
+ }
38
+ export function terminalCompactionMarker() {
39
+ return { role: 'system', content: '# 会话摘要' };
40
+ }
41
+ export function rollbackTerminalTranscript(transcript, firstDiscardedTurnId, retainedHistory) {
42
+ const firstRecordedTurn = transcript.turns[0];
43
+ if (!firstRecordedTurn || firstDiscardedTurnId === undefined || firstDiscardedTurnId < firstRecordedTurn.turnId) {
44
+ return createTerminalTranscript(retainedHistory);
45
+ }
46
+ return { base: transcript.base, turns: transcript.turns.filter((turn) => turn.turnId < firstDiscardedTurnId) };
47
+ }
48
+ export function createTerminalTurn(content, imageNames) {
49
+ const messages = [{ role: 'user', content: displayContent(content, imageNames) }];
50
+ return {
51
+ messages,
52
+ addUser(text) {
53
+ messages.push({ role: 'user', content: text });
54
+ },
55
+ addText(text) {
56
+ if (!text)
57
+ return;
58
+ const last = messages.at(-1);
59
+ if (last?.role === 'assistant' && typeof last.content === 'string' && !last.tool_calls?.length) {
60
+ last.content += text;
61
+ }
62
+ else {
63
+ messages.push({ role: 'assistant', content: text });
64
+ }
65
+ },
66
+ addTool(call, output) {
67
+ messages.push({
68
+ role: 'assistant',
69
+ content: null,
70
+ tool_calls: [{ id: call.id, type: 'function', function: { name: call.name, arguments: call.arguments } }],
71
+ }, { role: 'tool', tool_call_id: call.id, content: output });
72
+ },
73
+ compacted() {
74
+ messages.push(terminalCompactionMarker());
75
+ },
76
+ };
77
+ }
78
+ export function parseTerminalTranscript(value) {
79
+ if (!value || typeof value !== 'object')
80
+ return;
81
+ const { base, turns } = value;
82
+ const isMessageList = (items) => Array.isArray(items) && items.every((item) => item && typeof item === 'object' && typeof item.role === 'string');
83
+ if (isMessageList(base) &&
84
+ Array.isArray(turns) &&
85
+ turns.every((turn) => Number.isSafeInteger(turn?.turnId) && isMessageList(turn.messages)))
86
+ return { base, turns };
87
+ }
88
+ export function readTerminalTranscriptFile(dir) {
89
+ try {
90
+ return parseTerminalTranscript(JSON.parse(readFileSync(path.join(dir, TERMINAL_TRANSCRIPT_FILE), 'utf8')));
91
+ }
92
+ catch {
93
+ // 旧会话或损坏记录仍可按模型历史回放。
94
+ }
95
+ }
96
+ export function writeTerminalTranscriptFile(dir, transcript) {
97
+ const file = path.join(dir, TERMINAL_TRANSCRIPT_FILE);
98
+ const temporary = file + '.tmp';
99
+ writeFileSync(temporary, JSON.stringify(transcript), 'utf8');
100
+ renameSync(temporary, file);
101
+ }
@@ -125,8 +125,8 @@ export const askHumanTool = {
125
125
  'Ask the user a question and wait for their response.',
126
126
  ' CHOICES: pass 2-4 concrete options via `options`, each as { label, description? }; every non-empty option requires a non-empty `label`.',
127
127
  ' FREE-TEXT: pass `options: []` when the answer cannot be reduced to choices (e.g. "paste the error message").',
128
- ' MUST call BEFORE any decision the user has not made (multiple reasonable approaches) or any key modification (public API, schema, dependencies, file moves/deletes, architecture, security, large or irreversible changes); never decide these yourself.',
129
- ' Skip only for trivial details that follow repository precedent and are easily reversible.',
128
+ ' Ask BEFORE unresolved choices that materially affect the outcome and before key modifications (public API, schema, dependencies, file moves/deletes, architecture, security, large or irreversible changes).',
129
+ ' Carry out routine, reversible implementation details of a clear request using local conventions.',
130
130
  ].join(' '),
131
131
  parameters: {
132
132
  type: 'object',
@@ -1,9 +1,14 @@
1
1
  import { readFile } from 'node:fs/promises';
2
+ import { basename } from 'node:path';
3
+ import { unifiedFileDiff } from '../../changeset/unified-diff.js';
2
4
  import { jailResolve } from '../../sandbox/index.js';
3
5
  import { commitChangeSet, contentHash, createChangeSet, normalizeContentHash, summarizeChangeSet, } from '../../changeset/index.js';
4
6
  import { isProbablyBinary } from '../../attachments/image.js';
5
7
  /** 二进制嗅探只需文件头,与 read_file / write_file 同口径(16KB)。 */
6
8
  const SNIFF_BYTES = 16 * 1024;
9
+ // 复用已有 diff 渲染,只给模型回传完整的小补丁。大文件免去额外的全文拆行。
10
+ const MAX_PREVIEW_INPUT_CHARS = 256 * 1024;
11
+ const MAX_PREVIEW_CHARS = 2000;
7
12
  function conflict(path, details) {
8
13
  return {
9
14
  status: 'error',
@@ -11,18 +16,18 @@ function conflict(path, details) {
11
16
  retryable: false,
12
17
  changedFiles: [],
13
18
  staleFiles: [path],
14
- output: `CHANGE_CONFLICT: ${path} was not changed. ${details} Do not retry these arguments. Call read_file on this exact path and copy the exact target text (plus its latest hash if you pass expected_hash, which line-range mode requires) before editing again.`,
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.`,
15
20
  };
16
21
  }
17
22
  export const editFileTool = {
18
23
  name: 'edit_file',
19
24
  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:
20
25
 
21
- **String replacement (default):** old_string must occur EXACTLY once; copy it verbatim from a fresh read_file output (see Tool policy — never reconstruct it from memory, summaries, or grep output). expected_hash is OPTIONAL in this mode: omit it and the tool checks the file itself (old_string must still match exactly once, and the commit is conflict-checked). If you do pass it, it must match the current file or the edit is rejected.
26
+ **String replacement (default):** old_string must occur EXACTLY once. Copy it verbatim from fresh read_file output or a complete [edit_context ...] excerpt from grep. Always pass the excerpt's hash as expected_hash when using grep evidence. With read_file, the hash is optional; the tool still checks uniqueness and conflicts at commit. Ordinary search results, summaries and diffs are not exact edit evidence.
22
27
 
23
28
  **Multiple replacements:** pass replacements: [{ old_string, new_string }, …] to apply MANY edits across the file in ONE atomic call. Each old_string must occur exactly once in the original file and the matches must not overlap; if ANY of them is missing, ambiguous, or overlapping, the whole call is rejected and nothing is written. Prefer this over write_file whenever you change several spots — it keeps each payload small and never touches unrelated content. Mutually exclusive with the single old_string and line-range modes.
24
29
 
25
- **Line-range:** line_start/line_end (1-based, inclusive) instead of old_string — for large blocks, repeated patterns, or hard-to-reproduce text. Line numbers drift when a file changes, so expected_hash (sha256 from the read_file artifact header) is REQUIRED here; if it is stale, re-read and retry with the new hash.`,
30
+ **Line-range:** line_start/line_end (1-based, inclusive) instead of old_string — for large blocks, repeated patterns, or hard-to-reproduce text. expected_hash from a fresh read_file or [edit_context ...] header is REQUIRED. If stale, reread only the affected range and retry with the new hash.`,
26
31
  risk: 'confirm',
27
32
  parameters: {
28
33
  type: 'object',
@@ -59,7 +64,7 @@ export const editFileTool = {
59
64
  },
60
65
  expected_hash: {
61
66
  type: 'string',
62
- description: 'sha256 hash from the latest read_file artifact header (sha256:<64 hex>). Optional for old_string / replacements modes; required for line-range mode.',
67
+ description: 'Latest sha256:<64 hex> from read_file or [edit_context ...]. Always pass it with grep edit evidence or line-range edits.',
63
68
  },
64
69
  },
65
70
  // 注意:expected_hash 与模式专属字段(new_string / replacements / line_*)都不放进 schema required。
@@ -232,15 +237,33 @@ export const editFileTool = {
232
237
  };
233
238
  }
234
239
  const summary = summarizeChangeSet(result.changeSet);
240
+ const committed = result.changeSet.prepared[0];
241
+ const literal = mode === 'single' ? String(args.old_string) : '';
242
+ const literalStart = literal ? data.indexOf(literal) : -1;
243
+ // CRLF 归一化、非 UTF-8 和重叠命中可能改变替换范围,只有实际事务满足才提供证明。
244
+ const exactTextReplacement = literalStart >= 0 &&
245
+ result.changedFiles.length === 1 &&
246
+ data.length + replacement.length <= MAX_PREVIEW_INPUT_CHARS &&
247
+ committed.before?.equals(buffer) &&
248
+ Buffer.from(data).equals(buffer) &&
249
+ data.indexOf(literal, literalStart + 1) < 0 &&
250
+ data.replace(literal, () => String(args.new_string)) === replacement;
251
+ let preview = '';
252
+ if (result.changedFiles.length > 0 && data.length + replacement.length <= MAX_PREVIEW_INPUT_CHARS) {
253
+ const diff = unifiedFileDiff(basename(file), data, replacement, 1);
254
+ if (diff && diff.length <= MAX_PREVIEW_CHARS)
255
+ preview = `\n${diff}`;
256
+ }
235
257
  return {
236
258
  status: 'success',
237
259
  code: 'OK',
238
260
  retryable: false,
239
261
  changedFiles: result.changedFiles,
240
262
  changeSet: summary,
263
+ ...(exactTextReplacement ? { exactTextReplacement: true } : {}),
241
264
  output: result.changedFiles.length === 0
242
265
  ? `文件 ${file} 内容未变化 (ChangeSet ${summary.id})。`
243
- : `已事务化编辑 ${file} (ChangeSet ${summary.id}, sha256=${summary.changes[0]?.afterHash})。`,
266
+ : `已事务化编辑 ${file} (ChangeSet ${summary.id}, sha256=${summary.changes[0]?.afterHash})。${preview}`,
244
267
  };
245
268
  },
246
269
  };