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,628 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { gitRepositoryDirty } from '../jobs/worktree.js';
|
|
4
|
+
import { OrchestrationScheduler } from './scheduler.js';
|
|
5
|
+
import { isRunLive } from './state.js';
|
|
6
|
+
import { appendIntegrationLog, formatIntegration, integrateRun } from './integrate.js';
|
|
7
|
+
import { collectBoard, formatBoardSnapshot } from './board.js';
|
|
8
|
+
import { prepareDefinition } from './lanes.js';
|
|
9
|
+
import { listOrchestrations, OrchestrationStore } from './store.js';
|
|
10
|
+
import { reviewRun } from './review.js';
|
|
11
|
+
import { HostWorkerExecutor } from './worker.js';
|
|
12
|
+
import { formatWorkspaces, listWorkspaces } from './workspaces.js';
|
|
13
|
+
export const SUPERVISE_USAGE = [
|
|
14
|
+
'Usage: mocode supervise [<command>] [--sandbox-root <path>]',
|
|
15
|
+
' (no command) 进 Supervisor 对话:自然语言派活 / 查进度 / 收工',
|
|
16
|
+
' workspaces [--scan-roots <dir>] [--json] 列出这台机器上跑过 mocode 的工作区',
|
|
17
|
+
' start <objective> | start --file <dag.json> [--allow-inplace] [--auto-close] [--concurrency N]',
|
|
18
|
+
' dispatch <workspace> --lane <id> <objective> 向工作区派活(无 live run 时新建)',
|
|
19
|
+
' ask <lane> <question> --run <id> 在同一会话里问进度(真回合)',
|
|
20
|
+
' tell <lane> <message> --run <id> 插话纠偏,约束后续任务',
|
|
21
|
+
' close <lane> --run <id> 关闭 lane:导出累计 diff + 归档会话',
|
|
22
|
+
' watch [<run-id>] [--json] 无 id 打开监管工作台;有 id 观察那个 Run 的事件流',
|
|
23
|
+
' lane <run-id> --lane <id> 在 lane 现场跑一个真 mocode(supervisor 可派活,人也能直接打字)',
|
|
24
|
+
' resume <run-id> 继续一个 idle / awaiting_user 的 Run',
|
|
25
|
+
' integrate <run-id> [--lane <id>] [--apply] 把已 close 的 lane patch 合回工作区(默认 dry-run)',
|
|
26
|
+
' budget: --max-tokens <n> / --max-minutes <n> 整趟 Run 限额,超限进 awaiting_user',
|
|
27
|
+
' review <run-id> [--dry-run] 跑一次收工判定,看还差什么',
|
|
28
|
+
' list | status <run-id> | cancel <run-id>',
|
|
29
|
+
].join('\n');
|
|
30
|
+
function defaultDeps() {
|
|
31
|
+
return {
|
|
32
|
+
out: (text) => void process.stdout.write(text),
|
|
33
|
+
err: (text) => void process.stderr.write(text),
|
|
34
|
+
worker: () => new HostWorkerExecutor(),
|
|
35
|
+
async modelConfigured() {
|
|
36
|
+
const { isModelConfigured } = await import('../config/index.js');
|
|
37
|
+
return isModelConfigured();
|
|
38
|
+
},
|
|
39
|
+
installSigint(handler) {
|
|
40
|
+
// src/index.ts 的全局 SIGINT 会直接 exit(130),来不及落取消标记、收 Worker、清现场。
|
|
41
|
+
const globalListeners = process.listeners('SIGINT');
|
|
42
|
+
process.removeAllListeners('SIGINT');
|
|
43
|
+
process.once('SIGINT', handler);
|
|
44
|
+
return () => {
|
|
45
|
+
process.removeListener('SIGINT', handler);
|
|
46
|
+
for (const listener of globalListeners)
|
|
47
|
+
process.on('SIGINT', listener);
|
|
48
|
+
};
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
const VALUE_FLAGS = new Set([
|
|
53
|
+
'--sandbox-root',
|
|
54
|
+
'--file',
|
|
55
|
+
'--run',
|
|
56
|
+
'--lane',
|
|
57
|
+
'--task',
|
|
58
|
+
// lane 窗口的「本次拉起」标记。执行器开窗时会带上它,不注册就会被参数解析拒成
|
|
59
|
+
// Unknown flag,窗口一闪就退(表现为「没看到弹窗」,实际是立刻崩了)。
|
|
60
|
+
'--launch',
|
|
61
|
+
'--scan-roots',
|
|
62
|
+
'--concurrency',
|
|
63
|
+
'--max-tokens',
|
|
64
|
+
'--max-minutes',
|
|
65
|
+
]);
|
|
66
|
+
const BOOLEAN_FLAGS = new Set([
|
|
67
|
+
'--json',
|
|
68
|
+
'--allow-inplace',
|
|
69
|
+
'--auto-close',
|
|
70
|
+
'--reuse',
|
|
71
|
+
'--dry-run',
|
|
72
|
+
'--no-review',
|
|
73
|
+
'--apply',
|
|
74
|
+
'--all',
|
|
75
|
+
'--no-terminal',
|
|
76
|
+
]);
|
|
77
|
+
function parseArgs(args) {
|
|
78
|
+
const positionals = [];
|
|
79
|
+
const flags = new Map();
|
|
80
|
+
for (let index = 0; index < args.length; index++) {
|
|
81
|
+
const arg = args[index];
|
|
82
|
+
if (!arg.startsWith('--')) {
|
|
83
|
+
positionals.push(arg);
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (BOOLEAN_FLAGS.has(arg)) {
|
|
87
|
+
flags.set(arg, true);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (VALUE_FLAGS.has(arg)) {
|
|
91
|
+
const value = args[++index];
|
|
92
|
+
if (!value || value.startsWith('--'))
|
|
93
|
+
throw new Error(`${arg} requires a value.`);
|
|
94
|
+
flags.set(arg, value);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
throw new Error(`Unknown flag: ${arg}`);
|
|
98
|
+
}
|
|
99
|
+
return { positionals, flags };
|
|
100
|
+
}
|
|
101
|
+
function stringFlag(parsed, name) {
|
|
102
|
+
const value = parsed.flags.get(name);
|
|
103
|
+
return typeof value === 'string' ? value : undefined;
|
|
104
|
+
}
|
|
105
|
+
function boolFlag(parsed, name) {
|
|
106
|
+
return parsed.flags.get(name) === true;
|
|
107
|
+
}
|
|
108
|
+
function requireString(parsed, name, label) {
|
|
109
|
+
const value = stringFlag(parsed, name);
|
|
110
|
+
if (!value)
|
|
111
|
+
throw new Error(`${label} requires ${name}.`);
|
|
112
|
+
return value;
|
|
113
|
+
}
|
|
114
|
+
/** `--concurrency N` / `--max-tokens` / `--max-minutes` → policy 局部;非法值在 state 归一化处也会被拦一次。 */
|
|
115
|
+
function policyFlags(parsed) {
|
|
116
|
+
const policy = {};
|
|
117
|
+
const raw = stringFlag(parsed, '--concurrency');
|
|
118
|
+
if (raw !== undefined) {
|
|
119
|
+
const value = Number(raw);
|
|
120
|
+
if (!Number.isInteger(value) || value < 1)
|
|
121
|
+
throw new Error('--concurrency must be a positive integer.');
|
|
122
|
+
policy.maxConcurrentWorkers = value;
|
|
123
|
+
policy.maxConcurrentPerWorkspace = value;
|
|
124
|
+
}
|
|
125
|
+
if (boolFlag(parsed, '--no-review'))
|
|
126
|
+
policy.reviewOnIdle = false;
|
|
127
|
+
const budget = {};
|
|
128
|
+
const tokens = stringFlag(parsed, '--max-tokens');
|
|
129
|
+
if (tokens !== undefined) {
|
|
130
|
+
const value = Number(tokens);
|
|
131
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
132
|
+
throw new Error('--max-tokens must be a positive number.');
|
|
133
|
+
budget.maxTokensPerRun = Math.floor(value);
|
|
134
|
+
}
|
|
135
|
+
const minutes = stringFlag(parsed, '--max-minutes');
|
|
136
|
+
if (minutes !== undefined) {
|
|
137
|
+
const value = Number(minutes);
|
|
138
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
139
|
+
throw new Error('--max-minutes must be a positive number.');
|
|
140
|
+
budget.maxWallClockMs = Math.floor(value * 60_000);
|
|
141
|
+
}
|
|
142
|
+
if (Object.keys(budget).length > 0)
|
|
143
|
+
policy.budget = budget;
|
|
144
|
+
return Object.keys(policy).length > 0 ? policy : undefined;
|
|
145
|
+
}
|
|
146
|
+
/** `budget: tokens 12k/50k, 3.2/30 min`;没配就是 `unlimited`。 */
|
|
147
|
+
function formatBudget(run) {
|
|
148
|
+
const budget = run.policy?.budget;
|
|
149
|
+
if (!budget)
|
|
150
|
+
return 'budget unlimited';
|
|
151
|
+
const parts = [];
|
|
152
|
+
if (budget.maxTokensPerRun !== undefined) {
|
|
153
|
+
parts.push(`tokens ${run.usage?.tokens ?? 0}/${budget.maxTokensPerRun}`);
|
|
154
|
+
}
|
|
155
|
+
if (budget.maxWallClockMs !== undefined) {
|
|
156
|
+
const usedMin = ((run.usage?.wallClockMs ?? Date.now() - Date.parse(run.createdAt)) / 60_000).toFixed(1);
|
|
157
|
+
parts.push(`${usedMin}/${(budget.maxWallClockMs / 60_000).toFixed(0)} min`);
|
|
158
|
+
}
|
|
159
|
+
return `budget ${parts.join(', ')}`;
|
|
160
|
+
}
|
|
161
|
+
/** 剩余位置参数拼成一句话(objective / question)。 */
|
|
162
|
+
function message(parsed, from = 0) {
|
|
163
|
+
const text = parsed.positionals.slice(from).join(' ').trim();
|
|
164
|
+
if (!text)
|
|
165
|
+
throw new Error('A non-empty message is required.');
|
|
166
|
+
return text;
|
|
167
|
+
}
|
|
168
|
+
// ── 工作区与 lane 档位(判定逻辑在 ./lanes.ts,与 Supervisor 工具共用一份)──
|
|
169
|
+
function warnDirtyWorkspaces(definition, deps) {
|
|
170
|
+
for (const lane of definition.lanes ?? []) {
|
|
171
|
+
if (lane.mode !== 'worktree' || !lane.workspaceRoot)
|
|
172
|
+
continue;
|
|
173
|
+
if (!gitRepositoryDirty(lane.workspaceRoot))
|
|
174
|
+
continue;
|
|
175
|
+
deps.err(`mocode supervise: warning — ${lane.workspaceRoot} has uncommitted changes; worktree workers run against HEAD and will not see them.\n`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
// ── 输出 ─────────────────────────────────────────────────────────────────────
|
|
179
|
+
function taskGlyph(status) {
|
|
180
|
+
if (status === 'completed')
|
|
181
|
+
return '✓';
|
|
182
|
+
if (status === 'running' || status === 'dispatching')
|
|
183
|
+
return '▶';
|
|
184
|
+
if (status === 'failed' || status === 'interrupted')
|
|
185
|
+
return '!';
|
|
186
|
+
if (status === 'cancelled')
|
|
187
|
+
return '×';
|
|
188
|
+
return '○';
|
|
189
|
+
}
|
|
190
|
+
export function formatOrchestration(run) {
|
|
191
|
+
const tasks = Object.values(run.tasks);
|
|
192
|
+
const completed = tasks.filter((task) => task.status === 'completed').length;
|
|
193
|
+
const policy = run.policy;
|
|
194
|
+
const lines = [
|
|
195
|
+
`${run.id} ${run.status} ${completed}/${tasks.length}`,
|
|
196
|
+
`Objective: ${run.objective}`,
|
|
197
|
+
`Policy: concurrency ${policy?.maxConcurrentWorkers ?? 6}, per-workspace ${policy?.maxConcurrentPerWorkspace ?? 6}, review ${policy?.reviewOnIdle === false ? 'off' : 'on'}, ${formatBudget(run)}`,
|
|
198
|
+
];
|
|
199
|
+
if (run.awaitingReason)
|
|
200
|
+
lines.push(`Waiting for you: ${run.awaitingReason}`);
|
|
201
|
+
for (const lane of Object.values(run.lanes ?? {})) {
|
|
202
|
+
lines.push(`lane ${lane.id} ${lane.mode ?? 'worktree'} ${lane.workspaceRoot}` +
|
|
203
|
+
`\n status: ${lane.closed ? `closed (${lane.closed.reason})` : lane.worktreePath ? 'open' : 'idle'}` +
|
|
204
|
+
`${lane.worktreePath ? `\n workspace: ${lane.worktreePath}` : ''}` +
|
|
205
|
+
`${lane.sessionId ? `\n session: ${lane.sessionId}` : ''}` +
|
|
206
|
+
`${lane.closed?.patchPath ? `\n lane diff: ${lane.closed.patchPath}` : ''}` +
|
|
207
|
+
`${lane.closed?.sessionArchivePath ? `\n session archive: ${lane.closed.sessionArchivePath}` : ''}` +
|
|
208
|
+
`${lane.closed?.kept ? '\n kept: execution site preserved' : ''}` +
|
|
209
|
+
`${lane.closed?.error ? `\n error: ${lane.closed.error}` : ''}`);
|
|
210
|
+
}
|
|
211
|
+
for (const task of tasks) {
|
|
212
|
+
lines.push(`${taskGlyph(task.status)} ${task.id} ${task.status} ${task.title}${task.lane ? ` [lane ${task.lane}]` : ''}` +
|
|
213
|
+
`${task.sessionId ? `\n session: ${task.sessionId}` : ''}` +
|
|
214
|
+
`${task.workspacePath ? `\n workspace: ${task.workspacePath}` : ''}` +
|
|
215
|
+
`${task.patchPath ? `\n patch: ${task.patchPath}` : ''}` +
|
|
216
|
+
`${task.sessionArchivePath ? `\n session archive: ${task.sessionArchivePath}` : ''}` +
|
|
217
|
+
`${task.lastEvent ? `\n event: ${task.lastEvent}` : ''}` +
|
|
218
|
+
`${task.error ? `\n error: ${task.error}` : ''}`);
|
|
219
|
+
}
|
|
220
|
+
const review = run.lastReview;
|
|
221
|
+
if (review) {
|
|
222
|
+
lines.push(`review: ${review.verdict}${review.error ? ` (error: ${review.error})` : ''}` +
|
|
223
|
+
`${review.rationale ? `\n ${review.rationale}` : ''}` +
|
|
224
|
+
`${review.remaining.length > 0 ? `\n remaining: ${review.remaining.join(' | ')}` : ''}`);
|
|
225
|
+
}
|
|
226
|
+
return `${lines.join('\n')}\n`;
|
|
227
|
+
}
|
|
228
|
+
function formatReview(review) {
|
|
229
|
+
const lines = [`review: ${review.verdict} ${review.createdAt}`, `${review.rationale || '(no rationale)'}`];
|
|
230
|
+
if (review.remaining.length > 0)
|
|
231
|
+
lines.push(`remaining:\n${review.remaining.map((item) => ` - ${item}`).join('\n')}`);
|
|
232
|
+
if (review.error)
|
|
233
|
+
lines.push(`error: ${review.error}`);
|
|
234
|
+
return `${lines.join('\n')}\n`;
|
|
235
|
+
}
|
|
236
|
+
async function execute(store, deps, options = {}) {
|
|
237
|
+
const lease = store.acquireControllerLease();
|
|
238
|
+
const worker = deps.worker();
|
|
239
|
+
const scheduler = new OrchestrationScheduler(store, worker, {
|
|
240
|
+
onEvent(event, run) {
|
|
241
|
+
if (options.json) {
|
|
242
|
+
deps.out(`${JSON.stringify({ type: event.type, data: event.data, status: run.status, task: event.data })}\n`);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
if (event.type === 'task.progress')
|
|
246
|
+
deps.out(`[${event.data.taskId}] ${event.data.message}\n`);
|
|
247
|
+
else if (event.type !== 'run.created')
|
|
248
|
+
deps.out(`[supervise] ${event.type} · ${run.status}\n`);
|
|
249
|
+
},
|
|
250
|
+
}, { waitForMore: options.waitForMore });
|
|
251
|
+
const removeSigint = deps.installSigint?.(() => {
|
|
252
|
+
deps.out('\n[supervise] cancellation requested; stopping workers…\n');
|
|
253
|
+
store.requestCancellation();
|
|
254
|
+
});
|
|
255
|
+
try {
|
|
256
|
+
if (options.resumeAwaiting && store.current.status === 'awaiting_user') {
|
|
257
|
+
scheduler.resume('Operator resumed the run.');
|
|
258
|
+
}
|
|
259
|
+
const final = await scheduler.run();
|
|
260
|
+
if (!options.json)
|
|
261
|
+
deps.out(formatOrchestration(final));
|
|
262
|
+
// awaiting_user 不是错误:Run 情愿停下等人,退出码 0 让脚本能区分「正常等人」与「跑挂」
|
|
263
|
+
return final.status === 'completed' || final.status === 'idle' || final.status === 'awaiting_user'
|
|
264
|
+
? 0
|
|
265
|
+
: final.status === 'cancelled'
|
|
266
|
+
? 130
|
|
267
|
+
: 1;
|
|
268
|
+
}
|
|
269
|
+
finally {
|
|
270
|
+
removeSigint?.();
|
|
271
|
+
lease.release();
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/** 找该工作区最近一个还能接活的 Run(running / idle / awaiting_user)。 */
|
|
275
|
+
function latestLiveRun(root) {
|
|
276
|
+
return listOrchestrations(root).find((run) => isRunLive(run));
|
|
277
|
+
}
|
|
278
|
+
function nextTaskId(run, prefix) {
|
|
279
|
+
let index = 1;
|
|
280
|
+
while (run.tasks[`${prefix}-${index}`])
|
|
281
|
+
index++;
|
|
282
|
+
return `${prefix}-${index}`;
|
|
283
|
+
}
|
|
284
|
+
/** ask / tell 都是往同一 lane 的同一会话发一个回合;区别只在契约(只读 vs 可写)与意图。 */
|
|
285
|
+
async function askOrTell(parsed, deps, kind) {
|
|
286
|
+
const runId = requireString(parsed, '--run', kind);
|
|
287
|
+
const laneId = parsed.positionals[0];
|
|
288
|
+
if (!laneId)
|
|
289
|
+
throw new Error(`${kind} requires a lane id.`);
|
|
290
|
+
const text = message(parsed, 1);
|
|
291
|
+
const root = path.resolve(stringFlag(parsed, '--sandbox-root') ?? process.cwd());
|
|
292
|
+
if (!(await deps.modelConfigured()))
|
|
293
|
+
throw new Error('model not configured; run `mocode config` first.');
|
|
294
|
+
const store = OrchestrationStore.load(root, runId);
|
|
295
|
+
const run = store.current;
|
|
296
|
+
const lane = run.lanes[laneId];
|
|
297
|
+
if (!lane)
|
|
298
|
+
throw new Error(`run ${runId} has no lane ${laneId}.`);
|
|
299
|
+
if (lane.closed)
|
|
300
|
+
throw new Error(`lane ${laneId} is closed; dispatch --reuse first.`);
|
|
301
|
+
if (run.status === 'running')
|
|
302
|
+
throw new Error(`run ${runId} is running; wait for it to idle before asking.`);
|
|
303
|
+
const task = kind === 'ask'
|
|
304
|
+
? {
|
|
305
|
+
id: nextTaskId(run, 'ask'),
|
|
306
|
+
title: text.slice(0, 80),
|
|
307
|
+
objective: `${text}\n\nThis is a status question from the operator, delivered into this lane's existing session. ` +
|
|
308
|
+
'Answer from the work you already did in this session (files you read, commands you ran). ' +
|
|
309
|
+
'Do not modify any file; report what is done, what is verified, and what remains.',
|
|
310
|
+
lane: laneId,
|
|
311
|
+
changePolicy: 'read_only',
|
|
312
|
+
}
|
|
313
|
+
: {
|
|
314
|
+
id: nextTaskId(run, 'steer'),
|
|
315
|
+
title: text.slice(0, 80),
|
|
316
|
+
objective: `${text}\n\nThis is an operator steering message. Treat it as a binding constraint for this lane ` +
|
|
317
|
+
'and act accordingly in the same session. Do not redo work that is already on disk.',
|
|
318
|
+
lane: laneId,
|
|
319
|
+
changePolicy: 'isolated_write',
|
|
320
|
+
};
|
|
321
|
+
const lease = store.acquireControllerLease();
|
|
322
|
+
const scheduler = new OrchestrationScheduler(store, deps.worker(), {
|
|
323
|
+
onEvent(event, current) {
|
|
324
|
+
if (event.type === 'task.progress')
|
|
325
|
+
deps.out(`[${event.data.taskId}] ${event.data.message}\n`);
|
|
326
|
+
else if (event.type !== 'run.created')
|
|
327
|
+
deps.out(`[supervise] ${event.type} · ${current.status}\n`);
|
|
328
|
+
},
|
|
329
|
+
});
|
|
330
|
+
try {
|
|
331
|
+
scheduler.appendTask(task);
|
|
332
|
+
const final = await scheduler.run();
|
|
333
|
+
deps.out(formatOrchestration(final));
|
|
334
|
+
return final.status === 'failed' ? 1 : 0;
|
|
335
|
+
}
|
|
336
|
+
finally {
|
|
337
|
+
lease.release();
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/** 在一个已有 Run 上追加任务并跑起来(dispatch --run 的共用路径)。 */
|
|
341
|
+
async function dispatchToRun(store, deps, task, options) {
|
|
342
|
+
const lease = store.acquireControllerLease();
|
|
343
|
+
try {
|
|
344
|
+
const scheduler = new OrchestrationScheduler(store, deps.worker(), {
|
|
345
|
+
onEvent(event, current) {
|
|
346
|
+
if (event.type === 'task.progress')
|
|
347
|
+
deps.out(`[${event.data.taskId}] ${event.data.message}\n`);
|
|
348
|
+
else if (event.type !== 'run.created')
|
|
349
|
+
deps.out(`[supervise] ${event.type} · ${current.status}\n`);
|
|
350
|
+
},
|
|
351
|
+
});
|
|
352
|
+
scheduler.appendTask(task, { reopenLane: options.reopenLane });
|
|
353
|
+
const final = await scheduler.run();
|
|
354
|
+
deps.out(formatOrchestration(final));
|
|
355
|
+
return final.status === 'failed' ? 1 : 0;
|
|
356
|
+
}
|
|
357
|
+
finally {
|
|
358
|
+
lease.release();
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
export async function runSuperviseCli(rawArgs, deps = defaultDeps()) {
|
|
362
|
+
let parsed;
|
|
363
|
+
try {
|
|
364
|
+
parsed = parseArgs(rawArgs);
|
|
365
|
+
}
|
|
366
|
+
catch (error) {
|
|
367
|
+
deps.err(`mocode supervise: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
368
|
+
return 2;
|
|
369
|
+
}
|
|
370
|
+
const root = path.resolve(stringFlag(parsed, '--sandbox-root') ?? process.cwd());
|
|
371
|
+
const command = (parsed.positionals.shift() ?? '').toLowerCase();
|
|
372
|
+
try {
|
|
373
|
+
// 无子命令 = Supervisor 对话(本机所有工作区的编排入口)。非 TTY 由 repl 自己拒绝并给 CLI 提示。
|
|
374
|
+
if (command === '') {
|
|
375
|
+
const scanRoots = stringFlag(parsed, '--scan-roots');
|
|
376
|
+
if (!(await deps.modelConfigured()))
|
|
377
|
+
throw new Error('model not configured; run `mocode config` first.');
|
|
378
|
+
const { runSupervisorChat } = await import('./repl.js');
|
|
379
|
+
return runSupervisorChat({
|
|
380
|
+
root,
|
|
381
|
+
scanRoots: scanRoots ? [path.resolve(scanRoots)] : [],
|
|
382
|
+
// **不要**把 deps.worker 传进来。deps.worker 的默认值就是 headless 的
|
|
383
|
+
// `HostWorkerExecutor`,而 SupervisorRuntime 的规则是「显式注入优先于 watchTerminals」,
|
|
384
|
+
// 传进来就等于把可视化 lane 永久关掉了——派活永远不会弹 mocode 窗口(真踩过)。
|
|
385
|
+
// 让 SupervisorRuntime 自己按 watchTerminals 选执行器:默认可视化 lane,
|
|
386
|
+
// --no-terminal / CI 走 headless。
|
|
387
|
+
...(boolFlag(parsed, '--no-terminal') ? { watchTerminals: false } : {}),
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
if (command === 'workspaces') {
|
|
391
|
+
const scanRoots = stringFlag(parsed, '--scan-roots');
|
|
392
|
+
const list = listWorkspaces({
|
|
393
|
+
roots: [root],
|
|
394
|
+
scanRoots: scanRoots ? [path.resolve(scanRoots)] : [],
|
|
395
|
+
});
|
|
396
|
+
deps.out(boolFlag(parsed, '--json') ? `${JSON.stringify(list, null, 2)}\n` : formatWorkspaces(list));
|
|
397
|
+
return 0;
|
|
398
|
+
}
|
|
399
|
+
if (command === 'list') {
|
|
400
|
+
const runs = listOrchestrations(root);
|
|
401
|
+
if (runs.length === 0)
|
|
402
|
+
deps.out('No orchestration runs.\n');
|
|
403
|
+
else
|
|
404
|
+
for (const run of runs)
|
|
405
|
+
deps.out(`${run.id} ${run.status} ${run.objective}\n`);
|
|
406
|
+
return 0;
|
|
407
|
+
}
|
|
408
|
+
if (command === 'status') {
|
|
409
|
+
const id = parsed.positionals[0];
|
|
410
|
+
if (!id)
|
|
411
|
+
throw new Error('status requires a run id.');
|
|
412
|
+
deps.out(formatOrchestration(OrchestrationStore.load(root, id).current));
|
|
413
|
+
return 0;
|
|
414
|
+
}
|
|
415
|
+
if (command === 'cancel') {
|
|
416
|
+
const id = parsed.positionals[0];
|
|
417
|
+
if (!id)
|
|
418
|
+
throw new Error('cancel requires a run id.');
|
|
419
|
+
const store = OrchestrationStore.load(root, id);
|
|
420
|
+
if (!isRunLive(store.current))
|
|
421
|
+
throw new Error(`run ${id} is already ${store.current.status}.`);
|
|
422
|
+
store.requestCancellation();
|
|
423
|
+
deps.out(`Cancellation requested for ${id}.\n`);
|
|
424
|
+
return 0;
|
|
425
|
+
}
|
|
426
|
+
if (command === 'close') {
|
|
427
|
+
const runId = requireString(parsed, '--run', 'close');
|
|
428
|
+
const laneId = parsed.positionals[0];
|
|
429
|
+
if (!laneId)
|
|
430
|
+
throw new Error('close requires a lane id.');
|
|
431
|
+
const store = OrchestrationStore.load(root, runId);
|
|
432
|
+
if (!store.current.lanes[laneId])
|
|
433
|
+
throw new Error(`run ${runId} has no lane ${laneId}.`);
|
|
434
|
+
const lease = store.acquireControllerLease();
|
|
435
|
+
try {
|
|
436
|
+
const scheduler = new OrchestrationScheduler(store, deps.worker(), {
|
|
437
|
+
onEvent(event, current) {
|
|
438
|
+
if (event.type !== 'task.progress' && event.type !== 'run.created') {
|
|
439
|
+
deps.out(`[supervise] ${event.type} · ${current.status}\n`);
|
|
440
|
+
}
|
|
441
|
+
},
|
|
442
|
+
});
|
|
443
|
+
const final = await scheduler.closeLaneById(laneId, 'Closed by the operator.');
|
|
444
|
+
deps.out(formatOrchestration(final));
|
|
445
|
+
return 0;
|
|
446
|
+
}
|
|
447
|
+
finally {
|
|
448
|
+
lease.release();
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
if (command === 'integrate') {
|
|
452
|
+
const id = parsed.positionals[0] ?? stringFlag(parsed, '--run');
|
|
453
|
+
if (!id)
|
|
454
|
+
throw new Error('integrate requires a run id.');
|
|
455
|
+
const store = OrchestrationStore.load(root, id);
|
|
456
|
+
const laneFlag = stringFlag(parsed, '--lane');
|
|
457
|
+
const result = integrateRun(store.current, {
|
|
458
|
+
lanes: laneFlag ? [laneFlag] : undefined,
|
|
459
|
+
apply: boolFlag(parsed, '--apply'),
|
|
460
|
+
});
|
|
461
|
+
// 只落审计文件,不动事件账本:integrate 通常在 Run 终态后跑,而终态账本是冻结的。
|
|
462
|
+
appendIntegrationLog(store.artifactPath('integration.jsonl'), result);
|
|
463
|
+
deps.out(formatIntegration(result));
|
|
464
|
+
return result.results.some((item) => item.status === 'failed') ? 1 : 0;
|
|
465
|
+
}
|
|
466
|
+
if (command === 'ask' || command === 'tell')
|
|
467
|
+
return askOrTell(parsed, deps, command);
|
|
468
|
+
if (command === 'dispatch') {
|
|
469
|
+
const workspaceArg = parsed.positionals[0];
|
|
470
|
+
if (!workspaceArg)
|
|
471
|
+
throw new Error('dispatch requires a workspace path.');
|
|
472
|
+
const workspace = path.resolve(root, workspaceArg);
|
|
473
|
+
parsed.positionals.shift();
|
|
474
|
+
const laneId = requireString(parsed, '--lane', 'dispatch');
|
|
475
|
+
const objective = message(parsed);
|
|
476
|
+
if (!(await deps.modelConfigured()))
|
|
477
|
+
throw new Error('model not configured; run `mocode config` first.');
|
|
478
|
+
const existingId = stringFlag(parsed, '--run');
|
|
479
|
+
if (existingId) {
|
|
480
|
+
const store = OrchestrationStore.load(workspace, existingId);
|
|
481
|
+
const task = {
|
|
482
|
+
id: nextTaskId(store.current, 'task'),
|
|
483
|
+
title: objective.slice(0, 80),
|
|
484
|
+
objective,
|
|
485
|
+
lane: laneId,
|
|
486
|
+
};
|
|
487
|
+
return dispatchToRun(store, deps, task, { reopenLane: boolFlag(parsed, '--reuse') });
|
|
488
|
+
}
|
|
489
|
+
const definition = prepareDefinition({
|
|
490
|
+
objective,
|
|
491
|
+
autoClose: boolFlag(parsed, '--auto-close'),
|
|
492
|
+
lanes: [{ id: laneId, workspaceRoot: workspace }],
|
|
493
|
+
tasks: [{ id: 'task-1', title: objective.slice(0, 80), objective, lane: laneId }],
|
|
494
|
+
policy: policyFlags(parsed),
|
|
495
|
+
}, workspace, boolFlag(parsed, '--allow-inplace'));
|
|
496
|
+
const live = latestLiveRun(workspace);
|
|
497
|
+
if (live) {
|
|
498
|
+
deps.err(`mocode supervise: note — run ${live.id} is still open; pass '--run ${live.id}' to add this task to it.\n`);
|
|
499
|
+
}
|
|
500
|
+
warnDirtyWorkspaces(definition, deps);
|
|
501
|
+
const store = OrchestrationStore.create(workspace, definition);
|
|
502
|
+
deps.out(`Orchestration started: ${store.current.id}\n`);
|
|
503
|
+
return execute(store, deps);
|
|
504
|
+
}
|
|
505
|
+
if (command === 'start') {
|
|
506
|
+
if (!(await deps.modelConfigured()))
|
|
507
|
+
throw new Error('model not configured; run `mocode config` first.');
|
|
508
|
+
const loaded = loadDefinition(parsed, root);
|
|
509
|
+
const definition = prepareDefinition({ ...loaded, policy: { ...loaded.policy, ...policyFlags(parsed) } }, root, boolFlag(parsed, '--allow-inplace'));
|
|
510
|
+
warnDirtyWorkspaces(definition, deps);
|
|
511
|
+
const store = OrchestrationStore.create(root, definition);
|
|
512
|
+
deps.out(`Orchestration started: ${store.current.id}\n`);
|
|
513
|
+
return execute(store, deps);
|
|
514
|
+
}
|
|
515
|
+
if (command === 'review') {
|
|
516
|
+
const id = parsed.positionals[0] ?? stringFlag(parsed, '--run');
|
|
517
|
+
if (!id)
|
|
518
|
+
throw new Error('review requires a run id.');
|
|
519
|
+
const store = OrchestrationStore.load(root, id);
|
|
520
|
+
const dryRun = boolFlag(parsed, '--dry-run');
|
|
521
|
+
if (!dryRun && !(await deps.modelConfigured())) {
|
|
522
|
+
throw new Error('model not configured; run `mocode config` first, or pass --dry-run.');
|
|
523
|
+
}
|
|
524
|
+
const run = store.current;
|
|
525
|
+
const review = await reviewRun(run, { dryRun });
|
|
526
|
+
if (dryRun) {
|
|
527
|
+
deps.out(review.rationale);
|
|
528
|
+
return 0;
|
|
529
|
+
}
|
|
530
|
+
// 判定只是建议:只有 Run 未终态时才入账(终态账本冻结,reducer 会拒绝追加)。
|
|
531
|
+
if (run.status !== 'completed' && run.status !== 'failed' && run.status !== 'cancelled') {
|
|
532
|
+
const lease = store.acquireControllerLease();
|
|
533
|
+
try {
|
|
534
|
+
const scheduler = new OrchestrationScheduler(store, deps.worker(), {});
|
|
535
|
+
scheduler.recordReview(review);
|
|
536
|
+
}
|
|
537
|
+
finally {
|
|
538
|
+
lease.release();
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
deps.out(formatReview(review));
|
|
542
|
+
return review.verdict === 'unknown' ? 1 : 0;
|
|
543
|
+
}
|
|
544
|
+
if (command === 'lane') {
|
|
545
|
+
// 在 lane 的执行现场跑一个**真的 mocode REPL**:同款 TUI、同款输入框。
|
|
546
|
+
// 人可以直接在这个窗口里说话,supervisor 也能经 lane.commands 派活——两个输入源,一个输入框。
|
|
547
|
+
const runId = parsed.positionals[0] ?? stringFlag(parsed, '--run');
|
|
548
|
+
if (!runId)
|
|
549
|
+
throw new Error('lane requires a run id.');
|
|
550
|
+
const laneId = requireString(parsed, '--lane', 'lane');
|
|
551
|
+
const store = OrchestrationStore.load(root, runId);
|
|
552
|
+
const run = store.current;
|
|
553
|
+
if (!run.lanes[laneId])
|
|
554
|
+
throw new Error(`run ${run.id} has no lane ${laneId}.`);
|
|
555
|
+
const { runLaneRepl } = await import('./lane-repl.js');
|
|
556
|
+
const launch = stringFlag(parsed, '--launch');
|
|
557
|
+
return runLaneRepl({
|
|
558
|
+
workspaceRoot: run.workspaceRoot,
|
|
559
|
+
runId: run.id,
|
|
560
|
+
laneId,
|
|
561
|
+
...(launch ? { launch } : {}),
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
if (command === 'watch' && !parsed.positionals[0] && !stringFlag(parsed, '--run')) {
|
|
565
|
+
// 无 run id = 监管工作台:看这台机器上所有还在动的工作区 / lane。
|
|
566
|
+
const scanRoots = stringFlag(parsed, '--scan-roots');
|
|
567
|
+
const workspaces = listWorkspaces({
|
|
568
|
+
roots: [root],
|
|
569
|
+
scanRoots: scanRoots ? [path.resolve(scanRoots)] : [],
|
|
570
|
+
});
|
|
571
|
+
const json = boolFlag(parsed, '--json');
|
|
572
|
+
const includeTerminal = boolFlag(parsed, '--all');
|
|
573
|
+
if (json || !process.stdout.isTTY) {
|
|
574
|
+
const board = collectBoard({ workspaces, includeTerminal });
|
|
575
|
+
deps.out(formatBoardSnapshot(board, { json }));
|
|
576
|
+
return 0;
|
|
577
|
+
}
|
|
578
|
+
const { runBoardPanel } = await import('./watch-panel.js');
|
|
579
|
+
return runBoardPanel({ workspaces, collect: (known) => collectBoard({ workspaces: known, includeTerminal }) });
|
|
580
|
+
}
|
|
581
|
+
if (command === 'resume' || command === 'watch') {
|
|
582
|
+
const id = parsed.positionals[0] ?? stringFlag(parsed, '--run');
|
|
583
|
+
if (!id)
|
|
584
|
+
throw new Error(`${command} requires a run id.`);
|
|
585
|
+
const store = OrchestrationStore.load(root, id);
|
|
586
|
+
if (store.current.status === 'completed' || store.current.status === 'cancelled') {
|
|
587
|
+
throw new Error(`run ${id} is already ${store.current.status}.`);
|
|
588
|
+
}
|
|
589
|
+
// watch 是只读观察:不替人做「继续」的决定,先把原因摆出来。
|
|
590
|
+
if (command === 'watch' && store.current.status === 'awaiting_user') {
|
|
591
|
+
deps.out(`${formatOrchestration(store.current)}\n`);
|
|
592
|
+
deps.err(`mocode supervise: run ${id} is waiting for you — ${store.current.awaitingReason ?? 'needs a decision'}\n` +
|
|
593
|
+
` continue: mocode supervise resume ${id}\n` +
|
|
594
|
+
` add work: mocode supervise dispatch <workspace> --lane <id> --run ${id} <objective>\n`);
|
|
595
|
+
return 0;
|
|
596
|
+
}
|
|
597
|
+
if (!(await deps.modelConfigured()))
|
|
598
|
+
throw new Error('model not configured; run `mocode config` first.');
|
|
599
|
+
return execute(store, deps, {
|
|
600
|
+
waitForMore: command === 'watch',
|
|
601
|
+
json: boolFlag(parsed, '--json'),
|
|
602
|
+
resumeAwaiting: command === 'resume',
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
deps.err(`${SUPERVISE_USAGE}\n`);
|
|
606
|
+
return 2;
|
|
607
|
+
}
|
|
608
|
+
catch (error) {
|
|
609
|
+
deps.err(`mocode supervise: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
610
|
+
return 1;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
// ── dag.json ─────────────────────────────────────────────────────────────────
|
|
614
|
+
function loadDefinition(parsed, root) {
|
|
615
|
+
const file = stringFlag(parsed, '--file');
|
|
616
|
+
if (file) {
|
|
617
|
+
const definition = JSON.parse(fs.readFileSync(path.resolve(root, file), 'utf8'));
|
|
618
|
+
return { ...definition, autoClose: definition.autoClose === true || boolFlag(parsed, '--auto-close') };
|
|
619
|
+
}
|
|
620
|
+
const objective = parsed.positionals.join(' ').trim();
|
|
621
|
+
if (!objective)
|
|
622
|
+
throw new Error('start requires an objective or --file <dag.json>.');
|
|
623
|
+
return {
|
|
624
|
+
objective,
|
|
625
|
+
autoClose: boolFlag(parsed, '--auto-close'),
|
|
626
|
+
tasks: [{ id: 'task-1', title: objective.slice(0, 80), objective, changePolicy: 'isolated_write' }],
|
|
627
|
+
};
|
|
628
|
+
}
|