mocode-ai 1.9.6 → 1.9.8

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 (44) 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/vision-window.js +24 -9
  5. package/dist/host/protocol.js +4 -1
  6. package/dist/host/stdio.js +45 -1
  7. package/dist/index.js +7 -0
  8. package/dist/jobs/dir-snapshot.js +332 -0
  9. package/dist/jobs/worktree.js +78 -20
  10. package/dist/orchestrator/board.js +332 -0
  11. package/dist/orchestrator/cli.js +628 -0
  12. package/dist/orchestrator/index.js +4 -0
  13. package/dist/orchestrator/integrate.js +344 -0
  14. package/dist/orchestrator/lane-channel.js +146 -0
  15. package/dist/orchestrator/lane-executor.js +439 -0
  16. package/dist/orchestrator/lane-repl.js +154 -0
  17. package/dist/orchestrator/lane-site.js +255 -0
  18. package/dist/orchestrator/lanes.js +72 -0
  19. package/dist/orchestrator/lease.js +132 -0
  20. package/dist/orchestrator/live-log.js +193 -0
  21. package/dist/orchestrator/repl.js +435 -0
  22. package/dist/orchestrator/review.js +135 -0
  23. package/dist/orchestrator/scheduler.js +673 -0
  24. package/dist/orchestrator/scope.js +88 -0
  25. package/dist/orchestrator/state.js +533 -0
  26. package/dist/orchestrator/store.js +221 -0
  27. package/dist/orchestrator/supervisor-prompt.js +54 -0
  28. package/dist/orchestrator/supervisor.js +798 -0
  29. package/dist/orchestrator/tail.js +508 -0
  30. package/dist/orchestrator/task-prompt.js +93 -0
  31. package/dist/orchestrator/terminal.js +269 -0
  32. package/dist/orchestrator/tools.js +392 -0
  33. package/dist/orchestrator/types.js +1 -0
  34. package/dist/orchestrator/watch-panel.js +154 -0
  35. package/dist/orchestrator/worker.js +475 -0
  36. package/dist/orchestrator/workspaces.js +191 -0
  37. package/dist/repl/commands/memory.js +1 -1
  38. package/dist/repl/runtime.js +16 -2
  39. package/dist/session/store.js +1 -1
  40. package/dist/tools/builtins/ask-human.js +27 -6
  41. package/dist/ui/handoff-block.js +91 -0
  42. package/dist/ui/layout-internal/statusbar.js +2 -1
  43. package/dist/ui/prompt-internal/editor.js +49 -0
  44. package/package.json +2 -2
