codex-supervisor-mcp 0.11.0 → 0.12.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 +3 -3
- package/README.md +21 -11
- package/package.json +9 -2
- package/skills/codex-supervisor/SKILL.md +22 -9
- package/src/codex-runner.js +245 -54
- package/src/context-compiler.js +3 -1
- package/src/failure-class.js +31 -0
- package/src/handoff.js +9 -1
- package/src/landing.js +25 -8
- package/src/mcp-server.js +140 -15
- package/src/overview-delta.js +8 -1
- package/src/paths.js +1 -0
- package/src/prompt.js +6 -2
- package/src/sandbox-roots.js +19 -3
- package/src/stage-store.js +39 -0
- package/src/stage.js +17 -0
- package/src/task-store.js +243 -64
- package/src/thread-health.js +33 -0
- package/src/worker-env.js +14 -0
- package/src/worker-preflight.js +52 -5
- package/src/worktree.js +60 -8
package/src/codex-runner.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { createWriteStream, existsSync } from "node:fs";
|
|
2
|
-
import { mkdir, rm, stat } from "node:fs/promises";
|
|
2
|
+
import { lstat, mkdir, realpath, rm, stat, symlink } from "node:fs/promises";
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import { execFileSync, spawn } from "node:child_process";
|
|
5
|
-
import { join, resolve, sep, dirname, isAbsolute } from "node:path";
|
|
5
|
+
import { basename, join, resolve, relative, sep, dirname, isAbsolute } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import {
|
|
8
8
|
appendTaskEvent,
|
|
9
|
+
appendTaskEvents,
|
|
9
10
|
getTask,
|
|
10
11
|
getSession,
|
|
11
12
|
readActiveTasks,
|
|
@@ -25,6 +26,7 @@ import {
|
|
|
25
26
|
} from "./task-store.js";
|
|
26
27
|
import { ACTIVE_STATUSES, TERMINAL_STATUSES } from "./status.js";
|
|
27
28
|
import { worktreesDir } from "./paths.js";
|
|
29
|
+
import { clearStage } from "./stage-store.js";
|
|
28
30
|
import { buildGuardPreamble, frameWorkerPrompt } from "./prompt.js";
|
|
29
31
|
import { cacheRoots, resolveWritableRoot } from "./sandbox-roots.js";
|
|
30
32
|
import { readTaskChanges, snapshotTaskOutput } from "./worktree.js";
|
|
@@ -40,6 +42,7 @@ import { buildRuntimeContract, createPreflightMetadata, readPreflightResult, run
|
|
|
40
42
|
import { supervisorMcpDisableArgs } from "./mcp-config.js";
|
|
41
43
|
import { captureWorkspaceManifest, isGitCheckout, prepareWorkspace } from "./workspace-kind.js";
|
|
42
44
|
import { codexRunner } from "./runner-adapter.js";
|
|
45
|
+
import { withWorkerToolPath } from "./worker-env.js";
|
|
43
46
|
|
|
44
47
|
const processes = new Map();
|
|
45
48
|
// taskId -> control object of an acceptance run in progress ({ kill, cancelled }).
|
|
@@ -48,6 +51,8 @@ const cancelledTasks = new Set();
|
|
|
48
51
|
const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
49
52
|
const allowedReasoningEfforts = new Set(["minimal", "low", "medium", "high"]);
|
|
50
53
|
const MAX_RUN_HOST_PROMPT_BYTES = 4 * 1024 * 1024;
|
|
54
|
+
const RUN_HOST_STARTUP_TIMEOUT_MS = process.platform === "win32" ? 120000 : 30000;
|
|
55
|
+
const WORKTREE_LOCK_TIMEOUT_MS = 120000;
|
|
51
56
|
|
|
52
57
|
async function recordOutcomeFacts({ task, runId, report, reportEventId = null, acceptanceEventId = null, acceptancePassed = false }) {
|
|
53
58
|
if (!report?.valid) return;
|
|
@@ -63,6 +68,7 @@ async function recordOutcomeFacts({ task, runId, report, reportEventId = null, a
|
|
|
63
68
|
state: "candidate",
|
|
64
69
|
sourceEventId: reportEventId,
|
|
65
70
|
validForSha: task.base_commit ?? null,
|
|
71
|
+
validForContentHash: task.input_context?.content_hash ?? null,
|
|
66
72
|
validForManifestHash,
|
|
67
73
|
watchedPaths: task.owned_paths ?? []
|
|
68
74
|
});
|
|
@@ -76,6 +82,7 @@ async function recordOutcomeFacts({ task, runId, report, reportEventId = null, a
|
|
|
76
82
|
state: "verified",
|
|
77
83
|
sourceEventId: acceptanceEventId,
|
|
78
84
|
validForSha: task.base_commit ?? null,
|
|
85
|
+
validForContentHash: task.input_context?.content_hash ?? null,
|
|
79
86
|
validForManifestHash,
|
|
80
87
|
watchedPaths: task.owned_paths ?? [],
|
|
81
88
|
supersedesId: candidate.id,
|
|
@@ -162,6 +169,98 @@ async function ensureWorktree(cwd, taskId, baseRef = null) {
|
|
|
162
169
|
}
|
|
163
170
|
}
|
|
164
171
|
|
|
172
|
+
function insidePath(parent, child) {
|
|
173
|
+
const rel = relative(parent, child);
|
|
174
|
+
return rel === "" || (!rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function normalizeWorkspaceSetup(value, projectRoot) {
|
|
178
|
+
if (value == null) return null;
|
|
179
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("workspaceSetup must be an object");
|
|
180
|
+
const links = (value.links ?? []).map((entry) => {
|
|
181
|
+
if (!entry || typeof entry.path !== "string" || !entry.path.trim()
|
|
182
|
+
|| typeof entry.source !== "string" || !entry.source.trim()) throw new Error("workspaceSetup.links requires path and source");
|
|
183
|
+
const path = entry.path.trim();
|
|
184
|
+
if (isAbsolute(path) || path.split(/[\\/]/).includes("..")) throw new Error(`workspaceSetup link path must stay inside the worktree: ${path}`);
|
|
185
|
+
return { path, source: resolve(projectRoot, entry.source.trim()) };
|
|
186
|
+
});
|
|
187
|
+
const commands = (value.commands ?? []).map((command) => String(command).trim()).filter(Boolean);
|
|
188
|
+
if (links.length > 20 || commands.length > 20) throw new Error("workspaceSetup accepts at most 20 links and 20 commands");
|
|
189
|
+
const submodules = value.submodules === true;
|
|
190
|
+
return links.length || submodules || commands.length ? { links, submodules, commands } : null;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function prepareWorktreeWorkspace(setup, projectRoot, worktreePath, taskId) {
|
|
194
|
+
if (!setup) return;
|
|
195
|
+
for (const link of setup.links) {
|
|
196
|
+
if (!existsSync(link.source)) throw new Error(`workspaceSetup link source does not exist: ${link.source}`);
|
|
197
|
+
const destination = resolve(worktreePath, link.path);
|
|
198
|
+
if (!insidePath(worktreePath, destination)) throw new Error(`workspaceSetup link escapes the worktree: ${link.path}`);
|
|
199
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
200
|
+
if (existsSync(destination)) {
|
|
201
|
+
const existing = await lstat(destination);
|
|
202
|
+
if (!existing.isSymbolicLink()) throw new Error(`workspaceSetup link destination already exists: ${link.path}`);
|
|
203
|
+
const [actual, expected] = await Promise.all([realpath(destination), realpath(link.source)]);
|
|
204
|
+
if (actual !== expected) throw new Error(`workspaceSetup link destination points elsewhere: ${link.path}`);
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
const sourceInfo = await stat(link.source);
|
|
208
|
+
await symlink(link.source, destination, process.platform === "win32" ? "junction" : sourceInfo.isDirectory() ? "dir" : "file");
|
|
209
|
+
if (basename(link.path) === "node_modules" && sourceInfo.isDirectory()) {
|
|
210
|
+
for (const name of [".vite", ".vite-temp", ".cache"]) await mkdir(join(link.source, name), { recursive: true });
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (setup.submodules) {
|
|
214
|
+
await runCommand(defaultGitBin, ["-c", "protocol.file.allow=always", "-C", worktreePath, "submodule", "update", "--init", "--recursive"]);
|
|
215
|
+
}
|
|
216
|
+
if (setup.commands.length) {
|
|
217
|
+
const result = await runAcceptance(setup.commands, { cwd: worktreePath, taskId, timeoutMs: DEFAULT_ACCEPTANCE_TIMEOUT_MS });
|
|
218
|
+
if (!result.passed) {
|
|
219
|
+
const failing = result.checks.find((check) => !check.passed);
|
|
220
|
+
throw new Error(`workspaceSetup command failed: ${failing?.command ?? "unknown"}${failing?.output_tail ? `\n${failing.output_tail}` : ""}`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function workspaceSetupWriteRoots(record) {
|
|
226
|
+
const roots = [];
|
|
227
|
+
for (const link of record.workspace_metadata?.setup?.links ?? []) {
|
|
228
|
+
const source = resolveWritableRoot(link.source);
|
|
229
|
+
if (!source.error) roots.push(source.path);
|
|
230
|
+
if (basename(link.path) !== "node_modules") continue;
|
|
231
|
+
for (const name of [".vite", ".vite-temp", ".cache"]) {
|
|
232
|
+
const candidate = resolveWritableRoot(join(link.source, name));
|
|
233
|
+
if (!candidate.error) roots.push(candidate.path);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return roots;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function sleep(ms) {
|
|
240
|
+
return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async function withWorktreeCreationLock(cwd, work) {
|
|
244
|
+
const lockName = `create-${createHash("sha256").update(resolve(cwd)).digest("hex").slice(0, 24)}.lock`;
|
|
245
|
+
const lockPath = join(worktreesDir, lockName);
|
|
246
|
+
await mkdir(worktreesDir, { recursive: true });
|
|
247
|
+
const deadline = Date.now() + WORKTREE_LOCK_TIMEOUT_MS;
|
|
248
|
+
while (true) {
|
|
249
|
+
try {
|
|
250
|
+
await mkdir(lockPath);
|
|
251
|
+
break;
|
|
252
|
+
} catch (error) {
|
|
253
|
+
if (error.code !== "EEXIST" || Date.now() >= deadline) throw new Error(`worktree creation lock timed out for ${cwd}`);
|
|
254
|
+
await sleep(100);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
try {
|
|
258
|
+
return await work();
|
|
259
|
+
} finally {
|
|
260
|
+
await rm(lockPath, { recursive: true, force: true }).catch(() => {});
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
165
264
|
function normalizeOwnedPaths(ownedPaths, projectRoot) {
|
|
166
265
|
if (!Array.isArray(ownedPaths)) return [];
|
|
167
266
|
return Array.from(new Set(ownedPaths.map((entry) => resolve(projectRoot, String(entry).trim()))));
|
|
@@ -238,6 +337,9 @@ function failedStart(record, reason) {
|
|
|
238
337
|
// failed instead of taking the whole MCP process down.
|
|
239
338
|
async function spawnAndAwaitStart(target, args, options) {
|
|
240
339
|
const child = spawn(target.cmd, [...target.prefixArgs, ...args], options);
|
|
340
|
+
const earlyOutput = { stdout: [], stderr: [], capture: true };
|
|
341
|
+
child.stdout?.on("data", (chunk) => { if (earlyOutput.capture) earlyOutput.stdout.push(chunk); });
|
|
342
|
+
child.stderr?.on("data", (chunk) => { if (earlyOutput.capture) earlyOutput.stderr.push(chunk); });
|
|
241
343
|
const spawnError = await new Promise((resolvePromise) => {
|
|
242
344
|
let settled = false;
|
|
243
345
|
child.once("spawn", () => {
|
|
@@ -253,7 +355,7 @@ async function spawnAndAwaitStart(target, args, options) {
|
|
|
253
355
|
}
|
|
254
356
|
});
|
|
255
357
|
});
|
|
256
|
-
return { child, spawnError };
|
|
358
|
+
return { child, spawnError, earlyOutput };
|
|
257
359
|
}
|
|
258
360
|
|
|
259
361
|
// Attaches stream handlers and keeps `record` in the supervisor database.
|
|
@@ -268,8 +370,16 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
268
370
|
const externalBefore = await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [], { checkBaseline: (record.run_count ?? 0) === 0 });
|
|
269
371
|
const owned = [...findOutsideOwnedChanges(record, []).mapping.map((entry) => entry.worker), ...externalBefore.map((entry) => entry.path)];
|
|
270
372
|
const guardPolicy = { cwd: record.cwd, worktree: record.cwd, sandbox: record.sandbox, ownedPaths: owned, ...(record.guard_policy ?? {}),
|
|
271
|
-
allowedCommands: [
|
|
373
|
+
allowedCommands: [
|
|
374
|
+
...(record.guard_policy?.allowedCommands ?? []),
|
|
375
|
+
...(record.acceptance ?? []).map((check) => typeof check === "string" ? check : check.command),
|
|
376
|
+
// This CLI writes only data/stages/<this task>.json. It is part of the
|
|
377
|
+
// runtime contract, not an ad-hoc command the model must declare. The
|
|
378
|
+
// task id comes from the injected environment; stage.js has no override.
|
|
379
|
+
'node "$CODEX_SUPERVISOR_STAGE_CLI"*'
|
|
380
|
+
] };
|
|
272
381
|
const guard = fileURLToPath(new URL("./tool-guard.js", import.meta.url));
|
|
382
|
+
const stageCli = fileURLToPath(new URL("./stage.js", import.meta.url));
|
|
273
383
|
const quoteCommand = (path) => process.platform === "win32" ? `"${path.replace(/"/g, '""')}"` : `'${path.replace(/'/g, "'\\''")}'`;
|
|
274
384
|
const hookCommand = `${quoteCommand(process.execPath)} ${quoteCommand(guard)}`;
|
|
275
385
|
const configArgs = ["--output-schema", workerReportSchemaPath, "--dangerously-bypass-hook-trust", "-c",
|
|
@@ -278,16 +388,25 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
278
388
|
// must not inherit this supervisor and create a second orchestration tree.
|
|
279
389
|
configArgs.push(...supervisorMcpDisableArgs());
|
|
280
390
|
configArgs.push("-c", `sandbox_workspace_write.network_access=${record.guard_policy?.networkAccess === true}`);
|
|
281
|
-
const sandboxWritableRoots = [...new Set([
|
|
391
|
+
const sandboxWritableRoots = [...new Set([
|
|
392
|
+
...externalBefore.map((file) => dirname(file.path)),
|
|
393
|
+
...cacheRoots(),
|
|
394
|
+
...workspaceSetupWriteRoots(record),
|
|
395
|
+
...(record.guard_policy?.writableRoots ?? [])
|
|
396
|
+
])];
|
|
282
397
|
if (sandboxWritableRoots.length) configArgs.push("-c", `sandbox_workspace_write.writable_roots=${JSON.stringify(sandboxWritableRoots)}`);
|
|
283
398
|
// Insert before the prompt/session positional arguments for exec/resume.
|
|
284
399
|
const guardedArgs = [...args.slice(0, -1), ...configArgs, args.at(-1)];
|
|
285
400
|
prompt = `${buildGuardPreamble(guardPolicy)}\n\n${prompt}`;
|
|
286
401
|
|
|
287
|
-
|
|
402
|
+
clearStage(record.id);
|
|
403
|
+
|
|
404
|
+
const { child, spawnError, earlyOutput } = await spawnAndAwaitStart(target, guardedArgs, {
|
|
288
405
|
stdio: ["pipe", "pipe", "pipe"],
|
|
289
|
-
env: { ...process.env, NO_COLOR: "1", CODEX_SUPERVISOR_TASK_ID: record.id,
|
|
290
|
-
|
|
406
|
+
env: withWorkerToolPath({ ...process.env, NO_COLOR: "1", CODEX_SUPERVISOR_TASK_ID: record.id,
|
|
407
|
+
CODEX_SUPERVISOR_BASE_COMMIT: record.base_commit ?? "",
|
|
408
|
+
CODEX_SUPERVISOR_STAGE_CLI: stageCli,
|
|
409
|
+
CODEX_SUPERVISOR_RUN: String((record.run_count ?? 0) + 1), CODEX_SUPERVISOR_GUARD_POLICY: JSON.stringify(guardPolicy) }),
|
|
291
410
|
windowsHide: true,
|
|
292
411
|
...spawnOptions
|
|
293
412
|
});
|
|
@@ -301,6 +420,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
301
420
|
// the run that was lost, so a worker that was plainly running still showed
|
|
302
421
|
// "process disappeared" until it finished.
|
|
303
422
|
const priorAttemptFingerprint = record.run_evidence?.attempt_fingerprint ?? null;
|
|
423
|
+
const reportOnlyRecovery = record.attention_reason === "invalid_report";
|
|
304
424
|
let live = {
|
|
305
425
|
...record,
|
|
306
426
|
status: "running",
|
|
@@ -369,36 +489,60 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
369
489
|
let terminalEvent = false;
|
|
370
490
|
let rawReport = null;
|
|
371
491
|
let rawReportEventId = null;
|
|
372
|
-
const
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
492
|
+
const handleLines = async (lines) => {
|
|
493
|
+
const events = [];
|
|
494
|
+
for (const line of lines) {
|
|
495
|
+
try {
|
|
496
|
+
const event = JSON.parse(line);
|
|
497
|
+
logStream.write(`${JSON.stringify(event)}\n`);
|
|
498
|
+
events.push(event);
|
|
499
|
+
} catch (error) {
|
|
500
|
+
logStream.write(`${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
if (events.length === 0) return;
|
|
504
|
+
const storedEvents = await appendTaskEvents(record.id, events, { runId, actor: "codex" });
|
|
505
|
+
let next = live;
|
|
506
|
+
for (const [index, event] of events.entries()) {
|
|
507
|
+
if (event.type === "item.completed" && event.item?.type === "agent_message") {
|
|
508
|
+
rawReport = event.item.text;
|
|
509
|
+
rawReportEventId = storedEvents[index].id;
|
|
510
|
+
}
|
|
511
|
+
if (["turn.completed", "turn.failed"].includes(event.type)) terminalEvent = true;
|
|
512
|
+
next = codexRunner.parseEvent(next, event);
|
|
379
513
|
}
|
|
380
|
-
|
|
381
|
-
if (event.type === "item.completed" && event.item?.type === "agent_message") rawReport = event.item.text;
|
|
382
|
-
if (["turn.completed", "turn.failed"].includes(event.type)) terminalEvent = true;
|
|
383
|
-
const storedEvent = await appendTaskEvent(record.id, event, { runId, actor: "codex" });
|
|
384
|
-
if (event.type === "item.completed" && event.item?.type === "agent_message") rawReportEventId = storedEvent.id;
|
|
385
|
-
await persist(codexRunner.parseEvent(live, event));
|
|
514
|
+
await persist(next);
|
|
386
515
|
};
|
|
387
516
|
|
|
388
517
|
let stdoutRest = "";
|
|
389
|
-
|
|
518
|
+
let pendingLines = [];
|
|
519
|
+
let eventFlushPending = false;
|
|
520
|
+
const queueEventLines = (lines) => {
|
|
521
|
+
pendingLines.push(...lines);
|
|
522
|
+
if (eventFlushPending) return;
|
|
523
|
+
eventFlushPending = true;
|
|
524
|
+
eventChain = eventChain.then(async () => {
|
|
525
|
+
await new Promise((resolveFlush) => setImmediate(resolveFlush));
|
|
526
|
+
const batch = pendingLines;
|
|
527
|
+
pendingLines = [];
|
|
528
|
+
eventFlushPending = false;
|
|
529
|
+
await handleLines(batch);
|
|
530
|
+
}).catch((error) => {
|
|
531
|
+
process.stderr.write(`[codex-supervisor] event handling failed for ${record.id}: ${error.message}\n`);
|
|
532
|
+
});
|
|
533
|
+
};
|
|
534
|
+
const handleStdoutChunk = (chunk) => {
|
|
390
535
|
const split = splitLines(stdoutRest, chunk.toString("utf8"));
|
|
391
536
|
stdoutRest = split.rest;
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
});
|
|
537
|
+
const lines = split.lines.filter((line) => line.trim());
|
|
538
|
+
if (lines.length) queueEventLines(lines);
|
|
539
|
+
};
|
|
540
|
+
earlyOutput.capture = false;
|
|
541
|
+
for (const chunk of earlyOutput.stdout) handleStdoutChunk(chunk);
|
|
542
|
+
child.stdout.on("data", handleStdoutChunk);
|
|
399
543
|
child.stdout.on("error", () => {});
|
|
400
544
|
|
|
401
|
-
let stderr = "";
|
|
545
|
+
let stderr = earlyOutput.stderr.map((chunk) => chunk.toString("utf8")).join("");
|
|
402
546
|
child.stderr.on("data", (chunk) => {
|
|
403
547
|
stderr += chunk.toString("utf8");
|
|
404
548
|
persist({ ...live, stderr_tail: stderr.slice(-4000), updated_at: new Date().toISOString() });
|
|
@@ -413,12 +557,15 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
413
557
|
});
|
|
414
558
|
});
|
|
415
559
|
|
|
416
|
-
|
|
560
|
+
let settleRun;
|
|
561
|
+
const settled = new Promise((resolveSettled) => { settleRun = resolveSettled; });
|
|
562
|
+
let childSettled = false;
|
|
563
|
+
const finalizeChild = async (code, signal) => {
|
|
564
|
+
if (childSettled) return;
|
|
565
|
+
childSettled = true;
|
|
417
566
|
if (quotaWatch) clearInterval(quotaWatch);
|
|
418
567
|
processes.delete(record.id);
|
|
419
|
-
if (stdoutRest.trim())
|
|
420
|
-
process.stderr.write(`[codex-supervisor] final event failed for ${record.id}: ${error.message}\n`);
|
|
421
|
-
});
|
|
568
|
+
if (stdoutRest.trim()) queueEventLines([stdoutRest]);
|
|
422
569
|
await eventChain.catch(() => {});
|
|
423
570
|
logStream.end();
|
|
424
571
|
const finishedAt = new Date().toISOString();
|
|
@@ -449,10 +596,11 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
449
596
|
completed_at: live.completed_at ?? finishedAt,
|
|
450
597
|
updated_at: finishedAt
|
|
451
598
|
};
|
|
452
|
-
|
|
599
|
+
const stdinEpipe = /^stdin write failed:.*\bEPIPE\b/i.test(next.error ?? "");
|
|
600
|
+
if (status === "failed" && (!next.error || stdinEpipe)) {
|
|
453
601
|
next.error = `codex exited with code ${code}${signal ? ` (signal ${signal})` : ""}`;
|
|
454
602
|
}
|
|
455
|
-
if (status === "lost" && !next.error) {
|
|
603
|
+
if (status === "lost" && (!next.error || stdinEpipe)) {
|
|
456
604
|
next.error = signal ? `codex worker was killed by signal ${signal} before writing a terminal event` : "Codex worker exited without recording a terminal event";
|
|
457
605
|
}
|
|
458
606
|
if (status === "cancelled") next.error = null;
|
|
@@ -494,11 +642,11 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
494
642
|
})).digest("hex");
|
|
495
643
|
if (status === "completed" && code === 0 && live.sandbox !== "read-only"
|
|
496
644
|
&& !next.run_evidence.output_changed && next.run_evidence.output_changed !== null
|
|
497
|
-
&& live.commands.length === 0) {
|
|
645
|
+
&& live.commands.length === 0 && !reportOnlyRecovery) {
|
|
498
646
|
next.attention_reason = priorAttemptFingerprint === next.run_evidence.attempt_fingerprint ? "two_stall" : "no_work";
|
|
499
647
|
if (next.attention_reason === "two_stall") next.current_action = "No progress in two consecutive runs; needs attention";
|
|
500
648
|
}
|
|
501
|
-
if (status === "completed" && !next.run_evidence.structured_report.valid) {
|
|
649
|
+
if (status === "completed" && !next.run_evidence.structured_report.valid && !live.guard_policy?.preflight) {
|
|
502
650
|
next.status = "failed";
|
|
503
651
|
next.attention_reason = "invalid_report";
|
|
504
652
|
next.error = `Invalid final worker report: ${next.run_evidence.structured_report.error}`;
|
|
@@ -555,8 +703,6 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
555
703
|
: next.current_action,
|
|
556
704
|
updated_at: new Date().toISOString()
|
|
557
705
|
};
|
|
558
|
-
await persist(finalRecord);
|
|
559
|
-
await completeRunRecord(finalRecord, live.run_count);
|
|
560
706
|
await recordOutcomeFacts({
|
|
561
707
|
task: finalRecord,
|
|
562
708
|
runId,
|
|
@@ -566,10 +712,10 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
566
712
|
acceptancePassed: results.passed === true
|
|
567
713
|
});
|
|
568
714
|
if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
|
|
569
|
-
} else {
|
|
570
|
-
const finalRecord = acceptance ? { ...next, acceptance_results: null } : next;
|
|
571
715
|
await persist(finalRecord);
|
|
572
716
|
await completeRunRecord(finalRecord, live.run_count);
|
|
717
|
+
} else {
|
|
718
|
+
const finalRecord = acceptance ? { ...next, acceptance_results: null } : next;
|
|
573
719
|
await recordOutcomeFacts({
|
|
574
720
|
task: finalRecord,
|
|
575
721
|
runId,
|
|
@@ -577,9 +723,15 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
577
723
|
reportEventId: rawReportEventId
|
|
578
724
|
});
|
|
579
725
|
if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
|
|
726
|
+
await persist(finalRecord);
|
|
727
|
+
await completeRunRecord(finalRecord, live.run_count);
|
|
580
728
|
}
|
|
581
729
|
cancelledTasks.delete(record.id);
|
|
582
|
-
}
|
|
730
|
+
};
|
|
731
|
+
child.once("close", (code, signal) => { void finalizeChild(code, signal).finally(settleRun); });
|
|
732
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
733
|
+
setImmediate(() => { void finalizeChild(child.exitCode, child.signalCode).finally(settleRun); });
|
|
734
|
+
}
|
|
583
735
|
|
|
584
736
|
try {
|
|
585
737
|
child.stdin.end(prompt);
|
|
@@ -591,7 +743,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
591
743
|
});
|
|
592
744
|
}
|
|
593
745
|
|
|
594
|
-
return { ok: true, record: live, child };
|
|
746
|
+
return { ok: true, record: live, child, settled };
|
|
595
747
|
}
|
|
596
748
|
|
|
597
749
|
// The MCP client may disappear at any point. A detached process owns the
|
|
@@ -610,6 +762,7 @@ async function startTrackedRun(job) {
|
|
|
610
762
|
...job.record.input_context,
|
|
611
763
|
context: compiled.sourceRefs,
|
|
612
764
|
source_refs: compiled.sourceRefs,
|
|
765
|
+
content_hash: compiled.contentHash,
|
|
613
766
|
context_snapshot_id: compiled.snapshot.id,
|
|
614
767
|
context_snapshot_tokens: compiled.snapshot.estimated_tokens,
|
|
615
768
|
context_fact_count: compiled.factCount
|
|
@@ -621,7 +774,10 @@ async function startTrackedRun(job) {
|
|
|
621
774
|
env: process.env, windowsHide: true
|
|
622
775
|
});
|
|
623
776
|
const started = await new Promise((resolveStart) => {
|
|
777
|
+
let settled = false;
|
|
624
778
|
const finish = (result) => {
|
|
779
|
+
if (settled) return;
|
|
780
|
+
settled = true;
|
|
625
781
|
clearTimeout(timer);
|
|
626
782
|
host.removeAllListeners("message");
|
|
627
783
|
host.removeAllListeners("exit");
|
|
@@ -632,7 +788,7 @@ async function startTrackedRun(job) {
|
|
|
632
788
|
const timer = setTimeout(() => {
|
|
633
789
|
host.kill();
|
|
634
790
|
finish(failedStart(job.record, "run host startup timed out"));
|
|
635
|
-
},
|
|
791
|
+
}, RUN_HOST_STARTUP_TIMEOUT_MS);
|
|
636
792
|
host.once("message", finish);
|
|
637
793
|
host.once("error", (error) => finish(failedStart(job.record, `run host startup failed: ${error.message}`)));
|
|
638
794
|
host.once("exit", (code) => finish(failedStart(job.record, `run host exited before startup: ${code}`)));
|
|
@@ -735,6 +891,7 @@ export async function createCodexWorker({
|
|
|
735
891
|
followupOf = null,
|
|
736
892
|
workspaceKind = null,
|
|
737
893
|
inPlaceAuthorization = null,
|
|
894
|
+
workspaceSetup = null,
|
|
738
895
|
baseRef = null,
|
|
739
896
|
preflightId = null,
|
|
740
897
|
preflight = null,
|
|
@@ -803,6 +960,8 @@ export async function createCodexWorker({
|
|
|
803
960
|
});
|
|
804
961
|
const projectRoot = workspace.sourceRoot;
|
|
805
962
|
const normalizedOwnedPaths = normalizeOwnedPaths([...ownedPaths, ...externalOutputs.map((entry) => entry.path)], projectRoot);
|
|
963
|
+
const normalizedWorkspaceSetup = normalizeWorkspaceSetup(workspaceSetup, projectRoot);
|
|
964
|
+
if (normalizedWorkspaceSetup && workspace.kind !== "git_worktree") throw new Error("workspaceSetup is only supported for git_worktree workers");
|
|
806
965
|
const conflicts = await findOwnershipConflicts(normalizedOwnedPaths);
|
|
807
966
|
if (conflicts.length > 0) throw ownershipConflictError(conflicts);
|
|
808
967
|
|
|
@@ -819,7 +978,7 @@ export async function createCodexWorker({
|
|
|
819
978
|
const combinedAcceptance = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(acceptanceCommands ?? [])]);
|
|
820
979
|
|
|
821
980
|
const worktree = workspace.kind === "git_worktree"
|
|
822
|
-
? await ensureWorktree(projectRoot, id, baseRef)
|
|
981
|
+
? await withWorktreeCreationLock(projectRoot, () => ensureWorktree(projectRoot, id, baseRef))
|
|
823
982
|
: { path: null, baseCommit: null };
|
|
824
983
|
const worktreePath = worktree.path;
|
|
825
984
|
if (workspace.kind === "git_worktree" && !worktreePath) {
|
|
@@ -827,6 +986,15 @@ export async function createCodexWorker({
|
|
|
827
986
|
error.code = "git_worktree_unavailable";
|
|
828
987
|
throw error;
|
|
829
988
|
}
|
|
989
|
+
if (normalizedWorkspaceSetup) {
|
|
990
|
+
try {
|
|
991
|
+
await prepareWorktreeWorkspace(normalizedWorkspaceSetup, projectRoot, worktreePath, id);
|
|
992
|
+
} catch (error) {
|
|
993
|
+
await runCommand(defaultGitBin, ["-C", projectRoot, "worktree", "remove", worktreePath]).catch(() => {});
|
|
994
|
+
await runCommand(defaultGitBin, ["-C", projectRoot, "branch", "-D", `codex/${id}`]).catch(() => {});
|
|
995
|
+
throw error;
|
|
996
|
+
}
|
|
997
|
+
}
|
|
830
998
|
const effectiveCwd = worktreePath ?? workspace.executionCwd;
|
|
831
999
|
if (preflight && (!Array.isArray(preflight.probeCommands) || preflight.probeCommands.length === 0
|
|
832
1000
|
|| preflight.probeCommands.some((command) => typeof command !== "string" || !command.trim()))) {
|
|
@@ -834,7 +1002,14 @@ export async function createCodexWorker({
|
|
|
834
1002
|
}
|
|
835
1003
|
const guardPolicy = {
|
|
836
1004
|
forbid,
|
|
837
|
-
|
|
1005
|
+
// Probe commands need enough permission to prove the worker environment,
|
|
1006
|
+
// but they are not part of the target worker's executable contract. Keep
|
|
1007
|
+
// them in this preflight run's guard only so the final worker can reuse the
|
|
1008
|
+
// exact contract its dispatcher declared.
|
|
1009
|
+
allowedCommands: [...new Set([
|
|
1010
|
+
...allowedCommands,
|
|
1011
|
+
...(preflight?.probeCommands ?? [])
|
|
1012
|
+
])],
|
|
838
1013
|
externalOutputs,
|
|
839
1014
|
networkAccess,
|
|
840
1015
|
writableRoots: [...new Set(resolvedWritableRoots)],
|
|
@@ -852,6 +1027,7 @@ export async function createCodexWorker({
|
|
|
852
1027
|
writableRoots: guardPolicy.writableRoots,
|
|
853
1028
|
context,
|
|
854
1029
|
contracts,
|
|
1030
|
+
workspaceSetup: normalizedWorkspaceSetup,
|
|
855
1031
|
workspaceKind: workspace.kind,
|
|
856
1032
|
workspaceManifestSha256: workspace.beforeManifest?.sha256 ?? null
|
|
857
1033
|
});
|
|
@@ -875,7 +1051,8 @@ export async function createCodexWorker({
|
|
|
875
1051
|
before_manifest: workspace.beforeManifest,
|
|
876
1052
|
in_place_authorization: workspace.kind === "in_place_write" ? String(inPlaceAuthorization).trim() : null,
|
|
877
1053
|
landable: workspace.landable,
|
|
878
|
-
cleanable: workspace.cleanable
|
|
1054
|
+
cleanable: workspace.cleanable,
|
|
1055
|
+
setup: normalizedWorkspaceSetup
|
|
879
1056
|
},
|
|
880
1057
|
sandbox,
|
|
881
1058
|
model,
|
|
@@ -936,7 +1113,12 @@ export async function createCodexWorker({
|
|
|
936
1113
|
if (preflightResult.contract_hash !== contractHash) {
|
|
937
1114
|
const error = new Error(`preflight ${preflightId} does not match this worker's runtime contract; create a new preflight after changing baseRef, sandbox, ownedPaths, commands, context, contracts, network or writable roots`);
|
|
938
1115
|
error.code = "preflight_mismatch";
|
|
939
|
-
error.details = {
|
|
1116
|
+
error.details = {
|
|
1117
|
+
preflight_id: preflightId,
|
|
1118
|
+
expected_contract_hash: contractHash,
|
|
1119
|
+
actual_contract_hash: preflightResult.contract_hash,
|
|
1120
|
+
preflight: { expected_contract: runtimeContract, actual_contract: preflightResult.contract }
|
|
1121
|
+
};
|
|
940
1122
|
throw error;
|
|
941
1123
|
}
|
|
942
1124
|
}
|
|
@@ -962,7 +1144,11 @@ export async function createCodexWorker({
|
|
|
962
1144
|
objective: validatedGoal.objective,
|
|
963
1145
|
tokenBudget: validatedGoal.tokenBudget
|
|
964
1146
|
}, { acceptance: combinedAcceptance }),
|
|
965
|
-
logPath: record.run_log
|
|
1147
|
+
logPath: record.run_log,
|
|
1148
|
+
// --cd tells Codex where the agent works. The shell/tool process must also
|
|
1149
|
+
// inherit the worktree as its OS cwd: otherwise a login shell may restore
|
|
1150
|
+
// the project directory and relative probes read the wrong checkout.
|
|
1151
|
+
spawnOptions: { cwd: effectiveCwd }
|
|
966
1152
|
});
|
|
967
1153
|
return started.record;
|
|
968
1154
|
}
|
|
@@ -1074,6 +1260,7 @@ export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acc
|
|
|
1074
1260
|
export async function recoverEligibleRuns() {
|
|
1075
1261
|
const recovered = [];
|
|
1076
1262
|
for (const task of await readTasks()) {
|
|
1263
|
+
if (task.guard_policy?.preflight) continue;
|
|
1077
1264
|
if ((task.run_count ?? 0) !== 1 || !task.thread_id
|
|
1078
1265
|
|| !(task.run_evidence?.run === 1 || (task.run_host_pid && task.started_at)) || !task.guard_policy
|
|
1079
1266
|
|| !(task.status === "lost" || task.attention_reason === "no_work" || task.attention_reason === "invalid_report")
|
|
@@ -1104,6 +1291,7 @@ export async function recoverEligibleRuns() {
|
|
|
1104
1291
|
|
|
1105
1292
|
if (process.argv[1] === fileURLToPath(import.meta.url) && process.argv[2] === "--run-host") {
|
|
1106
1293
|
process.once("message", async (job) => {
|
|
1294
|
+
const keepAlive = setInterval(() => {}, 1000);
|
|
1107
1295
|
let result;
|
|
1108
1296
|
try {
|
|
1109
1297
|
result = await trackRunInHost(job);
|
|
@@ -1112,9 +1300,10 @@ if (process.argv[1] === fileURLToPath(import.meta.url) && process.argv[2] === "-
|
|
|
1112
1300
|
result = failedStart(job.record, `run host failed: ${error.message}`);
|
|
1113
1301
|
await upsertTask(result.record);
|
|
1114
1302
|
}
|
|
1115
|
-
if (process.connected) process.send({ ok: result.ok, record: result.record },
|
|
1116
|
-
|
|
1117
|
-
|
|
1303
|
+
if (process.connected) await new Promise((resolveSent) => process.send({ ok: result.ok, record: result.record }, resolveSent));
|
|
1304
|
+
if (result.settled) await result.settled;
|
|
1305
|
+
clearInterval(keepAlive);
|
|
1306
|
+
if (process.connected) process.disconnect();
|
|
1118
1307
|
});
|
|
1119
1308
|
}
|
|
1120
1309
|
|
|
@@ -1249,7 +1438,8 @@ export async function createFollowupWorker({
|
|
|
1249
1438
|
maxRunMs,
|
|
1250
1439
|
maxTotalMs,
|
|
1251
1440
|
workspaceKind,
|
|
1252
|
-
inPlaceAuthorization
|
|
1441
|
+
inPlaceAuthorization,
|
|
1442
|
+
workspaceSetup
|
|
1253
1443
|
}) {
|
|
1254
1444
|
const parent = await getTask(taskId);
|
|
1255
1445
|
if (!parent) throw new Error(`task not found: ${taskId}`);
|
|
@@ -1303,6 +1493,7 @@ export async function createFollowupWorker({
|
|
|
1303
1493
|
followupOf: parent.id,
|
|
1304
1494
|
workspaceKind: workspaceKind ?? (parent.workspace_kind === "legacy" ? null : parent.workspace_kind),
|
|
1305
1495
|
inPlaceAuthorization: inPlaceAuthorization ?? parent.workspace_metadata?.in_place_authorization ?? null,
|
|
1496
|
+
workspaceSetup: workspaceSetup ?? parent.workspace_metadata?.setup ?? null,
|
|
1306
1497
|
baseRef: baseRef ?? null,
|
|
1307
1498
|
// Inherited unless given; the follow-up runs in a fresh worktree cut
|
|
1308
1499
|
// from the project HEAD, so the parent's checks only pass there once
|
package/src/context-compiler.js
CHANGED
|
@@ -50,8 +50,10 @@ export async function compileWorkerContext(task, { attempt }) {
|
|
|
50
50
|
`- run_id: ${runIdFor(task.id, attempt)}`,
|
|
51
51
|
`- project_root: ${task.project_root}`,
|
|
52
52
|
`- base_sha: ${task.base_commit ?? "unknown"}`,
|
|
53
|
+
`- branch: ${task.worktree_path ? `codex/${task.id}` : "not applicable (in-place workspace)"}`,
|
|
53
54
|
`- worktree: ${task.worktree_path ?? task.cwd}`,
|
|
54
55
|
`- owned_paths: ${JSON.stringify(task.owned_paths ?? [])}`,
|
|
56
|
+
`- acceptance_source: ${Array.isArray(task.acceptance) && task.acceptance.length > 0 ? "dispatch or session policy; commands stay outside this capsule" : "no acceptance configured"}`,
|
|
55
57
|
"L1 task:",
|
|
56
58
|
`- objective: ${task.goal_objective ?? task.title ?? "unspecified"}`
|
|
57
59
|
];
|
|
@@ -82,5 +84,5 @@ export async function compileWorkerContext(task, { attempt }) {
|
|
|
82
84
|
candidate_facts: "never automatic"
|
|
83
85
|
}
|
|
84
86
|
});
|
|
85
|
-
return { text, snapshot, sourceRefs: handoff.source_refs, factCount: usedFacts.length };
|
|
87
|
+
return { text, snapshot, sourceRefs: handoff.source_refs, contentHash: handoff.content_hash, factCount: usedFacts.length };
|
|
86
88
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { isGoalNeedingAttention } from "./status.js";
|
|
2
|
+
|
|
3
|
+
function providerFailure(text) {
|
|
4
|
+
if (!/provider|upstream_status|upstream status|cc switch|responses endpoint/i.test(text)) return null;
|
|
5
|
+
const status = Number(text.match(/(?:upstream_status|upstream status|unexpected status|HTTP)\D{0,8}(\d{3})/i)?.[1] ?? 0);
|
|
6
|
+
const retryable = status === 429 || status >= 500 || /timeout|temporar|rate.?limit/i.test(text);
|
|
7
|
+
return { source: "provider", code: status ? `provider_http_${status}` : "provider_error", retryable };
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function classifyFailure(task) {
|
|
11
|
+
if (!task) return null;
|
|
12
|
+
const error = String(task.error ?? "");
|
|
13
|
+
const attention = String(task.attention_reason ?? "");
|
|
14
|
+
|
|
15
|
+
const provider = providerFailure(error);
|
|
16
|
+
if (provider) return provider;
|
|
17
|
+
if (/did not record the process exit/i.test(error)) return { source: "supervisor_process", code: "exit_unrecorded", retryable: true };
|
|
18
|
+
if (attention === "start_failed") return { source: "supervisor_process", code: "start_failed", retryable: true };
|
|
19
|
+
if (/^workspaceSetup command failed:/i.test(error)) return { source: "workspace_setup", code: "setup_command_failed", retryable: true };
|
|
20
|
+
if (/^workspaceSetup link /i.test(error)) return { source: "workspace_setup", code: "setup_link_failed", retryable: true };
|
|
21
|
+
if (attention === "invalid_report" || /Invalid final worker report/i.test(error)) return { source: "model_output", code: "invalid_report", retryable: true };
|
|
22
|
+
if (task.acceptance_results?.passed === false) return { source: "acceptance", code: "acceptance_failed", retryable: true };
|
|
23
|
+
if (attention === "no_work" || attention === "two_stall") return { source: "worker_progress", code: attention, retryable: false };
|
|
24
|
+
if (attention === "time_limit" || attention === "total_time_limit") return { source: "supervisor_process", code: attention, retryable: false };
|
|
25
|
+
if (task.status === "lost") return { source: "supervisor_process", code: "worker_lost", retryable: true };
|
|
26
|
+
if (task.status === "cancelled") return { source: "caller", code: "cancelled", retryable: true };
|
|
27
|
+
if (/codex exited with code/i.test(error)) return { source: "worker_process", code: "process_exit_nonzero", retryable: true };
|
|
28
|
+
if (isGoalNeedingAttention(task.goal_status)) return { source: "goal", code: `goal_${task.goal_status}`, retryable: false };
|
|
29
|
+
if (task.status === "failed") return { source: "unknown", code: "failed", retryable: null };
|
|
30
|
+
return null;
|
|
31
|
+
}
|
package/src/handoff.js
CHANGED
|
@@ -2,6 +2,14 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { readFile, lstat } from "node:fs/promises";
|
|
3
3
|
import { isAbsolute } from "node:path";
|
|
4
4
|
|
|
5
|
+
export function contextContentHash(refs = []) {
|
|
6
|
+
if (!Array.isArray(refs) || refs.length === 0) return null;
|
|
7
|
+
const canonical = refs
|
|
8
|
+
.map((ref) => ({ path: String(ref.path), sha256: String(ref.sha256) }))
|
|
9
|
+
.sort((left, right) => left.path.localeCompare(right.path));
|
|
10
|
+
return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
|
|
11
|
+
}
|
|
12
|
+
|
|
5
13
|
export async function buildHandoff({ goal, todo, contracts = [], context = [] }, { maxLines = 16, maxChars = 1800 } = {}) {
|
|
6
14
|
if (!Array.isArray(context) || context.length > 20 || !Array.isArray(contracts)
|
|
7
15
|
|| contracts.some((value) => typeof value !== "string") || JSON.stringify({ context, contracts }).length > 6000) throw new Error("context and contracts exceed the 6000 character input budget");
|
|
@@ -26,5 +34,5 @@ export async function buildHandoff({ goal, todo, contracts = [], context = [] },
|
|
|
26
34
|
}
|
|
27
35
|
const truncated = lines.length !== candidates.length;
|
|
28
36
|
if (truncated) lines.push(marker);
|
|
29
|
-
return { text: lines.join("\n"), truncated, source_refs: refs };
|
|
37
|
+
return { text: lines.join("\n"), truncated, source_refs: refs, content_hash: contextContentHash(refs) };
|
|
30
38
|
}
|