codex-supervisor-mcp 1.0.0 → 1.2.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.
Files changed (53) hide show
  1. package/README.en.md +6 -1
  2. package/README.md +6 -1
  3. package/package.json +2 -2
  4. package/skills/codex-supervisor/SKILL.md +4 -2
  5. package/src/app/cancel.js +11 -14
  6. package/src/app/cleanup-facts.js +14 -12
  7. package/src/app/cleanup-plan.js +19 -18
  8. package/src/app/compose.js +13 -3
  9. package/src/app/dispatch.js +12 -12
  10. package/src/app/followup.js +5 -0
  11. package/src/app/resume.js +15 -18
  12. package/src/app/side-chat.js +41 -20
  13. package/src/app/worktree-setup.js +43 -2
  14. package/src/domain/failure-class.js +34 -2
  15. package/src/domain/prompt.js +7 -3
  16. package/src/domain/status.js +8 -4
  17. package/src/domain/worker-preflight.js +6 -2
  18. package/src/infra/crash-guard.js +44 -0
  19. package/src/infra/git.js +35 -4
  20. package/src/infra/stage-store.js +1 -1
  21. package/src/infra/store/event-body.js +82 -0
  22. package/src/infra/store/events.js +7 -5
  23. package/src/infra/store/runner-readers.js +1 -1
  24. package/src/infra/store/tasks.js +15 -1
  25. package/src/infra/worktree.js +25 -5
  26. package/src/interface/bin/web-server.js +2 -0
  27. package/src/interface/mcp/handlers/dispatch.js +3 -0
  28. package/src/interface/mcp/handlers/overview.js +4 -1
  29. package/src/interface/mcp/handlers/results.js +11 -4
  30. package/src/interface/mcp/handlers/wait.js +5 -3
  31. package/src/interface/mcp/server.js +3 -0
  32. package/src/interface/mcp/tools/dispatch.js +7 -5
  33. package/src/interface/mcp/tools/shapes.js +1 -0
  34. package/src/interface/web/app.js +2 -2
  35. package/src/interface/web/views.js +5 -3
  36. package/src/run-host/entry.js +3 -0
  37. package/src/run-host/finalize.js +8 -1
  38. package/src/run-host/launch.js +5 -19
  39. package/src/run-host/live-run.js +4 -1
  40. package/src/run-host/streams.js +35 -9
  41. package/src/run-host/track.js +8 -4
  42. package/src/runners/claude/adapter.js +118 -0
  43. package/src/runners/claude/events.js +100 -0
  44. package/src/runners/claude/tool-guard.js +48 -0
  45. package/src/runners/codex/adapter.js +57 -0
  46. package/src/runners/codex/mcp-config.js +4 -0
  47. package/src/runners/contract-check.js +82 -0
  48. package/src/runners/contract.js +53 -0
  49. package/src/runners/registry.js +45 -0
  50. package/web/dist/assets/{index-fJQbspTY.js → index-BnV-AYYI.js} +1 -1
  51. package/web/dist/assets/index-f8esISCp.css +2 -0
  52. package/web/dist/index.html +2 -2
  53. package/web/dist/assets/index-DI1hLMxE.css +0 -2
@@ -26,9 +26,9 @@ import { ensureTaskWorktree } from "./restore-worktree.js";
26
26
  import "./compose.js";
27
27
  import { answerOf, partsFromChunks, turnView } from "../domain/side-turn-view.js";
28
28
  import { closeSideSession, getSideSession, insertSideTurn, interruptRunningSideTurns, openSideSession, readSideTurns, setSideSessionFork, updateSideTurn } from "../infra/store/sessions.js";
29
- import { codexRunner } from "../runners/codex/adapter.js";
30
- import { chunksFor } from "../runners/codex/chat-chunks.js";
31
- import { codexConfigText, disableMcpServerArgs } from "../runners/codex/mcp-config.js";
29
+ import { getTask } from "../infra/store/tasks.js";
30
+ import { unsupported } from "../runners/contract.js";
31
+ import { loadRunner, runnerOf } from "../runners/registry.js";
32
32
  import { endStream, sseHead, writeChunk } from "./sse.js";
33
33
  import { randomUUID } from "node:crypto";
34
34
 
