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.
- package/dist/agent/index.js +27 -0
- package/dist/agent/model-turn.js +6 -6
- package/dist/agent/request-governor.js +1 -1
- package/dist/context/pipeline.js +8 -3
- package/dist/context/vision-window.js +24 -9
- package/dist/host/protocol.js +4 -1
- package/dist/host/stdio.js +45 -1
- package/dist/index.js +7 -0
- package/dist/jobs/dir-snapshot.js +332 -0
- package/dist/jobs/worktree.js +78 -20
- package/dist/orchestrator/board.js +332 -0
- package/dist/orchestrator/cli.js +628 -0
- package/dist/orchestrator/index.js +4 -0
- package/dist/orchestrator/integrate.js +344 -0
- package/dist/orchestrator/lane-channel.js +146 -0
- package/dist/orchestrator/lane-executor.js +439 -0
- package/dist/orchestrator/lane-repl.js +154 -0
- package/dist/orchestrator/lane-site.js +255 -0
- package/dist/orchestrator/lanes.js +72 -0
- package/dist/orchestrator/lease.js +132 -0
- package/dist/orchestrator/live-log.js +193 -0
- package/dist/orchestrator/repl.js +435 -0
- package/dist/orchestrator/review.js +135 -0
- package/dist/orchestrator/scheduler.js +673 -0
- package/dist/orchestrator/scope.js +88 -0
- package/dist/orchestrator/state.js +533 -0
- package/dist/orchestrator/store.js +221 -0
- package/dist/orchestrator/supervisor-prompt.js +54 -0
- package/dist/orchestrator/supervisor.js +798 -0
- package/dist/orchestrator/tail.js +508 -0
- package/dist/orchestrator/task-prompt.js +93 -0
- package/dist/orchestrator/terminal.js +269 -0
- package/dist/orchestrator/tools.js +392 -0
- package/dist/orchestrator/types.js +1 -0
- package/dist/orchestrator/watch-panel.js +154 -0
- package/dist/orchestrator/worker.js +475 -0
- package/dist/orchestrator/workspaces.js +191 -0
- package/dist/repl/commands/memory.js +1 -1
- package/dist/repl/runtime.js +16 -2
- package/dist/session/compact.js +8 -1
- package/dist/session/store.js +1 -1
- package/dist/tools/builtins/ask-human.js +27 -6
- package/dist/tools/constants.js +10 -0
- package/dist/ui/handoff-block.js +91 -0
- package/dist/ui/layout-internal/statusbar.js +2 -1
- package/dist/ui/prompt-internal/editor.js +49 -0
- package/package.json +2 -2
|
@@ -0,0 +1,798 @@
|
|
|
1
|
+
// Supervisor 的控制面:把「这台机器上有哪些工作区 / 哪些 Run / 怎么派活」收成一个可被
|
|
2
|
+
// 工具调用的对象。对话 REPL(./repl.ts)与工具集(./tools.ts)都只跟它说话。
|
|
3
|
+
//
|
|
4
|
+
// 三条不变量:
|
|
5
|
+
// 1. 派活绝不阻塞前台对话:scheduler.run() 挂在后台 promise 上,工具立即返回 run id。
|
|
6
|
+
// 2. 一个 Run 同时只有一个控制器:本对象持有 controller.lock,直到 Run 终态或进程退出。
|
|
7
|
+
// 3. 账本只在 Run 处于 idle / awaiting_user 时接受新任务(reducer 的硬约束)。所以「边跑边派」
|
|
8
|
+
// 走内存队列:任务排队,后台 Run 一进 idle 立刻落账并继续跑。这与 CLI 的「等 idle 再 dispatch」
|
|
9
|
+
// 是同一语义,只是把等待从人身上挪到了队列里。
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { OrchestrationScheduler } from './scheduler.js';
|
|
13
|
+
import { OrchestrationStore, listOrchestrations, orchestrationRoot } from './store.js';
|
|
14
|
+
import { isRunLive, isRunTerminal } from './state.js';
|
|
15
|
+
import { prepareDefinition } from './lanes.js';
|
|
16
|
+
import { HostWorkerExecutor } from './worker.js';
|
|
17
|
+
import { LaneReplExecutor } from './lane-executor.js';
|
|
18
|
+
import { formatWorkspaces, listWorkspaces } from './workspaces.js';
|
|
19
|
+
import { appendIntegrationLog, formatIntegration, integrateRun } from './integrate.js';
|
|
20
|
+
const TERMINAL = new Set(['completed', 'failed', 'cancelled']);
|
|
21
|
+
/** 同一任务同一条进度消息的最小间隔:调度器 250ms 一轮,不节流会把对话刷没。 */
|
|
22
|
+
const PROGRESS_THROTTLE_MS = 700;
|
|
23
|
+
/** 一行 lane 摘要:档位 + 执行现场 + 会话是否已接上。 */
|
|
24
|
+
function laneLine(run, laneId) {
|
|
25
|
+
const lane = run.lanes[laneId];
|
|
26
|
+
if (!lane)
|
|
27
|
+
return `lane ${laneId} (unknown)`;
|
|
28
|
+
const state = lane.closed ? `closed: ${lane.closed.reason}` : lane.worktreePath ? 'open' : 'idle';
|
|
29
|
+
const extras = [
|
|
30
|
+
lane.mode,
|
|
31
|
+
state,
|
|
32
|
+
lane.sessionId ? `session ${lane.sessionId}` : 'no session yet',
|
|
33
|
+
lane.closed?.patchPath ? `patch ${lane.closed.patchPath}` : '',
|
|
34
|
+
].filter(Boolean);
|
|
35
|
+
return `lane ${lane.id} → ${lane.workspaceRoot} [${extras.join(' · ')}]`;
|
|
36
|
+
}
|
|
37
|
+
/** 给模型看的 Run 摘要:任务、lane、收工判定、awaiting 原因。不含路径噪音以外的东西。 */
|
|
38
|
+
export function formatRunForModel(run) {
|
|
39
|
+
const tasks = Object.values(run.tasks);
|
|
40
|
+
const done = tasks.filter((task) => task.status === 'completed').length;
|
|
41
|
+
const lines = [
|
|
42
|
+
`run ${run.id} · ${run.status} · ${done}/${tasks.length} task(s) completed`,
|
|
43
|
+
`objective: ${run.objective}`,
|
|
44
|
+
];
|
|
45
|
+
if (run.awaitingReason)
|
|
46
|
+
lines.push(`waiting for the user: ${run.awaitingReason}`);
|
|
47
|
+
for (const lane of Object.values(run.lanes ?? {}))
|
|
48
|
+
lines.push(laneLine(run, lane.id));
|
|
49
|
+
for (const task of tasks) {
|
|
50
|
+
const bits = [
|
|
51
|
+
`${taskGlyph(task.status)} ${task.id} ${task.status} [lane ${task.lane}] ${task.title}`,
|
|
52
|
+
task.sessionId ? ` session ${task.sessionId}` : '',
|
|
53
|
+
task.error ? ` error ${task.error}` : '',
|
|
54
|
+
task.output?.summary ? ` handoff ${firstLine(task.output.summary)}` : '',
|
|
55
|
+
// 风险必须出现在这里:Worker 把「我没做成的那部分」写进 risks,控制面不展示就等于被吞了。
|
|
56
|
+
...(task.output?.risks ?? []).map((risk) => ` risk ${firstLine(risk)}`),
|
|
57
|
+
task.lastEvent ? ` last ${task.lastEvent}` : '',
|
|
58
|
+
].filter(Boolean);
|
|
59
|
+
lines.push(bits.join('\n'));
|
|
60
|
+
for (const approval of Object.values(task.approvals ?? {})) {
|
|
61
|
+
lines.push(` ${approvalLine(approval)}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (run.lastReview) {
|
|
65
|
+
lines.push(`review: ${run.lastReview.verdict}` +
|
|
66
|
+
`${run.lastReview.rationale ? ` — ${firstLine(run.lastReview.rationale)}` : ''}` +
|
|
67
|
+
`${run.lastReview.remaining.length > 0 ? `\n remaining: ${run.lastReview.remaining.join(' | ')}` : ''}`);
|
|
68
|
+
}
|
|
69
|
+
return lines.join('\n');
|
|
70
|
+
}
|
|
71
|
+
function firstLine(text) {
|
|
72
|
+
const line = text
|
|
73
|
+
.split('\n')
|
|
74
|
+
.map((item) => item.trim())
|
|
75
|
+
.find((item) => item.length > 0);
|
|
76
|
+
return line ? (line.length > 160 ? `${line.slice(0, 157)}…` : line) : '';
|
|
77
|
+
}
|
|
78
|
+
/** 一行审批摘要:待决时带 id(回答要用它),已定时带结论。 */
|
|
79
|
+
export function approvalLine(approval) {
|
|
80
|
+
const what = `${approval.kind === 'ask_human' ? 'question' : 'approval'} ${approval.id}: ${approval.title}`;
|
|
81
|
+
if (!approval.resolved) {
|
|
82
|
+
const options = approval.options.length > 0 ? ` [${approval.options.join(' / ')}]` : ' [free text]';
|
|
83
|
+
return `? ${what}${options} — waiting for you`;
|
|
84
|
+
}
|
|
85
|
+
const resolution = approval.resolved;
|
|
86
|
+
const verdict = resolution.action === 'cancelled'
|
|
87
|
+
? 'cancelled'
|
|
88
|
+
: `${resolution.action}${resolution.value ? ` ${resolution.value}` : ''}`;
|
|
89
|
+
return `· ${what} — ${verdict} (${resolution.by})`;
|
|
90
|
+
}
|
|
91
|
+
function taskGlyph(status) {
|
|
92
|
+
if (status === 'completed')
|
|
93
|
+
return '✓';
|
|
94
|
+
if (status === 'running' || status === 'dispatching')
|
|
95
|
+
return '▶';
|
|
96
|
+
if (status === 'failed' || status === 'interrupted')
|
|
97
|
+
return '!';
|
|
98
|
+
if (status === 'cancelled')
|
|
99
|
+
return '×';
|
|
100
|
+
return '○';
|
|
101
|
+
}
|
|
102
|
+
export class SupervisorRuntime {
|
|
103
|
+
root;
|
|
104
|
+
scanRoots;
|
|
105
|
+
onNotice;
|
|
106
|
+
onWake;
|
|
107
|
+
workerFactory;
|
|
108
|
+
reviewFn;
|
|
109
|
+
workerInstance = null;
|
|
110
|
+
managed = new Map();
|
|
111
|
+
/** runId → 最近一次进度消息时刻(节流用)。 */
|
|
112
|
+
lastProgress = new Map();
|
|
113
|
+
/**
|
|
114
|
+
* 已唤醒过的状态键。
|
|
115
|
+
*
|
|
116
|
+
* 唤醒的语义是「这一份状态我刚交给模型看过」,所以去重键必须含状态本身
|
|
117
|
+
* (run 状态 + 完成数 + 待决审批数),而不是只含 runId——否则第二波任务跑完
|
|
118
|
+
* 就再也叫不醒了。反过来,同一份状态重复上报(idle 之后又来一条终态、审批
|
|
119
|
+
* 事件重放)必须只唤醒一次,否则模型会连环自言自语。
|
|
120
|
+
*/
|
|
121
|
+
woken = new Set();
|
|
122
|
+
/** runId → 最近一次收工判定(唤醒原文要自带它:上屏的通知不在模型历史里)。 */
|
|
123
|
+
lastReview = new Map();
|
|
124
|
+
constructor(options) {
|
|
125
|
+
this.root = path.resolve(options.root);
|
|
126
|
+
this.scanRoots = options.scanRoots ?? [];
|
|
127
|
+
this.onNotice = options.onNotice ?? (() => undefined);
|
|
128
|
+
this.onWake = options.onWake ?? (() => undefined);
|
|
129
|
+
/**
|
|
130
|
+
* 默认用哪种 Worker 执行器,由 `watchTerminals` 决定:
|
|
131
|
+
* - true:`LaneReplExecutor`——每个 lane 开一个**真 mocode REPL 窗口**,人也能在那儿打字;
|
|
132
|
+
* - false:`HostWorkerExecutor`——headless host 进程,没有画面,但控制通道最直接
|
|
133
|
+
* (CI / SSH / 测试都走这条)。
|
|
134
|
+
* 显式传 `worker` 时一律以注入为准(测试替身必须完全可控)。
|
|
135
|
+
*
|
|
136
|
+
* 默认**不**开窗:`SupervisorRuntime` 是给工具/测试用的库对象,弹窗口是副作用,
|
|
137
|
+
* 该由入口(supervise 对话 REPL)显式打开。默认值设成「跟随环境变量」会让单测
|
|
138
|
+
* 在开发者机器上真的弹出窗口(踩过一次:跑测试时冒出一排 node 进程占住 cwd,
|
|
139
|
+
* 临时目录 rm 报 EPERM)。
|
|
140
|
+
*/
|
|
141
|
+
const watchTerminals = options.watchTerminals ?? false;
|
|
142
|
+
this.workerFactory =
|
|
143
|
+
options.worker ??
|
|
144
|
+
(() => watchTerminals
|
|
145
|
+
? new LaneReplExecutor(options.openTerminal ? { openTerminal: options.openTerminal } : {})
|
|
146
|
+
: new HostWorkerExecutor());
|
|
147
|
+
this.reviewFn = options.review;
|
|
148
|
+
}
|
|
149
|
+
worker() {
|
|
150
|
+
if (!this.workerInstance)
|
|
151
|
+
this.workerInstance = this.workerFactory();
|
|
152
|
+
return this.workerInstance;
|
|
153
|
+
}
|
|
154
|
+
// ── 盘点 ──────────────────────────────────────────────────────────────────
|
|
155
|
+
workspaces(options = {}) {
|
|
156
|
+
return listWorkspaces({
|
|
157
|
+
roots: [this.root],
|
|
158
|
+
scanRoots: this.scanRoots,
|
|
159
|
+
includeSessions: options.includeSessions ?? true,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
formatWorkspaces() {
|
|
163
|
+
return formatWorkspaces(this.workspaces({ includeSessions: true }));
|
|
164
|
+
}
|
|
165
|
+
/** 跨工作区找 Run:先按 id 命中的目录判定,不做全盘遍历。 */
|
|
166
|
+
findRun(runId) {
|
|
167
|
+
for (const info of this.workspaces({ includeSessions: false })) {
|
|
168
|
+
if (!info.exists)
|
|
169
|
+
continue;
|
|
170
|
+
if (!fs.existsSync(path.join(orchestrationRoot(info.root), path.basename(runId))))
|
|
171
|
+
continue;
|
|
172
|
+
try {
|
|
173
|
+
return { store: OrchestrationStore.load(info.root, runId), workspaceRoot: info.root };
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
return undefined;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return undefined;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* 取某个 Run 的权威账本:内存里已托管就直接用那份,否则从盘上 load。
|
|
183
|
+
*
|
|
184
|
+
* 关键约束(踩过一次):同一 Run 绝不能同时存在两份 OrchestrationStore 实例。
|
|
185
|
+
* `appendTask` 只把事件写进自己那份 store 的内存状态,另一份看不见——驱动方会以为
|
|
186
|
+
* 「所有任务都已完成」,任务就永远停在 pending,Run 卡在 running。
|
|
187
|
+
*/
|
|
188
|
+
storeFor(workspaceRoot, runId) {
|
|
189
|
+
const managed = this.managed.get(runId);
|
|
190
|
+
if (managed)
|
|
191
|
+
return managed.store;
|
|
192
|
+
return OrchestrationStore.load(workspaceRoot, runId);
|
|
193
|
+
}
|
|
194
|
+
requireRun(runId) {
|
|
195
|
+
// 同一 Run 在内存里只能有一份账本。managed 里那份是权威实例(drive 循环持有它),
|
|
196
|
+
// 另 load 一份会让两边的 current 互相看不见对方刚 append 的事件——表现为「任务已落账为
|
|
197
|
+
// pending,但驱动方以为所有任务都跑完了」,run 卡在 running 再也不动。
|
|
198
|
+
const managed = this.managed.get(runId);
|
|
199
|
+
if (managed)
|
|
200
|
+
return { store: managed.store, workspaceRoot: managed.workspaceRoot };
|
|
201
|
+
const found = this.findRun(runId);
|
|
202
|
+
if (!found)
|
|
203
|
+
throw new Error(`no orchestration run ${runId} in any known workspace.`);
|
|
204
|
+
return found;
|
|
205
|
+
}
|
|
206
|
+
/** 这台机器上还能接活的 Run(running / idle / awaiting_user)。 */
|
|
207
|
+
liveRuns() {
|
|
208
|
+
const result = [];
|
|
209
|
+
for (const info of this.workspaces({ includeSessions: false })) {
|
|
210
|
+
if (!info.exists)
|
|
211
|
+
continue;
|
|
212
|
+
for (const run of listOrchestrations(info.root)) {
|
|
213
|
+
if (isRunLive(run))
|
|
214
|
+
result.push({ run, workspaceRoot: info.root });
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return result.sort((a, b) => b.run.createdAt.localeCompare(a.run.createdAt));
|
|
218
|
+
}
|
|
219
|
+
/** 每个工作区最近若干 Run(含终态,供「上次那单怎么样了」)。 */
|
|
220
|
+
recentRuns(limitPerWorkspace = 3) {
|
|
221
|
+
const result = [];
|
|
222
|
+
for (const info of this.workspaces({ includeSessions: false })) {
|
|
223
|
+
if (!info.exists)
|
|
224
|
+
continue;
|
|
225
|
+
for (const run of listOrchestrations(info.root).slice(0, limitPerWorkspace)) {
|
|
226
|
+
result.push({ run, workspaceRoot: info.root });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return result;
|
|
230
|
+
}
|
|
231
|
+
status(runId) {
|
|
232
|
+
if (runId)
|
|
233
|
+
return formatRunForModel(this.requireRun(runId).store.current);
|
|
234
|
+
const live = this.liveRuns();
|
|
235
|
+
if (live.length === 0)
|
|
236
|
+
return 'No live orchestration runs.';
|
|
237
|
+
return live.map(({ run }) => `${run.id} · ${run.status} · ${run.objective}`).join('\n');
|
|
238
|
+
}
|
|
239
|
+
// ── 人工介入 ──────────────────────────────────────────────────────────────
|
|
240
|
+
/**
|
|
241
|
+
* 全机待决的人工介入(工具审批 / Worker 提问)。
|
|
242
|
+
*
|
|
243
|
+
* 只读账本,不碰 Worker 进程:因此即使控制器在别的进程里(CLI 单发的 Run),
|
|
244
|
+
* 这里也能如实列出「谁在等」,只是回答不了——`respondApproval` 会返回 false。
|
|
245
|
+
*/
|
|
246
|
+
pendingApprovals() {
|
|
247
|
+
const result = [];
|
|
248
|
+
for (const { run } of this.recentRuns(3)) {
|
|
249
|
+
if (isRunTerminal(run))
|
|
250
|
+
continue;
|
|
251
|
+
for (const task of Object.values(run.tasks)) {
|
|
252
|
+
for (const approval of Object.values(task.approvals ?? {})) {
|
|
253
|
+
if (!approval.resolved)
|
|
254
|
+
result.push({ run, taskId: task.id, approval });
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return result;
|
|
259
|
+
}
|
|
260
|
+
/** 一行一条待决审批,含回答时要用的 approvalId。 */
|
|
261
|
+
formatApprovals() {
|
|
262
|
+
const pending = this.pendingApprovals();
|
|
263
|
+
if (pending.length === 0)
|
|
264
|
+
return '没有待决的人工介入。';
|
|
265
|
+
return pending
|
|
266
|
+
.map(({ run, approval }) => `${approval.id} run ${run.id} ${approval.taskId} ${approval.kind}\n` +
|
|
267
|
+
` ${approval.title}${approval.detail ? `\n ${firstLine(approval.detail)}` : ''}\n` +
|
|
268
|
+
` ${approval.options.length > 0 ? approval.options.map((item, index) => `[${index + 1}] ${item}`).join(' ') : '(自由文本)'}`)
|
|
269
|
+
.join('\n');
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* 把一个决定转给正在等它的 Worker。
|
|
273
|
+
*
|
|
274
|
+
* 只有「本进程托管的 Run + 该 approvalId 仍在执行器手里」才会成功。返回 false 时
|
|
275
|
+
* 调用方必须如实说「这条已经不可能回答了」,不能假装成功——用户会以为按钮生效了。
|
|
276
|
+
*/
|
|
277
|
+
respondApproval(approvalId, resolution) {
|
|
278
|
+
const owner = this.pendingApprovals().find((item) => item.approval.id === approvalId);
|
|
279
|
+
if (!owner)
|
|
280
|
+
return false;
|
|
281
|
+
const managed = this.managed.get(owner.run.id);
|
|
282
|
+
if (!managed)
|
|
283
|
+
return false;
|
|
284
|
+
return this.schedulerFor(managed.store, managed.workspaceRoot).respondApproval(approvalId, resolution);
|
|
285
|
+
}
|
|
286
|
+
/** 便捷入口:按序号(1-based,对齐 formatApprovals)或完整 id 回答。 */
|
|
287
|
+
answerApproval(target, action, value) {
|
|
288
|
+
const pending = this.pendingApprovals();
|
|
289
|
+
const index = Number.parseInt(target, 10);
|
|
290
|
+
const hit = Number.isInteger(index) && String(index) === target ? pending[index - 1] : undefined;
|
|
291
|
+
const picked = hit?.approval.id ?? target;
|
|
292
|
+
const resolution = {
|
|
293
|
+
action,
|
|
294
|
+
...(value ? { value } : {}),
|
|
295
|
+
by: 'operator',
|
|
296
|
+
at: new Date().toISOString(),
|
|
297
|
+
};
|
|
298
|
+
if (!this.respondApproval(picked, resolution)) {
|
|
299
|
+
return `approval ${picked} is no longer pending (already answered, timed out, or owned by another process).`;
|
|
300
|
+
}
|
|
301
|
+
return `approval ${picked} answered: ${action}${value ? ` ${value}` : ''}.`;
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* 每轮对话前注入的编排快照:工作区清单(压缩)+ 在跑的 Run。
|
|
305
|
+
* 只给「够判断往哪派、现在能不能派」的信息,不给完整任务表(那要 status 工具按需取)。
|
|
306
|
+
*/
|
|
307
|
+
snapshot() {
|
|
308
|
+
const workspaces = this.workspaces({ includeSessions: true });
|
|
309
|
+
const lines = ['## Orchestration snapshot'];
|
|
310
|
+
lines.push(`Supervisor cwd: ${this.root}`);
|
|
311
|
+
if (workspaces.length === 0) {
|
|
312
|
+
lines.push('Known workspaces: none yet (no mocode session has been started on this machine).');
|
|
313
|
+
}
|
|
314
|
+
else {
|
|
315
|
+
lines.push(`Known workspaces (${workspaces.length}):`);
|
|
316
|
+
for (const info of workspaces.slice(0, 12)) {
|
|
317
|
+
const flags = [
|
|
318
|
+
info.exists ? '' : 'missing',
|
|
319
|
+
info.git ? `git:${info.branch ?? '?'}${info.dirty ? '*' : ''}` : 'no-git',
|
|
320
|
+
`${info.sessions.length} session(s)`,
|
|
321
|
+
].filter(Boolean);
|
|
322
|
+
const lanes = info.lanes.length > 0
|
|
323
|
+
? ` · open lane(s): ${info.lanes.map((l) => `${l.laneId}(${l.status})`).join(', ')}`
|
|
324
|
+
: '';
|
|
325
|
+
lines.push(`- ${info.root} [${flags.join(' ')}]${lanes}`);
|
|
326
|
+
}
|
|
327
|
+
if (workspaces.length > 12)
|
|
328
|
+
lines.push(`- … ${workspaces.length - 12} more (use supervise_workspaces)`);
|
|
329
|
+
}
|
|
330
|
+
const live = this.liveRuns();
|
|
331
|
+
if (live.length === 0) {
|
|
332
|
+
lines.push('Live runs: none.');
|
|
333
|
+
}
|
|
334
|
+
else {
|
|
335
|
+
lines.push(`Live runs (${live.length}):`);
|
|
336
|
+
for (const { run } of live.slice(0, 8)) {
|
|
337
|
+
const tasks = Object.values(run.tasks);
|
|
338
|
+
const active = tasks.filter((task) => task.status === 'running' || task.status === 'dispatching').length;
|
|
339
|
+
const pending = this.managed.get(run.id)?.pending.length ?? 0;
|
|
340
|
+
lines.push(`- ${run.id} · ${run.status} · ${run.workspaceRoot} · ${tasks.filter((t) => t.status === 'completed').length}/${tasks.length} done` +
|
|
341
|
+
`${active > 0 ? ` · ${active} running` : ''}${pending > 0 ? ` · ${pending} queued` : ''}` +
|
|
342
|
+
`${run.awaitingReason ? ` · waiting: ${firstLine(run.awaitingReason)}` : ''}`);
|
|
343
|
+
}
|
|
344
|
+
if (live.length > 8)
|
|
345
|
+
lines.push(`- … ${live.length - 8} more (use supervise_status)`);
|
|
346
|
+
}
|
|
347
|
+
// 待决的人工介入必须在快照里:它是唯一「模型不主动查就会被漏掉」的状态,
|
|
348
|
+
// 而漏掉它意味着 Worker 一直停在那里等人。
|
|
349
|
+
const approvals = this.pendingApprovals();
|
|
350
|
+
if (approvals.length > 0) {
|
|
351
|
+
lines.push(`
|
|
352
|
+
## Waiting for a human (${approvals.length})`);
|
|
353
|
+
for (const { run, approval } of approvals.slice(0, 8)) {
|
|
354
|
+
const options = approval.options.length > 0 ? ` options: ${approval.options.join(' / ')}` : ' free text';
|
|
355
|
+
lines.push(`- run ${run.id} · ${approval.taskId} · ${approval.kind} ${approval.id}: ${approval.title}${options}`, ` ${approval.detail ? `detail: ${firstLine(approval.detail)}` : `requested ${approval.requestedAt}`}`);
|
|
356
|
+
}
|
|
357
|
+
lines.push('Answer with supervise_approve (or tell the operator these are waiting). The worker stays paused until answered ' +
|
|
358
|
+
'and the request is denied on timeout.');
|
|
359
|
+
}
|
|
360
|
+
return lines.join('\n');
|
|
361
|
+
}
|
|
362
|
+
// ── 派活 ──────────────────────────────────────────────────────────────────
|
|
363
|
+
/**
|
|
364
|
+
* 往某个工作区派活。
|
|
365
|
+
*
|
|
366
|
+
* 三种落点,按顺序判定:
|
|
367
|
+
* 1. 给了 runId → 追加到那个 Run(running 时排队);
|
|
368
|
+
* 2. 该工作区有还活着的 Run → 追加到它(`接着在那个会话派活`);
|
|
369
|
+
* 3. 都没有 → 新建一个 Run(autoClose=false,跑完进 idle,lane 保持可再用)。
|
|
370
|
+
*/
|
|
371
|
+
async dispatch(input) {
|
|
372
|
+
const workspace = path.resolve(input.workspace ?? this.root);
|
|
373
|
+
if (!fs.existsSync(workspace))
|
|
374
|
+
throw new Error(`workspace does not exist: ${workspace}`);
|
|
375
|
+
const objective = input.objective.trim();
|
|
376
|
+
if (!objective)
|
|
377
|
+
throw new Error('objective must not be empty.');
|
|
378
|
+
const title = (input.title ?? firstLine(objective)).slice(0, 80);
|
|
379
|
+
const taskId = input.taskId?.trim() || undefined;
|
|
380
|
+
const laneId = input.lane?.trim() || undefined;
|
|
381
|
+
if (input.runId) {
|
|
382
|
+
const { store, workspaceRoot } = this.requireRun(input.runId);
|
|
383
|
+
if (path.resolve(workspaceRoot) !== workspace && input.workspace) {
|
|
384
|
+
throw new Error(`run ${input.runId} belongs to ${workspaceRoot}, not ${workspace}; omit workspace or pass the matching one.`);
|
|
385
|
+
}
|
|
386
|
+
const task = this.buildTask(store.current, {
|
|
387
|
+
id: taskId,
|
|
388
|
+
title,
|
|
389
|
+
objective,
|
|
390
|
+
lane: laneId,
|
|
391
|
+
dependsOn: input.dependsOn,
|
|
392
|
+
requiredChecks: input.requiredChecks,
|
|
393
|
+
acceptanceCriteria: input.acceptanceCriteria,
|
|
394
|
+
changePolicy: input.changePolicy,
|
|
395
|
+
allow: input.allow,
|
|
396
|
+
deny: input.deny,
|
|
397
|
+
});
|
|
398
|
+
return this.enqueue(store, workspaceRoot, task);
|
|
399
|
+
}
|
|
400
|
+
const live = listOrchestrations(workspace).find((run) => isRunLive(run));
|
|
401
|
+
if (live) {
|
|
402
|
+
const store = this.storeFor(workspace, live.id);
|
|
403
|
+
const task = this.buildTask(store.current, {
|
|
404
|
+
id: taskId,
|
|
405
|
+
title,
|
|
406
|
+
objective,
|
|
407
|
+
lane: laneId,
|
|
408
|
+
dependsOn: input.dependsOn,
|
|
409
|
+
requiredChecks: input.requiredChecks,
|
|
410
|
+
acceptanceCriteria: input.acceptanceCriteria,
|
|
411
|
+
changePolicy: input.changePolicy,
|
|
412
|
+
allow: input.allow,
|
|
413
|
+
deny: input.deny,
|
|
414
|
+
});
|
|
415
|
+
const note = this.enqueue(store, workspace, task);
|
|
416
|
+
return `Reused the live run in ${workspace} instead of starting a new one.\n${note}`;
|
|
417
|
+
}
|
|
418
|
+
// 新建 Run:lane 档位按工作区能力判定(git 根 → worktree,非 git → copy)。
|
|
419
|
+
// 刻意不给 inplace 入口:对话里的一句话不该直接改写真实目录。
|
|
420
|
+
const definition = prepareDefinition({
|
|
421
|
+
objective,
|
|
422
|
+
autoClose: false,
|
|
423
|
+
lanes: [{ id: laneId ?? taskId ?? 'task-1', workspaceRoot: workspace }],
|
|
424
|
+
tasks: [{ id: taskId ?? 'task-1', title, objective, lane: laneId ?? taskId ?? 'task-1' }],
|
|
425
|
+
}, workspace, false);
|
|
426
|
+
const store = OrchestrationStore.create(workspace, definition);
|
|
427
|
+
const runId = store.current.id;
|
|
428
|
+
this.start(store, workspace);
|
|
429
|
+
const lane = Object.values(store.current.lanes)[0];
|
|
430
|
+
return (`Started run ${runId} in ${workspace}.\n` +
|
|
431
|
+
`${laneLine(store.current, lane.id)}\n` +
|
|
432
|
+
'The worker is running in the background; the conversation stays responsive.');
|
|
433
|
+
}
|
|
434
|
+
buildTask(run, input) {
|
|
435
|
+
const id = input.id ?? this.nextTaskId(run, 'task');
|
|
436
|
+
const lane = input.lane ?? id;
|
|
437
|
+
const task = {
|
|
438
|
+
id,
|
|
439
|
+
title: input.title,
|
|
440
|
+
objective: input.objective,
|
|
441
|
+
lane,
|
|
442
|
+
...(input.dependsOn && input.dependsOn.length > 0 ? { dependsOn: input.dependsOn } : {}),
|
|
443
|
+
...(input.requiredChecks && input.requiredChecks.length > 0 ? { requiredChecks: input.requiredChecks } : {}),
|
|
444
|
+
...(input.acceptanceCriteria && input.acceptanceCriteria.length > 0
|
|
445
|
+
? { acceptanceCriteria: input.acceptanceCriteria }
|
|
446
|
+
: {}),
|
|
447
|
+
...(input.changePolicy ? { changePolicy: input.changePolicy } : {}),
|
|
448
|
+
...(input.allow || input.deny
|
|
449
|
+
? { scope: { ...(input.allow ? { allow: input.allow } : {}), ...(input.deny ? { deny: input.deny } : {}) } }
|
|
450
|
+
: {}),
|
|
451
|
+
};
|
|
452
|
+
return task;
|
|
453
|
+
}
|
|
454
|
+
nextTaskId(run, prefix) {
|
|
455
|
+
let index = 1;
|
|
456
|
+
while (run.tasks[`${prefix}-${index}`])
|
|
457
|
+
index++;
|
|
458
|
+
return `${prefix}-${index}`;
|
|
459
|
+
}
|
|
460
|
+
/** 静默态直接落账并启动;running 时排队,等这一波收尾。 */
|
|
461
|
+
enqueue(store, workspaceRoot, task) {
|
|
462
|
+
const run = store.current;
|
|
463
|
+
const managed = this.managed.get(run.id);
|
|
464
|
+
if (TERMINAL.has(run.status)) {
|
|
465
|
+
throw new Error(`run ${run.id} is ${run.status}; dispatch to a live run or start a new one.`);
|
|
466
|
+
}
|
|
467
|
+
const busy = run.status === 'running' || (managed?.running ?? false);
|
|
468
|
+
if (busy) {
|
|
469
|
+
if (!managed)
|
|
470
|
+
throw new Error(`run ${run.id} is running under another controller; use ask/tell once it idles.`);
|
|
471
|
+
managed.pending.push(task);
|
|
472
|
+
return (`Queued task ${task.id} (lane ${task.lane}) on run ${run.id}: the run is still working. ` +
|
|
473
|
+
'It will be added and started automatically as soon as the current batch finishes.');
|
|
474
|
+
}
|
|
475
|
+
const scheduler = this.schedulerFor(store, workspaceRoot);
|
|
476
|
+
scheduler.appendTask(task, { reopenLane: true });
|
|
477
|
+
this.start(store, workspaceRoot);
|
|
478
|
+
return `Added task ${task.id} (lane ${task.lane}) to run ${run.id} and started it.`;
|
|
479
|
+
}
|
|
480
|
+
/** `ask` / `tell` 复用的同一入口:只读回合 vs 可写纠偏。 */
|
|
481
|
+
async laneTurn(kind, input) {
|
|
482
|
+
const { store } = this.requireRun(input.runId);
|
|
483
|
+
const run = store.current;
|
|
484
|
+
const lane = run.lanes[input.lane];
|
|
485
|
+
if (!lane)
|
|
486
|
+
throw new Error(`run ${run.id} has no lane ${input.lane}.`);
|
|
487
|
+
const text = input.text.trim();
|
|
488
|
+
if (!text)
|
|
489
|
+
throw new Error(`${kind} requires a non-empty message.`);
|
|
490
|
+
const task = kind === 'ask'
|
|
491
|
+
? this.buildTask(run, {
|
|
492
|
+
id: this.nextTaskId(run, 'ask'),
|
|
493
|
+
title: text.slice(0, 80),
|
|
494
|
+
objective: `${text}\n\nThis is a status question from the operator, delivered into this lane's existing session. ` +
|
|
495
|
+
'Answer from the work you already did in this session (files you read, commands you ran). ' +
|
|
496
|
+
'Do not modify any file; report what is done, what is verified, and what remains.',
|
|
497
|
+
lane: input.lane,
|
|
498
|
+
changePolicy: 'read_only',
|
|
499
|
+
})
|
|
500
|
+
: this.buildTask(run, {
|
|
501
|
+
id: this.nextTaskId(run, 'steer'),
|
|
502
|
+
title: text.slice(0, 80),
|
|
503
|
+
objective: `${text}\n\nThis is an operator steering message. Treat it as a binding constraint for this lane ` +
|
|
504
|
+
'and act accordingly in the same session. Do not redo work that is already on disk.',
|
|
505
|
+
lane: input.lane,
|
|
506
|
+
changePolicy: 'isolated_write',
|
|
507
|
+
});
|
|
508
|
+
const note = this.enqueue(store, run.workspaceRoot, task);
|
|
509
|
+
return `${kind === 'ask' ? 'Status question' : 'Steering message'} sent on lane ${input.lane}.\n${note}`;
|
|
510
|
+
}
|
|
511
|
+
// ── 收尾 ──────────────────────────────────────────────────────────────────
|
|
512
|
+
async closeLane(runId, laneId) {
|
|
513
|
+
const { store, workspaceRoot } = this.requireRun(runId);
|
|
514
|
+
if (store.current.status === 'running') {
|
|
515
|
+
throw new Error(`run ${runId} is running; close the lane after it idles (or cancel it first).`);
|
|
516
|
+
}
|
|
517
|
+
const managed = this.managed.get(runId);
|
|
518
|
+
const lease = managed?.lease ?? store.acquireControllerLease();
|
|
519
|
+
try {
|
|
520
|
+
const scheduler = this.schedulerFor(store, workspaceRoot);
|
|
521
|
+
const final = await scheduler.closeLaneById(laneId, 'Closed by the supervisor.');
|
|
522
|
+
return formatRunForModel(final);
|
|
523
|
+
}
|
|
524
|
+
finally {
|
|
525
|
+
if (!managed)
|
|
526
|
+
lease.release();
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
integrate(runId, options = {}) {
|
|
530
|
+
const { store, workspaceRoot } = this.requireRun(runId);
|
|
531
|
+
const result = integrateRun(store.current, {
|
|
532
|
+
lanes: options.lane ? [options.lane] : undefined,
|
|
533
|
+
apply: options.apply === true,
|
|
534
|
+
});
|
|
535
|
+
appendIntegrationLog(store.artifactPath('integration.jsonl'), result);
|
|
536
|
+
return `${formatIntegration(result)}workspace root: ${workspaceRoot}\n`;
|
|
537
|
+
}
|
|
538
|
+
async review(runId, options = {}) {
|
|
539
|
+
const { store, workspaceRoot } = this.requireRun(runId);
|
|
540
|
+
const { reviewRun } = await import('./review.js');
|
|
541
|
+
const review = await reviewRun(store.current, { dryRun: options.dryRun === true });
|
|
542
|
+
if (options.dryRun !== true && !isRunTerminal(store.current)) {
|
|
543
|
+
const managed = this.managed.get(runId);
|
|
544
|
+
const lease = managed?.lease ?? store.acquireControllerLease();
|
|
545
|
+
try {
|
|
546
|
+
this.schedulerFor(store, workspaceRoot).recordReview(review);
|
|
547
|
+
}
|
|
548
|
+
finally {
|
|
549
|
+
if (!managed)
|
|
550
|
+
lease.release();
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
return (`review: ${review.verdict}${review.error ? ` (error: ${review.error})` : ''}\n` +
|
|
554
|
+
`${review.rationale || '(no rationale)'}` +
|
|
555
|
+
`${review.remaining.length > 0 ? `\nremaining:\n${review.remaining.map((item) => `- ${item}`).join('\n')}` : ''}`);
|
|
556
|
+
}
|
|
557
|
+
async cancel(runId) {
|
|
558
|
+
const { store } = this.requireRun(runId);
|
|
559
|
+
if (!isRunLive(store.current))
|
|
560
|
+
return `run ${runId} is already ${store.current.status}.`;
|
|
561
|
+
store.requestCancellation();
|
|
562
|
+
return `Cancellation requested for ${runId}; the scheduler will stop its workers.`;
|
|
563
|
+
}
|
|
564
|
+
/** 释放所有控制器租约(不取消在跑的 Run:状态留在盘上,`supervise resume` 可续)。 */
|
|
565
|
+
shutdown() {
|
|
566
|
+
for (const managed of this.managed.values()) {
|
|
567
|
+
try {
|
|
568
|
+
managed.lease.release();
|
|
569
|
+
}
|
|
570
|
+
catch {
|
|
571
|
+
// 释放失败最多留一个按 PID 判活的过期锁,下次 acquire 会接管。
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
this.managed.clear();
|
|
575
|
+
}
|
|
576
|
+
// ── 调度 ──────────────────────────────────────────────────────────────────
|
|
577
|
+
schedulerFor(store, workspaceRoot) {
|
|
578
|
+
return new OrchestrationScheduler(store, this.worker(), {
|
|
579
|
+
onEvent: (event, run) => this.notify(event, run, workspaceRoot),
|
|
580
|
+
}, { pollMs: 300, ...(this.reviewFn ? { review: this.reviewFn } : {}) });
|
|
581
|
+
}
|
|
582
|
+
/** 拿到(或复用)该 Run 的控制器租约,把 scheduler.run() 挂到后台。 */
|
|
583
|
+
start(store, workspaceRoot) {
|
|
584
|
+
const runId = store.current.id;
|
|
585
|
+
const existing = this.managed.get(runId);
|
|
586
|
+
if (existing) {
|
|
587
|
+
if (existing.running)
|
|
588
|
+
existing.needsDrive = true;
|
|
589
|
+
else
|
|
590
|
+
void this.drive(existing);
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
const managed = {
|
|
594
|
+
store,
|
|
595
|
+
workspaceRoot,
|
|
596
|
+
lease: store.acquireControllerLease(),
|
|
597
|
+
running: false,
|
|
598
|
+
needsDrive: false,
|
|
599
|
+
pending: [],
|
|
600
|
+
};
|
|
601
|
+
this.managed.set(runId, managed);
|
|
602
|
+
void this.drive(managed);
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* 后台驱动循环:跑一波;跑空后若队列里有排队的任务就落账再跑,否则把控制器还给盘面
|
|
606
|
+
* (Run 停在 idle / awaiting_user,等下一次 dispatch)。
|
|
607
|
+
*/
|
|
608
|
+
async drive(managed) {
|
|
609
|
+
if (managed.running)
|
|
610
|
+
return;
|
|
611
|
+
managed.running = true;
|
|
612
|
+
try {
|
|
613
|
+
for (;;) {
|
|
614
|
+
const scheduler = this.schedulerFor(managed.store, managed.workspaceRoot);
|
|
615
|
+
let final;
|
|
616
|
+
try {
|
|
617
|
+
final = await scheduler.run();
|
|
618
|
+
}
|
|
619
|
+
catch (error) {
|
|
620
|
+
this.notice(managed, `scheduler stopped: ${error instanceof Error ? error.message : String(error)}`, 'error');
|
|
621
|
+
break;
|
|
622
|
+
}
|
|
623
|
+
if (TERMINAL.has(final.status))
|
|
624
|
+
break;
|
|
625
|
+
const next = managed.pending.shift();
|
|
626
|
+
if (!next)
|
|
627
|
+
break;
|
|
628
|
+
try {
|
|
629
|
+
scheduler.appendTask(next, { reopenLane: true });
|
|
630
|
+
}
|
|
631
|
+
catch (error) {
|
|
632
|
+
this.notice(managed, `could not add queued task ${next.id}: ${error instanceof Error ? error.message : String(error)}`, 'error');
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
finally {
|
|
637
|
+
managed.running = false;
|
|
638
|
+
// 终态 Run 的账本已冻结:控制器任务完成,交还租约。
|
|
639
|
+
if (TERMINAL.has(managed.store.current.status)) {
|
|
640
|
+
try {
|
|
641
|
+
managed.lease.release();
|
|
642
|
+
}
|
|
643
|
+
catch {
|
|
644
|
+
// ignore
|
|
645
|
+
}
|
|
646
|
+
this.managed.delete(managed.store.current.id);
|
|
647
|
+
}
|
|
648
|
+
else if (managed.needsDrive) {
|
|
649
|
+
// 收尾途中(run() 已返回、running 还没置回)又有新任务落账:这里补跑一波。
|
|
650
|
+
// 没有这个转接,派活会撞上「对话以为已启动、后台已退出循环」的静默死锁。
|
|
651
|
+
managed.needsDrive = false;
|
|
652
|
+
void this.drive(managed);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
notice(managed, text, level = 'info') {
|
|
657
|
+
this.onNotice({
|
|
658
|
+
runId: managed.store.current.id,
|
|
659
|
+
workspaceRoot: managed.workspaceRoot,
|
|
660
|
+
channel: 'event',
|
|
661
|
+
text,
|
|
662
|
+
level,
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
/**
|
|
666
|
+
* 「这一波落定了,该你接手了」——把一条真实用户消息交给 supervisor 的模型。
|
|
667
|
+
*
|
|
668
|
+
* 三条克制(不然就是自己给自己刷屏):
|
|
669
|
+
* 1. **只在一波落定时叫**:idle / 终态 / 等审批。逐条 `task.completed` 不叫——五个任务
|
|
670
|
+
* 并行时那是五次无效唤醒,模型每次都只能念同一份状态。
|
|
671
|
+
* 2. **同一份状态只叫一次**:去重键含状态本身(status + 完成数 + 待决审批数),
|
|
672
|
+
* 所以第二波任务跑完照样叫得醒,而重复上报的事件不会连环转。
|
|
673
|
+
* 3. **提示词自带上下文**:上屏的 `emit` 通知不进模型历史,光说「活干完了」它会去猜。
|
|
674
|
+
*/
|
|
675
|
+
wake(run, workspaceRoot, reason) {
|
|
676
|
+
const tasks = Object.values(run.tasks);
|
|
677
|
+
const completed = tasks.filter((task) => task.status === 'completed').length;
|
|
678
|
+
const approvals = this.pendingApprovals().length;
|
|
679
|
+
const key = `${run.id}:${run.status}:${completed}/${tasks.length}:${approvals}`;
|
|
680
|
+
if (this.woken.has(key))
|
|
681
|
+
return;
|
|
682
|
+
this.woken.add(key);
|
|
683
|
+
const head = reason === 'approval'
|
|
684
|
+
? `后台等你决定:run ${run.id}`
|
|
685
|
+
: reason === 'terminal'
|
|
686
|
+
? `后台有 run 收尾了:run ${run.id}`
|
|
687
|
+
: `后台这一波干完了:run ${run.id}`;
|
|
688
|
+
const review = this.lastReview.get(run.id);
|
|
689
|
+
const lines = [
|
|
690
|
+
`${head}(${workspaceRoot},${completed}/${tasks.length} 个任务完成,状态 ${run.status})。`,
|
|
691
|
+
'这段是系统通知,不是你自己的话:请现在查一下(supervise_status),',
|
|
692
|
+
reason === 'approval'
|
|
693
|
+
? '把等你的审批念清楚并给出可选项,等我决定;在我回答之前不要自行放行。'
|
|
694
|
+
: '如实汇报结果与风险,然后判断收工还是继续派活;需要验收的(close/integrate)先说明再问。',
|
|
695
|
+
];
|
|
696
|
+
if (review) {
|
|
697
|
+
lines.push(`上一轮的收工判定是 ${review.verdict}${review.rationale ? `(${firstLine(review.rationale)})` : ''}` +
|
|
698
|
+
`${review.remaining.length > 0 ? `,剩余:${review.remaining.map(firstLine).join(' | ')}` : ''}。`);
|
|
699
|
+
}
|
|
700
|
+
this.onWake({ key, runId: run.id, workspaceRoot, reason, prompt: lines.join('\n') });
|
|
701
|
+
}
|
|
702
|
+
/** 把调度器事件压成一行人话:状态变化进正文,执行进度只进底栏。 */
|
|
703
|
+
notify(event, run, workspaceRoot) {
|
|
704
|
+
const emit = (text, level = 'info') => {
|
|
705
|
+
this.onNotice({ runId: run.id, workspaceRoot, channel: 'event', text, level });
|
|
706
|
+
};
|
|
707
|
+
/**
|
|
708
|
+
* 只有「谁在动、动到哪一步」这一层走 activity 通道——它每几百毫秒就来一条,
|
|
709
|
+
* 写进正文会把对话刷没(这正是独立终端窗口要解决的那件事)。
|
|
710
|
+
*/
|
|
711
|
+
const activity = (taskId, text) => {
|
|
712
|
+
this.onNotice({ runId: run.id, workspaceRoot, channel: 'activity', text, level: 'info', taskId });
|
|
713
|
+
};
|
|
714
|
+
switch (event.type) {
|
|
715
|
+
case 'run.created':
|
|
716
|
+
case 'task.ready':
|
|
717
|
+
case 'lane.checkpoint':
|
|
718
|
+
return;
|
|
719
|
+
case 'run.reviewed': {
|
|
720
|
+
// 这次判定真花了一次模型回合(最长 90s),结论却只落盘不上屏,等于纯亏。
|
|
721
|
+
// 把它当正式通知显出来:用户要知道「系统自己认为收没收工」。
|
|
722
|
+
const review = event.data.review;
|
|
723
|
+
this.lastReview.set(run.id, review);
|
|
724
|
+
const remaining = review.remaining.length > 0 ? ` · remaining: ${review.remaining.map(firstLine).join(' | ')}` : '';
|
|
725
|
+
emit(`review: ${review.verdict}${review.error ? ` (error: ${firstLine(review.error)})` : ''}` +
|
|
726
|
+
`${review.rationale ? ` — ${firstLine(review.rationale)}` : ''}${remaining}`, review.verdict === 'continue' ? 'error' : 'info');
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
case 'task.progress': {
|
|
730
|
+
const key = `${run.id}:${event.data.taskId}`;
|
|
731
|
+
const last = this.lastProgress.get(key) ?? 0;
|
|
732
|
+
const now = Date.now();
|
|
733
|
+
if (now - last < PROGRESS_THROTTLE_MS)
|
|
734
|
+
return;
|
|
735
|
+
this.lastProgress.set(key, now);
|
|
736
|
+
activity(event.data.taskId, event.data.message);
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
case 'task.started':
|
|
740
|
+
emit(`${event.data.taskId} started${event.data.sessionId ? ` · session ${event.data.sessionId}` : ''}`);
|
|
741
|
+
return;
|
|
742
|
+
case 'task.completed': {
|
|
743
|
+
const summary = firstLine(event.data.handoff.summary);
|
|
744
|
+
emit(`${event.data.taskId} ✓ done${summary ? ` — ${summary}` : ''}`);
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
case 'task.failed':
|
|
748
|
+
case 'task.interrupted':
|
|
749
|
+
emit(`${event.data.taskId} ${event.type === 'task.failed' ? 'failed' : 'interrupted'} — ${firstLine(event.data.error)}`, 'error');
|
|
750
|
+
return;
|
|
751
|
+
case 'task.approval_requested': {
|
|
752
|
+
// 这一条必须显眼:Worker 已经停下来等人了,汇报里不能只当成一条普通进度。
|
|
753
|
+
const approval = event.data.approval;
|
|
754
|
+
const options = approval.options.length > 0 ? ` [${approval.options.join(' / ')}]` : ' [free text]';
|
|
755
|
+
emit(`${event.data.taskId} needs a human · ${approval.kind} ${approval.id}: ${approval.title}${options} — /approvals or supervise_approve`, 'error');
|
|
756
|
+
// 人也得被叫一声:Worker 就停在那里不动,不叫的话这个 Run 就是静默卡死。
|
|
757
|
+
this.wake(run, workspaceRoot, 'approval');
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
case 'task.approval_resolved':
|
|
761
|
+
emit(`approval ${event.data.approvalId} ${event.data.resolution.by === 'timeout' ? 'timed out — denied' : 'answered'}`);
|
|
762
|
+
return;
|
|
763
|
+
case 'task.deferred':
|
|
764
|
+
case 'conflict.serialized':
|
|
765
|
+
return;
|
|
766
|
+
case 'lane.opened':
|
|
767
|
+
emit(`lane ${event.data.laneId} opened at ${event.data.worktreePath}`);
|
|
768
|
+
return;
|
|
769
|
+
case 'lane.closed':
|
|
770
|
+
emit(`lane ${event.data.laneId} closed${event.data.patchPath ? ` · patch ${event.data.patchPath}` : ''}` +
|
|
771
|
+
`${event.data.error ? ` · ${event.data.error}` : ''}`, event.data.error ? 'error' : 'info');
|
|
772
|
+
return;
|
|
773
|
+
case 'run.idle':
|
|
774
|
+
emit(`run idle — ${Object.values(run.tasks).filter((task) => task.status === 'completed').length} task(s) done, lanes kept open. Add more work or close the lane.`);
|
|
775
|
+
// 断链就在这里:活干完了只有一行通知,没人接手 → 用户看到「跑完了,然后停在那儿」。
|
|
776
|
+
this.wake(run, workspaceRoot, 'idle');
|
|
777
|
+
return;
|
|
778
|
+
case 'run.awaiting_user':
|
|
779
|
+
emit(`run is waiting for you — ${event.data.reason}`, 'error');
|
|
780
|
+
this.wake(run, workspaceRoot, 'approval');
|
|
781
|
+
return;
|
|
782
|
+
case 'run.completed':
|
|
783
|
+
emit('run completed.');
|
|
784
|
+
this.wake(run, workspaceRoot, 'terminal');
|
|
785
|
+
return;
|
|
786
|
+
case 'run.failed':
|
|
787
|
+
emit(`run failed${event.data.reason ? ` — ${event.data.reason}` : ''}`, 'error');
|
|
788
|
+
this.wake(run, workspaceRoot, 'terminal');
|
|
789
|
+
return;
|
|
790
|
+
case 'run.cancelled':
|
|
791
|
+
emit('run cancelled.', 'error');
|
|
792
|
+
this.wake(run, workspaceRoot, 'terminal');
|
|
793
|
+
return;
|
|
794
|
+
default:
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
}
|