codex-supervisor-mcp 0.13.5 → 0.14.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.
Files changed (109) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/package.json +19 -63
  4. package/skills/codex-supervisor/SKILL.md +5 -4
  5. package/src/{acceptance.js → app/acceptance.js} +54 -68
  6. package/src/app/auto-cleanup.js +90 -0
  7. package/src/app/cancel.js +60 -0
  8. package/src/app/cleanup-facts.js +96 -0
  9. package/src/app/cleanup-plan.js +164 -0
  10. package/src/app/compose.js +7 -0
  11. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  12. package/src/app/dispatch.js +396 -0
  13. package/src/app/followup.js +98 -0
  14. package/src/app/land-chain.js +133 -0
  15. package/src/app/landing.js +357 -0
  16. package/src/app/ownership.js +57 -0
  17. package/src/app/rebase.js +216 -0
  18. package/src/app/restore-worktree.js +50 -0
  19. package/src/app/resume.js +181 -0
  20. package/src/app/run-state.js +26 -0
  21. package/src/app/settled.js +28 -0
  22. package/src/{side-chat.js → app/side-chat.js} +82 -265
  23. package/src/app/sse.js +20 -0
  24. package/src/app/start-run.js +77 -0
  25. package/src/app/verify-push.js +114 -0
  26. package/src/app/worktree-setup.js +176 -0
  27. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  28. package/src/domain/acceptance-spec.js +30 -0
  29. package/src/domain/cleanup-policy.js +44 -0
  30. package/src/domain/command-outcome.js +6 -0
  31. package/src/{overview-delta.js → domain/overview-delta.js} +7 -3
  32. package/src/domain/side-turn-view.js +73 -0
  33. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  34. package/src/{cleanup-hint.js → infra/cleanup-hint.js} +7 -8
  35. package/src/infra/git.js +30 -0
  36. package/src/infra/process.js +59 -0
  37. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  38. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  39. package/src/infra/store/db.js +265 -0
  40. package/src/infra/store/events.js +146 -0
  41. package/src/infra/store/facts.js +338 -0
  42. package/src/infra/store/reconcile.js +172 -0
  43. package/src/infra/store/records.js +171 -0
  44. package/src/infra/store/runner-readers.js +16 -0
  45. package/src/infra/store/schema.js +306 -0
  46. package/src/infra/store/sessions.js +138 -0
  47. package/src/infra/store/tasks.js +337 -0
  48. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  49. package/src/{auto-update.js → infra/update/auto-update.js} +3 -3
  50. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  51. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  52. package/src/{worktree.js → infra/worktree.js} +56 -41
  53. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  54. package/src/{cleanup.js → interface/bin/cleanup.js} +4 -3
  55. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  56. package/src/{setup.js → interface/bin/setup.js} +7 -6
  57. package/src/{stage.js → interface/bin/stage.js} +1 -1
  58. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  59. package/src/interface/mcp/meta.js +7 -0
  60. package/src/interface/mcp/result.js +34 -0
  61. package/src/interface/mcp/schemas.js +24 -0
  62. package/src/interface/mcp/server.js +94 -0
  63. package/src/interface/mcp/tools/delivery.js +197 -0
  64. package/src/interface/mcp/tools/dispatch.js +267 -0
  65. package/src/interface/mcp/tools/facts.js +239 -0
  66. package/src/interface/mcp/tools/overview.js +202 -0
  67. package/src/interface/mcp/tools/poll.js +58 -0
  68. package/src/interface/mcp/tools/results.js +284 -0
  69. package/src/interface/mcp/tools/review.js +135 -0
  70. package/src/interface/mcp/tools/wait.js +145 -0
  71. package/src/interface/mcp/update-state.js +34 -0
  72. package/src/interface/mcp/views/overview.js +183 -0
  73. package/src/interface/mcp/views/task.js +223 -0
  74. package/src/interface/web/app.js +226 -0
  75. package/src/interface/web/views.js +224 -0
  76. package/src/mcp-server.js +3 -2223
  77. package/src/run-host/entry.js +23 -0
  78. package/src/run-host/finalize.js +236 -0
  79. package/src/run-host/launch.js +63 -0
  80. package/src/run-host/live-run.js +73 -0
  81. package/src/run-host/outcome-facts.js +61 -0
  82. package/src/run-host/streams.js +76 -0
  83. package/src/run-host/track.js +128 -0
  84. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  85. package/src/runners/codex/chat-chunks.js +97 -0
  86. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  87. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  88. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  89. package/src/cleanup-plan.js +0 -158
  90. package/src/codex-runner.js +0 -1586
  91. package/src/landing.js +0 -507
  92. package/src/task-store.js +0 -1800
  93. package/src/web-app.js +0 -425
  94. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  95. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  96. /package/src/{prompt.js → domain/prompt.js} +0 -0
  97. /package/src/{status.js → domain/status.js} +0 -0
  98. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  99. /package/src/{truncate.js → domain/truncate.js} +0 -0
  100. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  101. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  102. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  103. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  104. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  105. /package/src/{external-output.js → infra/external-output.js} +0 -0
  106. /package/src/{handoff.js → infra/handoff.js} +0 -0
  107. /package/src/{paths.js → infra/paths.js} +0 -0
  108. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  109. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
