mocode-ai 1.9.6 → 1.9.9

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 (47) hide show
  1. package/dist/agent/index.js +27 -0
  2. package/dist/agent/model-turn.js +6 -6
  3. package/dist/agent/request-governor.js +1 -1
  4. package/dist/context/pipeline.js +8 -3
  5. package/dist/context/vision-window.js +24 -9
  6. package/dist/host/protocol.js +4 -1
  7. package/dist/host/stdio.js +45 -1
  8. package/dist/index.js +7 -0
  9. package/dist/jobs/dir-snapshot.js +332 -0
  10. package/dist/jobs/worktree.js +78 -20
  11. package/dist/orchestrator/board.js +332 -0
  12. package/dist/orchestrator/cli.js +628 -0
  13. package/dist/orchestrator/index.js +4 -0
  14. package/dist/orchestrator/integrate.js +344 -0
  15. package/dist/orchestrator/lane-channel.js +146 -0
  16. package/dist/orchestrator/lane-executor.js +439 -0
  17. package/dist/orchestrator/lane-repl.js +154 -0
  18. package/dist/orchestrator/lane-site.js +255 -0
  19. package/dist/orchestrator/lanes.js +72 -0
  20. package/dist/orchestrator/lease.js +132 -0
  21. package/dist/orchestrator/live-log.js +193 -0
  22. package/dist/orchestrator/repl.js +435 -0
  23. package/dist/orchestrator/review.js +135 -0
  24. package/dist/orchestrator/scheduler.js +673 -0
  25. package/dist/orchestrator/scope.js +88 -0
  26. package/dist/orchestrator/state.js +533 -0
  27. package/dist/orchestrator/store.js +221 -0
  28. package/dist/orchestrator/supervisor-prompt.js +54 -0
  29. package/dist/orchestrator/supervisor.js +798 -0
  30. package/dist/orchestrator/tail.js +508 -0
  31. package/dist/orchestrator/task-prompt.js +93 -0
  32. package/dist/orchestrator/terminal.js +269 -0
  33. package/dist/orchestrator/tools.js +392 -0
  34. package/dist/orchestrator/types.js +1 -0
  35. package/dist/orchestrator/watch-panel.js +154 -0
  36. package/dist/orchestrator/worker.js +475 -0
  37. package/dist/orchestrator/workspaces.js +191 -0
  38. package/dist/repl/commands/memory.js +1 -1
  39. package/dist/repl/runtime.js +16 -2
  40. package/dist/session/compact.js +8 -1
  41. package/dist/session/store.js +1 -1
  42. package/dist/tools/builtins/ask-human.js +27 -6
  43. package/dist/tools/constants.js +10 -0
  44. package/dist/ui/handoff-block.js +91 -0
  45. package/dist/ui/layout-internal/statusbar.js +2 -1
  46. package/dist/ui/prompt-internal/editor.js +49 -0
  47. package/package.json +2 -2
@@ -18,6 +18,7 @@ import { isToolErrorOutput } from '../tools/result.js';
18
18
  import { appendCurrentSessionTraceEvent } from '../session/index.js';
19
19
  import { buildTurnRecallSection, isTurnRecallEnabled } from '../memory/turn-recall.js';
20
20
  import { memoryTailChangedIds } from '../memory/tail.js';
21
+ import { createHandoffStripper, handoffDisplaySuppressed } from '../ui/handoff-block.js';
21
22
  /** 当前 turn 的 batch id(runAgent 内闭包变量;一条 turn 一轮 tool batch 结束即清空)。 */
22
23
  let currentBatchId = null;
23
24
  /** 当前活跃的 sub-agent 组容器批 id(同一轮并行派发的多个 sub-agent 合并到这一个顶层摘要行下)。
@@ -341,7 +342,28 @@ runtimeOrContext = defaultRuntime) {
341
342
  let pendingNarration = '';
342
343
  let narrationIsNoise = false;
343
344
  const TOOL_RESULTS_NOISE_RE = /^(?:\s*Tool results:\s*)+$/i;
345
+ // lane 窗口(supervise 派活)里摘掉机器协议块:它在 task-prompt 里被要求以
346
+ // `<mocode_handoff>…</mocode_handoff>` 收尾,控制面靠它入账,但摊在屏幕上对人有百害无一利。
347
+ // 只影响显示——`finalText` 仍由 core 原样带回,parseHandoff 一个字都不少。
348
+ const handoffStrip = handoffDisplaySuppressed() ? createHandoffStripper() : null;
344
349
  function writeAssistantText(s) {
350
+ if (!handoffStrip) {
351
+ emitAssistantText(s);
352
+ return;
353
+ }
354
+ const visible = handoffStrip.push(s);
355
+ if (visible)
356
+ emitAssistantText(visible);
357
+ }
358
+ /** 流末收尾:把仍被扣住的内容吐出(未闭合的块直接丢弃,绝不把半截 JSON 漏上屏)。 */
359
+ function flushHandoffBlock() {
360
+ if (!handoffStrip)
361
+ return;
362
+ const rest = handoffStrip.flush();
363
+ if (rest)
364
+ emitAssistantText(rest);
365
+ }
366
+ function emitAssistantText(s) {
345
367
  const inToolBlock = currentBatchId !== null || subAgentGroupId !== null || subAgentGroupPendingSeparator;
346
368
  if (inToolBlock && s.trim().length === 0)
347
369
  return;
@@ -442,6 +464,9 @@ runtimeOrContext = defaultRuntime) {
442
464
  layout.contentWrite(` ${ui.accent}●${ui.reset} 压缩图片 ${info.replaced} 张转为文字卡(${info.described} 张含描述) 请求体 ${fmt(info.bytesBefore)} → ${fmt(info.bytesAfter)}\n`);
443
465
  },
