codex-supervisor-mcp 0.13.4 → 0.13.6
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 +101 -297
- package/README.md +99 -310
- package/package.json +24 -63
- package/src/{acceptance.js → app/acceptance.js} +54 -68
- package/src/app/cancel.js +60 -0
- package/src/{cleanup-plan.js → app/cleanup-plan.js} +13 -14
- package/src/app/compose.js +7 -0
- package/src/{context-compiler.js → app/context-compiler.js} +7 -13
- package/src/app/dispatch.js +396 -0
- package/src/app/followup.js +98 -0
- package/src/app/land-chain.js +124 -0
- package/src/app/landing.js +357 -0
- package/src/app/ownership.js +57 -0
- package/src/app/rebase.js +216 -0
- package/src/app/resume.js +164 -0
- package/src/app/run-state.js +26 -0
- package/src/app/settled.js +28 -0
- package/src/{side-chat.js → app/side-chat.js} +79 -266
- package/src/app/sse.js +20 -0
- package/src/app/start-run.js +77 -0
- package/src/app/verify-push.js +119 -0
- package/src/app/worktree-setup.js +176 -0
- package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
- package/src/domain/acceptance-spec.js +30 -0
- package/src/domain/command-outcome.js +6 -0
- package/src/{overview-delta.js → domain/overview-delta.js} +5 -1
- package/src/domain/side-turn-view.js +73 -0
- package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
- package/src/infra/git.js +30 -0
- package/src/infra/process.js +59 -0
- package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
- package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
- package/src/infra/store/db.js +265 -0
- package/src/infra/store/events.js +146 -0
- package/src/infra/store/facts.js +338 -0
- package/src/infra/store/reconcile.js +172 -0
- package/src/infra/store/records.js +160 -0
- package/src/infra/store/runner-readers.js +16 -0
- package/src/infra/store/schema.js +306 -0
- package/src/infra/store/sessions.js +138 -0
- package/src/infra/store/tasks.js +307 -0
- package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
- package/src/{auto-update.js → infra/update/auto-update.js} +3 -4
- package/src/{update-check.js → infra/update/update-check.js} +4 -4
- package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
- package/src/{worktree.js → infra/worktree.js} +57 -42
- package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
- package/src/{cleanup.js → interface/bin/cleanup.js} +3 -2
- package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
- package/src/{setup.js → interface/bin/setup.js} +9 -8
- package/src/{stage.js → interface/bin/stage.js} +1 -1
- package/src/{web-server.js → interface/bin/web-server.js} +2 -2
- package/src/interface/mcp/meta.js +7 -0
- package/src/interface/mcp/result.js +34 -0
- package/src/interface/mcp/schemas.js +24 -0
- package/src/interface/mcp/server.js +94 -0
- package/src/interface/mcp/tools/delivery.js +197 -0
- package/src/interface/mcp/tools/dispatch.js +267 -0
- package/src/interface/mcp/tools/facts.js +239 -0
- package/src/interface/mcp/tools/overview.js +202 -0
- package/src/interface/mcp/tools/poll.js +62 -0
- package/src/interface/mcp/tools/results.js +270 -0
- package/src/interface/mcp/tools/review.js +135 -0
- package/src/interface/mcp/tools/wait.js +145 -0
- package/src/interface/mcp/update-state.js +34 -0
- package/src/interface/mcp/views/overview.js +183 -0
- package/src/interface/mcp/views/task.js +223 -0
- package/src/interface/web/app.js +226 -0
- package/src/interface/web/views.js +224 -0
- package/src/mcp-server.js +3 -2223
- package/src/run-host/entry.js +23 -0
- package/src/run-host/finalize.js +236 -0
- package/src/run-host/launch.js +63 -0
- package/src/run-host/live-run.js +73 -0
- package/src/run-host/outcome-facts.js +61 -0
- package/src/run-host/streams.js +76 -0
- package/src/run-host/track.js +128 -0
- package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
- package/src/runners/codex/chat-chunks.js +97 -0
- package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
- package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
- package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
- package/src/codex-runner.js +0 -1586
- package/src/landing.js +0 -507
- package/src/task-store.js +0 -1800
- package/src/web-app.js +0 -425
- /package/src/{failure-class.js → domain/failure-class.js} +0 -0
- /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
- /package/src/{prompt.js → domain/prompt.js} +0 -0
- /package/src/{status.js → domain/status.js} +0 -0
- /package/src/{thread-health.js → domain/thread-health.js} +0 -0
- /package/src/{truncate.js → domain/truncate.js} +0 -0
- /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
- /package/src/{worker-env.js → domain/worker-env.js} +0 -0
- /package/src/{worker-report.js → domain/worker-report.js} +0 -0
- /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
- /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
- /package/src/{cleanup-hint.js → infra/cleanup-hint.js} +0 -0
- /package/src/{external-output.js → infra/external-output.js} +0 -0
- /package/src/{handoff.js → infra/handoff.js} +0 -0
- /package/src/{paths.js → infra/paths.js} +0 -0
- /package/src/{stage-store.js → infra/stage-store.js} +0 -0
- /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
package/src/codex-runner.js
DELETED
|
@@ -1,1586 +0,0 @@
|
|
|
1
|
-
import { closeSync, createWriteStream, existsSync, openSync } from "node:fs";
|
|
2
|
-
import { lstat, mkdir, realpath, rm, stat, symlink } from "node:fs/promises";
|
|
3
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
-
import { execFileSync, spawn } from "node:child_process";
|
|
5
|
-
import { basename, join, resolve, relative, sep, dirname, isAbsolute } from "node:path";
|
|
6
|
-
import { fileURLToPath } from "node:url";
|
|
7
|
-
import {
|
|
8
|
-
appendTaskEvent,
|
|
9
|
-
appendTaskEvents,
|
|
10
|
-
getTask,
|
|
11
|
-
getSession,
|
|
12
|
-
readActiveTasks,
|
|
13
|
-
readTasks,
|
|
14
|
-
readTaskEvents,
|
|
15
|
-
taskRunPath,
|
|
16
|
-
upsertSession,
|
|
17
|
-
upsertTask,
|
|
18
|
-
ensureRunRecord,
|
|
19
|
-
completeRunRecord,
|
|
20
|
-
getWorkItemForTask,
|
|
21
|
-
recordFact,
|
|
22
|
-
runIdFor,
|
|
23
|
-
updateWorkItemDelivery,
|
|
24
|
-
claimTaskRun,
|
|
25
|
-
releaseTaskRun,
|
|
26
|
-
reserveTaskOwnership
|
|
27
|
-
} from "./task-store.js";
|
|
28
|
-
import { ACTIVE_STATUSES, TERMINAL_STATUSES } from "./status.js";
|
|
29
|
-
import { worktreesDir } from "./paths.js";
|
|
30
|
-
import { clearStage } from "./stage-store.js";
|
|
31
|
-
import { buildGuardPreamble, frameWorkerPrompt } from "./prompt.js";
|
|
32
|
-
import { cacheRoots, resolveWritableRoot } from "./sandbox-roots.js";
|
|
33
|
-
import { readTaskChanges, snapshotTaskOutput } from "./worktree.js";
|
|
34
|
-
import { rebaseWorktree } from "./landing.js";
|
|
35
|
-
import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, isArtifactOnlyAcceptance, normalizeAcceptance, runAcceptance } from "./acceptance.js";
|
|
36
|
-
import { appendFile } from "node:fs/promises";
|
|
37
|
-
import { findOutsideOwnedChanges } from "./owned-changes.js";
|
|
38
|
-
import { parseWorkerReportForRun, workerReportSchemaPath } from "./worker-report.js";
|
|
39
|
-
import { buildHandoff } from "./handoff.js";
|
|
40
|
-
import { readNativeGoalState } from "./goal-store.js";
|
|
41
|
-
import { compileWorkerContext } from "./context-compiler.js";
|
|
42
|
-
import { captureExternalOutputs, compareExternalOutputs } from "./external-output.js";
|
|
43
|
-
import { buildRuntimeContract, createPreflightMetadata, readPreflightResult, runtimeContractHash } from "./worker-preflight.js";
|
|
44
|
-
import { supervisorMcpDisableArgs } from "./mcp-config.js";
|
|
45
|
-
import { captureWorkspaceManifest, isGitCheckout, prepareWorkspace } from "./workspace-kind.js";
|
|
46
|
-
import { codexRunner } from "./runner-adapter.js";
|
|
47
|
-
import { withWorkerToolPath } from "./worker-env.js";
|
|
48
|
-
|
|
49
|
-
const processes = new Map();
|
|
50
|
-
// taskId -> control object of an acceptance run in progress ({ kill, cancelled }).
|
|
51
|
-
const acceptanceRuns = new Map();
|
|
52
|
-
const cancelledTasks = new Set();
|
|
53
|
-
const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
54
|
-
const allowedReasoningEfforts = new Set(["minimal", "low", "medium", "high"]);
|
|
55
|
-
const MAX_RUN_HOST_PROMPT_BYTES = 4 * 1024 * 1024;
|
|
56
|
-
const RUN_HOST_STARTUP_TIMEOUT_MS = process.platform === "win32" ? 120000 : 30000;
|
|
57
|
-
const WORKTREE_LOCK_TIMEOUT_MS = 120000;
|
|
58
|
-
|
|
59
|
-
async function recordOutcomeFacts({ task, runId, report, reportEventId = null, acceptanceEventId = null, acceptancePassed = false }) {
|
|
60
|
-
if (!report?.valid) return;
|
|
61
|
-
const workItem = await getWorkItemForTask(task.id);
|
|
62
|
-
if (!workItem) return;
|
|
63
|
-
const validForManifestHash = task.run_evidence?.workspace?.after_manifest?.sha256 ?? null;
|
|
64
|
-
const candidate = await recordFact({
|
|
65
|
-
workItemId: workItem.id,
|
|
66
|
-
scopeType: "run",
|
|
67
|
-
scopeId: runId,
|
|
68
|
-
key: "worker_outcome",
|
|
69
|
-
value: report.report,
|
|
70
|
-
state: "candidate",
|
|
71
|
-
sourceEventId: reportEventId,
|
|
72
|
-
validForSha: task.base_commit ?? null,
|
|
73
|
-
validForContentHash: task.input_context?.content_hash ?? null,
|
|
74
|
-
validForManifestHash,
|
|
75
|
-
watchedPaths: task.owned_paths ?? []
|
|
76
|
-
});
|
|
77
|
-
if (!acceptancePassed || report.format === "text") return;
|
|
78
|
-
await recordFact({
|
|
79
|
-
workItemId: workItem.id,
|
|
80
|
-
scopeType: "work_item",
|
|
81
|
-
scopeId: workItem.id,
|
|
82
|
-
key: "accepted_outcome",
|
|
83
|
-
value: report.report,
|
|
84
|
-
state: "verified",
|
|
85
|
-
sourceEventId: acceptanceEventId,
|
|
86
|
-
validForSha: task.base_commit ?? null,
|
|
87
|
-
validForContentHash: task.input_context?.content_hash ?? null,
|
|
88
|
-
validForManifestHash,
|
|
89
|
-
watchedPaths: task.owned_paths ?? [],
|
|
90
|
-
supersedesId: candidate.id,
|
|
91
|
-
verifiedBy: "supervisor.acceptance"
|
|
92
|
-
});
|
|
93
|
-
await updateWorkItemDelivery(task.id, "verified");
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
function splitLines(buffer, chunk) {
|
|
97
|
-
const next = buffer + chunk;
|
|
98
|
-
const lines = next.split(/\r?\n/);
|
|
99
|
-
return { lines: lines.slice(0, -1), rest: lines.at(-1) ?? "" };
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
async function exists(path) {
|
|
103
|
-
if (!path) return false;
|
|
104
|
-
try {
|
|
105
|
-
await stat(path);
|
|
106
|
-
return true;
|
|
107
|
-
} catch {
|
|
108
|
-
return false;
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
function runCommand(command, args, options = {}) {
|
|
113
|
-
return new Promise((resolvePromise, reject) => {
|
|
114
|
-
const child = spawn(command, args, { stdio: "ignore", windowsHide: true, ...options });
|
|
115
|
-
child.on("exit", (code) => {
|
|
116
|
-
if (code === 0) resolvePromise();
|
|
117
|
-
else reject(new Error(`${command} ${args.join(" ")} exited with ${code}`));
|
|
118
|
-
});
|
|
119
|
-
child.on("error", reject);
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
function resolveCommit(cwd, ref) {
|
|
124
|
-
return execFileSync(defaultGitBin, ["-C", cwd, "rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
|
|
125
|
-
encoding: "utf8",
|
|
126
|
-
timeout: 15000,
|
|
127
|
-
stdio: ["ignore", "pipe", "ignore"]
|
|
128
|
-
}).trim();
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
function invalidBaseRefError(cwd, baseRef) {
|
|
132
|
-
const error = new Error(`baseRef "${baseRef}" does not resolve to a commit in ${cwd}`);
|
|
133
|
-
error.code = "invalid_base_ref";
|
|
134
|
-
return error;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// The worktree is cut from baseRef when given, else from the repository's
|
|
138
|
-
// HEAD. The resolved commit is recorded on the task: it is what
|
|
139
|
-
// readWorktreeChanges diffs against, so committed work stays visible. An
|
|
140
|
-
// explicit baseRef that does not resolve is an error, not a silent fallback
|
|
141
|
-
// to HEAD - the caller asked for a specific baseline for a reason.
|
|
142
|
-
async function ensureWorktree(cwd, taskId, baseRef = null) {
|
|
143
|
-
const taskWorktreeDir = join(worktreesDir, taskId);
|
|
144
|
-
await mkdir(worktreesDir, { recursive: true });
|
|
145
|
-
const gitDir = join(cwd, ".git");
|
|
146
|
-
if (!(await exists(cwd)) || !(await exists(gitDir))) {
|
|
147
|
-
if (baseRef) throw invalidBaseRefError(cwd, baseRef);
|
|
148
|
-
return { path: null, baseCommit: null };
|
|
149
|
-
}
|
|
150
|
-
let baseCommit;
|
|
151
|
-
try {
|
|
152
|
-
baseCommit = resolveCommit(cwd, baseRef ?? "HEAD");
|
|
153
|
-
} catch {
|
|
154
|
-
if (baseRef) throw invalidBaseRefError(cwd, baseRef);
|
|
155
|
-
return { path: null, baseCommit: null };
|
|
156
|
-
}
|
|
157
|
-
if (!baseCommit) {
|
|
158
|
-
if (baseRef) throw invalidBaseRefError(cwd, baseRef);
|
|
159
|
-
return { path: null, baseCommit: null };
|
|
160
|
-
}
|
|
161
|
-
try {
|
|
162
|
-
await rm(taskWorktreeDir, { recursive: true, force: true });
|
|
163
|
-
const branch = `codex/${taskId}`;
|
|
164
|
-
await runCommand(defaultGitBin, ["-C", cwd, "worktree", "add", "--detach", taskWorktreeDir, baseCommit]);
|
|
165
|
-
await runCommand(defaultGitBin, ["-C", taskWorktreeDir, "switch", "-c", branch]);
|
|
166
|
-
return { path: taskWorktreeDir, baseCommit };
|
|
167
|
-
} catch (error) {
|
|
168
|
-
const failure = new Error(`could not create isolated worker checkout: ${error.message}`);
|
|
169
|
-
failure.code = "worktree_creation_failed";
|
|
170
|
-
throw failure;
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
function insidePath(parent, child) {
|
|
175
|
-
const rel = relative(parent, child);
|
|
176
|
-
return rel === "" || (!rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel));
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
function normalizeWorkspaceSetup(value, projectRoot) {
|
|
180
|
-
if (value == null) return null;
|
|
181
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("workspaceSetup must be an object");
|
|
182
|
-
const links = (value.links ?? []).map((entry) => {
|
|
183
|
-
if (!entry || typeof entry.path !== "string" || !entry.path.trim()
|
|
184
|
-
|| typeof entry.source !== "string" || !entry.source.trim()) throw new Error("workspaceSetup.links requires path and source");
|
|
185
|
-
const path = entry.path.trim();
|
|
186
|
-
if (isAbsolute(path) || path.split(/[\\/]/).includes("..")) throw new Error(`workspaceSetup link path must stay inside the worktree: ${path}`);
|
|
187
|
-
return { path, source: resolve(projectRoot, entry.source.trim()) };
|
|
188
|
-
});
|
|
189
|
-
const commands = (value.commands ?? []).map((command) => String(command).trim()).filter(Boolean);
|
|
190
|
-
if (links.length > 20 || commands.length > 20) throw new Error("workspaceSetup accepts at most 20 links and 20 commands");
|
|
191
|
-
const submodules = value.submodules === true;
|
|
192
|
-
return links.length || submodules || commands.length ? { links, submodules, commands } : null;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
const JS_DEPENDENCY_COMMAND = /(?:^|[\s"'/])(?:npm|pnpm|yarn|npx|vitest|jest|vue-tsc|tsc|eslint|oxlint|nuxi)(?:\s|$)/;
|
|
196
|
-
|
|
197
|
-
function requireDependencySetup({ kind, projectRoot, setup, commands }) {
|
|
198
|
-
if (kind !== "git_worktree" || setup || !existsSync(join(projectRoot, "package.json"))) return;
|
|
199
|
-
const commandText = (commands ?? []).map((check) => typeof check === "string" ? check : check?.command).filter(Boolean).join("\n");
|
|
200
|
-
if (!JS_DEPENDENCY_COMMAND.test(commandText)) return;
|
|
201
|
-
const error = new Error("workspace_setup_required: this JavaScript acceptance uses local project tooling, but the new worktree has no node_modules or generated prepare files; pass workspaceSetup with dependency links and prepare commands (the same setup must be used by preflight)");
|
|
202
|
-
error.code = "workspace_setup_required";
|
|
203
|
-
throw error;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
async function prepareWorktreeWorkspace(setup, projectRoot, worktreePath, taskId) {
|
|
207
|
-
if (!setup) return;
|
|
208
|
-
for (const link of setup.links) {
|
|
209
|
-
if (!existsSync(link.source)) throw new Error(`workspaceSetup link source does not exist: ${link.source}`);
|
|
210
|
-
const destination = resolve(worktreePath, link.path);
|
|
211
|
-
if (!insidePath(worktreePath, destination)) throw new Error(`workspaceSetup link escapes the worktree: ${link.path}`);
|
|
212
|
-
await mkdir(dirname(destination), { recursive: true });
|
|
213
|
-
if (existsSync(destination)) {
|
|
214
|
-
const existing = await lstat(destination);
|
|
215
|
-
if (!existing.isSymbolicLink()) throw new Error(`workspaceSetup link destination already exists: ${link.path}`);
|
|
216
|
-
const [actual, expected] = await Promise.all([realpath(destination), realpath(link.source)]);
|
|
217
|
-
if (actual !== expected) throw new Error(`workspaceSetup link destination points elsewhere: ${link.path}`);
|
|
218
|
-
continue;
|
|
219
|
-
}
|
|
220
|
-
const sourceInfo = await stat(link.source);
|
|
221
|
-
await symlink(link.source, destination, process.platform === "win32" ? "junction" : sourceInfo.isDirectory() ? "dir" : "file");
|
|
222
|
-
if (basename(link.path) === "node_modules" && sourceInfo.isDirectory()) {
|
|
223
|
-
for (const name of [".vite", ".vite-temp", ".cache"]) await mkdir(join(link.source, name), { recursive: true });
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
if (setup.submodules) {
|
|
227
|
-
await runCommand(defaultGitBin, ["-c", "protocol.file.allow=always", "-C", worktreePath, "submodule", "update", "--init", "--recursive"]);
|
|
228
|
-
}
|
|
229
|
-
if (setup.commands.length) {
|
|
230
|
-
const result = await runAcceptance(setup.commands, { cwd: worktreePath, taskId, timeoutMs: DEFAULT_ACCEPTANCE_TIMEOUT_MS });
|
|
231
|
-
if (!result.passed) {
|
|
232
|
-
const failing = result.checks.find((check) => !check.passed);
|
|
233
|
-
throw new Error(`workspaceSetup command failed: ${failing?.command ?? "unknown"}${failing?.output_tail ? `\n${failing.output_tail}` : ""}`);
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
function workspaceSetupWriteRoots(record) {
|
|
239
|
-
const roots = [];
|
|
240
|
-
for (const link of record.workspace_metadata?.setup?.links ?? []) {
|
|
241
|
-
const source = resolveWritableRoot(link.source);
|
|
242
|
-
if (!source.error) roots.push(source.path);
|
|
243
|
-
if (basename(link.path) !== "node_modules") continue;
|
|
244
|
-
for (const name of [".vite", ".vite-temp", ".cache"]) {
|
|
245
|
-
const candidate = resolveWritableRoot(join(link.source, name));
|
|
246
|
-
if (!candidate.error) roots.push(candidate.path);
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
return roots;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
function sleep(ms) {
|
|
253
|
-
return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
async function withWorktreeCreationLock(cwd, work) {
|
|
257
|
-
const lockName = `create-${createHash("sha256").update(resolve(cwd)).digest("hex").slice(0, 24)}.lock`;
|
|
258
|
-
const lockPath = join(worktreesDir, lockName);
|
|
259
|
-
await mkdir(worktreesDir, { recursive: true });
|
|
260
|
-
const deadline = Date.now() + WORKTREE_LOCK_TIMEOUT_MS;
|
|
261
|
-
while (true) {
|
|
262
|
-
try {
|
|
263
|
-
await mkdir(lockPath);
|
|
264
|
-
break;
|
|
265
|
-
} catch (error) {
|
|
266
|
-
if (error.code !== "EEXIST" || Date.now() >= deadline) throw new Error(`worktree creation lock timed out for ${cwd}`);
|
|
267
|
-
await sleep(100);
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
try {
|
|
271
|
-
return await work();
|
|
272
|
-
} finally {
|
|
273
|
-
await rm(lockPath, { recursive: true, force: true }).catch(() => {});
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
function normalizeOwnedPaths(ownedPaths, projectRoot) {
|
|
278
|
-
if (!Array.isArray(ownedPaths)) return [];
|
|
279
|
-
return Array.from(new Set(ownedPaths.map((entry) => resolve(projectRoot, String(entry).trim()))));
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
function pathOverlaps(left, right) {
|
|
283
|
-
// Windows paths are case-insensitive and may mix separators, so compare on a
|
|
284
|
-
// normalized form there. macOS and Linux keep the exact previous comparison -
|
|
285
|
-
// a backslash is a legal filename character on those platforms.
|
|
286
|
-
const windows = process.platform === "win32";
|
|
287
|
-
const normalize = (value) => (windows ? value.replace(/[\\/]+/g, sep).toLowerCase() : value);
|
|
288
|
-
const mine = normalize(left);
|
|
289
|
-
const theirs = normalize(right);
|
|
290
|
-
if (mine === theirs) return true;
|
|
291
|
-
const minePrefix = mine.endsWith(sep) ? mine : `${mine}${sep}`;
|
|
292
|
-
const theirsPrefix = theirs.endsWith(sep) ? theirs : `${theirs}${sep}`;
|
|
293
|
-
return minePrefix.startsWith(theirsPrefix) || theirsPrefix.startsWith(minePrefix);
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
// Two workers claiming overlapping paths will collide when their branches are
|
|
297
|
-
// merged, so the second dispatch is refused before any worktree is created.
|
|
298
|
-
export async function findOwnershipConflicts(ownedPaths, { excludeTaskId = null } = {}) {
|
|
299
|
-
if (!ownedPaths || ownedPaths.length === 0) return [];
|
|
300
|
-
const activeTasks = await readActiveTasks();
|
|
301
|
-
const conflicts = [];
|
|
302
|
-
for (const task of activeTasks) {
|
|
303
|
-
if (task.id === excludeTaskId) continue;
|
|
304
|
-
const theirs = Array.isArray(task.owned_paths) ? task.owned_paths : [];
|
|
305
|
-
const overlap = [];
|
|
306
|
-
for (const mine of ownedPaths) {
|
|
307
|
-
for (const other of theirs) {
|
|
308
|
-
if (pathOverlaps(mine, other)) overlap.push({ incoming: mine, existing: other });
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
if (overlap.length > 0) {
|
|
312
|
-
conflicts.push({
|
|
313
|
-
task_id: task.id,
|
|
314
|
-
title: task.title,
|
|
315
|
-
status: task.status,
|
|
316
|
-
overlapping_paths: overlap
|
|
317
|
-
});
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
return conflicts;
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
function ownershipConflictError(conflicts) {
|
|
324
|
-
const owners = conflicts.map((conflict) => conflict.task_id).join(", ");
|
|
325
|
-
const error = new Error(`ownedPaths overlap with active worker(s): ${owners}`);
|
|
326
|
-
error.code = "ownership_conflict";
|
|
327
|
-
error.conflicts = conflicts;
|
|
328
|
-
return error;
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
function failedStart(record, reason) {
|
|
332
|
-
const now = new Date().toISOString();
|
|
333
|
-
return {
|
|
334
|
-
ok: false,
|
|
335
|
-
record: {
|
|
336
|
-
...record,
|
|
337
|
-
status: "failed",
|
|
338
|
-
phase: null,
|
|
339
|
-
pid: null,
|
|
340
|
-
error: reason,
|
|
341
|
-
attention_reason: "start_failed",
|
|
342
|
-
completed_at: now,
|
|
343
|
-
updated_at: now
|
|
344
|
-
}
|
|
345
|
-
};
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
// Spawn can fail either by throwing synchronously, or by emitting "error"
|
|
349
|
-
// instead of "spawn". Both paths are handled so a bad CODEX_BIN marks the task
|
|
350
|
-
// failed instead of taking the whole MCP process down.
|
|
351
|
-
async function spawnAndAwaitStart(target, args, options) {
|
|
352
|
-
const child = spawn(target.cmd, [...target.prefixArgs, ...args], options);
|
|
353
|
-
const earlyOutput = { stdout: [], stderr: [], capture: true };
|
|
354
|
-
child.stdout?.on("data", (chunk) => { if (earlyOutput.capture) earlyOutput.stdout.push(chunk); });
|
|
355
|
-
child.stderr?.on("data", (chunk) => { if (earlyOutput.capture) earlyOutput.stderr.push(chunk); });
|
|
356
|
-
const spawnError = await new Promise((resolvePromise) => {
|
|
357
|
-
let settled = false;
|
|
358
|
-
child.once("spawn", () => {
|
|
359
|
-
if (!settled) {
|
|
360
|
-
settled = true;
|
|
361
|
-
resolvePromise(null);
|
|
362
|
-
}
|
|
363
|
-
});
|
|
364
|
-
child.once("error", (error) => {
|
|
365
|
-
if (!settled) {
|
|
366
|
-
settled = true;
|
|
367
|
-
resolvePromise(error);
|
|
368
|
-
}
|
|
369
|
-
});
|
|
370
|
-
});
|
|
371
|
-
return { child, spawnError, earlyOutput };
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
// Attaches stream handlers and keeps `record` in the supervisor database.
|
|
375
|
-
// Every write goes through one serialized chain so concurrent stdout/stderr
|
|
376
|
-
// callbacks cannot interleave and persist out of order.
|
|
377
|
-
async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}, outputSchema = true }) {
|
|
378
|
-
const capability = codexRunner.capabilityPreflight();
|
|
379
|
-
if (!capability.ok) return failedStart(record, capability.error);
|
|
380
|
-
const target = capability.target;
|
|
381
|
-
const outputBefore = snapshotTaskOutput(record);
|
|
382
|
-
const workspaceBefore = record.workspace_metadata?.before_manifest ?? null;
|
|
383
|
-
const externalBefore = await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [], { checkBaseline: (record.run_count ?? 0) === 0 });
|
|
384
|
-
const owned = [...findOutsideOwnedChanges(record, []).mapping.map((entry) => entry.worker), ...externalBefore.map((entry) => entry.path)];
|
|
385
|
-
const guardPolicy = { cwd: record.cwd, worktree: record.cwd, sandbox: record.sandbox, ownedPaths: owned, ...(record.guard_policy ?? {}),
|
|
386
|
-
output_schema: outputSchema,
|
|
387
|
-
goalTokenBudget: record.goal_token_budget ?? null,
|
|
388
|
-
allowedCommands: [
|
|
389
|
-
...(record.guard_policy?.allowedCommands ?? []),
|
|
390
|
-
...(record.acceptance ?? []).map((check) => typeof check === "string" ? check : check.command),
|
|
391
|
-
// This CLI writes only data/stages/<this task>.json. It is part of the
|
|
392
|
-
// runtime contract, not an ad-hoc command the model must declare. The
|
|
393
|
-
// task id comes from the injected environment; stage.js has no override.
|
|
394
|
-
'node "$CODEX_SUPERVISOR_STAGE_CLI"*',
|
|
395
|
-
'node "$CODEX_SUPERVISOR_ACCEPTANCE_CLI"*'
|
|
396
|
-
] };
|
|
397
|
-
const guard = fileURLToPath(new URL("./tool-guard.js", import.meta.url));
|
|
398
|
-
const stageCli = fileURLToPath(new URL("./stage.js", import.meta.url));
|
|
399
|
-
const acceptanceCli = fileURLToPath(new URL("./acceptance-cli.js", import.meta.url));
|
|
400
|
-
const quoteCommand = (path) => process.platform === "win32" ? `"${path.replace(/"/g, '""')}"` : `'${path.replace(/'/g, "'\\''")}'`;
|
|
401
|
-
const hookCommand = `${quoteCommand(process.execPath)} ${quoteCommand(guard)}`;
|
|
402
|
-
const configArgs = [...(outputSchema ? ["--output-schema", workerReportSchemaPath] : []), "--dangerously-bypass-hook-trust", "-c",
|
|
403
|
-
`hooks.PreToolUse=[{matcher="Bash|apply_patch|create_goal",hooks=[{type="command",command=${JSON.stringify(hookCommand)}}]}]`];
|
|
404
|
-
// A worker may use its explicitly configured business MCP servers, but it
|
|
405
|
-
// must not inherit this supervisor and create a second orchestration tree.
|
|
406
|
-
configArgs.push(...supervisorMcpDisableArgs());
|
|
407
|
-
configArgs.push("-c", `sandbox_workspace_write.network_access=${record.guard_policy?.networkAccess === true}`);
|
|
408
|
-
const sandboxWritableRoots = [...new Set([
|
|
409
|
-
...externalBefore.map((file) => dirname(file.path)),
|
|
410
|
-
...cacheRoots(),
|
|
411
|
-
...workspaceSetupWriteRoots(record),
|
|
412
|
-
...(record.guard_policy?.writableRoots ?? [])
|
|
413
|
-
])];
|
|
414
|
-
if (sandboxWritableRoots.length) configArgs.push("-c", `sandbox_workspace_write.writable_roots=${JSON.stringify(sandboxWritableRoots)}`);
|
|
415
|
-
// Insert before the prompt/session positional arguments for exec/resume.
|
|
416
|
-
const guardedArgs = [...args.slice(0, -1), ...configArgs, args.at(-1)];
|
|
417
|
-
prompt = `${buildGuardPreamble(guardPolicy)}\n\n${prompt}`;
|
|
418
|
-
|
|
419
|
-
clearStage(record.id);
|
|
420
|
-
|
|
421
|
-
const { child, spawnError, earlyOutput } = await spawnAndAwaitStart(target, guardedArgs, {
|
|
422
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
423
|
-
env: withWorkerToolPath({ ...process.env, NO_COLOR: "1", CODEX_SUPERVISOR_TASK_ID: record.id,
|
|
424
|
-
CODEX_SUPERVISOR_BASE_COMMIT: record.base_commit ?? "",
|
|
425
|
-
CODEX_SUPERVISOR_STAGE_CLI: stageCli,
|
|
426
|
-
CODEX_SUPERVISOR_ACCEPTANCE_CLI: acceptanceCli,
|
|
427
|
-
CODEX_SUPERVISOR_RUN: String((record.run_count ?? 0) + 1), CODEX_SUPERVISOR_GUARD_POLICY: JSON.stringify(guardPolicy) }),
|
|
428
|
-
windowsHide: true,
|
|
429
|
-
...spawnOptions
|
|
430
|
-
});
|
|
431
|
-
|
|
432
|
-
if (spawnError) {
|
|
433
|
-
return failedStart(record, `failed to spawn ${target.cmd}: ${spawnError.message}`);
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
const now = new Date().toISOString();
|
|
437
|
-
// A new run starts clean. A resumed worker used to carry the error from
|
|
438
|
-
// the run that was lost, so a worker that was plainly running still showed
|
|
439
|
-
// "process disappeared" until it finished.
|
|
440
|
-
const priorAttemptFingerprint = record.run_evidence?.attempt_fingerprint ?? null;
|
|
441
|
-
const reportOnlyRecovery = record.attention_reason === "invalid_report";
|
|
442
|
-
let live = {
|
|
443
|
-
...record,
|
|
444
|
-
status: "running",
|
|
445
|
-
phase: "starting",
|
|
446
|
-
pid: child.pid ?? null,
|
|
447
|
-
run_host_pid: process.pid,
|
|
448
|
-
started_at: now,
|
|
449
|
-
completed_at: null,
|
|
450
|
-
exit_code: null,
|
|
451
|
-
signal: null,
|
|
452
|
-
error: null,
|
|
453
|
-
cancel_requested_at: null,
|
|
454
|
-
acceptance_results: null,
|
|
455
|
-
attention_reason: null,
|
|
456
|
-
run_evidence: null,
|
|
457
|
-
guard_policy: { ...record.guard_policy, output_schema: outputSchema },
|
|
458
|
-
commands: [],
|
|
459
|
-
last_message: null,
|
|
460
|
-
current_action: null,
|
|
461
|
-
current_command: null,
|
|
462
|
-
// A resumed row still carries the last event of the run that ended;
|
|
463
|
-
// idle time for this run counts from now.
|
|
464
|
-
last_event_at: now,
|
|
465
|
-
last_event_type: null,
|
|
466
|
-
run_count: (record.run_count ?? 0) + 1,
|
|
467
|
-
updated_at: now
|
|
468
|
-
};
|
|
469
|
-
processes.set(record.id, child);
|
|
470
|
-
let quotaReason = null;
|
|
471
|
-
const maxRunMs = record.guard_policy?.maxRunMs;
|
|
472
|
-
const maxTotalMs = record.guard_policy?.maxTotalMs;
|
|
473
|
-
const quotaWatch = maxRunMs || maxTotalMs ? setInterval(() => {
|
|
474
|
-
if (quotaReason) return;
|
|
475
|
-
if (maxRunMs && Date.now() - Date.parse(now) >= maxRunMs) quotaReason = "run_time_limit";
|
|
476
|
-
else if (maxTotalMs && Date.now() - Date.parse(record.created_at) >= maxTotalMs) quotaReason = "total_time_limit";
|
|
477
|
-
if (quotaReason) terminateChild(child);
|
|
478
|
-
}, 250) : null;
|
|
479
|
-
|
|
480
|
-
let writeChain = Promise.resolve();
|
|
481
|
-
const writeSnapshot = (next) => {
|
|
482
|
-
live = next;
|
|
483
|
-
const snapshot = live;
|
|
484
|
-
const pending = writeChain.then(() => upsertTask(snapshot));
|
|
485
|
-
// Keep later writes usable after one failed snapshot. Callers that need
|
|
486
|
-
// failure visibility use the returned promise explicitly.
|
|
487
|
-
writeChain = pending.catch(() => {});
|
|
488
|
-
return pending;
|
|
489
|
-
};
|
|
490
|
-
const persist = async (next, label = "persist") => {
|
|
491
|
-
try { await writeSnapshot(next); }
|
|
492
|
-
catch (error) {
|
|
493
|
-
await appendTaskEvent(next.id, { type: "supervisor.persist_failed", label, error: error.message, run: next.run_count },
|
|
494
|
-
{ runId: runIdFor(next.id, next.run_count), actor: "supervisor" }).catch(() => null);
|
|
495
|
-
process.stderr.write(`[codex-supervisor] ${label} failed for ${next.id}: ${error.message}\n`);
|
|
496
|
-
}
|
|
497
|
-
};
|
|
498
|
-
await persist(live);
|
|
499
|
-
const runId = await ensureRunRecord(live, live.run_count);
|
|
500
|
-
|
|
501
|
-
const logStream = createWriteStream(logPath, { flags: "a" });
|
|
502
|
-
logStream.on("error", () => {});
|
|
503
|
-
|
|
504
|
-
// A child that exits early makes this write fail with EPIPE. That must not
|
|
505
|
-
// reach the process level, or one oversized prompt kills the MCP server.
|
|
506
|
-
child.stdin.on("error", (error) => {
|
|
507
|
-
persist({
|
|
508
|
-
...live,
|
|
509
|
-
error: live.error ?? `stdin write failed: ${error.message}`,
|
|
510
|
-
updated_at: new Date().toISOString()
|
|
511
|
-
});
|
|
512
|
-
});
|
|
513
|
-
|
|
514
|
-
let eventChain = Promise.resolve();
|
|
515
|
-
let terminalEvent = false;
|
|
516
|
-
let rawReport = null;
|
|
517
|
-
let rawReportEventId = null;
|
|
518
|
-
const projectOutcomeFacts = async (finalRecord, { acceptanceEventId = null, acceptancePassed = false } = {}) => {
|
|
519
|
-
try {
|
|
520
|
-
await recordOutcomeFacts({
|
|
521
|
-
task: finalRecord,
|
|
522
|
-
runId,
|
|
523
|
-
report: finalRecord.run_evidence?.structured_report,
|
|
524
|
-
reportEventId: rawReportEventId,
|
|
525
|
-
acceptanceEventId,
|
|
526
|
-
acceptancePassed
|
|
527
|
-
});
|
|
528
|
-
} catch (error) {
|
|
529
|
-
await appendTaskEvent(finalRecord.id, { type: "supervisor.fact_record_failed", error: error.message, run: live.run_count },
|
|
530
|
-
{ runId, actor: "supervisor" }).catch(() => null);
|
|
531
|
-
process.stderr.write(`[codex-supervisor] fact projection failed for ${finalRecord.id}: ${error.message}\n`);
|
|
532
|
-
}
|
|
533
|
-
};
|
|
534
|
-
const handleLines = async (lines) => {
|
|
535
|
-
const events = [];
|
|
536
|
-
for (const line of lines) {
|
|
537
|
-
try {
|
|
538
|
-
const event = JSON.parse(line);
|
|
539
|
-
logStream.write(`${JSON.stringify(event)}\n`);
|
|
540
|
-
events.push(event);
|
|
541
|
-
} catch (error) {
|
|
542
|
-
logStream.write(`${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
if (events.length === 0) return;
|
|
546
|
-
const storedEvents = await appendTaskEvents(record.id, events, { runId, actor: "codex" });
|
|
547
|
-
let next = live;
|
|
548
|
-
for (const [index, event] of events.entries()) {
|
|
549
|
-
if (event.type === "item.completed" && event.item?.type === "agent_message") {
|
|
550
|
-
rawReport = event.item.text;
|
|
551
|
-
rawReportEventId = storedEvents[index].id;
|
|
552
|
-
}
|
|
553
|
-
if (["turn.completed", "turn.failed"].includes(event.type)) terminalEvent = true;
|
|
554
|
-
next = codexRunner.parseEvent(next, event);
|
|
555
|
-
}
|
|
556
|
-
await persist(next);
|
|
557
|
-
};
|
|
558
|
-
|
|
559
|
-
let stdoutRest = "";
|
|
560
|
-
let pendingLines = [];
|
|
561
|
-
let eventFlushPending = false;
|
|
562
|
-
const queueEventLines = (lines) => {
|
|
563
|
-
pendingLines.push(...lines);
|
|
564
|
-
if (eventFlushPending) return;
|
|
565
|
-
eventFlushPending = true;
|
|
566
|
-
eventChain = eventChain.then(async () => {
|
|
567
|
-
await new Promise((resolveFlush) => setImmediate(resolveFlush));
|
|
568
|
-
const batch = pendingLines;
|
|
569
|
-
pendingLines = [];
|
|
570
|
-
eventFlushPending = false;
|
|
571
|
-
await handleLines(batch);
|
|
572
|
-
}).catch((error) => {
|
|
573
|
-
process.stderr.write(`[codex-supervisor] event handling failed for ${record.id}: ${error.message}\n`);
|
|
574
|
-
});
|
|
575
|
-
};
|
|
576
|
-
const handleStdoutChunk = (chunk) => {
|
|
577
|
-
const split = splitLines(stdoutRest, chunk.toString("utf8"));
|
|
578
|
-
stdoutRest = split.rest;
|
|
579
|
-
const lines = split.lines.filter((line) => line.trim());
|
|
580
|
-
if (lines.length) queueEventLines(lines);
|
|
581
|
-
};
|
|
582
|
-
earlyOutput.capture = false;
|
|
583
|
-
for (const chunk of earlyOutput.stdout) handleStdoutChunk(chunk);
|
|
584
|
-
child.stdout.on("data", handleStdoutChunk);
|
|
585
|
-
child.stdout.on("error", () => {});
|
|
586
|
-
|
|
587
|
-
let stderr = earlyOutput.stderr.map((chunk) => chunk.toString("utf8")).join("");
|
|
588
|
-
child.stderr.on("data", (chunk) => {
|
|
589
|
-
stderr += chunk.toString("utf8");
|
|
590
|
-
persist({ ...live, stderr_tail: stderr.slice(-4000), updated_at: new Date().toISOString() });
|
|
591
|
-
});
|
|
592
|
-
child.stderr.on("error", () => {});
|
|
593
|
-
|
|
594
|
-
child.on("error", (error) => {
|
|
595
|
-
persist({
|
|
596
|
-
...live,
|
|
597
|
-
error: live.error ?? `codex process error: ${error.message}`,
|
|
598
|
-
updated_at: new Date().toISOString()
|
|
599
|
-
});
|
|
600
|
-
});
|
|
601
|
-
|
|
602
|
-
let settleRun;
|
|
603
|
-
const settled = new Promise((resolveSettled) => { settleRun = resolveSettled; });
|
|
604
|
-
let childSettled = false;
|
|
605
|
-
const finalizeChild = async (code, signal) => {
|
|
606
|
-
if (childSettled) return;
|
|
607
|
-
childSettled = true;
|
|
608
|
-
if (quotaWatch) clearInterval(quotaWatch);
|
|
609
|
-
processes.delete(record.id);
|
|
610
|
-
if (stdoutRest.trim()) queueEventLines([stdoutRest]);
|
|
611
|
-
await eventChain.catch(() => {});
|
|
612
|
-
logStream.end();
|
|
613
|
-
const finishedAt = new Date().toISOString();
|
|
614
|
-
const stored = await getTask(record.id).catch(() => null);
|
|
615
|
-
// A cancel can be issued from another MCP process, so the marker is read
|
|
616
|
-
// back from disk rather than trusted to this process's memory.
|
|
617
|
-
const cancelRequested = cancelledTasks.has(record.id)
|
|
618
|
-
|| Boolean(live.cancel_requested_at)
|
|
619
|
-
|| Boolean(stored?.cancel_requested_at);
|
|
620
|
-
let status;
|
|
621
|
-
if (stored && TERMINAL_STATUSES.has(stored.status) && stored.status !== live.status) status = stored.status;
|
|
622
|
-
else if (terminalEvent && TERMINAL_STATUSES.has(live.status)) status = live.status;
|
|
623
|
-
else if (cancelRequested) status = "cancelled";
|
|
624
|
-
// Killed by a signal nobody asked for: the worker did not fail, it
|
|
625
|
-
// vanished. Re-running is the fix, so it is reported as lost.
|
|
626
|
-
else if (signal) status = "lost";
|
|
627
|
-
else if (code === 0) status = "lost";
|
|
628
|
-
else status = "failed";
|
|
629
|
-
const next = {
|
|
630
|
-
...live,
|
|
631
|
-
status,
|
|
632
|
-
phase: null,
|
|
633
|
-
changed_files: readTaskChanges(live),
|
|
634
|
-
exit_code: code,
|
|
635
|
-
signal,
|
|
636
|
-
current_command: null,
|
|
637
|
-
current_action: status === "completed" ? "Completed" : live.current_action,
|
|
638
|
-
completed_at: live.completed_at ?? finishedAt,
|
|
639
|
-
updated_at: finishedAt
|
|
640
|
-
};
|
|
641
|
-
const stdinEpipe = /^stdin write failed:.*\bEPIPE\b/i.test(next.error ?? "");
|
|
642
|
-
if (status === "failed" && (!next.error || stdinEpipe)) {
|
|
643
|
-
next.error = `codex exited with code ${code}${signal ? ` (signal ${signal})` : ""}`;
|
|
644
|
-
}
|
|
645
|
-
if (status === "lost" && (!next.error || stdinEpipe)) {
|
|
646
|
-
next.error = signal ? `codex worker was killed by signal ${signal} before writing a terminal event` : "Codex worker exited without recording a terminal event";
|
|
647
|
-
}
|
|
648
|
-
if (status === "cancelled") next.error = null;
|
|
649
|
-
if (quotaReason) { next.attention_reason = quotaReason; next.error = `Supervisor time quota exceeded: ${quotaReason}; inspect partial work before changing the budget`; }
|
|
650
|
-
const outputAfter = snapshotTaskOutput(live);
|
|
651
|
-
let externalChanges = [];
|
|
652
|
-
try { externalChanges = compareExternalOutputs(externalBefore, await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [])); }
|
|
653
|
-
catch (error) { next.attention_reason = "external_output_unverified"; next.error = error.message; }
|
|
654
|
-
let workspaceAfter = null;
|
|
655
|
-
if (workspaceBefore && Array.isArray(record.workspace_metadata?.manifest_paths)) {
|
|
656
|
-
try {
|
|
657
|
-
workspaceAfter = await captureWorkspaceManifest(record.workspace_metadata.source_root, record.workspace_metadata.manifest_paths);
|
|
658
|
-
} catch (error) {
|
|
659
|
-
next.attention_reason = "workspace_manifest_unverified";
|
|
660
|
-
next.error = error.message;
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
const structuredReport = parseWorkerReportForRun(rawReport, { outputSchema });
|
|
664
|
-
next.run_evidence = {
|
|
665
|
-
run: live.run_count, commands_run: live.commands.length,
|
|
666
|
-
structured_report: structuredReport,
|
|
667
|
-
output_before: outputBefore, output_after: outputAfter,
|
|
668
|
-
output_changed: outputBefore && outputAfter ? outputBefore !== outputAfter : null,
|
|
669
|
-
workspace: workspaceBefore ? {
|
|
670
|
-
kind: record.workspace_kind,
|
|
671
|
-
before_manifest: workspaceBefore,
|
|
672
|
-
after_manifest: workspaceAfter,
|
|
673
|
-
manifest_changed: workspaceAfter ? workspaceBefore.sha256 !== workspaceAfter.sha256 : null
|
|
674
|
-
} : null
|
|
675
|
-
};
|
|
676
|
-
next.run_evidence.external_outputs = externalChanges;
|
|
677
|
-
if (externalChanges.some((entry) => entry.changed)) next.run_evidence.output_changed = true;
|
|
678
|
-
next.changed_files = [...new Set([...next.changed_files, ...externalChanges.filter((entry) => entry.changed).map((entry) => entry.path)])];
|
|
679
|
-
next.run_evidence.attempt_fingerprint = createHash("sha256").update(JSON.stringify({
|
|
680
|
-
output_changed: next.run_evidence.output_changed,
|
|
681
|
-
commands_run: live.commands.length,
|
|
682
|
-
changed_files: next.changed_files,
|
|
683
|
-
acceptance_configured: Array.isArray(live.acceptance) && live.acceptance.length > 0,
|
|
684
|
-
workspace_manifest_changed: next.run_evidence.workspace?.manifest_changed ?? null
|
|
685
|
-
})).digest("hex");
|
|
686
|
-
if (status === "completed" && code === 0 && live.sandbox !== "read-only"
|
|
687
|
-
&& !next.run_evidence.output_changed && next.run_evidence.output_changed !== null
|
|
688
|
-
&& live.commands.length === 0 && !reportOnlyRecovery) {
|
|
689
|
-
next.attention_reason = priorAttemptFingerprint === next.run_evidence.attempt_fingerprint ? "two_stall" : "no_work";
|
|
690
|
-
if (next.attention_reason === "two_stall") next.current_action = "No progress in two consecutive runs; needs attention";
|
|
691
|
-
}
|
|
692
|
-
if (status === "completed" && !next.run_evidence.structured_report.valid && !live.guard_policy?.preflight) {
|
|
693
|
-
// The report is a summary, not the business result. Keep the completed
|
|
694
|
-
// lifecycle and let acceptance plus the reviewed diff decide whether it
|
|
695
|
-
// can land; a report-only recovery can still repair the summary.
|
|
696
|
-
next.attention_reason = "invalid_report";
|
|
697
|
-
next.error = `Invalid final worker report: ${next.run_evidence.structured_report.error}`;
|
|
698
|
-
next.current_action = "Work completed, but the final report is invalid; acceptance and diff remain authoritative";
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
// Acceptance runs after the worker is gone, in two writes. The first
|
|
702
|
-
// records the terminal status with exit_code still null and the run
|
|
703
|
-
// marked as this process's, so a wait keeps waiting and reconcile
|
|
704
|
-
// (which sees a dead codex pid) leaves the row alone; the second
|
|
705
|
-
// records exit_code and the verdict. changed_files is read before the
|
|
706
|
-
// checks run so build output they leave behind is not counted as the
|
|
707
|
-
// worker's.
|
|
708
|
-
const acceptance = Array.isArray(live.acceptance) && live.acceptance.length > 0 ? live.acceptance : null;
|
|
709
|
-
if (acceptance && (status === "completed" || status === "failed")) {
|
|
710
|
-
const control = { kill: null, cancelled: false, isCancelled: () => control.cancelled };
|
|
711
|
-
acceptanceRuns.set(record.id, control);
|
|
712
|
-
await persist({
|
|
713
|
-
...next,
|
|
714
|
-
exit_code: null,
|
|
715
|
-
signal: null,
|
|
716
|
-
current_action: "Running acceptance",
|
|
717
|
-
acceptance_results: { status: "running", passed: null, run: live.run_count, supervisor_pid: process.pid, started_at: finishedAt }
|
|
718
|
-
});
|
|
719
|
-
// A fresh MCP has no in-memory acceptance handle. Consume its durable
|
|
720
|
-
// cancellation marker while a command runs, then stop subsequent checks.
|
|
721
|
-
const cancellationWatch = setInterval(async () => {
|
|
722
|
-
const current = await getTask(record.id).catch(() => null);
|
|
723
|
-
if (current?.cancel_requested_at) {
|
|
724
|
-
control.cancelled = true;
|
|
725
|
-
control.kill?.();
|
|
726
|
-
}
|
|
727
|
-
}, 100);
|
|
728
|
-
let results;
|
|
729
|
-
try { results = await runAcceptance(acceptance, {
|
|
730
|
-
cwd: record.cwd,
|
|
731
|
-
timeoutMs: live.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS,
|
|
732
|
-
run: live.run_count,
|
|
733
|
-
taskId: record.id,
|
|
734
|
-
baseCommit: live.base_commit,
|
|
735
|
-
control
|
|
736
|
-
}); } finally { clearInterval(cancellationWatch); }
|
|
737
|
-
acceptanceRuns.delete(record.id);
|
|
738
|
-
const event = { type: "supervisor.acceptance", ...results };
|
|
739
|
-
const acceptanceEvent = await appendTaskEvent(record.id, event, { runId, actor: "supervisor" }).catch(() => null);
|
|
740
|
-
await appendFile(logPath, `${JSON.stringify(event)}\n`).catch(() => {});
|
|
741
|
-
const failing = results.checks.find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out);
|
|
742
|
-
const finalRecord = {
|
|
743
|
-
...next,
|
|
744
|
-
acceptance_results: results,
|
|
745
|
-
current_action: results.status === "passed"
|
|
746
|
-
? "Completed, acceptance passed"
|
|
747
|
-
: results.status === "failed"
|
|
748
|
-
? `Acceptance failed: ${failing ? `${failing.command.slice(0, 80)} exit ${failing.error ?? (failing.baseline?.passed === false ? "baseline/evidence mismatch" : failing.timed_out ? "timeout" : failing.exit_code ?? "?")}` : results.error ?? "see acceptance_results"}`
|
|
749
|
-
: next.current_action,
|
|
750
|
-
updated_at: new Date().toISOString()
|
|
751
|
-
};
|
|
752
|
-
// The terminal lifecycle and exit code are primary evidence. Persist
|
|
753
|
-
// them before fact projection, which is secondary and may fail on a
|
|
754
|
-
// stale control record without turning completed work into lost work.
|
|
755
|
-
await persist(finalRecord, "final persist");
|
|
756
|
-
await projectOutcomeFacts(finalRecord, {
|
|
757
|
-
acceptanceEventId: acceptanceEvent?.id ?? null,
|
|
758
|
-
acceptancePassed: results.passed === true
|
|
759
|
-
});
|
|
760
|
-
if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
|
|
761
|
-
await completeRunRecord(finalRecord, live.run_count);
|
|
762
|
-
} else {
|
|
763
|
-
const finalRecord = acceptance ? { ...next, acceptance_results: null } : next;
|
|
764
|
-
await persist(finalRecord, "final persist");
|
|
765
|
-
await projectOutcomeFacts(finalRecord);
|
|
766
|
-
if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
|
|
767
|
-
await completeRunRecord(finalRecord, live.run_count);
|
|
768
|
-
}
|
|
769
|
-
cancelledTasks.delete(record.id);
|
|
770
|
-
};
|
|
771
|
-
child.once("close", (code, signal) => { void finalizeChild(code, signal).finally(settleRun); });
|
|
772
|
-
if (child.exitCode !== null || child.signalCode !== null) {
|
|
773
|
-
setImmediate(() => { void finalizeChild(child.exitCode, child.signalCode).finally(settleRun); });
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
try {
|
|
777
|
-
child.stdin.end(prompt);
|
|
778
|
-
} catch (error) {
|
|
779
|
-
await persist({
|
|
780
|
-
...live,
|
|
781
|
-
error: live.error ?? `stdin write failed: ${error.message}`,
|
|
782
|
-
updated_at: new Date().toISOString()
|
|
783
|
-
});
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
return { ok: true, record: live, child, settled };
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
// The MCP client may disappear at any point. A detached process owns the
|
|
790
|
-
// streams, exit write and acceptance until all three settle; IPC is only a
|
|
791
|
-
// startup handshake and never the channel carrying worker results.
|
|
792
|
-
async function startTrackedRun(job) {
|
|
793
|
-
if (Buffer.byteLength(String(job.prompt ?? ""), "utf8") > MAX_RUN_HOST_PROMPT_BYTES) {
|
|
794
|
-
const result = failedStart(job.record, `worker prompt is too large for the detached run host IPC channel (maximum ${MAX_RUN_HOST_PROMPT_BYTES} bytes); reduce task text and move materials to context files`);
|
|
795
|
-
await upsertTask(result.record);
|
|
796
|
-
return result;
|
|
797
|
-
}
|
|
798
|
-
const compiled = await compileWorkerContext(job.record, { attempt: (job.record.run_count ?? 0) + 1 });
|
|
799
|
-
job.record = {
|
|
800
|
-
...job.record,
|
|
801
|
-
input_context: {
|
|
802
|
-
...job.record.input_context,
|
|
803
|
-
context: compiled.sourceRefs,
|
|
804
|
-
source_refs: compiled.sourceRefs,
|
|
805
|
-
content_hash: compiled.contentHash,
|
|
806
|
-
context_snapshot_id: compiled.snapshot.id,
|
|
807
|
-
context_snapshot_tokens: compiled.snapshot.estimated_tokens,
|
|
808
|
-
context_fact_count: compiled.factCount
|
|
809
|
-
}
|
|
810
|
-
};
|
|
811
|
-
job.prompt = `${compiled.text}\n\n${job.prompt}\n\nRequired input refs (read-only): ${JSON.stringify(compiled.sourceRefs)}\nRequired contracts: ${JSON.stringify(job.record.input_context.contracts ?? [])}`;
|
|
812
|
-
const hostLogPath = job.logPath.endsWith(".jsonl")
|
|
813
|
-
? job.logPath.replace(/\.jsonl$/, ".host.log")
|
|
814
|
-
: `${job.logPath}.host.log`;
|
|
815
|
-
let hostLogFd;
|
|
816
|
-
try {
|
|
817
|
-
hostLogFd = openSync(hostLogPath, "a");
|
|
818
|
-
} catch (error) {
|
|
819
|
-
const result = failedStart(job.record, `cannot open run host log ${hostLogPath}: ${error.message}`);
|
|
820
|
-
await upsertTask(result.record);
|
|
821
|
-
return result;
|
|
822
|
-
}
|
|
823
|
-
let host;
|
|
824
|
-
try {
|
|
825
|
-
host = spawn(process.execPath, [fileURLToPath(import.meta.url), "--run-host"], {
|
|
826
|
-
detached: true, stdio: ["ignore", hostLogFd, hostLogFd, "ipc"],
|
|
827
|
-
env: process.env, windowsHide: true
|
|
828
|
-
});
|
|
829
|
-
} finally {
|
|
830
|
-
closeSync(hostLogFd);
|
|
831
|
-
}
|
|
832
|
-
const started = await new Promise((resolveStart) => {
|
|
833
|
-
let settled = false;
|
|
834
|
-
const finish = (result) => {
|
|
835
|
-
if (settled) return;
|
|
836
|
-
settled = true;
|
|
837
|
-
clearTimeout(timer);
|
|
838
|
-
host.removeAllListeners("message");
|
|
839
|
-
host.removeAllListeners("exit");
|
|
840
|
-
if (host.connected) host.disconnect();
|
|
841
|
-
host.unref();
|
|
842
|
-
resolveStart(result);
|
|
843
|
-
};
|
|
844
|
-
const timer = setTimeout(() => {
|
|
845
|
-
host.kill();
|
|
846
|
-
finish(failedStart(job.record, "run host startup timed out"));
|
|
847
|
-
}, RUN_HOST_STARTUP_TIMEOUT_MS);
|
|
848
|
-
host.once("message", finish);
|
|
849
|
-
host.once("error", (error) => finish(failedStart(job.record, `run host startup failed: ${error.message}`)));
|
|
850
|
-
host.once("exit", (code) => finish(failedStart(job.record, `run host exited before startup: ${code}`)));
|
|
851
|
-
host.send(job, (error) => {
|
|
852
|
-
if (error) finish(failedStart(job.record, `run host IPC failed: ${error.message}`));
|
|
853
|
-
});
|
|
854
|
-
});
|
|
855
|
-
if (!started.ok) await upsertTask(started.record);
|
|
856
|
-
return started;
|
|
857
|
-
}
|
|
858
|
-
|
|
859
|
-
function validateGoal(goal) {
|
|
860
|
-
if (!goal || typeof goal !== "object" || typeof goal.objective !== "string" || goal.objective.trim() === "") {
|
|
861
|
-
throw new Error("goal.objective is required");
|
|
862
|
-
}
|
|
863
|
-
const tokenBudget = goal.tokenBudget ?? goal.token_budget ?? null;
|
|
864
|
-
if (tokenBudget !== null && (!Number.isInteger(tokenBudget) || tokenBudget <= 0)) {
|
|
865
|
-
throw new Error("goal.tokenBudget must be a positive integer when provided");
|
|
866
|
-
}
|
|
867
|
-
return { objective: goal.objective, tokenBudget };
|
|
868
|
-
}
|
|
869
|
-
|
|
870
|
-
function dependencyError(code, message, details = {}) {
|
|
871
|
-
const error = new Error(message);
|
|
872
|
-
error.code = code;
|
|
873
|
-
error.details = details;
|
|
874
|
-
return error;
|
|
875
|
-
}
|
|
876
|
-
|
|
877
|
-
function containsCommit(cwd, ancestor, descendant) {
|
|
878
|
-
try {
|
|
879
|
-
execFileSync(defaultGitBin, ["-C", cwd, "merge-base", "--is-ancestor", ancestor, descendant], {
|
|
880
|
-
stdio: "ignore",
|
|
881
|
-
timeout: 15000
|
|
882
|
-
});
|
|
883
|
-
return true;
|
|
884
|
-
} catch {
|
|
885
|
-
return false;
|
|
886
|
-
}
|
|
887
|
-
}
|
|
888
|
-
|
|
889
|
-
async function validateDependencies(dependsOn, projectRoot, baseCommit) {
|
|
890
|
-
const dependencyIds = [...new Set(dependsOn ?? [])];
|
|
891
|
-
for (const dependencyId of dependencyIds) {
|
|
892
|
-
const dependency = await getTask(dependencyId);
|
|
893
|
-
if (!dependency) {
|
|
894
|
-
throw dependencyError("dependency_not_found", `dependency ${dependencyId} does not exist`, { dependency_id: dependencyId });
|
|
895
|
-
}
|
|
896
|
-
if (resolve(dependency.project_root) !== resolve(projectRoot)) {
|
|
897
|
-
throw dependencyError("dependency_project_mismatch", `dependency ${dependencyId} belongs to a different project root`, {
|
|
898
|
-
dependency_id: dependencyId,
|
|
899
|
-
dependency_project_root: dependency.project_root,
|
|
900
|
-
project_root: projectRoot
|
|
901
|
-
});
|
|
902
|
-
}
|
|
903
|
-
if (dependency.status !== "completed" || dependency.exit_code !== 0 || dependency.attention_reason) {
|
|
904
|
-
throw dependencyError("dependency_not_ready", `dependency ${dependencyId} is not successfully settled`, {
|
|
905
|
-
dependency_id: dependencyId,
|
|
906
|
-
status: dependency.status,
|
|
907
|
-
exit_code: dependency.exit_code ?? null,
|
|
908
|
-
attention_reason: dependency.attention_reason ?? null
|
|
909
|
-
});
|
|
910
|
-
}
|
|
911
|
-
if (Array.isArray(dependency.acceptance) && dependency.acceptance.length > 0 && dependency.acceptance_results?.passed !== true) {
|
|
912
|
-
throw dependencyError("dependency_not_ready", `dependency ${dependencyId} has not passed acceptance`, {
|
|
913
|
-
dependency_id: dependencyId,
|
|
914
|
-
acceptance: dependency.acceptance_results?.status ?? null
|
|
915
|
-
});
|
|
916
|
-
}
|
|
917
|
-
if (!dependency.landed_at || !dependency.landed_head) {
|
|
918
|
-
throw dependencyError("dependency_not_landed", `dependency ${dependencyId} must be landed before a dependent worker starts`, {
|
|
919
|
-
dependency_id: dependencyId,
|
|
920
|
-
landed_at: dependency.landed_at ?? null
|
|
921
|
-
});
|
|
922
|
-
}
|
|
923
|
-
if (!baseCommit || !containsCommit(projectRoot, dependency.landed_head, baseCommit)) {
|
|
924
|
-
throw dependencyError("dependency_base_mismatch", `worker base does not contain landed dependency ${dependencyId}; use the integrated branch or a newer baseRef`, {
|
|
925
|
-
dependency_id: dependencyId,
|
|
926
|
-
dependency_head: dependency.landed_head,
|
|
927
|
-
base_commit: baseCommit ?? null
|
|
928
|
-
});
|
|
929
|
-
}
|
|
930
|
-
}
|
|
931
|
-
}
|
|
932
|
-
|
|
933
|
-
export async function createCodexWorker({
|
|
934
|
-
title,
|
|
935
|
-
task,
|
|
936
|
-
sessionId = null,
|
|
937
|
-
sessionTitle = null,
|
|
938
|
-
sessionNote = null,
|
|
939
|
-
cwd,
|
|
940
|
-
sandbox = "workspace-write",
|
|
941
|
-
model = null,
|
|
942
|
-
reasoningEffort = "high",
|
|
943
|
-
skipGitRepoCheck = true,
|
|
944
|
-
ownedPaths,
|
|
945
|
-
goal,
|
|
946
|
-
dependsOn = [],
|
|
947
|
-
followupOf = null,
|
|
948
|
-
workspaceKind = null,
|
|
949
|
-
inPlaceAuthorization = null,
|
|
950
|
-
workspaceSetup = null,
|
|
951
|
-
baseRef = null,
|
|
952
|
-
preflightId = null,
|
|
953
|
-
preflight = null,
|
|
954
|
-
acceptance = null,
|
|
955
|
-
acceptanceTimeoutMs = null,
|
|
956
|
-
forbid = [],
|
|
957
|
-
allowedCommands = [],
|
|
958
|
-
context = [],
|
|
959
|
-
contracts = [],
|
|
960
|
-
externalOutputs = [],
|
|
961
|
-
networkAccess = false,
|
|
962
|
-
writableRoots = [],
|
|
963
|
-
maxRunMs = null,
|
|
964
|
-
maxTotalMs = null
|
|
965
|
-
}) {
|
|
966
|
-
if (!task || typeof task !== "string") throw new Error("task is required");
|
|
967
|
-
const acceptanceCommands = normalizeAcceptance(acceptance);
|
|
968
|
-
if (!cwd || typeof cwd !== "string") throw new Error("cwd is required");
|
|
969
|
-
if (!allowedReasoningEfforts.has(reasoningEffort)) {
|
|
970
|
-
throw new Error(`unsupported reasoningEffort: ${reasoningEffort}`);
|
|
971
|
-
}
|
|
972
|
-
if (!Array.isArray(ownedPaths)) {
|
|
973
|
-
throw new Error("ownedPaths is required; pass an empty list only for a worker that must never land a change (a read-only verifier, or a research worker that reads and reports)");
|
|
974
|
-
}
|
|
975
|
-
if (ownedPaths.length > 0 && acceptanceCommands?.length && acceptanceCommands.every(isArtifactOnlyAcceptance)) {
|
|
976
|
-
throw new Error("a write worker cannot use only file-existence acceptance; add a real test, endpoint probe or structured execution evidence");
|
|
977
|
-
}
|
|
978
|
-
const validatedGoal = validateGoal(goal);
|
|
979
|
-
await buildHandoff({ context, contracts });
|
|
980
|
-
await captureExternalOutputs(externalOutputs, { checkBaseline: true });
|
|
981
|
-
if (externalOutputs.length && !acceptanceCommands?.length) throw new Error("shared outputs require explicit acceptance commands");
|
|
982
|
-
if (externalOutputs.length && sandbox === "read-only") throw new Error("a read-only worker cannot declare writable shared outputs");
|
|
983
|
-
if (networkAccess && sandbox === "danger-full-access") throw new Error("networkAccess is only for the sandboxed workers");
|
|
984
|
-
if (networkAccess && sandbox === "read-only") throw new Error("the read-only sandbox has no network (a fetch there fails on DNS even with network_access); for a worker that must fetch, use sandbox \"workspace-write\" with networkAccess: true and ownedPaths: []");
|
|
985
|
-
if (!Array.isArray(writableRoots) || writableRoots.length > 20 || writableRoots.some((root) => typeof root !== "string" || !isAbsolute(root))) {
|
|
986
|
-
throw new Error("writableRoots must be a list of at most 20 absolute paths");
|
|
987
|
-
}
|
|
988
|
-
if (writableRoots.length && sandbox !== "workspace-write") throw new Error("writableRoots is only configurable for workspace-write workers");
|
|
989
|
-
// Codex refuses a writable root with a symlink component and then fails every
|
|
990
|
-
// command in the worker, so a declared root is stored resolved. Passing the
|
|
991
|
-
// alias would look fine in the receipt and break the run.
|
|
992
|
-
const resolvedWritableRoots = [];
|
|
993
|
-
for (const root of writableRoots) {
|
|
994
|
-
const resolved = resolveWritableRoot(root);
|
|
995
|
-
if (resolved.error) throw new Error(`writableRoots entry is unusable: ${root} (${resolved.error}); pass an existing directory whose path has no symlink component`);
|
|
996
|
-
resolvedWritableRoots.push(resolved.path);
|
|
997
|
-
}
|
|
998
|
-
for (const value of [maxRunMs, maxTotalMs]) if (value !== null && (!Number.isInteger(value) || value < 1000)) throw new Error("time limits must be integer milliseconds of at least 1000");
|
|
999
|
-
for (const [name, values] of Object.entries({ forbid, allowedCommands })) {
|
|
1000
|
-
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`);
|
|
1001
|
-
}
|
|
1002
|
-
if (baseRef && !isGitCheckout(cwd)) throw invalidBaseRefError(cwd, baseRef);
|
|
1003
|
-
|
|
1004
|
-
const id = `codex-${Date.now()}-${randomUUID().slice(0, 8)}`;
|
|
1005
|
-
const workspace = await prepareWorkspace({
|
|
1006
|
-
cwd,
|
|
1007
|
-
workspaceKind,
|
|
1008
|
-
sandbox,
|
|
1009
|
-
ownedPaths,
|
|
1010
|
-
networkAccess,
|
|
1011
|
-
acceptance: acceptanceCommands,
|
|
1012
|
-
externalOutputs,
|
|
1013
|
-
inPlaceAuthorization,
|
|
1014
|
-
taskId: id,
|
|
1015
|
-
isPreflight: Boolean(preflight)
|
|
1016
|
-
});
|
|
1017
|
-
const projectRoot = workspace.sourceRoot;
|
|
1018
|
-
const normalizedOwnedPaths = normalizeOwnedPaths([...ownedPaths, ...externalOutputs.map((entry) => entry.path)], projectRoot);
|
|
1019
|
-
const normalizedWorkspaceSetup = normalizeWorkspaceSetup(workspaceSetup, projectRoot);
|
|
1020
|
-
if (normalizedWorkspaceSetup && workspace.kind !== "git_worktree") throw new Error("workspaceSetup is only supported for git_worktree workers");
|
|
1021
|
-
const conflicts = await findOwnershipConflicts(normalizedOwnedPaths);
|
|
1022
|
-
if (conflicts.length > 0) throw ownershipConflictError(conflicts);
|
|
1023
|
-
|
|
1024
|
-
if (sessionId && (sessionTitle || sessionNote)) {
|
|
1025
|
-
await upsertSession({ id: sessionId, title: sessionTitle, note: sessionNote });
|
|
1026
|
-
}
|
|
1027
|
-
|
|
1028
|
-
const session = sessionId ? await getSession(sessionId) : null;
|
|
1029
|
-
if (session?.approval_state === "waiting_user") {
|
|
1030
|
-
const error = new Error("session is waiting for user approval; do not dispatch or auto-resume");
|
|
1031
|
-
error.code = "session_waiting_user";
|
|
1032
|
-
throw error;
|
|
1033
|
-
}
|
|
1034
|
-
const combinedAcceptance = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(acceptanceCommands ?? [])]);
|
|
1035
|
-
requireDependencySetup({ kind: workspace.kind, projectRoot, setup: normalizedWorkspaceSetup,
|
|
1036
|
-
commands: [...(combinedAcceptance ?? []), ...(preflight?.probeCommands ?? [])] });
|
|
1037
|
-
|
|
1038
|
-
const worktree = workspace.kind === "git_worktree"
|
|
1039
|
-
? await withWorktreeCreationLock(projectRoot, () => ensureWorktree(projectRoot, id, baseRef))
|
|
1040
|
-
: { path: null, baseCommit: null };
|
|
1041
|
-
const worktreePath = worktree.path;
|
|
1042
|
-
if (workspace.kind === "git_worktree" && !worktreePath) {
|
|
1043
|
-
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");
|
|
1044
|
-
error.code = "git_worktree_unavailable";
|
|
1045
|
-
throw error;
|
|
1046
|
-
}
|
|
1047
|
-
if (normalizedWorkspaceSetup) {
|
|
1048
|
-
try {
|
|
1049
|
-
await prepareWorktreeWorkspace(normalizedWorkspaceSetup, projectRoot, worktreePath, id);
|
|
1050
|
-
} catch (error) {
|
|
1051
|
-
await runCommand(defaultGitBin, ["-C", projectRoot, "worktree", "remove", worktreePath]).catch(() => {});
|
|
1052
|
-
await runCommand(defaultGitBin, ["-C", projectRoot, "branch", "-D", `codex/${id}`]).catch(() => {});
|
|
1053
|
-
throw error;
|
|
1054
|
-
}
|
|
1055
|
-
}
|
|
1056
|
-
const effectiveCwd = worktreePath ?? workspace.executionCwd;
|
|
1057
|
-
if (preflight && (!Array.isArray(preflight.probeCommands) || preflight.probeCommands.length === 0
|
|
1058
|
-
|| preflight.probeCommands.some((command) => typeof command !== "string" || !command.trim()))) {
|
|
1059
|
-
throw new Error("preflight.probeCommands must be a nonempty list of shell commands");
|
|
1060
|
-
}
|
|
1061
|
-
const guardPolicy = {
|
|
1062
|
-
forbid,
|
|
1063
|
-
// Probe commands need enough permission to prove the worker environment,
|
|
1064
|
-
// but they are not part of the target worker's executable contract. Keep
|
|
1065
|
-
// them in this preflight run's guard only so the final worker can reuse the
|
|
1066
|
-
// exact contract its dispatcher declared.
|
|
1067
|
-
allowedCommands: [...new Set([
|
|
1068
|
-
...allowedCommands,
|
|
1069
|
-
...(preflight?.probeCommands ?? [])
|
|
1070
|
-
])],
|
|
1071
|
-
externalOutputs,
|
|
1072
|
-
networkAccess,
|
|
1073
|
-
writableRoots: [...new Set(resolvedWritableRoots)],
|
|
1074
|
-
maxRunMs,
|
|
1075
|
-
maxTotalMs,
|
|
1076
|
-
workspaceKind: workspace.kind
|
|
1077
|
-
};
|
|
1078
|
-
const runtimeContract = buildRuntimeContract({
|
|
1079
|
-
projectRoot,
|
|
1080
|
-
baseCommit: worktree.baseCommit,
|
|
1081
|
-
sandbox,
|
|
1082
|
-
ownedPaths: normalizedOwnedPaths,
|
|
1083
|
-
allowedCommands,
|
|
1084
|
-
networkAccess,
|
|
1085
|
-
writableRoots: guardPolicy.writableRoots,
|
|
1086
|
-
context,
|
|
1087
|
-
contracts,
|
|
1088
|
-
workspaceSetup: normalizedWorkspaceSetup,
|
|
1089
|
-
workspaceKind: workspace.kind,
|
|
1090
|
-
workspaceManifestSha256: workspace.beforeManifest?.sha256 ?? null
|
|
1091
|
-
});
|
|
1092
|
-
const preflightMetadata = preflight
|
|
1093
|
-
? createPreflightMetadata(runtimeContract, preflight.probeCommands)
|
|
1094
|
-
: null;
|
|
1095
|
-
|
|
1096
|
-
const record = {
|
|
1097
|
-
id,
|
|
1098
|
-
title: title || task.split("\n").find(Boolean)?.slice(0, 80) || "Codex worker",
|
|
1099
|
-
worker: "codex",
|
|
1100
|
-
status: "queued",
|
|
1101
|
-
phase: null,
|
|
1102
|
-
cwd: effectiveCwd,
|
|
1103
|
-
project_root: projectRoot,
|
|
1104
|
-
workspace_kind: workspace.kind,
|
|
1105
|
-
workspace_metadata: {
|
|
1106
|
-
source_root: workspace.sourceRoot,
|
|
1107
|
-
execution_root: effectiveCwd,
|
|
1108
|
-
manifest_paths: workspace.manifestPaths,
|
|
1109
|
-
before_manifest: workspace.beforeManifest,
|
|
1110
|
-
in_place_authorization: workspace.kind === "in_place_write" ? String(inPlaceAuthorization).trim() : null,
|
|
1111
|
-
landable: workspace.landable,
|
|
1112
|
-
cleanable: workspace.cleanable,
|
|
1113
|
-
setup: normalizedWorkspaceSetup
|
|
1114
|
-
},
|
|
1115
|
-
sandbox,
|
|
1116
|
-
model,
|
|
1117
|
-
reasoning_effort: reasoningEffort,
|
|
1118
|
-
skip_git_repo_check: skipGitRepoCheck,
|
|
1119
|
-
followup_of: followupOf,
|
|
1120
|
-
resumed_from: null,
|
|
1121
|
-
session_id: sessionId ?? null,
|
|
1122
|
-
thread_id: null,
|
|
1123
|
-
owned_paths: normalizedOwnedPaths,
|
|
1124
|
-
guard_policy: {
|
|
1125
|
-
...guardPolicy,
|
|
1126
|
-
...(preflightMetadata ? { preflight: preflightMetadata } : {}),
|
|
1127
|
-
...(preflightId ? { preflight_source_id: preflightId } : {}),
|
|
1128
|
-
workspace: {
|
|
1129
|
-
kind: workspace.kind,
|
|
1130
|
-
source_root: workspace.sourceRoot,
|
|
1131
|
-
execution_root: effectiveCwd,
|
|
1132
|
-
manifest_paths: workspace.manifestPaths,
|
|
1133
|
-
before_manifest_sha256: workspace.beforeManifest?.sha256 ?? null
|
|
1134
|
-
}
|
|
1135
|
-
},
|
|
1136
|
-
input_context: { context, contracts },
|
|
1137
|
-
depends_on: Array.isArray(dependsOn) ? dependsOn : [],
|
|
1138
|
-
goal_objective: validatedGoal.objective,
|
|
1139
|
-
goal_token_budget: validatedGoal.tokenBudget,
|
|
1140
|
-
goal_status: null,
|
|
1141
|
-
goal_tokens_used: null,
|
|
1142
|
-
goal_time_used_seconds: null,
|
|
1143
|
-
goal_updated_at: null,
|
|
1144
|
-
run_count: 0,
|
|
1145
|
-
worktree_path: worktreePath,
|
|
1146
|
-
base_commit: worktree.baseCommit,
|
|
1147
|
-
acceptance: combinedAcceptance,
|
|
1148
|
-
acceptance_local: acceptanceCommands,
|
|
1149
|
-
session_policy_revision: session?.policy_revision ?? null,
|
|
1150
|
-
acceptance_timeout_ms: combinedAcceptance ? (acceptanceTimeoutMs ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS) : null,
|
|
1151
|
-
acceptance_results: null,
|
|
1152
|
-
prompt: task,
|
|
1153
|
-
changed_files: [],
|
|
1154
|
-
commands: [],
|
|
1155
|
-
created_at: new Date().toISOString(),
|
|
1156
|
-
updated_at: new Date().toISOString(),
|
|
1157
|
-
run_log: taskRunPath(id)
|
|
1158
|
-
};
|
|
1159
|
-
try {
|
|
1160
|
-
await validateDependencies(dependsOn, projectRoot, worktree.baseCommit);
|
|
1161
|
-
if (preflightId) {
|
|
1162
|
-
const preflightTask = await getTask(preflightId);
|
|
1163
|
-
const preflightResult = readPreflightResult(preflightTask);
|
|
1164
|
-
if (preflightResult.status !== "passed") {
|
|
1165
|
-
const error = new Error(`preflight ${preflightId} is ${preflightResult.status}; wait for its probes to pass before dispatching this worker`);
|
|
1166
|
-
error.code = "preflight_not_passed";
|
|
1167
|
-
error.details = preflightResult;
|
|
1168
|
-
throw error;
|
|
1169
|
-
}
|
|
1170
|
-
const contractHash = runtimeContractHash(runtimeContract);
|
|
1171
|
-
if (preflightResult.contract_hash !== contractHash) {
|
|
1172
|
-
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`);
|
|
1173
|
-
error.code = "preflight_mismatch";
|
|
1174
|
-
error.details = {
|
|
1175
|
-
preflight_id: preflightId,
|
|
1176
|
-
expected_contract_hash: contractHash,
|
|
1177
|
-
actual_contract_hash: preflightResult.contract_hash,
|
|
1178
|
-
preflight: { expected_contract: runtimeContract, actual_contract: preflightResult.contract }
|
|
1179
|
-
};
|
|
1180
|
-
throw error;
|
|
1181
|
-
}
|
|
1182
|
-
}
|
|
1183
|
-
await reserveTaskOwnership(record);
|
|
1184
|
-
}
|
|
1185
|
-
catch (error) {
|
|
1186
|
-
if (worktreePath) {
|
|
1187
|
-
// This checkout belongs to this not-yet-started dispatch and contains
|
|
1188
|
-
// no model edits. Remove it normally; never force-remove user work.
|
|
1189
|
-
await runCommand(defaultGitBin,["-C",projectRoot,"worktree","remove",worktreePath]).catch(()=>{});
|
|
1190
|
-
await runCommand(defaultGitBin,["-C",projectRoot,"branch","-D",`codex/${id}`]).catch(()=>{});
|
|
1191
|
-
}
|
|
1192
|
-
if (workspace.scratchPath) await rm(workspace.scratchPath, { recursive: true, force: true }).catch(() => {});
|
|
1193
|
-
throw error;
|
|
1194
|
-
}
|
|
1195
|
-
|
|
1196
|
-
const args = codexRunner.startArgs({ cwd: effectiveCwd, sandbox, model, reasoningEffort, skipGitRepoCheck });
|
|
1197
|
-
|
|
1198
|
-
const started = await startTrackedRun({
|
|
1199
|
-
record,
|
|
1200
|
-
args,
|
|
1201
|
-
prompt: frameWorkerPrompt(task, {
|
|
1202
|
-
objective: validatedGoal.objective,
|
|
1203
|
-
tokenBudget: validatedGoal.tokenBudget
|
|
1204
|
-
}, { acceptance: combinedAcceptance, outputSchema: true }),
|
|
1205
|
-
logPath: record.run_log,
|
|
1206
|
-
outputSchema: true,
|
|
1207
|
-
// --cd tells Codex where the agent works. The shell/tool process must also
|
|
1208
|
-
// inherit the worktree as its OS cwd: otherwise a login shell may restore
|
|
1209
|
-
// the project directory and relative probes read the wrong checkout.
|
|
1210
|
-
spawnOptions: { cwd: effectiveCwd }
|
|
1211
|
-
});
|
|
1212
|
-
return started.record;
|
|
1213
|
-
}
|
|
1214
|
-
|
|
1215
|
-
// Continue the *same* Codex session. The worktree, thread id, ownership and
|
|
1216
|
-
// goal are all inherited from the original task, and the row is reused so one
|
|
1217
|
-
// logical piece of work stays one row.
|
|
1218
|
-
//
|
|
1219
|
-
// `rebaseOnto` names a ref, resolved in the project directory (HEAD, main, a
|
|
1220
|
-
// sha): the worktree is moved onto it first so the worker continues on
|
|
1221
|
-
// current code, and base_commit is recorded before the worker starts so a
|
|
1222
|
-
// spawn failure cannot leave the row describing the old base. A rebase that
|
|
1223
|
-
// does not go through puts the worktree back and throws with the file list;
|
|
1224
|
-
// the worker is not started. Refused while the worker is still running.
|
|
1225
|
-
export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acceptance = undefined, context = undefined }) {
|
|
1226
|
-
if (!prompt || typeof prompt !== "string") throw new Error("prompt is required");
|
|
1227
|
-
let task = await getTask(taskId);
|
|
1228
|
-
if (!task) throw new Error(`task not found: ${taskId}`);
|
|
1229
|
-
if (task.guard_policy?.maxTotalMs && Date.now() - Date.parse(task.created_at) >= task.guard_policy.maxTotalMs) {
|
|
1230
|
-
const error = new Error("total time quota exceeded; inspect partial work and explicitly dispatch a revised budget");error.code="time_quota_exceeded";throw error;
|
|
1231
|
-
}
|
|
1232
|
-
if (context !== undefined) {
|
|
1233
|
-
await buildHandoff({ context });
|
|
1234
|
-
task = { ...task, input_context: { ...task.input_context, context } };
|
|
1235
|
-
}
|
|
1236
|
-
const claim = await claimTaskRun(taskId, task.run_count ?? 0);
|
|
1237
|
-
if (!claim) {
|
|
1238
|
-
const error = new Error(`task ${taskId} is active or already claimed by another dispatcher; wait for it to settle`);
|
|
1239
|
-
error.code = "worker_active";
|
|
1240
|
-
throw error;
|
|
1241
|
-
}
|
|
1242
|
-
try {
|
|
1243
|
-
const session = task.session_id ? await getSession(task.session_id) : null;
|
|
1244
|
-
if (session?.approval_state === "waiting_user") {
|
|
1245
|
-
const error = new Error("session is waiting for user approval; do not resume");
|
|
1246
|
-
error.code = "session_waiting_user";
|
|
1247
|
-
throw error;
|
|
1248
|
-
}
|
|
1249
|
-
const localAcceptance = acceptance === undefined ? (task.session_policy_revision == null ? task.acceptance : task.acceptance_local) : normalizeAcceptance(acceptance);
|
|
1250
|
-
// `acceptance` replaces the stored commands when given; an empty list
|
|
1251
|
-
// clears them. Left out, the stored commands stay.
|
|
1252
|
-
if (acceptance !== undefined || session) {
|
|
1253
|
-
const commands = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(localAcceptance ?? [])]);
|
|
1254
|
-
task = {
|
|
1255
|
-
...task,
|
|
1256
|
-
acceptance: commands,
|
|
1257
|
-
acceptance_local: localAcceptance,
|
|
1258
|
-
session_policy_revision: session?.policy_revision ?? null,
|
|
1259
|
-
acceptance_timeout_ms: commands ? (task.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS) : null,
|
|
1260
|
-
updated_at: new Date().toISOString()
|
|
1261
|
-
};
|
|
1262
|
-
await upsertTask(task);
|
|
1263
|
-
}
|
|
1264
|
-
if (!task.thread_id) {
|
|
1265
|
-
throw new Error(
|
|
1266
|
-
`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.`
|
|
1267
|
-
);
|
|
1268
|
-
}
|
|
1269
|
-
let rebase = null;
|
|
1270
|
-
if (rebaseOnto) {
|
|
1271
|
-
if (ACTIVE_STATUSES.has(task.status) || processes.has(task.id)) {
|
|
1272
|
-
const error = new Error(`task ${taskId} is still ${task.status}; wait for it to settle (or cancel it) before rebasing its worktree`);
|
|
1273
|
-
error.code = "worker_active";
|
|
1274
|
-
throw error;
|
|
1275
|
-
}
|
|
1276
|
-
if (!task.worktree_path) {
|
|
1277
|
-
const error = new Error(`task ${taskId} ran in place and has no worktree to rebase`);
|
|
1278
|
-
error.code = "no_worktree";
|
|
1279
|
-
throw error;
|
|
1280
|
-
}
|
|
1281
|
-
let ontoCommit;
|
|
1282
|
-
try {
|
|
1283
|
-
ontoCommit = resolveCommit(task.project_root, rebaseOnto);
|
|
1284
|
-
} catch {
|
|
1285
|
-
const error = new Error(`rebaseOnto "${rebaseOnto}" does not resolve to a commit in ${task.project_root}`);
|
|
1286
|
-
error.code = "invalid_rebase_onto";
|
|
1287
|
-
throw error;
|
|
1288
|
-
}
|
|
1289
|
-
rebase = rebaseWorktree(task, ontoCommit);
|
|
1290
|
-
if (rebase.error) {
|
|
1291
|
-
const error = new Error(rebase.reason);
|
|
1292
|
-
error.code = rebase.error;
|
|
1293
|
-
error.details = rebase;
|
|
1294
|
-
throw error;
|
|
1295
|
-
}
|
|
1296
|
-
if (!rebase.noop && rebase.base_commit !== task.base_commit) {
|
|
1297
|
-
task = { ...task, base_commit: rebase.base_commit, updated_at: new Date().toISOString() };
|
|
1298
|
-
await upsertTask(task);
|
|
1299
|
-
}
|
|
1300
|
-
}
|
|
1301
|
-
|
|
1302
|
-
const cwd = (await exists(task.cwd)) ? task.cwd : task.project_root;
|
|
1303
|
-
const args = codexRunner.resumeArgs(task);
|
|
1304
|
-
const goalRead = readNativeGoalState(task.thread_id);
|
|
1305
|
-
// Only a thread with no native goal, or one explicitly stored as complete,
|
|
1306
|
-
// can safely resume with a structured output schema. Paused, blocked,
|
|
1307
|
-
// usage-limited and budget-limited goals are not complete; Codex can still
|
|
1308
|
-
// activate their goal turn and reject the incompatible schema.
|
|
1309
|
-
const outputSchema = ["missing_goal", "missing_database"].includes(goalRead.state)
|
|
1310
|
-
|| (goalRead.state === "available" && goalRead.goal?.storage_status === "complete");
|
|
1311
|
-
|
|
1312
|
-
const started = await startTrackedRun({
|
|
1313
|
-
record: { ...task, resumed_from: task.resumed_from ?? task.id },
|
|
1314
|
-
args,
|
|
1315
|
-
prompt: frameWorkerPrompt(prompt, {
|
|
1316
|
-
objective: task.goal_objective ?? task.title ?? task.id,
|
|
1317
|
-
resume: true
|
|
1318
|
-
}, { acceptance: task.acceptance, outputSchema }),
|
|
1319
|
-
logPath: task.run_log,
|
|
1320
|
-
outputSchema,
|
|
1321
|
-
spawnOptions: { cwd }
|
|
1322
|
-
});
|
|
1323
|
-
return rebase ? { ...started.record, rebase } : started.record;
|
|
1324
|
-
} finally { await releaseTaskRun(taskId, claim); }
|
|
1325
|
-
}
|
|
1326
|
-
|
|
1327
|
-
export async function recoverEligibleRuns() {
|
|
1328
|
-
const recovered = [];
|
|
1329
|
-
for (const task of await readTasks()) {
|
|
1330
|
-
if (task.guard_policy?.preflight) continue;
|
|
1331
|
-
if ((task.run_count ?? 0) !== 1 || !task.thread_id
|
|
1332
|
-
|| !(task.run_evidence?.run === 1 || (task.run_host_pid && task.started_at)) || !task.guard_policy
|
|
1333
|
-
|| !(task.status === "lost" || task.attention_reason === "no_work" || task.attention_reason === "invalid_report")
|
|
1334
|
-
|| ["blocked", "paused", "budget_limited", "usage_limited"].includes(task.goal_status)
|
|
1335
|
-
|| /401|403|unauthori[sz]ed|not logged|permission denied|approval|rate.?limit|429/i.test(task.error ?? "")
|
|
1336
|
-
|| /time_limit|quota/.test(`${task.attention_reason ?? ""} ${task.error ?? ""}`)
|
|
1337
|
-
|| await isPidAlive(task.pid) || await isPidAlive(task.run_host_pid)) continue;
|
|
1338
|
-
const session = task.session_id ? await getSession(task.session_id) : null;
|
|
1339
|
-
if (session?.approval_state === "waiting_user") continue;
|
|
1340
|
-
try {
|
|
1341
|
-
const result = await resumeCodexWorker({ taskId: task.id,
|
|
1342
|
-
prompt: task.attention_reason === "invalid_report"
|
|
1343
|
-
? "Your run finished, but the final message was not the required bare JSON report. Do not redo the work and do not edit files: reply with ONLY the JSON object with result (string), verification (string[]) and not_done (string[]), describing what you already did. No code fences, nothing before or after it."
|
|
1344
|
-
: `One automatic recovery after ${task.attention_reason ?? task.status}. Original task: ${task.prompt}\nContinue from files already present; do not repeat completed edits. Make concrete progress, run declared checks, and report remaining blockers accurately. This is the only automatic retry.` });
|
|
1345
|
-
const event = { type: "supervisor.recovery", automatic: true, from_run: 1, to_run: result.run_count,
|
|
1346
|
-
reason: task.attention_reason ?? task.status, started_at: new Date().toISOString() };
|
|
1347
|
-
await appendTaskEvent(task.id, event);
|
|
1348
|
-
await appendFile(task.run_log, `${JSON.stringify(event)}\n`);
|
|
1349
|
-
recovered.push({ id: task.id, run: result.run_count, reason: event.reason });
|
|
1350
|
-
} catch (error) {
|
|
1351
|
-
if (!["worker_active", "session_waiting_user"].includes(error.code)) {
|
|
1352
|
-
await appendTaskEvent(task.id, { type: "supervisor.recovery_refused", reason: error.code ?? "resume_failed" });
|
|
1353
|
-
}
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
return recovered;
|
|
1357
|
-
}
|
|
1358
|
-
|
|
1359
|
-
if (process.argv[1] === fileURLToPath(import.meta.url) && process.argv[2] === "--run-host") {
|
|
1360
|
-
process.once("message", async (job) => {
|
|
1361
|
-
const keepAlive = setInterval(() => {}, 1000);
|
|
1362
|
-
let result;
|
|
1363
|
-
try {
|
|
1364
|
-
result = await trackRunInHost(job);
|
|
1365
|
-
if (!result.ok) await upsertTask(result.record);
|
|
1366
|
-
} catch (error) {
|
|
1367
|
-
result = failedStart(job.record, `run host failed: ${error.message}`);
|
|
1368
|
-
await upsertTask(result.record);
|
|
1369
|
-
}
|
|
1370
|
-
if (process.connected) await new Promise((resolveSent) => process.send({ ok: result.ok, record: result.record }, resolveSent));
|
|
1371
|
-
if (result.settled) await result.settled;
|
|
1372
|
-
clearInterval(keepAlive);
|
|
1373
|
-
if (process.connected) process.disconnect();
|
|
1374
|
-
});
|
|
1375
|
-
}
|
|
1376
|
-
|
|
1377
|
-
// `powershell` by name is not always on PATH for a process a GUI client
|
|
1378
|
-
// started, so prefer the copy that ships with Windows. Only the CIM path needs
|
|
1379
|
-
// it; the rest of this file shells out to nothing but taskkill and git.
|
|
1380
|
-
function powershellBin() {
|
|
1381
|
-
const root = process.env.SystemRoot?.trim() || "C:\\Windows";
|
|
1382
|
-
const full = join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
1383
|
-
return existsSync(full) ? full : "powershell";
|
|
1384
|
-
}
|
|
1385
|
-
|
|
1386
|
-
// A pid recorded on disk is only signalled once it is confirmed to still be a
|
|
1387
|
-
// Codex worker, so a recycled pid belonging to an unrelated process is never
|
|
1388
|
-
// killed. Windows has no `ps`: CIM is the only reliable source for a full command
|
|
1389
|
-
// line, and the full line matters because the npm shim is bypassed by running
|
|
1390
|
-
// `node <entry>`, which puts the word "codex" in the arguments, not the image
|
|
1391
|
-
// name. `tasklist` is the fallback when PowerShell is unavailable - it only
|
|
1392
|
-
// reports the image name, so it can confirm a native codex.exe but never a
|
|
1393
|
-
// `node <entry>` worker.
|
|
1394
|
-
//
|
|
1395
|
-
// The timeout is generous on purpose: this runs once per cross-process cancel,
|
|
1396
|
-
// and a cold Windows PowerShell on a fresh machine routinely takes several
|
|
1397
|
-
// seconds to print anything. A tight timeout here silently degrades to the
|
|
1398
|
-
// useless tasklist probe, and the cancel comes back "process_not_found".
|
|
1399
|
-
function describeProcess(pid) {
|
|
1400
|
-
const options = { encoding: "utf8", timeout: 15000, windowsHide: true };
|
|
1401
|
-
try {
|
|
1402
|
-
if (process.platform === "win32") {
|
|
1403
|
-
try {
|
|
1404
|
-
const viaCim = execFileSync(
|
|
1405
|
-
powershellBin(),
|
|
1406
|
-
[
|
|
1407
|
-
"-NoLogo",
|
|
1408
|
-
"-NoProfile",
|
|
1409
|
-
"-NonInteractive",
|
|
1410
|
-
"-Command",
|
|
1411
|
-
`(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine`
|
|
1412
|
-
],
|
|
1413
|
-
options
|
|
1414
|
-
).trim();
|
|
1415
|
-
if (viaCim) return viaCim;
|
|
1416
|
-
} catch {
|
|
1417
|
-
// fall through to the image-name probe below
|
|
1418
|
-
}
|
|
1419
|
-
return execFileSync("tasklist", ["/FI", `PID eq ${Number(pid)}`, "/FO", "CSV", "/NH"], options).trim();
|
|
1420
|
-
}
|
|
1421
|
-
return execFileSync("ps", ["-p", String(pid), "-o", "command="], options).trim();
|
|
1422
|
-
} catch {
|
|
1423
|
-
return "";
|
|
1424
|
-
}
|
|
1425
|
-
}
|
|
1426
|
-
|
|
1427
|
-
function isLikelyCodexProcess(pid) {
|
|
1428
|
-
return codexRunner.ownsPid(pid, describeProcess);
|
|
1429
|
-
}
|
|
1430
|
-
|
|
1431
|
-
// Ends a worker and, on Windows, its whole process tree: the direct child there
|
|
1432
|
-
// is the JS wrapper around the native Codex binary, so terminating it alone
|
|
1433
|
-
// would leave the real CLI running and the task stuck in `running`.
|
|
1434
|
-
function terminateChild(child) {
|
|
1435
|
-
codexRunner.cancelChild(child);
|
|
1436
|
-
}
|
|
1437
|
-
|
|
1438
|
-
function terminatePid(pid) {
|
|
1439
|
-
codexRunner.cancelPid(pid);
|
|
1440
|
-
}
|
|
1441
|
-
|
|
1442
|
-
export async function cancelCodexWorker(taskId) {
|
|
1443
|
-
const acceptance = acceptanceRuns.get(taskId);
|
|
1444
|
-
if (acceptance) {
|
|
1445
|
-
acceptance.cancelled = true;
|
|
1446
|
-
acceptance.kill?.();
|
|
1447
|
-
return { cancelled: true, via: "acceptance", pid: null };
|
|
1448
|
-
}
|
|
1449
|
-
const child = processes.get(taskId);
|
|
1450
|
-
if (child) {
|
|
1451
|
-
cancelledTasks.add(taskId);
|
|
1452
|
-
terminateChild(child);
|
|
1453
|
-
return { cancelled: true, via: "process_handle", pid: child.pid ?? null };
|
|
1454
|
-
}
|
|
1455
|
-
// Another MCP process owns the handle; fall back to the pid recorded on disk.
|
|
1456
|
-
const task = await getTask(taskId);
|
|
1457
|
-
if (task?.acceptance_results?.status === "running" && await isPidAlive(task.acceptance_results.supervisor_pid)) {
|
|
1458
|
-
await upsertTask({ ...task, cancel_requested_at: new Date().toISOString(), updated_at: new Date().toISOString() });
|
|
1459
|
-
return { cancelled: true, via: "acceptance", pid: null };
|
|
1460
|
-
}
|
|
1461
|
-
if (task?.pid && (await isPidAlive(task.pid)) && isLikelyCodexProcess(task.pid)) {
|
|
1462
|
-
try {
|
|
1463
|
-
terminatePid(task.pid);
|
|
1464
|
-
return { cancelled: true, via: "pid", pid: task.pid };
|
|
1465
|
-
} catch (error) {
|
|
1466
|
-
return { cancelled: false, reason: "kill_failed", message: error.message, pid: task.pid };
|
|
1467
|
-
}
|
|
1468
|
-
}
|
|
1469
|
-
return { cancelled: false, reason: "process_not_found" };
|
|
1470
|
-
}
|
|
1471
|
-
|
|
1472
|
-
async function isPidAlive(pid) {
|
|
1473
|
-
if (!pid) return false;
|
|
1474
|
-
try {
|
|
1475
|
-
process.kill(pid, 0);
|
|
1476
|
-
return true;
|
|
1477
|
-
} catch {
|
|
1478
|
-
return false;
|
|
1479
|
-
}
|
|
1480
|
-
}
|
|
1481
|
-
|
|
1482
|
-
export async function createFollowupWorker({
|
|
1483
|
-
taskId,
|
|
1484
|
-
followupPrompt,
|
|
1485
|
-
sessionId = null,
|
|
1486
|
-
sessionTitle = null,
|
|
1487
|
-
sessionNote = null,
|
|
1488
|
-
title,
|
|
1489
|
-
cwd,
|
|
1490
|
-
sandbox,
|
|
1491
|
-
model,
|
|
1492
|
-
reasoningEffort,
|
|
1493
|
-
ownedPaths,
|
|
1494
|
-
goal,
|
|
1495
|
-
baseRef,
|
|
1496
|
-
acceptance,
|
|
1497
|
-
acceptanceTimeoutMs,
|
|
1498
|
-
forbid,
|
|
1499
|
-
allowedCommands,
|
|
1500
|
-
context,
|
|
1501
|
-
contracts,
|
|
1502
|
-
externalOutputs,
|
|
1503
|
-
networkAccess,
|
|
1504
|
-
writableRoots,
|
|
1505
|
-
maxRunMs,
|
|
1506
|
-
maxTotalMs,
|
|
1507
|
-
workspaceKind,
|
|
1508
|
-
inPlaceAuthorization,
|
|
1509
|
-
workspaceSetup
|
|
1510
|
-
}) {
|
|
1511
|
-
const parent = await getTask(taskId);
|
|
1512
|
-
if (!parent) throw new Error(`task not found: ${taskId}`);
|
|
1513
|
-
let inheritedBaseRef = baseRef ?? null;
|
|
1514
|
-
if (!baseRef && !parent.landed_at && parent.project_root && parent.worktree_path) {
|
|
1515
|
-
try {
|
|
1516
|
-
resolveCommit(parent.project_root, `codex/${parent.id}`);
|
|
1517
|
-
inheritedBaseRef = `codex/${parent.id}`;
|
|
1518
|
-
} catch {
|
|
1519
|
-
const error = new Error(`parent checkpoint codex/${parent.id} is unavailable; restore it or choose an explicit baseRef`);
|
|
1520
|
-
error.code = "followup_checkpoint_missing";
|
|
1521
|
-
throw error;
|
|
1522
|
-
}
|
|
1523
|
-
}
|
|
1524
|
-
const recentEvents = await readTaskEvents(taskId, 20);
|
|
1525
|
-
const prompt = [
|
|
1526
|
-
"You are continuing a previous Codex worker run.",
|
|
1527
|
-
"",
|
|
1528
|
-
`Parent task ID: ${parent.id}`,
|
|
1529
|
-
`Parent status: ${parent.status}`,
|
|
1530
|
-
`Parent title: ${parent.title}`,
|
|
1531
|
-
"",
|
|
1532
|
-
"Parent prompt:",
|
|
1533
|
-
parent.prompt,
|
|
1534
|
-
"",
|
|
1535
|
-
"Parent recent summary:",
|
|
1536
|
-
`- current_action: ${parent.current_action ?? "-"}`,
|
|
1537
|
-
`- current_command: ${parent.current_command ?? "-"}`,
|
|
1538
|
-
`- changed_files: ${(parent.changed_files ?? []).join(", ") || "-"}`,
|
|
1539
|
-
`- last_message: ${parent.last_message ?? "-"}`,
|
|
1540
|
-
"",
|
|
1541
|
-
"Parent recent events:",
|
|
1542
|
-
...recentEvents.map((event) => `- ${JSON.stringify(event)}`),
|
|
1543
|
-
"",
|
|
1544
|
-
"Follow-up instruction:",
|
|
1545
|
-
followupPrompt
|
|
1546
|
-
].join("\n");
|
|
1547
|
-
|
|
1548
|
-
return createCodexWorker({
|
|
1549
|
-
title: title ?? `Follow-up for ${parent.id}`,
|
|
1550
|
-
task: prompt,
|
|
1551
|
-
sessionId: sessionId ?? parent.session_id ?? null,
|
|
1552
|
-
sessionTitle,
|
|
1553
|
-
sessionNote,
|
|
1554
|
-
cwd: cwd ?? parent.project_root ?? parent.cwd,
|
|
1555
|
-
sandbox: sandbox ?? parent.sandbox,
|
|
1556
|
-
model: model ?? parent.model,
|
|
1557
|
-
reasoningEffort: reasoningEffort ?? parent.reasoning_effort ?? "high",
|
|
1558
|
-
skipGitRepoCheck: parent.skip_git_repo_check,
|
|
1559
|
-
ownedPaths: ownedPaths ?? parent.owned_paths,
|
|
1560
|
-
forbid: forbid ?? parent.guard_policy?.forbid ?? [],
|
|
1561
|
-
allowedCommands: allowedCommands ?? parent.guard_policy?.allowedCommands ?? [],
|
|
1562
|
-
context: context ?? parent.input_context?.context ?? [],
|
|
1563
|
-
contracts: contracts ?? parent.input_context?.contracts ?? [],
|
|
1564
|
-
externalOutputs: externalOutputs ?? parent.guard_policy?.externalOutputs ?? [],
|
|
1565
|
-
networkAccess: networkAccess ?? parent.guard_policy?.networkAccess ?? false,
|
|
1566
|
-
writableRoots: writableRoots ?? parent.guard_policy?.writableRoots ?? [],
|
|
1567
|
-
maxRunMs: maxRunMs ?? parent.guard_policy?.maxRunMs ?? null,
|
|
1568
|
-
maxTotalMs: maxTotalMs ?? parent.guard_policy?.maxTotalMs ?? null,
|
|
1569
|
-
goal: goal ?? { objective: parent.goal_objective ?? `Follow-up for ${parent.id}`, tokenBudget: parent.goal_token_budget ?? undefined },
|
|
1570
|
-
dependsOn: [],
|
|
1571
|
-
followupOf: parent.id,
|
|
1572
|
-
workspaceKind: workspaceKind ?? (parent.workspace_kind === "legacy" ? null : parent.workspace_kind),
|
|
1573
|
-
inPlaceAuthorization: inPlaceAuthorization ?? parent.workspace_metadata?.in_place_authorization ?? null,
|
|
1574
|
-
workspaceSetup: workspaceSetup ?? parent.workspace_metadata?.setup ?? null,
|
|
1575
|
-
// A follow-up continues the same logical line of work. Start from the
|
|
1576
|
-
// parent branch so commits already made there are present; uncommitted
|
|
1577
|
-
// parent edits remain in the parent worktree and are deliberately not
|
|
1578
|
-
// smuggled across task boundaries.
|
|
1579
|
-
baseRef: inheritedBaseRef,
|
|
1580
|
-
// Inherited unless given; the follow-up runs in a fresh worktree cut
|
|
1581
|
-
// from the parent's codex/<parent> branch, so checks that depend on the
|
|
1582
|
-
// parent checkpoint are valid before the parent has landed on the target.
|
|
1583
|
-
acceptance: acceptance === undefined ? (parent.session_policy_revision == null ? parent.acceptance : parent.acceptance_local) : acceptance,
|
|
1584
|
-
acceptanceTimeoutMs: acceptanceTimeoutMs ?? parent.acceptance_timeout_ms ?? null
|
|
1585
|
-
});
|
|
1586
|
-
}
|