codex-supervisor-mcp 0.5.7 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-supervisor-mcp",
3
- "version": "0.5.7",
3
+ "version": "0.5.9",
4
4
  "type": "module",
5
5
  "description": "MCP server that dispatches and supervises parallel Codex CLI workers, one isolated Git worktree each, with a persisted work state machine.",
6
6
  "license": "MIT",
@@ -43,6 +43,7 @@
43
43
  "src/cleanup.js",
44
44
  "src/monitor.jsx",
45
45
  "src/web-server.js",
46
+ "src/web-app.js",
46
47
  "src/update-check.js",
47
48
  "web/dist/",
48
49
  "skills/",
package/src/mcp-server.js CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  readTasks,
21
21
  readTasksBySession,
22
22
  reconcileDetachedActiveTasks,
23
+ recordTerminalChangedFiles,
23
24
  searchTasks,
24
25
  upsertSession,
25
26
  upsertTask
@@ -771,8 +772,10 @@ server.registerTool(
771
772
  const task = await getTask(task_id);
772
773
  if (!task) return textResult({ error: "task_not_found", task_id });
773
774
  const summary = buildWorkerSummary(task, readNativeGoal(task.thread_id));
774
- if (summary.changed_files.length !== (task.changed_files ?? []).length) {
775
- await upsertTask({ ...task, changed_files: summary.changed_files, updated_at: new Date().toISOString() });
775
+ // Cache the worktree diff on the row once the worker is done, so the
776
+ // overview's count stops lagging. A running row is the runner's to write.
777
+ if (TERMINAL_STATUSES.has(task.status) && summary.changed_files.length !== (task.changed_files ?? []).length) {
778
+ await recordTerminalChangedFiles(task.id, summary.changed_files);
776
779
  }
777
780
  return textResult(summary);
778
781
  }
package/src/task-store.js CHANGED
@@ -3,7 +3,7 @@ import { join } from "node:path";
3
3
  import { DatabaseSync } from "node:sqlite";
4
4
  import { dataDir, dbPath, runsDir } from "./paths.js";
5
5
  import { extractAgentMessage } from "./event-parser.js";
6
- import { ACTIVE_STATUSES, PHASES } from "./status.js";
6
+ import { ACTIVE_STATUSES, PHASES, TERMINAL_STATUSES } from "./status.js";
7
7
 
8
8
  let db;
9
9
 
@@ -395,6 +395,20 @@ export async function readTasksBySession(sessionId) {
395
395
  return rows.map(rowToTask);
396
396
  }
397
397
 
398
+ // Record the files a terminal worker changed, and nothing else. The summary
399
+ // read used to upsert the whole row, which on a running worker put stale
400
+ // copies of every live field (phase, current_action, exit_code) back over
401
+ // what the runner had just written. A terminal row has no writer left, and
402
+ // even then only this one column is touched.
403
+ export async function recordTerminalChangedFiles(taskId, changedFiles) {
404
+ await ensureFilesystem();
405
+ const terminal = Array.from(TERMINAL_STATUSES).map((s) => `'${s}'`).join(", ");
406
+ const result = openDb()
407
+ .prepare(`UPDATE tasks SET changed_files = @files WHERE id = @id AND status IN (${terminal})`)
408
+ .run({ id: taskId, files: encodeJson(changedFiles) });
409
+ return result.changes > 0;
410
+ }
411
+
398
412
  export async function upsertSession({ id, title = null, note = null }) {
399
413
  if (!id) throw new Error("session id is required");
400
414
  await ensureFilesystem();
package/src/web-app.js ADDED
@@ -0,0 +1,318 @@
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 { createServer } from "node:http";
8
+ import { createReadStream, existsSync, statSync } from "node:fs";
9
+ import { extname, join, normalize, resolve } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import {
12
+ getTask,
13
+ listTaskEventKinds,
14
+ readAgentMessages,
15
+ readSessions,
16
+ readTaskEvents,
17
+ readTasks,
18
+ reconcileDetachedActiveTasks
19
+ } from "./task-store.js";
20
+ import { readNativeGoal } from "./goal-store.js";
21
+ import { readTaskChanges } from "./worktree.js";
22
+ import { ACTIVE_STATUSES } from "./status.js";
23
+ import { supervisorRoot } from "./paths.js";
24
+ import { checkForUpdate } from "./update-check.js";
25
+
26
+ const here = fileURLToPath(new URL(".", import.meta.url));
27
+ const distDir = resolve(here, "..", "web", "dist");
28
+ const port = Number(process.env.SUPERVISOR_WEB_PORT ?? 7877);
29
+ const host = process.env.SUPERVISOR_WEB_HOST ?? "127.0.0.1";
30
+ const NO_SESSION = "none";
31
+
32
+ const MIME = {
33
+ ".html": "text/html; charset=utf-8",
34
+ ".js": "text/javascript; charset=utf-8",
35
+ ".css": "text/css; charset=utf-8",
36
+ ".json": "application/json; charset=utf-8",
37
+ ".svg": "image/svg+xml",
38
+ ".woff2": "font/woff2",
39
+ ".woff": "font/woff",
40
+ ".png": "image/png",
41
+ ".ico": "image/x-icon"
42
+ };
43
+
44
+ function clip(value, maxChars) {
45
+ if (value === null || value === undefined) return null;
46
+ const text = String(value);
47
+ return text.length <= maxChars ? text : `${text.slice(0, maxChars)}…`;
48
+ }
49
+
50
+ function durationMs(task) {
51
+ const start = Date.parse(task.started_at ?? task.created_at ?? "");
52
+ if (Number.isNaN(start)) return null;
53
+ const end = Date.parse(task.completed_at ?? "");
54
+ const stop = Number.isNaN(end) ? Date.now() : end;
55
+ return Math.max(0, stop - start);
56
+ }
57
+
58
+ // The row every list shows. No prompt, no raw events: those are per-worker
59
+ // reads, so a session with forty threads stays one cheap request.
60
+ function workerRow(task) {
61
+ return {
62
+ id: task.id,
63
+ title: task.title,
64
+ status: task.status,
65
+ phase: task.phase ?? null,
66
+ session_id: task.session_id ?? null,
67
+ thread_id: task.thread_id ?? null,
68
+ goal: task.goal_objective ?? null,
69
+ goal_status: task.goal_status ?? null,
70
+ model: task.model ?? null,
71
+ sandbox: task.sandbox,
72
+ project_root: task.project_root,
73
+ worktree_path: task.worktree_path ?? null,
74
+ branch: task.worktree_path ? `codex/${task.id}` : null,
75
+ base_commit: task.base_commit ?? null,
76
+ owned_paths: task.owned_paths ?? [],
77
+ depends_on: task.depends_on ?? [],
78
+ followup_of: task.followup_of ?? null,
79
+ resumed_from: task.resumed_from ?? null,
80
+ run_count: task.run_count ?? 0,
81
+ current_action: clip(task.current_action, 300),
82
+ last_message: clip(task.last_message, 400),
83
+ changed_file_count: liveChangeCount(task),
84
+ command_count: (task.commands ?? []).length,
85
+ error: task.error ?? null,
86
+ exit_code: task.exit_code ?? null,
87
+ pid: task.pid ?? null,
88
+ created_at: task.created_at || null,
89
+ started_at: task.started_at || null,
90
+ updated_at: task.updated_at || null,
91
+ completed_at: task.completed_at || null,
92
+ duration_ms: durationMs(task)
93
+ };
94
+ }
95
+
96
+ // Changed-file counts for the list. The stored changed_files on a row only
97
+ // knows about file_change events; the truth is the worktree diff, which costs
98
+ // two git calls per worker. Terminal rows never change again, so their count
99
+ // is memoised on (id, updated_at); running rows are re-read every time.
100
+ const changeCountCache = new Map();
101
+ function liveChangeCount(task) {
102
+ const key = `${task.id}:${task.updated_at}:${task.status}`;
103
+ const cached = changeCountCache.get(key);
104
+ if (cached !== undefined && !ACTIVE_STATUSES.has(task.status)) return cached;
105
+ const count = readTaskChanges(task).length;
106
+ changeCountCache.set(key, count);
107
+ if (changeCountCache.size > 2000) changeCountCache.delete(changeCountCache.keys().next().value);
108
+ return count;
109
+ }
110
+
111
+ function sessionKey(task) {
112
+ return task.session_id || NO_SESSION;
113
+ }
114
+
115
+ function latest(values) {
116
+ return values.filter(Boolean).sort().at(-1) ?? null;
117
+ }
118
+
119
+ // What a session is about. The title the main thread recorded wins; without
120
+ // one, the goals of its workers are the next best description.
121
+ function aboutSession(meta, tasks) {
122
+ if (meta?.title) return { title: meta.title, note: meta.note ?? null, derived: false };
123
+ const goals = Array.from(new Set(tasks.map((task) => task.goal_objective).filter(Boolean)));
124
+ const summary = goals.slice(0, 3).map((goal) => clip(goal, 60)).join(";");
125
+ return { title: summary || null, note: null, derived: true };
126
+ }
127
+
128
+ function sessionRow(key, tasks, meta = null) {
129
+ const counts = {};
130
+ for (const task of tasks) counts[task.status] = (counts[task.status] ?? 0) + 1;
131
+ const active = tasks.filter((task) => ACTIVE_STATUSES.has(task.status));
132
+ const byActivity = [...tasks].sort((a, b) => String(b.updated_at ?? "").localeCompare(String(a.updated_at ?? "")));
133
+ const lastReport = byActivity.find((task) => task.last_message);
134
+ const about = aboutSession(meta, tasks);
135
+ return {
136
+ id: key,
137
+ unsessioned: key === NO_SESSION,
138
+ title: about.title,
139
+ note: about.note,
140
+ title_derived: about.derived,
141
+ worker_count: tasks.length,
142
+ active_count: active.length,
143
+ counts,
144
+ project_roots: Array.from(new Set(tasks.map((task) => task.project_root).filter(Boolean))),
145
+ first_created_at: tasks.map((task) => task.created_at).filter(Boolean).sort()[0] ?? null,
146
+ last_activity_at: latest(tasks.map((task) => task.updated_at)),
147
+ // What the session is doing right now: one line per running thread.
148
+ now: active.map((task) => ({
149
+ id: task.id,
150
+ title: task.title,
151
+ phase: task.phase ?? null,
152
+ current_action: clip(task.current_action, 160)
153
+ })),
154
+ last_report: lastReport
155
+ ? { id: lastReport.id, title: lastReport.title, text: clip(lastReport.last_message, 240), at: lastReport.updated_at }
156
+ : null
157
+ };
158
+ }
159
+
160
+ async function overview() {
161
+ await reconcileDetachedActiveTasks();
162
+ const tasks = await readTasks();
163
+ const metas = new Map((await readSessions()).map((row) => [row.id, row]));
164
+ const groups = new Map();
165
+ for (const task of tasks) {
166
+ const key = sessionKey(task);
167
+ if (!groups.has(key)) groups.set(key, []);
168
+ groups.get(key).push(task);
169
+ }
170
+ const sessions = Array.from(groups, ([key, group]) => sessionRow(key, group, metas.get(key) ?? null)).sort((a, b) => {
171
+ if (a.active_count !== b.active_count) return b.active_count - a.active_count;
172
+ return String(b.last_activity_at ?? "").localeCompare(String(a.last_activity_at ?? ""));
173
+ });
174
+ return {
175
+ generated_at: new Date().toISOString(),
176
+ store: supervisorRoot,
177
+ total_workers: tasks.length,
178
+ active_workers: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
179
+ sessions
180
+ };
181
+ }
182
+
183
+ async function session(key) {
184
+ await reconcileDetachedActiveTasks();
185
+ const tasks = (await readTasks()).filter((task) => sessionKey(task) === key);
186
+ if (tasks.length === 0) return null;
187
+ const meta = (await readSessions()).find((row) => row.id === key) ?? null;
188
+ return {
189
+ ...sessionRow(key, tasks, meta),
190
+ workers: tasks.map(workerRow)
191
+ };
192
+ }
193
+
194
+ async function worker(taskId) {
195
+ const task = await getTask(taskId);
196
+ if (!task) return null;
197
+ const reports = await readAgentMessages(taskId, 10);
198
+ // Token spend comes from Codex's own turn.completed usage blocks; one per
199
+ // run, so a resumed worker sums its runs.
200
+ const usage = { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, reasoning_output_tokens: 0, turns: 0 };
201
+ for (const event of await readTaskEvents(taskId, 50, ["turn.completed"])) {
202
+ const block = event?.usage ?? {};
203
+ usage.turns += 1;
204
+ for (const key of ["input_tokens", "cached_input_tokens", "output_tokens", "reasoning_output_tokens"]) {
205
+ usage[key] += Number(block[key] ?? 0) || 0;
206
+ }
207
+ }
208
+ const commands = (task.commands ?? []).slice(-40).map((entry) => ({
209
+ ...entry,
210
+ command: clip(entry.command, 600)
211
+ }));
212
+ return {
213
+ ...workerRow(task),
214
+ prompt: task.prompt ?? null,
215
+ changed_files: readTaskChanges(task),
216
+ commands,
217
+ reports: reports.length > 0 ? reports : task.last_message ? [task.last_message] : [],
218
+ native_goal: readNativeGoal(task.thread_id),
219
+ usage,
220
+ notices: task.notices ?? null,
221
+ run_log: task.run_log ?? null,
222
+ event_kinds: await listTaskEventKinds(taskId)
223
+ };
224
+ }
225
+
226
+ async function events(taskId, url) {
227
+ const limit = Math.min(1000, Math.max(1, Number(url.searchParams.get("limit") ?? 150)));
228
+ const kinds = url.searchParams.get("kinds")?.split(",").filter(Boolean) ?? null;
229
+ return { task_id: taskId, events: await readTaskEvents(taskId, limit, kinds) };
230
+ }
231
+
232
+ function json(res, status, body) {
233
+ const text = JSON.stringify(body);
234
+ res.writeHead(status, {
235
+ "content-type": "application/json; charset=utf-8",
236
+ "cache-control": "no-store",
237
+ "content-length": Buffer.byteLength(text)
238
+ });
239
+ res.end(text);
240
+ }
241
+
242
+ function serveStatic(res, pathname) {
243
+ if (!existsSync(distDir)) {
244
+ res.writeHead(503, { "content-type": "text/plain; charset=utf-8" });
245
+ res.end("web/dist is missing. Run `npm run web:build` first.\n");
246
+ return;
247
+ }
248
+ const safe = normalize(pathname).replace(/^(\.\.[/\\])+/, "");
249
+ let file = join(distDir, safe);
250
+ if (!file.startsWith(distDir)) {
251
+ res.writeHead(403);
252
+ res.end();
253
+ return;
254
+ }
255
+ if (!existsSync(file) || statSync(file).isDirectory()) file = join(distDir, "index.html");
256
+ const type = MIME[extname(file)] ?? "application/octet-stream";
257
+ res.writeHead(200, {
258
+ "content-type": type,
259
+ "cache-control": file.endsWith("index.html") ? "no-store" : "public, max-age=31536000, immutable"
260
+ });
261
+ createReadStream(file).pipe(res);
262
+ }
263
+
264
+ async function route(req, res) {
265
+ const url = new URL(req.url ?? "/", `http://${host}`);
266
+ const parts = url.pathname.split("/").filter(Boolean);
267
+ if (parts[0] !== "api") return serveStatic(res, url.pathname);
268
+ if (req.method !== "GET") return json(res, 405, { error: "method_not_allowed" });
269
+
270
+ if (parts[1] === "overview" && parts.length === 2) return json(res, 200, await overview());
271
+ if (parts[1] === "version" && parts.length === 2) {
272
+ return json(res, 200, await checkForUpdate({ force: url.searchParams.get("force") === "1" }));
273
+ }
274
+ if (parts[1] === "sessions" && parts.length === 3) {
275
+ const body = await session(decodeURIComponent(parts[2]));
276
+ return body ? json(res, 200, body) : json(res, 404, { error: "session_not_found" });
277
+ }
278
+ if (parts[1] === "workers" && parts.length === 3) {
279
+ const body = await worker(decodeURIComponent(parts[2]));
280
+ return body ? json(res, 200, body) : json(res, 404, { error: "task_not_found" });
281
+ }
282
+ if (parts[1] === "workers" && parts.length === 4 && parts[3] === "events") {
283
+ const taskId = decodeURIComponent(parts[2]);
284
+ if (!(await getTask(taskId))) return json(res, 404, { error: "task_not_found" });
285
+ return json(res, 200, await events(taskId, url));
286
+ }
287
+ return json(res, 404, { error: "not_found" });
288
+ }
289
+
290
+ export function startWebServer({ storeOrigin = "default" } = {}) {
291
+ const server = createServer((req, res) => {
292
+ route(req, res).catch((error) => {
293
+ process.stderr.write(`[codex-supervisor-web] ${error.stack ?? error.message}\n`);
294
+ if (!res.headersSent) json(res, 500, { error: "internal", message: error.message });
295
+ else res.end();
296
+ });
297
+ });
298
+
299
+ // A taken port is the one error a person will actually hit, usually because
300
+ // a board is already running. Say that, not a stack trace.
301
+ server.on("error", (error) => {
302
+ if (error.code === "EADDRINUSE") {
303
+ process.stderr.write(
304
+ `codex-supervisor-web: port ${port} on ${host} is already in use.\n` +
305
+ ` A board may already be running at http://${host}:${port}\n` +
306
+ ` To run a second one, pick another port: SUPERVISOR_WEB_PORT=8080 codex-supervisor-web\n`
307
+ );
308
+ process.exit(1);
309
+ }
310
+ process.stderr.write(`codex-supervisor-web: ${error.message}\n`);
311
+ process.exit(1);
312
+ });
313
+
314
+ server.listen(port, host, () => {
315
+ process.stdout.write(`codex-supervisor web view on http://${host}:${port}\n store: ${supervisorRoot} (${storeOrigin})\n`);
316
+ });
317
+ return server;
318
+ }