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.
- package/README.en.md +42 -6
- package/README.md +42 -6
- package/package.json +14 -4
- package/skills/codex-supervisor/SKILL.md +17 -5
- package/src/codex-runner.js +62 -12
- package/src/mcp-server.js +129 -17
- package/src/task-store.js +71 -7
- package/src/update-check.js +206 -0
- package/src/web-server.js +302 -0
- package/src/worktree.js +65 -12
- package/web/dist/assets/index-DPTvsjxI.js +85 -0
- package/web/dist/assets/index-DnCjDsN6.css +2 -0
- package/web/dist/index.html +15 -0
package/src/mcp-server.js
CHANGED
|
@@ -10,8 +10,10 @@ import {
|
|
|
10
10
|
resumeCodexWorker
|
|
11
11
|
} from "./codex-runner.js";
|
|
12
12
|
import {
|
|
13
|
+
getSession,
|
|
13
14
|
getTask,
|
|
14
15
|
getTasks,
|
|
16
|
+
isPidAlive,
|
|
15
17
|
listTaskEventKinds,
|
|
16
18
|
readAgentMessages,
|
|
17
19
|
readTaskEvents,
|
|
@@ -19,12 +21,14 @@ import {
|
|
|
19
21
|
readTasksBySession,
|
|
20
22
|
reconcileDetachedActiveTasks,
|
|
21
23
|
searchTasks,
|
|
24
|
+
upsertSession,
|
|
22
25
|
upsertTask
|
|
23
26
|
} from "./task-store.js";
|
|
24
27
|
import { readNativeGoal } from "./goal-store.js";
|
|
25
|
-
import {
|
|
28
|
+
import { readTaskChanges } from "./worktree.js";
|
|
26
29
|
import { ACTIVE_STATUSES, TERMINAL_STATUSES, TASK_STATUSES, isGoalNeedingAttention } from "./status.js";
|
|
27
30
|
import { approxTokenCount, truncateEventStrings, truncateMiddleChars } from "./truncate.js";
|
|
31
|
+
import { checkForUpdate, updateNotice } from "./update-check.js";
|
|
28
32
|
|
|
29
33
|
// Report the real package version. This string had drifted to 0.4.0 while the
|
|
30
34
|
// package shipped 0.5.x, so the handshake named a version nobody was running.
|
|
@@ -37,6 +41,35 @@ const server = new McpServer({
|
|
|
37
41
|
version: packageVersion
|
|
38
42
|
});
|
|
39
43
|
|
|
44
|
+
// Nobody should keep running an old build without hearing about it. The
|
|
45
|
+
// registry is asked once at start and every six hours after; the answer
|
|
46
|
+
// rides along in the overview, the dispatch receipt and the wait response,
|
|
47
|
+
// which are the calls every orchestrating session makes.
|
|
48
|
+
const UPDATE_RECHECK_MS = 6 * 60 * 60 * 1000;
|
|
49
|
+
let updateState = null;
|
|
50
|
+
async function refreshUpdateState({ force = false } = {}) {
|
|
51
|
+
try {
|
|
52
|
+
updateState = await checkForUpdate({ force });
|
|
53
|
+
if (updateState.notice) process.stderr.write(`[codex-supervisor] ${updateState.notice}\n`);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
process.stderr.write(`[codex-supervisor] update check failed: ${error.message}\n`);
|
|
56
|
+
}
|
|
57
|
+
return updateState;
|
|
58
|
+
}
|
|
59
|
+
refreshUpdateState();
|
|
60
|
+
setInterval(() => refreshUpdateState({ force: true }), UPDATE_RECHECK_MS).unref();
|
|
61
|
+
|
|
62
|
+
// The short form for tool results: null when the install is current.
|
|
63
|
+
function updateField() {
|
|
64
|
+
return updateNotice(updateState);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Spread into a result: adds `update` only when there is something to say.
|
|
68
|
+
function withUpdate(payload) {
|
|
69
|
+
const update = updateField();
|
|
70
|
+
return update ? { ...payload, update } : payload;
|
|
71
|
+
}
|
|
72
|
+
|
|
40
73
|
const OVERVIEW_BYTE_BUDGET = 7000;
|
|
41
74
|
const OVERVIEW_CAP_LEVELS = [
|
|
42
75
|
{ title: 40, goal: 60, action: 60, path: 60 },
|
|
@@ -80,6 +113,19 @@ function sleep(ms) {
|
|
|
80
113
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
81
114
|
}
|
|
82
115
|
|
|
116
|
+
// A terminal status is written in two steps. Codex's turn.completed event
|
|
117
|
+
// flips status to completed while the process is still alive and exit_code is
|
|
118
|
+
// still null; the process exit then writes exit_code. A wait that returned on
|
|
119
|
+
// the first step handed the caller a snapshot with exit_code: null, and the
|
|
120
|
+
// next read said 0 - two answers for one worker. A row counts as settled once
|
|
121
|
+
// the exit is recorded, or once nobody is left to record it.
|
|
122
|
+
function isSettled(task) {
|
|
123
|
+
if (!TERMINAL_STATUSES.has(task.status)) return false;
|
|
124
|
+
if (task.status !== "completed" && task.status !== "failed") return true;
|
|
125
|
+
if (task.exit_code !== null && task.exit_code !== undefined) return true;
|
|
126
|
+
return !isPidAlive(task.pid);
|
|
127
|
+
}
|
|
128
|
+
|
|
83
129
|
function summarizeTask(task) {
|
|
84
130
|
return {
|
|
85
131
|
id: task.id,
|
|
@@ -133,7 +179,8 @@ function statusView(task, { includePrompt, promptMaxChars }) {
|
|
|
133
179
|
session_id: task.session_id ?? null,
|
|
134
180
|
pid: task.pid ?? null,
|
|
135
181
|
run_log: task.run_log ?? null,
|
|
136
|
-
|
|
182
|
+
base_commit: task.base_commit ?? null,
|
|
183
|
+
changed_files: readTaskChanges(task),
|
|
137
184
|
current_command: clip(task.current_command, COMMAND_PREVIEW_CHARS),
|
|
138
185
|
commands: commands.map((entry) => ({ ...entry, command: clip(entry.command, COMMAND_PREVIEW_CHARS) })),
|
|
139
186
|
prompt: clip(promptText, promptBudget),
|
|
@@ -158,6 +205,7 @@ function receipt(task) {
|
|
|
158
205
|
project_root: task.project_root,
|
|
159
206
|
worktree_path: task.worktree_path,
|
|
160
207
|
branch: task.worktree_path ? `codex/${task.id}` : null,
|
|
208
|
+
base_commit: task.base_commit ?? null,
|
|
161
209
|
sandbox: task.sandbox,
|
|
162
210
|
model: task.model,
|
|
163
211
|
reasoning_effort: task.reasoning_effort,
|
|
@@ -225,11 +273,12 @@ function settleTokenCount(payload) {
|
|
|
225
273
|
return Buffer.byteLength(JSON.stringify(payload), "utf8");
|
|
226
274
|
}
|
|
227
275
|
|
|
228
|
-
function buildOverview(tasks) {
|
|
276
|
+
function buildOverview(tasks, extras = {}) {
|
|
229
277
|
let payload;
|
|
230
278
|
for (const [index, caps] of OVERVIEW_CAP_LEVELS.entries()) {
|
|
231
279
|
payload = {
|
|
232
280
|
generated_at: new Date().toISOString(),
|
|
281
|
+
...extras,
|
|
233
282
|
total: tasks.length,
|
|
234
283
|
active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
|
|
235
284
|
needs_attention: tasks
|
|
@@ -253,7 +302,7 @@ function buildOverview(tasks) {
|
|
|
253
302
|
function buildWorkerSummary(task, nativeGoal) {
|
|
254
303
|
// Read the worktree too: a worker that edits via shell commands emits no
|
|
255
304
|
// file_change events, so the checkout is the authoritative diff.
|
|
256
|
-
const changed =
|
|
305
|
+
const changed = readTaskChanges(task);
|
|
257
306
|
const commands = task.commands ?? [];
|
|
258
307
|
const lines = [
|
|
259
308
|
`${task.title ?? task.id} — status=${task.status}${task.phase ? `, phase=${task.phase}` : ""}`,
|
|
@@ -313,6 +362,11 @@ server.registerTool(
|
|
|
313
362
|
task: z.string().min(1),
|
|
314
363
|
cwd: z.string().min(1),
|
|
315
364
|
session_id: z.string().min(1).optional(),
|
|
365
|
+
// What this batch is about, in one line, so a reader of the store sees
|
|
366
|
+
// "给 12 个接口补单测" instead of a bare session id. Set it on
|
|
367
|
+
// the first dispatch of a session; later dispatches may omit it.
|
|
368
|
+
session_title: z.string().min(1).max(120).optional(),
|
|
369
|
+
session_note: z.string().min(1).max(2000).optional(),
|
|
316
370
|
sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).default("workspace-write"),
|
|
317
371
|
model: z.string().optional(),
|
|
318
372
|
reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
|
|
@@ -322,13 +376,22 @@ server.registerTool(
|
|
|
322
376
|
objective: z.string().min(1),
|
|
323
377
|
tokenBudget: z.number().int().positive().optional()
|
|
324
378
|
}),
|
|
325
|
-
dependsOn: z.array(z.string().min(1)).optional()
|
|
379
|
+
dependsOn: z.array(z.string().min(1)).optional(),
|
|
380
|
+
// Which commit the worktree is cut from. Defaults to the repository's
|
|
381
|
+
// HEAD; pass a branch, tag or sha to build on work that is not on the
|
|
382
|
+
// main line yet (for example another worker's codex/<id> branch).
|
|
383
|
+
baseRef: z.string().min(1).optional()
|
|
326
384
|
}
|
|
327
385
|
},
|
|
328
386
|
async (input) => {
|
|
329
387
|
try {
|
|
330
|
-
const record = await createCodexWorker({
|
|
331
|
-
|
|
388
|
+
const record = await createCodexWorker({
|
|
389
|
+
...input,
|
|
390
|
+
sessionId: input.session_id ?? null,
|
|
391
|
+
sessionTitle: input.session_title ?? null,
|
|
392
|
+
sessionNote: input.session_note ?? null
|
|
393
|
+
});
|
|
394
|
+
return textResult(withUpdate(receipt(record)));
|
|
332
395
|
} catch (error) {
|
|
333
396
|
return errorResult(error);
|
|
334
397
|
}
|
|
@@ -345,6 +408,8 @@ server.registerTool(
|
|
|
345
408
|
task_id: z.string().min(1),
|
|
346
409
|
followup_prompt: z.string().min(1),
|
|
347
410
|
session_id: z.string().min(1).optional(),
|
|
411
|
+
session_title: z.string().min(1).max(120).optional(),
|
|
412
|
+
session_note: z.string().min(1).max(2000).optional(),
|
|
348
413
|
title: z.string().optional(),
|
|
349
414
|
cwd: z.string().optional(),
|
|
350
415
|
sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).optional(),
|
|
@@ -356,15 +421,18 @@ server.registerTool(
|
|
|
356
421
|
objective: z.string().min(1),
|
|
357
422
|
tokenBudget: z.number().int().positive().optional()
|
|
358
423
|
})
|
|
359
|
-
.optional()
|
|
424
|
+
.optional(),
|
|
425
|
+
baseRef: z.string().min(1).optional()
|
|
360
426
|
}
|
|
361
427
|
},
|
|
362
|
-
async ({ task_id, followup_prompt, session_id, ...options }) => {
|
|
428
|
+
async ({ task_id, followup_prompt, session_id, session_title, session_note, ...options }) => {
|
|
363
429
|
try {
|
|
364
430
|
const record = await createFollowupWorker({
|
|
365
431
|
taskId: task_id,
|
|
366
432
|
followupPrompt: followup_prompt,
|
|
367
433
|
sessionId: session_id ?? null,
|
|
434
|
+
sessionTitle: session_title ?? null,
|
|
435
|
+
sessionNote: session_note ?? null,
|
|
368
436
|
...options
|
|
369
437
|
});
|
|
370
438
|
return textResult(receipt(record));
|
|
@@ -433,7 +501,14 @@ server.registerTool(
|
|
|
433
501
|
await reconcileDetachedActiveTasks();
|
|
434
502
|
const tasks = await readTasks();
|
|
435
503
|
const filtered = (status ? tasks.filter((task) => task.status === status) : tasks).slice(-limit);
|
|
436
|
-
|
|
504
|
+
// version and update ride inside the budgeted payload so approx_tokens
|
|
505
|
+
// still reports the real cost of the whole reply.
|
|
506
|
+
return textResult(
|
|
507
|
+
buildOverview(filtered, {
|
|
508
|
+
version: packageVersion,
|
|
509
|
+
update: updateField() ?? { update_available: false, installed_version: packageVersion, checked: updateState?.source ?? "pending" }
|
|
510
|
+
})
|
|
511
|
+
);
|
|
437
512
|
}
|
|
438
513
|
);
|
|
439
514
|
|
|
@@ -481,8 +556,8 @@ server.registerTool(
|
|
|
481
556
|
while (Date.now() - startedAt < effectiveTimeoutMs) {
|
|
482
557
|
await reconcileDetachedActiveTasks();
|
|
483
558
|
tasks = (await getTasks(task_ids)).filter(Boolean);
|
|
484
|
-
const
|
|
485
|
-
const isDone = mode === "any" ?
|
|
559
|
+
const settledCount = tasks.filter(isSettled).length;
|
|
560
|
+
const isDone = mode === "any" ? settledCount > 0 : settledCount === task_ids.length;
|
|
486
561
|
if (isDone) break;
|
|
487
562
|
await sleep(pollMs);
|
|
488
563
|
}
|
|
@@ -490,9 +565,9 @@ server.registerTool(
|
|
|
490
565
|
await reconcileDetachedActiveTasks();
|
|
491
566
|
tasks = (await getTasks(task_ids)).filter(Boolean);
|
|
492
567
|
const missingIds = task_ids.filter((taskId) => !tasks.some((task) => task.id === taskId));
|
|
493
|
-
const
|
|
568
|
+
const settledTasks = tasks.filter(isSettled);
|
|
494
569
|
const timedOut =
|
|
495
|
-
mode === "any" ?
|
|
570
|
+
mode === "any" ? settledTasks.length === 0 : settledTasks.length !== task_ids.length;
|
|
496
571
|
|
|
497
572
|
const summaries = await Promise.all(
|
|
498
573
|
tasks.map(async (task) => ({
|
|
@@ -510,7 +585,7 @@ server.registerTool(
|
|
|
510
585
|
? `${Math.round(effectiveTimeoutMs / 60000)}-minute`
|
|
511
586
|
: `${Math.round(effectiveTimeoutMs / 1000)}-second`;
|
|
512
587
|
|
|
513
|
-
return textResult({
|
|
588
|
+
return textResult(withUpdate({
|
|
514
589
|
mode,
|
|
515
590
|
timed_out: timedOut,
|
|
516
591
|
still_running: timedOut,
|
|
@@ -527,7 +602,7 @@ server.registerTool(
|
|
|
527
602
|
lost_count: tasks.filter((task) => task.status === "lost").length,
|
|
528
603
|
active_count: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
|
|
529
604
|
workers: summaries
|
|
530
|
-
});
|
|
605
|
+
}));
|
|
531
606
|
}
|
|
532
607
|
);
|
|
533
608
|
|
|
@@ -543,8 +618,11 @@ server.registerTool(
|
|
|
543
618
|
},
|
|
544
619
|
async ({ session_id }) => {
|
|
545
620
|
const tasks = await readTasksBySession(session_id);
|
|
621
|
+
const meta = await getSession(session_id);
|
|
546
622
|
return textResult({
|
|
547
623
|
session_id,
|
|
624
|
+
title: meta?.title ?? null,
|
|
625
|
+
note: meta?.note ?? null,
|
|
548
626
|
count: tasks.length,
|
|
549
627
|
active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
|
|
550
628
|
works: tasks.map(workRow)
|
|
@@ -552,6 +630,40 @@ server.registerTool(
|
|
|
552
630
|
}
|
|
553
631
|
);
|
|
554
632
|
|
|
633
|
+
server.registerTool(
|
|
634
|
+
"check_for_update",
|
|
635
|
+
{
|
|
636
|
+
title: "Check for update",
|
|
637
|
+
description:
|
|
638
|
+
"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.",
|
|
639
|
+
inputSchema: {
|
|
640
|
+
force: z.boolean().default(true)
|
|
641
|
+
}
|
|
642
|
+
},
|
|
643
|
+
async ({ force }) => {
|
|
644
|
+
const result = await refreshUpdateState({ force });
|
|
645
|
+
return textResult(result ?? { error: "update_check_failed" });
|
|
646
|
+
}
|
|
647
|
+
);
|
|
648
|
+
|
|
649
|
+
server.registerTool(
|
|
650
|
+
"describe_session",
|
|
651
|
+
{
|
|
652
|
+
title: "Describe session",
|
|
653
|
+
description:
|
|
654
|
+
"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.",
|
|
655
|
+
inputSchema: {
|
|
656
|
+
session_id: z.string().min(1),
|
|
657
|
+
title: z.string().min(1).max(120).optional(),
|
|
658
|
+
note: z.string().min(1).max(2000).optional()
|
|
659
|
+
}
|
|
660
|
+
},
|
|
661
|
+
async ({ session_id, title, note }) => {
|
|
662
|
+
const row = await upsertSession({ id: session_id, title: title ?? null, note: note ?? null });
|
|
663
|
+
return textResult({ session_id, title: row?.title ?? null, note: row?.note ?? null, updated_at: row?.updated_at ?? null });
|
|
664
|
+
}
|
|
665
|
+
);
|
|
666
|
+
|
|
555
667
|
server.registerTool(
|
|
556
668
|
"search_works",
|
|
557
669
|
{
|
|
@@ -690,7 +802,7 @@ server.registerTool(
|
|
|
690
802
|
source = "task_row";
|
|
691
803
|
}
|
|
692
804
|
const truncated = maxChars === undefined ? reports : reports.map((text) => truncateMiddleChars(text, maxChars));
|
|
693
|
-
const changed =
|
|
805
|
+
const changed = readTaskChanges(task);
|
|
694
806
|
return textResult({
|
|
695
807
|
task_id,
|
|
696
808
|
title: task.title,
|
package/src/task-store.js
CHANGED
|
@@ -23,7 +23,8 @@ const POST_V1_COLUMNS = [
|
|
|
23
23
|
["run_count", "INTEGER NOT NULL DEFAULT 0"],
|
|
24
24
|
["cancel_requested_at", "TEXT"],
|
|
25
25
|
["notices", "TEXT"],
|
|
26
|
-
["session_id", "TEXT"]
|
|
26
|
+
["session_id", "TEXT"],
|
|
27
|
+
["base_commit", "TEXT"]
|
|
27
28
|
];
|
|
28
29
|
|
|
29
30
|
const TASKS_DDL = `
|
|
@@ -72,6 +73,7 @@ const TASKS_DDL = `
|
|
|
72
73
|
cancel_requested_at TEXT,
|
|
73
74
|
notices TEXT,
|
|
74
75
|
worktree_path TEXT,
|
|
76
|
+
base_commit TEXT,
|
|
75
77
|
run_log TEXT NOT NULL
|
|
76
78
|
);
|
|
77
79
|
`;
|
|
@@ -84,7 +86,7 @@ const TASK_COLUMNS = [
|
|
|
84
86
|
"current_command", "error", "followup_of", "resumed_from", "session_id", "thread_id", "owned_paths",
|
|
85
87
|
"depends_on", "goal_objective", "goal_token_budget", "goal_status", "goal_tokens_used",
|
|
86
88
|
"goal_time_used_seconds", "goal_updated_at", "run_count", "cancel_requested_at",
|
|
87
|
-
"notices", "worktree_path", "run_log"
|
|
89
|
+
"notices", "worktree_path", "base_commit", "run_log"
|
|
88
90
|
];
|
|
89
91
|
|
|
90
92
|
function tableColumns(dbInstance, tableName) {
|
|
@@ -156,6 +158,19 @@ const TASK_EVENTS_INDEX_DDL =
|
|
|
156
158
|
const TASKS_SESSION_INDEX_DDL =
|
|
157
159
|
"CREATE INDEX IF NOT EXISTS idx_tasks_session ON tasks(session_id);";
|
|
158
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
|
+
|
|
159
174
|
function sleepSync(ms) {
|
|
160
175
|
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
161
176
|
}
|
|
@@ -189,6 +204,7 @@ function initializeSchema(dbInstance) {
|
|
|
189
204
|
dbInstance.exec(TASK_EVENTS_DDL);
|
|
190
205
|
dbInstance.exec(TASK_EVENTS_INDEX_DDL);
|
|
191
206
|
dbInstance.exec(TASKS_SESSION_INDEX_DDL);
|
|
207
|
+
dbInstance.exec(SESSIONS_DDL);
|
|
192
208
|
dbInstance.exec("COMMIT;");
|
|
193
209
|
} catch (error) {
|
|
194
210
|
try {
|
|
@@ -251,7 +267,7 @@ function rowToTask(row) {
|
|
|
251
267
|
};
|
|
252
268
|
}
|
|
253
269
|
|
|
254
|
-
function isPidAlive(pid) {
|
|
270
|
+
export function isPidAlive(pid) {
|
|
255
271
|
if (!pid) return false;
|
|
256
272
|
try {
|
|
257
273
|
process.kill(pid, 0);
|
|
@@ -274,19 +290,39 @@ export async function readActiveTasks() {
|
|
|
274
290
|
|
|
275
291
|
// A worker whose process is gone and that never wrote a terminal event is not
|
|
276
292
|
// "failed": nothing told us it failed. It is lost, and the fix is to re-run it.
|
|
293
|
+
// A row can also be active without ever having had a process: the dispatch
|
|
294
|
+
// wrote the row and then died before the spawn was recorded (one real store
|
|
295
|
+
// carried such a row for days, pid 0 and no created_at, forever "running").
|
|
296
|
+
// Only a row old enough that the dispatch cannot still be in flight is judged
|
|
297
|
+
// this way; a row with an unreadable created_at is treated as old.
|
|
298
|
+
const NEVER_STARTED_GRACE_MS = 5 * 60 * 1000;
|
|
299
|
+
|
|
300
|
+
function neverStarted(task, now = Date.now()) {
|
|
301
|
+
if (task.pid) return false;
|
|
302
|
+
if (task.started_at) return false;
|
|
303
|
+
const created = Date.parse(task.created_at ?? "");
|
|
304
|
+
if (Number.isNaN(created)) return true;
|
|
305
|
+
return now - created > NEVER_STARTED_GRACE_MS;
|
|
306
|
+
}
|
|
307
|
+
|
|
277
308
|
export async function reconcileDetachedActiveTasks() {
|
|
278
309
|
const tasks = await readActiveTasks();
|
|
279
|
-
const staleTasks = tasks.filter((task) => task.pid && !isPidAlive(task.pid));
|
|
310
|
+
const staleTasks = tasks.filter((task) => (task.pid && !isPidAlive(task.pid)) || neverStarted(task));
|
|
280
311
|
for (const task of staleTasks) {
|
|
281
312
|
const now = new Date().toISOString();
|
|
313
|
+
const vanished = Boolean(task.pid);
|
|
282
314
|
await writeTask({
|
|
283
315
|
...task,
|
|
284
316
|
status: "lost",
|
|
285
317
|
phase: null,
|
|
286
|
-
current_action:
|
|
318
|
+
current_action: vanished
|
|
319
|
+
? "Worker process disappeared without a terminal event"
|
|
320
|
+
: "Worker was never started: no process was recorded for this row",
|
|
287
321
|
current_command: null,
|
|
288
|
-
error: task.error ??
|
|
289
|
-
|
|
322
|
+
error: task.error ?? (vanished
|
|
323
|
+
? "Codex worker process disappeared before a terminal event was recorded."
|
|
324
|
+
: "Codex worker row was written but no process was ever recorded for it."),
|
|
325
|
+
completed_at: task.completed_at || now,
|
|
290
326
|
updated_at: now
|
|
291
327
|
});
|
|
292
328
|
}
|
|
@@ -359,6 +395,34 @@ export async function readTasksBySession(sessionId) {
|
|
|
359
395
|
return rows.map(rowToTask);
|
|
360
396
|
}
|
|
361
397
|
|
|
398
|
+
export async function upsertSession({ id, title = null, note = null }) {
|
|
399
|
+
if (!id) throw new Error("session id is required");
|
|
400
|
+
await ensureFilesystem();
|
|
401
|
+
const now = new Date().toISOString();
|
|
402
|
+
// Only overwrite what the caller sent: a later dispatch that names the
|
|
403
|
+
// session without a title must not blank the title set earlier.
|
|
404
|
+
openDb()
|
|
405
|
+
.prepare(`
|
|
406
|
+
INSERT INTO sessions (id, title, note, created_at, updated_at) VALUES (@id, @title, @note, @now, @now)
|
|
407
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
408
|
+
title = COALESCE(excluded.title, sessions.title),
|
|
409
|
+
note = COALESCE(excluded.note, sessions.note),
|
|
410
|
+
updated_at = excluded.updated_at
|
|
411
|
+
`)
|
|
412
|
+
.run({ id, title: title ?? null, note: note ?? null, now });
|
|
413
|
+
return getSession(id);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
export async function getSession(sessionId) {
|
|
417
|
+
await ensureFilesystem();
|
|
418
|
+
return openDb().prepare("SELECT * FROM sessions WHERE id = ?").get(sessionId) ?? null;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
export async function readSessions() {
|
|
422
|
+
await ensureFilesystem();
|
|
423
|
+
return openDb().prepare("SELECT * FROM sessions").all();
|
|
424
|
+
}
|
|
425
|
+
|
|
362
426
|
export async function getTasks(taskIds) {
|
|
363
427
|
await ensureFilesystem();
|
|
364
428
|
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
|
+
}
|