codex-supervisor-mcp 0.5.6 → 0.5.8

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.6",
3
+ "version": "0.5.8",
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",
@@ -24,7 +24,8 @@
24
24
  ],
25
25
  "bin": {
26
26
  "codex-supervisor-mcp": "./src/mcp-server.js",
27
- "codex-supervisor-setup": "./src/setup.js"
27
+ "codex-supervisor-setup": "./src/setup.js",
28
+ "codex-supervisor-web": "./src/web-server.js"
28
29
  },
29
30
  "files": [
30
31
  "src/mcp-server.js",
@@ -41,6 +42,9 @@
41
42
  "src/prompt.js",
42
43
  "src/cleanup.js",
43
44
  "src/monitor.jsx",
45
+ "src/web-server.js",
46
+ "src/update-check.js",
47
+ "web/dist/",
44
48
  "skills/",
45
49
  "README.md",
46
50
  "LICENSE"
@@ -51,12 +55,18 @@
51
55
  "start": "node ./src/mcp-server.js",
52
56
  "monitor": "tsx ./src/monitor.jsx",
53
57
  "cleanup": "node ./src/cleanup.js",
54
- "test": "node ./src/bin-resolver-test.js && node ./src/truncate-test.js && node ./src/status-test.js && node ./src/migration-test.js && node ./src/setup-test.js && node ./src/setup-windows-test.js && node ./src/regression-test.js",
58
+ "test": "node ./src/bin-resolver-test.js && node ./src/truncate-test.js && node ./src/status-test.js && node ./src/migration-test.js && node ./src/setup-test.js && node ./src/setup-windows-test.js && node ./src/regression-test.js && node --test test/edge/*.test.js",
55
59
  "test:real": "node ./src/real-codex-test.js",
56
60
  "smoke": "node ./src/smoke-test.js",
57
61
  "smoke:followup": "node ./src/followup-smoke-test.js",
58
62
  "smoke:mcp": "node ./src/mcp-smoke-test.js",
59
- "smoke:mcp-wait": "node ./src/mcp-wait-smoke-test.js"
63
+ "smoke:mcp-wait": "node ./src/mcp-wait-smoke-test.js",
64
+ "web": "node ./src/web-server.js",
65
+ "web:install": "npm --prefix web install",
66
+ "web:build": "npm --prefix web run build",
67
+ "web:dev": "npm --prefix web run dev",
68
+ "test:edge": "node --test test/edge/*.test.js",
69
+ "prepublishOnly": "npm run web:build && npm test"
60
70
  },
