mocode-ai 1.8.9 → 1.9.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 (65) hide show
  1. package/dist/agent/index.js +17 -17
  2. package/dist/agent/model-turn.js +8 -4
  3. package/dist/agent/run-coordinator.js +6 -0
  4. package/dist/agent/spawn.js +8 -4
  5. package/dist/agent/stages/tool-dispatcher.js +31 -11
  6. package/dist/attachments/clipboard.js +22 -0
  7. package/dist/attachments/image.js +63 -0
  8. package/dist/changeset/hash.js +17 -0
  9. package/dist/changeset/index.js +6 -10
  10. package/dist/context/text-search.js +28 -10
  11. package/dist/flows/cli.js +1 -1
  12. package/dist/flows/flow.js +1 -1
  13. package/dist/flows/trace.js +1 -1
  14. package/dist/headless.js +23 -0
  15. package/dist/i18n/index.js +16 -2
  16. package/dist/index.js +1 -1
  17. package/dist/memory/anchor.js +319 -0
  18. package/dist/memory/audit.js +65 -0
  19. package/dist/memory/episodic.js +546 -0
  20. package/dist/memory/graph.js +233 -9
  21. package/dist/memory/health.js +208 -0
  22. package/dist/memory/index.js +12 -3
  23. package/dist/memory/pending.js +269 -0
  24. package/dist/memory/portable.js +150 -0
  25. package/dist/memory/proactive.js +588 -0
  26. package/dist/memory/recall-stats.js +1 -1
  27. package/dist/memory/reflect.js +260 -6
  28. package/dist/memory/relation-vocab.js +26 -4
  29. package/dist/memory/store.js +587 -41
  30. package/dist/memory/tail.js +88 -0
  31. package/dist/memory/write-gate.js +44 -0
  32. package/dist/permissions/computer-review.js +1 -1
  33. package/dist/permissions/flow-review.js +1 -1
  34. package/dist/repl/commands/flow.js +1 -1
  35. package/dist/repl/commands/image.js +30 -17
  36. package/dist/repl/commands/memory.js +257 -6
  37. package/dist/repl/commands/session.js +13 -0
  38. package/dist/repl/commands/tool-group.js +6 -0
  39. package/dist/repl/commands.js +1 -0
  40. package/dist/repl/episode-finalize.js +55 -0
  41. package/dist/repl/message-format.js +18 -0
  42. package/dist/repl/runtime.js +110 -5
  43. package/dist/runtime/uia-selector.js +1 -1
  44. package/dist/runtime/uia-service.js +3 -3
  45. package/dist/runtime/wait-until.js +1 -1
  46. package/dist/runtime/window-list.js +1 -1
  47. package/dist/sandbox/policy.js +49 -0
  48. package/dist/session/compact.js +47 -12
  49. package/dist/session/gui-actions.js +1 -1
  50. package/dist/tools/builtins/computer.js +5 -5
  51. package/dist/tools/builtins/memory-graph.js +12 -1
  52. package/dist/tools/builtins/memory-list.js +13 -3
  53. package/dist/tools/builtins/memory-save.js +82 -2
  54. package/dist/tools/builtins/memory-search.js +57 -2
  55. package/dist/tools/builtins/memory-update.js +52 -1
  56. package/dist/tools/builtins/read-file.js +51 -2
  57. package/dist/tools/builtins/run-flow.js +1 -1
  58. package/dist/tools/constants.js +60 -0
  59. package/dist/ui/clipboard.js +97 -0
  60. package/dist/ui/layout-internal/core.js +1 -1
  61. package/dist/ui/layout-internal/input-paint.js +7 -5
  62. package/dist/ui/layout-internal/state.js +8 -0
  63. package/dist/ui/layout-internal/statusbar.js +22 -1
  64. package/dist/ui/prompt-internal/editor.js +39 -0
  65. package/package.json +6 -1
@@ -299,6 +299,11 @@ onContextUpdate,
299
299
  toolPolicy,
300
300
  /** 仅真实用户 turn 传入;合成 plan 执行轮继承 policy 但不重复记录初始路由。 */
301
301
  initialToolRoute,
302
+ /**
303
+ * R17:会话内记忆尾注,由调用方每个用户轮现算(见 memory/tail.ts)。
304
+ * 走 ephemeral 段而非重建 history[0]——后者会让整段对话的前缀缓存每轮失效。
305
+ */
306
+ memoryTail,
302
307
  /** TUI composition root 绑定的 Runtime;旧调用传 AgentRuntimeContext 仍兼容。 */
