agent-supervisor-mcp 0.0.0-stage → 2.0.1

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 (122) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +208 -0
  3. package/README.md +206 -2
  4. package/package.json +76 -4
  5. package/skills/agent-supervisor/SKILL.md +139 -0
  6. package/src/app/acceptance.js +263 -0
  7. package/src/app/auto-cleanup.js +91 -0
  8. package/src/app/cancel.js +57 -0
  9. package/src/app/cleanup-facts.js +101 -0
  10. package/src/app/cleanup-plan.js +166 -0
  11. package/src/app/compose.js +17 -0
  12. package/src/app/context-compiler.js +83 -0
  13. package/src/app/dispatch.js +398 -0
  14. package/src/app/followup.js +104 -0
  15. package/src/app/land-chain.js +134 -0
  16. package/src/app/landing.js +357 -0
  17. package/src/app/ownership.js +57 -0
  18. package/src/app/rebase.js +216 -0
  19. package/src/app/restore-worktree.js +51 -0
  20. package/src/app/resume.js +179 -0
  21. package/src/app/run-state.js +26 -0
  22. package/src/app/settled.js +28 -0
  23. package/src/app/side-chat.js +370 -0
  24. package/src/app/sse.js +20 -0
  25. package/src/app/start-run.js +77 -0
  26. package/src/app/verify-push.js +114 -0
  27. package/src/app/worktree-setup.js +218 -0
  28. package/src/domain/acceptance-baseline.js +65 -0
  29. package/src/domain/acceptance-spec.js +30 -0
  30. package/src/domain/cleanup-policy.js +44 -0
  31. package/src/domain/command-outcome.js +6 -0
  32. package/src/domain/failure-class.js +63 -0
  33. package/src/domain/owned-changes.js +27 -0
  34. package/src/domain/prompt.js +161 -0
  35. package/src/domain/side-turn-view.js +73 -0
  36. package/src/domain/status.js +50 -0
  37. package/src/domain/thread-health.js +33 -0
  38. package/src/domain/truncate.js +148 -0
  39. package/src/domain/worker-branch.js +6 -0
  40. package/src/domain/worker-changes.js +58 -0
  41. package/src/domain/worker-env.js +14 -0
  42. package/src/domain/worker-preflight.js +167 -0
  43. package/src/domain/worker-report.js +85 -0
  44. package/src/domain/worker-report.schema.json +10 -0
  45. package/src/infra/bin-resolver.js +287 -0
  46. package/src/infra/cleanup-hint.js +29 -0
  47. package/src/infra/crash-guard.js +44 -0
  48. package/src/infra/external-output.js +29 -0
  49. package/src/infra/git.js +61 -0
  50. package/src/infra/handoff.js +38 -0
  51. package/src/infra/paths.js +34 -0
  52. package/src/infra/process.js +59 -0
  53. package/src/infra/sandbox-roots.js +106 -0
  54. package/src/infra/skill-sync.js +109 -0
  55. package/src/infra/stage-store.js +39 -0
  56. package/src/infra/store/db.js +265 -0
  57. package/src/infra/store/event-body.js +82 -0
  58. package/src/infra/store/events.js +149 -0
  59. package/src/infra/store/facts.js +338 -0
  60. package/src/infra/store/reconcile.js +173 -0
  61. package/src/infra/store/records.js +171 -0
  62. package/src/infra/store/runner-readers.js +16 -0
  63. package/src/infra/store/schema.js +306 -0
  64. package/src/infra/store/sessions.js +138 -0
  65. package/src/infra/store/tasks.js +351 -0
  66. package/src/infra/update/auto-update-worker.js +186 -0
  67. package/src/infra/update/auto-update.js +143 -0
  68. package/src/infra/update/update-check.js +246 -0
  69. package/src/infra/workspace-kind.js +165 -0
  70. package/src/infra/worktree.js +361 -0
  71. package/src/interface/bin/acceptance-cli.js +62 -0
  72. package/src/interface/bin/cleanup.js +81 -0
  73. package/src/interface/bin/monitor.jsx +301 -0
  74. package/src/interface/bin/setup.js +342 -0
  75. package/src/interface/bin/stage.js +17 -0
  76. package/src/interface/bin/web-server.js +53 -0
  77. package/src/interface/mcp/handlers/delivery.js +165 -0
  78. package/src/interface/mcp/handlers/dispatch.js +236 -0
  79. package/src/interface/mcp/handlers/facts.js +204 -0
  80. package/src/interface/mcp/handlers/overview.js +106 -0
  81. package/src/interface/mcp/handlers/results.js +262 -0
  82. package/src/interface/mcp/handlers/review.js +115 -0
  83. package/src/interface/mcp/handlers/wait.js +141 -0
  84. package/src/interface/mcp/meta.js +7 -0
  85. package/src/interface/mcp/result.js +34 -0
  86. package/src/interface/mcp/schemas.js +24 -0
  87. package/src/interface/mcp/server.js +64 -0
  88. package/src/interface/mcp/tools/deliver.js +48 -0
  89. package/src/interface/mcp/tools/dispatch.js +90 -0
  90. package/src/interface/mcp/tools/optional.js +57 -0
  91. package/src/interface/mcp/tools/read.js +115 -0
  92. package/src/interface/mcp/tools/run.js +57 -0
  93. package/src/interface/mcp/tools/shapes.js +67 -0
  94. package/src/interface/mcp/tools/track.js +84 -0
  95. package/src/interface/mcp/update-state.js +34 -0
  96. package/src/interface/mcp/views/overview.js +183 -0
  97. package/src/interface/mcp/views/task.js +224 -0
  98. package/src/interface/web/app.js +226 -0
  99. package/src/interface/web/views.js +227 -0
  100. package/src/mcp-server.js +4 -0
  101. package/src/run-host/entry.js +26 -0
  102. package/src/run-host/finalize.js +243 -0
  103. package/src/run-host/launch.js +49 -0
  104. package/src/run-host/live-run.js +76 -0
  105. package/src/run-host/outcome-facts.js +61 -0
  106. package/src/run-host/streams.js +102 -0
  107. package/src/run-host/track.js +132 -0
  108. package/src/runners/claude/adapter.js +118 -0
  109. package/src/runners/claude/events.js +100 -0
  110. package/src/runners/claude/tool-guard.js +48 -0
  111. package/src/runners/codex/adapter.js +157 -0
  112. package/src/runners/codex/chat-chunks.js +97 -0
  113. package/src/runners/codex/event-parser.js +266 -0
  114. package/src/runners/codex/goal-store.js +54 -0
  115. package/src/runners/codex/mcp-config.js +39 -0
  116. package/src/runners/codex/tool-guard.js +184 -0
  117. package/src/runners/contract-check.js +82 -0
  118. package/src/runners/contract.js +53 -0
  119. package/src/runners/registry.js +45 -0
  120. package/web/dist/assets/index-D-A2xlpx.js +154 -0
  121. package/web/dist/assets/index-f8esISCp.css +2 -0
  122. package/web/dist/index.html +15 -0
