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,439 @@
1
+ // 可视执行器:把「派活」变成「在那个窗口里说一句话」。
2
+ //
3
+ // 与 `HostWorkerExecutor` 的分工,一句话说清:
4
+ // - headless:spawn 一个 agent host 进程,stdout 走 NDJSON 控制通道,没人看得见它;
5
+ // - 本执行器:spawn 一个**真的 mocode REPL 窗口**,控制面通过 lane.commands 说话、
6
+ // 通过 lane.events 收结论。画面就是这个终端本身,人随时能接管打字。
7
+ //
8
+ // 三条由此产生的差异(不是遗漏,是有意的):
9
+ // 1. **不镜像输出**。要复制一份流式正文出来,就得在 REPL 里再插一层画屏钩子,
10
+ // 那正好破坏「跟手敲 mocode 一模一样」这个目标。
11
+ // 2. **审批在那个窗口里回答**。它是真 TTY、真权限面板,人在屏幕前按一下即可;
12
+ // 控制面的 `/approve` 只对 headless worker 有意义。
13
+ // 3. **进程死了就是死了**。窗口被关掉时这一轮不可能有结论,按 failed 上报并让下一次
14
+ // attempt 重开窗口,而不是假装还在跑。
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import { LaneSite } from './lane-site.js';
18
+ import { appendLaneCommand, clearLaneStop, laneChannelPaths, readChannel, requestLaneStop, resetLaneChannel, } from './lane-channel.js';
19
+ import { handoffViolation, parseHandoff, taskPrompt } from './task-prompt.js';
20
+ import { openTerminalWindow } from './terminal.js';
21
+ /** pid 还活着吗。用于「窗口被关掉但没有 exit 事件」(比如被外部 taskkill)。 */
22
+ function processAlive(pid) {
23
+ if (!pid)
24
+ return true; // 不知道 pid 就别乱判死
25
+ try {
26
+ process.kill(pid, 0);
27
+ return true;
28
+ }
29
+ catch (error) {
30
+ return error.code === 'EPERM';
31
+ }
32
+ }
33
+ function sleep(ms) {
34
+ return new Promise((resolve) => setTimeout(resolve, ms));
35
+ }
36
+ export class LaneReplExecutor {
37
+ site;
38
+ openTerminal;
39
+ readyTimeoutMs;
40
+ pollMs;
41
+ stopGraceMs;
42
+ /** `runId:laneId` → 那个 lane 的窗口进程。一个 lane 同时只跑一个任务(调度器保证)。 */
43
+ lanes = new Map();
44
+ /** 被取消的 lane key:正在跑的那一轮要在下一次轮询时收手。 */
45
+ cancelled = new Set();
46
+ constructor(options = {}) {
47
+ this.site = new LaneSite(options);
48
+ this.openTerminal = options.openTerminal ?? openTerminalWindow;
49
+ this.readyTimeoutMs = options.readyTimeoutMs ?? 30_000;
50
+ this.pollMs = options.pollMs ?? 300;
51
+ this.stopGraceMs = options.stopGraceMs ?? 15_000;
52
+ }
53
+ async run(request, onProgress) {
54
+ const lane = request.lane;
55
+ const laneId = lane?.id ?? request.task.id;
56
+ let site;
57
+ try {
58
+ site = this.site.openExecution(lane, request);
59
+ }
60
+ catch (error) {
61
+ return {
62
+ outcome: 'failed',
63
+ summary: 'Worker isolation could not be created.',
64
+ changedFiles: [],
65
+ error: error instanceof Error ? error.message : String(error),
66
+ laneId: lane?.id,
67
+ };
68
+ }
69
+ if (site.created) {
70
+ try {
71
+ const base = this.site.baseFor(site, request, lane);
72
+ onProgress({
73
+ message: site.mode === 'worktree' ? 'lane opened' : `lane opened (${site.mode})`,
74
+ workspacePath: site.path,
75
+ lane: { opened: true, baseTree: base.baseTree, baseIndex: base.baseIndex },
76
+ });
77
+ }
78
+ catch (error) {
79
+ return {
80
+ outcome: 'failed',
81
+ summary: 'Lane baseline could not be captured.',
82
+ changedFiles: [],
83
+ error: error instanceof Error ? error.message : String(error),
84
+ laneId: lane?.id,
85
+ worktreePath: site.path,
86
+ keepWorktree: true,
87
+ };
88
+ }
89
+ }
90
+ const paths = laneChannelPaths(request.run.workspaceRoot, request.run.id, laneId);
91
+ const ready = await this.ensureWindow(request, site, laneId, paths, onProgress);
92
+ if (!ready.ok) {
93
+ return { outcome: 'failed', summary: '', changedFiles: [], error: ready.error, laneId, worktreePath: site.path };
94
+ }
95
+ const process_ = ready.process;
96
+ const commandId = `${request.task.id}#${request.attempt}`;
97
+ appendLaneCommand(paths, {
98
+ t: Date.now(),
99
+ id: commandId,
100
+ taskId: request.task.id,
101
+ kind: 'task',
102
+ text: taskPrompt(request, { interactive: true }),
103
+ });
104
+ // sessionId 必须上报:账本据此落 `lane.session`,后续任务才能续同一段对话,
105
+ // 收尾时也才有会话可归档。窗口的 ready 里带的就是它。
106
+ onProgress({
107
+ message: 'worker started',
108
+ workspacePath: site.path,
109
+ started: true,
110
+ ...(process_.sessionId ? { sessionId: process_.sessionId } : {}),
111
+ });
112
+ const finished = await this.waitForTurn(process_, commandId);
113
+ // 这一轮不管是正常结束、被取消、还是窗口没了,都先把现场差分收上来:
114
+ // 半途失败恰恰最需要看到「已经改了什么」。
115
+ const collected = this.collect(request, site, lane, onProgress);
116
+ if (!finished) {
117
+ // 先取出再判:`delete` 之后 `has` 恒为 false,问「是不是被取消」必须用返回值。
118
+ const cancelled = this.cancelled.delete(process_.key);
119
+ return {
120
+ ...collected,
121
+ outcome: cancelled ? 'cancelled' : 'failed',
122
+ summary: '',
123
+ error: cancelled
124
+ ? 'The lane window was stopped by the operator.'
125
+ : 'The lane window closed before this task finished.',
126
+ laneId,
127
+ worktreePath: site.path,
128
+ };
129
+ }
130
+ const parsed = parseHandoff(finished.summary ?? '');
131
+ const violation = handoffViolation(request, parsed);
132
+ const outcome = finished.outcome === 'completed' && !violation ? 'completed' : 'failed';
133
+ return {
134
+ ...collected,
135
+ outcome,
136
+ summary: parsed.summary,
137
+ validation: parsed.validation,
138
+ risks: parsed.risks,
139
+ ...(outcome === 'completed'
140
+ ? {}
141
+ : { error: violation ?? finished.error ?? `Worker stopped: ${finished.outcome}` }),
142
+ laneId,
143
+ worktreePath: site.path,
144
+ };
145
+ }
146
+ /** 开窗一次,等到 `ready`。同一个 lane 的后续任务复用这个窗口(会话就在里面)。 */
147
+ async ensureWindow(request, site, laneId, paths, onProgress) {
148
+ const key = `${request.run.id}:${laneId}`;
149
+ const existing = this.lanes.get(key);
150
+ if (existing && !existing.dead) {
151
+ if (!existing.ready)
152
+ await this.waitReady(existing);
153
+ if (existing.ready)
154
+ return { ok: true, process: existing };
155
+ }
156
+ this.lanes.delete(key);
157
+ this.cancelled.delete(key);
158
+ // 开窗前先把通道清干净:上一代窗口的事件里可能还躺着一条 `exit`(协作式关窗时它
159
+ // 一定会写),而新建的 LaneProcess 游标从 0 开始——第一轮 pump 就会读到那条旧 exit,
160
+ // 把刚拉起的窗口直接判死,报「did not become ready」。窗口自己起来后也会 reset,
161
+ // 但那时控制面可能已经读过了;清在开窗之前才是唯一没有窗口期的位置。
162
+ resetLaneChannel(paths);
163
+ const launch = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
164
+ const opened = this.openTerminal({
165
+ title: `mocode · ${laneId} · ${request.run.id}`,
166
+ cwd: site.path,
167
+ args: [
168
+ 'supervise',
169
+ 'lane',
170
+ request.run.id,
171
+ '--lane',
172
+ laneId,
173
+ '--launch',
174
+ launch,
175
+ // 必须显式给账本根:窗口 cwd 是 lane 执行现场(worktree / 副本),
176
+ // 那里的 `.mocode/orchestrations` 根本不存在(worktree 基于 HEAD,副本还排除了 .mocode),
177
+ // 不给这个参数 `supervise lane` 会立刻报「run 不存在」,窗口一闪就退。
178
+ '--sandbox-root',
179
+ request.run.workspaceRoot,
180
+ ],
181
+ });
182
+ if (!opened.opened) {
183
+ // 开不出窗口不是「任务失败」的合理理由,但这里确实没法继续:没有 TTY 就没有 REPL。
184
+ // 调用方(supervisor)在无终端环境应改用 headless 执行器。
185
+ return {
186
+ ok: false,
187
+ error: 'could not open a terminal window for this lane; fall back to a headless worker (--no-terminal).',
188
+ };
189
+ }
190
+ const process_ = {
191
+ key,
192
+ runId: request.run.id,
193
+ laneId,
194
+ workspaceRoot: request.run.workspaceRoot,
195
+ launch,
196
+ consumed: 0,
197
+ ready: false,
198
+ dead: false,
199
+ };
200
+ this.lanes.set(key, process_);
201
+ onProgress({ message: 'lane window opened', workspacePath: site.path });
202
+ const ready = await this.waitReady(process_);
203
+ if (!ready) {
204
+ // 超时的窗口必须从表里摘掉并判死:否则它已经死了/半死不活地留在 lanes 里,
205
+ // 下一次派活还会复用它(`existing && !existing.dead`),同一个 lane 上叠出两个
206
+ // 窗口抢同一份 lane.commands。真实事故:ready 超时后重试,旧窗口还活着并重跑了旧指令。
207
+ process_.dead = true;
208
+ if (this.lanes.get(key) === process_)
209
+ this.lanes.delete(key);
210
+ return {
211
+ ok: false,
212
+ error: `the lane window did not become ready within ${Math.round(this.readyTimeoutMs / 1000)}s.`,
213
+ };
214
+ }
215
+ return { ok: true, process: process_ };
216
+ }
217
+ /** 轮询到 ready(带本次 launch 标记)。同时把 `turn.finished` 分发给等待方。 */
218
+ async waitReady(process_) {
219
+ const paths = laneChannelPaths(process_.workspaceRoot, process_.runId, process_.laneId);
220
+ const deadline = Date.now() + this.readyTimeoutMs;
221
+ while (Date.now() < deadline) {
222
+ this.pump(process_, paths);
223
+ if (process_.ready)
224
+ return true;
225
+ if (process_.dead)
226
+ return false;
227
+ await sleep(this.pollMs);
228
+ }
229
+ return false;
230
+ }
231
+ async waitForTurn(process_, commandId) {
232
+ const paths = laneChannelPaths(process_.workspaceRoot, process_.runId, process_.laneId);
233
+ // 注意顺序:先建 promise、再起轮询、最后才 await。写成 `await new Promise(...)` 会让
234
+ // 轮询根本没机会启动(await 卡在原地),表现是「任务永远不结束」。
235
+ let resolve;
236
+ const result = new Promise((done) => {
237
+ resolve = done;
238
+ process_.waiting = { id: commandId, resolve: done };
239
+ });
240
+ const timer = setInterval(() => {
241
+ this.pump(process_, paths);
242
+ // 取消 / 窗口消失时 pump 未必能 settle(它只在「有等待方」时发结论),这里补一刀。
243
+ if (this.cancelled.has(process_.key) || process_.dead)
244
+ this.settle(process_, null);
245
+ }, this.pollMs);
246
+ timer.unref?.();
247
+ try {
248
+ return await result;
249
+ }
250
+ finally {
251
+ clearInterval(timer);
252
+ process_.waiting = undefined;
253
+ void resolve;
254
+ }
255
+ }
256
+ settle(process_, event) {
257
+ const waiting = process_.waiting;
258
+ if (!waiting)
259
+ return;
260
+ process_.waiting = undefined;
261
+ waiting.resolve(event);
262
+ }
263
+ /** 读一次通道:更新 ready / dead,并把匹配的 turn.finished 交给等待方。 */
264
+ pump(process_, paths) {
265
+ let read = readChannel(paths.events, process_.consumed);
266
+ // 游标自愈:新窗口启动时会截断 events(resetLaneChannel)。文件比游标短 = 被截断过,
267
+ // 必须从头读,否则会一直 `slice(consumed)` 出空数组——真实事故就是 ready 明明写了、
268
+ // 控制面却等到 30s 超时判「窗口没起来」。
269
+ if (read.total < process_.consumed)
270
+ read = readChannel(paths.events, 0);
271
+ process_.consumed = read.consumed;
272
+ for (const event of read.items) {
273
+ if (!event || typeof event !== 'object')
274
+ continue;
275
+ if (event.kind === 'ready') {
276
+ // 只认本次窗口:旧进程残留的 ready 会让控制面往一个已经不存在的窗口里投任务。
277
+ if (event.launch && event.launch !== process_.launch)
278
+ continue;
279
+ process_.ready = true;
280
+ process_.pid = event.pid ?? process_.pid;
281
+ process_.sessionId = event.sessionId ?? process_.sessionId;
282
+ }
283
+ else if (event.kind === 'exit') {
284
+ process_.dead = true;
285
+ this.settle(process_, null);
286
+ }
287
+ else if (event.kind === 'turn.finished') {
288
+ // id 必须对上:人自己在这个窗口里敲的那一轮也会发 turn.finished,那不是派活的结论。
289
+ if (process_.waiting?.id === event.id)
290
+ this.settle(process_, event);
291
+ }
292
+ }
293
+ if (!process_.dead && process_.pid && !processAlive(process_.pid)) {
294
+ process_.dead = true;
295
+ this.settle(process_, null);
296
+ }
297
+ }
298
+ /** 收现场差分:哪些文件改了、attempt patch 落在哪、是否违反契约。 */
299
+ collect(request, site, lane, onProgress) {
300
+ const laneId = lane?.id ?? request.task.id;
301
+ const risks = [];
302
+ let patchPath;
303
+ let baselineTree;
304
+ let baselineIndex;
305
+ let changedFiles = [];
306
+ try {
307
+ const changes = this.site.collect(site, {
308
+ run: request.run,
309
+ laneId,
310
+ attempt: request.attempt,
311
+ baselineTree: lane?.baselineTree,
312
+ baselineIndex: lane?.baselineIndex,
313
+ });
314
+ baselineTree = changes.tree;
315
+ baselineIndex = changes.index;
316
+ changedFiles = changes.changedFiles;
317
+ patchPath = this.site.writeAttemptPatch(request.run, request.task.id, request.attempt, changes, site.mode);
318
+ if (!changes.patch && site.mode !== 'worktree' && changes.changedFiles.length > 0) {
319
+ risks.push(`${site.mode} lane cannot produce a content diff for this attempt.`);
320
+ }
321
+ const violations = this.site.violations(request.task.contract, changedFiles);
322
+ if (violations.length > 0)
323
+ risks.push(...violations);
324
+ }
325
+ catch (error) {
326
+ // 收不上差分也不能丢现场:保留 worktree 供人工打捞。
327
+ risks.push(`Artifact collection failed: ${error instanceof Error ? error.message : String(error)}`);
328
+ onProgress({ message: 'artifact collection failed', workspacePath: site.path });
329
+ return {
330
+ outcome: 'failed',
331
+ summary: '',
332
+ changedFiles: [],
333
+ error: `Artifact collection failed; the execution site was preserved at ${site.path}.`,
334
+ laneId,
335
+ worktreePath: site.path,
336
+ keepWorktree: true,
337
+ risks,
338
+ };
339
+ }
340
+ return {
341
+ outcome: 'completed',
342
+ summary: '',
343
+ changedFiles,
344
+ laneId,
345
+ worktreePath: site.path,
346
+ baselineTree,
347
+ baselineIndex,
348
+ patchPath,
349
+ risks,
350
+ };
351
+ }
352
+ /**
353
+ * 请 window 自己退,等它退;真卡住才硬杀。
354
+ *
355
+ * 顺序不能反:`process.kill` 在 Windows 上是 TerminateProcess,目标进程的
356
+ * `exit` / `SIGTERM` 处理器一个都不跑,`exitAltScreen()` 永远执行不到,于是终端留在
357
+ * alt screen 里——画面还在、鼠标追踪还开着,滚轮翻不动、点哪都没反应。所以先写 stop
358
+ * 信号让它走 REPL 自己的退出路径(会复原终端),宽限期到了才退到硬杀。
359
+ */
360
+ async stopWindow(process_, reason) {
361
+ const paths = laneChannelPaths(process_.workspaceRoot, process_.runId, process_.laneId);
362
+ // 先 settle:让正在等结论的那一轮立刻收手,不必等窗口真的退干净。
363
+ this.settle(process_, null);
364
+ if (process_.dead) {
365
+ clearLaneStop(paths);
366
+ return;
367
+ }
368
+ if (!process_.ready) {
369
+ // 还没 ready 的窗口:既没有 pid 可杀,stop 信号也会被它的启动清理(resetLaneChannel)
370
+ // 抹掉——等下去只会白等一个宽限期。直接放弃,那个窗口起来后是个没人管的空 REPL,
371
+ // 人按 Ctrl+D 就能关(它从未接过任务)。
372
+ process_.dead = true;
373
+ clearLaneStop(paths);
374
+ return;
375
+ }
376
+ requestLaneStop(paths, reason);
377
+ const deadline = Date.now() + this.stopGraceMs;
378
+ while (Date.now() < deadline) {
379
+ // 必须边等边读通道:窗口退出的证据就是它自己写的 exit 事件,
380
+ // 只 sleep 不 pump 会一直等到宽限期结束,然后误判「没理我们」而硬杀。
381
+ this.pump(process_, paths);
382
+ if (process_.dead)
383
+ break;
384
+ if (process_.pid && !processAlive(process_.pid)) {
385
+ process_.dead = true;
386
+ break;
387
+ }
388
+ await sleep(Math.min(this.pollMs, 200));
389
+ }
390
+ if (!process_.dead && process_.pid) {
391
+ // 超时:它没理我们。硬杀是最后手段——终端会烂在 alt screen 里,但至少进程不残留。
392
+ try {
393
+ process.kill(process_.pid);
394
+ }
395
+ catch {
396
+ // 已经退了
397
+ }
398
+ }
399
+ process_.dead = true;
400
+ clearLaneStop(paths);
401
+ }
402
+ async cancel(reason) {
403
+ const pending = [];
404
+ for (const process_ of this.lanes.values()) {
405
+ this.cancelled.add(process_.key);
406
+ pending.push(this.stopWindow(process_, reason ?? 'orchestration cancelled'));
407
+ }
408
+ // 并行等:5 个 lane 串行各等一个宽限期会像卡住。
409
+ await Promise.all(pending);
410
+ }
411
+ async closeLane(request) {
412
+ const key = `${request.run.id}:${request.lane.id}`;
413
+ const process_ = this.lanes.get(key);
414
+ if (process_)
415
+ await this.stopWindow(process_, request.reason);
416
+ this.lanes.delete(key);
417
+ this.cancelled.delete(key);
418
+ // 窗口退干净之后 `.mocode/sessions` 才稳定,才能安全归档会话。
419
+ await sleep(Math.min(this.pollMs, 300));
420
+ return this.site.closeLane(request);
421
+ }
422
+ /**
423
+ * 不实现 `respondApproval`:lane 窗口本身就是一个真 TTY,权限面板与 `ask_human`
424
+ * 都在那个窗口里直接回答。控制面替它作答会绕过人在屏幕前看到的那一次确认。
425
+ */
426
+ respondApproval(approvalId, resolution) {
427
+ void approvalId;
428
+ void resolution;
429
+ return false;
430
+ }
431
+ /** 供诊断/测试:某个 lane 的窗口是否还开着。 */
432
+ laneWindowAlive(runId, laneId) {
433
+ const process_ = this.lanes.get(`${runId}:${laneId}`);
434
+ return process_ !== undefined && !process_.dead;
435
+ }
436
+ }
437
+ /** 让 `fs` 的导入不被 lint 判为未使用(本模块只在 `collect` 的失败路径里间接依赖现场)。 */
438
+ void fs;
439
+ void path;
@@ -0,0 +1,154 @@
1
+ // `supervise lane`:在 lane 的执行目录里跑一个**真的 mocode REPL**。
2
+ //
3
+ // 这是整条设计的核心:派出去的 worker 不是"另一个东西",就是 mocode 本体——同一套 TUI、
4
+ // 同一个输入框、同一套斜杠命令。人可以在那个窗口里直接打字,supervisor 也可以经
5
+ // lane.commands 派活;两者是同一个输入框的两个来源,语义完全一致。
6
+ //
7
+ // 因此这里只做三件不属于 REPL 的事:
8
+ // 1. 把 cwd / 沙箱根 / 会话目录切到 lane 的执行现场(否则会话会落进别的工作区);
9
+ // 2. 把 lane 的会话读回来(同一个 lane 的后续任务续接同一段对话);
10
+ // 3. 接上 lane.events / lane.commands 这两个旁路文件(stdin/stdout 归 TUI,不能被动)。
11
+ //
12
+ // 不做的:不镜像画面(画面就是这个终端)、不改 UI(任何画屏代码都会让"看起来跟手敲 mocode
13
+ // 不一样")、不新增命令(斜杠命令树仍由主 REPL 提供)。
14
+ import fs from 'node:fs';
15
+ import { appendLaneEvent, laneChannelPaths, laneStopRequested, readChannel, resetLaneChannel, } from './lane-channel.js';
16
+ import { OrchestrationStore } from './store.js';
17
+ import { switchWorkspaceRoot } from '../workspace/index.js';
18
+ import { exitAltScreen } from '../ui/layout.js';
19
+ import { setHandoffDisplaySuppressed } from '../ui/handoff-block.js';
20
+ /**
21
+ * 解析一个 lane 的执行现场与通道路径(不产生副作用,CLI 与执行器都可复用)。
22
+ * lane 还没开过现场时回落到工作区根(inplace 语义)。
23
+ */
24
+ export function resolveLaneTarget(workspaceRoot, runId, laneId) {
25
+ const store = OrchestrationStore.load(workspaceRoot, runId);
26
+ const run = store.current;
27
+ const lane = run.lanes[laneId];
28
+ if (!lane)
29
+ throw new Error(`run ${runId} has no lane ${laneId}.`);
30
+ const execPath = lane.worktreePath ?? lane.workspaceRoot ?? run.workspaceRoot;
31
+ return { execPath, sessionId: lane.sessionId, paths: laneChannelPaths(run.workspaceRoot, run.id, lane.id) };
32
+ }
33
+ /**
34
+ * 跑一个 lane REPL,直到人退出(`/exit` / `Ctrl+D`)。
35
+ *
36
+ * 返回值只表示"这个窗口结束了",不代表任务成败——任务成败由 turn.finished 事件上报,
37
+ * 控制面据此记账。
38
+ */
39
+ export async function runLaneRepl(options) {
40
+ const workspaceRoot = options.workspaceRoot;
41
+ const target = resolveLaneTarget(workspaceRoot, options.runId, options.laneId);
42
+ // ① 现场三单例:chdir + sandboxRoot + sessionDir。只改其中一处会留半个工作区
43
+ // (文件读写走 lane,会话却写回主工作区),这是 /cd 早就踩过的坑。
44
+ if (fs.existsSync(target.execPath))
45
+ switchWorkspaceRoot(target.execPath);
46
+ const paths = target.paths;
47
+ resetLaneChannel(paths);
48
+ const exit = (reason) => {
49
+ appendLaneEvent(paths, { t: Date.now(), kind: 'exit', reason });
50
+ };
51
+ try {
52
+ // ② 续接 lane 的会话。会话目录必须已经切到 lane 现场,所以这里动态 import:
53
+ // session store 在模块加载时就会读 config.sessionDir。
54
+ const { loadSession } = await import('../session/index.js');
55
+ const loaded = target.sessionId ? loadSession(target.sessionId, { restoreAssets: true }) : null;
56
+ /** 已从通道取出、等待 REPL 空闲消费的指令(FIFO)。 */
57
+ const queue = [];
58
+ /** 正在执行的那条指令;REPL 一次只跑一轮,所以它最多一个。 */
59
+ let active;
60
+ let consumed = 0;
61
+ let poller;
62
+ const drain = () => {
63
+ const read = readChannel(paths.commands, consumed);
64
+ consumed = read.consumed;
65
+ for (const command of read.items) {
66
+ if (!command || typeof command.text !== 'string')
67
+ continue;
68
+ queue.push(command);
69
+ }
70
+ };
71
+ // 启动前先吃一遍:supervisor 可能在窗口起来之前就投了指令。
72
+ drain();
73
+ poller = setInterval(drain, options.pollMs ?? 400);
74
+ poller.unref?.();
75
+ // 关窗的兜底通道(与输入框的空闲轮询互补)。
76
+ //
77
+ // 输入框那条 externalExitRequested 只在**空闲**时被问到:正在跑一轮、或输入面板占着键时
78
+ // 根本轮不到它。而控制面的宽限期一到就会硬杀,于是终端照样烂在 alt screen 里。
79
+ // 这里不看 REPL 状态,只认「stop 信号挂了这么久还没退出」这一个事实。
80
+ let stopSince;
81
+ const stopWatchdog = setInterval(() => {
82
+ if (!laneStopRequested(paths)) {
83
+ stopSince = undefined;
84
+ return;
85
+ }
86
+ stopSince ??= Date.now();
87
+ if (Date.now() - stopSince < (options.stopFallbackMs ?? 8_000))
88
+ return;
89
+ // 走不到正常退出路径时,至少把终端复原再退——绝不把 alt screen 留给用户。
90
+ // 先报 exit:控制面据此知道是「响应了请求」,而不是把我们当卡死硬杀。
91
+ exit('stop request forced the window to close');
92
+ exitAltScreen();
93
+ process.exit(0);
94
+ }, Math.max(options.pollMs ?? 400, 200));
95
+ stopWatchdog.unref?.();
96
+ const { startRepl } = await import('../repl/index.js');
97
+ // 这个进程就是「派出去的那个 mocode」:模型收尾时按协议吐的 `<mocode_handoff>` 块
98
+ // 只在显示层摘掉,`finalText` 保持完整,控制面照旧解析入账。
99
+ // 手敲 `mocode` 的窗口永远不开这个开关(默认 false)。
100
+ setHandoffDisplaySuppressed(true);
101
+ await startRepl(loaded?.history, loaded?.id ?? target.sessionId, target.execPath, loaded?.queryHistory, loaded?.lastToolGroups, {
102
+ // 第二输入源:只有输入框为空时才取,人正在打字时绝不抢字。
103
+ takeExternalTurn: () => {
104
+ if (active)
105
+ return null;
106
+ const command = queue.shift();
107
+ if (!command)
108
+ return null;
109
+ active = command;
110
+ appendLaneEvent(paths, { t: Date.now(), kind: 'turn.started', id: command.id });
111
+ return command.text;
112
+ },
113
+ onTurnFinished: ({ ok, finalText }) => {
114
+ if (!active)
115
+ return; // 人自己打的字:不是派活,不产生交接
116
+ const command = active;
117
+ active = undefined;
118
+ const summary = (finalText ?? '').trim();
119
+ appendLaneEvent(paths, {
120
+ t: Date.now(),
121
+ kind: 'turn.finished',
122
+ id: command.id,
123
+ outcome: ok ? 'completed' : 'failed',
124
+ summary,
125
+ ...(ok ? {} : { error: summary ? summary.split('\n')[0] : 'The turn ended without a final answer.' }),
126
+ });
127
+ },
128
+ // 关窗走这里,不走 process.kill:kill 在 Windows 上是 TerminateProcess,目标进程
129
+ // 拿不到执行清理代码的机会,终端会烂在 alt screen 里(画面还在、滚轮翻不动)。
130
+ // 这里返回 true 后输入框按 Ctrl+D 处理,REPL 顺着正常退出路径复原终端。
131
+ externalExitRequested: () => laneStopRequested(paths),
132
+ onReady: ({ sessionId }) => {
133
+ appendLaneEvent(paths, {
134
+ t: Date.now(),
135
+ kind: 'ready',
136
+ pid: process.pid,
137
+ ...(sessionId ? { sessionId } : {}),
138
+ workspacePath: target.execPath,
139
+ ...(options.launch ? { launch: options.launch } : {}),
140
+ });
141
+ },
142
+ });
143
+ if (poller)
144
+ clearInterval(poller);
145
+ poller = undefined;
146
+ clearInterval(stopWatchdog);
147
+ exit('lane repl exited');
148
+ return 0;
149
+ }
150
+ catch (error) {
151
+ exit(error instanceof Error ? error.message : String(error));
152
+ throw error;
153
+ }
154
+ }