codex-supervisor-mcp 1.0.0 → 1.1.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.
@@ -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");
@@ -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();
@@ -45,5 +45,7 @@ if (!process.env.SUPERVISOR_HOME?.trim()) {
45
45
 
46
46
  // paths.js reads SUPERVISOR_HOME when it is first imported, so the import
47
47
  // has to come after the detection above.
48
+ const { installCrashGuard } = await import("../../infra/crash-guard.js");
49
+ installCrashGuard("web");
48
50
  const { startWebServer } = await import("../web/app.js");
49
51
  startWebServer({ storeOrigin });
@@ -3,6 +3,7 @@ import { ACTIVE_STATUSES } from "../../../domain/status.js";
3
3
  import { truncateEventStrings } from "../../../domain/truncate.js";
4
4
  import { getSession, upsertSession } from "../../../infra/store/sessions.js";
5
5
  import { getTask, readTasksBySession, searchTasks } from "../../../infra/store/tasks.js";
6
+ import { restoreEventBodies } from "../../../infra/store/event-body.js";
6
7
  import { listTaskEventKinds, readTaskEvents } from "../../../infra/store/events.js";
7
8
  import { errorResult, textResult } from "../result.js";
8
9
  import { acceptanceCheck } from "../schemas.js";
@@ -91,7 +92,9 @@ export const getCodexWorkerEventsOp = {
91
92
  handler: async ({ task_id, limit, maxChars, kinds }) => {
92
93
  const task = await getTask(task_id);
93
94
  if (!task) return textResult({ error: "task_not_found", task_id });
94
- const events = await readTaskEvents(task_id, limit, kinds ?? null);
95
+ const stored = await readTaskEvents(task_id, limit, kinds ?? null);
96
+ // Large bodies live in the run log only; max_chars then cuts the whole event, as it always did.
97
+ const events = await restoreEventBodies(stored, task.run_log);
95
98
  const trimmed = maxChars === undefined ? events : events.map((event) => truncateEventStrings(event, maxChars));
96
99
  return textResult({
97
100
  task_id,
@@ -2,6 +2,7 @@ import { acceptanceVerdict } from "../../../app/acceptance.js";
2
2
  import { ACTIVE_STATUSES } from "../../../domain/status.js";
3
3
  import { truncateEventStrings } from "../../../domain/truncate.js";
4
4
  import { getTasks } from "../../../infra/store/tasks.js";
5
+ import { restoreEventBodies } from "../../../infra/store/event-body.js";
5
6
  import { readTaskEvents } from "../../../infra/store/events.js";
6
7
  import { reconcileDetachedActiveTasks } from "../../../infra/store/reconcile.js";
7
8
  import { readTaskChanges } from "../../../infra/worktree.js";
@@ -63,9 +64,9 @@ function fullWorkerRows(tasks, { includeEvents, eventLimit, eventMaxChars, event
63
64
  tasks.map(async (task) => ({
64
65
  ...summarizeTask(task),
65
66
  recent_events: includeEvents
66
- ? await readTaskEvents(task.id, eventLimit, eventKinds ?? null).then((events) =>
67
- eventMaxChars === undefined ? events : events.map((event) => truncateEventStrings(event, eventMaxChars))
68
- )
67
+ ? await readTaskEvents(task.id, eventLimit, eventKinds ?? null)
68
+ .then((stored) => restoreEventBodies(stored, task.run_log))
69
+ .then((events) => (eventMaxChars === undefined ? events : events.map((event) => truncateEventStrings(event, eventMaxChars))))
69
70
  : undefined
70
71
  }))
71
72
  );
@@ -103,6 +104,7 @@ async function waitForWorkers(input, extra) {
103
104
  failed_count: tasks.filter((task) => task.status === "failed").length,
104
105
  cancelled_count: tasks.filter((task) => task.status === "cancelled").length,
105
106
  lost_count: tasks.filter((task) => task.status === "lost").length,
107
+ timed_out_count: tasks.filter((task) => task.status === "timed_out").length,
106
108
  active_count: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
107
109
  acceptance_failed_count: tasks.filter((task) => task.acceptance_results?.passed === false).length,
108
110
  workers: compact ? tasks.map(compactWorkerRow) : summaries
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import "../../app/compose.js";
3
+ import { installCrashGuard } from "../../infra/crash-guard.js";
3
4
  import { syncSkills } from "../../infra/skill-sync.js";
4
5
  import { packageVersion } from "./meta.js";
5
6
  import { refreshUpdateState, UPDATE_RECHECK_MS } from "./update-state.js";
@@ -11,6 +12,8 @@ import { factsTool, getArtifactTool, reviewTool } from "./tools/optional.js";
11
12
  import { askWorkerTool, describeSessionTool, findWorksTool, getWorkerDiffTool, getWorkerTool } from "./tools/read.js";
12
13
  import { pollWorkersTool, waitWorkersTool } from "./tools/track.js";
13
14
 
15
+ installCrashGuard("mcp-server");
16
+
14
17
  const server = new McpServer({
15
18
  name: "codex-supervisor",
16
19
  version: packageVersion
@@ -2,6 +2,7 @@
2
2
  import { branchOf } from "../../domain/worker-branch.js";
3
3
  import { ACTIVE_STATUSES } from "../../domain/status.js";
4
4
  import { supervisorRoot } from "../../infra/paths.js";
5
+ import { restoreEventBodies } from "../../infra/store/event-body.js";
5
6
  import { listTaskEventKinds, readAgentMessages, readTaskEvents } from "../../infra/store/events.js";
6
7
  import { reconcileDetachedActiveTasks } from "../../infra/store/reconcile.js";
7
8
  import { readSessions } from "../../infra/store/sessions.js";
@@ -221,5 +222,6 @@ export async function worker(taskId) {
221
222
  export async function events(taskId, url) {
222
223
  const limit = Math.min(1000, Math.max(1, Number(url.searchParams.get("limit") ?? 150)));
223
224
  const kinds = url.searchParams.get("kinds")?.split(",").filter(Boolean) ?? null;
224
- return { task_id: taskId, events: await readTaskEvents(taskId, limit, kinds) };
225
+ const task = await getTask(taskId);
226
+ return { task_id: taskId, events: await restoreEventBodies(await readTaskEvents(taskId, limit, kinds), task?.run_log ?? null) };
225
227
  }
@@ -4,8 +4,11 @@
4
4
  import "../app/compose.js";
5
5
  import { failedStart } from "../app/run-state.js";
6
6
  import { upsertTask } from "../infra/store/tasks.js";
7
+ import { installCrashGuard } from "../infra/crash-guard.js";
7
8
  import { trackRunInHost } from "./track.js";
8
9
 
10
+ installCrashGuard("run-host", { exitOnRejection: true });
11
+
9
12
  process.once("message", async (job) => {
10
13
  const keepAlive = setInterval(() => {}, 1000);
11
14
  let result;
@@ -27,6 +27,8 @@ function terminalStatus(run, stored, code, signal) {
27
27
  if (stored && TERMINAL_STATUSES.has(stored.status) && stored.status !== live.status) return stored.status;
28
28
  if (run.terminalEvent && TERMINAL_STATUSES.has(live.status)) return live.status;
29
29
  if (cancelRequested) return "cancelled";
30
+ // The supervisor stopped it for running out of time; the signal was its own.
31
+ if (run.quotaReason) return "timed_out";
30
32
  // Killed by a signal nobody asked for: the worker did not fail, it
31
33
  // vanished. Re-running is the fix, so it is reported as lost.
32
34
  if (signal) return "lost";
@@ -117,8 +119,13 @@ async function attachEvidence(run, next) {
117
119
  })).digest("hex");
118
120
  }
119
121
 
120
- function flagAttention(run, next, status, code) {
122
+ // "The evidence could not be read" outranks what the evidence would have
123
+ // said: no_work and invalid_report are both conclusions drawn from it.
124
+ const UNVERIFIED = new Set(["external_output_unverified", "workspace_manifest_unverified"]);
125
+
126
+ export function flagAttention(run, next, status, code) {
121
127
  const { live } = run;
128
+ if (UNVERIFIED.has(next.attention_reason)) return;
122
129
  if (status === "completed" && code === 0 && live.sandbox !== "read-only"
123
130
  && !next.run_evidence.output_changed && next.run_evidence.output_changed !== null
124
131
  && live.commands.length === 0 && !run.reportOnlyRecovery) {
@@ -21,6 +21,8 @@ export function startingRow(record, child, outputSchema, now) {
21
21
  exit_code: null,
22
22
  signal: null,
23
23
  error: null,
24
+ // What an earlier run wrote to stderr says nothing about how this one ends.
25
+ stderr_tail: null,
24
26
  cancel_requested_at: null,
25
27
  acceptance_results: null,
26
28
  attention_reason: null,
@@ -5,19 +5,40 @@ import { appendTaskEvents } from "../infra/store/events.js";
5
5
  import { codexRunner } from "../runners/codex/adapter.js";
6
6
  import { persist } from "./live-run.js";
7
7
 
8
+ const STDERR_KEEP = 64 * 1024;
9
+
10
+ // Resolves once the line is handed to the file, false when it was not.
11
+ function logLine(run, text) {
12
+ const offset = run.logOffset;
13
+ run.logOffset += Buffer.byteLength(text, "utf8");
14
+ const written = new Promise((resolveWrite) => {
15
+ run.logStream.write(text, (error) => {
16
+ if (error) run.logFailed = true;
17
+ resolveWrite(!error);
18
+ });
19
+ });
20
+ return { offset, written };
21
+ }
22
+
8
23
  async function handleLines(run, lines) {
9
24
  const events = [];
25
+ const logged = [];
10
26
  for (const line of lines) {
11
27
  try {
12
28
  const event = JSON.parse(line);
13
- run.logStream.write(`${JSON.stringify(event)}\n`);
29
+ logged.push(logLine(run, `${JSON.stringify(event)}\n`));
14
30
  events.push(event);
15
31
  } catch (error) {
16
- run.logStream.write(`${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
32
+ logLine(run, `${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
17
33
  }
18
34
  }
19
35
  if (events.length === 0) return;
20
- const storedEvents = await appendTaskEvents(run.record.id, events, { runId: run.runId, actor: "codex" });
36
+ // The store keeps only a clipped copy of a large event when the log has the
37
+ // whole of it, so the log comes first and a failed write keeps the event whole.
38
+ const inLog = (await Promise.all(logged.map((entry) => entry.written))).every(Boolean) && !run.logFailed;
39
+ const storedEvents = await appendTaskEvents(run.record.id, events, {
40
+ runId: run.runId, actor: "codex", bodyInLog: inLog, logOffsets: logged.map((entry) => entry.offset)
41
+ });
21
42
  let next = run.live;
22
43
  for (const [index, event] of events.entries()) {
23
44
  if (event.type === "item.completed" && event.item?.type === "agent_message") {
@@ -59,9 +80,11 @@ export function attachStreams(run, earlyOutput) {
59
80
  child.stdout.on("data", handleStdoutChunk);
60
81
  child.stdout.on("error", () => {});
61
82
 
62
- run.stderr = earlyOutput.stderr.map((chunk) => chunk.toString("utf8")).join("");
83
+ run.stderr = earlyOutput.stderr.map((chunk) => chunk.toString("utf8")).join("").slice(-STDERR_KEEP);
63
84
  child.stderr.on("data", (chunk) => {
64
- run.stderr += chunk.toString("utf8");
85
+ // Only the tail is ever used, so only the tail is kept: a worker that
86
+ // logs for hours must not grow this process without bound.
87
+ run.stderr = (run.stderr + chunk.toString("utf8")).slice(-STDERR_KEEP);
65
88
  persist(run, { ...run.live, stderr_tail: run.stderr.slice(-4000), updated_at: new Date().toISOString() });
66
89
  });
67
90
  child.stderr.on("error", () => {});
@@ -14,7 +14,7 @@ import { finalizeChild } from "./finalize.js";
14
14
  import { buildLaunch } from "./launch.js";
15
15
  import { persist, startingRow, watchQuota } from "./live-run.js";
16
16
  import { attachStreams } from "./streams.js";
17
- import { createWriteStream } from "node:fs";
17
+ import { createWriteStream, statSync } from "node:fs";
18
18
 
19
19
  // Spawn can fail either by throwing synchronously, or by emitting "error"
20
20
  // instead of "spawn". Both paths are handled so a bad CODEX_BIN marks the task
@@ -108,8 +108,11 @@ export async function trackRunInHost({ record, args, prompt, logPath, spawnOptio
108
108
  run.quotaWatch = watchQuota(run, now);
109
109
  await persist(run, run.live);
110
110
  run.runId = await ensureRunRecord(run.live, run.live.run_count);
111
+ // Where the next line will start, so a stored event can say where its full body is.
112
+ run.logOffset = statSync(logPath, { throwIfNoEntry: false })?.size ?? 0;
111
113
  run.logStream = createWriteStream(logPath, { flags: "a" });
112
- run.logStream.on("error", () => {});
114
+ // A log that cannot be written is not the place to keep the only copy of anything.
115
+ run.logStream.on("error", () => { run.logFailed = true; });
113
116
  child.stdin.on("error", (error) => { noteStdinFailure(run, error); });
114
117
  attachStreams(run, earlyOutput);
115
118