codex-supervisor-mcp 0.5.5 → 0.5.7

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,302 @@
1
+ #!/usr/bin/env node
2
+ // A thin read-only web view over the supervisor store: which sessions exist,
3
+ // what each one is doing right now, and what every Codex thread under a
4
+ // session has done. It reads the same SQLite file the MCP server writes and
5
+ // never writes to it, apart from the same orphan reconcile every read does.
6
+ //
7
+ // codex-supervisor-web # http://127.0.0.1:7877
8
+ // SUPERVISOR_WEB_PORT=8080 codex-supervisor-web
9
+ import { createServer } from "node:http";
10
+ import { createReadStream, existsSync, statSync } from "node:fs";
11
+ import { extname, join, normalize, resolve } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ import {
14
+ getTask,
15
+ listTaskEventKinds,
16
+ readAgentMessages,
17
+ readSessions,
18
+ readTaskEvents,
19
+ readTasks,
20
+ reconcileDetachedActiveTasks
21
+ } from "./task-store.js";
22
+ import { readNativeGoal } from "./goal-store.js";
23
+ import { readTaskChanges } from "./worktree.js";
24
+ import { ACTIVE_STATUSES } from "./status.js";
25
+ import { supervisorRoot } from "./paths.js";
26
+ import { checkForUpdate } from "./update-check.js";
27
+
28
+ const here = fileURLToPath(new URL(".", import.meta.url));
29
+ const distDir = resolve(here, "..", "web", "dist");
30
+ const port = Number(process.env.SUPERVISOR_WEB_PORT ?? 7877);
31
+ const host = process.env.SUPERVISOR_WEB_HOST ?? "127.0.0.1";
32
+ const NO_SESSION = "none";
33
+
34
+ const MIME = {
35
+ ".html": "text/html; charset=utf-8",
36
+ ".js": "text/javascript; charset=utf-8",
37
+ ".css": "text/css; charset=utf-8",
38
+ ".json": "application/json; charset=utf-8",
39
+ ".svg": "image/svg+xml",
40
+ ".woff2": "font/woff2",
41
+ ".woff": "font/woff",
42
+ ".png": "image/png",
43
+ ".ico": "image/x-icon"
44
+ };
45
+
46
+ function clip(value, maxChars) {
47
+ if (value === null || value === undefined) return null;
48
+ const text = String(value);
49
+ return text.length <= maxChars ? text : `${text.slice(0, maxChars)}…`;
50
+ }
51
+
52
+ function durationMs(task) {
53
+ const start = Date.parse(task.started_at ?? task.created_at ?? "");
54
+ if (Number.isNaN(start)) return null;
55
+ const end = Date.parse(task.completed_at ?? "");
56
+ const stop = Number.isNaN(end) ? Date.now() : end;
57
+ return Math.max(0, stop - start);
58
+ }
59
+
60
+ // The row every list shows. No prompt, no raw events: those are per-worker
61
+ // reads, so a session with forty threads stays one cheap request.
62
+ function workerRow(task) {
63
+ return {
64
+ id: task.id,
65
+ title: task.title,
66
+ status: task.status,
67
+ phase: task.phase ?? null,
68
+ session_id: task.session_id ?? null,
69
+ thread_id: task.thread_id ?? null,
70
+ goal: task.goal_objective ?? null,
71
+ goal_status: task.goal_status ?? null,
72
+ model: task.model ?? null,
73
+ sandbox: task.sandbox,
74
+ project_root: task.project_root,
75
+ worktree_path: task.worktree_path ?? null,
76
+ branch: task.worktree_path ? `codex/${task.id}` : null,
77
+ base_commit: task.base_commit ?? null,
78
+ owned_paths: task.owned_paths ?? [],
79
+ depends_on: task.depends_on ?? [],
80
+ followup_of: task.followup_of ?? null,
81
+ resumed_from: task.resumed_from ?? null,
82
+ run_count: task.run_count ?? 0,
83
+ current_action: clip(task.current_action, 300),
84
+ last_message: clip(task.last_message, 400),
85
+ changed_file_count: liveChangeCount(task),
86
+ command_count: (task.commands ?? []).length,
87
+ error: task.error ?? null,
88
+ exit_code: task.exit_code ?? null,
89
+ pid: task.pid ?? null,
90
+ created_at: task.created_at || null,
91
+ started_at: task.started_at || null,
92
+ updated_at: task.updated_at || null,
93
+ completed_at: task.completed_at || null,
94
+ duration_ms: durationMs(task)
95
+ };
96
+ }
97
+
98
+ // Changed-file counts for the list. The stored changed_files on a row only
99
+ // knows about file_change events; the truth is the worktree diff, which costs
100
+ // two git calls per worker. Terminal rows never change again, so their count
101
+ // is memoised on (id, updated_at); running rows are re-read every time.
102
+ const changeCountCache = new Map();
103
+ function liveChangeCount(task) {
104
+ const key = `${task.id}:${task.updated_at}:${task.status}`;
105
+ const cached = changeCountCache.get(key);
106
+ if (cached !== undefined && !ACTIVE_STATUSES.has(task.status)) return cached;
107
+ const count = readTaskChanges(task).length;
108
+ changeCountCache.set(key, count);
109
+ if (changeCountCache.size > 2000) changeCountCache.delete(changeCountCache.keys().next().value);
110
+ return count;
111
+ }
112
+
113
+ function sessionKey(task) {
114
+ return task.session_id || NO_SESSION;
115
+ }
116
+
117
+ function latest(values) {
118
+ return values.filter(Boolean).sort().at(-1) ?? null;
119
+ }
120
+
121
+ // What a session is about. The title the main thread recorded wins; without
122
+ // one, the goals of its workers are the next best description.
123
+ function aboutSession(meta, tasks) {
124
+ if (meta?.title) return { title: meta.title, note: meta.note ?? null, derived: false };
125
+ const goals = Array.from(new Set(tasks.map((task) => task.goal_objective).filter(Boolean)));
126
+ const summary = goals.slice(0, 3).map((goal) => clip(goal, 60)).join(";");
127
+ return { title: summary || null, note: null, derived: true };
128
+ }
129
+
130
+ function sessionRow(key, tasks, meta = null) {
131
+ const counts = {};
132
+ for (const task of tasks) counts[task.status] = (counts[task.status] ?? 0) + 1;
133
+ const active = tasks.filter((task) => ACTIVE_STATUSES.has(task.status));
134
+ const byActivity = [...tasks].sort((a, b) => String(b.updated_at ?? "").localeCompare(String(a.updated_at ?? "")));
135
+ const lastReport = byActivity.find((task) => task.last_message);
136
+ const about = aboutSession(meta, tasks);
137
+ return {
138
+ id: key,
139
+ unsessioned: key === NO_SESSION,
140
+ title: about.title,
141
+ note: about.note,
142
+ title_derived: about.derived,
143
+ worker_count: tasks.length,
144
+ active_count: active.length,
145
+ counts,
146
+ project_roots: Array.from(new Set(tasks.map((task) => task.project_root).filter(Boolean))),
147
+ first_created_at: tasks.map((task) => task.created_at).filter(Boolean).sort()[0] ?? null,
148
+ last_activity_at: latest(tasks.map((task) => task.updated_at)),
149
+ // What the session is doing right now: one line per running thread.
150
+ now: active.map((task) => ({
151
+ id: task.id,
152
+ title: task.title,
153
+ phase: task.phase ?? null,
154
+ current_action: clip(task.current_action, 160)
155
+ })),
156
+ last_report: lastReport
157
+ ? { id: lastReport.id, title: lastReport.title, text: clip(lastReport.last_message, 240), at: lastReport.updated_at }
158
+ : null
159
+ };
160
+ }
161
+
162
+ async function overview() {
163
+ await reconcileDetachedActiveTasks();
164
+ const tasks = await readTasks();
165
+ const metas = new Map((await readSessions()).map((row) => [row.id, row]));
166
+ const groups = new Map();
167
+ for (const task of tasks) {
168
+ const key = sessionKey(task);
169
+ if (!groups.has(key)) groups.set(key, []);
170
+ groups.get(key).push(task);
171
+ }
172
+ const sessions = Array.from(groups, ([key, group]) => sessionRow(key, group, metas.get(key) ?? null)).sort((a, b) => {
173
+ if (a.active_count !== b.active_count) return b.active_count - a.active_count;
174
+ return String(b.last_activity_at ?? "").localeCompare(String(a.last_activity_at ?? ""));
175
+ });
176
+ return {
177
+ generated_at: new Date().toISOString(),
178
+ store: supervisorRoot,
179
+ total_workers: tasks.length,
180
+ active_workers: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
181
+ sessions
182
+ };
183
+ }
184
+
185
+ async function session(key) {
186
+ await reconcileDetachedActiveTasks();
187
+ const tasks = (await readTasks()).filter((task) => sessionKey(task) === key);
188
+ if (tasks.length === 0) return null;
189
+ const meta = (await readSessions()).find((row) => row.id === key) ?? null;
190
+ return {
191
+ ...sessionRow(key, tasks, meta),
192
+ workers: tasks.map(workerRow)
193
+ };
194
+ }
195
+
196
+ async function worker(taskId) {
197
+ const task = await getTask(taskId);
198
+ if (!task) return null;
199
+ const reports = await readAgentMessages(taskId, 10);
200
+ // Token spend comes from Codex's own turn.completed usage blocks; one per
201
+ // run, so a resumed worker sums its runs.
202
+ const usage = { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, reasoning_output_tokens: 0, turns: 0 };
203
+ for (const event of await readTaskEvents(taskId, 50, ["turn.completed"])) {
204
+ const block = event?.usage ?? {};
205
+ usage.turns += 1;
206
+ for (const key of ["input_tokens", "cached_input_tokens", "output_tokens", "reasoning_output_tokens"]) {
207
+ usage[key] += Number(block[key] ?? 0) || 0;
208
+ }
209
+ }
210
+ const commands = (task.commands ?? []).slice(-40).map((entry) => ({
211
+ ...entry,
212
+ command: clip(entry.command, 600)
213
+ }));
214
+ return {
215
+ ...workerRow(task),
216
+ prompt: task.prompt ?? null,
217
+ changed_files: readTaskChanges(task),
218
+ commands,
219
+ reports: reports.length > 0 ? reports : task.last_message ? [task.last_message] : [],
220
+ native_goal: readNativeGoal(task.thread_id),
221
+ usage,
222
+ notices: task.notices ?? null,
223
+ run_log: task.run_log ?? null,
224
+ event_kinds: await listTaskEventKinds(taskId)
225
+ };
226
+ }
227
+
228
+ async function events(taskId, url) {
229
+ const limit = Math.min(1000, Math.max(1, Number(url.searchParams.get("limit") ?? 150)));
230
+ const kinds = url.searchParams.get("kinds")?.split(",").filter(Boolean) ?? null;
231
+ return { task_id: taskId, events: await readTaskEvents(taskId, limit, kinds) };
232
+ }
233
+
234
+ function json(res, status, body) {
235
+ const text = JSON.stringify(body);
236
+ res.writeHead(status, {
237
+ "content-type": "application/json; charset=utf-8",
238
+ "cache-control": "no-store",
239
+ "content-length": Buffer.byteLength(text)
240
+ });
241
+ res.end(text);
242
+ }
243
+
244
+ function serveStatic(res, pathname) {
245
+ if (!existsSync(distDir)) {
246
+ res.writeHead(503, { "content-type": "text/plain; charset=utf-8" });
247
+ res.end("web/dist is missing. Run `npm run web:build` first.\n");
248
+ return;
249
+ }
250
+ const safe = normalize(pathname).replace(/^(\.\.[/\\])+/, "");
251
+ let file = join(distDir, safe);
252
+ if (!file.startsWith(distDir)) {
253
+ res.writeHead(403);
254
+ res.end();
255
+ return;
256
+ }
257
+ if (!existsSync(file) || statSync(file).isDirectory()) file = join(distDir, "index.html");
258
+ const type = MIME[extname(file)] ?? "application/octet-stream";
259
+ res.writeHead(200, {
260
+ "content-type": type,
261
+ "cache-control": file.endsWith("index.html") ? "no-store" : "public, max-age=31536000, immutable"
262
+ });
263
+ createReadStream(file).pipe(res);
264
+ }
265
+
266
+ async function route(req, res) {
267
+ const url = new URL(req.url ?? "/", `http://${host}`);
268
+ const parts = url.pathname.split("/").filter(Boolean);
269
+ if (parts[0] !== "api") return serveStatic(res, url.pathname);
270
+ if (req.method !== "GET") return json(res, 405, { error: "method_not_allowed" });
271
+
272
+ if (parts[1] === "overview" && parts.length === 2) return json(res, 200, await overview());
273
+ if (parts[1] === "version" && parts.length === 2) {
274
+ return json(res, 200, await checkForUpdate({ force: url.searchParams.get("force") === "1" }));
275
+ }
276
+ if (parts[1] === "sessions" && parts.length === 3) {
277
+ const body = await session(decodeURIComponent(parts[2]));
278
+ return body ? json(res, 200, body) : json(res, 404, { error: "session_not_found" });
279
+ }
280
+ if (parts[1] === "workers" && parts.length === 3) {
281
+ const body = await worker(decodeURIComponent(parts[2]));
282
+ return body ? json(res, 200, body) : json(res, 404, { error: "task_not_found" });
283
+ }
284
+ if (parts[1] === "workers" && parts.length === 4 && parts[3] === "events") {
285
+ const taskId = decodeURIComponent(parts[2]);
286
+ if (!(await getTask(taskId))) return json(res, 404, { error: "task_not_found" });
287
+ return json(res, 200, await events(taskId, url));
288
+ }
289
+ return json(res, 404, { error: "not_found" });
290
+ }
291
+
292
+ const server = createServer((req, res) => {
293
+ route(req, res).catch((error) => {
294
+ process.stderr.write(`[codex-supervisor-web] ${error.stack ?? error.message}\n`);
295
+ if (!res.headersSent) json(res, 500, { error: "internal", message: error.message });
296
+ else res.end();
297
+ });
298
+ });
299
+
300
+ server.listen(port, host, () => {
301
+ process.stdout.write(`codex-supervisor web view on http://${host}:${port} (store: ${supervisorRoot})\n`);
302
+ });
package/src/worktree.js CHANGED
@@ -3,13 +3,31 @@
3
3
  // Codex reports edits as file_change items only when it uses its own patch
