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/src/web-server.js CHANGED
@@ -1,302 +1,49 @@
1
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.
2
+ // Entry for `codex-supervisor-web`. Decides which store to open, then starts
3
+ // the board (web-app.js).
6
4
  //
7
- // codex-supervisor-web # http://127.0.0.1:7877
5
+ // codex-supervisor-web # http://127.0.0.1:7877
8
6
  // 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;
7
+ // SUPERVISOR_HOME=/path/to/state codex-supervisor-web
8
+ //
9
+ // The store has to be the one the MCP server writes. Without SUPERVISOR_HOME
10
+ // in the environment, the nearest .mcp.json above the current directory is
11
+ // read: a project that configures codex-supervisor with its own
12
+ // SUPERVISOR_HOME gets a board on that store without retyping the path.
13
+ import { existsSync, readFileSync } from "node:fs";
14
+ import { dirname, join, resolve } from "node:path";
15
+
16
+ export function storeFromMcpConfig(startDir) {
17
+ let dir = resolve(startDir);
18
+ for (;;) {
19
+ const file = join(dir, ".mcp.json");
20
+ if (existsSync(file)) {
21
+ try {
22
+ const config = JSON.parse(readFileSync(file, "utf8"));
23
+ const home = config?.mcpServers?.["codex-supervisor"]?.env?.SUPERVISOR_HOME;
24
+ if (typeof home === "string" && home.trim()) return { home: resolve(dir, home.trim()), file };
25
+ } catch {
26
+ // an unreadable .mcp.json is somebody else's problem; keep walking
27
+ }
208
28
  }
29
+ const parent = dirname(dir);
30
+ if (parent === dir) return null;
31
+ dir = parent;
209
32
  }
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
33
  }
243
34
 
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;
35
+ let storeOrigin = "SUPERVISOR_HOME";
36
+ if (!process.env.SUPERVISOR_HOME?.trim()) {
37
+ const found = storeFromMcpConfig(process.cwd());
38
+ if (found) {
39
+ process.env.SUPERVISOR_HOME = found.home;
40
+ storeOrigin = `from ${found.file}`;
41
+ } else {
42
+ storeOrigin = "default, no SUPERVISOR_HOME and no .mcp.json above the current directory";
249
43
  }
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
44
  }
265
45
 
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
- });
46
+ // paths.js reads SUPERVISOR_HOME when it is first imported, so the import
47
+ // has to come after the detection above.
48
+ const { startWebServer } = await import("./web-app.js");
49
+ startWebServer({ storeOrigin });
package/src/worktree.js CHANGED
@@ -16,12 +16,20 @@ import { join } from "node:path";
16
16
 
17
17
  const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
18
18
 
19
+ // Two global flags on every read here.
20
+ //
19
21
  // core.quotePath is on by default and turns every non-ASCII path into an
20
22
  // 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
+ // this runs against have Chinese directory names, so it is switched off and
24
+ // paths come back as written.
25
+ //
26
+ // --no-optional-locks keeps `git status` from taking index.lock to refresh
27
+ // the index. These reads run while the worker is still working in the same
28
+ // worktree, from status polls and the board, and on Windows a status poll
29
+ // holding index.lock made the worker's own `git add` fail and the worker
30
+ // exit non-zero. An observer must never lock what it observes.
23
31
  function git(worktreePath, args) {
24
- return execFileSync(defaultGitBin, ["-C", worktreePath, "-c", "core.quotePath=false", ...args], {
32
+ return execFileSync(defaultGitBin, ["--no-optional-locks", "-C", worktreePath, "-c", "core.quotePath=false", ...args], {
25
33
  encoding: "utf8",
26
34
  timeout: 15000,
27
35
  stdio: ["ignore", "pipe", "ignore"]