303
308
  runtimeOrContext = defaultRuntime) {
304
309
  const runtime = runtimeOrContext instanceof Runtime
@@ -324,10 +329,8 @@ runtimeOrContext = defaultRuntime) {
324
329
  // lastChar 镜像:core 跟踪流式末字符决定补换行,但 TUI hooks 需读它决定 layout.contentWrite('\n')。
325
330
  // core 的 onTextEnd hook 只在 lastChar !== '\n' 时才调,调后置 '\n';镜像与此同步。
326
331
  let lastChar = '';
327
- // 正文 -> 工具的边界由 core.onTextEnd 与本层 onToolCall 分两段完成。
328
- // markdown 段末已经是完整物理行,因此再写 1 个 \n 就代表 1 条空白行;
329
- // 不能按普通字符串的“两个换行才有一个空行”来计算。
330
- let textBoundaryNewlines = 0;
332
+ // 正文 -> 工具的边界换行只在流末 onTextEnd 写一次:工具名 delta 可能在正文流到一半时
333
+ // 就先到(网关交错分片),绝不能在 onToolCall 里提前写 \n——那会在词中间封死 markdown 段。
331
334
  let hasPendingTextBoundary = false;
332
335
  let toolBatchFollowsText = false;
333
336
  // Claude 等模型在 tool_calls 前常输出 "Tool results:" 这类无意义叙述。
@@ -359,7 +362,6 @@ runtimeOrContext = defaultRuntime) {
359
362
  lastChar = visible[visible.length - 1];
360
363
  if (visible.trim().length > 0) {
361
364
  hasPendingTextBoundary = true;
362
- textBoundaryNewlines = 0;
363
365
  }
364
366
  }
365
367
  }
@@ -402,17 +404,13 @@ runtimeOrContext = defaultRuntime) {
402
404
  onToolCall: (name) => {
403
405
  // 工具调用开始前,先 flush 被抑制的叙述缓冲(若是纯噪声则丢弃)。
404
406
  flushPendingNarrationIfAny();
405
- // 文本/思考已流完,模型转而生成 tool_call 参数(可能很长,如 write_file 整篇内容):
406
- // 补换行(让随后的 ● 行与 diff 不黏在正文末尾)+ 启「生成中」内联 spinner,内容区不再干等。
407
- if (hasPendingTextBoundary) {
407
+ // 模型转而生成 tool_call 参数(可能很长,如 write_file 整篇内容):启「生成中」spinner。
408
+ // 此处**不写换行、不封 markdown 段**:工具名 delta 可能在正文流到一半时先到(部分网关
409
+ // 交错下发 content / tool_calls,剩余 content 随后才补完),提前 contentWrite('\n') 会
410
+ // 在词中间硬换行(「d / ispatcher」断词 bug)。只标记「正文后随工具批」,真正的边界换行
411
+ // 由流末 onTextEnd 落、空行归一并到 onToolHeader——那时全部 content 已到齐。
412
+ if (hasPendingTextBoundary)
408
413
  toolBatchFollowsText = true;
409
- if (textBoundaryNewlines < 1) {
410
- layout.contentWrite('\n');
411
- }
412
- lastChar = '\n';
413
- textBoundaryNewlines = 1;
414
- hasPendingTextBoundary = false;
415
- }
416
414
  if (name)
417
415
  spinner.start(t('agent.generating', { tool: name }));
418
416
  },
@@ -442,20 +440,21 @@ runtimeOrContext = defaultRuntime) {
442
440
  layout.contentWrite(` ${ui.accent}●${ui.reset} 压缩图片 ${info.replaced} 张转为文字卡(${info.described} 张含描述) 请求体 ${fmt(info.bytesBefore)} → ${fmt(info.bytesAfter)}\n`);
443
441
  },
444
442
  onTextEnd: () => {
443
+ // 流末正文收尾换行(此刻 content 已全部到齐,不会再出现词中间断行)。
445
444
  if (lastChar && lastChar !== '\n') {
446
445
  layout.contentWrite('\n');
447
446
  lastChar = '\n';
448
- if (hasPendingTextBoundary)
449
- textBoundaryNewlines = 1;
450
447
  }
451
448
  },
452
449
  onToolHeader: (tc) => {
453
450
  // mutation 的自动展开会把 current/committed 空行状态互相转换;在首摘要真正
454
451
  // 落屏前按视觉行归一,避免同样的文本→edit 边界偶发 1 行或 2 行。
452
+ // 普通工具的新建批在 writeToolHeader 内部同样归一,此处只保留 mutation 显式分支。
455
453
  if (toolBatchFollowsText && isMutationTool(tc.name, runtime.context.toolRuntime)) {
456
454
  layout.normalizeMutationBoundary();
457
455
  }
458
456
  toolBatchFollowsText = false;
457
+ hasPendingTextBoundary = false;
459
458
  writeToolHeader(tc, runtime.context.toolRuntime);
460
459
  },
461
460
  onToolStart: (name) => spinner.start(t('agent.executing', { tool: name })),
@@ -509,6 +508,7 @@ runtimeOrContext = defaultRuntime) {
509
508
  hooks: combinedHooks,
510
509
  toolPolicy,
511
510
  initialToolRoute,
511
+ memoryTail,
512
512
  onTraceEvent: appendCurrentSessionTraceEvent,
513
513
  });
514
514
  }
@@ -147,10 +147,11 @@ export async function runModelTurn(input) {
147
147
  stream.lastChar = text[text.length - 1];
148
148
  };
