codex-supervisor-mcp 0.0.0-stage → 0.5.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/LICENSE +21 -0
- package/README.md +270 -2
- package/package.json +70 -4
- package/skills/codex-supervisor/SKILL.md +114 -0
- package/src/bin-resolver.js +272 -0
- package/src/cleanup.js +128 -0
- package/src/codex-runner.js +625 -0
- package/src/event-parser.js +176 -0
- package/src/goal-store.js +51 -0
- package/src/mcp-server.js +599 -0
- package/src/monitor.jsx +298 -0
- package/src/paths.js +22 -0
- package/src/prompt.js +39 -0
- package/src/setup.js +317 -0
- package/src/status.js +37 -0
- package/src/task-store.js +453 -0
- package/src/truncate.js +135 -0
- package/src/worktree.js +44 -0
|
@@ -0,0 +1,625 @@
|
|
|
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, sep } 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
|
+
import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
|
|
20
|
+
|
|
21
|
+
const processes = new Map();
|
|
22
|
+
const cancelledTasks = new Set();
|
|
23
|
+
const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
|
|
24
|
+
const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
25
|
+
const allowedReasoningEfforts = new Set(["minimal", "low", "medium", "high"]);
|
|
26
|
+
|
|
27
|
+
function splitLines(buffer, chunk) {
|
|
28
|
+
const next = buffer + chunk;
|
|
29
|
+
const lines = next.split(/\r?\n/);
|
|
30
|
+
return { lines: lines.slice(0, -1), rest: lines.at(-1) ?? "" };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function exists(path) {
|
|
34
|
+
if (!path) return false;
|
|
35
|
+
try {
|
|
36
|
+
await stat(path);
|
|
37
|
+
return true;
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function runCommand(command, args, options = {}) {
|
|
44
|
+
return new Promise((resolvePromise, reject) => {
|
|
45
|
+
const child = spawn(command, args, { stdio: "ignore", windowsHide: true, ...options });
|
|
46
|
+
child.on("exit", (code) => {
|
|
47
|
+
if (code === 0) resolvePromise();
|
|
48
|
+
else reject(new Error(`${command} ${args.join(" ")} exited with ${code}`));
|
|
49
|
+
});
|
|
50
|
+
child.on("error", reject);
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function ensureWorktree(cwd, taskId) {
|
|
55
|
+
const taskWorktreeDir = join(worktreesDir, taskId);
|
|
56
|
+
await mkdir(worktreesDir, { recursive: true });
|
|
57
|
+
const gitDir = join(cwd, ".git");
|
|
58
|
+
if (!(await exists(cwd)) || !(await exists(gitDir))) {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
await rm(taskWorktreeDir, { recursive: true, force: true });
|
|
63
|
+
const branch = `codex/${taskId}`;
|
|
64
|
+
await runCommand(defaultGitBin, ["-C", cwd, "worktree", "add", "--detach", taskWorktreeDir, "HEAD"]);
|
|
65
|
+
await runCommand(defaultGitBin, ["-C", taskWorktreeDir, "switch", "-c", branch]);
|
|
66
|
+
return taskWorktreeDir;
|
|
67
|
+
} catch {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function normalizeOwnedPaths(ownedPaths, projectRoot) {
|
|
73
|
+
if (!Array.isArray(ownedPaths)) return [];
|
|
74
|
+
return Array.from(new Set(ownedPaths.map((entry) => resolve(projectRoot, String(entry).trim()))));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function pathOverlaps(left, right) {
|
|
78
|
+
// Windows paths are case-insensitive and may mix separators, so compare on a
|
|
79
|
+
// normalized form there. macOS and Linux keep the exact previous comparison -
|
|
80
|
+
// a backslash is a legal filename character on those platforms.
|
|
81
|
+
const windows = process.platform === "win32";
|
|
82
|
+
const normalize = (value) => (windows ? value.replace(/[\\/]+/g, sep).toLowerCase() : value);
|
|
83
|
+
const mine = normalize(left);
|
|
84
|
+
const theirs = normalize(right);
|
|
85
|
+
if (mine === theirs) return true;
|
|
86
|
+
const minePrefix = mine.endsWith(sep) ? mine : `${mine}${sep}`;
|
|
87
|
+
const theirsPrefix = theirs.endsWith(sep) ? theirs : `${theirs}${sep}`;
|
|
88
|
+
return minePrefix.startsWith(theirsPrefix) || theirsPrefix.startsWith(minePrefix);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Two workers claiming overlapping paths will collide when their branches are
|
|
92
|
+
// merged, so the second dispatch is refused before any worktree is created.
|
|
93
|
+
export async function findOwnershipConflicts(ownedPaths, { excludeTaskId = null } = {}) {
|
|
94
|
+
if (!ownedPaths || ownedPaths.length === 0) return [];
|
|
95
|
+
const activeTasks = await readActiveTasks();
|
|
96
|
+
const conflicts = [];
|
|
97
|
+
for (const task of activeTasks) {
|
|
98
|
+
if (task.id === excludeTaskId) continue;
|
|
99
|
+
const theirs = Array.isArray(task.owned_paths) ? task.owned_paths : [];
|
|
100
|
+
const overlap = [];
|
|
101
|
+
for (const mine of ownedPaths) {
|
|
102
|
+
for (const other of theirs) {
|
|
103
|
+
if (pathOverlaps(mine, other)) overlap.push({ incoming: mine, existing: other });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (overlap.length > 0) {
|
|
107
|
+
conflicts.push({
|
|
108
|
+
task_id: task.id,
|
|
109
|
+
title: task.title,
|
|
110
|
+
status: task.status,
|
|
111
|
+
overlapping_paths: overlap
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return conflicts;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function ownershipConflictError(conflicts) {
|
|
119
|
+
const owners = conflicts.map((conflict) => conflict.task_id).join(", ");
|
|
120
|
+
const error = new Error(`ownedPaths overlap with active worker(s): ${owners}`);
|
|
121
|
+
error.code = "ownership_conflict";
|
|
122
|
+
error.conflicts = conflicts;
|
|
123
|
+
return error;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// The Codex CLI as a spawnable target. On Windows npm installs a `codex.cmd`
|
|
127
|
+
// shim that Node refuses to spawn directly, so bin-resolver.js steps over it and
|
|
128
|
+
// hands back `node <entry>` instead; on macOS and Linux this is the bare name,
|
|
129
|
+
// unchanged. Resolved per dispatch so a CLI installed later is picked up.
|
|
130
|
+
function codexTarget() {
|
|
131
|
+
const configured = process.env.CODEX_BIN?.trim();
|
|
132
|
+
const located = configured ? configured : (findBinaryPath("codex", { extraDirs: defaultBinDirs() }) ?? "codex");
|
|
133
|
+
const target = resolveCommand(located, { npmEntry: CODEX_NPM_ENTRY });
|
|
134
|
+
if (target.shim) return { error: shimMessage("codex", target.cmd, "CODEX_BIN") };
|
|
135
|
+
return { cmd: target.cmd, prefixArgs: target.prefixArgs };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function failedStart(record, reason) {
|
|
139
|
+
const now = new Date().toISOString();
|
|
140
|
+
return {
|
|
141
|
+
ok: false,
|
|
142
|
+
record: {
|
|
143
|
+
...record,
|
|
144
|
+
status: "failed",
|
|
145
|
+
phase: null,
|
|
146
|
+
pid: null,
|
|
147
|
+
error: reason,
|
|
148
|
+
completed_at: now,
|
|
149
|
+
updated_at: now
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Spawn can fail either by throwing synchronously, or by emitting "error"
|
|
155
|
+
// instead of "spawn". Both paths are handled so a bad CODEX_BIN marks the task
|
|
156
|
+
// failed instead of taking the whole MCP process down.
|
|
157
|
+
async function spawnAndAwaitStart(target, args, options) {
|
|
158
|
+
const child = spawn(target.cmd, [...target.prefixArgs, ...args], options);
|
|
159
|
+
const spawnError = await new Promise((resolvePromise) => {
|
|
160
|
+
let settled = false;
|
|
161
|
+
child.once("spawn", () => {
|
|
162
|
+
if (!settled) {
|
|
163
|
+
settled = true;
|
|
164
|
+
resolvePromise(null);
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
child.once("error", (error) => {
|
|
168
|
+
if (!settled) {
|
|
169
|
+
settled = true;
|
|
170
|
+
resolvePromise(error);
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
return { child, spawnError };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Attaches stream handlers and keeps `record` in the supervisor database.
|
|
178
|
+
// Every write goes through one serialized chain so concurrent stdout/stderr
|
|
179
|
+
// callbacks cannot interleave and persist out of order.
|
|
180
|
+
async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {} }) {
|
|
181
|
+
const target = codexTarget();
|
|
182
|
+
if (target.error) return failedStart(record, target.error);
|
|
183
|
+
|
|
184
|
+
const { child, spawnError } = await spawnAndAwaitStart(target, args, {
|
|
185
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
186
|
+
env: { ...process.env, NO_COLOR: "1" },
|
|
187
|
+
windowsHide: true,
|
|
188
|
+
...spawnOptions
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
if (spawnError) {
|
|
192
|
+
return failedStart(record, `failed to spawn ${target.cmd}: ${spawnError.message}`);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const now = new Date().toISOString();
|
|
196
|
+
let live = {
|
|
197
|
+
...record,
|
|
198
|
+
status: "running",
|
|
199
|
+
phase: "starting",
|
|
200
|
+
pid: child.pid ?? null,
|
|
201
|
+
started_at: now,
|
|
202
|
+
completed_at: null,
|
|
203
|
+
exit_code: null,
|
|
204
|
+
signal: null,
|
|
205
|
+
run_count: (record.run_count ?? 0) + 1,
|
|
206
|
+
updated_at: now
|
|
207
|
+
};
|
|
208
|
+
processes.set(record.id, child);
|
|
209
|
+
|
|
210
|
+
let writeChain = Promise.resolve();
|
|
211
|
+
const persist = (next) => {
|
|
212
|
+
live = next;
|
|
213
|
+
const snapshot = live;
|
|
214
|
+
writeChain = writeChain
|
|
215
|
+
.then(() => upsertTask(snapshot))
|
|
216
|
+
.catch((error) => {
|
|
217
|
+
process.stderr.write(`[codex-supervisor] persist failed for ${snapshot.id}: ${error.message}\n`);
|
|
218
|
+
});
|
|
219
|
+
return writeChain;
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
const logStream = createWriteStream(logPath, { flags: "a" });
|
|
223
|
+
logStream.on("error", () => {});
|
|
224
|
+
|
|
225
|
+
// A child that exits early makes this write fail with EPIPE. That must not
|
|
226
|
+
// reach the process level, or one oversized prompt kills the MCP server.
|
|
227
|
+
child.stdin.on("error", (error) => {
|
|
228
|
+
persist({
|
|
229
|
+
...live,
|
|
230
|
+
error: live.error ?? `stdin write failed: ${error.message}`,
|
|
231
|
+
updated_at: new Date().toISOString()
|
|
232
|
+
});
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
let eventChain = Promise.resolve();
|
|
236
|
+
const handleLine = async (line) => {
|
|
237
|
+
let event;
|
|
238
|
+
try {
|
|
239
|
+
event = JSON.parse(line);
|
|
240
|
+
} catch (error) {
|
|
241
|
+
logStream.write(`${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
logStream.write(`${JSON.stringify(event)}\n`);
|
|
245
|
+
await appendTaskEvent(record.id, event);
|
|
246
|
+
await persist(applyCodexEvent(live, event));
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
let stdoutRest = "";
|
|
250
|
+
child.stdout.on("data", (chunk) => {
|
|
251
|
+
const split = splitLines(stdoutRest, chunk.toString("utf8"));
|
|
252
|
+
stdoutRest = split.rest;
|
|
253
|
+
for (const line of split.lines) {
|
|
254
|
+
if (!line.trim()) continue;
|
|
255
|
+
eventChain = eventChain.then(() => handleLine(line)).catch((error) => {
|
|
256
|
+
process.stderr.write(`[codex-supervisor] event handling failed for ${record.id}: ${error.message}\n`);
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
child.stdout.on("error", () => {});
|
|
261
|
+
|
|
262
|
+
let stderr = "";
|
|
263
|
+
child.stderr.on("data", (chunk) => {
|
|
264
|
+
stderr += chunk.toString("utf8");
|
|
265
|
+
persist({ ...live, stderr_tail: stderr.slice(-4000), updated_at: new Date().toISOString() });
|
|
266
|
+
});
|
|
267
|
+
child.stderr.on("error", () => {});
|
|
268
|
+
|
|
269
|
+
child.on("error", (error) => {
|
|
270
|
+
persist({
|
|
271
|
+
...live,
|
|
272
|
+
error: live.error ?? `codex process error: ${error.message}`,
|
|
273
|
+
updated_at: new Date().toISOString()
|
|
274
|
+
});
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
child.on("exit", async (code, signal) => {
|
|
278
|
+
processes.delete(record.id);
|
|
279
|
+
await eventChain.catch(() => {});
|
|
280
|
+
logStream.end();
|
|
281
|
+
const finishedAt = new Date().toISOString();
|
|
282
|
+
const stored = await getTask(record.id).catch(() => null);
|
|
283
|
+
// A cancel can be issued from another MCP process, so the marker is read
|
|
284
|
+
// back from disk rather than trusted to this process's memory.
|
|
285
|
+
const cancelRequested = cancelledTasks.has(record.id)
|
|
286
|
+
|| Boolean(live.cancel_requested_at)
|
|
287
|
+
|| Boolean(stored?.cancel_requested_at);
|
|
288
|
+
let status;
|
|
289
|
+
if (stored && TERMINAL_STATUSES.has(stored.status) && stored.status !== live.status) status = stored.status;
|
|
290
|
+
else if (TERMINAL_STATUSES.has(live.status) && live.status !== "failed") status = live.status;
|
|
291
|
+
else if (cancelRequested) status = "cancelled";
|
|
292
|
+
// Killed by a signal nobody asked for: the worker did not fail, it
|
|
293
|
+
// vanished. Re-running is the fix, so it is reported as lost.
|
|
294
|
+
else if (signal) status = "lost";
|
|
295
|
+
else if (code === 0) status = "completed";
|
|
296
|
+
else status = "failed";
|
|
297
|
+
const next = {
|
|
298
|
+
...live,
|
|
299
|
+
status,
|
|
300
|
+
phase: null,
|
|
301
|
+
changed_files: mergeChangedFiles(live.changed_files, readWorktreeChanges(live.worktree_path)),
|
|
302
|
+
exit_code: code,
|
|
303
|
+
signal,
|
|
304
|
+
current_command: null,
|
|
305
|
+
current_action: status === "completed" ? "Completed" : live.current_action,
|
|
306
|
+
completed_at: live.completed_at ?? finishedAt,
|
|
307
|
+
updated_at: finishedAt
|
|
308
|
+
};
|
|
309
|
+
if (status === "failed" && !next.error) {
|
|
310
|
+
next.error = `codex exited with code ${code}${signal ? ` (signal ${signal})` : ""}`;
|
|
311
|
+
}
|
|
312
|
+
if (status === "lost" && !next.error) {
|
|
313
|
+
next.error = `codex worker was killed by signal ${signal} before writing a terminal event`;
|
|
314
|
+
}
|
|
315
|
+
if (status === "cancelled") next.error = null;
|
|
316
|
+
await persist(next);
|
|
317
|
+
cancelledTasks.delete(record.id);
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
try {
|
|
321
|
+
child.stdin.end(prompt);
|
|
322
|
+
} catch (error) {
|
|
323
|
+
await persist({
|
|
324
|
+
...live,
|
|
325
|
+
error: live.error ?? `stdin write failed: ${error.message}`,
|
|
326
|
+
updated_at: new Date().toISOString()
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
return { ok: true, record: live, child };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function buildExecArgs({ cwd, sandbox, model, reasoningEffort, skipGitRepoCheck }) {
|
|
334
|
+
const args = ["exec", "--json", "--cd", cwd, "--sandbox", sandbox];
|
|
335
|
+
if (skipGitRepoCheck) args.push("--skip-git-repo-check");
|
|
336
|
+
if (model) args.push("--model", model);
|
|
337
|
+
args.push("-c", `model_reasoning_effort="${reasoningEffort}"`);
|
|
338
|
+
args.push("-");
|
|
339
|
+
return args;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function validateGoal(goal) {
|
|
343
|
+
if (!goal || typeof goal !== "object" || typeof goal.objective !== "string" || goal.objective.trim() === "") {
|
|
344
|
+
throw new Error("goal.objective is required");
|
|
345
|
+
}
|
|
346
|
+
const tokenBudget = goal.tokenBudget ?? goal.token_budget ?? null;
|
|
347
|
+
if (tokenBudget !== null && (!Number.isInteger(tokenBudget) || tokenBudget <= 0)) {
|
|
348
|
+
throw new Error("goal.tokenBudget must be a positive integer when provided");
|
|
349
|
+
}
|
|
350
|
+
return { objective: goal.objective, tokenBudget };
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export async function createCodexWorker({
|
|
354
|
+
title,
|
|
355
|
+
task,
|
|
356
|
+
sessionId = null,
|
|
357
|
+
cwd,
|
|
358
|
+
sandbox = "workspace-write",
|
|
359
|
+
model = null,
|
|
360
|
+
reasoningEffort = "high",
|
|
361
|
+
skipGitRepoCheck = true,
|
|
362
|
+
ownedPaths,
|
|
363
|
+
goal,
|
|
364
|
+
dependsOn = [],
|
|
365
|
+
followupOf = null,
|
|
366
|
+
useWorktree = true
|
|
367
|
+
}) {
|
|
368
|
+
if (!task || typeof task !== "string") throw new Error("task is required");
|
|
369
|
+
if (!cwd || typeof cwd !== "string") throw new Error("cwd is required");
|
|
370
|
+
if (!allowedReasoningEfforts.has(reasoningEffort)) {
|
|
371
|
+
throw new Error(`unsupported reasoningEffort: ${reasoningEffort}`);
|
|
372
|
+
}
|
|
373
|
+
if (!Array.isArray(ownedPaths) || ownedPaths.length === 0) {
|
|
374
|
+
throw new Error("ownedPaths is required and must list at least one path this worker is allowed to write");
|
|
375
|
+
}
|
|
376
|
+
const validatedGoal = validateGoal(goal);
|
|
377
|
+
|
|
378
|
+
const projectRoot = cwd;
|
|
379
|
+
const normalizedOwnedPaths = normalizeOwnedPaths(ownedPaths, projectRoot);
|
|
380
|
+
const conflicts = await findOwnershipConflicts(normalizedOwnedPaths);
|
|
381
|
+
if (conflicts.length > 0) throw ownershipConflictError(conflicts);
|
|
382
|
+
|
|
383
|
+
const id = `codex-${Date.now()}-${randomUUID().slice(0, 8)}`;
|
|
384
|
+
const worktreePath = useWorktree ? await ensureWorktree(projectRoot, id) : null;
|
|
385
|
+
const effectiveCwd = worktreePath ?? projectRoot;
|
|
386
|
+
|
|
387
|
+
const record = {
|
|
388
|
+
id,
|
|
389
|
+
title: title || task.split("\n").find(Boolean)?.slice(0, 80) || "Codex worker",
|
|
390
|
+
worker: "codex",
|
|
391
|
+
status: "queued",
|
|
392
|
+
phase: null,
|
|
393
|
+
cwd: effectiveCwd,
|
|
394
|
+
project_root: projectRoot,
|
|
395
|
+
sandbox,
|
|
396
|
+
model,
|
|
397
|
+
reasoning_effort: reasoningEffort,
|
|
398
|
+
skip_git_repo_check: skipGitRepoCheck,
|
|
399
|
+
followup_of: followupOf,
|
|
400
|
+
resumed_from: null,
|
|
401
|
+
session_id: sessionId ?? null,
|
|
402
|
+
thread_id: null,
|
|
403
|
+
owned_paths: normalizedOwnedPaths,
|
|
404
|
+
depends_on: Array.isArray(dependsOn) ? dependsOn : [],
|
|
405
|
+
goal_objective: validatedGoal.objective,
|
|
406
|
+
goal_token_budget: validatedGoal.tokenBudget,
|
|
407
|
+
goal_status: null,
|
|
408
|
+
goal_tokens_used: null,
|
|
409
|
+
goal_time_used_seconds: null,
|
|
410
|
+
goal_updated_at: null,
|
|
411
|
+
run_count: 0,
|
|
412
|
+
worktree_path: worktreePath,
|
|
413
|
+
prompt: task,
|
|
414
|
+
changed_files: [],
|
|
415
|
+
commands: [],
|
|
416
|
+
created_at: new Date().toISOString(),
|
|
417
|
+
updated_at: new Date().toISOString(),
|
|
418
|
+
run_log: taskRunPath(id)
|
|
419
|
+
};
|
|
420
|
+
await upsertTask(record);
|
|
421
|
+
|
|
422
|
+
const args = buildExecArgs({ cwd: effectiveCwd, sandbox, model, reasoningEffort, skipGitRepoCheck });
|
|
423
|
+
|
|
424
|
+
const started = await startTrackedRun({
|
|
425
|
+
record,
|
|
426
|
+
args,
|
|
427
|
+
prompt: withGoalPreamble(task, {
|
|
428
|
+
objective: validatedGoal.objective,
|
|
429
|
+
tokenBudget: validatedGoal.tokenBudget
|
|
430
|
+
}),
|
|
431
|
+
logPath: record.run_log
|
|
432
|
+
});
|
|
433
|
+
await upsertTask(started.record);
|
|
434
|
+
return started.record;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// Continue the *same* Codex session. The worktree, thread id, ownership and
|
|
438
|
+
// goal are all inherited from the original task, and the row is reused so one
|
|
439
|
+
// logical piece of work stays one row.
|
|
440
|
+
export async function resumeCodexWorker({ taskId, prompt }) {
|
|
441
|
+
if (!prompt || typeof prompt !== "string") throw new Error("prompt is required");
|
|
442
|
+
const task = await getTask(taskId);
|
|
443
|
+
if (!task) throw new Error(`task not found: ${taskId}`);
|
|
444
|
+
if (!task.thread_id) {
|
|
445
|
+
throw new Error(
|
|
446
|
+
`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.`
|
|
447
|
+
);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
const cwd = (await exists(task.cwd)) ? task.cwd : task.project_root;
|
|
451
|
+
const args = ["exec", "resume", "--json"];
|
|
452
|
+
args.push("-c", `sandbox_mode="${task.sandbox}"`);
|
|
453
|
+
if (task.model) args.push("--model", task.model);
|
|
454
|
+
args.push("-c", `model_reasoning_effort="${task.reasoning_effort ?? "high"}"`);
|
|
455
|
+
if (task.skip_git_repo_check) args.push("--skip-git-repo-check");
|
|
456
|
+
args.push(task.thread_id);
|
|
457
|
+
args.push("-");
|
|
458
|
+
|
|
459
|
+
const started = await startTrackedRun({
|
|
460
|
+
record: { ...task, resumed_from: task.resumed_from ?? task.id },
|
|
461
|
+
args,
|
|
462
|
+
prompt: withGoalPreamble(prompt, {
|
|
463
|
+
objective: task.goal_objective ?? task.title ?? task.id,
|
|
464
|
+
resume: true
|
|
465
|
+
}),
|
|
466
|
+
logPath: task.run_log,
|
|
467
|
+
spawnOptions: { cwd }
|
|
468
|
+
});
|
|
469
|
+
await upsertTask(started.record);
|
|
470
|
+
return started.record;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// A pid recorded on disk is only signalled once it is confirmed to still be a
|
|
474
|
+
// Codex worker, so a recycled pid belonging to an unrelated process is never
|
|
475
|
+
// killed. Windows has no `ps`: CIM is the only reliable source for a full command
|
|
476
|
+
// line, and the full line matters because the npm shim is bypassed by running
|
|
477
|
+
// `node <entry>`, which puts the word "codex" in the arguments, not the image
|
|
478
|
+
// name. `tasklist` is the fallback when PowerShell is unavailable.
|
|
479
|
+
function describeProcess(pid) {
|
|
480
|
+
const options = { encoding: "utf8", timeout: 2000, windowsHide: true };
|
|
481
|
+
try {
|
|
482
|
+
if (process.platform === "win32") {
|
|
483
|
+
try {
|
|
484
|
+
const viaCim = execFileSync(
|
|
485
|
+
"powershell",
|
|
486
|
+
[
|
|
487
|
+
"-NoProfile",
|
|
488
|
+
"-NonInteractive",
|
|
489
|
+
"-Command",
|
|
490
|
+
`(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine`
|
|
491
|
+
],
|
|
492
|
+
options
|
|
493
|
+
).trim();
|
|
494
|
+
if (viaCim) return viaCim;
|
|
495
|
+
} catch {
|
|
496
|
+
// fall through to the image-name probe below
|
|
497
|
+
}
|
|
498
|
+
return execFileSync("tasklist", ["/FI", `PID eq ${Number(pid)}`, "/FO", "CSV", "/NH"], options).trim();
|
|
499
|
+
}
|
|
500
|
+
return execFileSync("ps", ["-p", String(pid), "-o", "command="], options).trim();
|
|
501
|
+
} catch {
|
|
502
|
+
return "";
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function isLikelyCodexProcess(pid) {
|
|
507
|
+
const description = describeProcess(pid);
|
|
508
|
+
return description.includes("codex");
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// Ends a worker and, on Windows, its whole process tree: the direct child there
|
|
512
|
+
// is the JS wrapper around the native Codex binary, so terminating it alone
|
|
513
|
+
// would leave the real CLI running and the task stuck in `running`.
|
|
514
|
+
function terminateChild(child) {
|
|
515
|
+
if (process.platform === "win32" && child.pid) {
|
|
516
|
+
try {
|
|
517
|
+
execFileSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], {
|
|
518
|
+
stdio: "ignore",
|
|
519
|
+
timeout: 5000,
|
|
520
|
+
windowsHide: true
|
|
521
|
+
});
|
|
522
|
+
return;
|
|
523
|
+
} catch {
|
|
524
|
+
// fall back to the handle-based kill below
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
child.kill("SIGTERM");
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function terminatePid(pid) {
|
|
531
|
+
if (process.platform === "win32") {
|
|
532
|
+
execFileSync("taskkill", ["/PID", String(pid), "/T", "/F"], {
|
|
533
|
+
stdio: "ignore",
|
|
534
|
+
timeout: 5000,
|
|
535
|
+
windowsHide: true
|
|
536
|
+
});
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
process.kill(pid, "SIGTERM");
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
export async function cancelCodexWorker(taskId) {
|
|
543
|
+
const child = processes.get(taskId);
|
|
544
|
+
if (child) {
|
|
545
|
+
cancelledTasks.add(taskId);
|
|
546
|
+
terminateChild(child);
|
|
547
|
+
return { cancelled: true, via: "process_handle", pid: child.pid ?? null };
|
|
548
|
+
}
|
|
549
|
+
// Another MCP process owns the handle; fall back to the pid recorded on disk.
|
|
550
|
+
const task = await getTask(taskId);
|
|
551
|
+
if (task?.pid && (await isPidAlive(task.pid)) && isLikelyCodexProcess(task.pid)) {
|
|
552
|
+
try {
|
|
553
|
+
terminatePid(task.pid);
|
|
554
|
+
return { cancelled: true, via: "pid", pid: task.pid };
|
|
555
|
+
} catch (error) {
|
|
556
|
+
return { cancelled: false, reason: "kill_failed", message: error.message, pid: task.pid };
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
return { cancelled: false, reason: "process_not_found" };
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
async function isPidAlive(pid) {
|
|
563
|
+
if (!pid) return false;
|
|
564
|
+
try {
|
|
565
|
+
process.kill(pid, 0);
|
|
566
|
+
return true;
|
|
567
|
+
} catch {
|
|
568
|
+
return false;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
export async function createFollowupWorker({
|
|
573
|
+
taskId,
|
|
574
|
+
followupPrompt,
|
|
575
|
+
sessionId = null,
|
|
576
|
+
title,
|
|
577
|
+
cwd,
|
|
578
|
+
sandbox,
|
|
579
|
+
model,
|
|
580
|
+
reasoningEffort,
|
|
581
|
+
ownedPaths,
|
|
582
|
+
goal
|
|
583
|
+
}) {
|
|
584
|
+
const parent = await getTask(taskId);
|
|
585
|
+
if (!parent) throw new Error(`task not found: ${taskId}`);
|
|
586
|
+
const recentEvents = await readTaskEvents(taskId, 20);
|
|
587
|
+
const prompt = [
|
|
588
|
+
"You are continuing a previous Codex worker run.",
|
|
589
|
+
"",
|
|
590
|
+
`Parent task ID: ${parent.id}`,
|
|
591
|
+
`Parent status: ${parent.status}`,
|
|
592
|
+
`Parent title: ${parent.title}`,
|
|
593
|
+
"",
|
|
594
|
+
"Parent prompt:",
|
|
595
|
+
parent.prompt,
|
|
596
|
+
"",
|
|
597
|
+
"Parent recent summary:",
|
|
598
|
+
`- current_action: ${parent.current_action ?? "-"}`,
|
|
599
|
+
`- current_command: ${parent.current_command ?? "-"}`,
|
|
600
|
+
`- changed_files: ${(parent.changed_files ?? []).join(", ") || "-"}`,
|
|
601
|
+
`- last_message: ${parent.last_message ?? "-"}`,
|
|
602
|
+
"",
|
|
603
|
+
"Parent recent events:",
|
|
604
|
+
...recentEvents.map((event) => `- ${JSON.stringify(event)}`),
|
|
605
|
+
"",
|
|
606
|
+
"Follow-up instruction:",
|
|
607
|
+
followupPrompt
|
|
608
|
+
].join("\n");
|
|
609
|
+
|
|
610
|
+
return createCodexWorker({
|
|
611
|
+
title: title ?? `Follow-up for ${parent.id}`,
|
|
612
|
+
task: prompt,
|
|
613
|
+
sessionId: sessionId ?? parent.session_id ?? null,
|
|
614
|
+
cwd: cwd ?? parent.project_root ?? parent.cwd,
|
|
615
|
+
sandbox: sandbox ?? parent.sandbox,
|
|
616
|
+
model: model ?? parent.model,
|
|
617
|
+
reasoningEffort: reasoningEffort ?? parent.reasoning_effort ?? "high",
|
|
618
|
+
skipGitRepoCheck: parent.skip_git_repo_check,
|
|
619
|
+
ownedPaths: ownedPaths ?? parent.owned_paths,
|
|
620
|
+
goal: goal ?? { objective: parent.goal_objective ?? `Follow-up for ${parent.id}`, tokenBudget: parent.goal_token_budget ?? undefined },
|
|
621
|
+
dependsOn: [parent.id],
|
|
622
|
+
followupOf: parent.id,
|
|
623
|
+
useWorktree: true
|
|
624
|
+
});
|
|
625
|
+
}
|