61
71
  "dependencies": {
62
72
  "@modelcontextprotocol/sdk": "^1.21.0"
@@ -18,9 +18,10 @@ description: 把 Codex CLI 当并行 worker 派活、盯进度、收结果。用
18
18
  ## 一次派单
19
19
 
20
20
  1. 拆活。每路写清楚:干什么、能写哪些文件、怎么算做完。
21
- 2. `create_codex_worker` 派出去。返回的是一张精简回执(`id`、`worktree_path`、`branch`、`owned_paths`、`status`),任务原文不回传,派十一路也不会把你的提示词抄十一遍。
22
- 3. 派完就 `wait_codex_workers` 等。默认只等 2 分钟,到点返回进度快照,worker 照跑;拿同一批 `task_ids` 接着调,直到 `timed_out: false`。默认**不带**事件(`includeEvents: false`),返回只够看状态,要事件得自己开。
23
- 4. 收结果走 `get_worker_result`,拿完整汇报,别一上来读事件流。
21
+ 2. 第一路派单时带 `session_id` + `session_title`(一句话说这批活是干什么的,30 字以内,比如「给 12 个接口补单测」),要交代背景再加 `session_note`。看板左栏和 `get_session_works` 显示的是这个标题,不是 id。漏了就事后调 `describe_session` 补。
22
+ 3. `create_codex_worker` 派出去。返回的是一张精简回执(`id`、`worktree_path`、`branch`、`owned_paths`、`status`),任务原文不回传,派十一路也不会把你的提示词抄十一遍。
23
+ 4. 派完就 `wait_codex_workers` 等。默认只等 2 分钟,到点返回进度快照,worker 照跑;拿同一批 `task_ids` 接着调,直到 `timed_out: false`。默认**不带**事件(`includeEvents: false`),返回只够看状态,要事件得自己开。
24
+ 5. 收结果走 `get_worker_result`,拿完整汇报,别一上来读事件流。
24
25
 
25
26
  `ownedPaths` 和 `goal` 必填,不是可选项。
26
27
 
@@ -33,7 +34,9 @@ description: 把 Codex CLI 当并行 worker 派活、盯进度、收结果。用
33
34
  | `ownedPaths` | 这个 worker 允许写的路径。和正在跑的 worker 重叠会被拒,返回冲突的 `task_id` |
34
35
  | `goal.objective` | 一句话说清这路活的目标 |
35
36
  | `session_id` | 同一批派单传同一个值。断线重连靠它 |
37
+ | `session_title` / `session_note` | 这批活是干什么的,一句话 + 可选说明。第一路带上就行,后面几路不用重复 |
36
38
  | `dependsOn` | 有先后依赖时填上游的 `task_id` |
39
+ | `baseRef` | worktree 从哪个提交切。默认仓库 `HEAD`;要接着另一路还没合进主线的活干,填它的分支 `codex/<taskId>` |
37
40
 
38
41
  一次派一批:
39
42
 
@@ -42,6 +45,10 @@ create_codex_worker × N (同一个 session_id)
42
45
  wait_codex_workers (task_ids: [...], mode: "all")
43
46
  ```
44
47
 
48
+ ## 看到 `update` 字段就转告用户
49
+
50
+ `get_orchestration_overview`、派单回执、`wait_codex_workers` 的返回里出现 `update` 且 `update_available: true`(或 `integrity_matches: false`)时,当轮回复里告诉用户一句:现在装的是 `installed_version`,npm 上已经是 `latest_version`,跑 `install_command` 里那条命令,然后重启 Claude Code / Codex。只说一次,不要每轮重复。用户让你查时调 `check_for_update`。
51
+
45
52
  ## 读结果别把上下文撑爆
46
53
 
47
54
  按这个顺序读,能不动后面就别动:
@@ -115,6 +122,10 @@ wait_codex_workers (task_ids: [...], mode: "all")
115
122
  - **worktree 只隔离工作区,不隔离端口和数据库**。多路活要是都会连同一个 dev server 或同一个库,得自己错开。
116
123
  - **`cancel_codex_worker` 跨进程靠 pid**。要求那个 pid 的命令行里带 `codex`,防止误杀复用 pid 的进程。
117
124
 
125
+ ## 看板
126
+
127
+ 用户想用眼睛看这批活在干什么时,告诉他起 `codex-supervisor-web`(全局装过)或 `npx -p codex-supervisor-mcp codex-supervisor-web`,开 `http://127.0.0.1:7877`。看板按 session 分组,显示的就是派单时记的 `session_title`,所以标题要写得让人一眼看懂。
128
+
118
129
  ## 收尾
119
130
 
120
131
  一批活全部到终态后:
@@ -9,6 +9,7 @@ import {
9
9
  readActiveTasks,
10
10
  readTaskEvents,
11
11
  taskRunPath,
12
+ upsertSession,
12
13
  upsertTask
13
14
  } from "./task-store.js";
14
15
  import { applyCodexEvent } from "./event-parser.js";
@@ -386,6 +387,8 @@ export async function createCodexWorker({
386
387
  title,
387
388
  task,
388
389
  sessionId = null,
390
+ sessionTitle = null,
391
+ sessionNote = null,
389
392
  cwd,
390
393
  sandbox = "workspace-write",
391
394
  model = null,
@@ -413,6 +416,10 @@ export async function createCodexWorker({
413
416
  const conflicts = await findOwnershipConflicts(normalizedOwnedPaths);
414
417
  if (conflicts.length > 0) throw ownershipConflictError(conflicts);
415
418
 
419
+ if (sessionId && (sessionTitle || sessionNote)) {
420
+ await upsertSession({ id: sessionId, title: sessionTitle, note: sessionNote });
421
+ }
422
+
416
423
  const id = `codex-${Date.now()}-${randomUUID().slice(0, 8)}`;
417
424
  const worktree = useWorktree
418
425
  ? await ensureWorktree(projectRoot, id, baseRef)
@@ -627,6 +634,8 @@ export async function createFollowupWorker({
627
634
  taskId,
628
635
  followupPrompt,
629
636
  sessionId = null,
637
+ sessionTitle = null,
638
+ sessionNote = null,
630
639
  title,
631
640
  cwd,
632
641
  sandbox,
@@ -666,6 +675,8 @@ export async function createFollowupWorker({
666
675
  title: title ?? `Follow-up for ${parent.id}`,
667
676
  task: prompt,
668
677
  sessionId: sessionId ?? parent.session_id ?? null,
678
+ sessionTitle,
679
+ sessionNote,
669
680
  cwd: cwd ?? parent.project_root ?? parent.cwd,
670
681
  sandbox: sandbox ?? parent.sandbox,
671
682
  model: model ?? parent.model,
package/src/mcp-server.js CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  resumeCodexWorker
11
11
  } from "./codex-runner.js";
12
12
  import {
13
+ getSession,
13
14
  getTask,
14
15
  getTasks,
15
16
  isPidAlive,
@@ -19,13 +20,16 @@ import {
19
20
  readTasks,
20
21
  readTasksBySession,
21
22
  reconcileDetachedActiveTasks,
23
+ recordTerminalChangedFiles,
22
24
  searchTasks,
25
+ upsertSession,
23
26
  upsertTask
24
27
  } from "./task-store.js";
25
28
  import { readNativeGoal } from "./goal-store.js";
26
29
  import { readTaskChanges } from "./worktree.js";
27
30
  import { ACTIVE_STATUSES, TERMINAL_STATUSES, TASK_STATUSES, isGoalNeedingAttention } from "./status.js";
28
31
  import { approxTokenCount, truncateEventStrings, truncateMiddleChars } from "./truncate.js";
32
+ import { checkForUpdate, updateNotice } from "./update-check.js";
29
33
 
30
34
  // Report the real package version. This string had drifted to 0.4.0 while the
31
35
  // package shipped 0.5.x, so the handshake named a version nobody was running.
@@ -38,6 +42,35 @@ const server = new McpServer({
38
42
  version: packageVersion
39
43
  });
40
44
 
45
+ // Nobody should keep running an old build without hearing about it. The
46
+ // registry is asked once at start and every six hours after; the answer
47
+ // rides along in the overview, the dispatch receipt and the wait response,
48
+ // which are the calls every orchestrating session makes.
49
+ const UPDATE_RECHECK_MS = 6 * 60 * 60 * 1000;
50
+ let updateState = null;
51
+ async function refreshUpdateState({ force = false } = {}) {
52
+ try {
53
+ updateState = await checkForUpdate({ force });
54
+ if (updateState.notice) process.stderr.write(`[codex-supervisor] ${updateState.notice}\n`);
55
+ } catch (error) {
56
+ process.stderr.write(`[codex-supervisor] update check failed: ${error.message}\n`);
57
+ }
58
+ return updateState;
59
+ }
60
+ refreshUpdateState();
61
+ setInterval(() => refreshUpdateState({ force: true }), UPDATE_RECHECK_MS).unref();
62
+
63
+ // The short form for tool results: null when the install is current.
64
+ function updateField() {
65
+ return updateNotice(updateState);
66
+ }
67
+
68
+ // Spread into a result: adds `update` only when there is something to say.
69
+ function withUpdate(payload) {
70
+ const update = updateField();
71
+ return update ? { ...payload, update } : payload;
72
+ }
73
+
41
74
  const OVERVIEW_BYTE_BUDGET = 7000;
42
75
  const OVERVIEW_CAP_LEVELS = [
43
76
  { title: 40, goal: 60, action: 60, path: 60 },
@@ -241,11 +274,12 @@ function settleTokenCount(payload) {
241
274
  return Buffer.byteLength(JSON.stringify(payload), "utf8");
242
275
  }
243
276
 
244
- function buildOverview(tasks) {
277
+ function buildOverview(tasks, extras = {}) {
245
278
  let payload;
246
279
  for (const [index, caps] of OVERVIEW_CAP_LEVELS.entries()) {
247
280
  payload = {
248
281
  generated_at: new Date().toISOString(),
282
+ ...extras,
249
283
  total: tasks.length,
250
284
  active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
251
285
  needs_attention: tasks
@@ -329,6 +363,11 @@ server.registerTool(
329
363
  task: z.string().min(1),
330
364
  cwd: z.string().min(1),
331
365
  session_id: z.string().min(1).optional(),
366
+ // What this batch is about, in one line, so a reader of the store sees
367
+ // "给 12 个接口补单测" instead of a bare session id. Set it on
368
+ // the first dispatch of a session; later dispatches may omit it.
369
+ session_title: z.string().min(1).max(120).optional(),
370
+ session_note: z.string().min(1).max(2000).optional(),
332
371
  sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).default("workspace-write"),
333
372
  model: z.string().optional(),
334
373
  reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
@@ -347,8 +386,13 @@ server.registerTool(
347
386
  },
348
387
  async (input) => {
349
388
  try {
350
- const record = await createCodexWorker({ ...input, sessionId: input.session_id ?? null });
351
- return textResult(receipt(record));
389
+ const record = await createCodexWorker({
390
+ ...input,
391
+ sessionId: input.session_id ?? null,
392
+ sessionTitle: input.session_title ?? null,
393
+ sessionNote: input.session_note ?? null
394
+ });
395
+ return textResult(withUpdate(receipt(record)));
352
396
  } catch (error) {
353
397
  return errorResult(error);
354
398
  }
@@ -365,6 +409,8 @@ server.registerTool(
365
409
  task_id: z.string().min(1),
366
410
  followup_prompt: z.string().min(1),
367
411
  session_id: z.string().min(1).optional(),
412
+ session_title: z.string().min(1).max(120).optional(),
413
+ session_note: z.string().min(1).max(2000).optional(),
368
414
  title: z.string().optional(),
369
415
  cwd: z.string().optional(),
370
416
  sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).optional(),
@@ -380,12 +426,14 @@ server.registerTool(
380
426
  baseRef: z.string().min(1).optional()
381
427
  }
382
428
  },
383
- async ({ task_id, followup_prompt, session_id, ...options }) => {
429
+ async ({ task_id, followup_prompt, session_id, session_title, session_note, ...options }) => {
384
430
  try {
385
431
  const record = await createFollowupWorker({
386
432
  taskId: task_id,
387
433
  followupPrompt: followup_prompt,
388
434
  sessionId: session_id ?? null,
435
+ sessionTitle: session_title ?? null,
436
+ sessionNote: session_note ?? null,
389
437
  ...options
390
438
  });
391
439
  return textResult(receipt(record));
@@ -454,7 +502,14 @@ server.registerTool(
454
502
  await reconcileDetachedActiveTasks();
455
503
  const tasks = await readTasks();
456
504
  const filtered = (status ? tasks.filter((task) => task.status === status) : tasks).slice(-limit);
457
- return textResult(buildOverview(filtered));
505
+ // version and update ride inside the budgeted payload so approx_tokens
506
+ // still reports the real cost of the whole reply.
507
+ return textResult(
508
+ buildOverview(filtered, {
509
+ version: packageVersion,
510
+ update: updateField() ?? { update_available: false, installed_version: packageVersion, checked: updateState?.source ?? "pending" }
511
+ })
512
+ );
458
513
  }
459
514
  );
460
515
 
@@ -531,7 +586,7 @@ server.registerTool(
531
586
  ? `${Math.round(effectiveTimeoutMs / 60000)}-minute`
532
587
  : `${Math.round(effectiveTimeoutMs / 1000)}-second`;
533
588
 
534
- return textResult({
589
+ return textResult(withUpdate({
535
590
  mode,
536
591
  timed_out: timedOut,
537
592
  still_running: timedOut,
@@ -548,7 +603,7 @@ server.registerTool(
548
603
  lost_count: tasks.filter((task) => task.status === "lost").length,
549
604
  active_count: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
550
605
  workers: summaries
551
- });
606
+ }));
552
607
  }
553
608
  );
554
609
 
@@ -564,8 +619,11 @@ server.registerTool(
564
619
  },
565
620
  async ({ session_id }) => {
566
621
  const tasks = await readTasksBySession(session_id);
622
+ const meta = await getSession(session_id);
567
623
  return textResult({
568
624
  session_id,
625
+ title: meta?.title ?? null,
626
+ note: meta?.note ?? null,
569
627
  count: tasks.length,
570
628
  active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
571
629
  works: tasks.map(workRow)
@@ -573,6 +631,40 @@ server.registerTool(
573
631
  }
574
632
  );
575
633
 
634
+ server.registerTool(
635
+ "check_for_update",
636
+ {
637
+ title: "Check for update",
638
+ description:
639
+ "Ask the npm registry whether a newer codex-supervisor-mcp is published, and whether the installed files match the published tarball. Returns installed and latest version, integrity check, and the install command. The same check runs on startup; call this to force a fresh one.",
640
+ inputSchema: {
641
+ force: z.boolean().default(true)
642
+ }
643
+ },
644
+ async ({ force }) => {
645
+ const result = await refreshUpdateState({ force });
646
+ return textResult(result ?? { error: "update_check_failed" });
647
+ }
648
+ );
649
+
650
+ server.registerTool(
651
+ "describe_session",
652
+ {
653
+ title: "Describe session",
654
+ description:
655
+ "Record what a session is about: a one-line title and an optional note. Readers of the store (the web view, get_session_works) show these instead of the bare session id. Fields you omit are kept.",
656
+ inputSchema: {
657
+ session_id: z.string().min(1),
658
+ title: z.string().min(1).max(120).optional(),
659
+ note: z.string().min(1).max(2000).optional()
660
+ }
661
+ },
662
+ async ({ session_id, title, note }) => {
663
+ const row = await upsertSession({ id: session_id, title: title ?? null, note: note ?? null });
664
+ return textResult({ session_id, title: row?.title ?? null, note: row?.note ?? null, updated_at: row?.updated_at ?? null });
665
+ }
666
+ );
667
+
576
668
  server.registerTool(
577
669
  "search_works",
578
670
  {
@@ -680,8 +772,10 @@ server.registerTool(
680
772
  const task = await getTask(task_id);
681
773
  if (!task) return textResult({ error: "task_not_found", task_id });
682
774
  const summary = buildWorkerSummary(task, readNativeGoal(task.thread_id));
683
- if (summary.changed_files.length !== (task.changed_files ?? []).length) {
684
- 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);
685
779
  }
686
780
  return textResult(summary);
687
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
 
@@ -158,6 +158,19 @@ const TASK_EVENTS_INDEX_DDL =
158
158
  const TASKS_SESSION_INDEX_DDL =
159
159
  "CREATE INDEX IF NOT EXISTS idx_tasks_session ON tasks(session_id);";
160
160
 
161
+ // A session is a string on each task row; this table is what a session is
162
+ // *about*. A main thread sets it once per batch, so a reader sees "给 12
163
+ // 个接口补单测" instead of a bare id.
164
+ const SESSIONS_DDL = `
165
+ CREATE TABLE IF NOT EXISTS sessions (
166
+ id TEXT PRIMARY KEY,
167
+ title TEXT,
168
+ note TEXT,
169
+ created_at TEXT NOT NULL,
170
+ updated_at TEXT NOT NULL
171
+ );
172
+ `;
173
+
161
174
  function sleepSync(ms) {
162
175
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
163
176
  }
@@ -191,6 +204,7 @@ function initializeSchema(dbInstance) {
191
204
  dbInstance.exec(TASK_EVENTS_DDL);
192
205
  dbInstance.exec(TASK_EVENTS_INDEX_DDL);
193
206
  dbInstance.exec(TASKS_SESSION_INDEX_DDL);
207
+ dbInstance.exec(SESSIONS_DDL);
194
208
  dbInstance.exec("COMMIT;");
195
209
  } catch (error) {
196
210
  try {
@@ -381,6 +395,48 @@ export async function readTasksBySession(sessionId) {
381
395
  return rows.map(rowToTask);
382
396
  }
383
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
+
412
+ export async function upsertSession({ id, title = null, note = null }) {
413
+ if (!id) throw new Error("session id is required");
414
+ await ensureFilesystem();
415
+ const now = new Date().toISOString();
416
+ // Only overwrite what the caller sent: a later dispatch that names the
417
+ // session without a title must not blank the title set earlier.
418
+ openDb()
419
+ .prepare(`
420
+ INSERT INTO sessions (id, title, note, created_at, updated_at) VALUES (@id, @title, @note, @now, @now)
421
+ ON CONFLICT(id) DO UPDATE SET
422
+ title = COALESCE(excluded.title, sessions.title),
423
+ note = COALESCE(excluded.note, sessions.note),
424
+ updated_at = excluded.updated_at
425
+ `)
426
+ .run({ id, title: title ?? null, note: note ?? null, now });
427
+ return getSession(id);
428
+ }
429
+
430
+ export async function getSession(sessionId) {
431
+ await ensureFilesystem();
432
+ return openDb().prepare("SELECT * FROM sessions WHERE id = ?").get(sessionId) ?? null;
433
+ }
434
+
435
+ export async function readSessions() {
436
+ await ensureFilesystem();
437
+ return openDb().prepare("SELECT * FROM sessions").all();
438
+ }
439
+
384
440
  export async function getTasks(taskIds) {
385
441
  await ensureFilesystem();
386
442
  return taskIds.map((taskId) => {
@@ -0,0 +1,206 @@
1
+ // Is the running copy the latest published one? Asked once per MCP start and
2
+ // again every few hours, answered from the npm registry, cached on disk so a
3
+ // burst of MCP processes does not turn into a burst of registry calls.
4
+ //
5
+ // Two things are compared. The version, against the registry's `latest`
6
+ // dist-tag. And the tarball integrity: a global install records the
7
+ // integrity of what npm unpacked in node_modules/.package-lock.json, and
8
+ // the registry says what the integrity of that version should be. A
9
+ // mismatch means the files on disk are not the published build.
10
+ import { existsSync, readFileSync } from "node:fs";
11
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
12
+ import { execFileSync } from "node:child_process";
13
+ import { dirname, join, resolve } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { dataDir } from "./paths.js";
16
+
17
+ const PACKAGE_NAME = "codex-supervisor-mcp";
18
+ const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
19
+ const packageJson = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
20
+
21
+ export const INSTALL_COMMAND = `npm i -g ${PACKAGE_NAME}@latest`;
22
+ const DEFAULT_REGISTRY = "https://registry.npmjs.org";
23
+ const CACHE_TTL_MS = 60 * 60 * 1000;
24
+ const cachePath = join(dataDir, "update-check.json");
25
+
26
+ function registryUrl() {
27
+ return (process.env.CODEX_SUPERVISOR_REGISTRY?.trim() || DEFAULT_REGISTRY).replace(/\/+$/, "");
28
+ }
29
+
30
+ function timeoutMs() {
31
+ const raw = Number(process.env.CODEX_SUPERVISOR_UPDATE_TIMEOUT_MS ?? 4000);
32
+ return Number.isFinite(raw) && raw > 0 ? raw : 4000;
33
+ }
34
+
35
+ export function updateCheckDisabled() {
36
+ return /^(1|true|yes)$/i.test(process.env.CODEX_SUPERVISOR_NO_UPDATE_CHECK?.trim() ?? "");
37
+ }
38
+
39
+ // "1.2.3" -> [1,2,3]; a prerelease tag sorts below the release it precedes.
40
+ export function parseVersion(text) {
41
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/.exec(String(text ?? "").trim());
42
+ if (!match) return null;
43
+ return { parts: [Number(match[1]), Number(match[2]), Number(match[3])], prerelease: match[4] ?? null };
44
+ }
45
+
46
+ export function compareVersions(a, b) {
47
+ const left = parseVersion(a);
48
+ const right = parseVersion(b);
49
+ if (!left || !right) return null;
50
+ for (let i = 0; i < 3; i += 1) {
51
+ if (left.parts[i] !== right.parts[i]) return left.parts[i] < right.parts[i] ? -1 : 1;
52
+ }
53
+ if (left.prerelease === right.prerelease) return 0;
54
+ if (left.prerelease === null) return 1;
55
+ if (right.prerelease === null) return -1;
56
+ return left.prerelease < right.prerelease ? -1 : 1;
57
+ }
58
+
59
+ // What is actually on disk: the version from package.json, plus whichever
60
+ // provenance is available - npm's recorded integrity for a global install,
61
+ // the HEAD commit for a git checkout.
62
+ export function installedPackage() {
63
+ const info = { name: PACKAGE_NAME, version: packageJson.version, path: packageRoot, integrity: null, commit: null, source: "unknown" };
64
+ const lockPath = join(packageRoot, "..", ".package-lock.json");
65
+ if (existsSync(lockPath)) {
66
+ try {
67
+ const lock = JSON.parse(readFileSync(lockPath, "utf8"));
68
+ const entry = lock.packages?.[`node_modules/${PACKAGE_NAME}`];
69
+ if (entry?.integrity) {
70
+ info.integrity = entry.integrity;
71
+ info.source = "npm";
72
+ }
73
+ } catch {
74
+ // unreadable lock: fall through, provenance stays unknown
75
+ }
76
+ }
77
+ if (!info.integrity && existsSync(join(packageRoot, ".git"))) {
78
+ try {
79
+ info.commit = execFileSync("git", ["-C", packageRoot, "rev-parse", "HEAD"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }).trim();
80
+ info.source = "git";
81
+ } catch {
82
+ // not a usable checkout
83
+ }
84
+ }
85
+ return info;
86
+ }
87
+
88
+ async function fetchRegistry() {
89
+ const controller = new AbortController();
90
+ const timer = setTimeout(() => controller.abort(), timeoutMs());
91
+ try {
92
+ const response = await fetch(`${registryUrl()}/${PACKAGE_NAME}`, {
93
+ signal: controller.signal,
94
+ headers: { accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8" }
95
+ });
96
+ if (!response.ok) throw new Error(`registry answered ${response.status}`);
97
+ const body = await response.json();
98
+ const latestVersion = body?.["dist-tags"]?.latest;
99
+ if (!latestVersion || !parseVersion(latestVersion)) throw new Error("registry reply has no usable dist-tags.latest");
100
+ const dist = body.versions?.[latestVersion]?.dist ?? {};
101
+ return {
102
+ latest: {
103
+ version: latestVersion,
104
+ integrity: dist.integrity ?? null,
105
+ shasum: dist.shasum ?? null,
106
+ published_at: body.time?.[latestVersion] ?? null
107
+ },
108
+ versions: Object.fromEntries(
109
+ Object.entries(body.versions ?? {}).map(([version, meta]) => [version, { integrity: meta?.dist?.integrity ?? null }])
110
+ )
111
+ };
112
+ } finally {
113
+ clearTimeout(timer);
114
+ }
115
+ }
116
+
117
+ async function readCache() {
118
+ try {
119
+ return JSON.parse(await readFile(cachePath, "utf8"));
120
+ } catch {
121
+ return null;
122
+ }
123
+ }
124
+
125
+ async function writeCache(payload) {
126
+ try {
127
+ await mkdir(dataDir, { recursive: true });
128
+ await writeFile(cachePath, JSON.stringify(payload));
129
+ } catch {
130
+ // a cache that cannot be written only costs a registry call next time
131
+ }
132
+ }
133
+
134
+ // Pure: given what is installed and what the registry said, what to tell.
135
+ export function evaluateUpdate(installed, registry, { source, error }) {
136
+ const cmp = registry ? compareVersions(installed.version, registry.latest.version) : null;
137
+ const updateAvailable = cmp !== null && cmp < 0;
138
+ const expected = registry?.versions?.[installed.version]?.integrity ?? null;
139
+ const integrityMatches = installed.integrity && expected ? installed.integrity === expected : null;
140
+ let notice = null;
141
+ if (updateAvailable) {
142
+ notice = `codex-supervisor-mcp ${installed.version} is installed but ${registry.latest.version} is published. Run \`${INSTALL_COMMAND}\` and restart the MCP client.`;
143
+ } else if (integrityMatches === false) {
144
+ notice = `The installed codex-supervisor-mcp ${installed.version} does not match the published tarball (integrity differs). Reinstall with \`${INSTALL_COMMAND}\`.`;
145
+ }
146
+ return {
147
+ checked_at: new Date().toISOString(),
148
+ source,
149
+ error: error ?? null,
150
+ installed: { version: installed.version, integrity: installed.integrity, commit: installed.commit, source: installed.source, path: installed.path },
151
+ latest: registry?.latest ?? null,
152
+ update_available: updateAvailable,
153
+ integrity_matches: integrityMatches,
154
+ install_command: INSTALL_COMMAND,
155
+ notice
156
+ };
157
+ }
158
+
159
+ let inflight = null;
160
+
161
+ // The full answer. `force` skips the on-disk cache. Never throws: a registry
162
+ // that is down yields source: "offline" with the reason in `error`.
163
+ export async function checkForUpdate({ force = false } = {}) {
164
+ if (updateCheckDisabled()) {
165
+ return { ...evaluateUpdate(installedPackage(), null, { source: "disabled", error: null }), disabled: true };
166
+ }
167
+ if (inflight) return inflight;
168
+ inflight = (async () => {
169
+ const installed = installedPackage();
170
+ if (!force) {
171
+ const cached = await readCache();
172
+ const age = cached?.checked_at ? Date.now() - Date.parse(cached.checked_at) : Number.POSITIVE_INFINITY;
173
+ if (cached?.registry && age >= 0 && age < CACHE_TTL_MS && cached.registry_url === registryUrl()) {
174
+ return evaluateUpdate(installed, cached.registry, { source: "cache", error: null });
175
+ }
176
+ }
177
+ try {
178
+ const registry = await fetchRegistry();
179
+ await writeCache({ checked_at: new Date().toISOString(), registry_url: registryUrl(), registry });
180
+ return evaluateUpdate(installed, registry, { source: "registry", error: null });
181
+ } catch (error) {
182
+ const cached = await readCache();
183
+ if (cached?.registry && cached.registry_url === registryUrl()) {
184
+ return evaluateUpdate(installed, cached.registry, { source: "stale-cache", error: error.message });
185
+ }
186
+ return evaluateUpdate(installed, null, { source: "offline", error: error.message });
187
+ }
188
+ })().finally(() => {
189
+ inflight = null;
190
+ });
191
+ return inflight;
192
+ }
193
+
194
+ // The small object that rides along in tool results. Null when there is
195
+ // nothing to say, so the common case costs no bytes.
196
+ export function updateNotice(result) {
197
+ if (!result || !result.notice) return null;
198
+ return {
199
+ update_available: result.update_available,
200
+ installed_version: result.installed.version,
201
+ latest_version: result.latest?.version ?? null,
202
+ integrity_matches: result.integrity_matches,
203
+ install_command: result.install_command,
204
+ notice: result.notice
205
+ };
206
+ }