@@ -55,12 +55,9 @@ export function sideQuestionText(question) {
55
55
  // Codex config is switched off for the turn. Sub-tables
56
56
  // ([mcp_servers.x.env]) are not servers and are skipped.
57
57
  //
58
- // The key path is written bare: `-c mcp_servers.name.enabled=false`. A
59
- // quoted name (`mcp_servers."name".enabled`) is taken by codex as a new
60
- // server literally called "name", quotes included, with no transport, and
61
- // the whole config then fails to load.
62
- export function sideTurnConfigArgs(configText) {
63
- return disableMcpServerArgs(configText);
58
+ // A side question runs with none of the user's MCP servers: it only reads.
59
+ export function sideTurnConfigArgs(configText, runner = runnerOf(null)) {
60
+ return runner.sideChat.disableMcpServerArgs(configText);
64
61
  }
65
62
 
66
63
  // The session to ask on. A fork taken before the worker was resumed no
@@ -141,10 +138,12 @@ export function attachToTurn(taskId, res) {
141
138
  }
142
139
 
143
140
  function startSideChild(target, task, session) {
144
- const args = codexRunner.forkSideArgs({ forkThreadId: session.fork_thread_id, workerThreadId: task.thread_id, model: task.model });
145
- args.splice(-2, 0, ...sideTurnConfigArgs(codexConfigText()));
141
+ const runner = runnerOf(task);
142
+ const side = runner.sideChat;
143
+ const forkArgs = side.forkArgs({ forkThreadId: session.fork_thread_id, workerThreadId: task.thread_id, model: task.model });
144
+ const args = side.withConfig(forkArgs, sideTurnConfigArgs(side.configText(), runner));
146
145
  const cwd = task.worktree_path || task.project_root || process.cwd();
147
- return codexRunner.start(target, args, {
146
+ return runner.start(target, args, {
148
147
  cwd,
149
148
  stdio: ["pipe", "pipe", "pipe"],
150
149
  env: { ...process.env, NO_COLOR: "1" },
@@ -158,7 +157,8 @@ async function openLiveTurn(task, text, child) {
158
157
  const turnId = `turn-${Date.now()}-${randomUUID().slice(0, 8)}`;
159
158
  const startedAt = new Date().toISOString();
160
159
  const state = { toolsSeen: new Set(), completed: false, failed: false, usage: null };
161
- const live = { turnId, child, chunks: [], watchers: new Set(), startedAt, question: text, state, stderr: "", stoppedBy: null, persistTimer: null };
160
+ const live = { turnId, child, chunks: [], watchers: new Set(), startedAt, question: text, state, stderr: "", stoppedBy: null, persistTimer: null,
161
+ chunksFor: runnerOf(task).sideChat.chunksFor };
162
162
  const persistSoon = () => {
163
163
  if (live.persistTimer) return;
164
164
  live.persistTimer = setTimeout(() => {
@@ -173,7 +173,7 @@ async function openLiveTurn(task, text, child) {
173
173
  };
174
174
  live.stop = (reason) => {
175
175
  live.stoppedBy = reason;
176
- codexRunner.cancelChild(child);
176
+ runnerOf(task).cancelChild(child);
177
177
  };
178
178
  running.set(task.id, live);
179
179
  await insertSideTurn({ id: turnId, task_id: task.id, question: text, status: "running", chunks: [], started_at: startedAt });
@@ -200,7 +200,7 @@ function pipeSideOutput(child, live, session, taskId) {
200
200
  session.fork_thread_id = event.thread_id;
201
201
  setSideSessionFork(taskId, event.thread_id).catch(() => {});
202
202
  }
203
- for (const part of chunksFor(event, live.state)) live.broadcast(part);
203
+ for (const part of live.chunksFor(event, live.state)) live.broadcast(part);
204
204
  }
205
205
  });
206
206
  child.stderr.setEncoding("utf8");
@@ -234,13 +234,30 @@ async function settleSideTurn(live, taskId, code, signal) {
234
234
  return status;
235
235
  }
236
236
 
237
+ // For a caller that only wants to know whether to offer the question box.
238
+ export function supportsSideChat(task) {
239
+ try {
240
+ return runnerOf(task).capabilities.side_chat === true;
241
+ } catch {
242
+ return false; // a runner this process has not loaded
243
+ }
244
+ }
245
+
246
+ // Checked before a session row is opened, so a runner without a side chat leaves nothing behind.
247
+ export async function requireSideChat(task) {
248
+ const runner = await loadRunner(task.worker);
249
+ if (!runner.capabilities.side_chat) throw unsupported(runner, "side_chat", "asking a worker a side question");
250
+ return runner;
251
+ }
252
+
237
253
  // Start a turn. `res` (optional) becomes the first watcher. Resolves when the
238
254
  // turn has ended, however it ended.
239
255
  export async function runSideTurn({ task, text, res = null, fresh = false }) {
240
256
  await sweepOnce();
241
- if (!task.thread_id) throw Object.assign(new Error("this worker recorded no thread_id, so there is no Codex thread to fork"), { code: "no_thread" });
257
+ const runner = await requireSideChat(task);
258
+ if (!task.thread_id) throw Object.assign(new Error("this worker recorded no thread_id, so there is no thread to fork"), { code: "no_thread" });
242
259
  if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
243
- const target = codexRunner.resolveTarget();
260
+ const target = runner.resolveTarget();
244
261
  if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
245
262
 
246
263
  const { session, refreshed } = await prepareSideSession(task, { fresh });
@@ -296,6 +313,7 @@ export async function latestSideTurn(taskId) {
296
313
  export async function askWorker({ task, question, timeoutMs = 110000, fresh = false }) {
297
314
  // Decided here, before the race, so a turn that outruns the budget still
298
315
  // reports whether the fork was taken anew.
316
+ await requireSideChat(task);
299
317
  const { refreshed } = await prepareSideSession(task, { fresh });
300
318
  const turn = runSideTurn({ task, text: question });
301
319
  // runSideTurn throws synchronously-ish (rejected promise) for no_thread,
@@ -334,12 +352,15 @@ export async function endSideSession(taskId) {
334
352
  if (!row) return { ended: false };
335
353
  let deleted = false;
336
354
  if (row.fork_thread_id) {
337
- const target = codexRunner.resolveTarget();
355
+ // The task may be gone and its runner not loaded here; then the fork is left to the CLI's own housekeeping.
356
+ const stored = await getTask(taskId);
357
+ const runner = stored ? await loadRunner(stored.worker).catch(() => null) : null;
358
+ const target = runner?.capabilities.side_chat ? runner.resolveTarget() : { error: "no runner" };
338
359
  if (!target.error) {
339
360
  deleted = await new Promise((resolve) => {
340
361
  // --force: without a terminal codex asks for confirmation and exits.
341
- const child = codexRunner.start(target, ["delete", "--force", row.fork_thread_id], { stdio: "ignore", windowsHide: true, env: { ...process.env, NO_COLOR: "1" } });
342
- const t = setTimeout(() => { codexRunner.cancelChild(child); resolve(false); }, 15000);
362
+ const child = runner.start(target, runner.sideChat.deleteArgs(row.fork_thread_id), { stdio: "ignore", windowsHide: true, env: { ...process.env, NO_COLOR: "1" } });
363
+ const t = setTimeout(() => { runner.cancelChild(child); resolve(false); }, 15000);
343
364
  child.on("exit", (code) => { clearTimeout(t); resolve(code === 0); });
344
365
  child.on("error", () => { clearTimeout(t); resolve(false); });
345
366
  });
@@ -3,11 +3,12 @@ import { gitBin, runGit } from "../infra/git.js";
3
3
  import { worktreesDir } from "../infra/paths.js";
4
4
  import { runToExit } from "../infra/process.js";
5
5
  import { resolveWritableRoot } from "../infra/sandbox-roots.js";
6
+ import { isPidAlive } from "../infra/store/tasks.js";
6
7
  import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, runAcceptance } from "./acceptance.js";
7
8
  import { WORKTREE_LOCK_TIMEOUT_MS } from "./run-state.js";
8
9
  import { createHash } from "node:crypto";
9
10
  import { existsSync } from "node:fs";
10
- import { lstat, mkdir, realpath, rm, stat, symlink } from "node:fs/promises";
11
+ import { lstat, mkdir, readFile, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
11
12
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
12
13
 
13
14
  export function splitLines(buffer, chunk) {
@@ -155,6 +156,44 @@ function sleep(ms) {
155
156
  return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
156
157
  }
157
158
 
159
+ // A lock whose holder died would otherwise stay for good: nothing else
160
+ // removes it, and every later dispatch into that repository would time out.
161
+ // The holder writes its pid into the lock; a waiter that finds the pid dead
162
+ // takes the lock away by renaming it, which only one waiter can win.
163
+ const LOCK_UNCLAIMED_MS = 10000;
164
+
165
+ async function lockIsAbandoned(lockPath) {
166
+ let owner;
167
+ try {
168
+ owner = Number(await readFile(join(lockPath, "owner"), "utf8"));
169
+ } catch (error) {
170
+ // Only a missing file means "not written yet"; anything else is a lock we cannot judge.
171
+ if (error.code !== "ENOENT") return false;
172
+ owner = 0;
173
+ }
174
+ if (owner) return !isPidAlive(owner);
175
+ // No owner yet: either the holder is between mkdir and its write, or it
176
+ // died there. Age tells them apart.
177
+ const info = await stat(lockPath).catch(() => null);
178
+ return Boolean(info) && Date.now() - info.mtimeMs > LOCK_UNCLAIMED_MS;
179
+ }
180
+
181
+ async function breakAbandonedLock(lockPath) {
182
+ const aside = `${lockPath}.${process.pid}.${Date.now()}.stale`;
183
+ try {
184
+ await rename(lockPath, aside);
185
+ } catch {
186
+ return; // someone else broke it, or the holder released it
187
+ }
188
+ // Between the check and the rename another waiter may have broken the lock
189
+ // and taken a fresh one, which is then what was moved. It goes back.
190
+ if (!await lockIsAbandoned(aside)) {
191
+ await rename(aside, lockPath).catch(() => {});
192
+ return;
193
+ }
194
+ await rm(aside, { recursive: true, force: true }).catch(() => {});
195
+ }
196
+
158
197
  export async function withWorktreeCreationLock(cwd, work) {
159
198
  const lockName = `create-${createHash("sha256").update(resolve(cwd)).digest("hex").slice(0, 24)}.lock`;
160
199
  const lockPath = join(worktreesDir, lockName);
@@ -166,10 +205,12 @@ export async function withWorktreeCreationLock(cwd, work) {
166
205
  break;
167
206
  } catch (error) {
168
207
  if (error.code !== "EEXIST" || Date.now() >= deadline) throw new Error(`worktree creation lock timed out for ${cwd}`, { cause: error });
169
- await sleep(100);
208
+ if (await lockIsAbandoned(lockPath)) await breakAbandonedLock(lockPath);
209
+ else await sleep(100);
170
210
  }
171
211
  }
172
212
  try {
213
+ await writeFile(join(lockPath, "owner"), String(process.pid));
173
214
  return await work();
174
215
  } finally {
175
216
  await rm(lockPath, { recursive: true, force: true }).catch(() => {});
@@ -7,6 +7,36 @@ function providerFailure(text) {
7
7
  return { source: "provider", code: status ? `provider_http_${status}` : "provider_error", retryable };
8
8
  }
9
9
 
10
+ // "codex exited with code 1" says only that the process ended badly. The
11
+ // reason is whatever it last wrote to stderr, so that is read for the causes a
12
+ // caller acts on differently: fix the login, wait for the provider, fix the
13
+ // configuration. The last line is passed on either way.
14
+ const lastLine = (text) => text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).at(-1)?.slice(0, 300) ?? null;
15
+
16
+ function processExitFailure(stderr) {
17
+ const detail = lastLine(stderr);
18
+ const withDetail = (failure) => (detail ? { ...failure, detail } : failure);
19
+ // A bare 401 is also a line number or a millisecond; it counts only next to a word that makes it a status.
20
+ if (/(?:http|status|code|error)\D{0,8}(?:401|403)\b|unauthori[sz]ed|not logged in|login required|invalid api key|missing api key|forbidden/i.test(stderr)) {
21
+ return withDetail({ source: "auth", code: "auth_failed", retryable: false });
22
+ }
23
+ // A process of an earlier run still holds the session; it clears when that process ends.
24
+ if (/already has an active writer|thread-store conflict/i.test(stderr)) return withDetail({ source: "runner_session", code: "session_busy", retryable: true });
25
+ // The specific causes first: the general provider match answers to the word "provider" alone.
26
+ if (/(?:http|status|code|error)\D{0,8}429\b|rate.?limit|too many requests/i.test(stderr)) {
27
+ return withDetail({ source: "provider", code: "provider_rate_limited", retryable: true });
28
+ }
29
+ if (/ECONNREFUSED|ECONNRESET|ENOTFOUND|ETIMEDOUT|error sending request|connection (refused|reset|closed)|stream disconnected|dns error/i.test(stderr)) {
30
+ return withDetail({ source: "provider", code: "provider_unreachable", retryable: true });
31
+ }
32
+ const provider = providerFailure(stderr);
33
+ if (provider) return withDetail(provider);
34
+ if (/config\.toml|unknown model|model .{0,80}(not found|does not exist|not supported)|unexpected argument|invalid value/i.test(stderr)) {
35
+ return withDetail({ source: "runner_config", code: "config_invalid", retryable: false });
36
+ }
37
+ return withDetail({ source: "worker_process", code: "process_exit_nonzero", retryable: true });
38
+ }
39
+
10
40
  export function classifyFailure(task) {
11
41
  if (!task) return null;
12
42
  const error = String(task.error ?? "");
@@ -21,10 +51,12 @@ export function classifyFailure(task) {
21
51
  if (attention === "invalid_report" || /Invalid final worker report/i.test(error)) return { source: "model_output", code: "invalid_report", retryable: true };
22
52
  if (task.acceptance_results?.passed === false) return { source: "acceptance", code: "acceptance_failed", retryable: true };
23
53
  if (attention === "no_work" || attention === "two_stall") return { source: "worker_progress", code: attention, retryable: false };
24
- if (attention === "time_limit" || attention === "total_time_limit") return { source: "supervisor_process", code: attention, retryable: false };
54
+ if (task.status === "timed_out" || attention === "run_time_limit" || attention === "total_time_limit") {
55
+ return { source: "time_limit", code: attention || "time_limit", retryable: false };
56
+ }
25
57
  if (task.status === "lost") return { source: "supervisor_process", code: "worker_lost", retryable: true };
26
58
  if (task.status === "cancelled") return { source: "caller", code: "cancelled", retryable: true };
27
- if (/codex exited with code/i.test(error)) return { source: "worker_process", code: "process_exit_nonzero", retryable: true };
59
+ if (/codex exited with code/i.test(error)) return processExitFailure(String(task.stderr_tail ?? ""));
28
60
  if (isGoalNeedingAttention(task.goal_status)) return { source: "goal", code: `goal_${task.goal_status}`, retryable: false };
29
61
  if (task.status === "failed") return { source: "unknown", code: "failed", retryable: null };
30
62
  return null;
@@ -116,7 +116,7 @@ export function buildReportPreamble({ resume = false, acceptance = null, outputS
116
116
  }
117
117
  return withAcceptance([
118
118
  "Final report (your last message), under 2000 characters, in the language of the task. Quoted command output does not count toward the limit.",
119
- `Return JSON with exactly result:string, verification:string[], not_done:string[]; ${outputSchema ? "--output-schema enforces these fields" : "no output schema is active, so follow this shape exactly"}. Cover the following content in those fields.`,
119
+ `Return JSON with exactly result:string, verification:string[], not_done:string[]; ${outputSchema ? "an output schema enforces these fields" : "no output schema is active, so follow this shape exactly"}. Cover the following content in those fields.`,
120
120
  "Write that JSON value on its own: no markdown code fences and nothing before or after it.",
121
121
  "Keep each verification entry concise: command name, exit code and key evidence; avoid embedding long quoted shell source. Ensure arrays and the object are fully closed and all strings use valid JSON escaping.",
122
122
  "1. Result: what is done, in two or three sentences. Say plainly what is not done.",
@@ -134,8 +134,12 @@ export function withGoalPreamble(prompt, goalOptions) {
134
134
  }
135
135
 
136
136
  // The whole frame: goal in front, task text, report format at the end.
137
- export function frameWorkerPrompt(prompt, goalOptions, { acceptance = null, outputSchema = true } = {}) {
138
- return `${withGoalPreamble(prompt, goalOptions)}\n\n${buildReportPreamble({ resume: Boolean(goalOptions?.resume), acceptance, outputSchema })}`;
137
+ // nativeGoal false is a CLI with no goal of its own: it is told the objective
138
+ // in a line, not to call goal tools it does not have.
139
+ export function frameWorkerPrompt(prompt, goalOptions, { acceptance = null, outputSchema = true, nativeGoal = true } = {}) {
140
+ const plainObjective = !goalOptions?.resume && goalOptions?.objective ? `Objective: ${goalOptions.objective}\n\n${prompt}` : prompt;
141
+ const framed = nativeGoal ? withGoalPreamble(prompt, goalOptions) : plainObjective;
142
+ return `${framed}\n\n${buildReportPreamble({ resume: Boolean(goalOptions?.resume), acceptance, outputSchema })}`;
139
143
  }
140
144
 
141
145
  // Claude's native /goal owns its Stop condition. MCP cannot silently replace
@@ -4,13 +4,16 @@
4
4
  // phase = what the worker is doing right now. Only meaningful while
5
5
  // status === "running"; NULL once the work reaches a terminal status.
6
6
 
7
- export const TASK_STATUSES = ["queued", "running", "completed", "failed", "cancelled", "lost"];
7
+ // timed_out is a worker the supervisor stopped because its time budget ran
8
+ // out. It is not lost: nothing vanished, and re-running it unchanged would
9
+ // only run out of time again.
10
+ export const TASK_STATUSES = ["queued", "running", "completed", "failed", "cancelled", "lost", "timed_out"];
8
11
 
9
12
  export const PHASES = ["starting", "thinking", "command", "editing", "reporting"];
10
13
 
11
14
  export const ACTIVE_STATUSES = new Set(["queued", "running"]);
12
15
 
13
- export const TERMINAL_STATUSES = new Set(["completed", "failed", "cancelled", "lost"]);
16
+ export const TERMINAL_STATUSES = new Set(["completed", "failed", "cancelled", "lost", "timed_out"]);
14
17
 
15
18
  // Codex native thread goal status -> work status.
16
19
  // Storage uses snake_case ("usage_limited"); the RPC layer uses camelCase
@@ -37,10 +40,11 @@ export function isGoalNeedingAttention(nativeStatus) {
37
40
  }
38
41
 
39
42
  // True once nothing of a worker's last run can still be running: its exit
40
- // code is recorded (the last thing a run host writes), or the row was marked
43
+ // code or the signal that ended it is recorded (the last thing a run host
44
+ // writes), or the row was marked
41
45
  // lost (done only after both processes were seen gone). From then on the pids
42
46
  // on the row are history. The system hands them to other processes, on
43
47
  // Windows within seconds, and a live stranger must not read as a live worker.
44
48
  export function runIsOver(task) {
45
- return task.status === "lost" || (TERMINAL_STATUSES.has(task.status) && task.exit_code != null);
49
+ return task.status === "lost" || (TERMINAL_STATUSES.has(task.status) && (task.exit_code != null || task.signal != null));
46
50
  }
@@ -1,3 +1,4 @@
1
+ import { TERMINAL_STATUSES } from "./status.js";
1
2
  import { createHash } from "node:crypto";
2
3
  import { resolve } from "node:path";
3
4
  import { commandFailed } from "./command-outcome.js";
@@ -63,9 +64,12 @@ export function buildRuntimeContract({
63
64
  contracts,
64
65
  workspaceSetup = null,
65
66
  workspaceKind = "git_worktree",
66
- workspaceManifestSha256 = null
67
+ workspaceManifestSha256 = null,
68
+ runner = "codex"
67
69
  }) {
68
70
  return stableValue({
71
+ // Named only when it is not the default, so contracts made before runners existed still match.
72
+ ...(runner && runner !== "codex" ? { runner } : {}),
69
73
  version: PREFLIGHT_VERSION,
70
74
  project_root: resolve(projectRoot),
71
75
  base_commit: baseCommit ?? null,
@@ -117,7 +121,7 @@ export function readPreflightResult(task) {
117
121
  passed: Boolean(result) && !commandFailed(result)
118
122
  };
119
123
  });
120
- const terminal = ["completed", "failed", "cancelled", "lost"].includes(task.status);
124
+ const terminal = TERMINAL_STATUSES.has(task.status);
121
125
  const failedCommands = commands.filter(commandFailed);
122
126
  const probesPassed = probes.every((probe) => probe.passed);
123
127
  const exitConfirmed = task.status === "completed" && task.exit_code === 0;
@@ -0,0 +1,44 @@
1
+ // Last line of defence for a long-lived process. Without it one promise that
2
+ // nobody awaited ends the MCP server, and every tool call after that answers
3
+ // "Connection closed" with no trace of why.
4
+ //
5
+ // A rejection nobody handled is written down and the process carries on: the
6
+ // state is in the store, not in memory, so the next call is as good as the
7
+ // last. A thrown exception is written down and the process exits, because
8
+ // after one the stack it interrupted cannot be trusted.
9
+ import { appendFileSync, mkdirSync, statSync, writeFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { dataDir } from "./paths.js";
12
+
13
+ export const crashLogPath = join(dataDir, "crash.log");
14
+ const MAX_BYTES = 1024 * 1024;
15
+
16
+ function record(role, kind, error) {
17
+ const text = error instanceof Error ? (error.stack ?? error.message) : String(error);
18
+ const line = `${JSON.stringify({ at: new Date().toISOString(), role, pid: process.pid, kind, error: text })}\n`;
19
+ process.stderr.write(`[agent-supervisor] ${role} ${kind}: ${text}\n`);
20
+ try {
21
+ mkdirSync(dataDir, { recursive: true });
22
+ const size = statSync(crashLogPath, { throwIfNoEntry: false })?.size ?? 0;
23
+ if (size > MAX_BYTES) writeFileSync(crashLogPath, line);
24
+ else appendFileSync(crashLogPath, line);
25
+ } catch (writeError) {
26
+ process.stderr.write(`[agent-supervisor] could not write ${crashLogPath}: ${writeError.message}\n`);
27
+ }
28
+ }
29
+
30
+ // role names the process in the log: "mcp-server", "run-host", "web".
31
+ //
32
+ // exitOnRejection is for the run host, whose state is in memory: the live run,
33
+ // the child, the write chains. Kept alive after a rejection it would hold its
34
+ // row at "running" for good, where a dead one is found and recovered by pid.
35
+ export function installCrashGuard(role, { exitOnRejection = false } = {}) {
36
+ process.on("unhandledRejection", (reason) => {
37
+ record(role, "unhandled_rejection", reason);
38
+ if (exitOnRejection) process.exit(1);
39
+ });
40
+ process.on("uncaughtException", (error) => {
41
+ record(role, "uncaught_exception", error);
42
+ process.exit(1);
43
+ });
44
+ }
package/src/infra/git.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // The only place that runs git. Callers differ in real ways (optional locks,
2
2
  // path quoting, what happens to stderr, whether output is trimmed), so those
3
3
  // are options here instead of one private copy per caller.
4
- import { execFileSync } from "node:child_process";
4
+ import { execFile, execFileSync } from "node:child_process";
5
5
 
6
6
  export const gitBin = () => process.env.GIT_BIN?.trim() || "git";
7
7
 
@@ -19,12 +19,43 @@ export function runGit(cwd, args, options = {}) {
19
19
  return trim && typeof output === "string" ? output.trim() : output;
20
20
  }
21
21
 
22
- // For questions git answers with its exit code, such as merge-base --is-ancestor.
22
+ // git that does not hold the event loop, for the paths that run many
23
+ // commands inside one request: cleanup walks every finished worktree during a
24
+ // poll. Takes the options runGit takes, apart from input and stderr.
25
+ export function runGitAsync(cwd, args, options = {}) {
26
+ const { timeout = 60000, noOptionalLocks = false, rawPaths = false, maxBuffer, env, trim = true } = options;
27
+ const argv = [...(noOptionalLocks ? ["--no-optional-locks"] : []), "-C", cwd, ...(rawPaths ? ["-c", "core.quotePath=false"] : []), ...args];
28
+ return new Promise((resolveRun, rejectRun) => {
29
+ execFile(gitBin(), argv, { encoding: "utf8", timeout, ...(maxBuffer ? { maxBuffer } : {}), ...(env ? { env } : {}) }, (error, stdout, stderr) => {
30
+ if (!error) return resolveRun(trim ? stdout.trim() : stdout);
31
+ error.message = `${error.message.split("\n")[0]}${stderr?.trim() ? `\n${stderr.trim()}` : ""}`;
32
+ rejectRun(error);
33
+ });
34
+ });
35
+ }
36
+
37
+ // A question git answers with its exit code, such as merge-base
38
+ // --is-ancestor. An exit code is an answer. A timeout, a signal or a git that
39
+ // could not be started is not "no", and reading it as one turns a slow disk
40
+ // into "this commit never landed", so those throw.
41
+ const answered = (error) => typeof (error.status ?? error.code) === "number";
42
+
23
43
  export function gitSucceeds(cwd, args, { timeout = 15000 } = {}) {
24
44
  try {
25
45
  execFileSync(gitBin(), ["-C", cwd, ...args], { stdio: "ignore", timeout });
26
46
  return true;
27
- } catch {
28
- return false;
47
+ } catch (error) {
48
+ if (answered(error)) return false;
49
+ throw error;
29
50
  }
30
51
  }
52
+
53
+ export function gitSucceedsAsync(cwd, args, { timeout = 15000 } = {}) {
54
+ return new Promise((resolveRun, rejectRun) => {
55
+ execFile(gitBin(), ["-C", cwd, ...args], { timeout }, (error) => {
56
+ if (!error) resolveRun(true);
57
+ else if (answered(error)) resolveRun(false);
58
+ else rejectRun(error);
59
+ });
60
+ });
61
+ }
@@ -3,7 +3,7 @@ import { join } from "node:path";
3
3
  import { stagesDir } from "./paths.js";
4
4
 
5
5
  function validate(taskId, stage, detail) {
6
- if (!/^codex-[A-Za-z0-9-]+$/.test(String(taskId ?? ""))) throw new Error("invalid task id for stage checkpoint");
6
+ if (!/^[a-z][a-z0-9-]*-[A-Za-z0-9-]+$/.test(String(taskId ?? ""))) throw new Error("invalid task id for stage checkpoint");
7
7
  const name = String(stage ?? "").trim();
8
8
  if (!name || name.length > 200) throw new Error("stage must be 1-200 characters");
9
9
  const note = detail == null ? null : String(detail).trim();
@@ -0,0 +1,82 @@
1
+ // A worker's output is written twice: the raw line to its JSONL log and the
2
+ // event to the store. Nearly all of the store's size was the second copy of
3
+ // command output. A large event from the worker now keeps only a clipped copy
4
+ // in the store, marked with the hash of the full line; the JSONL is the one
5
+ // place the full body lives, and it is read back from there on request.
6
+ //
7
+ // Kept whole whatever their size: the worker's messages and turn events, which
8
+ // the state machine and the result readers query, and everything the
9
+ // supervisor writes itself, which is in no log.
10
+ import { truncateEventStrings } from "../../domain/truncate.js";
11
+ import { extractAgentMessage } from "./runner-readers.js";
12
+ import { createHash } from "node:crypto";
13
+ import { createReadStream } from "node:fs";
14
+ import { createInterface } from "node:readline";
15
+
16
+ export const EVENT_INLINE_BYTES = 2048;
17
+ const CLIPPED_STRING_BYTES = 1024;
18
+ // The marker is the supervisor's, named so it cannot be taken for a field of the worker's event.
19
+ export const CLIP_KEY = "supervisor_clipped";
20
+
21
+ const sha256 = (text) => createHash("sha256").update(text).digest("hex");
22
+
23
+ function keptWhole(event) {
24
+ if (String(event.type ?? "").startsWith("turn.") || event.type === "thread.started") return true;
25
+ try {
26
+ return extractAgentMessage(event) != null;
27
+ } catch {
28
+ return true; // an event the runner cannot read is not ours to cut
29
+ }
30
+ }
31
+
32
+ // Returns what goes in the store for one event: { payload, sha256 }, where
33
+ // sha256 is always the hash of the full line as the log has it.
34
+ export function storedForm(event, { bodyInLog = false, offset = null } = {}) {
35
+ const full = JSON.stringify(event);
36
+ const hash = sha256(full);
37
+ const bytes = Buffer.byteLength(full, "utf8");
38
+ if (!bodyInLog || bytes <= EVENT_INLINE_BYTES || keptWhole(event)) return { payload: full, sha256: hash };
39
+ const clipped = JSON.stringify({ ...truncateEventStrings(event, CLIPPED_STRING_BYTES), [CLIP_KEY]: { stored: "jsonl", bytes, sha256: hash, offset } });
40
+ // An event made of many small strings does not shrink; marking it would only cost a log read later.
41
+ if (Buffer.byteLength(clipped, "utf8") > bytes / 2) return { payload: full, sha256: hash };
42
+ return { payload: clipped, sha256: hash };
43
+ }
44
+
45
+ const isClipped = (event) => event?.[CLIP_KEY]?.stored === "jsonl" && typeof event[CLIP_KEY].sha256 === "string";
46
+
47
+ // Collects the wanted lines from the log, reading from `start`.
48
+ async function scanLog(logPath, start, wanted, found) {
49
+ const lines = createInterface({ input: createReadStream(logPath, { encoding: "utf8", start }), crlfDelay: Infinity });
50
+ for await (const line of lines) {
51
+ if (Buffer.byteLength(line, "utf8") <= EVENT_INLINE_BYTES) continue;
52
+ const hash = sha256(line);
53
+ if (wanted.has(hash)) found.set(hash, line);
54
+ if (found.size === wanted.size) break;
55
+ }
56
+ }
57
+
58
+ // Puts the full bodies back from the log. The recorded offset says where to
59
+ // start, so reading the newest events does not mean reading the whole log; a
60
+ // line that is not where it was recorded is looked for once from the top. An
61
+ // event whose line cannot be found stays clipped and says so.
62
+ export async function restoreEventBodies(events, logPath) {
63
+ const clipped = events.filter(isClipped);
64
+ if (clipped.length === 0) return events;
65
+ const wanted = new Set(clipped.map((event) => event[CLIP_KEY].sha256));
66
+ const found = new Map();
67
+ if (logPath) {
68
+ try {
69
+ const offsets = clipped.map((event) => event[CLIP_KEY].offset);
70
+ const start = offsets.every((offset) => Number.isInteger(offset) && offset >= 0) ? Math.min(...offsets) : 0;
71
+ await scanLog(logPath, start, wanted, found);
72
+ if (found.size < wanted.size && start > 0) await scanLog(logPath, 0, wanted, found);
73
+ } catch {
74
+ // a log that is gone leaves the events clipped, marked below
75
+ }
76
+ }
77
+ return events.map((event) => {
78
+ if (!isClipped(event)) return event;
79
+ const line = found.get(event[CLIP_KEY].sha256);
80
+ return line ? JSON.parse(line) : { ...event, [CLIP_KEY]: { ...event[CLIP_KEY], missing: true } };
81
+ });
82
+ }
@@ -1,7 +1,7 @@
1
1
  import { branchOf } from "../../domain/worker-branch.js";
2
2
  import { ensureControlRecords, ensureFilesystem, openDb, runIdFor, runWithRetry, workItemIdForTask } from "./db.js";
3
+ import { storedForm } from "./event-body.js";
3
4
  import { extractAgentMessage } from "./runner-readers.js";
4
- import { createHash } from "node:crypto";
5
5
 
6
6
  export async function ensureRunRecord(task, attempt) {
7
7
  await ensureFilesystem();
@@ -51,7 +51,10 @@ export async function completeRunRecord(task, attempt) {
51
51
  }));
52
52
  }
53
53
 
54
- export async function appendTaskEvents(taskId, events, { runId = null, actor = "supervisor" } = {}) {
54
+ // bodyInLog: each event is already in the run log (the caller waited for the
55
+ // write), so a large one need not be kept whole here as well. logOffsets says
56
+ // where each line starts.
57
+ export async function appendTaskEvents(taskId, events, { runId = null, actor = "supervisor", bodyInLog = false, logOffsets = [] } = {}) {
55
58
  await ensureFilesystem();
56
59
  if (!Array.isArray(events) || events.length === 0) return [];
57
60
  const dbInstance = openDb();
@@ -65,9 +68,8 @@ export async function appendTaskEvents(taskId, events, { runId = null, actor = "
65
68
  `);
66
69
  const createdAt = new Date().toISOString();
67
70
  const records = events.map((event, index) => {
68
- const payload = JSON.stringify(event);
69
- const result = insert.run(taskId, runId, nextSeqRow.seq + index, createdAt, actor, event.type ?? "unknown", payload,
70
- createHash("sha256").update(payload).digest("hex"));
71
+ const stored = storedForm(event, { bodyInLog, offset: logOffsets[index] ?? null });
72
+ const result = insert.run(taskId, runId, nextSeqRow.seq + index, createdAt, actor, event.type ?? "unknown", stored.payload, stored.sha256);
71
73
  return { id: Number(result.lastInsertRowid), run_id: runId, actor };
72
74
  });
73
75
  dbInstance.exec("COMMIT");
@@ -12,5 +12,5 @@ export function registerRunnerReaders({ nativeGoal, agentMessage }) {
12
12
  readers.agentMessage = agentMessage;
13
13
  }
14
14
 
15
- export const readNativeGoal = (threadId) => readers.nativeGoal(threadId);
15
+ export const readNativeGoal = (threadId, runnerName) => readers.nativeGoal(threadId, runnerName);
16
16
  export const extractAgentMessage = (event) => readers.agentMessage(event);
@@ -9,7 +9,7 @@ import { join, resolve } from "node:path";
9
9
 
10
10
  export function rowToTask(row) {
11
11
  if (!row) return null;
12
- const nativeGoal = readNativeGoal(row.thread_id);
12
+ const nativeGoal = readNativeGoal(row.thread_id, row.worker);
13
13
  return {
14
14
  ...row,
15
15
  workspace_kind: row.workspace_kind ?? "legacy",
@@ -46,6 +46,20 @@ export function isPidAlive(pid) {
46
46
  }
47
47
  }
48
48
 
49
+ // The run host leads its own process group and the worker runs inside it. A
50
+ // worker CLI is often a launcher around the real binary, so the recorded pid
51
+ // can be gone while the binary is still writing to the session. True while
52
+ // anything in the group is left. Windows has no process groups.
53
+ export function isGroupAlive(leaderPid) {
54
+ if (!leaderPid || process.platform === "win32") return false;
55
+ try {
56
+ process.kill(-leaderPid, 0);
57
+ return true;
58
+ } catch (error) {
59
+ return error.code === "EPERM";
60
+ }
61
+ }
62
+
49
63
  export async function readTasks() {
50
64
  await ensureFilesystem();
51
65
  const rows = openDb().prepare("SELECT * FROM tasks ORDER BY created_at ASC").all();