codex-supervisor-mcp 0.0.0-stage → 0.4.0

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.
@@ -0,0 +1,298 @@
1
+ #!/usr/bin/env node
2
+ import React, { useEffect, useMemo, useState } from "react";
3
+ import { Box, Newline, render, Text, useApp, useInput, useStdout } from "ink";
4
+ import { readTaskEvents, readTasks, reconcileDetachedActiveTasks } from "./task-store.js";
5
+
6
+ const REFRESH_MS = 1000;
7
+ const STATUS_LABELS = {
8
+ queued: "排队中",
9
+ running: "运行中",
10
+ editing: "编辑中",
11
+ command: "执行命令",
12
+ command_completed: "命令完成",
13
+ reporting: "汇报中",
14
+ completed: "已完成",
15
+ failed: "失败",
16
+ cancelled: "已取消"
17
+ };
18
+
19
+ const PHASE_LABELS = {
20
+ queued: "排队中",
21
+ starting: "启动中",
22
+ thinking: "思考中",
23
+ editing: "编辑中",
24
+ command: "执行命令",
25
+ command_completed: "命令完成",
26
+ reporting: "汇报中",
27
+ completed: "已完成",
28
+ failed: "失败",
29
+ cancelled: "已取消"
30
+ };
31
+ const ACTIVE_STATUSES = new Set(["queued", "running", "editing", "command", "command_completed", "reporting"]);
32
+
33
+ function truncate(value, width) {
34
+ const text = String(value ?? "");
35
+ if (width <= 1) return "";
36
+ return text.length > width ? `${text.slice(0, width - 1)}…` : text;
37
+ }
38
+
39
+ function statusColor(status) {
40
+ if (status === "completed") return "green";
41
+ if (status === "failed" || status === "cancelled") return "red";
42
+ if (status === "running") return "cyan";
43
+ if (status === "queued") return "yellow";
44
+ return "white";
45
+ }
46
+
47
+ function statusLabel(status) {
48
+ return STATUS_LABELS[status] ?? status ?? "-";
49
+ }
50
+
51
+ function phaseLabel(phase) {
52
+ return PHASE_LABELS[phase] ?? phase ?? "-";
53
+ }
54
+
55
+ function eventSummary(event) {
56
+ const type = event?.type ?? "unknown";
57
+ const item = event?.item;
58
+ if (!item) return type;
59
+
60
+ if (item.type === "agent_message") {
61
+ return `${type} agent_message: ${truncate(item.text, 120)}`;
62
+ }
63
+ if (item.type === "command_execution") {
64
+ return `${type} command: ${truncate(item.command ?? item.cmd ?? item.text ?? "", 120)}`;
65
+ }
66
+ if (item.type === "file_change") {
67
+ return `${type} file_change: ${truncate(item.path ?? item.file ?? item.file_path ?? "", 120)}`;
68
+ }
69
+ return `${type} ${item.type ?? ""}`.trim();
70
+ }
71
+
72
+ function eventActor(event) {
73
+ const type = event?.type ?? "";
74
+ const itemType = event?.item?.type;
75
+ if (itemType === "agent_message") return "agent";
76
+ if (itemType === "command_execution") return "cmd";
77
+ if (itemType === "file_change") return "file";
78
+ if (type.startsWith("turn.")) return "turn";
79
+ if (type.startsWith("thread.")) return "thread";
80
+ return "event";
81
+ }
82
+
83
+ function eventColor(event) {
84
+ const actor = eventActor(event);
85
+ if (actor === "agent") return "green";
86
+ if (actor === "cmd") return "yellow";
87
+ if (actor === "file") return "magenta";
88
+ if (actor === "turn") return "cyan";
89
+ return "gray";
90
+ }
91
+
92
+ function eventOutput(event) {
93
+ const item = event?.item;
94
+ if (item?.type === "agent_message") return item.text ?? "";
95
+ if (item?.type === "command_execution") {
96
+ const command = item.command ?? item.cmd ?? item.text ?? "";
97
+ const status = item.status ? ` ${item.status}` : "";
98
+ const exitCode = item.exit_code ?? item.exitCode;
99
+ const exitText = exitCode === undefined || exitCode === null ? "" : ` exit=${exitCode}`;
100
+ return `${command}${status}${exitText}`.trim();
101
+ }
102
+ if (item?.type === "file_change") {
103
+ return item.path ?? item.file ?? item.file_path ?? JSON.stringify(item);
104
+ }
105
+ if (event?.type === "turn.completed") return "turn completed";
106
+ if (event?.type === "turn.failed") return `turn failed: ${event.error ?? event.message ?? ""}`.trim();
107
+ if (event?.type === "thread.started") return `thread ${event.thread_id ?? ""}`.trim();
108
+ return eventSummary(event);
109
+ }
110
+
111
+ function useSupervisorData(selectedIndex, showAll) {
112
+ const [tasks, setTasks] = useState([]);
113
+ const [totalCount, setTotalCount] = useState(0);
114
+ const [events, setEvents] = useState([]);
115
+ const [error, setError] = useState(null);
116
+
117
+ useEffect(() => {
118
+ let active = true;
119
+
120
+ async function refresh() {
121
+ try {
122
+ await reconcileDetachedActiveTasks();
123
+ const allTasks = await readTasks();
124
+ const nextTasks = showAll ? allTasks : allTasks.filter((task) => ACTIVE_STATUSES.has(task.status));
125
+ if (!active) return;
126
+ setTotalCount(allTasks.length);
127
+ setTasks(nextTasks);
128
+ const selected = nextTasks[selectedIndex] ?? nextTasks[0];
129
+ const nextEvents = selected ? await readTaskEvents(selected.id, 80) : [];
130
+ if (!active) return;
131
+ setEvents(nextEvents);
132
+ setError(null);
133
+ } catch (refreshError) {
134
+ if (active) setError(refreshError.message);
135
+ }
136
+ }
137
+
138
+ refresh();
139
+ const timer = setInterval(refresh, REFRESH_MS);
140
+ return () => {
141
+ active = false;
142
+ clearInterval(timer);
143
+ };
144
+ }, [selectedIndex, showAll]);
145
+
146
+ return { tasks, totalCount, events, error };
147
+ }
148
+
149
+ function Header({ showAll }) {
150
+ return (
151
+ <Box borderStyle="single" paddingX={1}>
152
+ <Text bold>Codex 监督台</Text>
153
+ <Text dimColor>
154
+ {" "}q/Esc: 退出 ↑/↓ 或 j/k: 切换 worker a: {showAll ? "只看活跃" : "看全部/历史"} 每秒自动刷新
155
+ </Text>
156
+ </Box>
157
+ );
158
+ }
159
+
160
+ function ClaudePlanPanel({ width }) {
161
+ return (
162
+ <Box borderStyle="single" flexDirection="column" width={width} paddingX={1}>
163
+ <Text bold color="magenta">Claude CLI 总控</Text>
164
+ <Text dimColor>Claude 负责计划、派工、审查;这里负责观察状态。</Text>
165
+ <Newline />
166
+ <Text>1. Claude 先列计划和验收标准。</Text>
167
+ <Text>2. 前端/后端/测试拆成不同 Codex worker。</Text>
168
+ <Text>3. 右侧看每个 worker 当前状态。</Text>
169
+ <Text>4. 底部看输入、输出、事件和错误。</Text>
170
+ <Text>5. 完成后让 Claude 或 Codex review worker 审查。</Text>
171
+ <Newline />
172
+ <Text dimColor>Claude 可调用的 MCP 工具名:</Text>
173
+ <Text dimColor>create_codex_worker</Text>
174
+ <Text dimColor>create_codex_followup_worker</Text>
175
+ <Text dimColor>list_codex_workers</Text>
176
+ <Text dimColor>get_codex_worker_status</Text>
177
+ <Text dimColor>get_codex_worker_events</Text>
178
+ <Text dimColor>cancel_codex_worker</Text>
179
+ </Box>
180
+ );
181
+ }
182
+
183
+ function WorkersPanel({ tasks, selectedIndex, width, showAll, totalCount }) {
184
+ return (
185
+ <Box borderStyle="single" flexDirection="column" width={width} paddingX={1}>
186
+ <Text bold color="cyan">
187
+ Codex 执行队列 <Text dimColor>{showAll ? `全部 ${totalCount}` : `活跃 ${tasks.length} / 全部 ${totalCount}`}</Text>
188
+ </Text>
189
+ {tasks.length === 0 ? (
190
+ <Text dimColor>{showAll ? "暂无 worker。请在 Claude CLI 里创建任务。" : "暂无活跃 worker。按 a 查看历史。"}</Text>
191
+ ) : (
192
+ tasks.map((task, index) => {
193
+ const selected = index === selectedIndex;
194
+ const marker = selected ? ">" : " ";
195
+ const title = truncate(task.title ?? task.id, Math.max(16, width - 44));
196
+ const phase = truncate(phaseLabel(task.phase), 18);
197
+ const action = truncate(task.current_command ?? task.current_action ?? task.last_message ?? "", Math.max(12, width - 58));
198
+ return (
199
+ <Text key={task.id} inverse={selected}>
200
+ {marker} <Text color={statusColor(task.status)}>{truncate(statusLabel(task.status), 10).padEnd(10)}</Text>{" "}
201
+ {phase.padEnd(18)} {title} <Text dimColor>{action}</Text>
202
+ </Text>
203
+ );
204
+ })
205
+ )}
206
+ </Box>
207
+ );
208
+ }
209
+
210
+ function DetailPanel({ task, events, height }) {
211
+ const shownEvents = useMemo(() => events.slice(-Math.max(4, height - 12)), [events, height]);
212
+
213
+ return (
214
+ <Box borderStyle="single" flexDirection="column" paddingX={1} minHeight={height}>
215
+ <Text bold color="green">当前 Worker 详情</Text>
216
+ {!task ? (
217
+ <Text dimColor>未选中 worker。</Text>
218
+ ) : (
219
+ <>
220
+ <Text>ID: {task.id}</Text>
221
+ <Text>
222
+ 状态: <Text color={statusColor(task.status)}>{statusLabel(task.status)}</Text> 阶段: {phaseLabel(task.phase)}
223
+ </Text>
224
+ <Text>思考强度: {task.reasoning_effort ?? "high"}</Text>
225
+ <Text>执行目录: {truncate(task.cwd, 120)}</Text>
226
+ {task.worktree_path ? <Text>隔离 worktree: {truncate(task.worktree_path, 120)}</Text> : null}
227
+ {task.followup_of ? <Text>续跑来源: {task.followup_of}</Text> : null}
228
+ <Text>当前动作: {truncate(task.current_action ?? task.last_message ?? "-", 120)}</Text>
229
+ {task.current_command ? <Text>当前命令: {truncate(task.current_command, 120)}</Text> : null}
230
+ <Text>变更文件数: {(task.changed_files ?? []).length}</Text>
231
+ <Text dimColor>输入 prompt:</Text>
232
+ <Text>{truncate(task.prompt, 160)}</Text>
233
+ <Text dimColor>最近输出 / item 事件:</Text>
234
+ {shownEvents.length === 0 ? (
235
+ <Text dimColor>暂无事件。</Text>
236
+ ) : (
237
+ shownEvents.map((event, index) => (
238
+ <Text key={`${event.type}-${index}`}>
239
+ <Text color={eventColor(event)}>{eventActor(event).padEnd(6)}</Text>{" "}
240
+ <Text dimColor>{truncate(event.type ?? "unknown", 18).padEnd(18)}</Text>{" "}
241
+ {truncate(eventOutput(event), 132)}
242
+ </Text>
243
+ ))
244
+ )}
245
+ </>
246
+ )}
247
+ </Box>
248
+ );
249
+ }
250
+
251
+ function App() {
252
+ const { exit } = useApp();
253
+ const { stdout } = useStdout();
254
+ const terminalWidth = stdout.columns ?? 120;
255
+ const terminalHeight = stdout.rows ?? 36;
256
+ const [selectedIndex, setSelectedIndex] = useState(0);
257
+ const [showAll, setShowAll] = useState(false);
258
+ const { tasks, totalCount, events, error } = useSupervisorData(selectedIndex, showAll);
259
+
260
+ useInput((input, key) => {
261
+ if (input === "q" || key.escape) exit();
262
+ if (input === "a") {
263
+ setSelectedIndex(0);
264
+ setShowAll((current) => !current);
265
+ }
266
+ if (input === "j" || key.downArrow) {
267
+ setSelectedIndex((current) => Math.min(Math.max(tasks.length - 1, 0), current + 1));
268
+ }
269
+ if (input === "k" || key.upArrow) {
270
+ setSelectedIndex((current) => Math.max(0, current - 1));
271
+ }
272
+ });
273
+
274
+ useEffect(() => {
275
+ if (selectedIndex >= tasks.length) {
276
+ setSelectedIndex(Math.max(0, tasks.length - 1));
277
+ }
278
+ }, [selectedIndex, tasks.length]);
279
+
280
+ const leftWidth = Math.max(38, Math.floor(terminalWidth * 0.36));
281
+ const rightWidth = Math.max(50, terminalWidth - leftWidth - 2);
282
+ const selectedTask = tasks[selectedIndex] ?? null;
283
+ const detailHeight = Math.max(12, terminalHeight - 16);
284
+
285
+ return (
286
+ <Box flexDirection="column">
287
+ <Header showAll={showAll} />
288
+ {error ? <Text color="red">错误: {error}</Text> : null}
289
+ <Box>
290
+ <ClaudePlanPanel width={leftWidth} />
291
+ <WorkersPanel tasks={tasks} selectedIndex={selectedIndex} width={rightWidth} showAll={showAll} totalCount={totalCount} />
292
+ </Box>
293
+ <DetailPanel task={selectedTask} events={events} height={detailHeight} />
294
+ </Box>
295
+ );
296
+ }
297
+
298
+ render(<App />);
package/src/paths.js ADDED
@@ -0,0 +1,22 @@
1
+ import { homedir } from "node:os";
2
+ import { join, resolve } from "node:path";
3
+
4
+ // Runtime state root. Defaults to ~/.codex-supervisor so a globally installed
5
+ // package keeps one stable data directory regardless of where npm put it.
6
+ // Override with SUPERVISOR_HOME.
7
+ export const supervisorRoot = resolve(
8
+ process.env.SUPERVISOR_HOME?.trim() || join(homedir(), ".codex-supervisor")
9
+ );
10
+
11
+ // Codex's own home, used to read native thread goals. Read-only.
12
+ // Override with CODEX_HOME.
13
+ export const codexHome = resolve(
14
+ process.env.CODEX_HOME?.trim() || join(homedir(), ".codex")
15
+ );
16
+
17
+ export const goalsDbPath = join(codexHome, "goals_1.sqlite");
18
+
19
+ export const dataDir = join(supervisorRoot, "data");
20
+ export const dbPath = join(dataDir, "supervisor.sqlite");
21
+ export const runsDir = join(dataDir, "runs");
22
+ export const worktreesDir = join(supervisorRoot, "worktrees");
package/src/prompt.js ADDED
@@ -0,0 +1,39 @@
1
+ // Worker prompt framing.
2
+ //
3
+ // Codex exposes goal tools (create_goal / get_goal / update_goal) to every
4
+ // thread, but the model does not create a goal on its own. A worker therefore
5
+ // starts with no native goal unless we ask for one, which is why the supervisor
6
+ // prepends this block instead of only recording the goal on its own side.
7
+ //
8
+ // create_goal fails when an unfinished goal already exists, so the resume path
9
+ // must not ask for one: that thread already has its goal.
10
+
11
+ function oneLine(value) {
12
+ return String(value ?? "").replace(/\s+/g, " ").trim();
13
+ }
14
+
15
+ export function buildGoalPreamble({ objective, tokenBudget = null, resume = false }) {
16
+ const goal = oneLine(objective);
17
+ if (!goal) return "";
18
+ if (resume) {
19
+ return [
20
+ `This thread already has a goal: ${goal}`,
21
+ "Do not call create_goal; it fails while an unfinished goal exists.",
22
+ 'Call update_goal with status "complete" when the objective is achieved and no required work remains.',
23
+ 'If the same blocker repeats for three consecutive turns and you cannot make progress, call update_goal with status "blocked" instead.'
24
+ ].join("\n");
25
+ }
26
+ const budget = tokenBudget ? ` and token_budget ${tokenBudget}` : "";
27
+ return [
28
+ "Do this first, before any other work:",
29
+ `Call the create_goal tool with objective exactly "${goal}"${budget}.`,
30
+ "That goal is how your supervisor tracks this work; do not skip it.",
31
+ 'When the objective is achieved and no required work remains, call update_goal with status "complete".',
32
+ 'If the same blocker repeats for three consecutive turns and you cannot make progress, call update_goal with status "blocked" instead.'
33
+ ].join("\n");
34
+ }
35
+
36
+ export function withGoalPreamble(prompt, goalOptions) {
37
+ const preamble = buildGoalPreamble(goalOptions);
38
+ return preamble ? `${preamble}\n\n${prompt}` : prompt;
39
+ }
package/src/setup.js ADDED
@@ -0,0 +1,290 @@
1
+ #!/usr/bin/env node
2
+ // Installs the codex-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 codex-supervisor-setup
9
+ // codex-supervisor-setup --target claude --force
10
+ //
11
+ // Set CODEX_SUPERVISOR_SKIP_SETUP=1 to opt out of the automatic run.
12
+ import { execFile } from "node:child_process";
13
+ import { existsSync, readdirSync } from "node:fs";
14
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
15
+ import { homedir } from "node:os";
16
+ import { dirname, join } from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+ import { promisify } from "node:util";
19
+
20
+ const run = promisify(execFile);
21
+
22
+ const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
23
+ const skillSource = join(packageRoot, "skills", "codex-supervisor", "SKILL.md");
24
+ const serverEntry = join(packageRoot, "src", "mcp-server.js");
25
+
26
+ const SKILL_NAME = "codex-supervisor";
27
+ const MCP_NAME = "codex-supervisor";
28
+ const CLIENT_TIMEOUT_MS = 60_000;
29
+
30
+ // A client is "present" when its binary is on PATH or its skill directory
31
+ // already exists. We never invent directories for clients the user does not run.
32
+ const CLIENTS = [
33
+ { id: "claude", label: "Claude Code", skillRoot: join(homedir(), ".claude", "skills"), binary: "claude" },
34
+ { id: "agents", label: "~/.agents", skillRoot: join(homedir(), ".agents", "skills"), binary: null },
35
+ { id: "codex", label: "Codex", skillRoot: join(homedir(), ".codex", "skills"), binary: "codex" }
36
+ ];
37
+
38
+ function parseArgs(argv) {
39
+ const options = {
40
+ auto: false,
41
+ quiet: false,
42
+ dryRun: false,
43
+ force: false,
44
+ skills: true,
45
+ mcp: true,
46
+ targets: null,
47
+ help: false
48
+ };
49
+
50
+ for (let index = 0; index < argv.length; index += 1) {
51
+ const arg = argv[index];
52
+ if (arg === "--auto") {
53
+ options.auto = true;
54
+ } else if (arg === "--quiet") {
55
+ options.quiet = true;
56
+ } else if (arg === "--dry-run") {
57
+ options.dryRun = true;
58
+ } else if (arg === "--force") {
59
+ options.force = true;
60
+ } else if (arg === "--skill-only") {
61
+ options.mcp = false;
62
+ } else if (arg === "--mcp-only") {
63
+ options.skills = false;
64
+ } else if (arg === "--target") {
65
+ options.targets = String(argv[index + 1] ?? "")
66
+ .split(",")
67
+ .map((value) => value.trim())
68
+ .filter(Boolean);
69
+ index += 1;
70
+ } else if (arg === "--help" || arg === "-h") {
71
+ options.help = true;
72
+ } else {
73
+ throw new Error(`Unknown argument: ${arg}`);
74
+ }
75
+ }
76
+
77
+ if (options.targets?.includes("all")) options.targets = null;
78
+ return options;
79
+ }
80
+
81
+ function printHelp() {
82
+ console.log(`Usage: codex-supervisor-setup [options]
83
+
84
+ Installs the codex-supervisor skill and registers the MCP server with the
85
+ Claude Code and Codex clients found on this machine.
86
+
87
+ Options:
88
+ --target <list> Comma-separated: claude, agents, codex, all. Default: detected.
89
+ --skill-only Only install the skill; do not touch MCP config.
90
+ --mcp-only Only register the MCP server; do not install the skill.
91
+ --force Overwrite skill files without keeping a .bak copy.
92
+ --dry-run Print what would happen and change nothing.
93
+ --quiet Only print warnings and errors.
94
+ --auto Postinstall mode: global installs only, never fails.
95
+ -h, --help Show help.
96
+
97
+ Environment:
98
+ CODEX_SUPERVISOR_SKIP_SETUP=1 Skip the automatic postinstall run entirely.
99
+ `);
100
+ }
101
+
102
+ // PATH first, then the well-known global bin directories. A client installed
103
+ // with a custom npm prefix (npm config set prefix ~/.npm-global) or a version
104
+ // manager is usually absent from a non-interactive PATH, and without this the
105
+ // client would look "not installed" even though the user runs it every day.
106
+ const EXTRA_BIN_DIRS = [
107
+ join(homedir(), ".npm-global", "bin"),
108
+ join(homedir(), ".local", "bin"),
109
+ join(homedir(), ".bun", "bin"),
110
+ join(homedir(), ".volta", "bin"),
111
+ join(homedir(), "Library", "pnpm"),
112
+ "/opt/homebrew/bin",
113
+ "/usr/local/bin"
114
+ ];
115
+
116
+ const VERSION_MANAGER_ROOTS = [
117
+ [join(homedir(), ".nvm", "versions", "node"), join("bin")],
118
+ [join(homedir(), ".fnm", "node-versions"), join("installation", "bin")]
119
+ ];
120
+
121
+ function onPath(binary) {
122
+ for (const dir of (process.env.PATH ?? "").split(":")) {
123
+ if (!dir) continue;
124
+ const candidate = join(dir, binary);
125
+ if (existsSync(candidate)) return candidate;
126
+ }
127
+ for (const dir of EXTRA_BIN_DIRS) {
128
+ const candidate = join(dir, binary);
129
+ if (existsSync(candidate)) return candidate;
130
+ }
131
+ for (const [root, suffix] of VERSION_MANAGER_ROOTS) {
132
+ if (!existsSync(root)) continue;
133
+ let entries = [];
134
+ try {
135
+ entries = readdirSync(root);
136
+ } catch {
137
+ continue;
138
+ }
139
+ for (const entry of entries) {
140
+ const candidate = join(root, entry, suffix, binary);
141
+ if (existsSync(candidate)) return candidate;
142
+ }
143
+ }
144
+ return null;
145
+ }
146
+
147
+ function selectClients(options) {
148
+ return CLIENTS.filter((client) => {
149
+ if (options.targets && !options.targets.includes(client.id)) return false;
150
+ if (client.binary && onPath(client.binary)) return true;
151
+ return existsSync(client.skillRoot);
152
+ });
153
+ }
154
+
155
+ async function installSkill(client, options, log) {
156
+ const destination = join(client.skillRoot, SKILL_NAME, "SKILL.md");
157
+ const source = await readFile(skillSource, "utf8");
158
+
159
+ if (existsSync(destination)) {
160
+ const current = await readFile(destination, "utf8");
161
+ if (current === source) {
162
+ log(`skill ${client.label}: up to date`);
163
+ return "unchanged";
164
+ }
165
+ if (!options.force) {
166
+ const backup = `${destination}.bak-${Date.now()}`;
167
+ if (options.dryRun) {
168
+ log(`skill ${client.label}: would back up to ${backup} and overwrite`);
169
+ return "would-update";
170
+ }
171
+ await writeFile(backup, current);
172
+ }
173
+ if (options.dryRun) {
174
+ log(`skill ${client.label}: would overwrite`);
175
+ return "would-update";
176
+ }
177
+ await writeFile(destination, source);
178
+ log(`skill ${client.label}: updated`);
179
+ return "updated";
180
+ }
181
+
182
+ if (options.dryRun) {
183
+ log(`skill ${client.label}: would install to ${destination}`);
184
+ return "would-install";
185
+ }
186
+ await mkdir(dirname(destination), { recursive: true });
187
+ await writeFile(destination, source);
188
+ log(`skill ${client.label}: installed`);
189
+ return "installed";
190
+ }
191
+
192
+ async function mcpAlreadyRegistered(client, options) {
193
+ if (options.dryRun) return false;
194
+ const binary = onPath(client.binary);
195
+ if (!binary) return false;
196
+ try {
197
+ await run(binary, ["mcp", "get", MCP_NAME], { timeout: CLIENT_TIMEOUT_MS });
198
+ return true;
199
+ } catch {
200
+ return false;
201
+ }
202
+ }
203
+
204
+ async function registerMcp(client, options, log, warn) {
205
+ const binary = onPath(client.binary);
206
+ if (!binary) {
207
+ log(`mcp ${client.label}: skipped (no ${client.binary} found)`);
208
+ return "skipped";
209
+ }
210
+ if (await mcpAlreadyRegistered(client, options)) {
211
+ log(`mcp ${client.label}: already registered`);
212
+ return "unchanged";
213
+ }
214
+
215
+ const args =
216
+ client.id === "claude"
217
+ ? ["mcp", "add", "-s", "user", MCP_NAME, "--", process.execPath, serverEntry]
218
+ : ["mcp", "add", MCP_NAME, "--", process.execPath, serverEntry];
219
+
220
+ if (options.dryRun) {
221
+ log(`mcp ${client.label}: would run ${client.binary} ${args.join(" ")}`);
222
+ return "would-register";
223
+ }
224
+ try {
225
+ await run(binary, args, { timeout: CLIENT_TIMEOUT_MS });
226
+ log(`mcp ${client.label}: registered`);
227
+ return "registered";
228
+ } catch (error) {
229
+ warn(
230
+ `mcp ${client.label}: registration failed (${error.message.split("\n")[0]}) ` +
231
+ `- run "codex-supervisor-setup" once ${client.label} is working`
232
+ );
233
+ return "failed";
234
+ }
235
+ }
236
+
237
+ async function main() {
238
+ const options = parseArgs(process.argv.slice(2));
239
+
240
+ if (options.help) {
241
+ printHelp();
242
+ return 0;
243
+ }
244
+
245
+ if (options.auto) {
246
+ if (process.env.CODEX_SUPERVISOR_SKIP_SETUP) {
247
+ return 0;
248
+ }
249
+ if (process.env.npm_config_global !== "true") {
250
+ return 0;
251
+ }
252
+ }
253
+
254
+ const log = options.quiet ? () => {} : (line) => console.log(line);
255
+ const warn = (line) => console.error(line);
256
+ const clients = selectClients(options);
257
+
258
+ if (clients.length === 0) {
259
+ log("setup: no Claude Code / Codex client detected; nothing to do");
260
+ return 0;
261
+ }
262
+
263
+ log(`setup: ${options.dryRun ? "dry run against" : "configuring"} ${clients.map((client) => client.label).join(", ")}`);
264
+
265
+ if (options.skills) {
266
+ for (const client of clients) {
267
+ await installSkill(client, options, log);
268
+ }
269
+ }
270
+ if (options.mcp) {
271
+ for (const client of clients.filter((client) => client.binary)) {
272
+ await registerMcp(client, options, log, warn);
273
+ }
274
+ }
275
+
276
+ log("setup: done");
277
+ return 0;
278
+ }
279
+
280
+ try {
281
+ process.exitCode = await main();
282
+ } catch (error) {
283
+ const message = `setup: ${error.message}`;
284
+ if (process.argv.includes("--auto")) {
285
+ console.error(`${message} (ignored)`);
286
+ } else {
287
+ console.error(message);
288
+ process.exitCode = 1;
289
+ }
290
+ }
package/src/status.js ADDED
@@ -0,0 +1,37 @@
1
+ // Single source of truth for the work state machine.
2
+ //
3
+ // status = lifecycle. One value per work, never overwritten by progress.
4
+ // phase = what the worker is doing right now. Only meaningful while
5
+ // status === "running"; NULL once the work reaches a terminal status.
6
+
7
+ export const TASK_STATUSES = ["queued", "running", "completed", "failed", "cancelled", "lost"];
8
+
9
+ export const PHASES = ["starting", "thinking", "command", "editing", "reporting"];
10
+
11
+ export const ACTIVE_STATUSES = new Set(["queued", "running"]);
12
+
13
+ export const TERMINAL_STATUSES = new Set(["completed", "failed", "cancelled", "lost"]);
14
+
15
+ // Codex native thread goal status -> work status.
16
+ // Storage uses snake_case ("usage_limited"); the RPC layer uses camelCase
17
+ // ("usageLimited"). mapGoalStatus accepts either.
18
+ const GOAL_STATUS_MAP = new Map([
19
+ ["active", "running"],
20
+ ["paused", "running"],
21
+ ["blocked", "running"],
22
+ ["usagelimited", "failed"],
23
+ ["budgetlimited", "failed"],
24
+ ["complete", "completed"]
25
+ ]);
26
+
27
+ export function mapGoalStatus(nativeStatus) {
28
+ if (!nativeStatus) return null;
29
+ const key = String(nativeStatus).replace(/_/g, "").toLowerCase();
30
+ return GOAL_STATUS_MAP.get(key) ?? null;
31
+ }
32
+
33
+ // A goal that is not finished but is not progressing on its own.
34
+ export function isGoalNeedingAttention(nativeStatus) {
35
+ const key = String(nativeStatus ?? "").replace(/_/g, "").toLowerCase();
36
+ return key === "blocked" || key === "paused";
37
+ }