codex-supervisor-mcp 0.10.2 → 0.11.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 +25 -7
- package/README.md +23 -14
- package/package.json +6 -4
- package/skills/codex-supervisor/SKILL.md +20 -13
- package/src/cleanup-hint.js +3 -2
- package/src/cleanup-plan.js +67 -7
- package/src/cleanup.js +48 -40
- package/src/codex-runner.js +101 -79
- package/src/mcp-server.js +377 -36
- package/src/overview-delta.js +37 -5
- package/src/paths.js +2 -0
- package/src/prompt.js +5 -2
- package/src/runner-adapter.js +100 -0
- package/src/side-chat.js +10 -38
- package/src/task-store.js +284 -23
- package/src/worker-preflight.js +5 -1
- package/src/workspace-kind.js +167 -0
package/src/cleanup.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { applyCleanupPlan, createCleanupPlan } from "./cleanup-plan.js";
|
|
3
|
+
import { getCleanupPlan, saveCleanupPlan } from "./task-store.js";
|
|
4
4
|
|
|
5
5
|
function parseArgs(argv) {
|
|
6
|
-
const options = { apply: false, taskIds: [] };
|
|
6
|
+
const options = { apply: false, taskIds: [], itemIds: [], planId: null };
|
|
7
7
|
for (let index = 0; index < argv.length; index += 1) {
|
|
8
8
|
const arg = argv[index];
|
|
9
9
|
if (arg === "--apply") options.apply = true;
|
|
@@ -11,10 +11,19 @@ function parseArgs(argv) {
|
|
|
11
11
|
else if (arg === "--task") {
|
|
12
12
|
options.taskIds.push(argv[index + 1]);
|
|
13
13
|
index += 1;
|
|
14
|
+
} else if (arg === "--plan") {
|
|
15
|
+
options.planId = argv[index + 1];
|
|
16
|
+
index += 1;
|
|
17
|
+
} else if (arg === "--item") {
|
|
18
|
+
options.itemIds.push(argv[index + 1]);
|
|
19
|
+
index += 1;
|
|
14
20
|
} else if (arg === "--help" || arg === "-h") options.help = true;
|
|
15
21
|
else throw new Error(`Unknown argument: ${arg}`);
|
|
16
22
|
}
|
|
17
23
|
if (options.taskIds.some((id) => !id)) throw new Error("--task requires a task id");
|
|
24
|
+
if (options.itemIds.some((id) => !id)) throw new Error("--item requires a cleanup plan item id");
|
|
25
|
+
if (options.apply && (!options.planId || options.itemIds.length === 0)) throw new Error("--apply requires --plan <plan_id> and one or more --item <item_id>");
|
|
26
|
+
if (!options.apply && (options.planId || options.itemIds.length)) throw new Error("--plan and --item are only valid with --apply");
|
|
18
27
|
return options;
|
|
19
28
|
}
|
|
20
29
|
|
|
@@ -23,50 +32,49 @@ function printHelp() {
|
|
|
23
32
|
|
|
24
33
|
Options:
|
|
25
34
|
--dry-run Create and print a SAFE / REVIEW / BLOCKED plan. Default.
|
|
26
|
-
--apply
|
|
35
|
+
--apply Apply selected SAFE items from an existing plan.
|
|
27
36
|
--task <task_id> Limit the plan to one task; repeatable.
|
|
37
|
+
--plan <plan_id> Existing cleanup plan to apply (required with --apply).
|
|
38
|
+
--item <item_id> SAFE item to apply; repeatable (required with --apply).
|
|
28
39
|
-h, --help Show help.
|
|
29
40
|
|
|
30
41
|
Cleanup never removes branches, task rows, events, JSONL logs or artifacts.
|
|
31
42
|
`);
|
|
32
43
|
}
|
|
33
44
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
const plan = await createCleanupPlan({ taskIds: options.taskIds.length ? options.taskIds : null });
|
|
41
|
-
await saveCleanupPlan(plan);
|
|
42
|
-
const applied = [];
|
|
43
|
-
const skipped = [];
|
|
44
|
-
if (options.apply) {
|
|
45
|
-
for (const item of plan.items.filter((entry) => entry.verdict === "safe")) {
|
|
46
|
-
const task = await getTask(item.task_id);
|
|
47
|
-
try {
|
|
48
|
-
await removePlannedWorktree(task, item.fingerprint);
|
|
49
|
-
const now = await markCleanupPlanItemApplied(item.id, "cleanup_cli");
|
|
50
|
-
await updateWorkItemDelivery(task.id, "cleanup_removed");
|
|
51
|
-
await appendTaskEvent(task.id, { type: "supervisor.cleanup_removed", plan_id: plan.id, item_id: item.id, removed_at: now, retained: ["branch", "task", "events", "jsonl", "artifacts"] }, {
|
|
52
|
-
runId: runIdFor(task.id, task.run_count ?? 1), actor: "supervisor"
|
|
53
|
-
});
|
|
54
|
-
applied.push({ task_id: task.id, worktree_path: task.worktree_path, removed_at: now });
|
|
55
|
-
} catch (error) {
|
|
56
|
-
skipped.push({ task_id: item.task_id, reason: error.message.split("\n")[0] });
|
|
57
|
-
}
|
|
45
|
+
async function main() {
|
|
46
|
+
const options = parseArgs(process.argv.slice(2));
|
|
47
|
+
if (options.help) {
|
|
48
|
+
printHelp();
|
|
49
|
+
return;
|
|
58
50
|
}
|
|
51
|
+
|
|
52
|
+
const plan = options.apply
|
|
53
|
+
? await getCleanupPlan(options.planId)
|
|
54
|
+
: await createCleanupPlan({ taskIds: options.taskIds.length ? options.taskIds : null });
|
|
55
|
+
if (!plan) throw new Error(`cleanup plan not found: ${options.planId}`);
|
|
56
|
+
if (!options.apply) await saveCleanupPlan(plan);
|
|
57
|
+
const outcome = options.apply
|
|
58
|
+
? await applyCleanupPlan({ plan, itemIds: options.itemIds, actor: "cleanup_cli" })
|
|
59
|
+
: { applied: [], skipped: [] };
|
|
60
|
+
|
|
61
|
+
console.log(JSON.stringify({
|
|
62
|
+
dry_run: !options.apply,
|
|
63
|
+
plan_id: plan.id,
|
|
64
|
+
generated_at: plan.generated_at,
|
|
65
|
+
expires_at: plan.expires_at,
|
|
66
|
+
policy: plan.policy,
|
|
67
|
+
summary: plan.summary,
|
|
68
|
+
items: plan.items,
|
|
69
|
+
applied: outcome.applied,
|
|
70
|
+
skipped: outcome.skipped,
|
|
71
|
+
retained: ["branch", "task", "events", "jsonl", "artifacts"]
|
|
72
|
+
}, null, 2));
|
|
59
73
|
}
|
|
60
74
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
summary: plan.summary,
|
|
68
|
-
items: plan.items,
|
|
69
|
-
applied,
|
|
70
|
-
skipped,
|
|
71
|
-
retained: ["branch", "task", "events", "jsonl", "artifacts"]
|
|
72
|
-
}, null, 2));
|
|
75
|
+
try {
|
|
76
|
+
await main();
|
|
77
|
+
} catch (error) {
|
|
78
|
+
console.error(error.message);
|
|
79
|
+
process.exitCode = 1;
|
|
80
|
+
}
|
package/src/codex-runner.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createWriteStream, existsSync } from "node:fs";
|
|
2
2
|
import { mkdir, rm, stat } from "node:fs/promises";
|
|
3
|
-
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import { execFileSync, spawn } from "node:child_process";
|
|
5
5
|
import { join, resolve, sep, dirname, isAbsolute } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
@@ -23,7 +23,6 @@ import {
|
|
|
23
23
|
releaseTaskRun,
|
|
24
24
|
reserveTaskOwnership
|
|
25
25
|
} from "./task-store.js";
|
|
26
|
-
import { applyCodexEvent } from "./event-parser.js";
|
|
27
26
|
import { ACTIVE_STATUSES, TERMINAL_STATUSES } from "./status.js";
|
|
28
27
|
import { worktreesDir } from "./paths.js";
|
|
29
28
|
import { buildGuardPreamble, frameWorkerPrompt } from "./prompt.js";
|
|
@@ -32,7 +31,6 @@ import { readTaskChanges, snapshotTaskOutput } from "./worktree.js";
|
|
|
32
31
|
import { rebaseWorktree } from "./landing.js";
|
|
33
32
|
import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, isArtifactOnlyAcceptance, normalizeAcceptance, runAcceptance } from "./acceptance.js";
|
|
34
33
|
import { appendFile } from "node:fs/promises";
|
|
35
|
-
import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
|
|
36
34
|
import { findOutsideOwnedChanges } from "./owned-changes.js";
|
|
37
35
|
import { parseWorkerReport, workerReportSchemaPath } from "./worker-report.js";
|
|
38
36
|
import { buildHandoff } from "./handoff.js";
|
|
@@ -40,12 +38,13 @@ import { compileWorkerContext } from "./context-compiler.js";
|
|
|
40
38
|
import { captureExternalOutputs, compareExternalOutputs } from "./external-output.js";
|
|
41
39
|
import { buildRuntimeContract, createPreflightMetadata, readPreflightResult, runtimeContractHash } from "./worker-preflight.js";
|
|
42
40
|
import { supervisorMcpDisableArgs } from "./mcp-config.js";
|
|
41
|
+
import { captureWorkspaceManifest, isGitCheckout, prepareWorkspace } from "./workspace-kind.js";
|
|
42
|
+
import { codexRunner } from "./runner-adapter.js";
|
|
43
43
|
|
|
44
44
|
const processes = new Map();
|
|
45
45
|
// taskId -> control object of an acceptance run in progress ({ kill, cancelled }).
|
|
46
46
|
const acceptanceRuns = new Map();
|
|
47
47
|
const cancelledTasks = new Set();
|
|
48
|
-
const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
|
|
49
48
|
const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
50
49
|
const allowedReasoningEfforts = new Set(["minimal", "low", "medium", "high"]);
|
|
51
50
|
const MAX_RUN_HOST_PROMPT_BYTES = 4 * 1024 * 1024;
|
|
@@ -54,6 +53,7 @@ async function recordOutcomeFacts({ task, runId, report, reportEventId = null, a
|
|
|
54
53
|
if (!report?.valid) return;
|
|
55
54
|
const workItem = await getWorkItemForTask(task.id);
|
|
56
55
|
if (!workItem) return;
|
|
56
|
+
const validForManifestHash = task.run_evidence?.workspace?.after_manifest?.sha256 ?? null;
|
|
57
57
|
const candidate = await recordFact({
|
|
58
58
|
workItemId: workItem.id,
|
|
59
59
|
scopeType: "run",
|
|
@@ -63,6 +63,7 @@ async function recordOutcomeFacts({ task, runId, report, reportEventId = null, a
|
|
|
63
63
|
state: "candidate",
|
|
64
64
|
sourceEventId: reportEventId,
|
|
65
65
|
validForSha: task.base_commit ?? null,
|
|
66
|
+
validForManifestHash,
|
|
66
67
|
watchedPaths: task.owned_paths ?? []
|
|
67
68
|
});
|
|
68
69
|
if (!acceptancePassed) return;
|
|
@@ -75,8 +76,10 @@ async function recordOutcomeFacts({ task, runId, report, reportEventId = null, a
|
|
|
75
76
|
state: "verified",
|
|
76
77
|
sourceEventId: acceptanceEventId,
|
|
77
78
|
validForSha: task.base_commit ?? null,
|
|
79
|
+
validForManifestHash,
|
|
78
80
|
watchedPaths: task.owned_paths ?? [],
|
|
79
|
-
supersedesId: candidate.id
|
|
81
|
+
supersedesId: candidate.id,
|
|
82
|
+
verifiedBy: "supervisor.acceptance"
|
|
80
83
|
});
|
|
81
84
|
await updateWorkItemDelivery(task.id, "verified");
|
|
82
85
|
}
|
|
@@ -213,18 +216,6 @@ function ownershipConflictError(conflicts) {
|
|
|
213
216
|
return error;
|
|
214
217
|
}
|
|
215
218
|
|
|
216
|
-
// The Codex CLI as a spawnable target. On Windows npm installs a `codex.cmd`
|
|
217
|
-
// shim that Node refuses to spawn directly, so bin-resolver.js steps over it and
|
|
218
|
-
// hands back `node <entry>` instead; on macOS and Linux this is the bare name,
|
|
219
|
-
// unchanged. Resolved per dispatch so a CLI installed later is picked up.
|
|
220
|
-
function codexTarget() {
|
|
221
|
-
const configured = process.env.CODEX_BIN?.trim();
|
|
222
|
-
const located = configured ? configured : (findBinaryPath("codex", { extraDirs: defaultBinDirs() }) ?? "codex");
|
|
223
|
-
const target = resolveCommand(located, { npmEntry: CODEX_NPM_ENTRY });
|
|
224
|
-
if (target.shim) return { error: shimMessage("codex", target.cmd, "CODEX_BIN") };
|
|
225
|
-
return { cmd: target.cmd, prefixArgs: target.prefixArgs };
|
|
226
|
-
}
|
|
227
|
-
|
|
228
219
|
function failedStart(record, reason) {
|
|
229
220
|
const now = new Date().toISOString();
|
|
230
221
|
return {
|
|
@@ -269,15 +260,11 @@ async function spawnAndAwaitStart(target, args, options) {
|
|
|
269
260
|
// Every write goes through one serialized chain so concurrent stdout/stderr
|
|
270
261
|
// callbacks cannot interleave and persist out of order.
|
|
271
262
|
async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {} }) {
|
|
272
|
-
const
|
|
273
|
-
if (
|
|
274
|
-
|
|
275
|
-
const help = execFileSync(target.cmd, [...target.prefixArgs, "exec", "--help"], { encoding: "utf8", timeout: 15000, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
276
|
-
if (!help.includes("--dangerously-bypass-hook-trust") || !help.includes("--output-schema")) return failedStart(record, "Codex CLI lacks required per-run hooks/output-schema; install Codex 0.162 or newer before dispatch");
|
|
277
|
-
} catch (error) { return failedStart(record, error.code === "ENOENT"
|
|
278
|
-
? `failed to spawn ${target.cmd} for Codex capability preflight: ${error.message}`
|
|
279
|
-
: `Codex capability preflight failed: ${error.message}`); }
|
|
263
|
+
const capability = codexRunner.capabilityPreflight();
|
|
264
|
+
if (!capability.ok) return failedStart(record, capability.error);
|
|
265
|
+
const target = capability.target;
|
|
280
266
|
const outputBefore = snapshotTaskOutput(record);
|
|
267
|
+
const workspaceBefore = record.workspace_metadata?.before_manifest ?? null;
|
|
281
268
|
const externalBefore = await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [], { checkBaseline: (record.run_count ?? 0) === 0 });
|
|
282
269
|
const owned = [...findOutsideOwnedChanges(record, []).mapping.map((entry) => entry.worker), ...externalBefore.map((entry) => entry.path)];
|
|
283
270
|
const guardPolicy = { cwd: record.cwd, worktree: record.cwd, sandbox: record.sandbox, ownedPaths: owned, ...(record.guard_policy ?? {}),
|
|
@@ -313,6 +300,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
313
300
|
// A new run starts clean. A resumed worker used to carry the error from
|
|
314
301
|
// the run that was lost, so a worker that was plainly running still showed
|
|
315
302
|
// "process disappeared" until it finished.
|
|
303
|
+
const priorAttemptFingerprint = record.run_evidence?.attempt_fingerprint ?? null;
|
|
316
304
|
let live = {
|
|
317
305
|
...record,
|
|
318
306
|
status: "running",
|
|
@@ -394,7 +382,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
394
382
|
if (["turn.completed", "turn.failed"].includes(event.type)) terminalEvent = true;
|
|
395
383
|
const storedEvent = await appendTaskEvent(record.id, event, { runId, actor: "codex" });
|
|
396
384
|
if (event.type === "item.completed" && event.item?.type === "agent_message") rawReportEventId = storedEvent.id;
|
|
397
|
-
await persist(
|
|
385
|
+
await persist(codexRunner.parseEvent(live, event));
|
|
398
386
|
};
|
|
399
387
|
|
|
400
388
|
let stdoutRest = "";
|
|
@@ -473,18 +461,43 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
473
461
|
let externalChanges = [];
|
|
474
462
|
try { externalChanges = compareExternalOutputs(externalBefore, await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [])); }
|
|
475
463
|
catch (error) { next.attention_reason = "external_output_unverified"; next.error = error.message; }
|
|
464
|
+
let workspaceAfter = null;
|
|
465
|
+
if (workspaceBefore && Array.isArray(record.workspace_metadata?.manifest_paths)) {
|
|
466
|
+
try {
|
|
467
|
+
workspaceAfter = await captureWorkspaceManifest(record.workspace_metadata.source_root, record.workspace_metadata.manifest_paths);
|
|
468
|
+
} catch (error) {
|
|
469
|
+
next.attention_reason = "workspace_manifest_unverified";
|
|
470
|
+
next.error = error.message;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
476
473
|
next.run_evidence = {
|
|
477
474
|
run: live.run_count, commands_run: live.commands.length,
|
|
478
475
|
structured_report: parseWorkerReport(rawReport),
|
|
479
476
|
output_before: outputBefore, output_after: outputAfter,
|
|
480
|
-
output_changed: outputBefore && outputAfter ? outputBefore !== outputAfter : null
|
|
477
|
+
output_changed: outputBefore && outputAfter ? outputBefore !== outputAfter : null,
|
|
478
|
+
workspace: workspaceBefore ? {
|
|
479
|
+
kind: record.workspace_kind,
|
|
480
|
+
before_manifest: workspaceBefore,
|
|
481
|
+
after_manifest: workspaceAfter,
|
|
482
|
+
manifest_changed: workspaceAfter ? workspaceBefore.sha256 !== workspaceAfter.sha256 : null
|
|
483
|
+
} : null
|
|
481
484
|
};
|
|
482
485
|
next.run_evidence.external_outputs = externalChanges;
|
|
483
486
|
if (externalChanges.some((entry) => entry.changed)) next.run_evidence.output_changed = true;
|
|
484
487
|
next.changed_files = [...new Set([...next.changed_files, ...externalChanges.filter((entry) => entry.changed).map((entry) => entry.path)])];
|
|
488
|
+
next.run_evidence.attempt_fingerprint = createHash("sha256").update(JSON.stringify({
|
|
489
|
+
output_changed: next.run_evidence.output_changed,
|
|
490
|
+
commands_run: live.commands.length,
|
|
491
|
+
changed_files: next.changed_files,
|
|
492
|
+
acceptance_configured: Array.isArray(live.acceptance) && live.acceptance.length > 0,
|
|
493
|
+
workspace_manifest_changed: next.run_evidence.workspace?.manifest_changed ?? null
|
|
494
|
+
})).digest("hex");
|
|
485
495
|
if (status === "completed" && code === 0 && live.sandbox !== "read-only"
|
|
486
496
|
&& !next.run_evidence.output_changed && next.run_evidence.output_changed !== null
|
|
487
|
-
&& live.commands.length === 0)
|
|
497
|
+
&& live.commands.length === 0) {
|
|
498
|
+
next.attention_reason = priorAttemptFingerprint === next.run_evidence.attempt_fingerprint ? "two_stall" : "no_work";
|
|
499
|
+
if (next.attention_reason === "two_stall") next.current_action = "No progress in two consecutive runs; needs attention";
|
|
500
|
+
}
|
|
488
501
|
if (status === "completed" && !next.run_evidence.structured_report.valid) {
|
|
489
502
|
next.status = "failed";
|
|
490
503
|
next.attention_reason = "invalid_report";
|
|
@@ -552,6 +565,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
552
565
|
acceptanceEventId: acceptanceEvent?.id ?? null,
|
|
553
566
|
acceptancePassed: results.passed === true
|
|
554
567
|
});
|
|
568
|
+
if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
|
|
555
569
|
} else {
|
|
556
570
|
const finalRecord = acceptance ? { ...next, acceptance_results: null } : next;
|
|
557
571
|
await persist(finalRecord);
|
|
@@ -562,6 +576,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
562
576
|
report: finalRecord.run_evidence?.structured_report,
|
|
563
577
|
reportEventId: rawReportEventId
|
|
564
578
|
});
|
|
579
|
+
if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
|
|
565
580
|
}
|
|
566
581
|
cancelledTasks.delete(record.id);
|
|
567
582
|
});
|
|
@@ -629,15 +644,6 @@ async function startTrackedRun(job) {
|
|
|
629
644
|
return started;
|
|
630
645
|
}
|
|
631
646
|
|
|
632
|
-
function buildExecArgs({ cwd, sandbox, model, reasoningEffort, skipGitRepoCheck }) {
|
|
633
|
-
const args = ["exec", "--json", "--cd", cwd, "--sandbox", sandbox];
|
|
634
|
-
if (skipGitRepoCheck) args.push("--skip-git-repo-check");
|
|
635
|
-
if (model) args.push("--model", model);
|
|
636
|
-
args.push("-c", `model_reasoning_effort="${reasoningEffort}"`);
|
|
637
|
-
args.push("-");
|
|
638
|
-
return args;
|
|
639
|
-
}
|
|
640
|
-
|
|
641
647
|
function validateGoal(goal) {
|
|
642
648
|
if (!goal || typeof goal !== "object" || typeof goal.objective !== "string" || goal.objective.trim() === "") {
|
|
643
649
|
throw new Error("goal.objective is required");
|
|
@@ -727,7 +733,8 @@ export async function createCodexWorker({
|
|
|
727
733
|
goal,
|
|
728
734
|
dependsOn = [],
|
|
729
735
|
followupOf = null,
|
|
730
|
-
|
|
736
|
+
workspaceKind = null,
|
|
737
|
+
inPlaceAuthorization = null,
|
|
731
738
|
baseRef = null,
|
|
732
739
|
preflightId = null,
|
|
733
740
|
preflight = null,
|
|
@@ -779,8 +786,22 @@ export async function createCodexWorker({
|
|
|
779
786
|
for (const [name, values] of Object.entries({ forbid, allowedCommands })) {
|
|
780
787
|
if (!Array.isArray(values) || values.length > 100 || values.some((value) => typeof value !== "string" || !value.trim())) throw new Error(`${name} must be a list of at most 100 nonempty strings`);
|
|
781
788
|
}
|
|
789
|
+
if (baseRef && !isGitCheckout(cwd)) throw invalidBaseRefError(cwd, baseRef);
|
|
782
790
|
|
|
783
|
-
const
|
|
791
|
+
const id = `codex-${Date.now()}-${randomUUID().slice(0, 8)}`;
|
|
792
|
+
const workspace = await prepareWorkspace({
|
|
793
|
+
cwd,
|
|
794
|
+
workspaceKind,
|
|
795
|
+
sandbox,
|
|
796
|
+
ownedPaths,
|
|
797
|
+
networkAccess,
|
|
798
|
+
acceptance: acceptanceCommands,
|
|
799
|
+
externalOutputs,
|
|
800
|
+
inPlaceAuthorization,
|
|
801
|
+
taskId: id,
|
|
802
|
+
isPreflight: Boolean(preflight)
|
|
803
|
+
});
|
|
804
|
+
const projectRoot = workspace.sourceRoot;
|
|
784
805
|
const normalizedOwnedPaths = normalizeOwnedPaths([...ownedPaths, ...externalOutputs.map((entry) => entry.path)], projectRoot);
|
|
785
806
|
const conflicts = await findOwnershipConflicts(normalizedOwnedPaths);
|
|
786
807
|
if (conflicts.length > 0) throw ownershipConflictError(conflicts);
|
|
@@ -797,12 +818,16 @@ export async function createCodexWorker({
|
|
|
797
818
|
}
|
|
798
819
|
const combinedAcceptance = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(acceptanceCommands ?? [])]);
|
|
799
820
|
|
|
800
|
-
const
|
|
801
|
-
const worktree = useWorktree
|
|
821
|
+
const worktree = workspace.kind === "git_worktree"
|
|
802
822
|
? await ensureWorktree(projectRoot, id, baseRef)
|
|
803
823
|
: { path: null, baseCommit: null };
|
|
804
824
|
const worktreePath = worktree.path;
|
|
805
|
-
|
|
825
|
+
if (workspace.kind === "git_worktree" && !worktreePath) {
|
|
826
|
+
const error = new Error("workspaceKind git_worktree could not create an isolated worktree; use read_only_in_place for a non-writing inspection or initialize and commit the repository first");
|
|
827
|
+
error.code = "git_worktree_unavailable";
|
|
828
|
+
throw error;
|
|
829
|
+
}
|
|
830
|
+
const effectiveCwd = worktreePath ?? workspace.executionCwd;
|
|
806
831
|
if (preflight && (!Array.isArray(preflight.probeCommands) || preflight.probeCommands.length === 0
|
|
807
832
|
|| preflight.probeCommands.some((command) => typeof command !== "string" || !command.trim()))) {
|
|
808
833
|
throw new Error("preflight.probeCommands must be a nonempty list of shell commands");
|
|
@@ -814,7 +839,8 @@ export async function createCodexWorker({
|
|
|
814
839
|
networkAccess,
|
|
815
840
|
writableRoots: [...new Set(resolvedWritableRoots)],
|
|
816
841
|
maxRunMs,
|
|
817
|
-
maxTotalMs
|
|
842
|
+
maxTotalMs,
|
|
843
|
+
workspaceKind: workspace.kind
|
|
818
844
|
};
|
|
819
845
|
const runtimeContract = buildRuntimeContract({
|
|
820
846
|
projectRoot,
|
|
@@ -825,7 +851,9 @@ export async function createCodexWorker({
|
|
|
825
851
|
networkAccess,
|
|
826
852
|
writableRoots: guardPolicy.writableRoots,
|
|
827
853
|
context,
|
|
828
|
-
contracts
|
|
854
|
+
contracts,
|
|
855
|
+
workspaceKind: workspace.kind,
|
|
856
|
+
workspaceManifestSha256: workspace.beforeManifest?.sha256 ?? null
|
|
829
857
|
});
|
|
830
858
|
const preflightMetadata = preflight
|
|
831
859
|
? createPreflightMetadata(runtimeContract, preflight.probeCommands)
|
|
@@ -839,6 +867,16 @@ export async function createCodexWorker({
|
|
|
839
867
|
phase: null,
|
|
840
868
|
cwd: effectiveCwd,
|
|
841
869
|
project_root: projectRoot,
|
|
870
|
+
workspace_kind: workspace.kind,
|
|
871
|
+
workspace_metadata: {
|
|
872
|
+
source_root: workspace.sourceRoot,
|
|
873
|
+
execution_root: effectiveCwd,
|
|
874
|
+
manifest_paths: workspace.manifestPaths,
|
|
875
|
+
before_manifest: workspace.beforeManifest,
|
|
876
|
+
in_place_authorization: workspace.kind === "in_place_write" ? String(inPlaceAuthorization).trim() : null,
|
|
877
|
+
landable: workspace.landable,
|
|
878
|
+
cleanable: workspace.cleanable
|
|
879
|
+
},
|
|
842
880
|
sandbox,
|
|
843
881
|
model,
|
|
844
882
|
reasoning_effort: reasoningEffort,
|
|
@@ -851,7 +889,14 @@ export async function createCodexWorker({
|
|
|
851
889
|
guard_policy: {
|
|
852
890
|
...guardPolicy,
|
|
853
891
|
...(preflightMetadata ? { preflight: preflightMetadata } : {}),
|
|
854
|
-
...(preflightId ? { preflight_source_id: preflightId } : {})
|
|
892
|
+
...(preflightId ? { preflight_source_id: preflightId } : {}),
|
|
893
|
+
workspace: {
|
|
894
|
+
kind: workspace.kind,
|
|
895
|
+
source_root: workspace.sourceRoot,
|
|
896
|
+
execution_root: effectiveCwd,
|
|
897
|
+
manifest_paths: workspace.manifestPaths,
|
|
898
|
+
before_manifest_sha256: workspace.beforeManifest?.sha256 ?? null
|
|
899
|
+
}
|
|
855
900
|
},
|
|
856
901
|
input_context: { context, contracts },
|
|
857
902
|
depends_on: Array.isArray(dependsOn) ? dependsOn : [],
|
|
@@ -904,10 +949,11 @@ export async function createCodexWorker({
|
|
|
904
949
|
await runCommand(defaultGitBin,["-C",projectRoot,"worktree","remove",worktreePath]).catch(()=>{});
|
|
905
950
|
await runCommand(defaultGitBin,["-C",projectRoot,"branch","-D",`codex/${id}`]).catch(()=>{});
|
|
906
951
|
}
|
|
952
|
+
if (workspace.scratchPath) await rm(workspace.scratchPath, { recursive: true, force: true }).catch(() => {});
|
|
907
953
|
throw error;
|
|
908
954
|
}
|
|
909
955
|
|
|
910
|
-
const args =
|
|
956
|
+
const args = codexRunner.startArgs({ cwd: effectiveCwd, sandbox, model, reasoningEffort, skipGitRepoCheck });
|
|
911
957
|
|
|
912
958
|
const started = await startTrackedRun({
|
|
913
959
|
record,
|
|
@@ -1009,13 +1055,7 @@ export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acc
|
|
|
1009
1055
|
}
|
|
1010
1056
|
|
|
1011
1057
|
const cwd = (await exists(task.cwd)) ? task.cwd : task.project_root;
|
|
1012
|
-
const args =
|
|
1013
|
-
args.push("-c", `sandbox_mode="${task.sandbox}"`);
|
|
1014
|
-
if (task.model) args.push("--model", task.model);
|
|
1015
|
-
args.push("-c", `model_reasoning_effort="${task.reasoning_effort ?? "high"}"`);
|
|
1016
|
-
if (task.skip_git_repo_check) args.push("--skip-git-repo-check");
|
|
1017
|
-
args.push(task.thread_id);
|
|
1018
|
-
args.push("-");
|
|
1058
|
+
const args = codexRunner.resumeArgs(task);
|
|
1019
1059
|
|
|
1020
1060
|
const started = await startTrackedRun({
|
|
1021
1061
|
record: { ...task, resumed_from: task.resumed_from ?? task.id },
|
|
@@ -1129,39 +1169,18 @@ function describeProcess(pid) {
|
|
|
1129
1169
|
}
|
|
1130
1170
|
|
|
1131
1171
|
function isLikelyCodexProcess(pid) {
|
|
1132
|
-
|
|
1133
|
-
return description.includes("codex");
|
|
1172
|
+
return codexRunner.ownsPid(pid, describeProcess);
|
|
1134
1173
|
}
|
|
1135
1174
|
|
|
1136
1175
|
// Ends a worker and, on Windows, its whole process tree: the direct child there
|
|
1137
1176
|
// is the JS wrapper around the native Codex binary, so terminating it alone
|
|
1138
1177
|
// would leave the real CLI running and the task stuck in `running`.
|
|
1139
1178
|
function terminateChild(child) {
|
|
1140
|
-
|
|
1141
|
-
try {
|
|
1142
|
-
execFileSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], {
|
|
1143
|
-
stdio: "ignore",
|
|
1144
|
-
timeout: 5000,
|
|
1145
|
-
windowsHide: true
|
|
1146
|
-
});
|
|
1147
|
-
return;
|
|
1148
|
-
} catch {
|
|
1149
|
-
// fall back to the handle-based kill below
|
|
1150
|
-
}
|
|
1151
|
-
}
|
|
1152
|
-
child.kill("SIGTERM");
|
|
1179
|
+
codexRunner.cancelChild(child);
|
|
1153
1180
|
}
|
|
1154
1181
|
|
|
1155
1182
|
function terminatePid(pid) {
|
|
1156
|
-
|
|
1157
|
-
execFileSync("taskkill", ["/PID", String(pid), "/T", "/F"], {
|
|
1158
|
-
stdio: "ignore",
|
|
1159
|
-
timeout: 5000,
|
|
1160
|
-
windowsHide: true
|
|
1161
|
-
});
|
|
1162
|
-
return;
|
|
1163
|
-
}
|
|
1164
|
-
process.kill(pid, "SIGTERM");
|
|
1183
|
+
codexRunner.cancelPid(pid);
|
|
1165
1184
|
}
|
|
1166
1185
|
|
|
1167
1186
|
export async function cancelCodexWorker(taskId) {
|
|
@@ -1228,7 +1247,9 @@ export async function createFollowupWorker({
|
|
|
1228
1247
|
networkAccess,
|
|
1229
1248
|
writableRoots,
|
|
1230
1249
|
maxRunMs,
|
|
1231
|
-
maxTotalMs
|
|
1250
|
+
maxTotalMs,
|
|
1251
|
+
workspaceKind,
|
|
1252
|
+
inPlaceAuthorization
|
|
1232
1253
|
}) {
|
|
1233
1254
|
const parent = await getTask(taskId);
|
|
1234
1255
|
if (!parent) throw new Error(`task not found: ${taskId}`);
|
|
@@ -1280,7 +1301,8 @@ export async function createFollowupWorker({
|
|
|
1280
1301
|
goal: goal ?? { objective: parent.goal_objective ?? `Follow-up for ${parent.id}`, tokenBudget: parent.goal_token_budget ?? undefined },
|
|
1281
1302
|
dependsOn: [],
|
|
1282
1303
|
followupOf: parent.id,
|
|
1283
|
-
|
|
1304
|
+
workspaceKind: workspaceKind ?? (parent.workspace_kind === "legacy" ? null : parent.workspace_kind),
|
|
1305
|
+
inPlaceAuthorization: inPlaceAuthorization ?? parent.workspace_metadata?.in_place_authorization ?? null,
|
|
1284
1306
|
baseRef: baseRef ?? null,
|
|
1285
1307
|
// Inherited unless given; the follow-up runs in a fresh worktree cut
|
|
1286
1308
|
// from the project HEAD, so the parent's checks only pass there once
|