444
466
  onTextEnd: () => {
467
+ // 流末:把 handoff 过滤器里扣住的尾巴处理掉(块内残渣丢弃,块外正常吐)。
468
+ // 必须在收尾换行之前——否则残留内容会落到换行之后。
469
+ flushHandoffBlock();
445
470
  // 流末正文收尾换行(此刻 content 已全部到齐,不会再出现词中间断行)。
446
471
  if (lastChar && lastChar !== '\n') {
447
472
  layout.contentWrite('\n');
@@ -476,12 +501,14 @@ runtimeOrContext = defaultRuntime) {
476
501
  },
477
502
  onAbort: () => {
478
503
  spinner.stop();
504
+ flushHandoffBlock(); // 中断时流末未必走到 onTextEnd,这里也要收场(否则扣住的内容永远不上屏)
479
505
  if (lastChar && lastChar !== '\n')
480
506
  layout.contentWrite('\n');
481
507
  flushToolBatch();
482
508
  layout.contentWrite(`${ui.dim}${t('agent.aborted')}${ui.reset}\n`);
483
509
  },
484
510
  onDone: (elapsedMs, usage) => {
511
+ flushHandoffBlock();
485
512
  flushPendingNarrationIfAny();
486
513
  flushToolBatch();
487
514
  writeChangeOverview();
@@ -2,7 +2,7 @@ import { estimatePromptTokens, estimateTokens, isContextLengthError, } from '../
2
2
  import { imageTurnAgingEnabled, visionBatch, visionKeep } from '../config/index.js';
3
3
  import { estimateRequestBytes, learnRequestByteLimit, requestByteLimit } from '../context/request-limit.js';
4
4
  import { createImageDescriber, relieveRequestBytes } from './request-governor.js';
5
- import { countOversizedImagePlaceholders, countOversizedImages } from '../context/vision-window.js';
5
+ import { countOversizedImages } from '../context/vision-window.js';
6
6
  import { getActiveSessionStore } from '../session/store.js';
7
7
  import { getCurrentSessionId } from '../session/state.js';
8
8
  import { appendGlobalUsage } from '../session/global-usage.js';
@@ -81,6 +81,7 @@ export async function runModelTurn(input) {
81
81
  tools: activeTools,
82
82
  limitBytes: byteLimit,
83
83
  extraBytes: sessionStateText ? Buffer.byteLength(sessionStateText, 'utf8') : 0,
84
+ includeScreenFrames: true,
84
85
  signal,
85
86
  describe: createImageDescriber(modelRunner),
86
87
  onStart: (info) => {
@@ -318,6 +319,7 @@ export async function runModelTurn(input) {
318
319
  tools: activeTools,
319
320
  limitBytes: learned,
320
321
  extraBytes: requestHistory.length > history.length ? failingBytes - estimateRequestBytes(history, activeTools) : 0,
322
+ includeScreenFrames: true,
321
323
  signal,
322
324
  describe: createImageDescriber(modelRunner),
323
325
  onStart: (info) => {
@@ -361,12 +363,10 @@ export async function runModelTurn(input) {
361
363
  }
362
364
  }
363
365
  }
364
- // 上游按请求体字节数拒收(而非 token):本地估算远低于窗口、history 里却有大图 → 病因是图,
365
- // 摘要压缩救不了(摘要只会把图剥掉,模型没看过图又会重读,形成「读图→400→压缩」死循环)。
366
- // 已经摘过 >=2 次仍被拒,直接抛错,不再循环。
366
+ // 上游按请求体字节数拒收(而非 token):本地估算远低于窗口、history 里却有大图 → 病因是图。
367
+ // 字节 governor 已先把旧图(含旧屏幕帧)换成卡片;若仍超限,继续落到下方的文本 compact,
368
+ // 不能因历史上已有占位就放弃恢复,否则会话会永久卡死。
367
369
  const oversizedImages = !byteResult && !overflowRetried && isContextLengthError(error) ? countOversizedImages(history) : 0;
368
- if (oversizedImages > 0 && countOversizedImagePlaceholders(history) >= 2)
369
- throw error;
370
370
  const overflowLocalEstimate = oversizedImages > 0 ? estimatePromptTokens(requestHistory, activeTools) : 0;
371
371
  const overflowWindow = ctx.config.contextWindowTokens;
372
372
  if (byteResult) {
@@ -93,7 +93,7 @@ export async function relieveRequestBytes(input) {
93
93
  });
94
94
  if (!(limitBytes > 0))
95
95
  return idle('no_limit');
96
- const plan = planImageRelief(listReplaceableImages(messages), bytesBefore, limitBytes);
96
+ const plan = planImageRelief(listReplaceableImages(messages, { includeScreenFrames: input.includeScreenFrames }), bytesBefore, limitBytes);
97
97
  if (plan.kind !== 'replace')
98
98
  return idle(plan.kind);
99
99
  try {
@@ -14,7 +14,7 @@ import { builtinEncoders } from './encoders/index.js';
14
14
  import { passthroughEncoder } from './encoders/passthrough.js';
15
15
  import { capToolResultForHistory } from '../session/compact.js';
16
16
  import { config } from '../config/index.js';
17
- import { MAX_HISTORY_RESULT, MAX_SKILL_RESULT, MAX_MEMORY_RESULT } from '../tools/constants.js';
17
+ import { MAX_COMMAND_HISTORY_RESULT, MAX_HISTORY_RESULT, MAX_SKILL_RESULT, MAX_MEMORY_RESULT, } from '../tools/constants.js';
18
18
  let booted = false;
19
19
  /** 懒注册内置 encoder(首次调用 optimizeToolResult 时触发,避免模块加载期循环 import)。 */
20
20
  function boot() {
@@ -33,8 +33,9 @@ function tryParseArgs(raw) {
33
33
  }
34
34
  }
35
35
  /**
36
- * 按工具名取软目标 budget(字符)。对齐 capToolResultForHistory 的放宽规则:
37
- * use_skill / memory_search 走放宽上限(指令 / 记忆正文须完整);其余走 MAX_HISTORY_RESULT。
36
+ * 按工具名取软目标 budget(字符)。对齐 capToolResultForHistory 的分工具规则:
37
+ * use_skill / memory_search 走放宽上限(指令 / 记忆正文须完整);run_command 走更紧的
38
+ * 专属上限;其余走 MAX_HISTORY_RESULT。
38
39
  * 仅作 encoder 软目标;最终裁剪仍由末尾 capToolResultForHistory 兜底,故两处常量偶有漂移不致命。
39
40
  */
40
41
  function budgetFor(name) {
@@ -42,6 +43,10 @@ function budgetFor(name) {
42
43
  return MAX_SKILL_RESULT;
43
44
  if (name === 'memory_search')
44
45
  return MAX_MEMORY_RESULT;
46
+ // 与 capToolResultForHistory 的 run_command 专属上限同源,避免 encoder 仍按通用上限
47
+ // 产出过长文本、再被末尾硬裁一次。
48
+ if (name === 'run_command')
49
+ return MAX_COMMAND_HISTORY_RESULT;
45
50
  return MAX_HISTORY_RESULT;
46
51
  }
47
52
  /**
@@ -486,16 +486,18 @@ function findSourcePath(messages, msgIndex, name) {
486
486
  }
487
487
  /**
488
488
  * 列出 history 里可被换成文字卡的图片(按出现顺序,旧在前):非屏幕帧的工具图与用户粘贴图。
489
- * `computer-` 屏幕帧由 applyVisionWindow 管,这里不碰。纯函数、永不抛错。
489
+ * 请求体字节预算可显式纳入 Computer Use 屏幕帧,但始终保留最新一帧供当前操作 grounding。
490
+ * 纯函数、永不抛错。
490
491
  */
491
- export function listReplaceableImages(messages) {
492
+ export function listReplaceableImages(messages, opts = {}) {
492
493
  const out = [];
493
494
  try {
494
495
  if (!Array.isArray(messages))
495
496
  return out;
497
+ const includeScreenFrames = opts.includeScreenFrames === true;
496
498
  for (let i = 0; i < messages.length; i++) {
497
499
  const parts = userContentParts(messages[i]);
498
- if (!parts || imagePartCount(parts) === 0 || isFrameCarrier(messages[i]))
500
+ if (!parts || imagePartCount(parts) === 0)
499
501
  continue;
500
502
  const names = frameNames(messages[i]);
501
503
  let imageIndex = 0;
@@ -504,7 +506,8 @@ export function listReplaceableImages(messages) {
504
506
  continue;
505
507
  const name = names ? names[imageIndex] : undefined;
506
508
  imageIndex++;
507
- if (name !== undefined && VISION_FRAME_NAME_PREFIXES.some((prefix) => name.startsWith(prefix)))
509
+ const screenFrame = name !== undefined && VISION_FRAME_NAME_PREFIXES.some((prefix) => name.startsWith(prefix));
510
+ if (screenFrame && !includeScreenFrames)
508
511
  continue;
509
512
  const dataUrl = imageUrlOf(parts[j]);
510
513
  out.push({
@@ -514,10 +517,20 @@ export function listReplaceableImages(messages) {
514
517
  chars: dataUrl.length,
515
518
  dataUrl,
516
519
  name,
520
+ screenFrame,
517
521
  path: name !== undefined ? findSourcePath(messages, i, name) : undefined,
518
522
  });
519
523
  }
520
524
  }
525
+ // 字节预算的兜底不能让模型丢失当前 GUI 状态。仅纳入旧帧,最后一帧不参与候选。
526
+ if (includeScreenFrames) {
527
+ for (let i = out.length - 1; i >= 0; i--) {
528
+ if (out[i].screenFrame) {
529
+ out.splice(i, 1);
530
+ break;
531
+ }
532
+ }
533
+ }
521
534
  }
522
535
  catch {
523
536
  // 永不抛错:返回已收集到的部分。
@@ -528,11 +541,13 @@ export function listReplaceableImages(messages) {
528
541
  export function buildImageCard(img, description) {
529
542
  const kb = Math.round(img.chars / 1024);
530
543
  const label = img.name ?? 'pasted image';
531
- const reread = img.path
532
- ? `For details, call read_file on "${img.path}" again.`
533
- : img.name
534
- ? `For details, call read_file on the file "${img.name}" again.`
535
- : 'It has no file path and cannot be re-read.';
544
+ const reread = img.screenFrame
545
+ ? 'It was a past Computer Use screen frame. Call computer with action "screenshot" to capture the current screen if you need it.'
546
+ : img.path
547
+ ? `For details, call read_file on "${img.path}" again.`
548
+ : img.name
549
+ ? `For details, call read_file on the file "${img.name}" again.`
550
+ : 'It has no file path and cannot be re-read.';
536
551
  const body = description
537
552
  ? `Summary: ${description.trim().slice(0, IMAGE_CARD_MAX_DESCRIPTION_CHARS)}`
538
553
  : 'No summary is available (the image was not seen).';
@@ -34,7 +34,10 @@ export function parseCommand(value) {
34
34
  id: input.id,
35
35
  type: 'approval',
36
36
  approvalId: input.approvalId,
37
- action: input.action === 'selected' ? 'selected' : 'cancelled',
37
+ // 白名单而不是强转:未知取值一律当取消(fail-closed),不给「拼错的 action 意外放行」留口子。
38
+ action: input.action === 'selected' || input.action === 'submitted'
39
+ ? input.action
40
+ : 'cancelled',
38
41
  value: typeof input.value === 'string' ? input.value : undefined,
39
42
  };
40
43
  }
@@ -11,6 +11,7 @@ import { ToolPolicyController } from '../tools/policy.js';
11
11
  import { routeToolGroups } from '../tools/router.js';
12
12
  // 装配官方默认工具包:registry 不再顶层 import builtins(破模块循环),host 入口须显式装配。
13
13
  import '../tools/builtins/index.js';
14
+ import { setAskHumanHandler } from '../tools/builtins/ask-human.js';
14
15
  import { parseCommand } from './protocol.js';
15
16
  let initialized = null;
16
17
  let runtimeFacade = null;
@@ -53,12 +54,33 @@ async function initializeRuntime() {
53
54
  await createdRuntime.start();
54
55
  if (closing)
55
56
  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'));
74
+ }
56
75
  const runtimeConfig = createdRuntime.context.config;
57
76
  emit('runtime_ready', {
58
77
  projectRoot: createdRuntime.context.sandboxRoot,
59
78
  provider: runtimeConfig.provider,
60
79
  promptCache: runtimeConfig.provider === 'anthropic' && runtimeConfig.anthropicPromptCache,
61
80
  warnings: getMcpWarnings(),
81
+ // Supervised Worker 的控制面靠这两个字段确认「这个 host 是谁、还活着」。
82
+ pid: process.pid,
83
+ ...(process.env.MOCODE_WORKER_ID ? { workerId: process.env.MOCODE_WORKER_ID } : {}),
62
84
  });
63
85
  })();
64
86
  return initialized;
@@ -107,12 +129,15 @@ function prepareSession(requestedSessionId) {
107
129
  return true;
108
130
  return restoreSession(requestedSessionId) ? true : null;
109
131
  }
110
- function waitForApproval(runId, request) {
132
+ function waitForApproval(runId, request, kind = 'permission') {
111
133
  if (closing)
112
134
  return Promise.resolve({ action: 'cancelled' });
113
135
  const approvalId = randomUUID();
114
136
  emit('approval_requested', {
115
137
  approvalId,
138
+ // `kind` 让控制面能区分「工具权限面板」与「Worker 主动提问」:措辞、默认选项、
139
+ // 以及回答后回给模型的话术都不一样。旧客户端不认识它会忽略,行为与以前一致。
140
+ kind,
116
141
  title: request.title,
117
142
  detail: request.detail ?? '',
118
143
  options: (request.options ?? []).map((option) => (typeof option === 'string' ? option : option.label)),
@@ -324,6 +349,22 @@ async function handle(command) {
324
349
  return compact(command);
325
350
  resolveApproval(command);
326
351
  }
352
+ /** 心跳间隔:控制面用「最近一次心跳」判断 Worker 是卡死还是进程已死。 */
353
+ const HEARTBEAT_MS = 5_000;
354
+ /**
355
+ * Supervised Worker 才发心跳:普通 work-app 宿主不需要这份额外流量,
356
+ * 且旧客户端不认识这个事件(保持默认行为不变)。
357
+ */
358
+ function startHeartbeat() {
359
+ if (process.env.MOCODE_SUPERVISED_WORKER !== '1')
360
+ return undefined;
361
+ const timer = setInterval(() => {
362
+ emit('heartbeat', { pid: process.pid, at: Date.now() });
363
+ }, HEARTBEAT_MS);
364
+ // 不因为心跳把进程钉在事件循环上:stdin 关闭时该退就退。
365
+ timer.unref?.();
366
+ return timer;
367
+ }
327
368
  function requestShutdownCancellation() {
328
369
  activeRun?.controller.abort(hostClosedReason);
329
370
  runtimeFacade?.cancel(hostClosedReason);
@@ -334,6 +375,7 @@ function requestShutdownCancellation() {
334
375
  }
335
376
  const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
336
377
  const pendingCommands = new Set();
378
+ const heartbeatTimer = startHeartbeat();
337
379
  const startupPromise = initializeRuntime();
338
380
  void startupPromise.catch((cause) => error(cause instanceof Error ? cause.message : String(cause)));
339
381
  for await (const line of input) {
@@ -363,3 +405,5 @@ await Promise.allSettled([...pendingCommands]);
363
405
  const runtimeAtShutdown = runtimeFacade;
364
406
  await runtimeAtShutdown?.close().catch(() => undefined);
365
407
  await closeAllMcp().catch(() => undefined);
408
+ if (heartbeatTimer)
409
+ clearInterval(heartbeatTimer);
package/dist/index.js CHANGED
@@ -131,6 +131,13 @@ async function main() {
131
131
  await shutdownRuntime();
132
132
  process.exit(code);
133
133
  }
134
+ // Super Agent 编排:独立完整 mocode Worker + 可恢复任务 DAG(不进入普通 REPL)。
135
+ if (args[0] === 'supervise') {
136
+ const { runSuperviseCli } = await import('./orchestrator/cli.js');
137
+ const code = await runSuperviseCli(args.slice(1));
138
+ await shutdownRuntime();
139
+ process.exit(code);
140
+ }
134
141
  // Job runner 内部模式:detached 子进程入口。
135
142
  const runnerIdx = args.indexOf('--job-runner');
136
143
  if (runnerIdx !== -1) {
@@ -0,0 +1,332 @@
1
+ // 非 git 工作区的隔离执行支持:目录副本、目录索引快照、索引差分与 unified diff。
2
+ //
3
+ // git 仓库有 worktree + tree 对象,非 git 目录什么都没有。这里给出等价物:
4
+ // - createDirCopy:把工作区复制成一份可随意改动的副本(默认排除 node_modules/.git/.mocode 的运行时目录);
5
+ // - snapshotDirectory:把「文件 → size/mtime」索引落成 JSON,作为一次 attempt 的基线;
6
+ // - diffSnapshots:两次索引的差集(新增/删除/修改),作为 changedFiles 与契约校验的输入;
7
+ // - diffRoots:对指定文件生成 unified diff(供 lane.diff / attempt.diff)。
8
+ //
9
+ // 设计取舍:索引只存 size+mtimeMs 而不是内容哈希——快照要能在大目录上秒级完成,
10
+ // 内容比较留给真正需要 diff 的那几个文件。mtime 相同时的漏判由「大小变化 + diff 阶段
11
+ // 内容比较」兜底;代价是同一毫秒内的原地覆盖可能被漏掉,非 git 目录接受此限制。
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ /** 整目录跳过的目录名(无论在哪个层级)。 */
15
+ const SKIPPED_DIRS = new Set(['node_modules', '.git']);
16
+ /** 只在工作区根下跳过的相对路径(大小写按平台处理)。 */
17
+ const SKIPPED_RELATIVE = ['.mocode/orchestrations', '.mocode/worktrees', '.mocode/lanes'];
18
+ /**
19
+ * `.mocode` 下由项目自己维护、值得审计的路径。
20
+ * 其余 `.mocode/**` 全是 mocode 的运行时状态(会话、编排账本、记忆、统计、便签…)。
21
+ */
22
+ const MOCODE_KEPT_PREFIXES = ['.mocode/config', '.mocode/skills', '.mocode/agents-draft.md'];
23
+ /**
24
+ * 是否属于 mocode 自身的运行时状态。
25
+ *
26
+ * 用来区分「Worker 改了用户代码」和「Worker 只是让 mocode 写了自己的记忆/统计」:
27
+ * 后者不能算成任务改动,否则 `read_only` 任务会被自己的运行时文件误判为「改了文件」而失败。
28
+ */
29
+ export function isMocodeRuntimeState(rel) {
30
+ const normalized = normalizeRel(rel).toLowerCase();
31
+ if (normalized !== '.mocode' && !normalized.startsWith('.mocode/'))
32
+ return false;
33
+ return !MOCODE_KEPT_PREFIXES.some((kept) => normalized === kept || normalized.startsWith(`${kept}/`));
34
+ }
35
+ function normalizeRel(rel) {
36
+ return rel.split(path.sep).join('/');
37
+ }
38
+ function skipRelative(rel, extra, ignore) {
39
+ const normalized = normalizeRel(rel);
40
+ if (ignore?.(normalized))
41
+ return true;
42
+ const lower = normalized.toLowerCase();
43
+ for (const dir of SKIPPED_DIRS) {
44
+ if (normalized === dir || normalized.startsWith(`${dir}/`))
45
+ return true;
46
+ // 任意层级的 node_modules 都要排除(monorepo)。
47
+ if (normalized.includes(`/${dir}/`) || normalized.endsWith(`/${dir}`))
48
+ return true;
49
+ }
50
+ for (const rule of [...SKIPPED_RELATIVE, ...extra]) {
51
+ const target = rule.toLowerCase();
52
+ if (lower === target || lower.startsWith(`${target}/`))
53
+ return true;
54
+ }
55
+ return false;
56
+ }
57
+ /**
58
+ * 扫描目录得到索引快照。符号链接按零字节文件记录(不跟随,避免环与越界)。
59
+ * 任何不可读条目都被跳过:快照是增强能力,不能因为一个坏文件让整次派活失败。
60
+ */
61
+ export function snapshotDirectory(root, options = {}) {
62
+ const absolute = path.resolve(root);
63
+ const entries = {};
64
+ const extra = options.excludes ?? [];
65
+ const walk = (dir, relBase) => {
66
+ let dirents;
67
+ try {
68
+ dirents = fs.readdirSync(dir, { withFileTypes: true });
69
+ }
70
+ catch {
71
+ return;
72
+ }
73
+ for (const entry of dirents.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
74
+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
75
+ if (skipRelative(rel, extra, options.ignore))
76
+ continue;
77
+ const full = path.join(dir, entry.name);
78
+ if (entry.isDirectory()) {
79
+ walk(full, rel);
80
+ continue;
81
+ }
82
+ try {
83
+ const stat = fs.lstatSync(full);
84
+ entries[rel] = { size: entry.isSymbolicLink() ? 0 : stat.size, mtimeMs: stat.mtimeMs };
85
+ }
86
+ catch {
87
+ // 并发删除等情况直接忽略。
88
+ }
89
+ }
90
+ };
91
+ walk(absolute, '');
92
+ return { version: 1, root: absolute, createdAt: new Date().toISOString(), entries };
93
+ }
94
+ export function writeSnapshot(file, snapshot) {
95
+ fs.mkdirSync(path.dirname(file), { recursive: true });
96
+ fs.writeFileSync(file, `${JSON.stringify(snapshot)}\n`, 'utf8');
97
+ return file;
98
+ }
99
+ export function readSnapshot(file) {
100
+ const raw = fs.readFileSync(file, 'utf8');
101
+ const parsed = JSON.parse(raw);
102
+ if (parsed.version !== 1 || typeof parsed.entries !== 'object' || parsed.entries === null) {
103
+ throw new Error(`Unsupported directory snapshot: ${file}`);
104
+ }
105
+ return parsed;
106
+ }
107
+ export function diffSnapshots(before, after) {
108
+ const added = [];
109
+ const removed = [];
110
+ const modified = [];
111
+ for (const [rel, entry] of Object.entries(after.entries)) {
112
+ const previous = before.entries[rel];
113
+ if (!previous)
114
+ added.push(rel);
115
+ else if (previous.size !== entry.size || previous.mtimeMs !== entry.mtimeMs)
116
+ modified.push(rel);
117
+ }
118
+ for (const rel of Object.keys(before.entries)) {
119
+ if (!after.entries[rel])
120
+ removed.push(rel);
121
+ }
122
+ const changed = [...new Set([...added, ...removed, ...modified])].sort();
123
+ return { added: added.sort(), removed: removed.sort(), modified: modified.sort(), changed };
124
+ }
125
+ /** 估算某个路径(文件或目录)的字节数,跳过与快照相同的排除规则。 */
126
+ export function pathBytes(root, options = {}) {
127
+ const absolute = path.resolve(root);
128
+ let stat;
129
+ try {
130
+ stat = fs.statSync(absolute);
131
+ }
132
+ catch {
133
+ return 0;
134
+ }
135
+ if (stat.isFile())
136
+ return stat.size;
137
+ const extra = options.excludes ?? [];
138
+ let total = 0;
139
+ const walk = (dir, relBase) => {
140
+ let dirents;
141
+ try {
142
+ dirents = fs.readdirSync(dir, { withFileTypes: true });
143
+ }
144
+ catch {
145
+ return;
146
+ }
147
+ for (const entry of dirents) {
148
+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
149
+ if (skipRelative(rel, extra, options.ignore))
150
+ continue;
151
+ const full = path.join(dir, entry.name);
152
+ if (entry.isDirectory())
153
+ walk(full, rel);
154
+ else {
155
+ try {
156
+ total += fs.lstatSync(full).size;
157
+ }
158
+ catch {
159
+ // 忽略
160
+ }
161
+ }
162
+ }
163
+ };
164
+ walk(absolute, '');
165
+ return total;
166
+ }
167
+ export class LaneCopyTooLargeError extends Error {
168
+ source;
169
+ bytes;
170
+ limit;
171
+ constructor(source, bytes, limit) {
172
+ super(`workspace copy would be ${Math.round(bytes / 1024 / 1024)}MB, over the ${Math.round(limit / 1024 / 1024)}MB budget ` +
173
+ `(source: ${source}). Raise MOCODE_LANE_COPY_MAX_MB, pass --allow-inplace, or use a read-only task.`);
174
+ this.source = source;
175
+ this.bytes = bytes;
176
+ this.limit = limit;
177
+ this.name = 'LaneCopyTooLargeError';
178
+ }
179
+ }
180
+ export const DEFAULT_LANE_COPY_MAX_MB = 512;
181
+ export function laneCopyLimitBytes(env = process.env) {
182
+ const configured = Number(env.MOCODE_LANE_COPY_MAX_MB);
183
+ const megabytes = Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_LANE_COPY_MAX_MB;
184
+ return megabytes * 1024 * 1024;
185
+ }
186
+ /**
187
+ * 复制目录。超预算时抛 LaneCopyTooLargeError,绝不降级为原地写——
188
+ * 原地写是用户决定(`--allow-inplace`),系统不能自己替他选。
189
+ */
190
+ export function createDirCopy(source, target, options = {}) {
191
+ const from = path.resolve(source);
192
+ const to = path.resolve(target);
193
+ if (from === to)
194
+ throw new Error('Refusing to copy a directory onto itself.');
195
+ const limit = options.maxBytes ?? laneCopyLimitBytes();
196
+ const bytes = pathBytes(from, options);
197
+ if (limit > 0 && bytes > limit)
198
+ throw new LaneCopyTooLargeError(from, bytes, limit);
199
+ fs.rmSync(to, { recursive: true, force: true });
200
+ fs.mkdirSync(path.dirname(to), { recursive: true });
201
+ fs.cpSync(from, to, {
202
+ recursive: true,
203
+ force: true,
204
+ errorOnExist: false,
205
+ filter: (src) => {
206
+ if (path.resolve(src) === to)
207
+ return false;
208
+ const rel = normalizeRel(path.relative(from, src));
209
+ if (!rel)
210
+ return true;
211
+ // .mocode 下只排除运行时产物,保留 sessions/config 以便 Worker 有上下文。
212
+ return !skipRelative(rel, options.excludes ?? []);
213
+ },
214
+ });
215
+ return to;
216
+ }
217
+ // ── unified diff ─────────────────────────────────────────────────────────────
218
+ const MAX_DIFF_CELLS = 4_000_000;
219
+ function splitLines(text) {
220
+ if (!text)
221
+ return [];
222
+ const normalized = text.endsWith('\n') ? text.slice(0, -1) : text;
223
+ return normalized.split('\n');
224
+ }
225
+ /** LCS-based 行级 diff。超过规模上限时退化为「整文件替换」,避免 O(n*m) 卡死。 */
226
+ function lineOps(before, after) {
227
+ const n = before.length;
228
+ const m = after.length;
229
+ if (n * m > MAX_DIFF_CELLS) {
230
+ return [
231
+ ...before.map((line) => ({ kind: '-', line })),
232
+ ...after.map((line) => ({ kind: '+', line })),
233
+ ];
234
+ }
235
+ const table = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
236
+ for (let i = n - 1; i >= 0; i--) {
237
+ for (let j = m - 1; j >= 0; j--) {
238
+ table[i][j] = before[i] === after[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
239
+ }
240
+ }
241
+ const ops = [];
242
+ let i = 0;
243
+ let j = 0;
244
+ while (i < n && j < m) {
245
+ if (before[i] === after[j]) {
246
+ ops.push({ kind: ' ', line: before[i] });
247
+ i++;
248
+ j++;
249
+ }
250
+ else if (table[i + 1][j] >= table[i][j + 1]) {
251
+ ops.push({ kind: '-', line: before[i++] });
252
+ }
253
+ else {
254
+ ops.push({ kind: '+', line: after[j++] });
255
+ }
256
+ }
257
+ while (i < n)
258
+ ops.push({ kind: '-', line: before[i++] });
259
+ while (j < m)
260
+ ops.push({ kind: '+', line: after[j++] });
261
+ return ops;
262
+ }
263
+ /** 生成单个文件的 unified diff(含 3 行上下文)。无差异返回空串。 */
264
+ export function unifiedDiff(beforeText, afterText, label, context = 3) {
265
+ if (beforeText === afterText)
266
+ return '';
267
+ const ops = lineOps(splitLines(beforeText), splitLines(afterText));
268
+ const changed = ops.map((op, index) => (op.kind === ' ' ? -1 : index)).filter((index) => index >= 0);
269
+ if (changed.length === 0)
270
+ return '';
271
+ // 合并相邻改动,避免同一段被切成一堆小 hunk。
272
+ const hunks = [];
273
+ for (const index of changed) {
274
+ const last = hunks.at(-1);
275
+ if (last && index - last[1] <= context * 2)
276
+ last[1] = index;
277
+ else
278
+ hunks.push([index, index]);
279
+ }
280
+ const out = [`--- a/${label}`, `+++ b/${label}`];
281
+ for (const [start, end] of hunks) {
282
+ const from = Math.max(0, start - context);
283
+ const to = Math.min(ops.length - 1, end + context);
284
+ const slice = ops.slice(from, to + 1);
285
+ const beforeCount = slice.filter((op) => op.kind !== '+').length;
286
+ const afterCount = slice.filter((op) => op.kind !== '-').length;
287
+ const beforeStart = ops.slice(0, from).filter((op) => op.kind !== '+').length + 1;
288
+ const afterStart = ops.slice(0, from).filter((op) => op.kind !== '-').length + 1;
289
+ out.push(`@@ -${beforeStart},${beforeCount} +${afterStart},${afterCount} @@`);
290
+ for (const op of slice)
291
+ out.push(`${op.kind}${op.line}`);
292
+ }
293
+ return `${out.join('\n')}\n`;
294
+ }
295
+ function isBinary(buffer) {
296
+ const limit = Math.min(buffer.length, 8000);
297
+ for (let i = 0; i < limit; i++)
298
+ if (buffer[i] === 0)
299
+ return true;
300
+ return false;
301
+ }
302
+ function readTextOrNull(file) {
303
+ try {
304
+ const buffer = fs.readFileSync(file);
305
+ return isBinary(buffer) ? null : buffer.toString('utf8');
306
+ }
307
+ catch {
308
+ return null;
309
+ }
310
+ }
311
+ /** 把相对路径列表转换为 unified diff。二进制/不可读文件以一行说明代替内容。 */
312
+ export function diffRoots(beforeRoot, afterRoot, files, options = {}) {
313
+ const chunks = [];
314
+ for (const rel of [...files].sort()) {
315
+ if (skipRelative(rel, options.excludes ?? [], options.ignore))
316
+ continue;
317
+ const beforePath = path.join(beforeRoot, rel);
318
+ const afterPath = path.join(afterRoot, rel);
319
+ const beforeExists = fs.existsSync(beforePath);
320
+ const afterExists = fs.existsSync(afterPath);
321
+ const before = beforeExists ? readTextOrNull(beforePath) : '';
322
+ const after = afterExists ? readTextOrNull(afterPath) : '';
323
+ if (before === null || after === null) {
324
+ chunks.push(`--- a/${rel}\n+++ b/${rel}\n@@ binary @@\n(binary file changed)\n`);
325
+ continue;
326
+ }
327
+ const diff = unifiedDiff(before, after, rel);
328
+ if (diff)
329
+ chunks.push(diff);
330
+ }
331
+ return chunks.join('');
332
+ }