mocode-ai 1.9.9 → 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 (74) 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 +83 -16
  4. package/dist/agent/progress-guard.js +67 -0
  5. package/dist/agent/run-coordinator.js +151 -23
  6. package/dist/agent/short-path-completion.js +109 -0
  7. package/dist/agent/spawn.js +46 -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/changeset/unified-diff.js +59 -0
  13. package/dist/config/index.js +13 -10
  14. package/dist/context/relevance.js +2 -1
  15. package/dist/context/usage-snapshot.js +50 -0
  16. package/dist/headless.js +3 -1
  17. package/dist/host/commit-message.js +41 -0
  18. package/dist/host/protocol.js +205 -10
  19. package/dist/host/stdio.js +1096 -63
  20. package/dist/i18n/index.js +26 -10
  21. package/dist/llm/index.js +28 -3
  22. package/dist/llm/message-shape.js +45 -0
  23. package/dist/llm/providers/anthropic.js +2 -0
  24. package/dist/llm/reasoning.js +17 -0
  25. package/dist/memory/adoption.js +159 -27
  26. package/dist/memory/anchor-relocate.js +227 -0
  27. package/dist/memory/consolidate-skips.js +196 -0
  28. package/dist/memory/health.js +88 -6
  29. package/dist/memory/index.js +2 -1
  30. package/dist/memory/reflect.js +36 -4
  31. package/dist/memory/store.js +30 -0
  32. package/dist/models/reasoning-cap.js +19 -2
  33. package/dist/orchestrator/lane-executor.js +7 -1
  34. package/dist/orchestrator/repl.js +30 -49
  35. package/dist/prompt/system-prompt.js +30 -0
  36. package/dist/repl/commands/appearance.js +1 -2
  37. package/dist/repl/commands/compact.js +4 -0
  38. package/dist/repl/commands/diff.js +5 -46
  39. package/dist/repl/commands/memory.js +77 -4
  40. package/dist/repl/commands/model-actions.js +4 -3
  41. package/dist/repl/commands/model.js +2 -3
  42. package/dist/repl/message-format.js +7 -6
  43. package/dist/repl/running-input.js +27 -65
  44. package/dist/repl/runtime.js +129 -89
  45. package/dist/repl/status-bar.js +4 -38
  46. package/dist/rollback/store.js +36 -23
  47. package/dist/runtime/browser-diagnostics.js +77 -0
  48. package/dist/runtime/browser-manager.js +150 -22
  49. package/dist/runtime/runtime.js +1 -1
  50. package/dist/session/compact.js +44 -4
  51. package/dist/session/retention.js +4 -0
  52. package/dist/session/short-path-metrics.js +185 -0
  53. package/dist/session/store.js +78 -3
  54. package/dist/session/terminal-transcript.js +101 -0
  55. package/dist/tools/builtins/ask-human.js +2 -2
  56. package/dist/tools/builtins/browser.js +4 -1
  57. package/dist/tools/builtins/edit-file.js +28 -5
  58. package/dist/tools/builtins/grep.js +85 -35
  59. package/dist/tools/builtins/memory-save.js +1 -1
  60. package/dist/tools/builtins/memory-update.js +1 -1
  61. package/dist/tools/builtins/plan-update.js +4 -2
  62. package/dist/tools/builtins/read-file.js +95 -44
  63. package/dist/tools/builtins/run-command.js +57 -9
  64. package/dist/tools/builtins/task.js +4 -0
  65. package/dist/tools/constants.js +8 -0
  66. package/dist/tools/ripgrep-client.js +31 -11
  67. package/dist/tools/tool-runtime.js +29 -8
  68. package/dist/ui/layout-internal/content-write.js +7 -3
  69. package/dist/ui/layout-internal/core.js +1 -1
  70. package/dist/ui/layout-internal/state.js +0 -6
  71. package/dist/ui/layout-internal/statusbar.js +0 -30
  72. package/dist/ui/output-sink.js +24 -0
  73. package/dist/ui/spinner.js +3 -1
  74. package/package.json +4 -2
@@ -1,18 +1,35 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
3
+ import path from 'node:path';
2
4
  import readline from 'node:readline';
3
5
  import { createRuntime } from '../runtime/index.js';
4
- import { buildBasePrompt } from '../config/index.js';
5
- import { estimateMessagesTokens } from '../llm/index.js';
6
+ import { config, isMemoryEnabled } from '../config/index.js';
7
+ import { measureContextUsage } from '../context/usage-snapshot.js';
6
8
  import { initializeAllMcp, getMcpTools, getMcpWarnings, closeAllMcp } from '../mcp/index.js';
7
- import { appendCurrentSessionTraceEvent, createContextState } from '../session/index.js';
8
- import { effectiveSystemPrompt } from '../skills/index.js';
9
+ import { appendCurrentSessionTraceEvent, createContextState, SessionStore, } from '../session/index.js';
10
+ import { registerWorkspace, readWorkspaceRegistry } from '../workspace/registry.js';
9
11
  import { clearSkillActivation } from '../skills/activation.js';
12
+ import { buildSystemMessage } from '../prompt/system-prompt.js';
13
+ import { buildMemoryTailSection, buildTurnRecallSection, captureMemoryBaseline, gcMemories, initPersona, isTurnRecallEnabled, memoryTailChangedIds, } from '../memory/index.js';
10
14
  import { ToolPolicyController } from '../tools/policy.js';
11
15
  import { routeToolGroups } from '../tools/router.js';
12
16
  // 装配官方默认工具包:registry 不再顶层 import builtins(破模块循环),host 入口须显式装配。
13
17
  import '../tools/builtins/index.js';
18
+ import { muteStdoutOutput } from '../ui/output-sink.js';
14
19
  import { setAskHumanHandler } from '../tools/builtins/ask-human.js';
15
- import { parseCommand } from './protocol.js';
20
+ import { HOST_PROTOCOL_VERSION, parseCommand } from './protocol.js';
21
+ // ── 面板数据源(会话 / 回滚 / 改动 / 用量 / 记忆 / 设置)──
22
+ // 这些在 terminal 里各是一个斜杠命令,命令体本身是 ui/layout 渲染 + 数据拼装两段;
23
+ // host 只取「拼装」那一半:数据从同一批 core 函数来,渲染交给 GUI。
24
+ import { readGlobalUsage, summarizeGlobalUsage } from '../session/global-usage.js';
25
+ import { summarizeUsage } from '../session/usage-stats.js';
26
+ import { unifiedFileDiff } from '../changeset/unified-diff.js';
27
+ import { buildMemoryHealth, forgetEntry, formatMemoryHealth, invalidateEdge, inspectPrimaryProfile, isMemoryWritesPaused, kickoffReflection, listInternalizedProfile, listProfileCandidates, loadAll, promoteEdge, readAudit, searchEntries, snapshotTranscript, } from '../memory/index.js';
28
+ import { readRecallStats } from '../memory/recall-stats.js';
29
+ import { getActiveEffort, isComputerUseEnabled, isFrontendToolsEnabled, isSubAgentEnabled, isToolRoutingEnabled, updateComputerUseConfig, updateFrontendToolsConfig, updateMemoryConfig, updateModelConfig, updateSubAgentConfig, updateToolRoutingEnabled, } from '../config/index.js';
30
+ import { parseReasoningEffort } from '../llm/reasoning.js';
31
+ import { writeConfigKeys } from '../config/file.js';
32
+ import { generateCommitMessage } from './commit-message.js';
16
33
  let initialized = null;
17
34
  let runtimeFacade = null;
18
35
  let activeRun = null;
@@ -23,8 +40,10 @@ let sessionId = '';
23
40
  let history = [];
24
41
  let queryHistory = [];
25
42
  let lastToolGroups = [];
26
- let contextState = createContextState();
43
+ let contextState = createContextState({ archiveHistory: true });
27
44
  const approvals = new Map();