4
4
  // tool. A worker that edits through shell commands produces no such item, so
5
5
  // the worktree itself is the authoritative source: every worker gets its own
6
- // checkout, so `git status` inside it is exactly that worker's diff.
6
+ // checkout, so the diff inside it is exactly that worker's work.
7
+ //
8
+ // Two reads are needed. `git status` covers what is still uncommitted. A
9
+ // worker that commits on its branch leaves a clean status, and one real batch
10
+ // of five workers all did exactly that and reported no changed files at all -
11
+ // so the committed part is read as `git diff --name-only <base> HEAD`, where
12
+ // base is the commit the worktree was created from.
7
13
  import { execFileSync } from "node:child_process";
8
14
  import { existsSync } from "node:fs";
9
15
  import { join } from "node:path";
10
16
 
11
17
  const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
12
18
 
19
+ // core.quotePath is on by default and turns every non-ASCII path into an
20
+ // octal-escaped, double-quoted string ("\344\270\255..."). The projects
21
+ // this runs against have Chinese directory names, so it is switched off for
22
+ // every read here and paths come back as written.
23
+ function git(worktreePath, args) {
24
+ return execFileSync(defaultGitBin, ["-C", worktreePath, "-c", "core.quotePath=false", ...args], {
25
+ encoding: "utf8",
26
+ timeout: 15000,
27
+ stdio: ["ignore", "pipe", "ignore"]
28
+ });
29
+ }
30
+
13
31
  function parsePorcelainLine(line) {
14
32
  // " M path", "?? path", "R old -> new"
15
33
  const trimmed = line.replace(/\s+$/, "");
@@ -21,24 +39,59 @@ function parsePorcelainLine(line) {
21
39
  return rest.trim() || null;
22
40
  }
23
41
 
24
- export function readWorktreeChanges(worktreePath) {
42
+ function nonEmptyLines(output) {
43
+ return output.split("\n").map((line) => line.trim()).filter(Boolean);
44
+ }
45
+
46
+ // The commit the worker started from. Rows written by this version carry it
47
+ // as base_commit. Older rows do not, but the branch reflog still has it: the
48
+ // oldest reflog entry of `codex/<id>` is the branch's creation point.
49
+ export function resolveWorktreeBase(worktreePath, { baseCommit = null, branch = null } = {}) {
50
+ if (baseCommit) return baseCommit;
51
+ if (!branch) return null;
52
+ try {
53
+ const entries = nonEmptyLines(git(worktreePath, ["reflog", "show", "--format=%H", branch]));
54
+ return entries.at(-1) ?? null;
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ export function readWorktreeChanges(worktreePath, { baseCommit = null, branch = null } = {}) {
25
61
  if (!worktreePath || !existsSync(worktreePath)) return [];
62
+ const found = new Set();
26
63
  try {
27
- const output = execFileSync(defaultGitBin, ["-C", worktreePath, "status", "--porcelain"], {
28
- encoding: "utf8",
29
- timeout: 15000,
30
- stdio: ["ignore", "pipe", "ignore"]
31
- });
32
- const relative = output
33
- .split("\n")
34
- .map(parsePorcelainLine)
35
- .filter(Boolean);
36
- return Array.from(new Set(relative.map((entry) => join(worktreePath, entry))));
64
+ const output = git(worktreePath, ["status", "--porcelain"]);
65
+ for (const entry of output.split("\n").map(parsePorcelainLine).filter(Boolean)) found.add(entry);
37
66
  } catch {
38
67
  return [];
39
68
  }
69
+ const base = resolveWorktreeBase(worktreePath, { baseCommit, branch });
70
+ if (base) {
71
+ try {
72
+ for (const entry of nonEmptyLines(git(worktreePath, ["diff", "--name-only", base, "HEAD"]))) found.add(entry);
73
+ } catch {
74
+ // A base that no longer resolves (history rewritten) leaves only the
75
+ // uncommitted part. Better a partial answer than none.
76
+ }
77
+ }
78
+ return Array.from(found, (entry) => join(worktreePath, entry));
40
79
  }
41
80
 
42
81
  export function mergeChangedFiles(existing, discovered) {
43
82
  return Array.from(new Set([...(existing ?? []), ...(discovered ?? [])]));
44
83
  }
84
+
85
+ // What a task row knows about its own worktree, in the shape
86
+ // readWorktreeChanges wants. Kept here so every caller derives the branch
87
+ // name the same way the runner creates it.
88
+ export function worktreeRef(task) {
89
+ return {
90
+ baseCommit: task.base_commit ?? null,
91
+ branch: task.worktree_path ? `codex/${task.id}` : null
92
+ };
93
+ }
94
+
95
+ export function readTaskChanges(task) {
96
+ return mergeChangedFiles(task.changed_files, readWorktreeChanges(task.worktree_path, worktreeRef(task)));
97
+ }