@@ -0,0 +1,301 @@
1
+ #!/usr/bin/env node
2
+ import "../../app/compose.js";
3
+ import React, { useEffect, useMemo, useState } from "react";
4
+ import { Box, Newline, render, Text, useApp, useInput, useStdout } from "ink";
5
+ import { readTaskEvents } from "../../infra/store/events.js";
6
+ import { readTasks } from "../../infra/store/tasks.js";
7
+ import { reconcileDetachedActiveTasks } from "../../infra/store/reconcile.js";
8
+
9
+ const REFRESH_MS = 1000;
10
+ const STATUS_LABELS = {
11
+ queued: "排队中",
12
+ running: "运行中",
13
+ editing: "编辑中",
14
+ command: "执行命令",
15
+ command_completed: "命令完成",
16
+ reporting: "汇报中",
17
+ completed: "已完成",
18
+ failed: "失败",
19
+ cancelled: "已取消"
20
+ };
21
+
22
+ const PHASE_LABELS = {
23
+ queued: "排队中",
24
+ starting: "启动中",
25
+ thinking: "思考中",
26
+ editing: "编辑中",
27
+ command: "执行命令",
28
+ command_completed: "命令完成",
29
+ reporting: "汇报中",
30
+ completed: "已完成",
31
+ failed: "失败",
32
+ cancelled: "已取消"
33
+ };
34
+ const ACTIVE_STATUSES = new Set(["queued", "running", "editing", "command", "command_completed", "reporting"]);
35
+
36
+ function truncate(value, width) {
37
+ const text = String(value ?? "");
38
+ if (width <= 1) return "";
39
+ return text.length > width ? `${text.slice(0, width - 1)}…` : text;
40
+ }
41
+
42
+ function statusColor(status) {
43
+ if (status === "completed") return "green";
44
+ if (status === "failed" || status === "cancelled") return "red";
45
+ if (status === "running") return "cyan";
46
+ if (status === "queued") return "yellow";
47
+ return "white";
48
+ }
49
+
50
+ function statusLabel(status) {
51
+ return STATUS_LABELS[status] ?? status ?? "-";
52
+ }
53
+
54
+ function phaseLabel(phase) {
55
+ return PHASE_LABELS[phase] ?? phase ?? "-";
56
+ }
57
+
58
+ function eventSummary(event) {
59
+ const type = event?.type ?? "unknown";
60
+ const item = event?.item;
61
+ if (!item) return type;
62
+
63
+ if (item.type === "agent_message") {
64
+ return `${type} agent_message: ${truncate(item.text, 120)}`;
65
+ }
66
+ if (item.type === "command_execution") {
67
+ return `${type} command: ${truncate(item.command ?? item.cmd ?? item.text ?? "", 120)}`;
68
+ }
69
+ if (item.type === "file_change") {
70
+ return `${type} file_change: ${truncate(item.path ?? item.file ?? item.file_path ?? "", 120)}`;
71
+ }
72
+ return `${type} ${item.type ?? ""}`.trim();
73
+ }
74
+
75
+ function eventActor(event) {
76
+ const type = event?.type ?? "";
77
+ const itemType = event?.item?.type;
78
+ if (itemType === "agent_message") return "agent";
79
+ if (itemType === "command_execution") return "cmd";
80
+ if (itemType === "file_change") return "file";
81
+ if (type.startsWith("turn.")) return "turn";
82
+ if (type.startsWith("thread.")) return "thread";
83
+ return "event";
84
+ }
85
+
86
+ function eventColor(event) {
87
+ const actor = eventActor(event);
88
+ if (actor === "agent") return "green";
89
+ if (actor === "cmd") return "yellow";
90
+ if (actor === "file") return "magenta";
91
+ if (actor === "turn") return "cyan";
92
+ return "gray";
93
+ }
94
+
95
+ function eventOutput(event) {
96
+ const item = event?.item;
97
+ if (item?.type === "agent_message") return item.text ?? "";
98
+ if (item?.type === "command_execution") {
99
+ const command = item.command ?? item.cmd ?? item.text ?? "";
100
+ const status = item.status ? ` ${item.status}` : "";
101
+ const exitCode = item.exit_code ?? item.exitCode;
102
+ const exitText = exitCode === undefined || exitCode === null ? "" : ` exit=${exitCode}`;
103
+ return `${command}${status}${exitText}`.trim();
104
+ }
105
+ if (item?.type === "file_change") {
106
+ return item.path ?? item.file ?? item.file_path ?? JSON.stringify(item);
107
+ }
108
+ if (event?.type === "turn.completed") return "turn completed";
109
+ if (event?.type === "turn.failed") return `turn failed: ${event.error ?? event.message ?? ""}`.trim();
110
+ if (event?.type === "thread.started") return `thread ${event.thread_id ?? ""}`.trim();
111
+ return eventSummary(event);
112
+ }
113
+
114
+ function useSupervisorData(selectedIndex, showAll) {
115
+ const [tasks, setTasks] = useState([]);
116
+ const [totalCount, setTotalCount] = useState(0);
117
+ const [events, setEvents] = useState([]);
118
+ const [error, setError] = useState(null);
119
+
120
+ useEffect(() => {
121
+ let active = true;
122
+
123
+ async function refresh() {
124
+ try {
125
+ await reconcileDetachedActiveTasks();
126
+ const allTasks = await readTasks();
127
+ const nextTasks = showAll ? allTasks : allTasks.filter((task) => ACTIVE_STATUSES.has(task.status));
128
+ if (!active) return;
129
+ setTotalCount(allTasks.length);
130
+ setTasks(nextTasks);
131
+ const selected = nextTasks[selectedIndex] ?? nextTasks[0];
132
+ const nextEvents = selected ? await readTaskEvents(selected.id, 80) : [];
133
+ if (!active) return;
134
+ setEvents(nextEvents);
135
+ setError(null);
136
+ } catch (refreshError) {
137
+ if (active) setError(refreshError.message);
138
+ }
139
+ }
140
+
141
+ refresh();
142
+ const timer = setInterval(refresh, REFRESH_MS);
143
+ return () => {
144
+ active = false;
145
+ clearInterval(timer);
146
+ };
147
+ }, [selectedIndex, showAll]);
148
+
149
+ return { tasks, totalCount, events, error };
150
+ }
151
+
152
+ function Header({ showAll }) {
153
+ return (
154
+ <Box borderStyle="single" paddingX={1}>
155
+ <Text bold>Codex 监督台</Text>
156
+ <Text dimColor>
157
+ {" "}q/Esc: 退出 ↑/↓ 或 j/k: 切换 worker a: {showAll ? "只看活跃" : "看全部/历史"} 每秒自动刷新
158
+ </Text>
159
+ </Box>
160
+ );
161
+ }
162
+
163
+ function ClaudePlanPanel({ width }) {
164
+ return (
165
+ <Box borderStyle="single" flexDirection="column" width={width} paddingX={1}>
166
+ <Text bold color="magenta">Claude CLI 总控</Text>
167
+ <Text dimColor>Claude 负责计划、派工、审查;这里负责观察状态。</Text>
168
+ <Newline />
169
+ <Text>1. Claude 先列计划和验收标准。</Text>
170
+ <Text>2. 前端/后端/测试拆成不同 Codex worker。</Text>
171
+ <Text>3. 右侧看每个 worker 当前状态。</Text>
172
+ <Text>4. 底部看输入、输出、事件和错误。</Text>
173
+ <Text>5. 完成后让 Claude 或 Codex review worker 审查。</Text>
174
+ <Newline />
175
+ <Text dimColor>Claude 可调用的 MCP 工具名:</Text>
176
+ <Text dimColor>create_worker</Text>
177
+ <Text dimColor>create_worker with followup_of</Text>
178
+ <Text dimColor>poll_workers</Text>
179
+ <Text dimColor>get_worker</Text>
180
+ <Text dimColor>get_worker (include events)</Text>
181
+ <Text dimColor>cancel_worker</Text>
182
+ </Box>
183
+ );
184
+ }
185
+
186
+ function WorkersPanel({ tasks, selectedIndex, width, showAll, totalCount }) {
187
+ return (
188
+ <Box borderStyle="single" flexDirection="column" width={width} paddingX={1}>
189
+ <Text bold color="cyan">
190
+ Codex 执行队列 <Text dimColor>{showAll ? `全部 ${totalCount}` : `活跃 ${tasks.length} / 全部 ${totalCount}`}</Text>
191
+ </Text>
192
+ {tasks.length === 0 ? (
193
+ <Text dimColor>{showAll ? "暂无 worker。请在 Claude CLI 里创建任务。" : "暂无活跃 worker。按 a 查看历史。"}</Text>
194
+ ) : (
195
+ tasks.map((task, index) => {
196
+ const selected = index === selectedIndex;
197
+ const marker = selected ? ">" : " ";
198
+ const title = truncate(task.title ?? task.id, Math.max(16, width - 44));
199
+ const phase = truncate(phaseLabel(task.phase), 18);
200
+ const action = truncate(task.current_command ?? task.current_action ?? task.last_message ?? "", Math.max(12, width - 58));
201
+ return (
202
+ <Text key={task.id} inverse={selected}>
203
+ {marker} <Text color={statusColor(task.status)}>{truncate(statusLabel(task.status), 10).padEnd(10)}</Text>{" "}
204
+ {phase.padEnd(18)} {title} <Text dimColor>{action}</Text>
205
+ </Text>
206
+ );
207
+ })
208
+ )}
209
+ </Box>
210
+ );
211
+ }
212
+
213
+ function DetailPanel({ task, events, height }) {
214
+ const shownEvents = useMemo(() => events.slice(-Math.max(4, height - 12)), [events, height]);
215
+
216
+ return (
217
+ <Box borderStyle="single" flexDirection="column" paddingX={1} minHeight={height}>
218
+ <Text bold color="green">当前 Worker 详情</Text>
219
+ {!task ? (
220
+ <Text dimColor>未选中 worker。</Text>
221
+ ) : (
222
+ <>
223
+ <Text>ID: {task.id}</Text>
224
+ <Text>
225
+ 状态: <Text color={statusColor(task.status)}>{statusLabel(task.status)}</Text> 阶段: {phaseLabel(task.phase)}
226
+ </Text>
227
+ <Text>思考强度: {task.reasoning_effort ?? "high"}</Text>
228
+ <Text>执行目录: {truncate(task.cwd, 120)}</Text>
229
+ {task.worktree_path ? <Text>隔离 worktree: {truncate(task.worktree_path, 120)}</Text> : null}
230
+ {task.followup_of ? <Text>续跑来源: {task.followup_of}</Text> : null}
231
+ <Text>当前动作: {truncate(task.current_action ?? task.last_message ?? "-", 120)}</Text>
232
+ {task.current_command ? <Text>当前命令: {truncate(task.current_command, 120)}</Text> : null}
233
+ <Text>变更文件数: {(task.changed_files ?? []).length}</Text>
234
+ <Text dimColor>输入 prompt:</Text>
235
+ <Text>{truncate(task.prompt, 160)}</Text>
236
+ <Text dimColor>最近输出 / item 事件:</Text>
237
+ {shownEvents.length === 0 ? (
238
+ <Text dimColor>暂无事件。</Text>
239
+ ) : (
240
+ shownEvents.map((event, index) => (
241
+ <Text key={`${event.type}-${index}`}>
242
+ <Text color={eventColor(event)}>{eventActor(event).padEnd(6)}</Text>{" "}
243
+ <Text dimColor>{truncate(event.type ?? "unknown", 18).padEnd(18)}</Text>{" "}
244
+ {truncate(eventOutput(event), 132)}
245
+ </Text>
246
+ ))
247
+ )}
248
+ </>
249
+ )}
250
+ </Box>
251
+ );
252
+ }
253
+
254
+ function App() {
255
+ const { exit } = useApp();
256
+ const { stdout } = useStdout();
257
+ const terminalWidth = stdout.columns ?? 120;
258
+ const terminalHeight = stdout.rows ?? 36;
259
+ const [selectedIndex, setSelectedIndex] = useState(0);
260
+ const [showAll, setShowAll] = useState(false);
261
+ const { tasks, totalCount, events, error } = useSupervisorData(selectedIndex, showAll);
262
+
263
+ useInput((input, key) => {
264
+ if (input === "q" || key.escape) exit();
265
+ if (input === "a") {
266
+ setSelectedIndex(0);
267
+ setShowAll((current) => !current);
268
+ }
269
+ if (input === "j" || key.downArrow) {
270
+ setSelectedIndex((current) => Math.min(Math.max(tasks.length - 1, 0), current + 1));
271
+ }
272
+ if (input === "k" || key.upArrow) {
273
+ setSelectedIndex((current) => Math.max(0, current - 1));
274
+ }
275
+ });
276
+
277
+ useEffect(() => {
278
+ if (selectedIndex >= tasks.length) {
279
+ setSelectedIndex(Math.max(0, tasks.length - 1));
280
+ }
281
+ }, [selectedIndex, tasks.length]);
282
+
283
+ const leftWidth = Math.max(38, Math.floor(terminalWidth * 0.36));
284
+ const rightWidth = Math.max(50, terminalWidth - leftWidth - 2);
285
+ const selectedTask = tasks[selectedIndex] ?? null;
286
+ const detailHeight = Math.max(12, terminalHeight - 16);
287
+
288
+ return (
289
+ <Box flexDirection="column">
290
+ <Header showAll={showAll} />
291
+ {error ? <Text color="red">错误: {error}</Text> : null}
292
+ <Box>
293
+ <ClaudePlanPanel width={leftWidth} />
294
+ <WorkersPanel tasks={tasks} selectedIndex={selectedIndex} width={rightWidth} showAll={showAll} totalCount={totalCount} />
295
+ </Box>
296
+ <DetailPanel task={selectedTask} events={events} height={detailHeight} />
297
+ </Box>
298
+ );
299
+ }
300
+
301
+ render(<App />);
@@ -0,0 +1,342 @@
1
+ #!/usr/bin/env node
2
+ // Installs the agent-supervisor skill into the skill directories of the agent
3
+ // clients found on this machine, and registers the MCP server with them.
4
+ //
5
+ // Runs automatically after a *global* npm install (`postinstall`), and can be
6
+ // invoked directly to repair or re-run setup:
7
+ //
8
+ // npx agent-supervisor-setup
9
+ // agent-supervisor-setup --target claude --force
10
+ //
11
+ // Set AGENT_SUPERVISOR_SKIP_SETUP=1 to opt out of the automatic run.
12
+ import { runFile } from "../../infra/process.js";
13
+ import { existsSync, readdirSync } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { basename, dirname, isAbsolute, join } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { promisify } from "node:util";
18
+ import {
19
+ defaultBinDirs,
20
+ findBinaryPath,
21
+ resolveCommand,
22
+ shimMessage
23
+ } from "../../infra/bin-resolver.js";
24
+
25
+ const run = promisify(runFile);
26
+
27
+ import { installSkill, skillRoots } from "../../infra/skill-sync.js";
28
+
29
+ const packageRoot = fileURLToPath(new URL("../../..", import.meta.url)).replace(/[\\/]$/, "");
30
+ const serverEntry = join(packageRoot, "src", "mcp-server.js");
31
+
32
+ const MCP_NAME = "agent-supervisor";
33
+ // What this package registered itself as when it was codex-supervisor-mcp.
34
+ const LEGACY_MCP_NAME = "codex-supervisor";
35
+ const CLIENT_TIMEOUT_MS = 60_000;
36
+
37
+ // A client is "present" when its binary is on PATH or its skill directory
38
+ // already exists. We never invent directories for clients the user does not run.
39
+ // `npmEntry` lets bin-resolver.js step over a Windows .cmd shim by pointing at
40
+ // the package's own entry point. `binEnv` is the override named in the repair
41
+ // message when that fails (only Codex has one).
42
+ const SKILL_ROOTS = skillRoots();
43
+ const CLIENTS = [
44
+ {
45
+ ...SKILL_ROOTS.claude,
46
+ binary: "claude",
47
+ binEnv: "CLAUDE_BIN",
48
+ npmEntry: { pkg: "@anthropic-ai/claude-code", bin: "bin/claude.exe" }
49
+ },
50
+ { ...SKILL_ROOTS.agents, binary: null },
51
+ {
52
+ ...SKILL_ROOTS.codex,
53
+ binary: "codex",
54
+ binEnv: "CODEX_BIN",
55
+ npmEntry: { pkg: "@openai/codex", bin: "bin/codex.js" }
56
+ }
57
+ ];
58
+
59
+ function parseArgs(argv) {
60
+ const options = {
61
+ auto: false,
62
+ quiet: false,
63
+ dryRun: false,
64
+ force: false,
65
+ skills: true,
66
+ mcp: true,
67
+ targets: null,
68
+ help: false
69
+ };
70
+
71
+ for (let index = 0; index < argv.length; index += 1) {
72
+ const arg = argv[index];
73
+ if (arg === "--auto") {
74
+ options.auto = true;
75
+ } else if (arg === "--quiet") {
76
+ options.quiet = true;
77
+ } else if (arg === "--dry-run") {
78
+ options.dryRun = true;
79
+ } else if (arg === "--force") {
80
+ options.force = true;
81
+ } else if (arg === "--skill-only") {
82
+ options.mcp = false;
83
+ } else if (arg === "--mcp-only") {
84
+ options.skills = false;
85
+ } else if (arg === "--target") {
86
+ options.targets = String(argv[index + 1] ?? "")
87
+ .split(",")
88
+ .map((value) => value.trim())
89
+ .filter(Boolean);
90
+ index += 1;
91
+ } else if (arg === "--help" || arg === "-h") {
92
+ options.help = true;
93
+ } else {
94
+ throw new Error(`Unknown argument: ${arg}`);
95
+ }
96
+ }
97
+
98
+ if (options.targets?.includes("all")) options.targets = null;
99
+ return options;
100
+ }
101
+
102
+ function printHelp() {
103
+ console.log(`Usage: agent-supervisor-setup [options]
104
+
105
+ Installs the agent-supervisor skill and registers the MCP server with the
106
+ Claude Code and Codex clients found on this machine.
107
+
108
+ Options:
109
+ --target <list> Comma-separated: claude, agents, codex, all. Default: detected.
110
+ --skill-only Only install the skill; do not touch MCP config.
111
+ --mcp-only Only register the MCP server; do not install the skill.
112
+ --force Overwrite skill files without keeping a .bak copy.
113
+ --dry-run Print what would happen and change nothing.
114
+ --quiet Only print warnings and errors.
115
+ --auto Postinstall mode: global installs only, never fails.
116
+ -h, --help Show help.
117
+
118
+ Environment:
119
+ AGENT_SUPERVISOR_SKIP_SETUP=1 Skip the automatic postinstall run entirely.
120
+ `);
121
+ }
122
+
123
+ // PATH first, then the well-known global bin directories (shared with the
124
+ // worker runner so both look in the same places), then the version managers,
125
+ // whose node bin directory is only discoverable by listing.
126
+ const EXTRA_BIN_DIRS = defaultBinDirs();
127
+
128
+ const VERSION_MANAGER_ROOTS = [
129
+ [join(homedir(), ".nvm", "versions", "node"), join("bin")],
130
+ [join(homedir(), ".fnm", "node-versions"), join("installation", "bin")]
131
+ ];
132
+
133
+ function versionManagerBinDirs() {
134
+ const dirs = [];
135
+ for (const [root, suffix] of VERSION_MANAGER_ROOTS) {
136
+ if (!existsSync(root)) continue;
137
+ let entries;
138
+ try {
139
+ entries = readdirSync(root);
140
+ } catch {
141
+ continue;
142
+ }
143
+ for (const entry of entries) {
144
+ dirs.push(join(root, entry, suffix));
145
+ }
146
+ }
147
+ return dirs;
148
+ }
149
+
150
+ // Turns a client binary into a spawnable target, or null when the client is not
151
+ // installed. On Windows a bare `codex` resolves to `codex.cmd`, which Node
152
+ // refuses to execute directly, so the resolver hands back `cmd` + `prefixArgs`
153
+ // instead (see bin-resolver.js).
154
+ function locateClient(binary) {
155
+ if (!binary) return null;
156
+ const client = CLIENTS.find((entry) => entry.binary === binary);
157
+ const configured = client?.binEnv && process.env[client.binEnv]?.trim();
158
+ const path = findBinaryPath(configured || binary, {
159
+ extraDirs: [...EXTRA_BIN_DIRS, ...versionManagerBinDirs()]
160
+ });
161
+ if (!path) return null;
162
+ const target = resolveCommand(path, { npmEntry: CLIENTS.find((c) => c.binary === binary)?.npmEntry });
163
+ return { path, cmd: target.cmd, args: target.prefixArgs, shim: target.shim };
164
+ }
165
+
166
+ function runClient(target, args, options = {}) {
167
+ return run(target.cmd, [...target.args, ...args], { windowsHide: true, ...options });
168
+ }
169
+
170
+ function selectClients(options) {
171
+ return CLIENTS.filter((client) => {
172
+ if (options.targets && !options.targets.includes(client.id)) return false;
173
+ if (client.binary && locateClient(client.binary)) return true;
174
+ return existsSync(client.skillRoot) || (client.binary && existsSync(dirname(client.skillRoot)));
175
+ });
176
+ }
177
+
178
+ async function registeredMcp(target, client, name = MCP_NAME) {
179
+ try {
180
+ const { stdout } = await runClient(target, ["mcp", "get", name, ...(client.id === "codex" ? ["--json"] : [])], { timeout: CLIENT_TIMEOUT_MS });
181
+ if (client.id === "codex") {
182
+ const value = JSON.parse(stdout);
183
+ const transport = value.transport ?? value;
184
+ const { command, args = [], env = {}, cwd } = transport;
185
+ return { command, args: args ?? [], env: env ?? {}, cwd, enabled: value.enabled !== false, userScope: true };
186
+ }
187
+ const command = stdout.match(/^\s*Command: (.+)$/m)?.[1]?.trim();
188
+ const args = stdout.match(/^\s*Args: (.*)$/m)?.[1]?.trim();
189
+ const environment = stdout.split(/\n[ \t]*Environment:[ \t]*\r?\n/)[1]?.split(/(?:^|\n)[ \t]*To remove/)[0]?.trim();
190
+ return { command, args: args ? [args] : [], env: environment ? { custom: true } : {}, enabled: !/Status:.*Disabled/i.test(stdout), userScope: /Scope: User config/.test(stdout) };
191
+ } catch (error) {
192
+ const message = `${error.stdout ?? ""}${error.stderr ?? ""}${error.message}`;
193
+ if (/not found|no mcp server|could not find|does not exist/i.test(message)) return null;
194
+ throw new Error(`cannot read ${client.label} MCP registration: ${error.message.split("\n")[0]}`, { cause: error });
195
+ }
196
+ }
197
+
198
+ // A registration this installer wrote and nobody edited: user scope, plain
199
+ // node, the package's own entry, no environment. Only such a one is replaced
200
+ // or removed without asking.
201
+ function isManaged(entry, packageName) {
202
+ return entry.userScope && entry.enabled && !entry.cwd && Object.keys(entry.env).length === 0
203
+ && ["node", "node.exe"].includes(basename(entry.command ?? "").toLowerCase())
204
+ && entry.args.length === 1 && isAbsolute(entry.args[0])
205
+ && new RegExp(`(?:^|[\\\\/])${packageName}[\\\\/]src[\\\\/]mcp-server\\.js$`).test(entry.args[0])
206
+ && (/[\\/]node_modules[\\/]/.test(entry.args[0]) || !existsSync(entry.args[0]));
207
+ }
208
+
209
+ // Two registrations would give a session both tool sets and two supervisors on
210
+ // one store. The former name's entry goes once the new one is in place, unless
211
+ // someone customised it, in which case they are told.
212
+ async function retireLegacyRegistration(target, client, log, warn) {
213
+ const legacy = await registeredMcp(target, client, LEGACY_MCP_NAME).catch(() => null);
214
+ if (!legacy) return;
215
+ if (!isManaged(legacy, "codex-supervisor-mcp")) {
216
+ warn(`mcp ${client.label}: "${LEGACY_MCP_NAME}" is still registered with custom settings; remove it with "${client.binary} mcp remove ${LEGACY_MCP_NAME}" so only one supervisor is loaded`);
217
+ return;
218
+ }
219
+ await runClient(target, client.id === "claude" ? ["mcp", "remove", "-s", "user", LEGACY_MCP_NAME] : ["mcp", "remove", LEGACY_MCP_NAME], { timeout: CLIENT_TIMEOUT_MS });
220
+ log(`mcp ${client.label}: removed the former "${LEGACY_MCP_NAME}" registration`);
221
+ }
222
+
223
+ async function registerMcp(client, options, log, warn) {
224
+ const target = locateClient(client.binary);
225
+ if (!target) {
226
+ warn(`mcp ${client.label}: no ${client.binary} CLI found; install it or set ${client.binEnv} to its executable, then run "agent-supervisor-setup"`);
227
+ return "failed";
228
+ }
229
+ if (target.shim) {
230
+ warn(
231
+ `mcp ${client.label}: ${shimMessage(client.binary, target.path, client.binEnv)}`
232
+ );
233
+ return "failed";
234
+ }
235
+ let previous;
236
+ try { previous = options.dryRun ? null : await registeredMcp(target, client); }
237
+ catch (error) { warn(`mcp ${client.label}: ${error.message}`); return "failed"; }
238
+ if (previous) {
239
+ const same = previous.userScope && previous.command === process.execPath && previous.args.length === 1 && previous.args[0] === serverEntry;
240
+ if (same && previous.enabled) {
241
+ await retireLegacyRegistration(target, client, log, warn).catch(() => {});
242
+ log(`mcp ${client.label}: already registered at this installation`);
243
+ return "unchanged";
244
+ }
245
+ if (!isManaged(previous, "agent-supervisor-mcp")) {
246
+ warn(`mcp ${client.label}: existing custom, disabled or project registration preserved; inspect "${client.binary} mcp get ${MCP_NAME}" before replacing it`);
247
+ return "failed";
248
+ }
249
+ }
250
+
251
+ const args =
252
+ client.id === "claude"
253
+ ? ["mcp", "add", "-s", "user", MCP_NAME, "--", process.execPath, serverEntry]
254
+ : ["mcp", "add", MCP_NAME, "--", process.execPath, serverEntry];
255
+
256
+ if (options.dryRun) {
257
+ if (previous) log(`mcp ${client.label}: would repair stale package registration`);
258
+ log(`mcp ${client.label}: would run ${client.binary} ${args.join(" ")}`);
259
+ return "would-register";
260
+ }
261
+ try {
262
+ if (previous) await runClient(target, client.id === "claude" ? ["mcp", "remove", "-s", "user", MCP_NAME] : ["mcp", "remove", MCP_NAME], { timeout: CLIENT_TIMEOUT_MS });
263
+ await runClient(target, args, { timeout: CLIENT_TIMEOUT_MS });
264
+ const actual = await registeredMcp(target, client);
265
+ if (!actual || actual.command !== process.execPath || actual.args.length !== 1 || actual.args[0] !== serverEntry || !actual.enabled) throw new Error("registration command succeeded but read-back does not match this package");
266
+ await retireLegacyRegistration(target, client, log, warn).catch((error) => warn(`mcp ${client.label}: could not remove "${LEGACY_MCP_NAME}" (${error.message.split("\n")[0]})`));
267
+ log(`mcp ${client.label}: ${previous ? "repaired" : "registered"}`);
268
+ return "registered";
269
+ } catch (error) {
270
+ if (previous) {
271
+ try {
272
+ await runClient(target, client.id === "claude" ? ["mcp", "remove", "-s", "user", MCP_NAME] : ["mcp", "remove", MCP_NAME], { timeout: CLIENT_TIMEOUT_MS }).catch(() => {});
273
+ const restore = client.id === "claude" ? ["mcp", "add", "-s", "user", MCP_NAME, "--", previous.command, ...previous.args] : ["mcp", "add", MCP_NAME, "--", previous.command, ...previous.args];
274
+ await runClient(target, restore, { timeout: CLIENT_TIMEOUT_MS });
275
+ } catch (restoreError) { warn(`mcp ${client.label}: restoring the original registration failed (${restoreError.message.split("\n")[0]})`); }
276
+ }
277
+ warn(
278
+ `mcp ${client.label}: registration failed (${error.message.split("\n")[0]}) ` +
279
+ `- run "agent-supervisor-setup" once ${client.label} is working`
280
+ );
281
+ return "failed";
282
+ }
283
+ }
284
+
285
+ async function main() {
286
+ const options = parseArgs(process.argv.slice(2));
287
+
288
+ if (options.help) {
289
+ printHelp();
290
+ return 0;
291
+ }
292
+
293
+ if (options.auto) {
294
+ if (process.env.AGENT_SUPERVISOR_SKIP_SETUP) {
295
+ return 0;
296
+ }
297
+ if (process.env.npm_config_global !== "true") {
298
+ return 0;
299
+ }
300
+ }
301
+
302
+ const log = options.quiet ? () => {} : (line) => console.log(line);
303
+ const warn = (line) => console.error(line);
304
+ const clients = selectClients(options);
305
+ const missingTargets = options.targets?.filter((id) => !clients.some((client) => client.id === id)) ?? [];
306
+ if (missingTargets.length) warn(`setup: requested client(s) not detected: ${missingTargets.join(", ")}; install the CLI or set CLAUDE_BIN / CODEX_BIN`);
307
+
308
+ if (clients.length === 0) {
309
+ warn("setup: no Claude Code / Codex client detected; MCP was not registered. Install a client, then run agent-supervisor-setup.");
310
+ return options.targets?.length && !options.auto ? 1 : 0;
311
+ }
312
+
313
+ log(`setup: ${options.dryRun ? "dry run against" : "configuring"} ${clients.map((client) => client.label).join(", ")}`);
314
+
315
+ let failures = missingTargets.length;
316
+ if (options.skills) {
317
+ for (const client of clients) {
318
+ try { await installSkill(client, options, log); }
319
+ catch (error) { failures += 1; warn(`skill ${client.label}: install failed (${error.message.split("\n")[0]}); MCP registration will still be attempted`); }
320
+ }
321
+ }
322
+ if (options.mcp) {
323
+ for (const client of clients.filter((client) => client.binary)) {
324
+ if (await registerMcp(client, options, log, warn) === "failed") failures += 1;
325
+ }
326
+ }
327
+
328
+ log(failures ? `setup: ${failures} setup step(s) require repair` : "setup: done");
329
+ return failures && !options.auto ? 1 : 0;
330
+ }
331
+
332
+ try {
333
+ process.exitCode = await main();
334
+ } catch (error) {
335
+ const message = `setup: ${error.message}`;
336
+ if (process.argv.includes("--auto")) {
337
+ console.error(`${message} (ignored)`);
338
+ } else {
339
+ console.error(message);
340
+ process.exitCode = 1;
341
+ }
342
+ }
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ import { writeStage } from "../../infra/stage-store.js";
3
+
4
+ const argv = process.argv.slice(2);
5
+ let taskId = process.env.AGENT_SUPERVISOR_TASK_ID;
6
+ let detail = null;
7
+ const positional = [];
8
+ for (let index = 0; index < argv.length; index += 1) {
9
+ if (argv[index] === "--detail") detail = argv[++index];
10
+ else positional.push(argv[index]);
11
+ }
12
+ const stage = positional.join(" ").trim();
13
+ if (!taskId || !stage) {
14
+ console.error('usage: agent-supervisor-stage "gate:s3" [--detail "..."] (task comes from AGENT_SUPERVISOR_TASK_ID)');
15
+ process.exit(2);
16
+ }
17
+ process.stdout.write(`${JSON.stringify(writeStage(taskId, stage, detail))}\n`);