@@ -0,0 +1,269 @@
1
+ // 独立终端窗口拉起器:把 worker 放到用户自己的终端里跑。
2
+ //
3
+ // 为什么需要它:supervisor 的对话 TUI 只有一块内容区,把 worker 的每一步都写进去会刷屏,
4
+ // 而人真正想看的是「那个 mocode 在某个工作区里到底在干什么」。于是 worker 开在自己的窗口里
5
+ // ——而且那个窗口跑的**就是 mocode 本体**(`supervise lane`,见 ./lane-repl.ts)。
6
+ //
7
+ // 关键约束:
8
+ // - **窗口是独立进程,与 supervisor 无父子关系**:supervisor 退出不应该杀掉它(人可以继续
9
+ // 在那个窗口里对话);supervisor 崩了也不影响它。
10
+ // - **失败要够诚实**:没有 wt.exe、没有 DISPLAY、SSH 里跑——开不出窗口本身不是致命错误,
11
+ // 但必须返回 `{opened:false}` 让调用方如实说「没开成」,绝不能假装开了让人干等。
12
+ // - **命令要能自举**:dev(tsx src/index.ts)与生产(dist/index.js)两种形态都要能起。
13
+ import { spawn, spawnSync } from 'node:child_process';
14
+ import os from 'node:os';
15
+ import { buildEntryArgs } from '../jobs/launch.js';
16
+ /** 把一组参数拼成一条可在 shell 里安全执行的行(osascript / `cmd start` 要字符串)。 */
17
+ export function quoteCommandLine(argv) {
18
+ return argv
19
+ .map((arg) => {
20
+ if (arg.length === 0)
21
+ return '""';
22
+ if (/^[A-Za-z0-9_@%+=:,./\\-]+$/.test(arg))
23
+ return arg;
24
+ return `"${arg.replace(/"/g, '\\"')}"`;
25
+ })
26
+ .join(' ');
27
+ }
28
+ /**
29
+ * 构造「重新跑一遍 mocode」的完整 argv(node 可执行 + 入口 + 内部参数)。
30
+ *
31
+ * **不要带 `process.execArgv`**:它会把调用方的运行参数原样传下去(`--test`、`--test-timeout`、
32
+ * 调试端口…),新窗口会变成「跑测试」而不是「跑 tail」。dev/prod 形态的差异已经由
33
+ * `buildEntryArgs` 处理(tsx loader vs 编译产物)。
34
+ */
35
+ export function selfCommand(args) {
36
+ return [process.execPath, ...buildEntryArgs([...args])];
37
+ }
38
+ /**
39
+ * Windows:优先 `wt.exe`(Windows Terminal 支持标题与独立标签),失败退回 `cmd start`。
40
+ *
41
+ * 为什么不用 `start /b`:那是同控制台后台进程,没有窗口,等于没开。
42
+ *
43
+ * **必须先探测 `wt.exe` 是否真的存在。** `spawn` 找不到程序时不会同步抛错,它只是稍后
44
+ * 发一个 `error` 事件——旧写法一律返回 `opened: true`,于是调用方以为窗口开了、干等 30s 的
45
+ * `ready`,最后报一句「did not become ready」,人看到的是「什么都没发生」(真踩过)。
46
+ */
47
+ let wtAvailable;
48
+ function probeWt() {
49
+ if (wtAvailable !== undefined)
50
+ return wtAvailable;
51
+ try {
52
+ const probe = spawnSync('wt.exe', ['--version'], { windowsHide: true, timeout: 8_000, stdio: 'ignore' });
53
+ wtAvailable = probe.error === undefined && probe.status === 0;
54
+ }
55
+ catch {
56
+ wtAvailable = false;
57
+ }
58
+ return wtAvailable;
59
+ }
60
+ /**
61
+ * 把标题匹配的窗口压到任务栏(不隐藏、不关闭,任务栏仍可见)。
62
+ *
63
+ * 为什么必须用 Win32 而没法在拉起时指定:实测 Windows Terminal 完全无视 `STARTUPINFO`
64
+ * 的窗口状态——`start /min`、`Start-Process -WindowStyle Minimized` 出来的窗口
65
+ * `IsIconic` 都是 False,而 `-WindowStyle Hidden` 会让窗口干脆不可见(连任务栏都没有)。
66
+ * 唯一有效的是拿到 HWND 后 `ShowWindow(SW_MINIMIZE)` + `SendMessage(WM_SYSCOMMAND,
67
+ * SC_MINIMIZE)`,两者缺一 WT 都不缩(`ShowWindowAsync` 同样无效)。
68
+ *
69
+ * 代价是拉起的那一下必然抢一次焦点(约百毫秒),这是 WT 的行为,绕不过去。
70
+ *
71
+ * 用 `-EncodedCommand` 传脚本(base64 UTF-16LE):省掉整条命令的引号地狱,
72
+ * 标题走环境变量传递,永远不会被当成 PowerShell 代码执行。
73
+ */
74
+ const MINIMIZE_SCRIPT = `$ErrorActionPreference = 'SilentlyContinue'
75
+ Add-Type @"
76
+ using System;
77
+ using System.Runtime.InteropServices;
78
+ using System.Text;
79
+ public class MocodeTaskbar {
80
+ public delegate bool EnumProc(IntPtr h, IntPtr p);
81
+ [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc cb, IntPtr p);
82
+ [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h);
83
+ [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int c);
84
+ [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr h, uint m, IntPtr w, IntPtr l);
85
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowTextW(IntPtr h, StringBuilder s, int n);
86
+ public static int Minimize(string title) {
87
+ int hits = 0;
88
+ EnumWindows((h, p) => {
89
+ if (IsIconic(h)) return true;
90
+ var t = new StringBuilder(512);
91
+ GetWindowTextW(h, t, 512);
92
+ if (t.ToString() != title) return true;
93
+ ShowWindow(h, 6);
94
+ SendMessage(h, 0x0112, new IntPtr(0xF020), IntPtr.Zero);
95
+ hits++;
96
+ return true;
97
+ }, IntPtr.Zero);
98
+ return hits;
99
+ }
100
+ }
101
+ "@
102
+ $title = $env:MOCODE_MINIMIZE_TITLE
103
+ $deadline = (Get-Date).AddMilliseconds([int]$env:MOCODE_MINIMIZE_TIMEOUT_MS)
104
+ while ((Get-Date) -lt $deadline) {
105
+ if ([MocodeTaskbar]::Minimize($title) -gt 0) { break }
106
+ Start-Sleep -Milliseconds 50
107
+ }
108
+ `;
109
+ /** 窗口压缩到任务栏的超时;默认 8s(WT 冷启动 + 脚本自编译 Add-Type 都要时间)。 */
110
+ const MINIMIZE_TIMEOUT_MS = 8_000;
111
+ /**
112
+ * 起一个后台 PowerShell 只做一件事:等到标题匹配的窗口出现并把它压到任务栏。
113
+ *
114
+ * 轮询放在 PowerShell 里而不是 Node 里,是为了只付出一次进程启动与一次 `Add-Type`
115
+ * 编译成本;从 Node 里反复 spawn 探测会慢十倍且更容易错过窗口创建的时刻。
116
+ *
117
+ * **必须经 `cmd /c start /min` 分离,不能直接 `spawn(..., {detached: true})`。**
118
+ * 实测后者会让 helper **静默死掉**:连脚本第一行写日志都没执行,窗口永远压不下去
119
+ * (三种 detached 组合全失败、非 detached 全成功)。原因是 detached 会脱离父控制台,
120
+ * 而 powershell 在这种无控制台状态下启动即退。借 `start` 由 cmd 提供一个新的(最小化)
121
+ * 控制台,脚本才跑得起来。
122
+ */
123
+ export function minimizeWindowByTitle(title, spawnImpl = spawn, timeoutMs = MINIMIZE_TIMEOUT_MS) {
124
+ try {
125
+ const encoded = Buffer.from(MINIMIZE_SCRIPT, 'utf16le').toString('base64');
126
+ const child = spawnImpl('cmd', [
127
+ '/c',
128
+ 'start',
129
+ '', // start 的第一个带引号参数是窗口标题,留空避免抢一个假标题
130
+ '/min',
131
+ 'powershell',
132
+ '-NoProfile',
133
+ '-NonInteractive',
134
+ '-EncodedCommand',
135
+ encoded,
136
+ ], {
137
+ stdio: 'ignore',
138
+ windowsHide: true,
139
+ // 注意:这里故意**不设** detached —— 分离交给 `start` 做(见上面的注释)。
140
+ env: {
141
+ ...process.env,
142
+ MOCODE_MINIMIZE_TITLE: title,
143
+ MOCODE_MINIMIZE_TIMEOUT_MS: String(timeoutMs),
144
+ },
145
+ });
146
+ child.on('error', () => undefined);
147
+ child.unref();
148
+ }
149
+ catch {
150
+ // 压不下去就让它在前台:这不是功能失败,不该冒泡成一个错误。
151
+ }
152
+ }
153
+ /** 是否把新窗口自动压到任务栏(`MOCODE_SUPERVISE_NO_MINIMIZE=1` 可关掉)。 */
154
+ export function autoMinimizeEnabled() {
155
+ const raw = (process.env.MOCODE_SUPERVISE_NO_MINIMIZE ?? '').trim().toLowerCase();
156
+ return !(raw === '1' || raw === 'true' || raw === 'yes');
157
+ }
158
+ function launchWindows(command, title, cwd, spawnImpl, minimizeImpl) {
159
+ const safeCwd = cwd ?? process.cwd();
160
+ // 注入了 spawnImpl 说明是测试:跳过探测(测试机不一定装了 wt.exe),直接按 wt 走。
161
+ // 真实运行没有 wt.exe(旧系统 / 精简镜像)时退回 cmd start。
162
+ if (spawnImpl !== spawn || probeWt()) {
163
+ try {
164
+ // 先挂 helper 再起窗口:helper 要 0.5–1s 编译 Add-Type,而窗口 ~100ms 就抢到焦点。
165
+ // 让编译与窗口创建并行,能把「挡在屏幕上」的时间压到最短。
166
+ if (minimizeImpl)
167
+ minimizeImpl(title);
168
+ else if (autoMinimizeEnabled())
169
+ minimizeWindowByTitle(title);
170
+ const child = spawnImpl('wt.exe', ['-w', '-1', 'new-tab', '--title', title, '--', ...command], {
171
+ cwd: safeCwd,
172
+ detached: true,
173
+ stdio: 'ignore',
174
+ windowsHide: false,
175
+ });
176
+ child.on('error', () => undefined);
177
+ child.unref();
178
+ return { opened: true, via: 'wt' };
179
+ }
180
+ catch {
181
+ // 继续尝试 cmd
182
+ }
183
+ }
184
+ try {
185
+ // `start` 的第一个带引号参数就是窗口标题(cmd 的怪癖)。这里给真标题,而不是空占位:
186
+ // 压到任务栏的 helper 靠标题找窗口,标题为空就永远匹配不上。
187
+ const child = spawnImpl('cmd', ['/c', 'start', title, '/D', safeCwd, ...command], {
188
+ cwd: safeCwd,
189
+ detached: true,
190
+ stdio: 'ignore',
191
+ windowsHide: true,
192
+ });
193
+ child.on('error', () => undefined);
194
+ child.unref();
195
+ if (minimizeImpl)
196
+ minimizeImpl(title);
197
+ else if (autoMinimizeEnabled())
198
+ minimizeWindowByTitle(title);
199
+ return { opened: true, via: 'cmd-start' };
200
+ }
201
+ catch {
202
+ return { opened: false };
203
+ }
204
+ }
205
+ function launchMac(command, cwd, spawnImpl) {
206
+ const line = quoteCommandLine(command);
207
+ const script = `tell application "Terminal"
208
+ activate
209
+ do script ${JSON.stringify(`cd ${JSON.stringify(cwd ?? process.cwd())} && ${line}`)}
210
+ end tell`;
211
+ try {
212
+ const child = spawnImpl('osascript', ['-e', script], { detached: true, stdio: 'ignore' });
213
+ child.on('error', () => undefined);
214
+ child.unref();
215
+ return { opened: true, via: 'Terminal.app' };
216
+ }
217
+ catch {
218
+ return { opened: false };
219
+ }
220
+ }
221
+ /**
222
+ * Linux/其他 POSIX:按优先级试几个常见终端。
223
+ * `-e` 后面接完整命令是 xterm/konsole 的通用写法;gnome-terminal 需要 `--`。
224
+ */
225
+ function launchLinux(command, title, cwd, spawnImpl) {
226
+ const cwdArgs = cwd ? ['cd ' + JSON.stringify(cwd) + ' &&'] : [];
227
+ const line = [...cwdArgs, quoteCommandLine(command)].join(' ');
228
+ const candidates = [
229
+ { bin: 'x-terminal-emulator', args: ['-e', 'sh', '-c', line] },
230
+ { bin: 'gnome-terminal', args: ['--title', title, '--', 'sh', '-c', line] },
231
+ { bin: 'konsole', args: ['-e', 'sh', '-c', line] },
232
+ { bin: 'xfce4-terminal', args: ['--title', title, '-e', `sh -c ${JSON.stringify(line)}`] },
233
+ { bin: 'xterm', args: ['-T', title, '-e', 'sh', '-c', line] },
234
+ ];
235
+ for (const candidate of candidates) {
236
+ try {
237
+ const child = spawnImpl(candidate.bin, candidate.args, { detached: true, stdio: 'ignore' });
238
+ child.on('error', () => undefined);
239
+ child.unref();
240
+ return { opened: true, via: candidate.bin };
241
+ }
242
+ catch {
243
+ // 换下一个
244
+ }
245
+ }
246
+ return { opened: false };
247
+ }
248
+ /**
249
+ * 打开一个独立终端跑 `args`(`mocode supervise lane …`)。
250
+ *
251
+ * 永远不会 reject:环境不支持就返回 `{opened:false}`,调用方据此决定是否提示。
252
+ */
253
+ export function openTerminalWindow(options) {
254
+ const spawnImpl = options.spawnImpl ?? spawn;
255
+ const command = selfCommand(options.args);
256
+ const platform = os.platform();
257
+ if (platform === 'win32')
258
+ return launchWindows(command, options.title, options.cwd, spawnImpl, options.minimizeImpl);
259
+ if (platform === 'darwin')
260
+ return launchMac(command, options.cwd, spawnImpl);
261
+ return launchLinux(command, options.title, options.cwd, spawnImpl);
262
+ }
263
+ /** 是否允许自动开窗(用户可用环境变量关掉:CI / SSH / 只想要一个 TUI)。 */
264
+ export function terminalAutoOpenEnabled() {
265
+ const raw = (process.env.MOCODE_SUPERVISE_NO_TERMINAL ?? '').trim().toLowerCase();
266
+ if (raw === '1' || raw === 'true' || raw === 'yes')
267
+ return false;
268
+ return true;
269
+ }
@@ -0,0 +1,392 @@
1
+ // Supervisor 的工具面:对话 REPL 只挂这一小撮控制面工具,模型看不到 read_file / run_command,
2
+ // 因此它无法自己"顺手改代码"——所有实际工作都必须经 Worke(孤立 lane)落地。
3
+ //
4
+ // 与 CLI 的对应关系是一比一:dispatch / ask / tell / close / integrate / review / cancel / status /
5
+ // workspaces。区别只在两处:
6
+ // - 调度器挂在后台跑(supervisor.ts 的 drive 循环),工具立即返回;
7
+ // - `supervise_apply` 单独成一个工具并声明 risk='confirm',每次真正合入真实工作区都要人按一下。
8
+ function ok(output) {
9
+ return { status: 'success', code: 'OK', retryable: false, output };
10
+ }
11
+ function fail(message) {
12
+ return { status: 'error', code: 'EXECUTION_ERROR', retryable: false, output: `错误:${message}` };
13
+ }
14
+ function strings(value) {
15
+ if (!Array.isArray(value))
16
+ return undefined;
17
+ const list = value.map((item) => String(item).trim()).filter(Boolean);
18
+ return list.length > 0 ? list : undefined;
19
+ }
20
+ const CHANGE_POLICY = ['read_only', 'isolated_write'];
21
+ function changePolicy(value) {
22
+ const text = typeof value === 'string' ? value.trim() : '';
23
+ return CHANGE_POLICY.includes(text) ? text : undefined;
24
+ }
25
+ /** 对话里可用的全部控制面工具名(REPL 用它收窄工具面)。 */
26
+ export const SUPERVISOR_TOOL_NAMES = [
27
+ 'supervise_workspaces',
28
+ 'supervise_status',
29
+ 'supervise_dispatch',
30
+ 'supervise_ask',
31
+ 'supervise_tell',
32
+ 'supervise_close',
33
+ 'supervise_integrate',
34
+ 'supervise_apply',
35
+ 'supervise_review',
36
+ 'supervise_cancel',
37
+ 'supervise_approve',
38
+ ];
39
+ export function createSupervisorTools(supervisor) {
40
+ const workspaces = {
41
+ name: 'supervise_workspaces',
42
+ description: "List the workspaces on this machine that have run mocode, plus each one's git state, recent sessions and open lanes. " +
43
+ 'Call this before dispatching when you are unsure which directory the user means.',
44
+ risk: 'safe',
45
+ capabilities: { effect: 'read', concurrency: 'parallel' },
46
+ parameters: {
47
+ type: 'object',
48
+ properties: {
49
+ scanRoot: {
50
+ type: 'string',
51
+ description: 'Optional directory to scan (depth ≤ 3) for extra workspaces that have never registered.',
52
+ },
53
+ },
54
+ },
55
+ async execute(args) {
56
+ try {
57
+ const scan = typeof args.scanRoot === 'string' && args.scanRoot ? [args.scanRoot] : [];
58
+ return ok(scan.length > 0
59
+ ? (await import('./workspaces.js')).formatWorkspaces(supervisor.workspaces()) +
60
+ `(scanRoot ${scan[0]} is not applied at runtime; pass it via the CLI --scan-roots flag.)\n`
61
+ : supervisor.formatWorkspaces());
62
+ }
63
+ catch (error) {
64
+ return fail(error instanceof Error ? error.message : String(error));
65
+ }
66
+ },
67
+ };
68
+ const status = {
69
+ name: 'supervise_status',
70
+ description: 'Show orchestration status: with runId, the full task/lane table of that run; without it, every live run on this machine. ' +
71
+ 'Use it to answer "how is it going" and to decide whether to dispatch more work.',
72
+ risk: 'safe',
73
+ capabilities: { effect: 'read', concurrency: 'parallel' },
74
+ parameters: {
75
+ type: 'object',
76
+ properties: {
77
+ runId: { type: 'string', description: 'Run id, e.g. 20261106-222105-292d. Omit to list live runs.' },
78
+ includeFinished: {
79
+ type: 'boolean',
80
+ description: 'When runId is omitted, also list recently finished runs from each workspace.',
81
+ },
82
+ },
83
+ },
84
+ async execute(args) {
85
+ try {
86
+ const runId = typeof args.runId === 'string' ? args.runId.trim() : '';
87
+ if (runId)
88
+ return ok(supervisor.status(runId));
89
+ const live = supervisor.status();
90
+ if (args.includeFinished !== true)
91
+ return ok(live);
92
+ const recent = supervisor
93
+ .recentRuns(2)
94
+ .map(({ run, workspaceRoot }) => `${run.id} · ${run.status} · ${workspaceRoot} · ${run.objective}`)
95
+ .join('\n');
96
+ return ok(`${live}\n\nRecent runs:\n${recent || '(none)'}`);
97
+ }
98
+ catch (error) {
99
+ return fail(error instanceof Error ? error.message : String(error));
100
+ }
101
+ },
102
+ };
103
+ const dispatch = {
104
+ name: 'supervise_dispatch',
105
+ description: [
106
+ 'Dispatch work to a mocode worker in a specific workspace, then return immediately (the worker runs in the background).',
107
+ "Target selection: with runId → append to that run; else the workspace's live run if it has one (continues that lane and its session); else a new run is created.",
108
+ 'If the run is still working, the task is queued and added automatically when the current batch finishes — say so, do not claim it started.',
109
+ "Workers run in an isolated lane (git worktree for git repos, a copy for plain directories); the user's directory is not touched until an explicit apply.",
110
+ ].join(' '),
111
+ risk: 'safe',
112
+ capabilities: { effect: 'process', concurrency: 'serial', supportsAbort: false },
113
+ parameters: {
114
+ type: 'object',
115
+ properties: {
116
+ objective: {
117
+ type: 'string',
118
+ description: 'The task for the worker. Be concrete: what to do, where, and what "done" means. The worker sees its lane\'s session history plus this text.',
119
+ },
120
+ workspace: {
121
+ type: 'string',
122
+ description: 'Absolute (or cwd-relative) workspace directory. Omit to use the supervisor cwd. Must be a git repository root or a plain directory.',
123
+ },
124
+ lane: {
125
+ type: 'string',
126
+ description: 'Lane id. Reuse an existing lane id to continue that lane/session; omit to derive one from the task id.',
127
+ },
128
+ title: { type: 'string', description: 'Short label (≤80 chars) shown in status output.' },
129
+ runId: { type: 'string', description: 'Append to this existing run instead of choosing one automatically.' },
130
+ taskId: { type: 'string', description: 'Explicit task id; omit to auto-number task-N.' },
131
+ dependsOn: {
132
+ type: 'array',
133
+ items: { type: 'string' },
134
+ description: 'Task ids that must complete first.',
135
+ },
136
+ changePolicy: {
137
+ type: 'string',
138
+ enum: [...CHANGE_POLICY],
139
+ description: 'read_only for investigation/status questions, isolated_write (default) when the worker should edit the lane.',
140
+ },
141
+ requiredChecks: {
142
+ type: 'array',
143
+ items: { type: 'string' },
144
+ description: 'Commands the worker must report as passed, e.g. ["npm run typecheck"].',
145
+ },
146
+ acceptanceCriteria: {
147
+ type: 'array',
148
+ items: { type: 'string' },
149
+ description: 'Human-readable acceptance criteria carried in the task contract.',
150
+ },
151
+ allow: { type: 'array', items: { type: 'string' }, description: 'Glob paths the worker may change.' },
152
+ deny: { type: 'array', items: { type: 'string' }, description: 'Glob paths the worker must not change.' },
153
+ },
154
+ required: ['objective'],
155
+ },
156
+ async execute(args) {
157
+ try {
158
+ const objective = typeof args.objective === 'string' ? args.objective : '';
159
+ return ok(await supervisor.dispatch({
160
+ objective,
161
+ workspace: typeof args.workspace === 'string' ? args.workspace : undefined,
162
+ lane: typeof args.lane === 'string' ? args.lane : undefined,
163
+ title: typeof args.title === 'string' ? args.title : undefined,
164
+ runId: typeof args.runId === 'string' ? args.runId : undefined,
165
+ taskId: typeof args.taskId === 'string' ? args.taskId : undefined,
166
+ dependsOn: strings(args.dependsOn),
167
+ requiredChecks: strings(args.requiredChecks),
168
+ acceptanceCriteria: strings(args.acceptanceCriteria),
169
+ changePolicy: changePolicy(args.changePolicy),
170
+ allow: strings(args.allow),
171
+ deny: strings(args.deny),
172
+ }));
173
+ }
174
+ catch (error) {
175
+ return fail(error instanceof Error ? error.message : String(error));
176
+ }
177
+ },
178
+ };
179
+ const ask = {
180
+ name: 'supervise_ask',
181
+ description: "Ask a lane a status question: the message is delivered as a real turn into that lane's existing worker session (read-only task). " +
182
+ 'Use it to find out what a worker actually did, what it verified, and what is left. Queued if the run is still working.',
183
+ risk: 'safe',
184
+ capabilities: { effect: 'process', concurrency: 'serial' },
185
+ parameters: {
186
+ type: 'object',
187
+ properties: {
188
+ runId: { type: 'string', description: 'Run id that owns the lane.' },
189
+ lane: { type: 'string', description: 'Lane id to ask.' },
190
+ question: { type: 'string', description: 'The question or status request.' },
191
+ },
192
+ required: ['runId', 'lane', 'question'],
193
+ },
194
+ async execute(args) {
195
+ try {
196
+ return ok(await supervisor.laneTurn('ask', {
197
+ runId: String(args.runId ?? ''),
198
+ lane: String(args.lane ?? ''),
199
+ text: String(args.question ?? ''),
200
+ }));
201
+ }
202
+ catch (error) {
203
+ return fail(error instanceof Error ? error.message : String(error));
204
+ }
205
+ },
206
+ };
207
+ const tell = {
208
+ name: 'supervise_tell',
209
+ description: "Send a steering message into a lane's existing worker session: a binding constraint for the rest of its work (scope, style, stop doing X). " +
210
+ 'Queued if the run is still working.',
211
+ risk: 'safe',
212
+ capabilities: { effect: 'process', concurrency: 'serial' },
213
+ parameters: {
214
+ type: 'object',
215
+ properties: {
216
+ runId: { type: 'string', description: 'Run id that owns the lane.' },
217
+ lane: { type: 'string', description: 'Lane id to steer.' },
218
+ message: { type: 'string', description: 'The constraint or correction.' },
219
+ },
220
+ required: ['runId', 'lane', 'message'],
221
+ },
222
+ async execute(args) {
223
+ try {
224
+ return ok(await supervisor.laneTurn('tell', {
225
+ runId: String(args.runId ?? ''),
226
+ lane: String(args.lane ?? ''),
227
+ text: String(args.message ?? ''),
228
+ }));
229
+ }
230
+ catch (error) {
231
+ return fail(error instanceof Error ? error.message : String(error));
232
+ }
233
+ },
234
+ };
235
+ const close = {
236
+ name: 'supervise_close',
237
+ description: 'Close a lane: export its accumulated diff to the run artifacts, archive the lane session, and drop the execution site. ' +
238
+ 'Close only when the user says the work batch is finished; a closed lane can be reopened by dispatching to it again.',
239
+ risk: 'safe',
240
+ capabilities: { effect: 'process', concurrency: 'serial' },
241
+ parameters: {
242
+ type: 'object',
243
+ properties: {
244
+ runId: { type: 'string', description: 'Run id that owns the lane.' },
245
+ lane: { type: 'string', description: 'Lane id to close.' },
246
+ },
247
+ required: ['runId', 'lane'],
248
+ },
249
+ async execute(args) {
250
+ try {
251
+ return ok(await supervisor.closeLane(String(args.runId ?? ''), String(args.lane ?? '')));
252
+ }
253
+ catch (error) {
254
+ return fail(error instanceof Error ? error.message : String(error));
255
+ }
256
+ },
257
+ };
258
+ const integrate = {
259
+ name: 'supervise_integrate',
260
+ description: 'Dry-run the integration of closed lanes back into the real workspace: per lane, whether its patch applies cleanly, which files it touches, ' +
261
+ 'and what blocks it (open lane, missing patch, dirty working tree, conflict). Nothing is written. Requires a closed lane.',
262
+ risk: 'safe',
263
+ capabilities: { effect: 'process', concurrency: 'serial' },
264
+ parameters: {
265
+ type: 'object',
266
+ properties: {
267
+ runId: { type: 'string', description: 'Run id.' },
268
+ lane: { type: 'string', description: 'Only plan this lane; omit for every lane of the run.' },
269
+ },
270
+ required: ['runId'],
271
+ },
272
+ async execute(args) {
273
+ try {
274
+ return ok(supervisor.integrate(String(args.runId ?? ''), {
275
+ lane: typeof args.lane === 'string' ? args.lane : undefined,
276
+ apply: false,
277
+ }));
278
+ }
279
+ catch (error) {
280
+ return fail(error instanceof Error ? error.message : String(error));
281
+ }
282
+ },
283
+ };
284
+ const apply = {
285
+ name: 'supervise_apply',
286
+ description: 'Apply the closed lane patches into the real workspace (git apply, no commit). The user confirms this through a permission panel every time. ' +
287
+ 'Only call after supervise_integrate reported every lane as ready, and only when the user asked for the work to land.',
288
+ risk: 'confirm',
289
+ capabilities: { effect: 'process', concurrency: 'serial' },
290
+ parameters: {
291
+ type: 'object',
292
+ properties: {
293
+ runId: { type: 'string', description: 'Run id.' },
294
+ lane: { type: 'string', description: 'Only apply this lane; omit for every ready lane of the run.' },
295
+ },
296
+ required: ['runId'],
297
+ },
298
+ async execute(args) {
299
+ try {
300
+ return ok(supervisor.integrate(String(args.runId ?? ''), {
301
+ lane: typeof args.lane === 'string' ? args.lane : undefined,
302
+ apply: true,
303
+ }));
304
+ }
305
+ catch (error) {
306
+ return fail(error instanceof Error ? error.message : String(error));
307
+ }
308
+ },
309
+ };
310
+ const review = {
311
+ name: 'supervise_review',
312
+ description: 'Ask the supervisor model for a "is this run finished?" verdict over the run\'s handoffs and evidence (one model call). ' +
313
+ 'Use it when the queue is drained and you need a second opinion before closing lanes. dryRun returns the evidence pack without calling the model.',
314
+ risk: 'safe',
315
+ capabilities: { effect: 'process', concurrency: 'serial' },
316
+ parameters: {
317
+ type: 'object',
318
+ properties: {
319
+ runId: { type: 'string', description: 'Run id.' },
320
+ dryRun: { type: 'boolean', description: 'Return the evidence pack only; no model call, no ledger write.' },
321
+ },
322
+ required: ['runId'],
323
+ },
324
+ async execute(args) {
325
+ try {
326
+ return ok(await supervisor.review(String(args.runId ?? ''), { dryRun: args.dryRun === true }));
327
+ }
328
+ catch (error) {
329
+ return fail(error instanceof Error ? error.message : String(error));
330
+ }
331
+ },
332
+ };
333
+ const approve = {
334
+ name: 'supervise_approve',
335
+ description: [
336
+ 'Answer a worker that is paused waiting for a human: a tool-permission request or a question the worker asked with ask_human.',
337
+ 'Use the approval id from the snapshot / supervise_status. For a choice, pass the option label as value; for free text, pass the text.',
338
+ "The worker resumes inside the same session. Never answer on the operator's behalf without telling them what you answered — this is the one place a wrong click changes the work.",
339
+ ].join(' '),
340
+ risk: 'confirm',
341
+ capabilities: { effect: 'process', concurrency: 'serial' },
342
+ parameters: {
343
+ type: 'object',
344
+ properties: {
345
+ approvalId: {
346
+ type: 'string',
347
+ description: 'Approval id from the snapshot or supervise_status (e.g. 8f2c…), or its 1-based index in the pending list.',
348
+ },
349
+ action: {
350
+ type: 'string',
351
+ enum: ['selected', 'submitted', 'cancelled'],
352
+ description: 'selected = pick one of the offered options; submitted = send free text; cancelled = refuse (the worker is told the human declined).',
353
+ },
354
+ value: { type: 'string', description: 'The chosen option label, or the free-text answer. Omit for cancelled.' },
355
+ },
356
+ required: ['approvalId', 'action'],
357
+ },
358
+ async execute(args) {
359
+ try {
360
+ const action = String(args.action ?? '');
361
+ if (!['selected', 'submitted', 'cancelled'].includes(action)) {
362
+ return fail(`action must be selected, submitted or cancelled (got "${action}").`);
363
+ }
364
+ return ok(supervisor.answerApproval(String(args.approvalId ?? ''), action, typeof args.value === 'string' && args.value ? args.value : undefined));
365
+ }
366
+ catch (error) {
367
+ return fail(error instanceof Error ? error.message : String(error));
368
+ }
369
+ },
370
+ };
371
+ const cancel = {
372
+ name: 'supervise_cancel',
373
+ description: 'Request cancellation of a run: running workers are stopped, lanes are closed and the run becomes terminal. ' +
374
+ 'Irreversible — confirm with the user first unless they explicitly asked to cancel.',
375
+ risk: 'confirm',
376
+ capabilities: { effect: 'process', concurrency: 'serial' },
377
+ parameters: {
378
+ type: 'object',
379
+ properties: { runId: { type: 'string', description: 'Run id.' } },
380
+ required: ['runId'],
381
+ },
382
+ async execute(args) {
383
+ try {
384
+ return ok(await supervisor.cancel(String(args.runId ?? '')));
385
+ }
386
+ catch (error) {
387
+ return fail(error instanceof Error ? error.message : String(error));
388
+ }
389
+ },
390
+ };
391
+ return [workspaces, status, dispatch, ask, tell, close, integrate, apply, review, cancel, approve];
392
+ }
@@ -0,0 +1 @@
1
+ export const ORCHESTRATION_SCHEMA_VERSION = 1;