45
+ /** 独立 AI 请求按面板 requestId 取消;不得复用任务 run 的 activeRun。 */
46
+ const commitMessageRequests = new Map();
28
47
  function runtime() {
29
48
  if (!runtimeFacade)
30
49
  throw new Error('Runtime is not initialized.');
@@ -39,6 +58,14 @@ function emit(event, payload = {}, requestId) {
39
58
  function error(message, requestId) {
40
59
  write({ type: 'error', error: message, requestId });
41
60
  }
61
+ /**
62
+ * 转发的「执行前文件内容」上限。
63
+ *
64
+ * write_file 覆盖写时旧内容是 diff 的删除侧,必须让 GUI 看得到改动前的样子;但这份内容要
65
+ * JSON 序列化穿过 stdio + IPC 两跳再进 DOM,几十万字符会把管道和渲染都拖垮。
66
+ * 超限就不转发,GUI 按「全部新增」展示(与终端 replay 路径同策略)。
67
+ */
68
+ const MAX_FORWARDED_OLD_BYTES = 200_000;
42
69
  async function initializeRuntime() {
43
70
  if (initialized)
44
71
  return initialized;
@@ -52,28 +79,52 @@ async function initializeRuntime() {
52
79
  runtimeFacade = createdRuntime;
53
80
  createdRuntime.context.toolRuntime.registerToolsExtension('mcp', getMcpTools());
54
81
  await createdRuntime.start();
82
+ // 登记到全局工作空间注册表:终端每进一个目录都会登记(src/workspace/index.ts),
83
+ // host 以前不登记 —— 于是 work-app 的工作空间在注册表里永远缺席,
84
+ // 「跨工作空间列会话」看不到它,而终端也看不到 work-app 里建的会话。
85
+ registerWorkspace(process.cwd());
55
86
  if (closing)
56
87
  return;
57
- // Supervised Worker:`ask_human` 不再是「不可用」,而是走同一条审批通道转给控制面。
58
- // 只在受监管时注入——普通 Host(work-app)本来就有人盯着面板,不该多绕一层 NDJSON。
59
- if (process.env.MOCODE_SUPERVISED_WORKER === '1') {
60
- setAskHumanHandler((request) => waitForApproval(activeRun?.id ?? '', {
61
- type: request.options.length > 0 ? 'choice' : 'input',
62
- title: request.question,
63
- ...(request.options.length > 0
64
- ? {
65
- options: request.options.map((item) => ({
66
- label: item.label,
67
- ...(item.detail ? { detail: item.detail } : {}),
68
- })),
69
- }
70
- : {}),
71
- ...(request.context ? { detail: request.context } : {}),
72
- allowCustom: false,
73
- }, 'ask_human'));
88
+ // 启动期身份归一 + 记忆 GC:与 REPL 同序(见 src/repl/runtime.ts 的 startRepl)。
89
+ // 顺序有意义——先归一把画像碎片并入 person-primary,About you 段才渲染得出来;
90
+ // GC 放在归一之后。两者都 best-effort,失败不能拖垮 host 启动。
91
+ initPersona(isMemoryEnabled());
92
+ if (isMemoryEnabled()) {
93
+ try {
94
+ gcMemories();
95
+ }
96
+ catch {
97
+ /* best-effort */
98
+ }
74
99
  }
100
+ // `ask_human` 一律走审批通道转给控制面 —— 不能只在 supervised 模式下注入。
101
+ //
102
+ // 旧代码把注入锁在 `MOCODE_SUPERVISED_WORKER === '1'` 里,注释说「普通 Host 有人盯着面板」,
103
+ // 但普通 Host 压根没有面板:没有 handler 时 ask_human 落到 promptIntervention,
104
+ // 而 host 进程没有 layout,layout.isActive() 为 false,于是走「非 TTY 降级」分支
105
+ // **自动选第一项并当作已答复返回给模型**(src/ui/intervention.ts:113-124)。
106
+ // 结果是模型「问」了、用户从没看见、却已经被答复——最坏情况下选中的是危险选项。
107
+ // 现在两种模式同一条通道,差别只在 who 回答(supervised 由父 agent,普通由 GUI)。
108
+ setAskHumanHandler((request) => waitForApproval(activeRun?.id ?? '', {
109
+ type: request.options.length > 0 ? 'choice' : 'input',
110
+ title: request.question,
111
+ ...(request.options.length > 0
112
+ ? {
113
+ options: request.options.map((item) => ({
114
+ label: item.label,
115
+ ...(item.detail ? { detail: item.detail } : {}),
116
+ })),
117
+ }
118
+ : {}),
119
+ ...(request.context ? { detail: request.context } : {}),
120
+ // 允许控制面在选项之外输入自由文本:ask_human 的常见形态是「给我一个值」,
121
+ // 把用户限制在模型预设的选项里,等于逼他选一个错的。
122
+ allowCustom: true,
123
+ }, 'ask_human'));
75
124
  const runtimeConfig = createdRuntime.context.config;
76
125
  emit('runtime_ready', {
126
+ // 握手回执里必须带版本:客户端据此判断「我发的新命令它认不认」,而不是靠猜。
127
+ protocolVersion: HOST_PROTOCOL_VERSION,
77
128
  projectRoot: createdRuntime.context.sandboxRoot,
78
129
  provider: runtimeConfig.provider,
79
130
  promptCache: runtimeConfig.provider === 'anthropic' && runtimeConfig.anthropicPromptCache,
@@ -85,17 +136,70 @@ async function initializeRuntime() {
85
136
  })();
86
137
  return initialized;
87
138
  }
88
- function systemMessage() {
89
- return effectiveSystemPrompt(buildBasePrompt(sessionId));
139
+ /**
140
+ * 当前模式下的系统提示(history[0] 的唯一来源)。
141
+ *
142
+ * 段组合的单一事实源在 src/prompt/system-prompt.ts —— REPL 与 stdio host 走同一个函数。
143
+ * 此前 host 自己拼了一版、漏掉 About you / Memory Index / Episode / graph hint / plan 段,
144
+ * 结果是「记忆开关打开、库也写满了,工作台里的模型却从没见过」。
145
+ * planMode 现读:模式切换要立刻反映在下一步请求的系统提示里。
146
+ */
147
+ function currentSystemMessage() {
148
+ const planMode = (runtimeFacade?.context.getAgentMode() ?? 'auto') === 'plan';
149
+ return buildSystemMessage({ sessionId, planMode });
150
+ }
151
+ /** 当前是否 plan 模式(现读,不缓存:切换后下一步请求就要看到)。 */
152
+ function isPlanMode() {
153
+ return (runtimeFacade?.context.getAgentMode() ?? 'auto') === 'plan';
154
+ }
155
+ /**
156
+ * 切换 agent 模式。与 REPL 的 cycleMode 同语义(src/repl/runtime.ts:534-549):
157
+ * ① 改模式状态;② 重写 history[0] 的系统提示(plan 段随之出现/消失);
158
+ * ③ 回 `mode_changed` 让控制面刷新指示。
159
+ *
160
+ * 为什么必须重写 history[0]:system 提示是对话里唯一常驻的指令位,plan 约束写在那里
161
+ * 模型才会在**下一步**就只读;只改状态而提示还停在 auto,模型会继续写文件。
162
+ * 为什么模式只能由用户面触发:模型不该给自己解锁(见 src/agent/mode.ts 的注释)。
163
+ */
164
+ function setMode(command) {
165
+ if (closing)
166
+ return;
167
+ if (!runtimeFacade) {
168
+ // 还没初始化:先记为待生效,启动后再落。这里直接初始化更简单,但会拖慢首条命令;
169
+ // 客户端在 start 后就发 set_mode,initializeRuntime 已在跑,await 它即可。
170
+ void initializeRuntime()
171
+ .then(() => setMode(command))
172
+ .catch(() => undefined);
173
+ return;
174
+ }
175
+ const previous = runtime().context.setAgentMode(command.mode);
176
+ if (sessionId) {
177
+ history[0] = { role: 'system', content: currentSystemMessage() };
178
+ }
179
+ emit('mode_changed', { mode: command.mode, previous }, command.id);
180
+ }
181
+ /**
182
+ * R18 每轮静默召回段。开关求与的写法与 REPL 一致(src/agent/index.ts 的 runAgent):
183
+ * 记忆总开关 × 召回子开关。排除 memoryTailChangedIds() —— 那批已由 R17 尾注播报。
184
+ */
185
+ function turnRecallFor(prompt) {
186
+ if (!isMemoryEnabled() || !isTurnRecallEnabled())
187
+ return '';
188
+ return buildTurnRecallSection(prompt, { excludeIds: memoryTailChangedIds() });
90
189
  }
91
190
  function createSession() {
92
191
  const activeRuntime = runtime();
93
192
  sessionId = activeRuntime.session.create();
94
- activeRuntime.context.setAgentMode('auto');
95
- history = [{ role: 'system', content: systemMessage() }];
193
+ // 不在这里重置模式:host 的模式是进程级状态、由控制面通过 set_mode 管理,
194
+ // 新建会话不该顺手把用户刚切的 plan 打回 auto(终端里 /clear 也不改模式)。
195
+ // 首次启动的 auto 由 createRuntime({ initialMode: 'auto' }) 保证。
196
+ history = [{ role: 'system', content: currentSystemMessage() }];
96
197
  queryHistory = [];
97
198
  lastToolGroups = [];
98
- contextState = createContextState();
199
+ contextState = createContextState({ archiveHistory: true });
200
+ // R17 基线必须跟着「会话真正开始」这一刻拍:/clear、resume 之后旧基线作废,
201
+ // 否则新会话第一条消息会把上一会话的改动当成「本轮新增」播报一遍。
202
+ captureMemoryBaseline();
99
203
  }
100
204
  function restoreSession(id) {
101
205
  const activeRuntime = runtime();
@@ -106,18 +210,25 @@ function restoreSession(id) {
106
210
  activeRuntime.context.setAgentMode('auto');
107
211
  history = [...loaded.history];
108
212
  if (history[0]?.role === 'system')
109
- history[0] = { role: 'system', content: systemMessage() };
213
+ history[0] = { role: 'system', content: currentSystemMessage() };
110
214
  else
111
- history.unshift({ role: 'system', content: systemMessage() });
215
+ history.unshift({ role: 'system', content: currentSystemMessage() });
112
216
  queryHistory = [...(loaded.queryHistory ?? [])];
113
217
  lastToolGroups = [...(loaded.lastToolGroups ?? [])];
114
- contextState = createContextState();
218
+ contextState = createContextState({ archiveHistory: true });
219
+ captureMemoryBaseline();
115
220
  return true;
116
221
  }
117
222
  function persistSession() {
118
223
  if (!sessionId)
119
224
  return;
120
- runtime().session.save(history, sessionId, queryHistory, lastToolGroups);
225
+ // 工具批提交后的检查点仍处在 Runtime.run 内,runtime.session.save 的 assertIdle
226
+ // 会把它拒掉。host 每个任务独占一个 Runtime,这里沿同一条同步调用链写该 Runtime
227
+ // 自己的 store;不能为了绕过闸门另建全局 SessionStore,否则会写到别的工作区。
228
+ const activeRuntime = runtime();
229
+ activeRuntime.context.sessionStore.setCurrentSessionId(sessionId);
230
+ activeRuntime.context.sessionStore.save(history, sessionId, queryHistory, lastToolGroups);
231
+ activeRuntime.context.rollbackStore.persistSnapshots(sessionId);
121
232
  }
122
233
  function prepareSession(requestedSessionId) {
123
234
  if (!requestedSessionId) {
@@ -141,27 +252,141 @@ function waitForApproval(runId, request, kind = 'permission') {
141
252
  title: request.title,
142
253
  detail: request.detail ?? '',
143
254
  options: (request.options ?? []).map((option) => (typeof option === 'string' ? option : option.label)),
255
+ // 下面四项以前都没过协议,导致控制面只能「猜」:
256
+ // type — choice / input。input 形态没有选项,必须给输入框;
257
+ // allowCustom — 默认 true,控制面据此决定是否露出「其他…」输入;
258
+ // defaultIndex — 危险操作把它落在「拒绝」上;不传就是默认高亮首项,
259
+ // 用户顺手回车就放行了 rm -rf;
260
+ // seed — input 形态的预填文本(例如建议的路径)。
261
+ type: request.type,
262
+ allowCustom: request.allowCustom !== false,
263
+ defaultIndex: request.defaultIndex ?? 0,
264
+ seed: request.seed ?? '',
144
265
  }, runId);
145
266
  return new Promise((resolve) => approvals.set(approvalId, { resolve, runId }));
146
267
  }
268
+ /**
269
+ * 把 agent 的展示接缝翻译成 NDJSON 事件。
270
+ *
271
+ * 每个钩子的取舍标准是「终端里看得见、而 GUI 不转发就等于没有」:
272
+ * - onModelRetry:退避重试期间终端有状态行;不转发的话用户在 GUI 面对的是几十秒静止。
273
+ * - onLiveUsage:底栏上下文进度条的实时来源;只在轮末给一次百分比会让人以为卡住。
274
+ * - onImageRelief:图片压缩要几十秒,终端有「正在压缩图片…」;GUI 无反馈就是假死。
275
+ * - onToolOutput:长命令(build/test)的流式输出,终端边跑边出,GUI 只能等最后一坨。
276
+ * - onNoReply / onMaxSteps:两种「没内容但有结局」的终止,必须各自可见。
277
+ * onToolDone / onTextEnd / onChatDone / onToolBatchEnd / onHistoryRebuilt 是终端的行排版细节
278
+ * (批次收口、换行归一、spinner 停转),GUI 用 DOM 结构表达,不需要镜像。
279
+ */
147
280
  function hooksFor(runId) {
148
281
  return {
149
282
  onStepStart: () => emit('status', { value: 'thinking' }, runId),
150
283
  onText: (text) => emit('text_delta', { text }, runId),
151
284
  onToolCall: (name) => emit('status', { value: 'preparing_tool', tool: name }, runId),
285
+ // 用户消息追加后、第一批工具提交后各保存一次。崩溃留下的半个模型回答只由
286
+ // work-app 的 UI 日志回放,绝不能伪装成完整 assistant 消息写入可续聊的会话。
287
+ onCheckpoint: () => persistSession(),
152
288
  onToolHeader: (tool) => emit('tool_started', { id: tool.id, name: tool.name, arguments: tool.arguments }, runId),
153
289
  onToolStart: (name) => emit('status', { value: 'running_tool', tool: name }, runId),
154
- onToolResult: (tool, output) => emit('tool_completed', { id: tool.id, name: tool.name, output }, runId),
290
+ onToolOutput: (tool, chunk) => emit('tool_output', { id: tool.id, name: tool.name, chunk }, runId),
291
+ onToolResult: (tool, output, _parsed, preWriteOld, editStartLine, multiHunks, outcome) => emit('tool_completed', {
292
+ id: tool.id,
293
+ name: tool.name,
294
+ output,
295
+ // 结构化结局:GUI 靠它区分成功/失败/被拒/中断、显示改动文件数,
296
+ // 而不是在 output 上嗅探 '错误:' / 'CHANGE_CONFLICT' 这类字符串前缀。
297
+ ...(outcome
298
+ ? {
299
+ status: outcome.status,
300
+ code: outcome.code,
301
+ retryable: outcome.retryable,
302
+ changedFiles: outcome.changedFiles ?? [],
303
+ ...(outcome.durationMs != null ? { durationMs: outcome.durationMs } : {}),
304
+ ...(outcome.changeSet
305
+ ? { changeSetId: outcome.changeSet.id, changeSetFiles: outcome.changeSet.changedFiles }
306
+ : {}),
307
+ ...(outcome.usage ? { nestedUsage: outcome.usage } : {}),
308
+ }
309
+ : {}),
310
+ // 真实行号:终端 diff 头行的行号来自执行前快照(src/agent/tool-helpers.ts:readDiffContext)。
311
+ // 不转发的话 GUI 只能用「相对本次改动的 1」重算,与终端对不上、也看不出改在文件哪一段。
312
+ ...(editStartLine > 1 ? { editStartLine } : {}),
313
+ ...(multiHunks && multiHunks.length > 0 ? { multiHunks } : {}),
314
+ // write_file 覆盖写:旧内容就是 diff 的「删除侧」。超过上限不转发(IPC 与 DOM 都吃不消),
315
+ // GUI 退回「全部按新增展示」,与终端 replay 同策略。
316
+ ...(preWriteOld != null && preWriteOld.length <= MAX_FORWARDED_OLD_BYTES ? { preWriteOld } : {}),
317
+ }, runId),
318
+ onModelRetry: (info) => emit('model_retry', { attempt: info.attempt, nextAttempt: info.nextAttempt, waitMs: info.waitMs, code: info.code }, runId),
319
+ onLiveUsage: (usage) => {
320
+ // usage.totalTokens 是本轮累计消耗,绝不是上下文占用;详情统一读当前 prompt 快照。
321
+ emit('live_usage', { ...usage, contextUsage: contextUsageSnapshot() }, runId);
322
+ },
323
+ // 自动压缩:终端有「压缩中」spinner + 压缩行,GUI 什么都看不到 —— 用户只会发现
324
+ // 上下文百分比莫名掉了一截。所以 start 立刻给状态行,done 在会话流里留一条系统行。
325
+ onCompactProgress: (event) => {
326
+ if (event.phase === 'start') {
327
+ emit('context_compacting', { manual: event.manual, ...(event.focus ? { focus: event.focus } : {}) }, runId);
328
+ return;
329
+ }
330
+ // 失败/中断只收状态行:没压成功就不该在会话流里留一条「已压缩」。
331
+ if (event.failed || event.aborted || !event.compacted) {
332
+ emit('context_compacting_done', { failed: event.failed === true, aborted: event.aborted === true }, runId);
333
+ return;
334
+ }
335
+ const usage = contextUsageSnapshot();
336
+ emit('context_compacted', {
337
+ manual: event.manual,
338
+ summarized: event.summarized,
339
+ reason: event.reason,
340
+ historyRebuilt: event.historyRebuilt === true,
341
+ beforeTokens: event.estimateBefore,
342
+ afterTokens: event.estimateAfter,
343
+ usagePercent: usage.percent,
344
+ contextUsage: usage,
345
+ contextWindow: runtime().context.config.contextWindowTokens,
346
+ }, runId);
347
+ },
348
+ onImageRelief: (info) => emit('image_relief', { ...info }, runId),
349
+ onNoReply: () => emit('no_reply', {}, runId),
350
+ onMaxSteps: () => emit('max_steps', {}, runId),
155
351
  onAbort: () => emit('run_aborted', {}, runId),
156
352
  onDone: (elapsedMs, usage) => emit('run_finished', { elapsedMs, usage }, runId),
157
353
  };
158
354
  }
355
+ function inputForRun(command) {
356
+ return command.attachments?.length
357
+ ? [
358
+ ...(command.prompt ? [{ type: 'text', text: command.prompt }] : []),
359
+ ...command.attachments.flatMap((attachment) => {
360
+ if (attachment.dataUrl)
361
+ return [{ type: 'image_url', name: attachment.name, image_url: { url: attachment.dataUrl } }];
362
+ if (typeof attachment.text !== 'string')
363
+ return [];
364
+ // name/attachment/truncated 是会话回放元数据,transport 发送前统一移除。
365
+ return [
366
+ {
367
+ type: 'text',
368
+ name: attachment.name,
369
+ attachment: true,
370
+ truncated: attachment.truncated === true,
371
+ text: `用户附件 ${JSON.stringify(attachment.name)} 的提取文本如下。${attachment.truncated ? '(内容已截断,仅提供前 100000 字符)' : ''}\n\n${attachment.text}`,
372
+ },
373
+ ];
374
+ }),
375
+ ]
376
+ : command.prompt;
377
+ }
159
378
  async function run(command) {
160
379
  if (closing)
161
380
  return;
162
- if (activeRun)
163
- return error('An agent run is already active for this project.', command.id);
164
- if (!command.prompt.trim())
381
+ if (activeRun) {
382
+ if (activeRun.id !== command.id || activeRun.controller.signal.aborted)
383
+ return error('The active run cannot accept this message.', command.id);
384
+ activeRun.pending.push(inputForRun(command));
385
+ queryHistory.push(command.prompt);
386
+ emit('message_received', { pending: activeRun.pending.length }, command.id);
387
+ return;
388
+ }
389
+ if (!command.prompt.trim() && !command.attachments?.length)
165
390
  return;
166
391
  let toolPolicy;
167
392
  try {
@@ -174,17 +399,13 @@ async function run(command) {
174
399
  // 每个被接受的 stdio run 都是真实用户 turn;在路由与 Agent 执行前清除上一轮 skill deny。
175
400
  clearSkillActivation();
176
401
  const controller = new AbortController();
177
- activeRun = { id: command.id, controller };
402
+ activeRun = { id: command.id, controller, pending: [] };
178
403
  queryHistory.push(command.prompt);
179
- const userInput = command.attachments?.length
180
- ? [
181
- { type: 'text', text: command.prompt },
182
- ...command.attachments.map((attachment) => ({
183
- type: 'image_url',
184
- image_url: { url: attachment.dataUrl },
185
- })),
186
- ]
187
- : command.prompt;
404
+ // 首个模型请求前也要有可恢复的用户轮。run-coordinator 的 cancellation checkpoint
405
+ // 是内存快照、不会调用 onCheckpoint;这里追加 user 后再落盘,避免首轮崩溃只剩侧栏标题。
406
+ const userInput = inputForRun(command);
407
+ history.push({ role: 'user', content: userInput });
408
+ persistSession();
188
409
  emit('run_started', {
189
410
  sessionId,
190
411
  projectRoot: process.cwd(),
@@ -194,10 +415,13 @@ async function run(command) {
194
415
  attachments: command.attachments?.map((attachment) => attachment.name) ?? [],
195
416
  }, command.id);
196
417
  const previousGroups = [...lastToolGroups];
418
+ // planMode 现读而不是硬编码:plan 模式下路由器要拿到 "PLAN" 语境(只挑探查类能力),
419
+ // 工具面也要走 ToolPolicyController.snapshot(true) 的只读过滤(PLAN_DISABLED_TOOLS)。
420
+ const planMode = isPlanMode();
197
421
  const decision = await routeToolGroups({
198
422
  input: command.prompt,
199
423
  previousGroups,
200
- planMode: false,
424
+ planMode,
201
425
  attachmentNames: command.attachments?.map((attachment) => attachment.name),
202
426
  signal: controller.signal,
203
427
  transport: runtime().context.modelTransport,
@@ -221,7 +445,7 @@ async function run(command) {
221
445
  reason: decision.reason,
222
446
  latencyMs: decision.latencyMs,
223
447
  fallback: decision.fallback,
224
- planMode: false,
448
+ planMode,
225
449
  };
226
450
  emit('tool_route', initialToolRoute, command.id);
227
451
  const result = await runtime().run({
@@ -229,6 +453,9 @@ async function run(command) {
229
453
  turnLabel: command.prompt.split('\n')[0]?.slice(0, 40) ?? command.prompt.slice(0, 40),
230
454
  history,
231
455
  userInput,
456
+ // 上面已把用户轮写入首个持久化检查点,core 不能再 append 一次。
457
+ continueFromHistory: true,
458
+ drainUserMessages: () => activeRun?.pending.splice(0) ?? [],
232
459
  signal: controller.signal,
233
460
  hooks: hooksFor(command.id),
234
461
  contextState,
@@ -237,9 +464,15 @@ async function run(command) {
237
464
  traceContext: { sessionId },
238
465
  onTraceEvent: appendCurrentSessionTraceEvent,
239
466
  permissionPrompt: (request) => waitForApproval(command.id, request),
467
+ // R17 尾注 + R18 静默召回:与 REPL 同口径(src/agent/index.ts 的 runAgent)。
468
+ // 两者都走 ephemeral 段,不重建 history[0],前缀缓存不受影响;
469
+ // 排除 memoryTailChangedIds() 是刻意的——那批条目已由尾注播报,同一轮不重复讲。
470
+ memoryTail: buildMemoryTailSection(isMemoryEnabled()),
471
+ memoryRecall: turnRecallFor(command.prompt),
240
472
  });
241
473
  lastToolGroups = toolPolicy.groupNames;
242
474
  persistSession();
475
+ const contextUsage = contextUsageSnapshot();
243
476
  emit('run_completed', {
244
477
  sessionId,
245
478
  completed: result.completed,
@@ -248,7 +481,8 @@ async function run(command) {
248
481
  usage: result.usage,
249
482
  provider: runtime().context.config.provider,
250
483
  promptCache: runtime().context.config.provider === 'anthropic' && runtime().context.config.anthropicPromptCache,
251
- usagePercent: Math.round(contextUsagePercent() * 100),
484
+ usagePercent: contextUsage.percent,
485
+ contextUsage,
252
486
  contextWindow: runtime().context.config.contextWindowTokens,
253
487
  }, command.id);
254
488
  }
@@ -277,6 +511,13 @@ async function run(command) {
277
511
  approvals.delete(approvalId);
278
512
  }
279
513
  }
514
+ // Accepted messages must survive cancellation or a step-limit exit before consumption.
515
+ const remaining = activeRun?.pending.splice(0) ?? [];
516
+ if (remaining.length > 0) {
517
+ for (const content of remaining)
518
+ history.push({ role: 'user', content });
519
+ persistSession();
520
+ }
280
521
  activeRun = null;
281
522
  }
282
523
  }
@@ -293,11 +534,9 @@ function cancel(command) {
293
534
  }
294
535
  emit('cancelling', {}, command.id);
295
536
  }
296
- /** 计算当前上下文用量百分比(不含 system prompt),用于 UI 展示。 */
297
- function contextUsagePercent() {
298
- const dialog = history.filter((m) => m.role !== 'system');
299
- const est = estimateMessagesTokens(dialog);
300
- return Math.min(1, est / runtime().context.config.contextWindowTokens);
537
+ /** 与终端底栏同源:system + 对话 + 实际工具 schema + ephemeral。 */
538
+ function contextUsageSnapshot() {
539
+ return measureContextUsage(history, runtime().context.config.contextWindowTokens, contextState);
301
540
  }
302
541
  async function compact(command) {
303
542
  if (closing)
@@ -311,6 +550,7 @@ async function compact(command) {
311
550
  if (!sessionId)
312
551
  createSession();
313
552
  emit('status', { value: 'compacting' }, command.id);
553
+ emit('context_compacting', { manual: true, ...(command.focus ? { focus: command.focus } : {}) }, command.id);
314
554
  const activeRuntime = runtime();
315
555
  const log = await activeRuntime.compact(history, {
316
556
  focus: command.focus,
@@ -319,12 +559,28 @@ async function compact(command) {
319
559
  signal: shutdownController.signal,
320
560
  });
321
561
  persistSession();
322
- const pct = contextUsagePercent();
562
+ // 旧实测锚点属于压缩前请求,不能跨摘要边界继续外推。
563
+ contextState.promptAnchor = undefined;
564
+ const usage = contextUsageSnapshot();
565
+ // 与自动路径同一个事件形状:GUI 的会话流据此留一条「已压缩」系统行(切走再回来还在)。
566
+ // compact_done 保留给旧客户端的 toast,两条事件在这里是有意的分工,不是重复。
567
+ emit('context_compacted', {
568
+ manual: true,
569
+ summarized: log.compactDetail?.reason === 'summarize',
570
+ reason: log.compactDetail?.reason,
571
+ historyRebuilt: log.historyMutation === 'rebuild',
572
+ beforeTokens: log.compactDetail?.estimateBefore,
573
+ afterTokens: log.compactDetail?.estimateAfter,
574
+ usagePercent: usage.percent,
575
+ contextUsage: usage,
576
+ contextWindow: runtime().context.config.contextWindowTokens,
577
+ }, command.id);
323
578
  emit('compact_done', {
324
579
  compacted: log.compactHistoryCalled,
325
580
  beforeTokens: log.compactDetail?.estimateBefore,
326
581
  afterTokens: log.compactDetail?.estimateAfter,
327
- usagePercent: Math.round(pct * 100),
582
+ usagePercent: usage.percent,
583
+ contextUsage: usage,
328
584
  contextWindow: runtime().context.config.contextWindowTokens,
329
585
  }, command.id);
330
586
  }
@@ -340,14 +596,785 @@ function resolveApproval(command) {
340
596
  approvals.delete(command.approvalId);
341
597
  waiter.resolve({ action: command.action, value: command.value });
342
598
  }
599
+ /* ────────────────────────────────────────────────────────────────
600
+ * 面板命令:会话 / 回滚 / 改动 / 用量 / 记忆 / 设置
601
+ *
602
+ * 这些在终端里各是一条斜杠命令(/sessions、/rollback、/diff、/usage、/memory、/effort…),
603
+ * 命令体里都是「取数据 → 排版成终端文本」两段。这里只复刻**取数据**那一段,
604
+ * 数据以结构化 payload 回给 GUI,由 GUI 自己排版 —— 别把终端文案搬到协议里,
605
+ * 否则渲染层只能原样打印一行行等宽文本,点什么都没法交互。
606
+ *
607
+ * 所有 handler 都遵守同一条:出错用 error(msg, requestId),**不抛**。
608
+ * 抛出去会被 stdio 主循环当成未处理拒绝,客户端只看到「没有响应」。
609
+ * ──────────────────────────────────────────────────────────────── */
610
+ /** 面板命令统一前置:host 还没起来就先 etc 起来;运行中则拒绝(读会话/回滚都要求空闲)。 */
611
+ async function withRuntime(commandId, allowRunning) {
612
+ await initializeRuntime();
613
+ if (closing)
614
+ return false;
615
+ if (!allowRunning && activeRun) {
616
+ error('有正在运行的任务,请先停止后再操作。', commandId);
617
+ return false;
618
+ }
619
+ return true;
620
+ }
621
+ /** 会话元数据 → 协议载荷(只带 GUI 用得上的字段,history 另走磁盘回放)。 */
622
+ function sessionMetaPayload(meta) {
623
+ return {
624
+ id: meta.id,
625
+ createdAt: meta.createdAt,
626
+ model: meta.model,
627
+ firstUser: meta.firstUser,
628
+ ...(meta.archived ? { archived: true } : {}),
629
+ current: meta.id === sessionId,
630
+ };
631
+ }
632
+ /** host 的工作区根:host 以 `cwd = 工作空间根` 启动(见 initializeRuntime 的 sandboxRoot)。 */
633
+ function hostWorkspaceRoot() {
634
+ return path.resolve(process.cwd());
635
+ }
636
+ /**
637
+ * 要扫描会话的工作空间清单(按最近使用倒序)。
638
+ *
639
+ * 当前工作空间永远排第一并强制包含:注册表可能还没登记它(例如 work-app 首次启动,
640
+ * 或注册表被清空),少了它就会出现「终端能看到、GUI 看不到」的错位。
641
+ */
642
+ function sessionWorkspaceRoots() {
643
+ const current = hostWorkspaceRoot();
644
+ const rows = readWorkspaceRegistry().map((entry) => ({
645
+ root: path.resolve(entry.root),
646
+ name: entry.name || path.basename(entry.root),
647
+ lastSeen: entry.lastSeen,
648
+ }));
649
+ const key = (root) => root.toLowerCase();
650
+ const currentRow = rows.find((row) => key(row.root) === key(current));
651
+ const rest = rows.filter((row) => key(row.root) !== key(current));
652
+ return [{ root: current, name: path.basename(current) || current, lastSeen: currentRow?.lastSeen ?? '' }, ...rest];
653
+ }
654
+ /**
655
+ * 跨工作空间聚合会话列表。
656
+ *
657
+ * 每个工作空间一个独立 SessionStore(各自读 `<root>/.mocode/sessions`),
658
+ * 终端在 F:\mocode 留下的会话与 work-app 在 %APPDATA% 留下的会话因此同列。
659
+ * 单次全量扫描实测 ≈1.3s(47 个工作空间 / 376 条),面板级操作可以接受;
660
+ * 注册表里会话数为 0 的工作空间直接跳过,不白扫临时目录。
661
+ */
662
+ function listSessionsEverywhere(limit) {
663
+ const current = hostWorkspaceRoot();
664
+ const registered = new Map(readWorkspaceRegistry().map((entry) => [path.resolve(entry.root).toLowerCase(), entry.sessions]));
665
+ const out = [];
666
+ for (const workspace of sessionWorkspaceRoots()) {
667
+ const known = registered.get(workspace.root.toLowerCase());
668
+ if (known === 0)
669
+ continue;
670
+ const sessionsRoot = path.join(workspace.root, '.mocode', 'sessions');
671
+ if (!existsSync(sessionsRoot))
672
+ continue;
673
+ let metas;
674
+ try {
675
+ metas = new SessionStore({ sessionsRoot }).list(limit);
676
+ }
677
+ catch {
678
+ continue; // 单个工作空间读不了不能拖垮整张列表
679
+ }
680
+ const isCurrent = workspace.root.toLowerCase() === current.toLowerCase();
681
+ for (const meta of metas) {
682
+ out.push({
683
+ ...sessionMetaPayload(meta),
684
+ workspace: workspace.root,
685
+ workspaceName: workspace.name,
686
+ // 只有当前工作空间里的会话可能是「当前会话」。
687
+ current: isCurrent && meta.id === sessionId,
688
+ });
689
+ }
690
+ }
691
+ out.sort((left, right) => (String(left.createdAt) < String(right.createdAt) ? 1 : -1));
692
+ return out.slice(0, limit);
693
+ }
694
+ /**
695
+ * 会话面板:list / search / resume / fork / workspaces,
696
+ * 对齐终端 /sessions、/ssearch、/resume、/fork。
697
+ *
698
+ * resume 会**切换 host 内存里的当前会话**(后续 run 续在这个会话上),
699
+ * fork 只产出一个副本、不动当前会话 —— 与终端语义一致,别把两者合并。
700
+ */
701
+ async function sessionsCommand(command) {
702
+ // workspaces 只读全局注册表,不需要 runtime:GUI 在没有任务时也要能问「有哪些工作空间」。
703
+ if (command.action === 'workspaces') {
704
+ const current = hostWorkspaceRoot();
705
+ emit('sessions_report', {
706
+ action: 'workspaces',
707
+ currentWorkspace: current,
708
+ workspaces: sessionWorkspaceRoots().map((workspace) => ({
709
+ root: workspace.root,
710
+ name: workspace.name,
711
+ lastSeen: workspace.lastSeen,
712
+ sessionCount: (() => {
713
+ try {
714
+ return readdirSync(path.join(workspace.root, '.mocode', 'sessions'), { withFileTypes: true }).filter((entry) => entry.isDirectory() && /^\d{8}-\d{6}(?:-\d{3}-[a-f0-9]{8})?$/.test(entry.name)).length;
715
+ }
716
+ catch {
717
+ return 0;
718
+ }
719
+ })(),
720
+ isCurrent: workspace.root.toLowerCase() === current.toLowerCase(),
721
+ })),
722
+ }, command.id);
723
+ return;
724
+ }
725
+ // list / search 是只读的:任务正在跑时也要能查(终端 /sessions 同理不打断 run)。
726
+ // resume / fork 会换当前会话或写磁盘,必须等这一轮跑完。
727
+ const readOnly = command.action === 'list' || command.action === 'search';
728
+ if (!(await withRuntime(command.id, readOnly)))
729
+ return;
730
+ const activeRuntime = runtime();
731
+ try {
732
+ if (command.action === 'list') {
733
+ const limit = command.limit ?? 50;
734
+ emit('sessions_report', {
735
+ action: 'list',
736
+ scope: command.scope ?? 'current',
737
+ // scope=all 才扫全盘;缺省与终端 /sessions 一致,只看本工作空间。
738
+ sessions: command.scope === 'all'
739
+ ? listSessionsEverywhere(limit)
740
+ : activeRuntime.session.list(limit).map(sessionMetaPayload),
741
+ currentSessionId: sessionId,
742
+ currentWorkspace: hostWorkspaceRoot(),
743
+ }, command.id);
744
+ return;
745
+ }
746
+ if (command.action === 'search') {
747
+ const query = (command.query ?? '').trim();
748
+ if (!query)
749
+ return error('搜索关键词为空。', command.id);
750
+ emit('sessions_report', {
751
+ action: 'search',
752
+ query,
753
+ // 归档命中即使 purged 也保留(只能看摘要)—— GUI 据此禁用「恢复」按钮。
754
+ hits: activeRuntime.session.searchArchive(query, command.limit ?? 10).map((hit) => ({ ...hit })),
755
+ currentSessionId: sessionId,
756
+ }, command.id);
757
+ return;
758
+ }
759
+ if (command.action === 'resume') {
760
+ const target = command.sessionId?.trim();
761
+ if (!target)
762
+ return error('缺少要恢复的会话 id。', command.id);
763
+ if (target === sessionId) {
764
+ emit('session_resumed', { sessionId, unchanged: true }, command.id);
765
+ return;
766
+ }
767
+ if (!restoreSession(target))
768
+ return error(`会话 ${target} 无法恢复(文件缺失或内容为空)。`, command.id);
769
+ emit('session_resumed', {
770
+ sessionId,
771
+ messages: history.filter((message) => message.role !== 'system').length,
772
+ // 渲染层切会话要重放历史:把来源告诉它,由它决定走磁盘回放还是等 run_started。
773
+ source: 'resume',
774
+ }, command.id);
775
+ return;
776
+ }
777
+ // fork:先把内存里最新对话落盘,副本才包含尚未自动保存的尾部(与终端 /fork 同因)。
778
+ const sourceId = command.sessionId?.trim() || sessionId;
779
+ if (!sourceId)
780
+ return error('当前还没有会话可分叉。', command.id);
781
+ if (sourceId === sessionId && history.length > 1)
782
+ persistSession();
783
+ const newId = activeRuntime.session.fork(sourceId);
784
+ if (!newId)
785
+ return error(`会话 ${sourceId} 只有归档副本,无法分叉。`, command.id);
786
+ emit('session_forked', { sourceId, sessionId: newId }, command.id);
787
+ }
788
+ catch (cause) {
789
+ error(cause instanceof Error ? cause.message : String(cause), command.id);
790
+ }
791
+ }
792
+ /** 每轮改动(供回滚菜单展示「选这一轮会丢掉哪些文件」)。 */
793
+ function turnChangesPayload() {
794
+ const store = runtime().context.rollbackStore;
795
+ const turns = store.listTurns();
796
+ const snapshots = store.snapshotsSince(0);
797
+ return turns.map((turn, index) => {
798
+ // 选第 index 轮 = 放弃这一轮及之后的全部改动,所以文件面是「该轮及以后」的并集。
799
+ const byPath = new Map();
800
+ for (const snapshot of snapshots) {
801
+ if (snapshot.turnId < turn.turnId)
802
+ continue;
803
+ const entry = byPath.get(snapshot.path) ?? { path: snapshot.path, ops: [], snapshotAvailable: true };
804
+ if (snapshot.contentUnavailable)
805
+ entry.snapshotAvailable = false;
806
+ for (const op of snapshot.ops ?? ['file_change'])
807
+ if (!entry.ops.includes(op))
808
+ entry.ops.push(op);
809
+ byPath.set(snapshot.path, entry);
810
+ }
811
+ return {
812
+ index,
813
+ turnId: turn.turnId,
814
+ firstLine: turn.firstLine,
815
+ files: [...byPath.values()].sort((left, right) => left.path.localeCompare(right.path)),
816
+ };
817
+ });
818
+ }
819
+ /**
820
+ * 回滚:list 只读;apply 截断对话到第 turnIndex 轮之前,并**只**还原显式列出的文件。
821
+ *
822
+ * 文件还原默认一个都不做(revertFiles 空集),与终端 /rollback 的默认一致:
823
+ * 用户点「回滚对话」时,磁盘上的代码不该悄悄跟着变。
824
+ */
825
+ async function rollbackCommand(command) {
826
+ if (!(await withRuntime(command.id, false)))
827
+ return;
828
+ try {
829
+ if (command.action === 'list') {
830
+ if (!sessionId)
831
+ return emit('rollback_report', { action: 'list', turns: [], currentSessionId: '' }, command.id);
832
+ emit('rollback_report', { action: 'list', turns: turnChangesPayload(), currentSessionId: sessionId }, command.id);
833
+ return;
834
+ }
835
+ if (!sessionId)
836
+ return error('当前还没有会话,无法回滚。', command.id);
837
+ const turns = runtime().context.rollbackStore.listTurns();
838
+ const turnIndex = command.turnIndex ?? -1;
839
+ if (turnIndex < 0 || turnIndex >= turns.length) {
840
+ return error(`轮次下标无效:当前可回滚 ${turns.length} 轮。`, command.id);
841
+ }
842
+ const plan = runtime().rollback.plan(turnIndex, history);
843
+ const revertPaths = new Set();
844
+ const skipped = [];
845
+ for (const path of command.revertFiles ?? []) {
846
+ const change = plan.changes.find((item) => item.path === path);
847
+ // 快照不可用的文件(超出捕获预算)不能还原:静默跳过会让用户以为已经还原了。
848
+ if (change?.snapshotAvailable)
849
+ revertPaths.add(path);
850
+ else
851
+ skipped.push(path);
852
+ }
853
+ const result = runtime().rollback.apply(plan, history, revertPaths);
854
+ // 被撤销轮次的最终路由不能再当 continuation 基线(与终端 rollbackFlow 同处理)。
855
+ lastToolGroups = [];
856
+ persistSession();
857
+ captureMemoryBaseline();
858
+ emit('rollback_applied', {
859
+ turnIndex,
860
+ deletedMsgs: result.deletedMsgs,
861
+ revertedFiles: result.revertedFiles,
862
+ conflictedFiles: result.conflictedFiles,
863
+ skippedFiles: skipped,
864
+ messages: history.filter((message) => message.role !== 'system').length,
865
+ sessionId,
866
+ }, command.id);
867
+ }
868
+ catch (cause) {
869
+ error(cause instanceof Error ? cause.message : String(cause), command.id);
870
+ }
871
+ }
872
+ /** 快照 before → 文本(与终端 /diff 同口径:base64 解不动就当 null)。 */
873
+ function snapshotTextOf(snapshot) {
874
+ if (snapshot.before === null)
875
+ return null;
876
+ if (snapshot.encoding === 'base64') {
877
+ try {
878
+ return Buffer.from(snapshot.before, 'base64').toString('utf8');
879
+ }
880
+ catch {
881
+ return null;
882
+ }
883
+ }
884
+ return snapshot.before;
885
+ }
886
+ function readWorkspaceText(relativePath) {
887
+ try {
888
+ return readFileSync(path.resolve(runtime().context.sandboxRoot, relativePath), 'utf8');
889
+ }
890
+ catch {
891
+ return null;
892
+ }
893
+ }
894
+ /**
895
+ * 改动面板:list 给文件清单(含每文件是否可回滚),diff 给 unified diff 文本。
896
+ *
897
+ * `turn` 省略 = 最近一轮;给 0-based 下标 = 指定轮;≥ 轮数 = 全部累计(与终端 `/diff all` 等价)。
898
+ * 数据源是 rollback 快照而不是 git:没有 git 的目录也能看,且口径与回滚完全一致。
899
+ */
900
+ async function changesCommand(command) {
901
+ if (!(await withRuntime(command.id, true)))
902
+ return;
903
+ try {
904
+ const store = runtime().context.rollbackStore;
905
+ const turns = store.listTurns();
906
+ if (turns.length === 0) {
907
+ return emit('changes_report', { action: command.action, turn: null, files: [], empty: true }, command.id);
908
+ }
909
+ let minTurnIdExclusive;
910
+ let label;
911
+ let turnIndex;
912
+ if (command.turn === undefined) {
913
+ const last = turns[turns.length - 1];
914
+ minTurnIdExclusive = last.turnId - 1;
915
+ label = 'latest';
916
+ turnIndex = turns.length - 1;
917
+ }
918
+ else if (command.turn >= turns.length) {
919
+ minTurnIdExclusive = 0;
920
+ label = 'all';
921
+ turnIndex = null;
922
+ }
923
+ else {
924
+ minTurnIdExclusive = turns[command.turn].turnId - 1;
925
+ label = 'turn';
926
+ turnIndex = command.turn;
927
+ }
928
+ // 每 path 取范围内最早的 before(= 该范围开始前的状态),与 /diff 一致。
929
+ const byPath = new Map();
930
+ for (const snapshot of store.snapshotsSince(minTurnIdExclusive)) {
931
+ if (command.path && snapshot.path !== command.path)
932
+ continue;
933
+ const existing = byPath.get(snapshot.path);
934
+ const diffable = snapshot.kind === 'file' && snapshot.contentUnavailable !== true;
935
+ if (!existing || snapshot.turnId < existing.snapshot.turnId) {
936
+ byPath.set(snapshot.path, { snapshot, unavailable: (existing?.unavailable ?? false) || !diffable });
937
+ }
938
+ else if (!diffable) {
939
+ existing.unavailable = true;
940
+ }
941
+ }
942
+ const entries = [...byPath.entries()].sort(([left], [right]) => left.localeCompare(right));
943
+ const files = [];
944
+ for (const [relativePath, entry] of entries) {
945
+ const after = readWorkspaceText(relativePath);
946
+ const base = {
947
+ path: relativePath,
948
+ unavailable: entry.unavailable,
949
+ ops: entry.snapshot.ops ?? [],
950
+ };
951
+ if (command.action === 'list') {
952
+ files.push({ ...base, diffAvailable: !entry.unavailable });
953
+ continue;
954
+ }
955
+ if (entry.unavailable) {
956
+ files.push({ ...base, diff: '' });
957
+ continue;
958
+ }
959
+ const diff = unifiedFileDiff(relativePath, snapshotTextOf(entry.snapshot), after);
960
+ files.push({ ...base, diff, unchanged: diff === '' });
961
+ }
962
+ emit('changes_report', { action: command.action, label, turn: turnIndex, files }, command.id);
963
+ }
964
+ catch (cause) {
965
+ error(cause instanceof Error ? cause.message : String(cause), command.id);
966
+ }
967
+ }
968
+ /** 当前任务读内存中的实测锚点;旧任务只读自己的落盘 history,不篡改当前会话。 */
969
+ async function contextUsageCommand(command) {
970
+ if (!(await withRuntime(command.id, true)))
971
+ return;
972
+ try {
973
+ const targetSessionId = command.sessionId?.trim() || sessionId;
974
+ if (!targetSessionId)
975
+ return emit('context_usage', { contextUsage: null }, command.id);
976
+ if (targetSessionId === sessionId) {
977
+ return emit('context_usage', { sessionId: targetSessionId, contextUsage: contextUsageSnapshot() }, command.id);
978
+ }
979
+ const loaded = runtime().context.sessionStore.load(targetSessionId);
980
+ if (!loaded)
981
+ return emit('context_usage', { sessionId: targetSessionId, contextUsage: null }, command.id);
982
+ const restored = [...loaded.history];
983
+ const system = buildSystemMessage({ sessionId: targetSessionId, planMode: isPlanMode() });
984
+ if (restored[0]?.role === 'system')
985
+ restored[0] = { role: 'system', content: system };
986
+ else
987
+ restored.unshift({ role: 'system', content: system });
988
+ const historicalState = createContextState();
989
+ const policy = new ToolPolicyController({
990
+ groups: loaded.lastToolGroups ?? [],
991
+ tools: runtime().context.toolRuntime.tools,
992
+ });
993
+ historicalState.activeTools = policy.snapshot(isPlanMode()).tools;
994
+ const contextUsage = measureContextUsage(restored, runtime().context.config.contextWindowTokens, historicalState);
995
+ emit('context_usage', { sessionId: targetSessionId, contextUsage }, command.id);
996
+ }
997
+ catch (cause) {
998
+ error(cause instanceof Error ? cause.message : String(cause), command.id);
999
+ }
1000
+ }
1001
+ /**
1002
+ * 用量:session = 指定会话的 usage.jsonl;global = 跨工作空间账本(days 默认 7)。
1003
+ *
1004
+ * session 口径优先用命令带的 sessionId:面板命令由懒启动的 host 处理时,
1005
+ * 进程内 `sessionId` 还没建立(它只在 run 期间有效),只认进程内值就永远查不到。
1006
+ */
1007
+ async function usageCommand(command) {
1008
+ if (!(await withRuntime(command.id, true)))
1009
+ return;
1010
+ try {
1011
+ if (command.scope === 'session') {
1012
+ const targetSessionId = command.sessionId?.trim() || sessionId;
1013
+ if (!targetSessionId)
1014
+ return emit('usage_report', { scope: 'session', empty: true }, command.id);
1015
+ const raw = runtime().context.sessionStore.readUsage(targetSessionId);
1016
+ // usage.jsonl 是历史文件,坏行/旧字段都可能出现;只保留形状对得上的记录,
1017
+ // 否则 summarizeUsage 里会把 undefined 累加成 NaN,整张表变成 NaN。
1018
+ const records = raw.filter((row) => typeof row.inputTokens === 'number' &&
1019
+ typeof row.outputTokens === 'number' &&
1020
+ typeof row.cachedTokens === 'number');
1021
+ emit('usage_report', {
1022
+ scope: 'session',
1023
+ sessionId: targetSessionId,
1024
+ summary: summarizeUsage(records.map((row) => ({
1025
+ step: Number(row.step) || 0,
1026
+ phase: row.phase === 'compact' ? 'compact' : 'main',
1027
+ inputTokens: Number(row.inputTokens) || 0,
1028
+ outputTokens: Number(row.outputTokens) || 0,
1029
+ cachedTokens: Number(row.cachedTokens) || 0,
1030
+ reasoningTokens: Number(row.reasoningTokens) || 0,
1031
+ ...(typeof row.cacheCreationTokens === 'number' ? { cacheCreationTokens: row.cacheCreationTokens } : {}),
1032
+ }))),
1033
+ }, command.id);
1034
+ return;
1035
+ }
1036
+ const days = command.days ?? 7;
1037
+ const records = readGlobalUsage();
1038
+ // 热力图窗口 == 统计窗口:GUI 的 7 / 30 / 180 / 365 天选择决定日历跨度,一格永远是一天。
1039
+ // 只扫一遍、只算一次 —— 两段同源,省掉 GUI 第二趟往返,也不会出现「窗口与日历不一致」。
1040
+ const summary = summarizeGlobalUsage(records, days);
1041
+ emit('usage_report', {
1042
+ scope: 'global',
1043
+ days,
1044
+ summary,
1045
+ calendar: { fromDay: summary.fromDay, toDay: summary.toDay, days: summary.byDay },
1046
+ }, command.id);
1047
+ }
1048
+ catch (cause) {
1049
+ error(cause instanceof Error ? cause.message : String(cause), command.id);
1050
+ }
1051
+ }
1052
+ /** 记忆条目 → 载荷(正文截断:面板只列不读全文,全文用 show 动作取)。 */
1053
+ function memoryEntryPayload(entry) {
1054
+ return {
1055
+ id: entry.id,
1056
+ type: entry.type,
1057
+ name: entry.name,
1058
+ summary: entry.summary,
1059
+ status: entry.status,
1060
+ scope: entry.scope,
1061
+ pinned: entry.pinned,
1062
+ recallCount: entry.recallCount,
1063
+ updatedAt: entry.updatedAt,
1064
+ ...(entry.source?.file ? { seededFrom: entry.source.file } : {}),
1065
+ ...(entry.source?.session ? { fromSession: entry.source.session } : {}),
1066
+ };
1067
+ }
1068
+ /**
1069
+ * 记忆面板:对齐终端 /memory 全家桶。
1070
+ *
1071
+ * 写操作(confirm / drop / forget / reflect)一律要求 `confirm: true`:
1072
+ * 协议层不信任客户端「已经问过用户了」,GUI 忘了弹确认就是静默改用户记忆库。
1073
+ */
1074
+ async function memoryCommand(command) {
1075
+ if (!(await withRuntime(command.id, true)))
1076
+ return;
1077
+ const needsConfirm = command.action === 'confirm' || command.action === 'drop' || command.action === 'forget';
1078
+ if (needsConfirm && command.confirm !== true) {
1079
+ return error('该操作会修改记忆库,需要客户端二次确认后再带 confirm:true 重发。', command.id);
1080
+ }
1081
+ try {
1082
+ if (command.action === 'overview') {
1083
+ const all = loadAll();
1084
+ const active = all.filter((entry) => entry.status === 'active');
1085
+ const byType = {};
1086
+ for (const entry of active)
1087
+ byType[entry.type] = (byType[entry.type] ?? 0) + 1;
1088
+ emit('memory_report', {
1089
+ action: 'overview',
1090
+ enabled: isMemoryEnabled(),
1091
+ paused: isMemoryWritesPaused(),
1092
+ counts: {
1093
+ total: all.length,
1094
+ active: active.length,
1095
+ archived: all.filter((entry) => entry.status === 'archived').length,
1096
+ superseded: all.filter((entry) => entry.status === 'superseded').length,
1097
+ byType,
1098
+ },
1099
+ // 最近更新的在前:面板默认列这些,不做分页(记忆库量级本来就小)。
1100
+ entries: [...active]
1101
+ .sort((left, right) => right.updatedAt.localeCompare(left.updatedAt))
1102
+ .slice(0, command.limit ?? 50)
1103
+ .map(memoryEntryPayload),
1104
+ }, command.id);
1105
+ return;
1106
+ }
1107
+ if (command.action === 'health') {
1108
+ emit('memory_report', { action: 'health', health: buildMemoryHealth(), lines: formatMemoryHealth() }, command.id);
1109
+ return;
1110
+ }
1111
+ if (command.action === 'audit') {
1112
+ emit('memory_report', { action: 'audit', records: readAudit(command.limit ?? 50) }, command.id);
1113
+ return;
1114
+ }
1115
+ if (command.action === 'profile') {
1116
+ const { me, edges } = inspectPrimaryProfile();
1117
+ emit('memory_report', {
1118
+ action: 'profile',
1119
+ primary: me ? { id: me.id, name: me.name } : null,
1120
+ edgeCount: edges.length,
1121
+ internalized: listInternalizedProfile().map((candidate) => ({
1122
+ id: candidate.edge.id,
1123
+ text: candidate.text,
1124
+ relation: candidate.relation,
1125
+ confidence: candidate.edge.confidence ?? null,
1126
+ evidence: candidate.edge.evidence ?? null,
1127
+ })),
1128
+ candidates: listProfileCandidates().map((candidate) => ({
1129
+ id: candidate.edge.id,
1130
+ text: candidate.text,
1131
+ relation: candidate.relation,
1132
+ confidence: candidate.edge.confidence ?? null,
1133
+ evidence: candidate.edge.evidence ?? null,
1134
+ })),
1135
+ recall: readRecallStats(),
1136
+ }, command.id);
1137
+ return;
1138
+ }
1139
+ if (command.action === 'search') {
1140
+ const query = (command.query ?? '').trim();
1141
+ if (!query)
1142
+ return error('搜索关键词为空。', command.id);
1143
+ emit('memory_report', {
1144
+ action: 'search',
1145
+ query,
1146
+ entries: searchEntries(query, { limit: command.limit ?? 8, status: 'any' }).map(memoryEntryPayload),
1147
+ }, command.id);
1148
+ return;
1149
+ }
1150
+ if (command.action === 'confirm') {
1151
+ const id = command.entryId?.trim();
1152
+ if (!id)
1153
+ return error('缺少要确认的边 id。', command.id);
1154
+ const result = promoteEdge(id);
1155
+ if (!result.ok)
1156
+ return error(`确认失败:${result.reason}`, command.id);
1157
+ // 画像进了 About you,下一轮系统提示必须重算,否则要等下一次 /resume 才生效。
1158
+ if (sessionId)
1159
+ history[0] = { role: 'system', content: currentSystemMessage() };
1160
+ emit('memory_report', { action: 'confirm', entryId: id, ok: true }, command.id);
1161
+ return;
1162
+ }
1163
+ if (command.action === 'drop') {
1164
+ const id = command.entryId?.trim();
1165
+ if (!id)
1166
+ return error('缺少要撤销的边 id。', command.id);
1167
+ const result = invalidateEdge(id, 'profile-dropped');
1168
+ if (!result.ok)
1169
+ return error(`撤销失败:${result.reason}`, command.id);
1170
+ if (sessionId)
1171
+ history[0] = { role: 'system', content: currentSystemMessage() };
1172
+ emit('memory_report', { action: 'drop', entryId: id, ok: true }, command.id);
1173
+ return;
1174
+ }
1175
+ if (command.action === 'forget') {
1176
+ const id = command.entryId?.trim();
1177
+ if (!id)
1178
+ return error('缺少要遗忘的记忆 id。', command.id);
1179
+ const result = forgetEntry(id);
1180
+ emit('memory_report', { action: 'forget', entryId: id, ...result }, command.id);
1181
+ return;
1182
+ }
1183
+ if (command.action === 'reflect') {
1184
+ if (!isMemoryEnabled())
1185
+ return error('记忆子系统已关闭,反思不会执行。', command.id);
1186
+ // manual=true:绕过自动节流的次数/转录闸门(用户显式点了按钮)。
1187
+ kickoffReflection(snapshotTranscript(history, 20), true);
1188
+ emit('memory_report', { action: 'reflect', triggered: true }, command.id);
1189
+ return;
1190
+ }
1191
+ }
1192
+ catch (cause) {
1193
+ error(cause instanceof Error ? cause.message : String(cause), command.id);
1194
+ }
1195
+ }
1196
+ /** 设置项 → 当前值(read 侧)。与 set 侧共用同一份键名,避免两边各写一套字符串。 */
1197
+ function readSettingsSnapshot() {
1198
+ const envFlag = (key, fallback) => {
1199
+ const raw = process.env[key];
1200
+ if (raw === undefined)
1201
+ return fallback;
1202
+ return !['0', 'false', 'off', 'no'].includes(raw.trim().toLowerCase());
1203
+ };
1204
+ return {
1205
+ effort: getActiveEffort(),
1206
+ router: isToolRoutingEnabled(),
1207
+ memory: isMemoryEnabled(),
1208
+ subAgent: isSubAgentEnabled(),
1209
+ frontendTools: isFrontendToolsEnabled(),
1210
+ computerUse: isComputerUseEnabled(),
1211
+ turnRecall: isTurnRecallEnabled(),
1212
+ proactive: envFlag('MOCODE_MEMORY_PROACTIVE', true),
1213
+ episodic: envFlag('MOCODE_MEMORY_EPISODIC', true),
1214
+ consolidate: envFlag('MOCODE_MEMORY_CONSOLIDATE', true),
1215
+ autoCompact: config.autoCompact,
1216
+ autoReflect: config.autoReflect,
1217
+ };
1218
+ }
1219
+ /**
1220
+ * 运行时设置:get 返回快照;set 应用 patch 并持久化到 ~/.mocode/config。
1221
+ *
1222
+ * 为什么必须写盘:host 每次启动都重新读配置,只在内存里改等于「重启就丢」。
1223
+ * 为什么改完要调用方重启 host:模型客户端、工具表、路由开关都在 host 启动期固化成快照,
1224
+ * 改内存值对已经起来的子进程不生效(与切模型同因,见 work-app 的 restartAllAgents)。
1225
+ */
1226
+ async function settingsCommand(command) {
1227
+ if (command.action === 'get') {
1228
+ // get 不要求 runtime:设置本身是进程级配置,host 没起来也能读(GUI 首屏就要显示)。
1229
+ return emit('settings_state', { settings: readSettingsSnapshot() }, command.id);
1230
+ }
1231
+ const patch = command.patch ?? {};
1232
+ const persist = {};
1233
+ const changed = [];
1234
+ try {
1235
+ for (const [key, value] of Object.entries(patch)) {
1236
+ if (key === 'effort') {
1237
+ const effort = parseReasoningEffort(value);
1238
+ if (!effort)
1239
+ return error(`无效的思考强度:${String(value)}`, command.id);
1240
+ updateModelConfig({ reasoningEffort: effort });
1241
+ persist.REASONING_EFFORT = effort;
1242
+ changed.push(key);
1243
+ continue;
1244
+ }
1245
+ if (typeof value !== 'boolean')
1246
+ continue;
1247
+ switch (key) {
1248
+ case 'router':
1249
+ updateToolRoutingEnabled(value);
1250
+ persist.MOCODE_ROUTER_ENABLED = String(value);
1251
+ break;
1252
+ case 'memory':
1253
+ updateMemoryConfig(value);
1254
+ persist.MEMORY_ENABLED = String(value);
1255
+ break;
1256
+ case 'subAgent':
1257
+ updateSubAgentConfig(value);
1258
+ persist.MOCODE_SUBAGENT_ENABLED = String(value);
1259
+ break;
1260
+ case 'frontendTools':
1261
+ updateFrontendToolsConfig(value);
1262
+ persist.MOCODE_FRONTEND_TOOLS_ENABLED = String(value);
1263
+ break;
1264
+ case 'computerUse':
1265
+ updateComputerUseConfig(value);
1266
+ persist.MOCODE_COMPUTER_USE_ENABLED = String(value);
1267
+ break;
1268
+ case 'turnRecall':
1269
+ process.env.MOCODE_MEMORY_TURN_RECALL = String(value);
1270
+ persist.MOCODE_MEMORY_TURN_RECALL = String(value);
1271
+ break;
1272
+ case 'proactive':
1273
+ process.env.MOCODE_MEMORY_PROACTIVE = String(value);
1274
+ persist.MOCODE_MEMORY_PROACTIVE = String(value);
1275
+ break;
1276
+ case 'episodic':
1277
+ process.env.MOCODE_MEMORY_EPISODIC = String(value);
1278
+ persist.MOCODE_MEMORY_EPISODIC = String(value);
1279
+ break;
1280
+ case 'consolidate':
1281
+ process.env.MOCODE_MEMORY_CONSOLIDATE = String(value);
1282
+ persist.MOCODE_MEMORY_CONSOLIDATE = String(value);
1283
+ break;
1284
+ case 'autoCompact':
1285
+ // 这两个没有 update* 写入口:config 单例的布尔字段就是唯一真源,直接改。
1286
+ config.autoCompact = value;
1287
+ process.env.AUTO_COMPACT = String(value);
1288
+ persist.AUTO_COMPACT = String(value);
1289
+ break;
1290
+ case 'autoReflect':
1291
+ config.autoReflect = value;
1292
+ process.env.AUTO_REFLECT = String(value);
1293
+ persist.AUTO_REFLECT = String(value);
1294
+ break;
1295
+ default:
1296
+ continue;
1297
+ }
1298
+ changed.push(key);
1299
+ }
1300
+ if (Object.keys(persist).length > 0)
1301
+ writeConfigKeys(persist);
1302
+ // 记忆总开关变了,history[0] 的 Memory Index / plan 段都要重算(否则下一轮还是旧画面)。
1303
+ if (sessionId && changed.includes('memory')) {
1304
+ history[0] = { role: 'system', content: currentSystemMessage() };
1305
+ }
1306
+ emit('settings_state', { settings: readSettingsSnapshot(), changed, restartRequired: changed.length > 0 }, command.id);
1307
+ }
1308
+ catch (cause) {
1309
+ error(cause instanceof Error ? cause.message : String(cause), command.id);
1310
+ }
1311
+ }
1312
+ async function commitMessageCommand(command) {
1313
+ const previous = commitMessageRequests.get(command.id);
1314
+ if (previous)
1315
+ return error('Duplicate commit message request id.', command.id);
1316
+ const controller = new AbortController();
1317
+ commitMessageRequests.set(command.id, controller);
1318
+ try {
1319
+ await initializeRuntime();
1320
+ if (closing || controller.signal.aborted)
1321
+ return;
1322
+ // 独立无工具请求:绝不把 diff 或结果追加到任务 history,也不执行 commit。
1323
+ const message = await generateCommitMessage(command, runtime().context.modelTransport, controller.signal);
1324
+ if (!controller.signal.aborted)
1325
+ emit('commit_message_report', { message }, command.id);
1326
+ }
1327
+ catch (cause) {
1328
+ if (!controller.signal.aborted)
1329
+ error(cause instanceof Error ? cause.message : String(cause), command.id);
1330
+ }
1331
+ finally {
1332
+ commitMessageRequests.delete(command.id);
1333
+ }
1334
+ }
1335
+ function cancelCommitMessage(command) {
1336
+ commitMessageRequests.get(command.targetId)?.abort();
1337
+ }
1338
+ /**
1339
+ * 命令分发。default 分支显式报错而不是静默丢弃:新客户端发来本 host 不认识的命令时,
1340
+ * 用户要能看到「这条指令没生效」,而不是盯着一个没有反应的界面。
1341
+ */
343
1342
  async function handle(command) {
344
- if (command.type === 'run')
345
- return run(command);
346
- if (command.type === 'cancel')
347
- return cancel(command);
348
- if (command.type === 'compact')
349
- return compact(command);
350
- resolveApproval(command);
1343
+ // 先取出这两个字段:switch 穷尽后 default 分支里的 command 会被收窄成 never,
1344
+ // 而这里仍要报出「具体哪个 type 没被支持」。不用 as 去掉类型,用局部变量保留可读性。
1345
+ const { type, id } = command;
1346
+ switch (command.type) {
1347
+ case 'run':
1348
+ return run(command);
1349
+ case 'cancel':
1350
+ return cancel(command);
1351
+ case 'compact':
1352
+ return compact(command);
1353
+ case 'approval':
1354
+ return resolveApproval(command);
1355
+ case 'set_mode':
1356
+ return setMode(command);
1357
+ case 'sessions':
1358
+ return sessionsCommand(command);
1359
+ case 'rollback':
1360
+ return rollbackCommand(command);
1361
+ case 'changes':
1362
+ return changesCommand(command);
1363
+ case 'usage':
1364
+ return usageCommand(command);
1365
+ case 'context_usage':
1366
+ return contextUsageCommand(command);
1367
+ case 'memory':
1368
+ return memoryCommand(command);
1369
+ case 'settings':
1370
+ return settingsCommand(command);
1371
+ case 'commit_message':
1372
+ return commitMessageCommand(command);
1373
+ case 'cancel_commit_message':
1374
+ return cancelCommitMessage(command);
1375
+ default:
1376
+ return error(`Host does not support command type "${type}" (protocol v${HOST_PROTOCOL_VERSION}).`, id);
1377
+ }
351
1378
  }
352
1379
  /** 心跳间隔:控制面用「最近一次心跳」判断 Worker 是卡死还是进程已死。 */
353
1380
  const HEARTBEAT_MS = 5_000;
@@ -367,6 +1394,8 @@ function startHeartbeat() {
367
1394
  }
368
1395
  function requestShutdownCancellation() {
369
1396
  activeRun?.controller.abort(hostClosedReason);
1397
+ for (const controller of commitMessageRequests.values())
1398
+ controller.abort(hostClosedReason);
370
1399
  runtimeFacade?.cancel(hostClosedReason);
371
1400
  for (const [approvalId, waiter] of approvals) {
372
1401
  waiter.resolve({ action: 'cancelled' });
@@ -374,6 +1403,10 @@ function requestShutdownCancellation() {
374
1403
  }
375
1404
  }
376
1405
  const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
1406
+ // host 的 stdout 是 NDJSON 协议通道:layout.contentWrite / Spinner 的「非 TTY 直接写」兜底
1407
+ // 会把压缩行、图片卡片行这类裸文本灌进来,客户端 JSON.parse 失败后当 diagnostic 丢掉。
1408
+ // 用户可见反馈必须走下面的事件(context_compacted / image_relief …),兜底写一律静音。
1409
+ muteStdoutOutput();
377
1410
  const pendingCommands = new Set();
378
1411
  const heartbeatTimer = startHeartbeat();
379
1412
  const startupPromise = initializeRuntime();