149
149
  const onToolCall = (name) => {
150
- if (stream.lastChar && stream.lastChar !== '\n') {
151
- hooks.onTextEnd?.();
152
- stream.lastChar = '\n';
153
- }
150
+ // 注意:不能在这里因工具名到达就发 onTextEnd。部分 OpenAI 兼容网关会在同一响应里
151
+ // 交错下发 content 与 tool_calls delta(文字流到一半先到工具名,后续 content 才补完)。
152
+ // 流中即发 onTextEnd 会让 UI 在词中间硬换行并封死 markdown 段(「继续通读:d / ispatcher」
153
+ // 断词 bug)。onToolCall 此刻只驱动「生成中」spinner;正文收尾换行统一由流末
154
+ // (tool-turn / run-coordinator)依据 stream.lastChar 发一次 onTextEnd,届时全部 content 已到齐。
154
155
  hooks.onToolCall?.(name);
155
156
  };
156
157
  let result;
@@ -179,6 +180,9 @@ export async function runModelTurn(input) {
179
180
  '4. Before re-running a search/read you think you already did, check the summary and notes first; repeat only if the result is genuinely missing or the target changed.'
180
181
  : '',
181
182
  sessionStateText,
183
+ // R17:会话内记忆尾注。放最后——它是最"新"的信息,且每轮可能不同,
184
+ // 放在固定段之后能最大限度保住前缀缓存的可复用部分。
185
+ opts.memoryTail ?? '',
182
186
  ]
183
187
  .filter(Boolean)
184
188
  .join('\n\n');
