codex-supervisor-mcp 1.1.0 → 1.3.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 (37) hide show
  1. package/README.en.md +5 -1
  2. package/README.md +5 -1
  3. package/package.json +2 -2
  4. package/skills/codex-supervisor/SKILL.md +2 -1
  5. package/src/app/cancel.js +11 -14
  6. package/src/app/compose.js +13 -3
  7. package/src/app/dispatch.js +12 -12
  8. package/src/app/followup.js +5 -0
  9. package/src/app/resume.js +9 -16
  10. package/src/app/side-chat.js +41 -20
  11. package/src/domain/prompt.js +7 -3
  12. package/src/domain/worker-preflight.js +4 -1
  13. package/src/infra/stage-store.js +1 -1
  14. package/src/infra/store/runner-readers.js +1 -1
  15. package/src/infra/store/tasks.js +1 -1
  16. package/src/infra/update/auto-update-worker.js +44 -2
  17. package/src/infra/update/handover.js +125 -0
  18. package/src/infra/worktree.js +25 -5
  19. package/src/interface/mcp/handlers/dispatch.js +3 -0
  20. package/src/interface/mcp/handlers/results.js +11 -4
  21. package/src/interface/mcp/tools/dispatch.js +7 -5
  22. package/src/interface/mcp/tools/shapes.js +1 -0
  23. package/src/interface/mcp/update-state.js +10 -4
  24. package/src/interface/web/app.js +2 -2
  25. package/src/interface/web/views.js +2 -2
  26. package/src/run-host/launch.js +5 -19
  27. package/src/run-host/live-run.js +2 -1
  28. package/src/run-host/streams.js +9 -6
  29. package/src/run-host/track.js +3 -2
  30. package/src/runners/claude/adapter.js +118 -0
  31. package/src/runners/claude/events.js +100 -0
  32. package/src/runners/claude/tool-guard.js +48 -0
  33. package/src/runners/codex/adapter.js +57 -0
  34. package/src/runners/codex/mcp-config.js +4 -0
  35. package/src/runners/contract-check.js +82 -0
  36. package/src/runners/contract.js +53 -0
  37. package/src/runners/registry.js +45 -0
