codex-supervisor-mcp 0.0.0-stage → 0.4.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.
@@ -0,0 +1,540 @@
1
+ import { createWriteStream } from "node:fs";
2
+ import { mkdir, rm, stat } from "node:fs/promises";
3
+ import { randomUUID } from "node:crypto";
4
+ import { execFileSync, spawn } from "node:child_process";
5
+ import { join, resolve } from "node:path";
6
+ import {
7
+ appendTaskEvent,
8
+ getTask,
9
+ readActiveTasks,
10
+ readTaskEvents,
11
+ taskRunPath,
12
+ upsertTask
13
+ } from "./task-store.js";
14
+ import { applyCodexEvent } from "./event-parser.js";
15
+ import { TERMINAL_STATUSES } from "./status.js";
16
+ import { worktreesDir } from "./paths.js";
17
+ import { withGoalPreamble } from "./prompt.js";
18
+ import { mergeChangedFiles, readWorktreeChanges } from "./worktree.js";
19
+
20
+ const processes = new Map();
21
+ const cancelledTasks = new Set();
22
+ const defaultCodexBin = process.env.CODEX_BIN?.trim() || "codex";
23
+ const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
24
+ const allowedReasoningEfforts = new Set(["minimal", "low", "medium", "high"]);
25
+
26
+ function splitLines(buffer, chunk) {
27
+ const next = buffer + chunk;
28
+ const lines = next.split(/\r?\n/);
29
+ return { lines: lines.slice(0, -1), rest: lines.at(-1) ?? "" };
30
+ }
31
+
32
+ async function exists(path) {
33
+ if (!path) return false;
34
+ try {
35
+ await stat(path);
36
+ return true;
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+
42
+ function runCommand(command, args, options = {}) {
43
+ return new Promise((resolvePromise, reject) => {
44
+ const child = spawn(command, args, { stdio: "ignore", ...options });
45
+ child.on("exit", (code) => {
46
+ if (code === 0) resolvePromise();
47
+ else reject(new Error(`${command} ${args.join(" ")} exited with ${code}`));
48
+ });
49
+ child.on("error", reject);
50
+ });
51
+ }
52
+
53
+ async function ensureWorktree(cwd, taskId) {
54
+ const taskWorktreeDir = join(worktreesDir, taskId);
55
+ await mkdir(worktreesDir, { recursive: true });
56
+ const gitDir = join(cwd, ".git");
57
+ if (!(await exists(cwd)) || !(await exists(gitDir))) {
58
+ return null;
59
+ }
60
+ try {
61
+ await rm(taskWorktreeDir, { recursive: true, force: true });
62
+ const branch = `codex/${taskId}`;
63
+ await runCommand(defaultGitBin, ["-C", cwd, "worktree", "add", "--detach", taskWorktreeDir, "HEAD"]);
64
+ await runCommand(defaultGitBin, ["-C", taskWorktreeDir, "switch", "-c", branch]);
65
+ return taskWorktreeDir;
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+
71
+ function normalizeOwnedPaths(ownedPaths, projectRoot) {
72
+ if (!Array.isArray(ownedPaths)) return [];
73
+ return Array.from(new Set(ownedPaths.map((entry) => resolve(projectRoot, String(entry).trim()))));
74
+ }
75
+
76
+ function pathOverlaps(left, right) {
77
+ if (left === right) return true;
78
+ const leftPrefix = left.endsWith("/") ? left : `${left}/`;
79
+ const rightPrefix = right.endsWith("/") ? right : `${right}/`;
80
+ return leftPrefix.startsWith(rightPrefix) || rightPrefix.startsWith(leftPrefix);
81
+ }
82
+
83
+ // Two workers claiming overlapping paths will collide when their branches are
84
+ // merged, so the second dispatch is refused before any worktree is created.
85
+ export async function findOwnershipConflicts(ownedPaths, { excludeTaskId = null } = {}) {
86
+ if (!ownedPaths || ownedPaths.length === 0) return [];
87
+ const activeTasks = await readActiveTasks();
88
+ const conflicts = [];
89
+ for (const task of activeTasks) {
90
+ if (task.id === excludeTaskId) continue;
91
+ const theirs = Array.isArray(task.owned_paths) ? task.owned_paths : [];
92
+ const overlap = [];
93
+ for (const mine of ownedPaths) {
94
+ for (const other of theirs) {
95
+ if (pathOverlaps(mine, other)) overlap.push({ incoming: mine, existing: other });
96
+ }
97
+ }
98
+ if (overlap.length > 0) {
99
+ conflicts.push({
100
+ task_id: task.id,
101
+ title: task.title,
102
+ status: task.status,
103
+ overlapping_paths: overlap
104
+ });
105
+ }
106
+ }
107
+ return conflicts;
108
+ }
109
+
110
+ function ownershipConflictError(conflicts) {
111
+ const owners = conflicts.map((conflict) => conflict.task_id).join(", ");
112
+ const error = new Error(`ownedPaths overlap with active worker(s): ${owners}`);
113
+ error.code = "ownership_conflict";
114
+ error.conflicts = conflicts;
115
+ return error;
116
+ }
117
+
118
+ // Spawn can fail either by throwing synchronously, or by emitting "error"
119
+ // instead of "spawn". Both paths are handled so a bad CODEX_BIN marks the task
120
+ // failed instead of taking the whole MCP process down.
121
+ async function spawnAndAwaitStart(args, options) {
122
+ const child = spawn(defaultCodexBin, args, options);
123
+ const spawnError = await new Promise((resolvePromise) => {
124
+ let settled = false;
125
+ child.once("spawn", () => {
126
+ if (!settled) {
127
+ settled = true;
128
+ resolvePromise(null);
129
+ }
130
+ });
131
+ child.once("error", (error) => {
132
+ if (!settled) {
133
+ settled = true;
134
+ resolvePromise(error);
135
+ }
136
+ });
137
+ });
138
+ return { child, spawnError };
139
+ }
140
+
141
+ // Attaches stream handlers and keeps `record` in the supervisor database.
142
+ // Every write goes through one serialized chain so concurrent stdout/stderr
143
+ // callbacks cannot interleave and persist out of order.
144
+ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {} }) {
145
+ const { child, spawnError } = await spawnAndAwaitStart(args, {
146
+ stdio: ["pipe", "pipe", "pipe"],
147
+ env: { ...process.env, NO_COLOR: "1" },
148
+ ...spawnOptions
149
+ });
150
+
151
+ if (spawnError) {
152
+ const now = new Date().toISOString();
153
+ return {
154
+ ok: false,
155
+ record: {
156
+ ...record,
157
+ status: "failed",
158
+ phase: null,
159
+ pid: null,
160
+ error: `failed to spawn ${defaultCodexBin}: ${spawnError.message}`,
161
+ completed_at: now,
162
+ updated_at: now
163
+ }
164
+ };
165
+ }
166
+
167
+ const now = new Date().toISOString();
168
+ let live = {
169
+ ...record,
170
+ status: "running",
171
+ phase: "starting",
172
+ pid: child.pid ?? null,
173
+ started_at: now,
174
+ completed_at: null,
175
+ exit_code: null,
176
+ signal: null,
177
+ run_count: (record.run_count ?? 0) + 1,
178
+ updated_at: now
179
+ };
180
+ processes.set(record.id, child);
181
+
182
+ let writeChain = Promise.resolve();
183
+ const persist = (next) => {
184
+ live = next;
185
+ const snapshot = live;
186
+ writeChain = writeChain
187
+ .then(() => upsertTask(snapshot))
188
+ .catch((error) => {
189
+ process.stderr.write(`[codex-supervisor] persist failed for ${snapshot.id}: ${error.message}\n`);
190
+ });
191
+ return writeChain;
192
+ };
193
+
194
+ const logStream = createWriteStream(logPath, { flags: "a" });
195
+ logStream.on("error", () => {});
196
+
197
+ // A child that exits early makes this write fail with EPIPE. That must not
198
+ // reach the process level, or one oversized prompt kills the MCP server.
199
+ child.stdin.on("error", (error) => {
200
+ persist({
201
+ ...live,
202
+ error: live.error ?? `stdin write failed: ${error.message}`,
203
+ updated_at: new Date().toISOString()
204
+ });
205
+ });
206
+
207
+ let eventChain = Promise.resolve();
208
+ const handleLine = async (line) => {
209
+ let event;
210
+ try {
211
+ event = JSON.parse(line);
212
+ } catch (error) {
213
+ logStream.write(`${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
214
+ return;
215
+ }
216
+ logStream.write(`${JSON.stringify(event)}\n`);
217
+ await appendTaskEvent(record.id, event);
218
+ await persist(applyCodexEvent(live, event));
219
+ };
220
+
221
+ let stdoutRest = "";
222
+ child.stdout.on("data", (chunk) => {
223
+ const split = splitLines(stdoutRest, chunk.toString("utf8"));
224
+ stdoutRest = split.rest;
225
+ for (const line of split.lines) {
226
+ if (!line.trim()) continue;
227
+ eventChain = eventChain.then(() => handleLine(line)).catch((error) => {
228
+ process.stderr.write(`[codex-supervisor] event handling failed for ${record.id}: ${error.message}\n`);
229
+ });
230
+ }
231
+ });
232
+ child.stdout.on("error", () => {});
233
+
234
+ let stderr = "";
235
+ child.stderr.on("data", (chunk) => {
236
+ stderr += chunk.toString("utf8");
237
+ persist({ ...live, stderr_tail: stderr.slice(-4000), updated_at: new Date().toISOString() });
238
+ });
239
+ child.stderr.on("error", () => {});
240
+
241
+ child.on("error", (error) => {
242
+ persist({
243
+ ...live,
244
+ error: live.error ?? `codex process error: ${error.message}`,
245
+ updated_at: new Date().toISOString()
246
+ });
247
+ });
248
+
249
+ child.on("exit", async (code, signal) => {
250
+ processes.delete(record.id);
251
+ await eventChain.catch(() => {});
252
+ logStream.end();
253
+ const finishedAt = new Date().toISOString();
254
+ const stored = await getTask(record.id).catch(() => null);
255
+ // A cancel can be issued from another MCP process, so the marker is read
256
+ // back from disk rather than trusted to this process's memory.
257
+ const cancelRequested = cancelledTasks.has(record.id)
258
+ || Boolean(live.cancel_requested_at)
259
+ || Boolean(stored?.cancel_requested_at);
260
+ let status;
261
+ if (stored && TERMINAL_STATUSES.has(stored.status) && stored.status !== live.status) status = stored.status;
262
+ else if (TERMINAL_STATUSES.has(live.status) && live.status !== "failed") status = live.status;
263
+ else if (cancelRequested) status = "cancelled";
264
+ // Killed by a signal nobody asked for: the worker did not fail, it
265
+ // vanished. Re-running is the fix, so it is reported as lost.
266
+ else if (signal) status = "lost";
267
+ else if (code === 0) status = "completed";
268
+ else status = "failed";
269
+ const next = {
270
+ ...live,
271
+ status,
272
+ phase: null,
273
+ changed_files: mergeChangedFiles(live.changed_files, readWorktreeChanges(live.worktree_path)),
274
+ exit_code: code,
275
+ signal,
276
+ current_command: null,
277
+ current_action: status === "completed" ? "Completed" : live.current_action,
278
+ completed_at: live.completed_at ?? finishedAt,
279
+ updated_at: finishedAt
280
+ };
281
+ if (status === "failed" && !next.error) {
282
+ next.error = `codex exited with code ${code}${signal ? ` (signal ${signal})` : ""}`;
283
+ }
284
+ if (status === "lost" && !next.error) {
285
+ next.error = `codex worker was killed by signal ${signal} before writing a terminal event`;
286
+ }
287
+ if (status === "cancelled") next.error = null;
288
+ await persist(next);
289
+ cancelledTasks.delete(record.id);
290
+ });
291
+
292
+ try {
293
+ child.stdin.end(prompt);
294
+ } catch (error) {
295
+ await persist({
296
+ ...live,
297
+ error: live.error ?? `stdin write failed: ${error.message}`,
298
+ updated_at: new Date().toISOString()
299
+ });
300
+ }
301
+
302
+ return { ok: true, record: live, child };
303
+ }
304
+
305
+ function buildExecArgs({ cwd, sandbox, model, reasoningEffort, skipGitRepoCheck }) {
306
+ const args = ["exec", "--json", "--cd", cwd, "--sandbox", sandbox];
307
+ if (skipGitRepoCheck) args.push("--skip-git-repo-check");
308
+ if (model) args.push("--model", model);
309
+ args.push("-c", `model_reasoning_effort="${reasoningEffort}"`);
310
+ args.push("-");
311
+ return args;
312
+ }
313
+
314
+ function validateGoal(goal) {
315
+ if (!goal || typeof goal !== "object" || typeof goal.objective !== "string" || goal.objective.trim() === "") {
316
+ throw new Error("goal.objective is required");
317
+ }
318
+ const tokenBudget = goal.tokenBudget ?? goal.token_budget ?? null;
319
+ if (tokenBudget !== null && (!Number.isInteger(tokenBudget) || tokenBudget <= 0)) {
320
+ throw new Error("goal.tokenBudget must be a positive integer when provided");
321
+ }
322
+ return { objective: goal.objective, tokenBudget };
323
+ }
324
+
325
+ export async function createCodexWorker({
326
+ title,
327
+ task,
328
+ sessionId = null,
329
+ cwd,
330
+ sandbox = "workspace-write",
331
+ model = null,
332
+ reasoningEffort = "high",
333
+ skipGitRepoCheck = true,
334
+ ownedPaths,
335
+ goal,
336
+ dependsOn = [],
337
+ followupOf = null,
338
+ useWorktree = true
339
+ }) {
340
+ if (!task || typeof task !== "string") throw new Error("task is required");
341
+ if (!cwd || typeof cwd !== "string") throw new Error("cwd is required");
342
+ if (!allowedReasoningEfforts.has(reasoningEffort)) {
343
+ throw new Error(`unsupported reasoningEffort: ${reasoningEffort}`);
344
+ }
345
+ if (!Array.isArray(ownedPaths) || ownedPaths.length === 0) {
346
+ throw new Error("ownedPaths is required and must list at least one path this worker is allowed to write");
347
+ }
348
+ const validatedGoal = validateGoal(goal);
349
+
350
+ const projectRoot = cwd;
351
+ const normalizedOwnedPaths = normalizeOwnedPaths(ownedPaths, projectRoot);
352
+ const conflicts = await findOwnershipConflicts(normalizedOwnedPaths);
353
+ if (conflicts.length > 0) throw ownershipConflictError(conflicts);
354
+
355
+ const id = `codex-${Date.now()}-${randomUUID().slice(0, 8)}`;
356
+ const worktreePath = useWorktree ? await ensureWorktree(projectRoot, id) : null;
357
+ const effectiveCwd = worktreePath ?? projectRoot;
358
+
359
+ const record = {
360
+ id,
361
+ title: title || task.split("\n").find(Boolean)?.slice(0, 80) || "Codex worker",
362
+ worker: "codex",
363
+ status: "queued",
364
+ phase: null,
365
+ cwd: effectiveCwd,
366
+ project_root: projectRoot,
367
+ sandbox,
368
+ model,
369
+ reasoning_effort: reasoningEffort,
370
+ skip_git_repo_check: skipGitRepoCheck,
371
+ followup_of: followupOf,
372
+ resumed_from: null,
373
+ session_id: sessionId ?? null,
374
+ thread_id: null,
375
+ owned_paths: normalizedOwnedPaths,
376
+ depends_on: Array.isArray(dependsOn) ? dependsOn : [],
377
+ goal_objective: validatedGoal.objective,
378
+ goal_token_budget: validatedGoal.tokenBudget,
379
+ goal_status: null,
380
+ goal_tokens_used: null,
381
+ goal_time_used_seconds: null,
382
+ goal_updated_at: null,
383
+ run_count: 0,
384
+ worktree_path: worktreePath,
385
+ prompt: task,
386
+ changed_files: [],
387
+ commands: [],
388
+ created_at: new Date().toISOString(),
389
+ updated_at: new Date().toISOString(),
390
+ run_log: taskRunPath(id)
391
+ };
392
+ await upsertTask(record);
393
+
394
+ const args = buildExecArgs({ cwd: effectiveCwd, sandbox, model, reasoningEffort, skipGitRepoCheck });
395
+
396
+ const started = await startTrackedRun({
397
+ record,
398
+ args,
399
+ prompt: withGoalPreamble(task, {
400
+ objective: validatedGoal.objective,
401
+ tokenBudget: validatedGoal.tokenBudget
402
+ }),
403
+ logPath: record.run_log
404
+ });
405
+ await upsertTask(started.record);
406
+ return started.record;
407
+ }
408
+
409
+ // Continue the *same* Codex session. The worktree, thread id, ownership and
410
+ // goal are all inherited from the original task, and the row is reused so one
411
+ // logical piece of work stays one row.
412
+ export async function resumeCodexWorker({ taskId, prompt }) {
413
+ if (!prompt || typeof prompt !== "string") throw new Error("prompt is required");
414
+ const task = await getTask(taskId);
415
+ if (!task) throw new Error(`task not found: ${taskId}`);
416
+ if (!task.thread_id) {
417
+ throw new Error(
418
+ `task ${taskId} has no Codex thread_id recorded. Only workers created by this version of codex-supervisor-mcp can be resumed; use create_codex_followup_worker otherwise.`
419
+ );
420
+ }
421
+
422
+ const cwd = (await exists(task.cwd)) ? task.cwd : task.project_root;
423
+ const args = ["exec", "resume", "--json"];
424
+ args.push("-c", `sandbox_mode="${task.sandbox}"`);
425
+ if (task.model) args.push("--model", task.model);
426
+ args.push("-c", `model_reasoning_effort="${task.reasoning_effort ?? "high"}"`);
427
+ if (task.skip_git_repo_check) args.push("--skip-git-repo-check");
428
+ args.push(task.thread_id);
429
+ args.push("-");
430
+
431
+ const started = await startTrackedRun({
432
+ record: { ...task, resumed_from: task.resumed_from ?? task.id },
433
+ args,
434
+ prompt: withGoalPreamble(prompt, {
435
+ objective: task.goal_objective ?? task.title ?? task.id,
436
+ resume: true
437
+ }),
438
+ logPath: task.run_log,
439
+ spawnOptions: { cwd }
440
+ });
441
+ await upsertTask(started.record);
442
+ return started.record;
443
+ }
444
+
445
+ function isLikelyCodexProcess(pid) {
446
+ try {
447
+ const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], {
448
+ encoding: "utf8",
449
+ timeout: 2000
450
+ }).trim();
451
+ return command.includes("codex");
452
+ } catch {
453
+ return false;
454
+ }
455
+ }
456
+
457
+ export async function cancelCodexWorker(taskId) {
458
+ const child = processes.get(taskId);
459
+ if (child) {
460
+ cancelledTasks.add(taskId);
461
+ child.kill("SIGTERM");
462
+ return { cancelled: true, via: "process_handle", pid: child.pid ?? null };
463
+ }
464
+ // Another MCP process owns the handle; fall back to the pid recorded on disk.
465
+ const task = await getTask(taskId);
466
+ if (task?.pid && (await isPidAlive(task.pid)) && isLikelyCodexProcess(task.pid)) {
467
+ try {
468
+ process.kill(task.pid, "SIGTERM");
469
+ return { cancelled: true, via: "pid", pid: task.pid };
470
+ } catch (error) {
471
+ return { cancelled: false, reason: "kill_failed", message: error.message, pid: task.pid };
472
+ }
473
+ }
474
+ return { cancelled: false, reason: "process_not_found" };
475
+ }
476
+
477
+ async function isPidAlive(pid) {
478
+ if (!pid) return false;
479
+ try {
480
+ process.kill(pid, 0);
481
+ return true;
482
+ } catch {
483
+ return false;
484
+ }
485
+ }
486
+
487
+ export async function createFollowupWorker({
488
+ taskId,
489
+ followupPrompt,
490
+ sessionId = null,
491
+ title,
492
+ cwd,
493
+ sandbox,
494
+ model,
495
+ reasoningEffort,
496
+ ownedPaths,
497
+ goal
498
+ }) {
499
+ const parent = await getTask(taskId);
500
+ if (!parent) throw new Error(`task not found: ${taskId}`);
501
+ const recentEvents = await readTaskEvents(taskId, 20);
502
+ const prompt = [
503
+ "You are continuing a previous Codex worker run.",
504
+ "",
505
+ `Parent task ID: ${parent.id}`,
506
+ `Parent status: ${parent.status}`,
507
+ `Parent title: ${parent.title}`,
508
+ "",
509
+ "Parent prompt:",
510
+ parent.prompt,
511
+ "",
512
+ "Parent recent summary:",
513
+ `- current_action: ${parent.current_action ?? "-"}`,
514
+ `- current_command: ${parent.current_command ?? "-"}`,
515
+ `- changed_files: ${(parent.changed_files ?? []).join(", ") || "-"}`,
516
+ `- last_message: ${parent.last_message ?? "-"}`,
517
+ "",
518
+ "Parent recent events:",
519
+ ...recentEvents.map((event) => `- ${JSON.stringify(event)}`),
520
+ "",
521
+ "Follow-up instruction:",
522
+ followupPrompt
523
+ ].join("\n");
524
+
525
+ return createCodexWorker({
526
+ title: title ?? `Follow-up for ${parent.id}`,
527
+ task: prompt,
528
+ sessionId: sessionId ?? parent.session_id ?? null,
529
+ cwd: cwd ?? parent.project_root ?? parent.cwd,
530
+ sandbox: sandbox ?? parent.sandbox,
531
+ model: model ?? parent.model,
532
+ reasoningEffort: reasoningEffort ?? parent.reasoning_effort ?? "high",
533
+ skipGitRepoCheck: parent.skip_git_repo_check,
534
+ ownedPaths: ownedPaths ?? parent.owned_paths,
535
+ goal: goal ?? { objective: parent.goal_objective ?? `Follow-up for ${parent.id}`, tokenBudget: parent.goal_token_budget ?? undefined },
536
+ dependsOn: [parent.id],
537
+ followupOf: parent.id,
538
+ useWorktree: true
539
+ });
540
+ }