@@ -44,6 +44,11 @@ import { createLegacyCapabilityResolver, createLegacyTerminationPolicy, createSt
44
44
  export async function runAgentCoreLegacy(opts, historyManager, stages) {
45
45
  const { history, userInput, signal, hooks } = opts;
46
46
  const ctx = opts.runtimeContext ?? defaultAgentRuntimeContext;
47
+ // R3:前摄匹配的上下文取本轮用户文本(纯文本部分)。图片等非文本 part 不参与。
48
+ const proactiveContext = (Array.isArray(userInput) ? userInput : [{ type: 'text', text: userInput }])
49
+ .filter((p) => p.type === 'text')
50
+ .map((p) => p.text)
51
+ .join(' ');
47
52
  const runtimeToolSchemas = ctx.toolRuntime.tools.map((tool) => ({
48
53
  type: 'function',
49
54
  function: {
@@ -327,6 +332,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
327
332
  readDedup,
328
333
  argumentErrorHint: (name) => argumentErrorHint(name, runtimeContextState),
329
334
  ...(result.finishReason ? { finishReason: result.finishReason } : {}),
335
+ proactiveContext,
330
336
  onToolOutput: (call, chunk) => hooks.onToolOutput?.(call, chunk),
331
337
  ...(opts.toolPolicy
332
338
  ? {
@@ -233,16 +233,20 @@ export async function spawnAgent(opts) {
233
233
  if (s)
234
234
  lastChar = s[s.length - 1];
235
235
  },
236
- onToolCall: (_name) => {
236
+ onToolCall: () => {
237
+ // 不能在工具名到达时就给转写补 \n:网关可能交错下发 content / tool_calls,
238
+ // 工具名先到、正文后补完,提前换行会在词中间断句。换行延迟到 onToolHeader(流已结束)。
239
+ // 子 agent 静默:不启 spinner(name 参数仅主 agent 用)
240
+ },
241
+ onToolHeader: (tc) => {
242
+ // 流末工具头落缓冲前补正文收尾换行(等价主 agent 的 onTextEnd)。
237
243
  if (lastChar && lastChar !== '\n') {
238
244
  writeBuf('\n');
239
245
  lastChar = '\n';
240
246
  }
241
- // 子 agent 静默:不启 spinner(name 参数仅主 agent 用)
242
- },
243
- onToolHeader: (tc) => {
244
247
  const summary = summarizeToolCall(tc.name, tc.arguments);
245
248
  writeBuf(` ● ${tc.name} ${summary}\n`);
249
+ lastChar = '\n';
246
250
  // 实时写入主内容区:子 agent 的每次工具调用累计到摘要行计数。
247
251
  ensureQuietLine(opts.quietLabel ?? t('skill.executing', { name: opts.prompt.slice(0, 40) }));
248
252
  ensureLiveBatch();
@@ -1,6 +1,7 @@
1
1
  import { ADD_TOOL_GROUPS_TOOL_NAME } from '../../config/profiles.js';
2
- import { config } from '../../config/index.js';
2
+ import { config, isMemoryEnabled } from '../../config/index.js';
3
3
  import { t } from '../../i18n/index.js';
4
+ import { isProactiveEnabled, proactiveHint } from '../../memory/proactive.js';
4
5
  import { checkPermission as defaultCheckPermission } from '../../permissions/index.js';
5
6
  import { jailResolve as defaultJailResolve } from '../../sandbox/index.js';
6
7
  import { summarizeToolArguments } from '../../session/index.js';
@@ -23,6 +24,9 @@ class LegacyCompatibleToolDispatcher {
23
24
  async dispatch(request) {
24
25
  const { toolRuntime, checkPermission, jailResolve } = this.dependencies;
25
26
  const calls = request.calls;
27
+ // R3.5:每批只判一次开关。memory 总开关 veto 优先于前摄独立开关——用户关掉记忆就不该
28
+ // 再有记忆注入,否则"关闭"只关了一半。
29
+ const proactiveOn = isMemoryEnabled() && isProactiveEnabled();
26
30
  const argumentSummaries = calls.map((call) => summarizeToolArguments(call.arguments));
27
31
  const orderedResults = new Array(calls.length);
28
32
  const modelAttachments = [];
@@ -42,16 +46,32 @@ class LegacyCompatibleToolDispatcher {
42
46
  argumentSummary: argumentSummaries[index],
43
47
  outcome,
44
48
  });
45
- const execute = (call, hint, onLockAcquired) => toolRuntime.executeToolOutcome(call.name, call.arguments, request.signal, {
46
- callId: call.id,
47
- onOutput: (chunk) => request.onToolOutput?.(call, chunk),
48
- allowedToolNames: request.currentAllowedToolNames(),
49
- delegation: request.delegation(),
50
- readDedup: request.readDedup,
51
- ...(hint ? { argumentErrorHint: hint } : {}),
52
- ...(request.finishReason ? { finishReason: request.finishReason } : {}),
53
- ...(onLockAcquired ? { onLockAcquired } : {}),
54
- });
49
+ const execute = (call, hint, onLockAcquired) => {
50
+ const pending = toolRuntime.executeToolOutcome(call.name, call.arguments, request.signal, {
51
+ callId: call.id,
52
+ onOutput: (chunk) => request.onToolOutput?.(call, chunk),
53
+ allowedToolNames: request.currentAllowedToolNames(),
54
+ delegation: request.delegation(),
55
+ readDedup: request.readDedup,
56
+ ...(hint ? { argumentErrorHint: hint } : {}),
57
+ ...(request.finishReason ? { finishReason: request.finishReason } : {}),
58
+ ...(onLockAcquired ? { onLockAcquired } : {}),
59
+ });
60
+ if (!proactiveOn)
61
+ return pending;
62
+ // R3.3:前摄注入挂在**这一个**统一出口上,四种调度分支(并行只读 / 编排 / 资源锁 /
63
+ // 串行)自然全覆盖,无须各写一遍。放在 outcome 落地后做:被拒绝或未执行的调用
64
+ // 根本不经过这里,不会白烧一次匹配。
65
+ return pending.then((outcome) => {
66
+ if (outcome.status !== 'success' && outcome.status !== 'error')
67
+ return outcome;
68
+ const proactive = proactiveHint(call.name, parseArgs(call.arguments), true, request.proactiveContext);
69
+ if (!proactive)
70
+ return outcome;
71
+ const base = outcome.output ?? '';
72
+ return { ...outcome, output: base ? `${base}\n\n${proactive}` : proactive };
73
+ });
74
+ };
55
75
  const executionEvents = (index, parsed, outcome) => {
56
76
  request.onEvent({ type: 'usage', usage: outcome.usage });
57
77
  request.onEvent({ type: 'host_outcome', call: calls[index], parsed: parsed ?? {}, outcome });
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 剪贴板截图 → 待发附件的共享通道(Ctrl+Y 快捷键与 /image clip 命令共用)。
3
+ *
4
+ * 这里只负责"系统剪贴板字节 → ImageAttachment(含 4MiB 上限 / PNG 降采样)";
5
+ * 入队去重、视觉能力警告、上屏反馈由调用方各自处理。
6
+ */
7
+ import { config } from '../config/index.js';
8
+ import { readClipboardImage } from '../ui/clipboard.js';
9
+ import { buildImageAttachmentFromBuffer, MAX_INLINE_BYTES_DEFAULT } from './image.js';
10
+ export async function readClipboardAsAttachment() {
11
+ const buf = await readClipboardImage();
12
+ if (!buf)
13
+ return { ok: false, empty: true };
14
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
15
+ const name = `clipboard-${ts}.png`;
16
+ const r = buildImageAttachmentFromBuffer(buf, `clipboard:${ts}`, name, {
17
+ maxBytes: config.maxImageBytes ?? MAX_INLINE_BYTES_DEFAULT,
18
+ });
19
+ if (!r.ok)
20
+ return { ok: false, reason: r.reason };
21
+ return { ok: true, att: r.att, downscaledFrom: r.downscaledFrom };
22
+ }
@@ -134,6 +134,7 @@ async function downscalePngFile(abs, maxBytes, failPrefix, budgetBytes) {
134
134
  bytes: buf.length,
135
135
  mime: 'image/png',
136
136
  dataUrl: `data:image/png;base64,${buf.toString('base64')}`,
137
+ downscaledFrom: { width: png.width, height: png.height },
137
138
  },
138
139
  };
139
140
  }
@@ -174,6 +175,68 @@ export async function loadImageAttachmentWithDownscale(input, opts) {
174
175
  }
175
176
  return downscalePngFile(abs, opts.maxBytes, loaded.reason, opts.budgetBytes ?? INLINE_PNG_BUDGET_BYTES);
176
177
  }
178
+ /**
179
+ * 从内存字节构造附件(剪贴板截图通道:PNG 由系统 API 直接给出,无落盘路径)。
180
+ *
181
+ * 与 loadImageAttachmentWithDownscale 同口径:魔数嗅探类型、4 MiB 硬上限、超软预算/超限
182
+ * 的 PNG 走同一套手写解码降采样(零原生依赖),JPEG/WebP/GIF 超限拒绝。`name` 仅用于
183
+ * chip 展示与去重,`source` 写进 path(发送时只读 dataUrl,path 不被打开)。
184
+ */
185
+ export function buildImageAttachmentFromBuffer(buf, source, name, opts) {
186
+ const mime = sniffImageMime(buf);
187
+ if (!mime)
188
+ return { ok: false, reason: 'unsupported: 剪贴板内容不是可识别的图片(png/jpg/gif/webp)' };
189
+ const budget = opts.budgetBytes ?? INLINE_PNG_BUDGET_BYTES;
190
+ let out = buf;
191
+ let downscaledFrom;
192
+ if (mime === 'image/png' && (out.length > opts.maxBytes || out.length > budget)) {
193
+ try {
194
+ const png = decodePng(buf);
195
+ let img = downscale(png, DOWNSCALE_MAX_EDGE).img;
196
+ let encoded = encodePng(img);
197
+ for (const edge of DOWNSCALE_FALLBACK_EDGES) {
198
+ if (encoded.length <= budget || edge >= Math.max(img.width, img.height))
199
+ continue;
200
+ img = downscale(png, edge).img;
201
+ encoded = encodePng(img);
202
+ }
203
+ if (encoded.length <= opts.maxBytes && encoded.length < out.length) {
204
+ downscaledFrom = { width: png.width, height: png.height };
205
+ out = encoded;
206
+ }
207
+ }
208
+ catch (error) {
209
+ const message = error instanceof Error ? error.message : String(error);
210
+ // 8-bit RGB/RGBA 之外的 PNG(如 16-bit/调色板)手写解码不支持:降采样失败时
211
+ // 不致命——未超硬上限就原样发,超了走下面的 too large 拒绝。
212
+ if (buf.length > opts.maxBytes) {
213
+ return {
214
+ ok: false,
215
+ reason: `too large: ${formatBytes(buf.length)} (max ${formatBytes(opts.maxBytes)});降采样失败: ${message}`,
216
+ };
217
+ }
218
+ }
219
+ }
220
+ if (out.length > opts.maxBytes) {
221
+ return { ok: false, reason: `too large: ${formatBytes(out.length)} (max ${formatBytes(opts.maxBytes)})` };
222
+ }
223
+ // id 只哈希内容(不含 source/name):同一张剪贴板截图连抓两次时间戳不同但字节相同,
224
+ // 去重仍能命中(pendingAttachments 按 id 判重)。
225
+ const id = createHash('sha1').update(out).digest('hex');
226
+ return {
227
+ ok: true,
228
+ att: {
229
+ id,
230
+ path: source,
231
+ name,
232
+ bytes: out.length,
233
+ mime,
234
+ dataUrl: `data:${mime};base64,${out.toString('base64')}`,
235
+ ...(downscaledFrom ? { downscaledFrom } : {}),
236
+ },
237
+ ...(downscaledFrom ? { downscaledFrom } : {}),
238
+ };
239
+ }
177
240
  export async function loadImageAttachment(input, opts) {
178
241
  const trimmed = input.trim();
179
242
  if (!trimmed)
@@ -0,0 +1,17 @@
1
+ // 内容哈希的**唯一实现**。叶子模块:只依赖 node:crypto 与本地类型。
2
+ //
3
+ // 为什么单独拆出来:哈希口径必须全局一致(read_file 的 artifact hash、changeset 的
4
+ // expected_hash、记忆锚点 R2 的 stale 判定都靠它对齐),但 `changeset/index.ts` 会
5
+ // 引入 sandbox/rollback/tools.resource-lock——`memory/store.ts` 是叶模块,不能为了
6
+ // 拿一个 sha256 就把整条工具链依赖拖进来。所以哈希下沉到本文件,changeset/index.ts
7
+ // 改为 re-export,两边字面上是同一个函数对象,口径不可能漂移。
8
+ import { createHash } from 'node:crypto';
9
+ export function contentHash(content) {
10
+ const data = typeof content === 'string' ? Buffer.from(content, 'utf8') : content;
11
+ return `sha256:${createHash('sha256').update(data).digest('hex')}`;
12
+ }
13
+ export function normalizeContentHash(value) {
14
+ const normalized = value.trim().toLowerCase();
15
+ const hex = normalized.startsWith('sha256:') ? normalized.slice(7) : normalized;
16
+ return /^[a-f0-9]{64}$/.test(hex) ? `sha256:${hex}` : null;
17
+ }
@@ -1,19 +1,15 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { chmod, copyFile, mkdir, readFile, rename, rm, rmdir, stat, writeFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
- import { createHash } from 'node:crypto';
5
4
  import { jailResolve } from '../sandbox/index.js';
6
5
  import { beginPathMutation, endPathMutation } from '../rollback/index.js';
7
6
  import { canonicalFileResourceKey, toolResourceLockManager } from '../tools/resource-lock.js';
8
- export function contentHash(content) {
9
- const data = typeof content === 'string' ? Buffer.from(content, 'utf8') : content;
10
- return `sha256:${createHash('sha256').update(data).digest('hex')}`;
11
- }
12
- export function normalizeContentHash(value) {
13
- const normalized = value.trim().toLowerCase();
14
- const hex = normalized.startsWith('sha256:') ? normalized.slice(7) : normalized;
15
- return /^[a-f0-9]{64}$/.test(hex) ? `sha256:${hex}` : null;
16
- }
7
+ // 哈希实现已下沉到 ./hash.ts(叶模块):memory/store.ts 要用同一口径算锚点 hash,
8
+ // 但它不能依赖本文件(这里拉着 sandbox/rollback/resource-lock)。re-export 保证
9
+ // 「同一个函数对象」,调用方无需改 import。
10
+ export { contentHash, normalizeContentHash } from './hash.js';
11
+ // re-export 不会把名字带进本模块作用域,内部仍在用 → 单独 import 一次。
12
+ import { contentHash } from './hash.js';
17
13
  function applyTextEdits(source, edits) {
18
14
  const ordered = [...edits].sort((left, right) => left.start - right.start || left.end - right.end);
19
15
  let cursor = 0;
@@ -7,7 +7,7 @@
7
7
  // 多字段加权 BM25:每个字段独立长度归一,字段分按 weight 加权求和。
8
8
  const CJK_RE = /[㐀-䶿一-鿿豈-﫿぀-ヿ가-힯]/;
9
9
  /** CJK 感知分词(小写)。 */
10
- export function tokenize(input) {
10
+ export function tokenize(input, mode = 'both') {
11
11
  const text = (input ?? '').toLowerCase();
12
12
  const tokens = [];
13
13
  const chars = Array.from(text);
@@ -26,8 +26,9 @@ export function tokenize(input) {
26
26
  }
27
27
  flushWord();
28
28
  if (CJK_RE.test(ch)) {
29
- tokens.push(ch); // unigram
30
- if (i + 1 < chars.length && CJK_RE.test(chars[i + 1])) {
29
+ if (mode !== 'bigram')
30
+ tokens.push(ch); // unigram
31
+ if (mode !== 'unigram' && i + 1 < chars.length && CJK_RE.test(chars[i + 1])) {
31
32
  tokens.push(ch + chars[i + 1]); // bigram
32
33
  }
33
34
  }
@@ -42,9 +43,14 @@ export class TextSearchIndex {
42
43
  ids;
43
44
  fieldStats;
44
45
  fieldWeights;
45
- constructor(docs, k1 = 1.5, b = 0.75) {
46
- this.k1 = k1;
47
- this.b = b;
46
+ mode;
47
+ minEvidence;
48
+ constructor(docs, k1OrOpts = 1.5, b = 0.75) {
49
+ const opts = typeof k1OrOpts === 'number' ? { k1: k1OrOpts, b } : (k1OrOpts ?? {});
50
+ this.k1 = opts.k1 ?? 1.5;
51
+ this.b = opts.b ?? 0.75;
52
+ this.mode = opts.tokenizeMode ?? 'both';
53
+ this.minEvidence = Math.max(0, opts.minEvidenceMatched ?? 0);
48
54
  this.ids = docs.map((d) => d.id);
49
55
  const fieldCount = Math.max(1, ...docs.map((d) => d.fields.length));
50
56
  this.fieldWeights = Array.from({ length: fieldCount }, (_, f) => docs[0]?.fields[f]?.weight ?? 1);
@@ -57,7 +63,7 @@ export class TextSearchIndex {
57
63
  docs.forEach((doc, docId) => {
58
64
  doc.fields.forEach((field, f) => {
59
65
  const stats = this.fieldStats[f];
60
- const toks = tokenize(field.text);
66
+ const toks = tokenize(field.text, this.mode);
61
67
  stats.dl.set(docId, toks.length);
62
68
  const seen = new Set();
63
69
  for (const t of toks) {
@@ -83,13 +89,18 @@ export class TextSearchIndex {
83
89
  }
84
90
  /** 检索;无有效查询词时返回空数组(调用方自行决定是否回退全量)。 */
85
91
  search(query, limit = 10) {
86
- const terms = tokenize(query);
92
+ const terms = tokenize(query, this.mode);
87
93
  if (terms.length === 0 || this.ids.length === 0)
88
94
  return [];
89
95
  const n = this.ids.length;
96
+ // 下限的分子:查询里有多少「证据词元」(长度 ≥ 2)。分母与文档无关,先算一次。
97
+ // 查询没有证据词元时(如单字「画」)整条规则退化为不过滤——短查询不该被误杀。
98
+ const evidenceTerms = this.minEvidence > 0 ? [...new Set(terms.filter((t) => t.length >= 2))] : [];
99
+ const needEvidence = evidenceTerms.length === 0 ? 0 : Math.min(this.minEvidence, evidenceTerms.length);
90
100
  const hits = [];
91
101
  for (let docId = 0; docId < n; docId++) {
92
102
  let score = 0;
103
+ const matchedEvidence = needEvidence > 0 ? new Set() : null;
93
104
  this.fieldStats.forEach((stats, f) => {
94
105
  const dl = stats.dl.get(docId);
95
106
  if (dl === undefined)
@@ -99,13 +110,20 @@ export class TextSearchIndex {
99
110
  const tf = stats.tf.get(term)?.get(docId);
100
111
  if (!tf)
101
112
  continue;
113
+ if (matchedEvidence && term.length >= 2)
114
+ matchedEvidence.add(term);
102
115
  const df = stats.df.get(term) ?? 0;
103
116
  const idf = Math.log(1 + (n - df + 0.5) / (df + 0.5));
104
117
  score += ((this.fieldWeights[f] ?? 1) * (idf * (tf * (this.k1 + 1)))) / (tf + norm);
105
118
  }
106
119
  });
107
- if (score > 0)
108
- hits.push({ id: this.ids[docId], score });
120
+ if (score <= 0)
121
+ continue;
122
+ // 相关性下限:命中证据词元数不够就不算「相关」,无论分数多高。
123
+ // 放在排序前而不是截断后:被过滤的文档不该占 limit 的名额。
124
+ if (needEvidence > 0 && (matchedEvidence?.size ?? 0) < needEvidence)
125
+ continue;
126
+ hits.push({ id: this.ids[docId], score });
109
127
  }
110
128
  hits.sort((a, b) => b.score - a.score);
111
129
  return hits.slice(0, Math.max(1, limit));
package/dist/flows/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * `mocode flow list | show <name> | run <name> [k=v ...] [--window <正则>] [--yes] [--sandbox-root <path>]`
3
- * (design-notes/computer-use-rpa.md §5.4)。
3
+ * (design-notes/computer-use/computer-use-rpa.md §5.4)。
4
4
  *
5
5
  * 非交互回放入口:不经过模型、不依赖 REPL。权限语义与 `/flow run` 一致但 fail-closed:
6
6
  * - 受 Computer Use 总开关否决(MOCODE_COMPUTER_USE_ENABLED=false);
@@ -1,5 +1,5 @@
1
1
  /**
2
- * flow 文件:格式、校验、从 trace 导出、参数模板、存取(design-notes/computer-use-rpa.md §5.2)。
2
+ * flow 文件:格式、校验、从 trace 导出、参数模板、存取(design-notes/computer-use/computer-use-rpa.md §5.2)。
3
3
  *
4
4
  * flow 是 `.mocode/flows/<name>.json`,人可编辑,是回放的唯一事实源。设计要点:
5
5
  * - 步骤是扁平对象:保留键(selector/target/fallback/window/allowCoordinateFallback/fragile/onError/note)
@@ -1,5 +1,5 @@
1
1
  /**
2
- * computer 动作的结构化录制(design-notes/computer-use-rpa.md §5.1)。
2
+ * computer 动作的结构化录制(design-notes/computer-use/computer-use-rpa.md §5.1)。
3
3
  *
4
4
  * 与 session/gui-actions.ts 的区别:台账是给模型看的有损文本(24 条滚动);trace 是给 flow 导出用的
5
5
  * 结构化 JSONL(`gui-trace.jsonl`,同会话目录),元素动作落盘的是 selector 而不是会过期的 ref。
package/dist/headless.js CHANGED
@@ -25,6 +25,9 @@ import { effectiveSystemPrompt } from './skills/index.js';
25
25
  import { buildMemoryIndexSection, gcMemories } from './memory/store.js';
26
26
  import { buildAboutYouSection, initPersona } from './memory/persona.js';
27
27
  import { buildProjectGraphHint } from './memory/recall.js';
28
+ import { buildEpisodeSection, collectChangedFiles, extractCompactionSummary, recordSessionEpisode, } from './memory/episodic.js';
29
+ import { flushProactiveStats } from './memory/proactive.js';
30
+ import { writeMemoryHealth } from './memory/health.js';
28
31
  import { defaultRuntime, Runtime } from './runtime/index.js';
29
32
  import { runAgentCore } from './agent/core.js';
30
33
  import { summarizeToolCall, summarizeToolResult } from './ui/render.js';
@@ -170,6 +173,7 @@ export async function runHeadless(opts) {
170
173
  const baseConventions = buildBasePrompt(sessionId) +
171
174
  buildAboutYouSection(memoryOn) +
172
175
  buildMemoryIndexSection(memoryOn) +
176
+ buildEpisodeSection(memoryOn) +
173
177
  buildProjectGraphHint(memoryOn);
174
178
  const systemContent = botInfo
175
179
  ? `# Role\n${botInfo.bot.systemPrompt}\n\n` +
@@ -278,7 +282,26 @@ export async function runHeadless(opts) {
278
282
  catch {
279
283
  // 落盘失败不覆盖主结果
280
284
  }
285
+ // R6.1:一次性执行同样落情节——同一个工作区下次跑 `mocode -p` 才知道上次干到哪。
286
+ // 纯本地零 LLM,失败静默(记忆是增强,不能拖垮一次性执行的退出码)。
287
+ if (memoryOn) {
288
+ try {
289
+ recordSessionEpisode({
290
+ sessionId,
291
+ queries: [prompt],
292
+ changedFiles: collectChangedFiles(history),
293
+ summaryText: extractCompactionSummary(history),
294
+ });
295
+ }
296
+ catch {
297
+ // best-effort
298
+ }
299
+ }
281
300
  closeAllMcp();
301
+ // R4.1:一次性执行同样留下度量 —— 否则 `mocode -p` 用的那一侧永远是空白。
302
+ // 只在前摄计数有增量时才落盘,健康快照失败静默。
303
+ flushProactiveStats();
304
+ writeMemoryHealth(memoryOn);
282
305
  await runtime.close();
283
306
  if (wt) {
284
307
  try {
@@ -142,7 +142,14 @@ const zhCN = {
142
142
  'prompt.revertFiles': '撤销文件改动{detail}',
143
143
  'prompt.revertDetail': '({count} 个文件恢复到回滚前)',
144
144
  'prompt.messagesOnly': '只撤销消息,保留文件改动',
145
- 'prompt.emptyPlaceholder': '输入需求,按 Enter 开始干活;或者可按 Ctrl+G 打开输入面板去编辑你的需求',
145
+ 'prompt.emptyPlaceholder': '输入需求,按 Enter 开始干活;Ctrl+G 打开输入面板,Ctrl+Y 粘贴剪贴板截图',
146
+ 'prompt.imageEmpty': '剪贴板里没有图片(先截图或复制图片,再按 Ctrl+Y)',
147
+ 'prompt.imageFailed': '[image] 剪贴板抓图失败: {reason}',
148
+ 'prompt.imageDownscaled': '⚠ 原图 {width}×{height} 超过内联上限,已降采样后附加(剪贴板原图未保存)',
149
+ 'prompt.imageDownscaledFile': '⚠ 原图 {width}×{height} 超过内联上限,已降采样后附加(磁盘原图不变)',
150
+ 'prompt.imageDownscaledBadge': '↓{width}×{height}',
151
+ 'prompt.imageVisionWarningShort': '⚠ {model} 不支持视觉',
152
+ 'commands.imageClip': '从剪贴板抓截图附加',
146
153
  'prompt.confirmSendHint': '再按一次 Enter 发送 · 其它键继续编辑',
147
154
  'composer.title': '输入面板',
148
155
  'composer.pos': '{row}/{total} 行 · {col} 列 · {chars} 字',
@@ -596,7 +603,14 @@ const en = {
596
603
  'prompt.revertFiles': 'Revert file changes{detail}',
597
604
  'prompt.revertDetail': ' ({count} files restored to before the rollback)',
598
605
  'prompt.messagesOnly': 'Roll back messages only; keep file changes',
599
- 'prompt.emptyPlaceholder': 'Type what you need, press Enter to get started; or press Ctrl+G to open the composer panel and edit your request',
606
+ 'prompt.emptyPlaceholder': 'Type what you need, press Enter to get started; Ctrl+G opens the composer, Ctrl+Y pastes a screenshot from the clipboard',
607
+ 'prompt.imageEmpty': 'No image in clipboard (screenshot or copy an image first, then press Ctrl+Y)',
608
+ 'prompt.imageFailed': '[image] clipboard capture failed: {reason}',
609
+ 'prompt.imageDownscaled': '⚠ Source {width}×{height} exceeds the inline limit; downscaled copy attached (clipboard image not saved)',
610
+ 'prompt.imageDownscaledFile': '⚠ Source {width}×{height} exceeds the inline limit; downscaled copy attached (original file unchanged)',
611
+ 'prompt.imageDownscaledBadge': '↓{width}×{height}',
612
+ 'prompt.imageVisionWarningShort': '⚠ {model} has no vision',
613
+ 'commands.imageClip': 'Attach a screenshot from the clipboard',
600
614
  'prompt.confirmSendHint': 'Press Enter again to send · any other key keeps editing',
601
615
  'composer.title': 'Composer',
602
616
  'composer.pos': '{row}/{total} lines · col {col} · {chars} chars',
package/dist/index.js CHANGED
@@ -124,7 +124,7 @@ async function main() {
124
124
  await runConfigWizard();
125
125
  process.exit(0);
126
126
  }
127
- // 桌面流程:mocode flow list | show <name> | run <name> ...(不经模型、不进 REPL;design-notes/computer-use-rpa.md §5.4)。
127
+ // 桌面流程:mocode flow list | show <name> | run <name> ...(不经模型、不进 REPL;design-notes/computer-use/computer-use-rpa.md §5.4)。
128
128
  if (args[0] === 'flow') {
129
129
  const { runFlowCli } = await import('./flows/cli.js');
130
130
  const code = await runFlowCli(args.slice(1));