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
@@ -12,8 +12,8 @@
12
12
  // base is the commit the worktree was created from.
13
13
  import { branchOf } from "../domain/worker-branch.js";
14
14
  import { runGit } from "./git.js";
15
- import { existsSync, readFileSync, lstatSync } from "node:fs";
16
- import { join, relative, resolve } from "node:path";
15
+ import { existsSync, lstatSync, readFileSync, realpathSync } from "node:fs";
16
+ import { basename, dirname, join, relative, resolve } from "node:path";
17
17
  import { truncateMiddleChars } from "../domain/truncate.js";
18
18
  import { createHash } from "node:crypto";
19
19
 
@@ -263,8 +263,27 @@ function statusWord(code) {
263
263
  }
264
264
  }
265
265
 
266
- export function mergeChangedFiles(existing, discovered) {
267
- return Array.from(new Set([...(existing ?? []), ...(discovered ?? [])]));
266
+ // A CLI may name a file through a different path than git does: relative to
267
+ // the worktree, or through another name for the same directory (on macOS a
268
+ // temp directory is both /var/... and /private/var/...). One file is listed
269
+ // once. The directory is resolved and the name kept, so a deleted file is
270
+ // still matched and a symlink is not folded into its target.
271
+ function sameFileKey(path, root) {
272
+ const absolute = root ? resolve(root, path) : resolve(path);
273
+ try {
274
+ return join(realpathSync(dirname(absolute)), basename(absolute));
275
+ } catch {
276
+ return absolute; // the directory is gone too: the name is all there is
277
+ }
278
+ }
279
+
280
+ export function mergeChangedFiles(existing, discovered, root = null) {
281
+ const seen = new Map();
282
+ for (const path of [...(existing ?? []), ...(discovered ?? [])]) {
283
+ const key = sameFileKey(path, root);
284
+ if (!seen.has(key)) seen.set(key, path);
285
+ }
286
+ return [...seen.values()];
268
287
  }
269
288
 
270
289
  // What a task row knows about its own worktree, in the shape
@@ -278,7 +297,8 @@ export function worktreeRef(task) {
278
297
  }
279
298
 
280
299
  export function readTaskChanges(task) {
281
- return filterWorkspaceSetupChanges(task, mergeChangedFiles(task.changed_files, readWorktreeChanges(task.worktree_path, worktreeRef(task))));
300
+ const observed = readWorktreeChanges(task.worktree_path, worktreeRef(task));
301
+ return filterWorkspaceSetupChanges(task, mergeChangedFiles(task.changed_files, observed, task.worktree_path ?? task.cwd));
282
302
  }
283
303
 
284
304
  // Compare output at this run's start/end, rather than treating the previous
@@ -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 });
@@ -39,6 +39,7 @@ export const checkAcceptanceOp = {
39
39
  export const preflightCodexWorkerOp = {
40
40
  input: z.object({
41
41
  title: z.string().optional(),
42
+ runner: z.string().regex(/^[a-z][a-z0-9-]{0,31}$/).optional(),
42
43
  cwd: z.string().min(1),
43
44
  sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).default("workspace-write"),
44
45
  model: z.string().optional(),
@@ -95,6 +96,7 @@ export const getWorkerPreflightOp = {
95
96
  export const createCodexWorkerOp = {
96
97
  input: z.object({
97
98
  title: z.string().optional(),
99
+ runner: z.string().regex(/^[a-z][a-z0-9-]{0,31}$/).optional(),
98
100
  task: z.string().min(1),
99
101
  cwd: z.string().min(1),
100
102
  session_id: z.string().min(1).optional(),
@@ -166,6 +168,7 @@ export const createCodexFollowupWorkerOp = {
166
168
  session_title: z.string().min(1).max(120).optional(),
167
169
  session_note: z.string().min(1).max(2000).optional(),
168
170
  title: z.string().optional(),
171
+ runner: z.string().regex(/^[a-z][a-z0-9-]{0,31}$/).optional(),
169
172
  cwd: z.string().optional(),
170
173
  sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).optional(),
171
174
  model: z.string().optional(),
@@ -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,
@@ -7,12 +7,19 @@ import { getTask, recordTerminalChangedFiles } from "../../../infra/store/tasks.
7
7
  import { readAgentMessages } from "../../../infra/store/events.js";
8
8
  import { baseBehind, readTaskChanges, readWorktreeDiff, splitPatchHunks, workspaceSetupIgnorePaths, worktreeRef } from "../../../infra/worktree.js";
9
9
  import { summarizeVerification } from "../../../runners/codex/event-parser.js";
10
- import { readNativeGoal, readNativeGoalState } from "../../../runners/codex/goal-store.js";
10
+ import { readNativeGoal } from "../../../infra/store/runner-readers.js";
11
+ import { loadRunner } from "../../../runners/registry.js";
11
12
  import { textResult } from "../result.js";
12
13
  import { buildWorkerSummary, externalOutputView, reportView, runEvidenceView } from "../views/overview.js";
13
14
  import { acceptanceView } from "../views/task.js";
14
15
  import { z } from "zod";
15
16
 
17
+ // A runner with no native goal, or one this process cannot load, has none to read.
18
+ async function nativeGoalRead(task) {
19
+ const runner = await loadRunner(task.worker).catch(() => null);
20
+ return runner?.capabilities.native_goal ? runner.nativeGoalState(task.thread_id) : { state: "unsupported", goal: null };
21
+ }
22
+
16
23
  export const getWorkerGoalOp = {
17
24
  input: z.object({
18
25
  task_id: z.string().min(1)
@@ -28,8 +35,8 @@ export const getWorkerGoalOp = {
28
35
  token_budget: task.goal_token_budget,
29
36
  goal_status: task.goal_status,
30
37
  needs_attention: isGoalNeedingAttention(task.goal_status),
31
- native_goal: readNativeGoal(task.thread_id),
32
- native_goal_read: readNativeGoalState(task.thread_id)
38
+ native_goal: readNativeGoal(task.thread_id, task.worker),
39
+ native_goal_read: await nativeGoalRead(task)
33
40
  });
34
41
  }
35
42
  };
@@ -41,7 +48,7 @@ export const getWorkerSummaryOp = {
41
48
  handler: async ({ task_id }) => {
42
49
  const task = await getTask(task_id);
43
50
  if (!task) return textResult({ error: "task_not_found", task_id });
44
- const summary = buildWorkerSummary(task, readNativeGoal(task.thread_id));
51
+ const summary = buildWorkerSummary(task, readNativeGoal(task.thread_id, task.worker));
45
52
  // Cache the worktree diff on the row once the worker is done, so the
46
53
  // overview's count stops lagging. A running row is the runner's to write.
47
54
  if (TERMINAL_STATUSES.has(task.status) && summary.changed_files.length !== (task.changed_files ?? []).length) {
@@ -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
@@ -15,6 +15,7 @@ export const preflightWorkerTool = defineTool("preflight_worker", {
15
15
  acceptance: acceptanceShape,
16
16
  owned_paths: z.array(z.string()).optional().describe("Required with probe_commands"),
17
17
  title: z.string().optional(),
18
+ runner: z.string().optional(),
18
19
  model: z.string().optional(),
19
20
  reasoning_effort: effort,
20
21
  workspace: workspaceShape,
@@ -36,16 +37,17 @@ export const preflightWorkerTool = defineTool("preflight_worker", {
36
37
 
37
38
  export const createWorkerTool = defineTool("create_worker", {
38
39
  title: "Dispatch a worker",
39
- description: "Start a worker on one independently verifiable piece of work in its own git worktree and branch. It never commits or pushes. Put the whole brief in task: background, spec, write set, verify command, output format. followup_of continues a finished worker from its branch with its settings.",
40
+ description: "Start a worker on one verifiable piece of work in its own git worktree and branch. It never commits or pushes. task is the whole brief: background, spec, write set, verify command, output format. followup_of continues a finished worker from its branch with its settings. runner: codex (default) or claude.",
40
41
  inputSchema: {
41
42
  task: z.string(),
42
43
  cwd: z.string().optional().describe("Repository. Required unless followup_of"),
43
- owned_paths: z.array(z.string()).optional().describe("Paths the worker may change; overlap with an active worker is refused. Required unless followup_of"),
44
+ owned_paths: z.array(z.string()).optional().describe("Paths it may change; overlap with an active worker is refused. Required unless followup_of"),
44
45
  goal: group("{objective, token_budget}. Required unless followup_of"),
45
46
  title: z.string().optional(),
46
- followup_of: z.string().optional().describe("Task to continue"),
47
- depends_on: z.array(z.string()).optional().describe("Task ids that must land first"),
48
- preflight_id: z.string().optional().describe("A passed preflight_worker id"),
47
+ followup_of: z.string().optional(),
48
+ depends_on: z.array(z.string()).optional().describe("Tasks that must land first"),
49
+ preflight_id: z.string().optional().describe("Passed preflight id"),
50
+ runner: z.string().optional(),
49
51
  model: z.string().optional(),
50
52
  reasoning_effort: effort,
51
53
  session: group("{id, title, note}: one id per batch"),
@@ -31,6 +31,7 @@ export function dispatchOptions(args) {
31
31
  const { sandbox = {}, workspace = {}, context = {}, acceptance, limits = {}, session = {}, goal } = args;
32
32
  return {
33
33
  title: args.title,
34
+ runner: args.runner,
34
35
  cwd: args.cwd,
35
36
  model: args.model,
36
37
  reasoningEffort: args.reasoning_effort,
@@ -5,7 +5,7 @@
5
5
  // reconcile every read does. web-server.js is the entry that decides which
6
6
  // store to open and then calls startWebServer().
7
7
  import "../../app/compose.js";
8
- import { attachToTurn, endSideSession, runSideTurn, sideSessionState, stopSideTurn } from "../../app/side-chat.js";
8
+ import { attachToTurn, endSideSession, runSideTurn, sideSessionState, stopSideTurn, supportsSideChat } from "../../app/side-chat.js";
9
9
  import { supervisorRoot } from "../../infra/paths.js";
10
10
  import { getTask } from "../../infra/store/tasks.js";
11
11
  import { checkForUpdate } from "../../infra/update/update-check.js";
@@ -148,7 +148,7 @@ async function route(req, res) {
148
148
  attachToTurn(taskId, res);
149
149
  return undefined;
150
150
  }
151
- if (req.method === "GET" && !action) return json(res, 200, { task_id: taskId, can_ask: Boolean(task.thread_id), worker_status: task.status, ...(await sideSessionState(taskId)) });
151
+ if (req.method === "GET" && !action) return json(res, 200, { task_id: taskId, can_ask: Boolean(task.thread_id) && supportsSideChat(task), worker_status: task.status, ...(await sideSessionState(taskId)) });
152
152
  if (req.method === "DELETE" && !action) return json(res, 200, { task_id: taskId, ...(await endSideSession(taskId)) });
153
153
  if (req.method === "POST" && action === "stop") return json(res, 200, { task_id: taskId, ...stopSideTurn(taskId) });
154
154
  if (req.method === "POST" && !action) {
@@ -2,12 +2,13 @@
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";
8
9
  import { getTask, readTasks } from "../../infra/store/tasks.js";
9
10
  import { readTaskChanges } from "../../infra/worktree.js";
10
- import { readNativeGoal } from "../../runners/codex/goal-store.js";
11
+ import { readNativeGoal } from "../../infra/store/runner-readers.js";
11
12
 
12
13
  const NO_SESSION = "none";
13
14
 
@@ -210,7 +211,7 @@ export async function worker(taskId) {
210
211
  changed_files: readTaskChanges(task),
211
212
  commands,
212
213
  reports: reports.length > 0 ? reports : task.last_message ? [task.last_message] : [],
213
- native_goal: readNativeGoal(task.thread_id),
214
+ native_goal: readNativeGoal(task.thread_id, task.worker),
214
215
  usage,
215
216
  notices: task.notices ?? null,
216
217
  run_log: task.run_log ?? null,
@@ -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) {
@@ -4,14 +4,11 @@ import { workspaceSetupWriteRoots } from "../app/worktree-setup.js";
4
4
  import { findOutsideOwnedChanges } from "../domain/owned-changes.js";
5
5
  import { buildGuardPreamble } from "../domain/prompt.js";
6
6
  import { withWorkerToolPath } from "../domain/worker-env.js";
7
- import { workerReportSchemaPath } from "../domain/worker-report.js";
8
7
  import { cacheRoots } from "../infra/sandbox-roots.js";
9
- import { supervisorMcpDisableArgs } from "../runners/codex/mcp-config.js";
8
+ import { runnerOf } from "../runners/registry.js";
10
9
  import { dirname } from "node:path";
11
10
  import { fileURLToPath } from "node:url";
12
11
 
13
- const quoteCommand = (path) => process.platform === "win32" ? `"${path.replace(/"/g, '""')}"` : `'${path.replace(/'/g, "'\\''")}'`;
14
-
15
12
  function guardPolicyFor(record, externalBefore, outputSchema) {
16
13
  const owned = [...findOutsideOwnedChanges(record, []).mapping.map((entry) => entry.worker), ...externalBefore.map((entry) => entry.path)];
17
14
  return { cwd: record.cwd, worktree: record.cwd, sandbox: record.sandbox, ownedPaths: owned, ...(record.guard_policy ?? {}),
@@ -28,32 +25,21 @@ function guardPolicyFor(record, externalBefore, outputSchema) {
28
25
  ] };
29
26
  }
30
27
 
31
- function configArgsFor(record, externalBefore, outputSchema) {
32
- const guard = fileURLToPath(new URL("../runners/codex/tool-guard.js", import.meta.url));
33
- const hookCommand = `${quoteCommand(process.execPath)} ${quoteCommand(guard)}`;
34
- const configArgs = [...(outputSchema ? ["--output-schema", workerReportSchemaPath] : []), "--dangerously-bypass-hook-trust", "-c",
35
- `hooks.PreToolUse=[{matcher="Bash|apply_patch|create_goal",hooks=[{type="command",command=${JSON.stringify(hookCommand)}}]}]`];
36
- // A worker may use its explicitly configured business MCP servers, but it
37
- // must not inherit this supervisor and create a second orchestration tree.
38
- configArgs.push(...supervisorMcpDisableArgs());
39
- configArgs.push("-c", `sandbox_workspace_write.network_access=${record.guard_policy?.networkAccess === true}`);
40
- const sandboxWritableRoots = [...new Set([
28
+ // Directories the sandbox must let the worker write besides its worktree.
29
+ function writableRootsFor(record, externalBefore) {
30
+ return [...new Set([
41
31
  ...externalBefore.map((file) => dirname(file.path)),
42
32
  ...cacheRoots(),
43
33
  ...workspaceSetupWriteRoots(record),
44
34
  ...(record.guard_policy?.writableRoots ?? [])
45
35
  ])];
46
- if (sandboxWritableRoots.length) configArgs.push("-c", `sandbox_workspace_write.writable_roots=${JSON.stringify(sandboxWritableRoots)}`);
47
- return configArgs;
48
36
  }
49
37
 
50
38
  export function buildLaunch({ record, args, prompt, outputSchema, externalBefore }) {
51
39
  const guardPolicy = guardPolicyFor(record, externalBefore, outputSchema);
52
40
  const stageCli = fileURLToPath(new URL("../interface/bin/stage.js", import.meta.url));
53
41
  const acceptanceCli = fileURLToPath(new URL("../interface/bin/acceptance-cli.js", import.meta.url));
54
- const configArgs = configArgsFor(record, externalBefore, outputSchema);
55
- // Insert before the prompt/session positional arguments for exec/resume.
56
- const guardedArgs = [...args.slice(0, -1), ...configArgs, args.at(-1)];
42
+ const guardedArgs = runnerOf(record).launchArgs({ args, record, outputSchema, writableRoots: writableRootsFor(record, externalBefore) });
57
43
  const env = () => withWorkerToolPath({ ...process.env, NO_COLOR: "1", AGENT_SUPERVISOR_TASK_ID: record.id,
58
44
  AGENT_SUPERVISOR_BASE_COMMIT: record.base_commit ?? "",
59
45
  AGENT_SUPERVISOR_STAGE_CLI: stageCli,
@@ -2,6 +2,7 @@
2
2
  // write path that keeps the task row in step with it. Every write goes through
3
3
  // one chain so concurrent stdout/stderr callbacks cannot persist out of order.
4
4
  import { terminateChild } from "../app/cancel.js";
5
+ import { runnerOf } from "../runners/registry.js";
5
6
  import { runIdFor } from "../infra/store/db.js";
6
7
  import { appendTaskEvent } from "../infra/store/events.js";
7
8
  import { upsertTask } from "../infra/store/tasks.js";
@@ -21,6 +22,8 @@ export function startingRow(record, child, outputSchema, now) {
21
22
  exit_code: null,
22
23
  signal: null,
23
24
  error: null,
25
+ // What an earlier run wrote to stderr says nothing about how this one ends.
26
+ stderr_tail: null,
24
27
  cancel_requested_at: null,
25
28
  acceptance_results: null,
26
29
  attention_reason: null,
@@ -48,7 +51,7 @@ export function watchQuota(run, now) {
48
51
  if (run.quotaReason) return;
49
52
  if (maxRunMs && Date.now() - Date.parse(now) >= maxRunMs) run.quotaReason = "run_time_limit";
50
53
  else if (maxTotalMs && Date.now() - Date.parse(run.record.created_at) >= maxTotalMs) run.quotaReason = "total_time_limit";
51
- if (run.quotaReason) terminateChild(run.child);
54
+ if (run.quotaReason) terminateChild(run.child, runnerOf(run.record));
52
55
  }, 250);
53
56
  }
54
57
 
@@ -2,22 +2,46 @@
2
2
  // task row forward, stderr keeps a tail on the row.
3
3
  import { splitLines } from "../app/worktree-setup.js";
4
4
  import { appendTaskEvents } from "../infra/store/events.js";
5
- import { codexRunner } from "../runners/codex/adapter.js";
5
+ import { runnerOf } from "../runners/registry.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) {
24
+ const runner = runnerOf(run.record);
9
25
  const events = [];
26
+ const logged = [];
10
27
  for (const line of lines) {
11
28
  try {
12
- const event = JSON.parse(line);
13
- run.logStream.write(`${JSON.stringify(event)}\n`);
14
- events.push(event);
29
+ // One line of the CLI's output is zero or more events in the supervisor's vocabulary.
30
+ for (const event of runner.toEvents(line)) {
31
+ logged.push(logLine(run, `${JSON.stringify(event)}\n`));
32
+ events.push(event);
33
+ }
15
34
  } catch (error) {
16
- run.logStream.write(`${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
35
+ logLine(run, `${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
17
36
  }
18
37
  }
19
38
  if (events.length === 0) return;
20
- const storedEvents = await appendTaskEvents(run.record.id, events, { runId: run.runId, actor: "codex" });
39
+ // The store keeps only a clipped copy of a large event when the log has the
40
+ // whole of it, so the log comes first and a failed write keeps the event whole.
41
+ const inLog = (await Promise.all(logged.map((entry) => entry.written))).every(Boolean) && !run.logFailed;
42
+ const storedEvents = await appendTaskEvents(run.record.id, events, {
43
+ runId: run.runId, actor: runner.name, bodyInLog: inLog, logOffsets: logged.map((entry) => entry.offset)
44
+ });
21
45
  let next = run.live;
22
46
  for (const [index, event] of events.entries()) {
23
47
  if (event.type === "item.completed" && event.item?.type === "agent_message") {
@@ -25,7 +49,7 @@ async function handleLines(run, lines) {
25
49
  run.rawReportEventId = storedEvents[index].id;
26
50
  }
27
51
  if (["turn.completed", "turn.failed"].includes(event.type)) run.terminalEvent = true;
28
- next = codexRunner.parseEvent(next, event);
52
+ next = runner.parseEvent(next, event);
29
53
  }
30
54
  await persist(run, next);
31
55
  }
@@ -59,9 +83,11 @@ export function attachStreams(run, earlyOutput) {
59
83
  child.stdout.on("data", handleStdoutChunk);
60
84
  child.stdout.on("error", () => {});
61
85
 
62
- run.stderr = earlyOutput.stderr.map((chunk) => chunk.toString("utf8")).join("");
86
+ run.stderr = earlyOutput.stderr.map((chunk) => chunk.toString("utf8")).join("").slice(-STDERR_KEEP);
63
87
  child.stderr.on("data", (chunk) => {
64
- run.stderr += chunk.toString("utf8");
88
+ // Only the tail is ever used, so only the tail is kept: a worker that
89
+ // logs for hours must not grow this process without bound.
90
+ run.stderr = (run.stderr + chunk.toString("utf8")).slice(-STDERR_KEEP);
65
91
  persist(run, { ...run.live, stderr_tail: run.stderr.slice(-4000), updated_at: new Date().toISOString() });
66
92
  });
67
93
  child.stderr.on("error", () => {});
@@ -9,12 +9,12 @@ import { clearStage } from "../infra/stage-store.js";
9
9
  import { appendTaskEvent, ensureRunRecord } from "../infra/store/events.js";
10
10
  import { getTask } from "../infra/store/tasks.js";
11
11
  import { snapshotTaskOutput } from "../infra/worktree.js";
12
- import { codexRunner } from "../runners/codex/adapter.js";
12
+ import { loadRunner } from "../runners/registry.js";
13
13
  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
@@ -83,7 +83,8 @@ async function noteFinalizeFailure(run, error) {
83
83
  }
84
84
 
85
85
  export async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}, outputSchema = true }) {
86
- const capability = codexRunner.capabilityPreflight();
86
+ // The run host is its own process: a third-party runner is loaded here again.
87
+ const capability = await (await loadRunner(record.worker)).capabilityPreflight();
87
88
  if (!capability.ok) return failedStart(record, capability.error);
88
89
  const target = capability.target;
89
90
  const before = {
@@ -108,8 +109,11 @@ export async function trackRunInHost({ record, args, prompt, logPath, spawnOptio
108
109
  run.quotaWatch = watchQuota(run, now);
109
110
  await persist(run, run.live);
110
111
  run.runId = await ensureRunRecord(run.live, run.live.run_count);
112
+ // Where the next line will start, so a stored event can say where its full body is.
113
+ run.logOffset = statSync(logPath, { throwIfNoEntry: false })?.size ?? 0;
111
114
  run.logStream = createWriteStream(logPath, { flags: "a" });
112
- run.logStream.on("error", () => {});
115
+ // A log that cannot be written is not the place to keep the only copy of anything.
116
+ run.logStream.on("error", () => { run.logFailed = true; });
113
117
  child.stdin.on("error", (error) => { noteStdinFailure(run, error); });
114
118
  attachStreams(run, earlyOutput);
115
119
 
@@ -0,0 +1,118 @@
1
+ // Claude Code as a worker, through its headless mode (`claude -p`).
2
+ //
3
+ // What it has: sessions that resume, a PreToolUse hook, a structured final
4
+ // answer. What it lacks: an OS sandbox (the hook is the only confinement, so
5
+ // the core allows it only a worktree or a read-only run), a read-only fork to
6
+ // ask side questions in, and a native goal.
7
+ import { workerReportSchemaPath } from "../../domain/worker-report.js";
8
+ import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "../../infra/bin-resolver.js";
9
+ import { runSync, spawnProcess } from "../../infra/process.js";
10
+ import { applyCodexEvent } from "../codex/event-parser.js";
11
+ import { createTranslator } from "./events.js";
12
+ import { readFileSync } from "node:fs";
13
+ import { fileURLToPath } from "node:url";
14
+
15
+ const CLAUDE_NPM_ENTRY = { pkg: "@anthropic-ai/claude-code", bin: "cli.js" };
16
+ // Claude Code has no "minimal"; the nearest it has is low.
17
+ const EFFORTS = new Map([["minimal", "low"], ["low", "low"], ["medium", "medium"], ["high", "high"]]);
18
+ const quoteCommand = (path) => process.platform === "win32" ? `"${path.replace(/"/g, '""')}"` : `'${path.replace(/'/g, "'\\''")}'`;
19
+
20
+ export class ClaudeRunnerAdapter {
21
+ constructor({ env = process.env } = {}) {
22
+ this.env = env;
23
+ this.name = "claude";
24
+ this.capabilities = { os_sandbox: false, resume: true, side_chat: false, tool_guard: true, structured_report: true, native_goal: false };
25
+ this.translate = createTranslator();
26
+ }
27
+
28
+ resolveTarget() {
29
+ const configured = this.env.CLAUDE_BIN?.trim();
30
+ const located = configured ? configured : (findBinaryPath("claude", { extraDirs: defaultBinDirs() }) ?? "claude");
31
+ const target = resolveCommand(located, { npmEntry: CLAUDE_NPM_ENTRY });
32
+ if (target.shim) return { error: shimMessage("claude", target.cmd, "CLAUDE_BIN") };
33
+ return { cmd: target.cmd, prefixArgs: target.prefixArgs };
34
+ }
35
+
36
+ capabilityPreflight(target = this.resolveTarget()) {
37
+ if (target.error) return { ok: false, error: target.error };
38
+ try {
39
+ const help = runSync(target.cmd, [...target.prefixArgs, "--help"], { encoding: "utf8", timeout: 20000, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
40
+ const missing = ["--json-schema", "--settings", "--resume", "--output-format", "--permission-mode", "--strict-mcp-config", "--disallowed-tools"].filter((flag) => !help.includes(flag));
41
+ if (missing.length) return { ok: false, error: `Claude Code lacks ${missing.join(", ")}; install a newer Claude Code before dispatch` };
42
+ return { ok: true, target };
43
+ } catch (error) {
44
+ return { ok: false, error: error.code === "ENOENT"
45
+ ? `failed to spawn ${target.cmd} for the Claude Code capability preflight: ${error.message}`
46
+ : `Claude Code capability preflight failed: ${error.message}` };
47
+ }
48
+ }
49
+
50
+ // The prompt is read from stdin. The working directory is the process's own.
51
+ baseArgs({ sandbox, model, reasoningEffort }) {
52
+ // Headless, nobody can answer a permission prompt: permissions are bypassed
53
+ // and the guard hook decides instead.
54
+ const args = ["-p", "--output-format", "stream-json", "--verbose", "--permission-mode", "bypassPermissions",
55
+ // A worker must not inherit this supervisor and start a second orchestration tree.
56
+ "--strict-mcp-config"];
57
+ if (sandbox === "read-only") args.push("--disallowed-tools", "Edit", "Write", "MultiEdit", "NotebookEdit");
58
+ if (model) args.push("--model", model);
59
+ if (EFFORTS.has(reasoningEffort)) args.push("--effort", EFFORTS.get(reasoningEffort));
60
+ return args;
61
+ }
62
+
63
+ startArgs({ sandbox, model, reasoningEffort }) {
64
+ return this.baseArgs({ sandbox, model, reasoningEffort });
65
+ }
66
+
67
+ resumeArgs(task) {
68
+ return [...this.baseArgs({ sandbox: task.sandbox, model: task.model, reasoningEffort: task.reasoning_effort }), "--resume", task.thread_id];
69
+ }
70
+
71
+ launchArgs({ args, outputSchema }) {
72
+ const guard = fileURLToPath(new URL("./tool-guard.js", import.meta.url));
73
+ const settings = { hooks: { PreToolUse: [{ matcher: "Bash|Edit|Write|MultiEdit|NotebookEdit",
74
+ hooks: [{ type: "command", command: `${quoteCommand(process.execPath)} ${quoteCommand(guard)}` }] }] } };
75
+ const launch = [...args, "--settings", JSON.stringify(settings)];
76
+ if (outputSchema) launch.push("--json-schema", JSON.stringify(JSON.parse(readFileSync(workerReportSchemaPath, "utf8"))));
77
+ return launch;
78
+ }
79
+
80
+ start(target, args, options) {
81
+ return spawnProcess(target.cmd, [...target.prefixArgs, ...args], options);
82
+ }
83
+
84
+ toEvents(line) {
85
+ return this.translate(JSON.parse(line));
86
+ }
87
+
88
+ // The translated events are the supervisor's vocabulary, which the shared reducer reads.
89
+ parseEvent(task, event) {
90
+ return applyCodexEvent(task, event);
91
+ }
92
+
93
+ cancelChild(child) {
94
+ if (process.platform === "win32" && child.pid) {
95
+ try {
96
+ runSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", timeout: 5000, windowsHide: true });
97
+ return;
98
+ } catch {
99
+ // fall through to the process handle
100
+ }
101
+ }
102
+ child.kill("SIGTERM");
103
+ }
104
+
105
+ cancelPid(pid) {
106
+ if (process.platform === "win32") {
107
+ runSync("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", timeout: 5000, windowsHide: true });
108
+ return;
109
+ }
110
+ process.kill(pid, "SIGTERM");
111
+ }
112
+
113
+ ownsPid(pid, describeProcess) {
114
+ return describeProcess(pid).includes("claude");
115
+ }
116
+ }
117
+
118
+ export const claudeRunner = new ClaudeRunnerAdapter();