codex-supervisor-mcp 0.5.8 → 0.6.0
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 +8 -4
- package/README.md +7 -3
- package/package.json +3 -1
- package/skills/codex-supervisor/SKILL.md +13 -1
- package/src/codex-runner.js +6 -0
- package/src/side-chat.js +425 -0
- package/src/task-store.js +105 -0
- package/src/web-app.js +422 -0
- package/src/web-server.js +39 -292
- package/web/dist/assets/index-DI1hLMxE.css +2 -0
- package/web/dist/assets/index-Dne-82WY.js +154 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-DPTvsjxI.js +0 -85
- package/web/dist/assets/index-DnCjDsN6.css +0 -2
package/src/task-store.js
CHANGED
|
@@ -171,6 +171,31 @@ const SESSIONS_DDL = `
|
|
|
171
171
|
);
|
|
172
172
|
`;
|
|
173
173
|
|
|
174
|
+
// Side questions asked from the board. One side session per worker (the
|
|
175
|
+
// forked Codex thread), many turns under it. A turn keeps the stream chunks
|
|
176
|
+
// it produced, so a page that comes back can replay what it missed and the
|
|
177
|
+
// conversation survives a board restart.
|
|
178
|
+
const SIDE_DDL = `
|
|
179
|
+
CREATE TABLE IF NOT EXISTS side_sessions (
|
|
180
|
+
task_id TEXT PRIMARY KEY,
|
|
181
|
+
fork_thread_id TEXT,
|
|
182
|
+
created_at TEXT NOT NULL,
|
|
183
|
+
ended_at TEXT
|
|
184
|
+
);
|
|
185
|
+
CREATE TABLE IF NOT EXISTS side_turns (
|
|
186
|
+
id TEXT PRIMARY KEY,
|
|
187
|
+
task_id TEXT NOT NULL,
|
|
188
|
+
question TEXT NOT NULL,
|
|
189
|
+
status TEXT NOT NULL,
|
|
190
|
+
chunks TEXT NOT NULL DEFAULT '[]',
|
|
191
|
+
usage TEXT,
|
|
192
|
+
error TEXT,
|
|
193
|
+
started_at TEXT NOT NULL,
|
|
194
|
+
ended_at TEXT
|
|
195
|
+
);
|
|
196
|
+
CREATE INDEX IF NOT EXISTS idx_side_turns_task ON side_turns(task_id, started_at);
|
|
197
|
+
`;
|
|
198
|
+
|
|
174
199
|
function sleepSync(ms) {
|
|
175
200
|
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
176
201
|
}
|
|
@@ -205,6 +230,7 @@ function initializeSchema(dbInstance) {
|
|
|
205
230
|
dbInstance.exec(TASK_EVENTS_INDEX_DDL);
|
|
206
231
|
dbInstance.exec(TASKS_SESSION_INDEX_DDL);
|
|
207
232
|
dbInstance.exec(SESSIONS_DDL);
|
|
233
|
+
dbInstance.exec(SIDE_DDL);
|
|
208
234
|
dbInstance.exec("COMMIT;");
|
|
209
235
|
} catch (error) {
|
|
210
236
|
try {
|
|
@@ -437,6 +463,85 @@ export async function readSessions() {
|
|
|
437
463
|
return openDb().prepare("SELECT * FROM sessions").all();
|
|
438
464
|
}
|
|
439
465
|
|
|
466
|
+
// ---- side sessions and turns
|
|
467
|
+
|
|
468
|
+
export async function getSideSession(taskId) {
|
|
469
|
+
await ensureFilesystem();
|
|
470
|
+
return openDb().prepare("SELECT * FROM side_sessions WHERE task_id = ? AND ended_at IS NULL").get(taskId) ?? null;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export async function openSideSession(taskId) {
|
|
474
|
+
await ensureFilesystem();
|
|
475
|
+
const now = new Date().toISOString();
|
|
476
|
+
openDb()
|
|
477
|
+
.prepare(`INSERT INTO side_sessions (task_id, fork_thread_id, created_at, ended_at) VALUES (?, NULL, ?, NULL)
|
|
478
|
+
ON CONFLICT(task_id) DO UPDATE SET fork_thread_id = NULL, created_at = excluded.created_at, ended_at = NULL`)
|
|
479
|
+
.run(taskId, now);
|
|
480
|
+
return getSideSession(taskId);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
export async function setSideSessionFork(taskId, forkThreadId) {
|
|
484
|
+
await ensureFilesystem();
|
|
485
|
+
openDb().prepare("UPDATE side_sessions SET fork_thread_id = ? WHERE task_id = ? AND ended_at IS NULL").run(forkThreadId, taskId);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
export async function closeSideSession(taskId) {
|
|
489
|
+
await ensureFilesystem();
|
|
490
|
+
const db = openDb();
|
|
491
|
+
const row = db.prepare("SELECT * FROM side_sessions WHERE task_id = ? AND ended_at IS NULL").get(taskId) ?? null;
|
|
492
|
+
const now = new Date().toISOString();
|
|
493
|
+
db.prepare("UPDATE side_sessions SET ended_at = ? WHERE task_id = ? AND ended_at IS NULL").run(now, taskId);
|
|
494
|
+
db.prepare("DELETE FROM side_turns WHERE task_id = ?").run(taskId);
|
|
495
|
+
return row;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
export async function insertSideTurn(turn) {
|
|
499
|
+
await ensureFilesystem();
|
|
500
|
+
openDb()
|
|
501
|
+
.prepare(`INSERT INTO side_turns (id, task_id, question, status, chunks, usage, error, started_at, ended_at)
|
|
502
|
+
VALUES (@id, @task_id, @question, @status, @chunks, @usage, @error, @started_at, @ended_at)`)
|
|
503
|
+
.run({
|
|
504
|
+
id: turn.id,
|
|
505
|
+
task_id: turn.task_id,
|
|
506
|
+
question: turn.question,
|
|
507
|
+
status: turn.status,
|
|
508
|
+
chunks: JSON.stringify(turn.chunks ?? []),
|
|
509
|
+
usage: turn.usage ? JSON.stringify(turn.usage) : null,
|
|
510
|
+
error: turn.error ?? null,
|
|
511
|
+
started_at: turn.started_at,
|
|
512
|
+
ended_at: turn.ended_at ?? null
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
export async function updateSideTurn(id, fields) {
|
|
517
|
+
await ensureFilesystem();
|
|
518
|
+
const sets = [];
|
|
519
|
+
const params = { id };
|
|
520
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
521
|
+
sets.push(`${key} = @${key}`);
|
|
522
|
+
params[key] = key === "chunks" || key === "usage" ? (value === null ? null : JSON.stringify(value)) : value;
|
|
523
|
+
}
|
|
524
|
+
if (sets.length === 0) return;
|
|
525
|
+
openDb().prepare(`UPDATE side_turns SET ${sets.join(", ")} WHERE id = @id`).run(params);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
export async function readSideTurns(taskId) {
|
|
529
|
+
await ensureFilesystem();
|
|
530
|
+
return openDb()
|
|
531
|
+
.prepare("SELECT * FROM side_turns WHERE task_id = ? ORDER BY started_at ASC")
|
|
532
|
+
.all(taskId)
|
|
533
|
+
.map((row) => ({ ...row, chunks: decodeJson(row.chunks, []), usage: row.usage ? decodeJson(row.usage, null) : null }));
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// A board that restarts cannot own a turn that was running when it died.
|
|
537
|
+
export async function interruptRunningSideTurns() {
|
|
538
|
+
await ensureFilesystem();
|
|
539
|
+
const now = new Date().toISOString();
|
|
540
|
+
return openDb()
|
|
541
|
+
.prepare("UPDATE side_turns SET status = 'interrupted', error = COALESCE(error, 'the board restarted while this turn was running'), ended_at = ? WHERE status = 'running'")
|
|
542
|
+
.run(now).changes;
|
|
543
|
+
}
|
|
544
|
+
|
|
440
545
|
export async function getTasks(taskIds) {
|
|
441
546
|
await ensureFilesystem();
|
|
442
547
|
return taskIds.map((taskId) => {
|
package/src/web-app.js
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
// The board's HTTP server: a thin read-only view over the supervisor store.
|
|
2
|
+
// Which sessions exist, what each one is doing right now, what every Codex
|
|
3
|
+
// thread under a session has done. It reads the same SQLite file the MCP
|
|
4
|
+
// server writes and never writes to it, apart from the same orphan
|
|
5
|
+
// reconcile every read does. web-server.js is the entry that decides which
|
|
6
|
+
// store to open and then calls startWebServer().
|
|
7
|
+
import { createServer } from "node:http";
|
|
8
|
+
import { createReadStream, existsSync, statSync } from "node:fs";
|
|
9
|
+
import { extname, join, normalize, resolve } from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import {
|
|
12
|
+
getTask,
|
|
13
|
+
listTaskEventKinds,
|
|
14
|
+
readAgentMessages,
|
|
15
|
+
readSessions,
|
|
16
|
+
readTaskEvents,
|
|
17
|
+
readTasks,
|
|
18
|
+
reconcileDetachedActiveTasks
|
|
19
|
+
} from "./task-store.js";
|
|
20
|
+
import { readNativeGoal } from "./goal-store.js";
|
|
21
|
+
import { readTaskChanges } from "./worktree.js";
|
|
22
|
+
import { ACTIVE_STATUSES } from "./status.js";
|
|
23
|
+
import { supervisorRoot } from "./paths.js";
|
|
24
|
+
import { checkForUpdate } from "./update-check.js";
|
|
25
|
+
import { attachToTurn, endSideSession, runSideTurn, sideSessionState, stopSideTurn } from "./side-chat.js";
|
|
26
|
+
|
|
27
|
+
const here = fileURLToPath(new URL(".", import.meta.url));
|
|
28
|
+
const distDir = resolve(here, "..", "web", "dist");
|
|
29
|
+
const port = Number(process.env.SUPERVISOR_WEB_PORT ?? 7877);
|
|
30
|
+
const host = process.env.SUPERVISOR_WEB_HOST ?? "127.0.0.1";
|
|
31
|
+
const NO_SESSION = "none";
|
|
32
|
+
|
|
33
|
+
const MIME = {
|
|
34
|
+
".html": "text/html; charset=utf-8",
|
|
35
|
+
".js": "text/javascript; charset=utf-8",
|
|
36
|
+
".css": "text/css; charset=utf-8",
|
|
37
|
+
".json": "application/json; charset=utf-8",
|
|
38
|
+
".svg": "image/svg+xml",
|
|
39
|
+
".woff2": "font/woff2",
|
|
40
|
+
".woff": "font/woff",
|
|
41
|
+
".png": "image/png",
|
|
42
|
+
".ico": "image/x-icon"
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
function clip(value, maxChars) {
|
|
46
|
+
if (value === null || value === undefined) return null;
|
|
47
|
+
const text = String(value);
|
|
48
|
+
return text.length <= maxChars ? text : `${text.slice(0, maxChars)}…`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function durationMs(task) {
|
|
52
|
+
const start = Date.parse(task.started_at ?? task.created_at ?? "");
|
|
53
|
+
if (Number.isNaN(start)) return null;
|
|
54
|
+
const end = Date.parse(task.completed_at ?? "");
|
|
55
|
+
const stop = Number.isNaN(end) ? Date.now() : end;
|
|
56
|
+
return Math.max(0, stop - start);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// The row every list shows. No prompt, no raw events: those are per-worker
|
|
60
|
+
// reads, so a session with forty threads stays one cheap request.
|
|
61
|
+
function workerRow(task) {
|
|
62
|
+
return {
|
|
63
|
+
id: task.id,
|
|
64
|
+
title: task.title,
|
|
65
|
+
status: task.status,
|
|
66
|
+
phase: task.phase ?? null,
|
|
67
|
+
session_id: task.session_id ?? null,
|
|
68
|
+
thread_id: task.thread_id ?? null,
|
|
69
|
+
goal: task.goal_objective ?? null,
|
|
70
|
+
goal_status: task.goal_status ?? null,
|
|
71
|
+
model: task.model ?? null,
|
|
72
|
+
sandbox: task.sandbox,
|
|
73
|
+
project_root: task.project_root,
|
|
74
|
+
worktree_path: task.worktree_path ?? null,
|
|
75
|
+
branch: task.worktree_path ? `codex/${task.id}` : null,
|
|
76
|
+
base_commit: task.base_commit ?? null,
|
|
77
|
+
owned_paths: task.owned_paths ?? [],
|
|
78
|
+
depends_on: task.depends_on ?? [],
|
|
79
|
+
followup_of: task.followup_of ?? null,
|
|
80
|
+
resumed_from: task.resumed_from ?? null,
|
|
81
|
+
run_count: task.run_count ?? 0,
|
|
82
|
+
current_action: clip(task.current_action, 300),
|
|
83
|
+
last_message: clip(task.last_message, 400),
|
|
84
|
+
changed_file_count: liveChangeCount(task),
|
|
85
|
+
command_count: (task.commands ?? []).length,
|
|
86
|
+
error: task.error ?? null,
|
|
87
|
+
exit_code: task.exit_code ?? null,
|
|
88
|
+
pid: task.pid ?? null,
|
|
89
|
+
created_at: task.created_at || null,
|
|
90
|
+
started_at: task.started_at || null,
|
|
91
|
+
updated_at: task.updated_at || null,
|
|
92
|
+
completed_at: task.completed_at || null,
|
|
93
|
+
duration_ms: durationMs(task)
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Changed-file counts for the list. The stored changed_files on a row only
|
|
98
|
+
// knows about file_change events; the truth is the worktree diff, which costs
|
|
99
|
+
// two git calls per worker. Terminal rows never change again, so their count
|
|
100
|
+
// is memoised on (id, updated_at); running rows are re-read every time.
|
|
101
|
+
const changeCountCache = new Map();
|
|
102
|
+
function liveChangeCount(task) {
|
|
103
|
+
const key = `${task.id}:${task.updated_at}:${task.status}`;
|
|
104
|
+
const cached = changeCountCache.get(key);
|
|
105
|
+
if (cached !== undefined && !ACTIVE_STATUSES.has(task.status)) return cached;
|
|
106
|
+
const count = readTaskChanges(task).length;
|
|
107
|
+
changeCountCache.set(key, count);
|
|
108
|
+
if (changeCountCache.size > 2000) changeCountCache.delete(changeCountCache.keys().next().value);
|
|
109
|
+
return count;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function sessionKey(task) {
|
|
113
|
+
return task.session_id || NO_SESSION;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function latest(values) {
|
|
117
|
+
return values.filter(Boolean).sort().at(-1) ?? null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// What a session is about. The title the main thread recorded wins; without
|
|
121
|
+
// one, the goals of its workers are the next best description.
|
|
122
|
+
function aboutSession(meta, tasks) {
|
|
123
|
+
if (meta?.title) return { title: meta.title, note: meta.note ?? null, derived: false };
|
|
124
|
+
const goals = Array.from(new Set(tasks.map((task) => task.goal_objective).filter(Boolean)));
|
|
125
|
+
const summary = goals.slice(0, 3).map((goal) => clip(goal, 60)).join(";");
|
|
126
|
+
return { title: summary || null, note: null, derived: true };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function sessionRow(key, tasks, meta = null) {
|
|
130
|
+
const counts = {};
|
|
131
|
+
for (const task of tasks) counts[task.status] = (counts[task.status] ?? 0) + 1;
|
|
132
|
+
const active = tasks.filter((task) => ACTIVE_STATUSES.has(task.status));
|
|
133
|
+
const byActivity = [...tasks].sort((a, b) => String(b.updated_at ?? "").localeCompare(String(a.updated_at ?? "")));
|
|
134
|
+
const lastReport = byActivity.find((task) => task.last_message);
|
|
135
|
+
const about = aboutSession(meta, tasks);
|
|
136
|
+
return {
|
|
137
|
+
id: key,
|
|
138
|
+
unsessioned: key === NO_SESSION,
|
|
139
|
+
title: about.title,
|
|
140
|
+
note: about.note,
|
|
141
|
+
title_derived: about.derived,
|
|
142
|
+
worker_count: tasks.length,
|
|
143
|
+
active_count: active.length,
|
|
144
|
+
counts,
|
|
145
|
+
project_roots: Array.from(new Set(tasks.map((task) => task.project_root).filter(Boolean))),
|
|
146
|
+
first_created_at: tasks.map((task) => task.created_at).filter(Boolean).sort()[0] ?? null,
|
|
147
|
+
last_activity_at: latest(tasks.map((task) => task.updated_at)),
|
|
148
|
+
// What the session is doing right now: one line per running thread.
|
|
149
|
+
now: active.map((task) => ({
|
|
150
|
+
id: task.id,
|
|
151
|
+
title: task.title,
|
|
152
|
+
phase: task.phase ?? null,
|
|
153
|
+
current_action: clip(task.current_action, 160)
|
|
154
|
+
})),
|
|
155
|
+
last_report: lastReport
|
|
156
|
+
? { id: lastReport.id, title: lastReport.title, text: clip(lastReport.last_message, 240), at: lastReport.updated_at }
|
|
157
|
+
: null
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Pagination for the lists: `limit` rows after `offset`, newest activity
|
|
162
|
+
// first for sessions, dispatch order for workers. The page says whether
|
|
163
|
+
// there is more so the board loads the rest as the user scrolls.
|
|
164
|
+
function pageParams(url, defaultLimit) {
|
|
165
|
+
const limit = Math.min(200, Math.max(1, Number(url.searchParams.get("limit") ?? defaultLimit) || defaultLimit));
|
|
166
|
+
const offset = Math.max(0, Number(url.searchParams.get("offset") ?? 0) || 0);
|
|
167
|
+
return { limit, offset };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function paginate(items, { limit, offset }) {
|
|
171
|
+
return { items: items.slice(offset, offset + limit), total: items.length, offset, limit, has_more: offset + limit < items.length };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function overview({ limit, offset } = { limit: 20, offset: 0 }) {
|
|
175
|
+
await reconcileDetachedActiveTasks();
|
|
176
|
+
const tasks = await readTasks();
|
|
177
|
+
const metas = new Map((await readSessions()).map((row) => [row.id, row]));
|
|
178
|
+
const groups = new Map();
|
|
179
|
+
for (const task of tasks) {
|
|
180
|
+
const key = sessionKey(task);
|
|
181
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
182
|
+
groups.get(key).push(task);
|
|
183
|
+
}
|
|
184
|
+
const sessions = Array.from(groups, ([key, group]) => sessionRow(key, group, metas.get(key) ?? null)).sort((a, b) => {
|
|
185
|
+
if (a.active_count !== b.active_count) return b.active_count - a.active_count;
|
|
186
|
+
return String(b.last_activity_at ?? "").localeCompare(String(a.last_activity_at ?? ""));
|
|
187
|
+
});
|
|
188
|
+
const page = paginate(sessions, { limit, offset });
|
|
189
|
+
return {
|
|
190
|
+
generated_at: new Date().toISOString(),
|
|
191
|
+
store: supervisorRoot,
|
|
192
|
+
total_workers: tasks.length,
|
|
193
|
+
active_workers: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
|
|
194
|
+
total_sessions: sessions.length,
|
|
195
|
+
offset: page.offset,
|
|
196
|
+
limit: page.limit,
|
|
197
|
+
has_more: page.has_more,
|
|
198
|
+
sessions: page.items
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function session(key, { limit, offset } = { limit: 40, offset: 0 }) {
|
|
203
|
+
await reconcileDetachedActiveTasks();
|
|
204
|
+
const tasks = (await readTasks()).filter((task) => sessionKey(task) === key);
|
|
205
|
+
if (tasks.length === 0) return null;
|
|
206
|
+
const meta = (await readSessions()).find((row) => row.id === key) ?? null;
|
|
207
|
+
const ordered = [...tasks].sort((a, b) => String(a.created_at ?? "").localeCompare(String(b.created_at ?? "")));
|
|
208
|
+
const page = paginate(ordered, { limit, offset });
|
|
209
|
+
return {
|
|
210
|
+
...sessionRow(key, tasks, meta),
|
|
211
|
+
offset: page.offset,
|
|
212
|
+
limit: page.limit,
|
|
213
|
+
has_more: page.has_more,
|
|
214
|
+
workers: page.items.map(workerRow)
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async function worker(taskId) {
|
|
219
|
+
const task = await getTask(taskId);
|
|
220
|
+
if (!task) return null;
|
|
221
|
+
const reports = await readAgentMessages(taskId, 10);
|
|
222
|
+
// Token spend comes from Codex's own turn.completed usage blocks; one per
|
|
223
|
+
// run, so a resumed worker sums its runs.
|
|
224
|
+
const usage = { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, reasoning_output_tokens: 0, turns: 0 };
|
|
225
|
+
for (const event of await readTaskEvents(taskId, 50, ["turn.completed"])) {
|
|
226
|
+
const block = event?.usage ?? {};
|
|
227
|
+
usage.turns += 1;
|
|
228
|
+
for (const key of ["input_tokens", "cached_input_tokens", "output_tokens", "reasoning_output_tokens"]) {
|
|
229
|
+
usage[key] += Number(block[key] ?? 0) || 0;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
const commands = (task.commands ?? []).slice(-40).map((entry) => ({
|
|
233
|
+
...entry,
|
|
234
|
+
command: clip(entry.command, 600)
|
|
235
|
+
}));
|
|
236
|
+
return {
|
|
237
|
+
...workerRow(task),
|
|
238
|
+
prompt: task.prompt ?? null,
|
|
239
|
+
changed_files: readTaskChanges(task),
|
|
240
|
+
commands,
|
|
241
|
+
reports: reports.length > 0 ? reports : task.last_message ? [task.last_message] : [],
|
|
242
|
+
native_goal: readNativeGoal(task.thread_id),
|
|
243
|
+
usage,
|
|
244
|
+
notices: task.notices ?? null,
|
|
245
|
+
run_log: task.run_log ?? null,
|
|
246
|
+
event_kinds: await listTaskEventKinds(taskId)
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function events(taskId, url) {
|
|
251
|
+
const limit = Math.min(1000, Math.max(1, Number(url.searchParams.get("limit") ?? 150)));
|
|
252
|
+
const kinds = url.searchParams.get("kinds")?.split(",").filter(Boolean) ?? null;
|
|
253
|
+
return { task_id: taskId, events: await readTaskEvents(taskId, limit, kinds) };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Read a JSON request body, capped so a stray client cannot fill memory.
|
|
257
|
+
function readJson(req, limit = 2 * 1024 * 1024) {
|
|
258
|
+
return new Promise((resolve, reject) => {
|
|
259
|
+
let size = 0;
|
|
260
|
+
const chunks = [];
|
|
261
|
+
req.on("data", (chunk) => {
|
|
262
|
+
size += chunk.length;
|
|
263
|
+
if (size > limit) {
|
|
264
|
+
reject(Object.assign(new Error("request body too large"), { code: "too_large" }));
|
|
265
|
+
req.destroy();
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
chunks.push(chunk);
|
|
269
|
+
});
|
|
270
|
+
req.on("end", () => {
|
|
271
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
272
|
+
if (!text.trim()) return resolve({});
|
|
273
|
+
try {
|
|
274
|
+
resolve(JSON.parse(text));
|
|
275
|
+
} catch (error) {
|
|
276
|
+
reject(Object.assign(new Error(`invalid JSON body: ${error.message}`), { code: "bad_json" }));
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
req.on("error", reject);
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// The last user message of an AI SDK useChat request, as plain text.
|
|
284
|
+
function lastUserText(body) {
|
|
285
|
+
if (typeof body?.text === "string") return body.text;
|
|
286
|
+
const messages = Array.isArray(body?.messages) ? body.messages : [];
|
|
287
|
+
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
|
288
|
+
const m = messages[i];
|
|
289
|
+
if (m?.role !== "user") continue;
|
|
290
|
+
const parts = Array.isArray(m.parts) ? m.parts : [];
|
|
291
|
+
const text = parts.filter((p) => p?.type === "text").map((p) => p.text ?? "").join("\n").trim();
|
|
292
|
+
if (text) return text;
|
|
293
|
+
if (typeof m.content === "string" && m.content.trim()) return m.content.trim();
|
|
294
|
+
}
|
|
295
|
+
return "";
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function json(res, status, body) {
|
|
299
|
+
const text = JSON.stringify(body);
|
|
300
|
+
res.writeHead(status, {
|
|
301
|
+
"content-type": "application/json; charset=utf-8",
|
|
302
|
+
"cache-control": "no-store",
|
|
303
|
+
"content-length": Buffer.byteLength(text)
|
|
304
|
+
});
|
|
305
|
+
res.end(text);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function serveStatic(res, pathname) {
|
|
309
|
+
if (!existsSync(distDir)) {
|
|
310
|
+
res.writeHead(503, { "content-type": "text/plain; charset=utf-8" });
|
|
311
|
+
res.end("web/dist is missing. Run `npm run web:build` first.\n");
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
const safe = normalize(pathname).replace(/^(\.\.[/\\])+/, "");
|
|
315
|
+
let file = join(distDir, safe);
|
|
316
|
+
if (!file.startsWith(distDir)) {
|
|
317
|
+
res.writeHead(403);
|
|
318
|
+
res.end();
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
if (!existsSync(file) || statSync(file).isDirectory()) file = join(distDir, "index.html");
|
|
322
|
+
const type = MIME[extname(file)] ?? "application/octet-stream";
|
|
323
|
+
res.writeHead(200, {
|
|
324
|
+
"content-type": type,
|
|
325
|
+
"cache-control": file.endsWith("index.html") ? "no-store" : "public, max-age=31536000, immutable"
|
|
326
|
+
});
|
|
327
|
+
createReadStream(file).pipe(res);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
async function route(req, res) {
|
|
331
|
+
const url = new URL(req.url ?? "/", `http://${host}`);
|
|
332
|
+
const parts = url.pathname.split("/").filter(Boolean);
|
|
333
|
+
if (parts[0] !== "api") return serveStatic(res, url.pathname);
|
|
334
|
+
|
|
335
|
+
// The side chat is the one place the board does something: it forks the
|
|
336
|
+
// worker's Codex thread for a read-only side question.
|
|
337
|
+
if (parts[1] === "workers" && parts.length >= 4 && parts[3] === "chat") {
|
|
338
|
+
const taskId = decodeURIComponent(parts[2]);
|
|
339
|
+
const task = await getTask(taskId);
|
|
340
|
+
if (!task) return json(res, 404, { error: "task_not_found" });
|
|
341
|
+
const action = parts[4] ?? null;
|
|
342
|
+
// GET .../chat/<chatId>/stream is what the AI SDK client calls to
|
|
343
|
+
// resume: replay the running turn, or 204 when nothing is running.
|
|
344
|
+
if (req.method === "GET" && parts.length === 6 && parts[5] === "stream") {
|
|
345
|
+
attachToTurn(taskId, res);
|
|
346
|
+
return undefined;
|
|
347
|
+
}
|
|
348
|
+
if (req.method === "GET" && !action) return json(res, 200, { task_id: taskId, can_ask: Boolean(task.thread_id), worker_status: task.status, ...(await sideSessionState(taskId)) });
|
|
349
|
+
if (req.method === "DELETE" && !action) return json(res, 200, { task_id: taskId, ...(await endSideSession(taskId)) });
|
|
350
|
+
if (req.method === "POST" && action === "stop") return json(res, 200, { task_id: taskId, ...stopSideTurn(taskId) });
|
|
351
|
+
if (req.method === "POST" && !action) {
|
|
352
|
+
let body;
|
|
353
|
+
try {
|
|
354
|
+
body = await readJson(req);
|
|
355
|
+
} catch (error) {
|
|
356
|
+
return json(res, 400, { error: error.code ?? "bad_request", message: error.message });
|
|
357
|
+
}
|
|
358
|
+
const text = lastUserText(body);
|
|
359
|
+
if (!text) return json(res, 400, { error: "empty_question", message: "send a user message with text" });
|
|
360
|
+
try {
|
|
361
|
+
await runSideTurn({ task, text, res });
|
|
362
|
+
} catch (error) {
|
|
363
|
+
if (res.headersSent) return undefined;
|
|
364
|
+
const status = error.code === "busy" ? 409 : error.code === "no_thread" ? 400 : error.code === "codex_missing" ? 503 : 500;
|
|
365
|
+
return json(res, status, { error: error.code ?? "side_chat_failed", message: error.message });
|
|
366
|
+
}
|
|
367
|
+
return undefined;
|
|
368
|
+
}
|
|
369
|
+
return json(res, 405, { error: "method_not_allowed" });
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
if (req.method !== "GET") return json(res, 405, { error: "method_not_allowed" });
|
|
373
|
+
|
|
374
|
+
if (parts[1] === "overview" && parts.length === 2) return json(res, 200, await overview(pageParams(url, 20)));
|
|
375
|
+
if (parts[1] === "version" && parts.length === 2) {
|
|
376
|
+
return json(res, 200, await checkForUpdate({ force: url.searchParams.get("force") === "1" }));
|
|
377
|
+
}
|
|
378
|
+
if (parts[1] === "sessions" && parts.length === 3) {
|
|
379
|
+
const body = await session(decodeURIComponent(parts[2]), pageParams(url, 40));
|
|
380
|
+
return body ? json(res, 200, body) : json(res, 404, { error: "session_not_found" });
|
|
381
|
+
}
|
|
382
|
+
if (parts[1] === "workers" && parts.length === 3) {
|
|
383
|
+
const body = await worker(decodeURIComponent(parts[2]));
|
|
384
|
+
return body ? json(res, 200, body) : json(res, 404, { error: "task_not_found" });
|
|
385
|
+
}
|
|
386
|
+
if (parts[1] === "workers" && parts.length === 4 && parts[3] === "events") {
|
|
387
|
+
const taskId = decodeURIComponent(parts[2]);
|
|
388
|
+
if (!(await getTask(taskId))) return json(res, 404, { error: "task_not_found" });
|
|
389
|
+
return json(res, 200, await events(taskId, url));
|
|
390
|
+
}
|
|
391
|
+
return json(res, 404, { error: "not_found" });
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
export function startWebServer({ storeOrigin = "default" } = {}) {
|
|
395
|
+
const server = createServer((req, res) => {
|
|
396
|
+
route(req, res).catch((error) => {
|
|
397
|
+
process.stderr.write(`[codex-supervisor-web] ${error.stack ?? error.message}\n`);
|
|
398
|
+
if (!res.headersSent) json(res, 500, { error: "internal", message: error.message });
|
|
399
|
+
else res.end();
|
|
400
|
+
});
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
// A taken port is the one error a person will actually hit, usually because
|
|
404
|
+
// a board is already running. Say that, not a stack trace.
|
|
405
|
+
server.on("error", (error) => {
|
|
406
|
+
if (error.code === "EADDRINUSE") {
|
|
407
|
+
process.stderr.write(
|
|
408
|
+
`codex-supervisor-web: port ${port} on ${host} is already in use.\n` +
|
|
409
|
+
` A board may already be running at http://${host}:${port}\n` +
|
|
410
|
+
` To run a second one, pick another port: SUPERVISOR_WEB_PORT=8080 codex-supervisor-web\n`
|
|
411
|
+
);
|
|
412
|
+
process.exit(1);
|
|
413
|
+
}
|
|
414
|
+
process.stderr.write(`codex-supervisor-web: ${error.message}\n`);
|
|
415
|
+
process.exit(1);
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
server.listen(port, host, () => {
|
|
419
|
+
process.stdout.write(`codex-supervisor web view on http://${host}:${port}\n store: ${supervisorRoot} (${storeOrigin})\n`);
|
|
420
|
+
});
|
|
421
|
+
return server;
|
|
422
|
+
}
|