@@ -0,0 +1,223 @@
1
+ import { acceptanceVerdict } from "../../../app/acceptance.js";
2
+ import { classifyFailure } from "../../../domain/failure-class.js";
3
+ import { ACTIVE_STATUSES, isGoalNeedingAttention } from "../../../domain/status.js";
4
+ import { threadHealth } from "../../../domain/thread-health.js";
5
+ import { readStage } from "../../../infra/stage-store.js";
6
+ import { readTaskChanges } from "../../../infra/worktree.js";
7
+ import { summarizeVerification } from "../../../runners/codex/event-parser.js";
8
+ import { clip } from "../result.js";
9
+
10
+ // `current_action` is "Running <command>", and a command can be a heredoc that
11
+ // writes a whole file. Returning it whole put tens of thousands of characters
12
+ // into every wait response, which then blew past the client's MCP output cap
13
+ // and came back a second time as a notification. The full command stays in
14
+ // current_command / commands and is readable through get_codex_worker_events.
15
+ export const ACTION_PREVIEW_CHARS = 300;
16
+ const COMMAND_PREVIEW_CHARS = 300;
17
+ const COMMAND_TAIL = 20;
18
+ const PROMPT_PREVIEW_CHARS = 300;
19
+ // The single-worker status read is the drill-in for one worker, so its copy of
20
+ // the last message stays much larger than the overview's 400. The full report
21
+ // is still get_worker_result's job.
22
+ const STATUS_MESSAGE_CHARS = 4000;
23
+
24
+ // Codex emits nothing while a command runs and nothing while the model
25
+ // thinks, so a snapshot that has not moved for ten minutes looks the same
26
+ // either way. These three fields tell them apart: current_command is set
27
+ // from the command's item.started until its item.completed, so a long idle
28
+ // with a command is a long command, and a long idle without one is the model
29
+ // (or a stuck process, which reconcile turns into lost on its own).
30
+ const LIVE_COMMAND_PREVIEW_CHARS = 120;
31
+ export function liveness(task) {
32
+ if (!ACTIVE_STATUSES.has(task.status)) {
33
+ const stage = readStage(task.id);
34
+ return {
35
+ idle_seconds: null,
36
+ command_running: false,
37
+ current_command: null,
38
+ current_stage: null,
39
+ current_stage_detail: null,
40
+ last_stage: stage?.stage ?? null,
41
+ stage_updated_at: stage?.updated_at ?? null
42
+ };
43
+ }
44
+ const since = Date.parse(task.last_event_at ?? task.started_at ?? "");
45
+ const idle = Number.isFinite(since) ? Math.max(0, Math.floor((Date.now() - since) / 1000)) : null;
46
+ const command = task.current_command ? clip(task.current_command, LIVE_COMMAND_PREVIEW_CHARS) : null;
47
+ const stage = readStage(task.id);
48
+ const active = ACTIVE_STATUSES.has(task.status);
49
+ return {
50
+ idle_seconds: idle,
51
+ command_running: Boolean(task.current_command),
52
+ current_command: command,
53
+ current_stage: active ? stage?.stage ?? null : null,
54
+ current_stage_detail: active ? stage?.detail ?? null : null,
55
+ last_stage: active ? null : stage?.stage ?? null,
56
+ stage_updated_at: stage?.updated_at ?? null
57
+ };
58
+ }
59
+
60
+ export function compactLiveness(task) {
61
+ const live = liveness(task);
62
+ return {
63
+ idle_seconds: live.idle_seconds,
64
+ command_running: live.command_running,
65
+ current_command: live.current_command,
66
+ ...(live.current_stage ? { current_stage: live.current_stage } : {}),
67
+ ...(live.current_stage_detail ? { current_stage_detail: live.current_stage_detail } : {}),
68
+ ...(live.last_stage ? { last_stage: live.last_stage } : {}),
69
+ ...(live.stage_updated_at ? { stage_updated_at: live.stage_updated_at } : {})
70
+ };
71
+ }
72
+
73
+ // The acceptance verdict as get_worker_result reports it, with the one
74
+ // contradiction a tool can see spelled out: checks passed, worker says
75
+ // otherwise (the "it was never built" case, where it was).
76
+ export function acceptanceView(task, behind) {
77
+ const configured = Array.isArray(task.acceptance) && task.acceptance.length > 0;
78
+ const results = task.acceptance_results ?? null;
79
+ const view = {
80
+ configured,
81
+ commands: configured ? task.acceptance : [],
82
+ status: results?.status ?? null,
83
+ passed: results?.passed ?? null,
84
+ run: results?.run ?? null,
85
+ checks: results?.checks ?? [],
86
+ error: results?.error ?? null,
87
+ // Drift matters only before the work is landed: once it is on the
88
+ // branch, the branch having moved is expected.
89
+ stale: Boolean(results && behind && behind.behind > 0 && !(task.landed_at && task.landed_at >= (results.finished_at ?? ""))),
90
+ next_step: null
91
+ };
92
+ if (!configured) return view;
93
+ if (view.status === "failed") {
94
+ const failing = view.checks.find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out) ?? null;
95
+ view.next_step = failing
96
+ ? `acceptance failed: ${clip(failing.command, 120)} failed ${failing.error ?? (failing.baseline?.passed === false ? "baseline/evidence mismatch" : failing.timed_out ? "by timeout" : `exit ${failing.exit_code}`)}; resume the worker with checks[].output_tail in the prompt, or fix it yourself. Do not land until it passes.`
97
+ : `acceptance could not run (${view.error ?? "unknown"}); fix that first`;
98
+ } else if (view.status === "passed") {
99
+ const verification = summarizeVerification(task);
100
+ const workerSaysNo = task.status === "failed" || isGoalNeedingAttention(task.goal_status) || verification.last_command_failed;
101
+ if (workerSaysNo) view.next_step = "the checks passed but the worker reports otherwise; trust the checks and read the diff";
102
+ else if (view.stale) view.next_step = "the checks passed on the old base and the project has moved since; resume with rebaseOnto to re-run them on current code before landing";
103
+ } else if (view.status === "running") {
104
+ view.next_step = "acceptance is still running in the supervisor; wait_codex_workers returns when it is done";
105
+ } else if (view.status === "interrupted") {
106
+ view.next_step = "the supervisor exited while running acceptance; resume the worker (or cancel and redispatch) to run it again";
107
+ } else if (view.status === "cancelled") {
108
+ view.next_step = "acceptance was cancelled; resume the worker to run it again";
109
+ } else if (view.status === null) {
110
+ view.next_step = "acceptance has not run yet for this worker";
111
+ }
112
+ return view;
113
+ }
114
+
115
+ export function summarizeTask(task) {
116
+ return {
117
+ id: task.id,
118
+ title: task.title,
119
+ worker: task.worker,
120
+ status: task.status,
121
+ phase: task.phase ?? null,
122
+ cwd: task.cwd,
123
+ project_root: task.project_root,
124
+ workspace_kind: task.workspace_kind ?? "legacy",
125
+ sandbox: task.sandbox,
126
+ model: task.model,
127
+ reasoning_effort: task.reasoning_effort ?? "high",
128
+ thread_id: task.thread_id,
129
+ followup_of: task.followup_of,
130
+ resumed_from: task.resumed_from,
131
+ depends_on: task.depends_on ?? [],
132
+ owned_paths: task.owned_paths ?? [],
133
+ worktree_path: task.worktree_path,
134
+ goal_objective: task.goal_objective,
135
+ goal_token_budget: task.goal_token_budget,
136
+ goal_status: task.goal_status,
137
+ goal_tokens_used: task.goal_tokens_used ?? null,
138
+ thread_health: threadHealth(task),
139
+ attention_reason: task.attention_reason ?? null,
140
+ failure: classifyFailure(task),
141
+ changed_file_count: (task.changed_files ?? []).length,
142
+ command_count: (task.commands ?? []).length,
143
+ run_count: task.run_count ?? 0,
144
+ acceptance: acceptanceVerdict(task),
145
+ landed_at: task.landed_at ?? null,
146
+ current_action: clip(task.current_action, ACTION_PREVIEW_CHARS),
147
+ ...liveness(task),
148
+ last_event_at: task.last_event_at ?? null,
149
+ last_event_type: task.last_event_type,
150
+ last_message: clip(task.last_message, 400),
151
+ notices: clip(task.notices, 400),
152
+ error: task.error,
153
+ created_at: task.created_at,
154
+ updated_at: task.updated_at,
155
+ started_at: task.started_at,
156
+ completed_at: task.completed_at,
157
+ exit_code: task.exit_code
158
+ };
159
+ }
160
+
161
+ // The status read used to hand back the stored row verbatim. For a follow-up
162
+ // worker that row carries the parent prompt plus the whole command history and
163
+ // the events folded into it; one real call returned 180k characters, past the
164
+ // client's MCP output cap, so the reply landed on disk and had to be grepped.
165
+ // This is the same status surface the other reads use, plus explicitly bounded
166
+ // extras. includePrompt is the escape hatch for the full task text.
167
+ export function statusView(task, { includePrompt, promptMaxChars }) {
168
+ const promptText = task.prompt ?? null;
169
+ const promptBudget = includePrompt ? promptMaxChars : PROMPT_PREVIEW_CHARS;
170
+ const commands = (task.commands ?? []).slice(-COMMAND_TAIL);
171
+ return {
172
+ ...summarizeTask(task),
173
+ last_message: clip(task.last_message, STATUS_MESSAGE_CHARS),
174
+ session_id: task.session_id ?? null,
175
+ pid: task.pid ?? null,
176
+ run_log: task.run_log ?? null,
177
+ base_commit: task.base_commit ?? null,
178
+ changed_files: readTaskChanges(task),
179
+ current_command: clip(task.current_command, COMMAND_PREVIEW_CHARS),
180
+ commands: commands.map((entry) => ({ ...entry, command: clip(entry.command, COMMAND_PREVIEW_CHARS) })),
181
+ prompt: clip(promptText, promptBudget),
182
+ prompt_truncated: Boolean(promptText) && String(promptText).length > promptBudget
183
+ };
184
+ }
185
+
186
+ // The dispatch receipt. Dispatch used to return the whole task record, which
187
+ // echoes the task text - and for a follow-up, the parent prompt plus 20 raw
188
+ // events - back to the caller on every call. Dispatching eleven workers made
189
+ // the main thread pay for its own instructions eleven times, and pushed the
190
+ // result into the client's MCP output cap. Read the rest per worker with
191
+ // get_worker_summary / get_worker_result when you actually need it.
192
+ export function receipt(task) {
193
+ return {
194
+ id: task.id,
195
+ title: task.title,
196
+ worker: task.worker,
197
+ status: task.status,
198
+ phase: task.phase ?? null,
199
+ cwd: task.cwd,
200
+ project_root: task.project_root,
201
+ workspace_kind: task.workspace_kind ?? "legacy",
202
+ worktree_path: task.worktree_path,
203
+ branch: task.worktree_path ? `codex/${task.id}` : null,
204
+ base_commit: task.base_commit ?? null,
205
+ sandbox: task.sandbox,
206
+ model: task.model,
207
+ reasoning_effort: task.reasoning_effort,
208
+ thread_id: task.thread_id,
209
+ session_id: task.session_id ?? null,
210
+ followup_of: task.followup_of,
211
+ resumed_from: task.resumed_from,
212
+ depends_on: task.depends_on ?? [],
213
+ owned_paths: task.owned_paths ?? [],
214
+ goal_objective: task.goal_objective,
215
+ goal_token_budget: task.goal_token_budget,
216
+ error: task.error ?? null,
217
+ failure: classifyFailure(task),
218
+ run_count: task.run_count ?? 0,
219
+ run_log: task.run_log,
220
+ created_at: task.created_at,
221
+ updated_at: task.updated_at
222
+ };
223
+ }
@@ -0,0 +1,226 @@
1
+ // The board's HTTP server: a thin read-only view over the supervisor store.
2
+ // Which sessions exist, what each one is doing right now, what every Codex
3
+ // thread under a session has done. It reads the same SQLite file the MCP
4
+ // server writes and never writes to it, apart from the same orphan
5
+ // reconcile every read does. web-server.js is the entry that decides which
6
+ // store to open and then calls startWebServer().
7
+ import "../../app/compose.js";
8
+ import { attachToTurn, endSideSession, runSideTurn, sideSessionState, stopSideTurn } from "../../app/side-chat.js";
9
+ import { supervisorRoot } from "../../infra/paths.js";
10
+ import { getTask } from "../../infra/store/tasks.js";
11
+ import { checkForUpdate } from "../../infra/update/update-check.js";
12
+ import { events, overview, pageParams, session, worker } from "./views.js";
13
+ import { createReadStream, existsSync, statSync } from "node:fs";
14
+ import { createServer } from "node:http";
15
+ import { extname, join, normalize, resolve } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+
18
+ const here = fileURLToPath(new URL(".", import.meta.url));
19
+ const distDir = resolve(here, "..", "..", "..", "web", "dist");
20
+ const port = Number(process.env.SUPERVISOR_WEB_PORT ?? 7877);
21
+ const host = process.env.SUPERVISOR_WEB_HOST ?? "127.0.0.1";
22
+
23
+ const MIME = {
24
+ ".html": "text/html; charset=utf-8",
25
+ ".js": "text/javascript; charset=utf-8",
26
+ ".css": "text/css; charset=utf-8",
27
+ ".json": "application/json; charset=utf-8",
28
+ ".svg": "image/svg+xml",
29
+ ".woff2": "font/woff2",
30
+ ".woff": "font/woff",
31
+ ".png": "image/png",
32
+ ".ico": "image/x-icon"
33
+ };
34
+
35
+ // Read a JSON request body, capped so a stray client cannot fill memory.
36
+ function readJson(req, limit = 2 * 1024 * 1024) {
37
+ return new Promise((resolve, reject) => {
38
+ let size = 0;
39
+ const chunks = [];
40
+ req.on("data", (chunk) => {
41
+ size += chunk.length;
42
+ if (size > limit) {
43
+ reject(Object.assign(new Error("request body too large"), { code: "too_large" }));
44
+ req.destroy();
45
+ return;
46
+ }
47
+ chunks.push(chunk);
48
+ });
49
+ req.on("end", () => {
50
+ const text = Buffer.concat(chunks).toString("utf8");
51
+ if (!text.trim()) return resolve({});
52
+ try {
53
+ resolve(JSON.parse(text));
54
+ } catch (error) {
55
+ reject(Object.assign(new Error(`invalid JSON body: ${error.message}`), { code: "bad_json" }));
56
+ }
57
+ });
58
+ req.on("error", reject);
59
+ });
60
+ }
61
+
62
+ // The last user message of an AI SDK useChat request, as plain text.
63
+ function lastUserText(body) {
64
+ if (typeof body?.text === "string") return body.text;
65
+ const messages = Array.isArray(body?.messages) ? body.messages : [];
66
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
67
+ const m = messages[i];
68
+ if (m?.role !== "user") continue;
69
+ const parts = Array.isArray(m.parts) ? m.parts : [];
70
+ const text = parts.filter((p) => p?.type === "text").map((p) => p.text ?? "").join("\n").trim();
71
+ if (text) return text;
72
+ if (typeof m.content === "string" && m.content.trim()) return m.content.trim();
73
+ }
74
+ return "";
75
+ }
76
+
77
+ function json(res, status, body) {
78
+ const text = JSON.stringify(body);
79
+ res.writeHead(status, {
80
+ "content-type": "application/json; charset=utf-8",
81
+ "cache-control": "no-store",
82
+ "content-length": Buffer.byteLength(text)
83
+ });
84
+ res.end(text);
85
+ }
86
+
87
+ function serveStatic(res, pathname) {
88
+ if (!existsSync(distDir)) {
89
+ res.writeHead(503, { "content-type": "text/plain; charset=utf-8" });
90
+ res.end("web/dist is missing. Run `npm run web:build` first.\n");
91
+ return;
92
+ }
93
+ const safe = normalize(pathname).replace(/^(\.\.[/\\])+/, "");
94
+ let file = join(distDir, safe);
95
+ if (!file.startsWith(distDir)) {
96
+ res.writeHead(403);
97
+ res.end();
98
+ return;
99
+ }
100
+ if (!existsSync(file) || statSync(file).isDirectory()) file = join(distDir, "index.html");
101
+ const type = MIME[extname(file)] ?? "application/octet-stream";
102
+ res.writeHead(200, {
103
+ "content-type": type,
104
+ "cache-control": file.endsWith("index.html") ? "no-store" : "public, max-age=31536000, immutable"
105
+ });
106
+ createReadStream(file).pipe(res);
107
+ }
108
+
109
+ const LOOPBACK_NAMES = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
110
+
111
+ // A page on another site can send a POST here without a CORS preflight, and a
112
+ // rebound DNS name can make its origin look local. A browser request that
113
+ // changes something must come from the board's own origin, and when the board
114
+ // listens on loopback that origin must be a loopback name. Clients that send
115
+ // no Origin (curl, the tests) are not browsers and are let through.
116
+ function crossSiteRefusal(req) {
117
+ if (req.method === "GET" || req.method === "HEAD") return null;
118
+ const origin = req.headers.origin;
119
+ if (!origin) return null;
120
+ let parsed;
121
+ try {
122
+ parsed = new URL(origin);
123
+ } catch {
124
+ return "the Origin header is not a URL";
125
+ }
126
+ if (parsed.host !== req.headers.host) return "the request comes from another origin";
127
+ if (LOOPBACK_NAMES.has(host) && !LOOPBACK_NAMES.has(parsed.hostname)) return "the board listens on loopback and the origin is not a loopback name";
128
+ return null;
129
+ }
130
+
131
+ async function route(req, res) {
132
+ const url = new URL(req.url ?? "/", `http://${host}`);
133
+ const parts = url.pathname.split("/").filter(Boolean);
134
+ if (parts[0] !== "api") return serveStatic(res, url.pathname);
135
+ const refusal = crossSiteRefusal(req);
136
+ if (refusal) return json(res, 403, { error: "cross_origin_refused", message: refusal });
137
+
138
+ // The side chat is the one place the board does something: it forks the
139
+ // worker's Codex thread for a read-only side question.
140
+ if (parts[1] === "workers" && parts.length >= 4 && parts[3] === "chat") {
141
+ const taskId = decodeURIComponent(parts[2]);
142
+ const task = await getTask(taskId);
143
+ if (!task) return json(res, 404, { error: "task_not_found" });
144
+ const action = parts[4] ?? null;
145
+ // GET .../chat/<chatId>/stream is what the AI SDK client calls to
146
+ // resume: replay the running turn, or 204 when nothing is running.
147
+ if (req.method === "GET" && parts.length === 6 && parts[5] === "stream") {
148
+ attachToTurn(taskId, res);
149
+ return undefined;
150
+ }
151
+ if (req.method === "GET" && !action) return json(res, 200, { task_id: taskId, can_ask: Boolean(task.thread_id), worker_status: task.status, ...(await sideSessionState(taskId)) });
152
+ if (req.method === "DELETE" && !action) return json(res, 200, { task_id: taskId, ...(await endSideSession(taskId)) });
153
+ if (req.method === "POST" && action === "stop") return json(res, 200, { task_id: taskId, ...stopSideTurn(taskId) });
154
+ if (req.method === "POST" && !action) {
155
+ let body;
156
+ try {
157
+ body = await readJson(req);
158
+ } catch (error) {
159
+ return json(res, 400, { error: error.code ?? "bad_request", message: error.message });
160
+ }
161
+ const text = lastUserText(body);
162
+ if (!text) return json(res, 400, { error: "empty_question", message: "send a user message with text" });
163
+ try {
164
+ await runSideTurn({ task, text, res });
165
+ } catch (error) {
166
+ if (res.headersSent) return undefined;
167
+ const status = error.code === "busy" ? 409 : error.code === "no_thread" ? 400 : error.code === "codex_missing" ? 503 : 500;
168
+ return json(res, status, { error: error.code ?? "side_chat_failed", message: error.message });
169
+ }
170
+ return undefined;
171
+ }
172
+ return json(res, 405, { error: "method_not_allowed" });
173
+ }
174
+
175
+ if (req.method !== "GET") return json(res, 405, { error: "method_not_allowed" });
176
+
177
+ if (parts[1] === "overview" && parts.length === 2) return json(res, 200, await overview(pageParams(url, 20)));
178
+ if (parts[1] === "version" && parts.length === 2) {
179
+ return json(res, 200, await checkForUpdate({ force: url.searchParams.get("force") === "1" }));
180
+ }
181
+ if (parts[1] === "sessions" && parts.length === 3) {
182
+ const body = await session(decodeURIComponent(parts[2]), pageParams(url, 40));
183
+ return body ? json(res, 200, body) : json(res, 404, { error: "session_not_found" });
184
+ }
185
+ if (parts[1] === "workers" && parts.length === 3) {
186
+ const body = await worker(decodeURIComponent(parts[2]));
187
+ return body ? json(res, 200, body) : json(res, 404, { error: "task_not_found" });
188
+ }
189
+ if (parts[1] === "workers" && parts.length === 4 && parts[3] === "events") {
190
+ const taskId = decodeURIComponent(parts[2]);
191
+ if (!(await getTask(taskId))) return json(res, 404, { error: "task_not_found" });
192
+ return json(res, 200, await events(taskId, url));
193
+ }
194
+ return json(res, 404, { error: "not_found" });
195
+ }
196
+
197
+ export function startWebServer({ storeOrigin = "default" } = {}) {
198
+ const server = createServer((req, res) => {
199
+ route(req, res).catch((error) => {
200
+ process.stderr.write(`[codex-supervisor-web] ${error.stack ?? error.message}\n`);
201
+ if (!res.headersSent) json(res, 500, { error: "internal", message: error.message });
202
+ else res.end();
203
+ });
204
+ });
205
+
206
+ // A taken port is the one error a person will actually hit, usually because
207
+ // a board is already running. Say that, not a stack trace.
208
+ server.on("error", (error) => {
209
+ if (error.code === "EADDRINUSE") {
210
+ process.stderr.write(
211
+ `codex-supervisor-web: port ${port} on ${host} is already in use.\n` +
212
+ ` A board may already be running at http://${host}:${port}\n` +
213
+ ` To run a second one, pick another port: SUPERVISOR_WEB_PORT=8080 codex-supervisor-web\n`
214
+ );
215
+ process.exit(1);
216
+ }
217
+ process.stderr.write(`codex-supervisor-web: ${error.message}\n`);
218
+ process.exit(1);
219
+ });
220
+
221
+ server.listen(port, host, () => {
222
+ const boundPort = server.address().port;
223
+ process.stdout.write(`codex-supervisor web view on http://${host}:${boundPort}\n store: ${supervisorRoot} (${storeOrigin})\n`);
224
+ });
225
+ return server;
226
+ }
@@ -0,0 +1,224 @@
1
+ // What the board shows: session and worker rows built from the store, read-only.
2
+ import { ACTIVE_STATUSES } from "../../domain/status.js";
3
+ import { supervisorRoot } from "../../infra/paths.js";
4
+ import { listTaskEventKinds, readAgentMessages, readTaskEvents } from "../../infra/store/events.js";
5
+ import { reconcileDetachedActiveTasks } from "../../infra/store/reconcile.js";
6
+ import { readSessions } from "../../infra/store/sessions.js";
7
+ import { getTask, readTasks } from "../../infra/store/tasks.js";
8
+ import { readTaskChanges } from "../../infra/worktree.js";
9
+ import { readNativeGoal } from "../../runners/codex/goal-store.js";
10
+
11
+ const NO_SESSION = "none";
12
+
13
+ function clip(value, maxChars) {
14
+ if (value === null || value === undefined) return null;
15
+ const text = String(value);
16
+ return text.length <= maxChars ? text : `${text.slice(0, maxChars)}…`;
17
+ }
18
+
19
+ function durationMs(task) {
20
+ const start = Date.parse(task.started_at ?? task.created_at ?? "");
21
+ if (Number.isNaN(start)) return null;
22
+ const end = Date.parse(task.completed_at ?? "");
23
+ const stop = Number.isNaN(end) ? Date.now() : end;
24
+ return Math.max(0, stop - start);
25
+ }
26
+
27
+ // The row every list shows. No prompt, no raw events: those are per-worker
28
+ // reads, so a session with forty threads stays one cheap request.
29
+ function workerRow(task) {
30
+ return {
31
+ id: task.id,
32
+ title: task.title,
33
+ status: task.status,
34
+ phase: task.phase ?? null,
35
+ session_id: task.session_id ?? null,
36
+ thread_id: task.thread_id ?? null,
37
+ goal: task.goal_objective ?? null,
38
+ goal_status: task.goal_status ?? null,
39
+ model: task.model ?? null,
40
+ sandbox: task.sandbox,
41
+ project_root: task.project_root,
42
+ worktree_path: task.worktree_path ?? null,
43
+ branch: task.worktree_path ? `codex/${task.id}` : null,
44
+ base_commit: task.base_commit ?? null,
45
+ owned_paths: task.owned_paths ?? [],
46
+ depends_on: task.depends_on ?? [],
47
+ followup_of: task.followup_of ?? null,
48
+ resumed_from: task.resumed_from ?? null,
49
+ run_count: task.run_count ?? 0,
50
+ current_action: clip(task.current_action, 300),
51
+ last_message: clip(task.last_message, 400),
52
+ changed_file_count: liveChangeCount(task),
53
+ acceptance: task.acceptance_results?.status ?? null,
54
+ landed_at: task.landed_at ?? null,
55
+ command_count: (task.commands ?? []).length,
56
+ error: task.error ?? null,
57
+ exit_code: task.exit_code ?? null,
58
+ pid: task.pid ?? null,
59
+ created_at: task.created_at || null,
60
+ started_at: task.started_at || null,
61
+ updated_at: task.updated_at || null,
62
+ completed_at: task.completed_at || null,
63
+ duration_ms: durationMs(task)
64
+ };
65
+ }
66
+
67
+ // Changed-file counts for the list. The stored changed_files on a row only
68
+ // knows about file_change events; the truth is the worktree diff, which costs
69
+ // two git calls per worker. Terminal rows never change again, so their count
70
+ // is memoised on (id, updated_at); running rows are re-read every time.
71
+ const changeCountCache = new Map();
72
+ function liveChangeCount(task) {
73
+ const key = `${task.id}:${task.updated_at}:${task.status}`;
74
+ const cached = changeCountCache.get(key);
75
+ if (cached !== undefined && !ACTIVE_STATUSES.has(task.status)) return cached;
76
+ const count = readTaskChanges(task).length;
77
+ changeCountCache.set(key, count);
78
+ if (changeCountCache.size > 2000) changeCountCache.delete(changeCountCache.keys().next().value);
79
+ return count;
80
+ }
81
+
82
+ function sessionKey(task) {
83
+ return task.session_id || NO_SESSION;
84
+ }
85
+
86
+ function latest(values) {
87
+ return values.filter(Boolean).sort().at(-1) ?? null;
88
+ }
89
+
90
+ // What a session is about. The title the main thread recorded wins; without
91
+ // one, the goals of its workers are the next best description.
92
+ function aboutSession(meta, tasks) {
93
+ if (meta?.title) return { title: meta.title, note: meta.note ?? null, derived: false };
94
+ const goals = Array.from(new Set(tasks.map((task) => task.goal_objective).filter(Boolean)));
95
+ const summary = goals.slice(0, 3).map((goal) => clip(goal, 60)).join(";");
96
+ return { title: summary || null, note: null, derived: true };
97
+ }
98
+
99
+ function sessionRow(key, tasks, meta = null) {
100
+ const counts = {};
101
+ for (const task of tasks) counts[task.status] = (counts[task.status] ?? 0) + 1;
102
+ const active = tasks.filter((task) => ACTIVE_STATUSES.has(task.status));
103
+ const byActivity = [...tasks].sort((a, b) => String(b.updated_at ?? "").localeCompare(String(a.updated_at ?? "")));
104
+ const lastReport = byActivity.find((task) => task.last_message);
105
+ const about = aboutSession(meta, tasks);
106
+ return {
107
+ id: key,
108
+ unsessioned: key === NO_SESSION,
109
+ title: about.title,
110
+ note: about.note,
111
+ title_derived: about.derived,
112
+ worker_count: tasks.length,
113
+ active_count: active.length,
114
+ counts,
115
+ project_roots: Array.from(new Set(tasks.map((task) => task.project_root).filter(Boolean))),
116
+ first_created_at: tasks.map((task) => task.created_at).filter(Boolean).sort()[0] ?? null,
117
+ last_activity_at: latest(tasks.map((task) => task.updated_at)),
118
+ // What the session is doing right now: one line per running thread.
119
+ now: active.map((task) => ({
120
+ id: task.id,
121
+ title: task.title,
122
+ phase: task.phase ?? null,
123
+ current_action: clip(task.current_action, 160)
124
+ })),
125
+ last_report: lastReport
126
+ ? { id: lastReport.id, title: lastReport.title, text: clip(lastReport.last_message, 240), at: lastReport.updated_at }
127
+ : null
128
+ };
129
+ }
130
+
131
+ // Pagination for the lists: `limit` rows after `offset`, newest activity
132
+ // first for sessions, dispatch order for workers. The page says whether
133
+ // there is more so the board loads the rest as the user scrolls.
134
+ export function pageParams(url, defaultLimit) {
135
+ const limit = Math.min(200, Math.max(1, Number(url.searchParams.get("limit") ?? defaultLimit) || defaultLimit));
136
+ const offset = Math.max(0, Number(url.searchParams.get("offset") ?? 0) || 0);
137
+ return { limit, offset };
138
+ }
139
+
140
+ function paginate(items, { limit, offset }) {
141
+ return { items: items.slice(offset, offset + limit), total: items.length, offset, limit, has_more: offset + limit < items.length };
142
+ }
143
+
144
+ export async function overview({ limit, offset } = { limit: 20, offset: 0 }) {
145
+ await reconcileDetachedActiveTasks();
146
+ const tasks = await readTasks();
147
+ const metas = new Map((await readSessions()).map((row) => [row.id, row]));
148
+ const groups = new Map();
149
+ for (const task of tasks) {
150
+ const key = sessionKey(task);
151
+ if (!groups.has(key)) groups.set(key, []);
152
+ groups.get(key).push(task);
153
+ }
154
+ const sessions = Array.from(groups, ([key, group]) => sessionRow(key, group, metas.get(key) ?? null)).sort((a, b) => {
155
+ if (a.active_count !== b.active_count) return b.active_count - a.active_count;
156
+ return String(b.last_activity_at ?? "").localeCompare(String(a.last_activity_at ?? ""));
157
+ });
158
+ const page = paginate(sessions, { limit, offset });
159
+ return {
160
+ generated_at: new Date().toISOString(),
161
+ store: supervisorRoot,
162
+ total_workers: tasks.length,
163
+ active_workers: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
164
+ total_sessions: sessions.length,
165
+ offset: page.offset,
166
+ limit: page.limit,
167
+ has_more: page.has_more,
168
+ sessions: page.items
169
+ };
170
+ }
171
+
172
+ export async function session(key, { limit, offset } = { limit: 40, offset: 0 }) {
173
+ await reconcileDetachedActiveTasks();
174
+ const tasks = (await readTasks()).filter((task) => sessionKey(task) === key);
175
+ if (tasks.length === 0) return null;
176
+ const meta = (await readSessions()).find((row) => row.id === key) ?? null;
177
+ const ordered = [...tasks].sort((a, b) => String(a.created_at ?? "").localeCompare(String(b.created_at ?? "")));
178
+ const page = paginate(ordered, { limit, offset });
179
+ return {
180
+ ...sessionRow(key, tasks, meta),
181
+ offset: page.offset,
182
+ limit: page.limit,
183
+ has_more: page.has_more,
184
+ workers: page.items.map(workerRow)
185
+ };
186
+ }
187
+
188
+ export async function worker(taskId) {
189
+ const task = await getTask(taskId);
190
+ if (!task) return null;
191
+ const reports = await readAgentMessages(taskId, 10);
192
+ // Token spend comes from Codex's own turn.completed usage blocks; one per
193
+ // run, so a resumed worker sums its runs.
194
+ const usage = { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, reasoning_output_tokens: 0, turns: 0 };
195
+ for (const event of await readTaskEvents(taskId, 50, ["turn.completed"])) {
196
+ const block = event?.usage ?? {};
197
+ usage.turns += 1;
198
+ for (const key of ["input_tokens", "cached_input_tokens", "output_tokens", "reasoning_output_tokens"]) {
199
+ usage[key] += Number(block[key] ?? 0) || 0;
200
+ }
201
+ }
202
+ const commands = (task.commands ?? []).slice(-40).map((entry) => ({
203
+ ...entry,
204
+ command: clip(entry.command, 600)
205
+ }));
206
+ return {
207
+ ...workerRow(task),
208
+ prompt: task.prompt ?? null,
209
+ changed_files: readTaskChanges(task),
210
+ commands,
211
+ reports: reports.length > 0 ? reports : task.last_message ? [task.last_message] : [],
212
+ native_goal: readNativeGoal(task.thread_id),
213
+ usage,
214
+ notices: task.notices ?? null,
215
+ run_log: task.run_log ?? null,
216
+ event_kinds: await listTaskEventKinds(taskId)
217
+ };
218
+ }
219
+
220
+ export async function events(taskId, url) {
221
+ const limit = Math.min(1000, Math.max(1, Number(url.searchParams.get("limit") ?? 150)));
222
+ const kinds = url.searchParams.get("kinds")?.split(",").filter(Boolean) ?? null;
223
+ return { task_id: taskId, events: await readTaskEvents(taskId, limit, kinds) };
224
+ }