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
@@ -0,0 +1,154 @@
1
+ // `mocode supervise watch`(无 run id)= 监管工作台面板。
2
+ //
3
+ // 为什么不复用 REPL 的 layout 栈:那套是「内容区 + 固定底栏 + 输入框」的单对话布局,
4
+ // 有 spinner、状态栏心跳、DECSTBM 滚动区、markdown 重排等一堆为对话服务的状态。
5
+ // 工作台是一次性全屏只读视图,自己管 alt screen 更简单,也不会与 REPL 全局单例互相污染
6
+ // (面板退出后 REPL 仍然干净)。
7
+ //
8
+ // 交互:↑/↓ 或 j/k 移动,g/G 首尾,Enter 无副作用(宽屏已常驻详情),r 立即刷新,q/Esc 退出。
9
+ // 非 TTY 或 `--json` 走 `formatBoardSnapshot` 一次性输出,脚本可直接消费。
10
+ import { stdin, stdout } from 'node:process';
11
+ import readline from 'node:readline';
12
+ import { ui } from '../ui/theme.js';
13
+ import { boardRows, collectBoard, renderBoard } from './board.js';
14
+ const ESC = '\x1B[';
15
+ const ALT_ON = `${ESC}?1049h`;
16
+ const ALT_OFF = `${ESC}?1049l`;
17
+ const CURSOR_OFF = `${ESC}?25l`;
18
+ const CURSOR_ON = `${ESC}?25h`;
19
+ const CLEAR_BELOW = `${ESC}0J`;
20
+ function collect(options) {
21
+ if (options.collect)
22
+ return options.collect(options.workspaces);
23
+ return collectBoard({ workspaces: options.workspaces });
24
+ }
25
+ /** 每帧:整屏重画(工作台行数不多,全量写比增量 diff 稳,且不会残留旧字符)。 */
26
+ function paint(lines) {
27
+ let frame = `${ESC}H`;
28
+ for (const line of lines) {
29
+ // 行尾 EL:上一帧更长时不会留下尾巴。
30
+ frame += `${line}${ESC}K\r\n`;
31
+ }
32
+ stdout.write(`${frame}${CLEAR_BELOW}`);
33
+ }
34
+ /**
35
+ * 进入面板直到用户退出。返回进程退出码(0 = 正常退出,130 = Ctrl-C)。
36
+ * 非 TTY 不进入面板:返回 1 并给出提示,让调用方退化到一次性快照。
37
+ */
38
+ export async function runBoardPanel(options) {
39
+ if (!stdout.isTTY || !stdin.isTTY)
40
+ return 1;
41
+ let board = collect(options);
42
+ let rows = boardRows(board);
43
+ let selected = 0;
44
+ let stopped = false;
45
+ let timer;
46
+ const height = () => stdout.rows || 24;
47
+ const width = () => stdout.columns || 80;
48
+ const draw = () => {
49
+ const rendered = renderBoard(board, { cols: width(), rows: height(), selected });
50
+ rows = rendered.rows;
51
+ if (rows.length > 0)
52
+ selected = Math.min(selected, rows.length - 1);
53
+ paint(rendered.lines);
54
+ options.onFrame?.(board, { lines: rendered.lines, selected });
55
+ };
56
+ const refresh = () => {
57
+ board = collect(options);
58
+ rows = boardRows(board);
59
+ if (rows.length > 0)
60
+ selected = Math.min(selected, rows.length - 1);
61
+ draw();
62
+ };
63
+ const cleanup = () => {
64
+ if (stopped)
65
+ return;
66
+ stopped = true;
67
+ if (timer)
68
+ clearInterval(timer);
69
+ timer = undefined;
70
+ process.removeListener('SIGWINCH', onResize);
71
+ stdin.removeListener('keypress', onKey);
72
+ try {
73
+ stdin.setRawMode(false);
74
+ }
75
+ catch {
76
+ // 非 TTY / 不支持:忽略
77
+ }
78
+ stdin.pause();
79
+ stdout.write(`${CURSOR_ON}${ALT_OFF}`);
80
+ };
81
+ const onResize = () => draw();
82
+ function onKey(_str, key) {
83
+ if (key.ctrl && key.name === 'c') {
84
+ cleanup();
85
+ resolveExit(130);
86
+ return;
87
+ }
88
+ switch (key.name) {
89
+ case 'q':
90
+ case 'escape':
91
+ cleanup();
92
+ resolveExit(0);
93
+ return;
94
+ case 'up':
95
+ case 'k':
96
+ if (rows.length > 0)
97
+ selected = (selected - 1 + rows.length) % rows.length;
98
+ draw();
99
+ return;
100
+ case 'down':
101
+ case 'j':
102
+ if (rows.length > 0)
103
+ selected = (selected + 1) % rows.length;
104
+ draw();
105
+ return;
106
+ case 'g':
107
+ selected = 0;
108
+ draw();
109
+ return;
110
+ case 'G':
111
+ selected = Math.max(0, rows.length - 1);
112
+ draw();
113
+ return;
114
+ case 'r':
115
+ refresh();
116
+ return;
117
+ default:
118
+ return;
119
+ }
120
+ }
121
+ let resolveExit;
122
+ const done = new Promise((resolve) => {
123
+ resolveExit = resolve;
124
+ });
125
+ stdout.write(`${ALT_ON}${CURSOR_OFF}`);
126
+ readline.emitKeypressEvents(stdin);
127
+ try {
128
+ stdin.setRawMode(true);
129
+ }
130
+ catch {
131
+ // 不支持 raw:按键不会来,但画面仍可看;交给定时器/信号退出。
132
+ }
133
+ stdin.resume();
134
+ stdin.on('keypress', onKey);
135
+ process.on('SIGWINCH', onResize);
136
+ draw();
137
+ const interval = options.refreshMs ?? 1500;
138
+ if (interval > 0) {
139
+ timer = setInterval(refresh, interval);
140
+ timer.unref?.();
141
+ }
142
+ if (options.shouldExit) {
143
+ const poll = setInterval(() => {
144
+ if (options.shouldExit?.()) {
145
+ cleanup();
146
+ resolveExit(0);
147
+ }
148
+ }, 20);
149
+ poll.unref?.();
150
+ }
151
+ return done;
152
+ }
153
+ /** 面板头部的说明行,供 `--help` 与文档引用。 */
154
+ export const BOARD_HINT = `${ui.dim}监管工作台:↑↓ 选择 · r 刷新 · q 退出(mocode supervise watch <run-id> 看单个 Run 的事件流)${ui.reset}`;
@@ -0,0 +1,475 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { LaneSite } from './lane-site.js';
5
+ import { handoffViolation, parseHandoff, taskPrompt } from './task-prompt.js';
6
+ // 现场逻辑(worktree / copy / inplace 的打开、基线、差分、收尾)已抽到 ./lane-site.ts,
7
+ // 因为可视执行器 `LaneReplExecutor` 要用同一套口径。这两个函数是历史导出点,测试仍在用。
8
+ export { isWithin, resolveCopyTarget } from './lane-site.js';
9
+ function defaultHostPath() {
10
+ return fileURLToPath(new URL('../../bin/mocode-agent-host.js', import.meta.url));
11
+ }
12
+ async function killWorkerTree(child) {
13
+ if (child.exitCode !== null)
14
+ return;
15
+ if (process.platform === 'win32' && child.pid) {
16
+ // Windows: taskkill /T 覆盖 Host 自己派生的子进程(run_command 等),单 kill 会留孤儿。
17
+ await new Promise((resolve) => {
18
+ const killer = spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], {
19
+ stdio: 'ignore',
20
+ windowsHide: true,
21
+ });
22
+ killer.on('close', () => resolve());
23
+ killer.on('error', () => resolve());
24
+ });
25
+ if (child.exitCode === null) {
26
+ try {
27
+ child.kill();
28
+ }
29
+ catch {
30
+ // Already gone.
31
+ }
32
+ }
33
+ return;
34
+ }
35
+ try {
36
+ child.kill('SIGKILL');
37
+ }
38
+ catch {
39
+ // Already gone.
40
+ }
41
+ }
42
+ async function stopChild(child, timeoutMs) {
43
+ if (child.exitCode !== null)
44
+ return;
45
+ await new Promise((resolve) => {
46
+ let settled = false;
47
+ const finish = () => {
48
+ if (settled)
49
+ return;
50
+ settled = true;
51
+ clearTimeout(timer);
52
+ child.off('exit', finish);
53
+ child.off('close', finish);
54
+ child.off('error', finish);
55
+ resolve();
56
+ };
57
+ const timer = setTimeout(() => {
58
+ void killWorkerTree(child).finally(finish);
59
+ }, timeoutMs);
60
+ child.once('exit', finish);
61
+ child.once('close', finish);
62
+ child.once('error', finish);
63
+ try {
64
+ child.stdin.end();
65
+ }
66
+ catch {
67
+ void killWorkerTree(child).finally(finish);
68
+ }
69
+ });
70
+ }
71
+ function messageFor(event, payload) {
72
+ if (event === 'status')
73
+ return typeof payload.value === 'string' ? payload.value : null;
74
+ if (event === 'tool_started')
75
+ return typeof payload.name === 'string' ? `tool: ${payload.name}` : null;
76
+ if (event === 'tool_completed')
77
+ return typeof payload.name === 'string' ? `tool done: ${payload.name}` : null;
78
+ return null;
79
+ }
80
+ export class HostWorkerExecutor {
81
+ /** 在跑的 Host 进程,按 requestId 记录:并发调度下同一时刻可以有多个 Worker。 */
82
+ active = new Map();
83
+ hostEntry;
84
+ startupTimeoutMs;
85
+ stopTimeoutMs;
86
+ /** 现场管理(worktree / copy / inplace 与产物归档),与可视执行器共用同一份实现。 */
87
+ site;
88
+ heartbeatTimeoutMs;
89
+ approvalTimeoutMs;
90
+ /** workerId → 最近一次收到心跳的时刻;UI/控制面用 isAlive 区分「卡死」与「已退出」。 */
91
+ heartbeats = new Map();
92
+ /**
93
+ * 挂起中的人工介入:approvalId → 投递通道。
94
+ * 控制面通过 `respondApproval()` 直接回写 Host 的 `approval` 命令,不需要重启进程或重放会话。
95
+ */
96
+ pendingApprovals = new Map();
97
+ constructor(options = {}) {
98
+ this.hostEntry = options.hostPath ?? defaultHostPath();
99
+ this.startupTimeoutMs = options.startupTimeoutMs ?? 20_000;
100
+ this.stopTimeoutMs = options.stopTimeoutMs ?? 2_000;
101
+ this.site = new LaneSite(options);
102
+ this.heartbeatTimeoutMs = options.heartbeatTimeoutMs ?? 60_000;
103
+ this.approvalTimeoutMs = options.approvalTimeoutMs ?? 600_000;
104
+ }
105
+ async run(request, onProgress) {
106
+ const lane = request.lane;
107
+ let site;
108
+ try {
109
+ site = this.site.openExecution(lane, request);
110
+ }
111
+ catch (error) {
112
+ return {
113
+ outcome: 'failed',
114
+ summary: 'Worker isolation could not be created.',
115
+ changedFiles: [],
116
+ error: error instanceof Error ? error.message : String(error),
117
+ laneId: lane?.id,
118
+ };
119
+ }
120
+ if (site.created) {
121
+ try {
122
+ const base = this.site.baseFor(site, request, lane);
123
+ onProgress({
124
+ message: site.mode === 'worktree' ? 'lane opened' : `lane opened (${site.mode})`,
125
+ workspacePath: site.path,
126
+ lane: { opened: true, baseTree: base.baseTree, baseIndex: base.baseIndex },
127
+ });
128
+ }
129
+ catch (error) {
130
+ return {
131
+ outcome: 'failed',
132
+ summary: 'Lane baseline could not be captured.',
133
+ changedFiles: [],
134
+ error: error instanceof Error ? error.message : String(error),
135
+ laneId: lane?.id,
136
+ worktreePath: site.path,
137
+ keepWorktree: true,
138
+ };
139
+ }
140
+ }
141
+ const requestId = randomUUID();
142
+ // 这里不镜像执行画面:stdout 是**独占的控制通道**(审批回传 / 取消 / 心跳都在上面)。
143
+ // 人想看画面的场景走 `LaneReplExecutor`——它直接开一个真 mocode,画面就是那个终端本身。
144
+ const child = spawn(process.execPath, [this.hostEntry], {
145
+ cwd: site.path,
146
+ env: { ...process.env, MOCODE_SUPERVISED_WORKER: '1', MOCODE_WORKER_ID: request.workerId },
147
+ stdio: ['pipe', 'pipe', 'pipe'],
148
+ windowsHide: true,
149
+ });
150
+ this.active.set(requestId, child);
151
+ this.heartbeats.set(request.workerId, Date.now());
152
+ let buffer = '';
153
+ let text = '';
154
+ let sessionId;
155
+ let stderr = '';
156
+ let settled = false;
157
+ let ready = false;
158
+ /** 最近一次收到任何 Host envelope 的时刻;心跳事件会刷新它。 */
159
+ let lastSeen = Date.now();
160
+ let resolveResult;
161
+ const resultPromise = new Promise((resolve) => {
162
+ resolveResult = resolve;
163
+ });
164
+ const finish = (result) => {
165
+ if (settled)
166
+ return;
167
+ settled = true;
168
+ if (heartbeatWatchdog)
169
+ clearInterval(heartbeatWatchdog);
170
+ this.heartbeats.delete(request.workerId);
171
+ // 这条 Worker 一旦收尾,它名下不可能再有能得到回答的审批:全部按超时口径清干净,
172
+ // 否则控制面会一直显示「在等你回答」。
173
+ for (const [approvalId, entry] of this.pendingApprovals) {
174
+ if (entry.requestId !== requestId)
175
+ continue;
176
+ if (entry.timer)
177
+ clearTimeout(entry.timer);
178
+ this.pendingApprovals.delete(approvalId);
179
+ }
180
+ resolveResult({ ...result, sessionId, workspacePath: site.path });
181
+ };
182
+ const send = (command) => {
183
+ if (child.stdin.writable)
184
+ child.stdin.write(`${JSON.stringify(command)}\n`);
185
+ };
186
+ /**
187
+ * 回答一个挂起中的审批:把决定写回 Host 的 `approval` 命令,并把 resolved 上报给控制面。
188
+ * 只有 pendingApprovals 里确实有这条才算成功——超时/已答/不属于本 Worker 都返回 false。
189
+ */
190
+ const settleApproval = (approvalId, resolution) => {
191
+ const entry = this.pendingApprovals.get(approvalId);
192
+ if (!entry || entry.requestId !== requestId)
193
+ return false;
194
+ this.pendingApprovals.delete(approvalId);
195
+ if (entry.timer)
196
+ clearTimeout(entry.timer);
197
+ send({ id: randomUUID(), type: 'approval', approvalId, action: resolution.action, value: resolution.value });
198
+ onProgress({
199
+ message: resolution.by === 'timeout'
200
+ ? `approval ${approvalId} timed out — denied`
201
+ : `approval ${approvalId} answered: ${resolution.action}${resolution.value ? ` (${resolution.value})` : ''}`,
202
+ sessionId,
203
+ approval: { state: 'resolved', id: approvalId, resolution },
204
+ });
205
+ return true;
206
+ };
207
+ const handle = (envelope) => {
208
+ lastSeen = Date.now();
209
+ if (request.workerId)
210
+ this.heartbeats.set(request.workerId, lastSeen);
211
+ if (envelope.type === 'error') {
212
+ if (envelope.requestId === requestId || !envelope.requestId) {
213
+ finish({ outcome: 'failed', summary: text.trim(), changedFiles: [], error: envelope.error ?? 'Host error.' });
214
+ }
215
+ return;
216
+ }
217
+ const event = envelope.event ?? '';
218
+ const payload = envelope.payload ?? {};
219
+ if (event === 'runtime_ready') {
220
+ ready = true;
221
+ send({
222
+ id: requestId,
223
+ type: 'run',
224
+ prompt: taskPrompt(request),
225
+ // lane 已有会话时续接,Worker 能继承此前的上下文继续干活。
226
+ ...(lane?.sessionId ? { sessionId: lane.sessionId } : {}),
227
+ });
228
+ onProgress({ message: 'host ready', workspacePath: site.path });
229
+ }
230
+ else if (envelope.requestId === requestId) {
231
+ if (event === 'run_started') {
232
+ sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : undefined;
233
+ onProgress({ message: 'worker started', sessionId, workspacePath: site.path, started: true });
234
+ }
235
+ else if (event === 'text_delta' && typeof payload.text === 'string') {
236
+ text += payload.text;
237
+ }
238
+ else if (event === 'approval_requested') {
239
+ const approvalId = typeof payload.approvalId === 'string' ? payload.approvalId : '';
240
+ const title = typeof payload.title === 'string' ? payload.title : 'Approval requested';
241
+ const detail = typeof payload.detail === 'string' ? payload.detail : undefined;
242
+ const options = Array.isArray(payload.options)
243
+ ? payload.options.filter((item) => typeof item === 'string')
244
+ : [];
245
+ // `ask_human` 走同一条事件,用 payload.kind 区分;缺省按权限面板处理(旧 Host 不发 kind)。
246
+ const kind = payload.kind === 'ask_human' ? 'ask_human' : 'permission';
247
+ if (!approvalId) {
248
+ onProgress({ message: `${title} — ignored (host sent no approval id)`, sessionId });
249
+ }
250
+ else {
251
+ this.pendingApprovals.set(approvalId, {
252
+ requestId,
253
+ answer: (resolution) => settleApproval(approvalId, resolution),
254
+ ...(this.approvalTimeoutMs > 0
255
+ ? {
256
+ timer: setTimeout(() => {
257
+ settleApproval(approvalId, {
258
+ action: 'cancelled',
259
+ by: 'timeout',
260
+ at: new Date().toISOString(),
261
+ });
262
+ }, this.approvalTimeoutMs),
263
+ }
264
+ : {}),
265
+ });
266
+ this.pendingApprovals.get(approvalId).timer?.unref?.();
267
+ onProgress({
268
+ message: `${kind === 'ask_human' ? 'question' : 'approval'}: ${title}`,
269
+ sessionId,
270
+ approval: { state: 'requested', id: approvalId, kind, title, ...(detail ? { detail } : {}), options },
271
+ });
272
+ }
273
+ }
274
+ else if (event === 'run_completed') {
275
+ const changedFiles = Array.isArray(payload.changedFiles)
276
+ ? payload.changedFiles.filter((item) => typeof item === 'string')
277
+ : [];
278
+ const completed = payload.completed === true;
279
+ const parsed = parseHandoff(text);
280
+ const handoffError = !parsed.found
281
+ ? 'Worker completed without the required machine-readable handoff.'
282
+ : handoffViolation(request, parsed);
283
+ const error = completed
284
+ ? handoffError
285
+ : `Worker stopped: ${String(payload.terminationReason ?? 'incomplete')}`;
286
+ const reportedTokens = payload.usage && typeof payload.usage === 'object'
287
+ ? Number(payload.usage.totalTokens)
288
+ : Number.NaN;
289
+ finish({
290
+ outcome: completed && !error ? 'completed' : 'failed',
291
+ summary: parsed.summary,
292
+ changedFiles,
293
+ validation: parsed.validation,
294
+ risks: parsed.risks,
295
+ error,
296
+ tokens: Number.isFinite(reportedTokens) ? reportedTokens : undefined,
297
+ });
298
+ }
299
+ else if (event === 'run_failed') {
300
+ finish({
301
+ outcome: 'failed',
302
+ summary: text.trim(),
303
+ changedFiles: [],
304
+ error: typeof payload.message === 'string' ? payload.message : 'Worker failed.',
305
+ });
306
+ }
307
+ else if (event === 'run_aborted') {
308
+ finish({ outcome: 'cancelled', summary: text.trim(), changedFiles: [], error: 'Worker aborted.' });
309
+ }
310
+ else {
311
+ const message = messageFor(event, payload);
312
+ if (message)
313
+ onProgress({ message, sessionId });
314
+ }
315
+ }
316
+ };
317
+ child.stdout.setEncoding('utf8');
318
+ child.stdout.on('data', (chunk) => {
319
+ buffer += chunk;
320
+ let newline = buffer.indexOf('\n');
321
+ while (newline >= 0) {
322
+ const line = buffer.slice(0, newline).trim();
323
+ buffer = buffer.slice(newline + 1);
324
+ if (line) {
325
+ try {
326
+ handle(JSON.parse(line));
327
+ }
328
+ catch {
329
+ stderr += `Invalid host NDJSON: ${line}\n`;
330
+ }
331
+ }
332
+ newline = buffer.indexOf('\n');
333
+ }
334
+ });
335
+ child.stderr.setEncoding('utf8');
336
+ child.stderr.on('data', (chunk) => {
337
+ stderr = `${stderr}${chunk}`.slice(-16_000);
338
+ });
339
+ child.once('error', (error) => finish({ outcome: 'interrupted', summary: text.trim(), changedFiles: [], error: error.message }));
340
+ child.once('exit', (code) => {
341
+ if (!settled) {
342
+ finish({
343
+ outcome: 'interrupted',
344
+ summary: text.trim(),
345
+ changedFiles: [],
346
+ error: `Worker host exited with code ${code ?? 'unknown'}.${stderr ? ` ${stderr.trim()}` : ''}`,
347
+ });
348
+ }
349
+ });
350
+ const timeout = setTimeout(() => {
351
+ if (ready)
352
+ return;
353
+ finish({
354
+ outcome: 'interrupted',
355
+ summary: text.trim(),
356
+ changedFiles: [],
357
+ error: 'Worker host startup timed out.',
358
+ });
359
+ void killWorkerTree(child);
360
+ }, this.startupTimeoutMs);
361
+ // 心跳看门狗:只在 Worker 已 ready 后生效(启动慢由 startupTimeout 管)。
362
+ // 判死时保留执行现场,成果仍按 lane.patch / lane.diff 归档,不丢现场。
363
+ const heartbeatWatchdog = this.heartbeatTimeoutMs > 0
364
+ ? setInterval(() => {
365
+ if (settled || !ready)
366
+ return;
367
+ if (Date.now() - lastSeen <= this.heartbeatTimeoutMs)
368
+ return;
369
+ finish({
370
+ outcome: 'interrupted',
371
+ summary: text.trim(),
372
+ changedFiles: [],
373
+ error: `Worker stopped reporting heartbeats for ${Math.round(this.heartbeatTimeoutMs / 1000)}s.`,
374
+ });
375
+ void killWorkerTree(child);
376
+ }, Math.min(this.heartbeatTimeoutMs, 5_000))
377
+ : undefined;
378
+ heartbeatWatchdog?.unref?.();
379
+ onProgress({ message: 'creating isolated worker', workspacePath: site.path });
380
+ let result = await resultPromise;
381
+ clearTimeout(timeout);
382
+ await stopChild(child, this.stopTimeoutMs);
383
+ let patchPath;
384
+ const artifactRisks = [...(result.risks ?? [])];
385
+ let keepWorktree = false;
386
+ let baselineTree;
387
+ let baselineIndex;
388
+ try {
389
+ const changes = this.site.collect(site, {
390
+ run: request.run,
391
+ laneId: lane?.id ?? request.task.id,
392
+ attempt: request.attempt,
393
+ baselineTree: lane?.baselineTree,
394
+ baselineIndex: lane?.baselineIndex,
395
+ });
396
+ baselineTree = changes.tree;
397
+ baselineIndex = changes.index;
398
+ const changedFiles = changes.changedFiles.length > 0 ? changes.changedFiles : result.changedFiles;
399
+ patchPath = this.site.writeAttemptPatch(request.run, request.task.id, request.attempt, changes, site.mode);
400
+ if (!changes.patch && site.mode !== 'worktree' && changes.changedFiles.length > 0) {
401
+ artifactRisks.push(`${site.mode} lane cannot produce a content diff for this attempt; changed files are listed in the handoff.`);
402
+ }
403
+ result = { ...result, changedFiles };
404
+ if (result.outcome === 'completed') {
405
+ const violations = this.site.violations(request.task.contract, changedFiles);
406
+ if (violations.length > 0)
407
+ result = { ...result, outcome: 'failed', error: violations.join(' ') };
408
+ }
409
+ }
410
+ catch (error) {
411
+ const message = error instanceof Error ? error.message : String(error);
412
+ artifactRisks.push(`Artifact collection failed: ${message}`);
413
+ if (request.task.contract.changePolicy === 'isolated_write') {
414
+ // 无法证明没有改动时,绝不销毁唯一副本:任务判失败,现场留在原地供人工打捞。
415
+ keepWorktree = true;
416
+ result = {
417
+ ...result,
418
+ outcome: 'failed',
419
+ error: `Artifact collection failed; the execution site was preserved at ${site.path}. ${message}`,
420
+ };
421
+ }
422
+ }
423
+ this.active.delete(requestId);
424
+ // 会话归档推迟到 closeLane:lane 内后续任务还要续接同一个会话目录。
425
+ return {
426
+ ...result,
427
+ laneId: lane?.id,
428
+ worktreePath: site.path,
429
+ baselineTree,
430
+ baselineIndex,
431
+ keepWorktree,
432
+ patchPath,
433
+ risks: artifactRisks,
434
+ };
435
+ }
436
+ /** 收尾 lane(口径与可视执行器共用 `LaneSite`,避免两套 patch 语义)。 */
437
+ async closeLane(request) {
438
+ return this.site.closeLane(request);
439
+ }
440
+ /** Worker 是否还在活着(最近一次心跳在阈值内)。未启动过 / 已退出返回 false。 */
441
+ isAlive(workerId) {
442
+ const at = this.heartbeats.get(workerId);
443
+ if (at === undefined)
444
+ return false;
445
+ return Date.now() - at <= this.heartbeatTimeoutMs;
446
+ }
447
+ /** 挂起中的人工介入 id 清单(控制面在重启后据此对账)。 */
448
+ pendingApprovalIds() {
449
+ return [...this.pendingApprovals.keys()];
450
+ }
451
+ /**
452
+ * 把人的决定送进那个正在等着的 Host 进程。
453
+ * 返回 false = 这个 id 已经不在我等的人里(超时 / 已答 / 进程已退),调用方应当报错而不是装作成功。
454
+ */
455
+ respondApproval(approvalId, resolution) {
456
+ const entry = this.pendingApprovals.get(approvalId);
457
+ if (!entry)
458
+ return false;
459
+ return entry.answer(resolution);
460
+ }
461
+ async cancel() {
462
+ const children = [...this.active.values()];
463
+ if (children.length === 0)
464
+ return;
465
+ for (const child of children) {
466
+ if (child.stdin.writable)
467
+ child.stdin.write(`${JSON.stringify({ id: randomUUID(), type: 'cancel' })}\n`);
468
+ }
469
+ setTimeout(() => {
470
+ for (const child of children)
471
+ if (child.exitCode === null)
472
+ void killWorkerTree(child);
473
+ }, 1_000).unref();
474
+ }
475
+ }