@@ -0,0 +1,125 @@
1
+ // This package was renamed to agent-supervisor-mcp. This is its last release
2
+ // under the old name, and its one job beyond working as before is to bring the
3
+ // machine over without anyone typing a command.
4
+ //
5
+ // At start-up, if this copy is a global npm install and the new package is
6
+ // not installed beside it, a detached worker runs
7
+ // `npm install -g agent-supervisor-mcp`. The new package's own install step
8
+ // then registers itself with the clients it finds, removes this package's
9
+ // registration and retires its skill. The session that is running keeps
10
+ // running; the next one starts on the new package. The state directory is
11
+ // not touched: the new package keeps using it.
12
+ //
13
+ // As with auto-update, only a copy npm installed globally is acted on. A
14
+ // checkout, an npx copy or a project dependency only gets the notice.
15
+ import { spawnProcess } from "../process.js";
16
+ import { closeSync, existsSync, openSync } from "node:fs";
17
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
18
+ import { dirname, join } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+ import { dataDir } from "../paths.js";
21
+ import { autoUpdateDisabled } from "./auto-update.js";
22
+
23
+ export const SUCCESSOR = "agent-supervisor-mcp";
24
+ export const handoverStatePath = join(dataDir, "handover.json");
25
+ const logPath = join(dataDir, "auto-update.log");
26
+ const workerEntry = join(dirname(fileURLToPath(import.meta.url)), "auto-update-worker.js");
27
+ const RETRY_AFTER_MS = 24 * 60 * 60 * 1000;
28
+ const MANUAL = `npm install -g ${SUCCESSOR}`;
29
+
30
+ // Pure. Why nothing is installed automatically, or null when it should be.
31
+ export function handoverBlocker(update, env = process.env) {
32
+ if (!update) return "no update check result yet";
33
+ if (update.disabled) return "update check is disabled";
34
+ if (autoUpdateDisabled(env)) return "disabled by AGENT_SUPERVISOR_NO_AUTO_UPDATE";
35
+ if (env.CI) return "CI environment";
36
+ const source = update.installed?.source;
37
+ if (source !== "npm") return `installed from ${source ?? "an unknown source"}, not a global npm install`;
38
+ return null;
39
+ }
40
+
41
+ async function readState() {
42
+ try {
43
+ return JSON.parse(await readFile(handoverStatePath, "utf8"));
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ function processAlive(pid) {
50
+ if (!pid) return false;
51
+ try {
52
+ process.kill(pid, 0);
53
+ return true;
54
+ } catch (error) {
55
+ return error.code === "EPERM";
56
+ }
57
+ }
58
+
59
+ async function launchWorker({ packageRoot, registry }) {
60
+ await mkdir(dataDir, { recursive: true });
61
+ const args = [workerEntry, "--successor", SUCCESSOR, "--package-root", packageRoot];
62
+ if (registry) args.push("--registry", registry);
63
+ const log = openSync(logPath, "a");
64
+ try {
65
+ const child = spawnProcess(process.execPath, args, {
66
+ detached: true, stdio: ["ignore", log, log], env: { ...process.env, AGENT_SUPERVISOR_NO_AUTO_UPDATE: "1" }, windowsHide: true
67
+ });
68
+ child.unref();
69
+ return child.pid;
70
+ } finally {
71
+ closeSync(log);
72
+ }
73
+ }
74
+
75
+ // Returns the handover record: { state: "done" | "started" | "running" | "failed" | "skipped", reason? }.
76
+ let queue = Promise.resolve();
77
+ export function maybeHandOver(update, options = {}) {
78
+ const next = queue.then(() => decide(update, options));
79
+ queue = next.catch(() => {});
80
+ return next;
81
+ }
82
+
83
+ async function decide(update, { env = process.env, launch = launchWorker, exists = existsSync } = {}) {
84
+ const blocker = handoverBlocker(update, env);
85
+ if (blocker) return { state: "skipped", reason: blocker };
86
+ // npm puts global packages side by side.
87
+ const successorRoot = join(dirname(update.installed.path), SUCCESSOR);
88
+ if (exists(join(successorRoot, "package.json"))) return { state: "done", installed_path: successorRoot };
89
+
90
+ const prior = await readState();
91
+ if (prior && ["started", "running"].includes(prior.state) && processAlive(prior.pid)) return prior;
92
+ const age = prior?.updated_at ? Date.now() - Date.parse(prior.updated_at) : Number.POSITIVE_INFINITY;
93
+ // A failed attempt is not repeated on every start; once a day is enough to get past a registry outage.
94
+ if (prior?.state === "failed" && age < RETRY_AFTER_MS) return prior;
95
+
96
+ let record;
97
+ try {
98
+ const pid = await launch({ packageRoot: update.installed.path, registry: env.AGENT_SUPERVISOR_REGISTRY?.trim() || null });
99
+ record = { state: "started", pid };
100
+ } catch (error) {
101
+ record = { state: "failed", reason: `could not start the installer: ${error.message}` };
102
+ }
103
+ try {
104
+ await mkdir(dataDir, { recursive: true });
105
+ await writeFile(handoverStatePath, JSON.stringify({ ...record, updated_at: new Date().toISOString() }, null, 2));
106
+ } catch {
107
+ // the worker rewrites it anyway
108
+ }
109
+ return record;
110
+ }
111
+
112
+ // What every tool result says about it. This package always has something to say.
113
+ export function handoverNotice(record) {
114
+ const renamed = `codex-supervisor-mcp is now ${SUCCESSOR}`;
115
+ if (record?.state === "done") {
116
+ return { renamed_to: SUCCESSOR, state: "done",
117
+ notice: `${renamed}, and it has been installed and registered. Start a new session (restart the MCP client) to use it; its tools are the same. Afterwards: npm uninstall -g codex-supervisor-mcp` };
118
+ }
119
+ if (record?.state === "started" || record?.state === "running") {
120
+ return { renamed_to: SUCCESSOR, state: record.state, notice: `${renamed}. It is being installed in the background; the next session starts on it once the install finishes.` };
121
+ }
122
+ const why = record?.reason ? ` (not installed automatically: ${record.reason})` : "";
123
+ return { renamed_to: SUCCESSOR, state: record?.state ?? "pending", install_command: MANUAL,
124
+ notice: `${renamed}. This is the last release under the old name. Run \`${MANUAL}\` and restart the MCP client${why}.` };
125
+ }
@@ -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
@@ -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(),
@@ -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) {
@@ -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,
@@ -1,4 +1,5 @@
1
1
  import { maybeAutoUpdate } from "../../infra/update/auto-update.js";
2
+ import { handoverNotice, maybeHandOver } from "../../infra/update/handover.js";
2
3
  import { checkForUpdate, updateNotice } from "../../infra/update/update-check.js";
3
4
 
4
5
  // Nobody should keep running an old build without hearing about it. The
@@ -10,21 +11,26 @@ export let updateState = null;
10
11
  // The last word from auto-update.js: null until a check found a newer
11
12
  // version, then started | running | done | failed | skipped.
12
13
  export let autoUpdateState = null;
14
+ // The package was renamed; handover.js installs the new one. Null until the first check.
15
+ export let handoverState = null;
13
16
  export async function refreshUpdateState({ force = false } = {}) {
14
17
  try {
15
18
  updateState = await checkForUpdate({ force });
16
19
  autoUpdateState = await maybeAutoUpdate(updateState);
17
- const notice = updateNotice(updateState, autoUpdateState)?.notice;
18
- if (notice) process.stderr.write(`[codex-supervisor] ${notice}\n`);
20
+ handoverState = await maybeHandOver(updateState);
21
+ if (!updateState.disabled) process.stderr.write(`[codex-supervisor] ${handoverNotice(handoverState).notice}\n`);
19
22
  } catch (error) {
20
23
  process.stderr.write(`[codex-supervisor] update check failed: ${error.message}\n`);
21
24
  }
22
25
  return updateState;
23
26
  }
24
27
 
25
- // The short form for tool results: null when the install is current.
28
+ // The short form for tool results. The rename is always said; a newer release
29
+ // of this package is not worth a line beside it.
26
30
  export function updateField() {
27
- return updateNotice(updateState, autoUpdateState);
31
+ // With the update check switched off the server says nothing unasked, the rename included.
32
+ if (!updateState || updateState.disabled) return updateNotice(updateState, autoUpdateState);
33
+ return handoverNotice(handoverState);
28
34
  }
29
35
 
30
36
  // Spread into a result: adds `update` only when there is something to say.
@@ -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) {
@@ -8,7 +8,7 @@ import { reconcileDetachedActiveTasks } from "../../infra/store/reconcile.js";
8
8
  import { readSessions } from "../../infra/store/sessions.js";
9
9
  import { getTask, readTasks } from "../../infra/store/tasks.js";
10
10
  import { readTaskChanges } from "../../infra/worktree.js";
11
- import { readNativeGoal } from "../../runners/codex/goal-store.js";
11
+ import { readNativeGoal } from "../../infra/store/runner-readers.js";
12
12
 
13
13
  const NO_SESSION = "none";
14
14
 
@@ -211,7 +211,7 @@ export async function worker(taskId) {
211
211
  changed_files: readTaskChanges(task),
212
212
  commands,
213
213
  reports: reports.length > 0 ? reports : task.last_message ? [task.last_message] : [],
214
- native_goal: readNativeGoal(task.thread_id),
214
+ native_goal: readNativeGoal(task.thread_id, task.worker),
215
215
  usage,
216
216
  notices: task.notices ?? null,
217
217
  run_log: task.run_log ?? null,
@@ -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";
@@ -50,7 +51,7 @@ export function watchQuota(run, now) {
50
51
  if (run.quotaReason) return;
51
52
  if (maxRunMs && Date.now() - Date.parse(now) >= maxRunMs) run.quotaReason = "run_time_limit";
52
53
  else if (maxTotalMs && Date.now() - Date.parse(run.record.created_at) >= maxTotalMs) run.quotaReason = "total_time_limit";
53
- if (run.quotaReason) terminateChild(run.child);
54
+ if (run.quotaReason) terminateChild(run.child, runnerOf(run.record));
54
55
  }, 250);
55
56
  }
56
57
 
@@ -2,7 +2,7 @@
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
8
  const STDERR_KEEP = 64 * 1024;
@@ -21,13 +21,16 @@ function logLine(run, text) {
21
21
  }
22
22
 
23
23
  async function handleLines(run, lines) {
24
+ const runner = runnerOf(run.record);
24
25
  const events = [];
25
26
  const logged = [];
26
27
  for (const line of lines) {
27
28
  try {
28
- const event = JSON.parse(line);
29
- logged.push(logLine(run, `${JSON.stringify(event)}\n`));
30
- 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
+ }
31
34
  } catch (error) {
32
35
  logLine(run, `${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
33
36
  }
@@ -37,7 +40,7 @@ async function handleLines(run, lines) {
37
40
  // whole of it, so the log comes first and a failed write keeps the event whole.
38
41
  const inLog = (await Promise.all(logged.map((entry) => entry.written))).every(Boolean) && !run.logFailed;
39
42
  const storedEvents = await appendTaskEvents(run.record.id, events, {
40
- runId: run.runId, actor: "codex", bodyInLog: inLog, logOffsets: logged.map((entry) => entry.offset)
43
+ runId: run.runId, actor: runner.name, bodyInLog: inLog, logOffsets: logged.map((entry) => entry.offset)
41
44
  });
42
45
  let next = run.live;
43
46
  for (const [index, event] of events.entries()) {
@@ -46,7 +49,7 @@ async function handleLines(run, lines) {
46
49
  run.rawReportEventId = storedEvents[index].id;
47
50
  }
48
51
  if (["turn.completed", "turn.failed"].includes(event.type)) run.terminalEvent = true;
49
- next = codexRunner.parseEvent(next, event);
52
+ next = runner.parseEvent(next, event);
50
53
  }
51
54
  await persist(run, next);
52
55
  }
@@ -9,7 +9,7 @@ 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";
@@ -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 = {
@@ -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();