codex-supervisor-mcp 1.1.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.
@@ -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) {
@@ -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();
@@ -0,0 +1,100 @@
1
+ // Turns Claude Code's stream-json into the supervisor's event vocabulary
2
+ // (see ../contract.js). Claude Code prints whole messages: an assistant
3
+ // message holds the tool calls it makes, a later user message holds their
4
+ // results. A tool call is therefore remembered until its result arrives.
5
+ const FILE_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
6
+ const MAX_PENDING = 500;
7
+
8
+ function textOf(content) {
9
+ if (typeof content === "string") return content;
10
+ if (!Array.isArray(content)) return "";
11
+ return content.map((part) => (typeof part === "string" ? part : part?.text ?? "")).join("");
12
+ }
13
+
14
+ function usageOf(usage) {
15
+ if (!usage) return undefined;
16
+ return {
17
+ input_tokens: (usage.input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0),
18
+ cached_input_tokens: usage.cache_read_input_tokens ?? 0,
19
+ output_tokens: usage.output_tokens ?? 0
20
+ };
21
+ }
22
+
23
+ export function createTranslator() {
24
+ const pending = new Map();
25
+ let reported = false;
26
+
27
+ function toolCall(part) {
28
+ if (pending.size >= MAX_PENDING) pending.delete(pending.keys().next().value);
29
+ if (part.name === "Bash") {
30
+ const command = String(part.input?.command ?? "");
31
+ pending.set(part.id, { type: "command_execution", command });
32
+ return [{ type: "item.started", item: { id: part.id, type: "command_execution", command, aggregated_output: "", exit_code: null, status: "in_progress" } }];
33
+ }
34
+ if (FILE_TOOLS.has(part.name)) {
35
+ const path = part.input?.file_path ?? part.input?.notebook_path ?? null;
36
+ pending.set(part.id, { type: "file_change", path });
37
+ return [];
38
+ }
39
+ // The structured report arrives as a call of this tool; it is the worker's final message.
40
+ if (part.name === "StructuredOutput") {
41
+ reported = true;
42
+ return [{ type: "item.completed", item: { id: part.id, type: "agent_message", text: JSON.stringify(part.input ?? {}) } }];
43
+ }
44
+ pending.set(part.id, { type: "mcp_tool_call", tool: part.name });
45
+ return [{ type: "item.started", item: { id: part.id, type: "mcp_tool_call", tool: part.name, status: "in_progress" } }];
46
+ }
47
+
48
+ function toolResult(part, message) {
49
+ const call = pending.get(part.tool_use_id);
50
+ if (!call) return [];
51
+ pending.delete(part.tool_use_id);
52
+ const failed = part.is_error === true;
53
+ if (call.type === "command_execution") {
54
+ const raw = message.tool_use_result;
55
+ const output = raw && typeof raw === "object" ? [raw.stdout, raw.stderr].filter(Boolean).join("\n") : textOf(part.content);
56
+ return [{ type: "item.completed", item: { id: part.tool_use_id, type: "command_execution", command: call.command,
57
+ aggregated_output: output || textOf(part.content), exit_code: failed ? 1 : 0, status: failed ? "failed" : "completed" } }];
58
+ }
59
+ if (call.type === "file_change") {
60
+ // A refused or failed edit changed nothing.
61
+ if (failed || !call.path) return [];
62
+ return [{ type: "item.completed", item: { id: part.tool_use_id, type: "file_change", changes: [{ path: call.path, kind: "update" }], status: "completed" } }];
63
+ }
64
+ return [{ type: "item.completed", item: { id: part.tool_use_id, type: "mcp_tool_call", tool: call.tool, status: failed ? "failed" : "completed" } }];
65
+ }
66
+
67
+ function result(message) {
68
+ if (message.is_error || (message.subtype && message.subtype !== "success")) {
69
+ const text = typeof message.result === "string" && message.result ? message.result : `Claude Code ended with ${message.subtype ?? "an error"}`;
70
+ return [{ type: "turn.failed", error: { message: text } }];
71
+ }
72
+ const events = [];
73
+ if (!reported && message.structured_output != null) {
74
+ events.push({ type: "item.completed", item: { id: `result-${message.uuid ?? "final"}`, type: "agent_message", text: JSON.stringify(message.structured_output) } });
75
+ }
76
+ events.push({ type: "turn.completed", usage: usageOf(message.usage) });
77
+ return events;
78
+ }
79
+
80
+ return function translate(message) {
81
+ if (message.type === "system" && message.subtype === "init") {
82
+ reported = false;
83
+ return [{ type: "thread.started", thread_id: message.session_id }, { type: "turn.started" }];
84
+ }
85
+ if (message.type === "assistant") {
86
+ const events = [];
87
+ for (const part of message.message?.content ?? []) {
88
+ if (part.type === "text" && part.text?.trim()) events.push({ type: "item.completed", item: { id: `${message.message.id}-text`, type: "agent_message", text: part.text } });
89
+ else if (part.type === "tool_use") events.push(...toolCall(part));
90
+ }
91
+ return events;
92
+ }
93
+ if (message.type === "user") {
94
+ const parts = Array.isArray(message.message?.content) ? message.message.content : [];
95
+ return parts.filter((part) => part?.type === "tool_result").flatMap((part) => toolResult(part, message));
96
+ }
97
+ if (message.type === "result") return result(message);
98
+ return [];
99
+ };
100
+ }
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env node
2
+ // PreToolUse hook for a Claude Code worker. Claude Code has no OS sandbox, so
3
+ // this hook is all that confines a worker: a file tool may only write what the
4
+ // worker owns, and the shell runs reads and the commands the dispatcher
5
+ // declared. A declared command is trusted as written; it is not sandboxed.
6
+ import { evaluateToolUse } from "../codex/tool-guard.js";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const FILE_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
10
+
11
+ export function evaluateClaudeToolUse(event, policy) {
12
+ const deny = (reason) => ({ allow: false, reason });
13
+ if (!policy || !Array.isArray(policy.ownedPaths) || !policy.cwd) return deny("missing supervisor guard policy");
14
+ const tool = event.tool_name;
15
+ if (FILE_TOOLS.has(tool)) {
16
+ const path = event.tool_input?.file_path ?? event.tool_input?.notebook_path;
17
+ if (typeof path !== "string" || !path) return deny("the edit names no file");
18
+ // Judged exactly as a one-file patch is for a Codex worker.
19
+ return evaluateToolUse({ ...event, tool_name: "apply_patch", tool_input: { command: `*** Begin Patch\n*** Update File: ${path}\n*** End Patch` } }, policy);
20
+ }
21
+ if (tool === "Bash") {
22
+ // The shared rules accept a patch written through the shell and judge it by
23
+ // the sandbox; the override below would hide that this worker is read-only.
24
+ if (policy.sandbox === "read-only" && /\bapply_patch\b/.test(String(event.tool_input?.command ?? ""))) {
25
+ return deny("read-only worker: only read commands run; report the change instead of making it");
26
+ }
27
+ // With an OS sandbox a worker that lands nothing may run anything, since
28
+ // the sandbox stops its writes. Here nothing would, so the allowlist
29
+ // always applies: that is what danger-full-access means to the shared rules.
30
+ const decision = evaluateToolUse(event, { ...policy, sandbox: "danger-full-access" });
31
+ if (decision.allow || !/^undeclared shell command/.test(decision.reason)) return decision;
32
+ return deny(policy.sandbox === "read-only"
33
+ ? "read-only worker: only read commands run; report the change instead of making it"
34
+ : "undeclared shell command; edit files with the Edit or Write tool, or have the dispatcher declare the command in sandbox.allowed_commands");
35
+ }
36
+ // Reading tools and the structured report are not writes.
37
+ return { allow: true, reason: "tool is outside the write policy" };
38
+ }
39
+
40
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
41
+ let input = "";
42
+ for await (const chunk of process.stdin) input += chunk;
43
+ let decision;
44
+ try { decision = evaluateClaudeToolUse(JSON.parse(input), JSON.parse(process.env.AGENT_SUPERVISOR_GUARD_POLICY ?? "null")); }
45
+ catch (error) { decision = { allow: false, reason: "invalid supervisor guard input: " + error.message }; }
46
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse",
47
+ permissionDecision: decision.allow ? "allow" : "deny", permissionDecisionReason: decision.reason } }) + "\n");
48
+ }
@@ -1,6 +1,13 @@
1
1
  import { runSync, spawnProcess } from "../../infra/process.js";
2
2
  import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "../../infra/bin-resolver.js";
3
+ import { workerReportSchemaPath } from "../../domain/worker-report.js";
4
+ import { chunksFor } from "./chat-chunks.js";
3
5
  import { applyCodexEvent } from "./event-parser.js";
6
+ import { readNativeGoal, readNativeGoalState } from "./goal-store.js";
7
+ import { codexConfigText, disableMcpServerArgs, supervisorMcpDisableArgs } from "./mcp-config.js";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ const quoteCommand = (path) => process.platform === "win32" ? `"${path.replace(/"/g, '""')}"` : `'${path.replace(/'/g, "'\\''")}'`;
4
11
 
5
12
  const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
6
13
 
@@ -8,6 +15,56 @@ export class CodexRunnerAdapter {
8
15
  constructor({ env = process.env } = {}) {
9
16
  this.env = env;
10
17
  this.name = "codex";
18
+ this.capabilities = { os_sandbox: true, resume: true, side_chat: true, tool_guard: true, structured_report: true, native_goal: true };
19
+ // The read-only fork a side question runs in.
20
+ this.sideChat = {
21
+ forkArgs: (options) => this.forkSideArgs(options),
22
+ // Config overrides go before the thread id and the stdin marker.
23
+ withConfig: (args, configArgs) => [...args.slice(0, -2), ...configArgs, ...args.slice(-2)],
24
+ configText: codexConfigText,
25
+ disableMcpServerArgs,
26
+ chunksFor,
27
+ deleteArgs: (threadId) => ["delete", "--force", threadId]
28
+ };
29
+ }
30
+
31
+ // Adds what installs the guard hook, the report schema and the sandbox
32
+ // settings to the arguments of a start or a resume.
33
+ launchArgs({ args, record, outputSchema, writableRoots }) {
34
+ const guard = fileURLToPath(new URL("./tool-guard.js", import.meta.url));
35
+ const hookCommand = `${quoteCommand(process.execPath)} ${quoteCommand(guard)}`;
36
+ const configArgs = [...(outputSchema ? ["--output-schema", workerReportSchemaPath] : []), "--dangerously-bypass-hook-trust", "-c",
37
+ `hooks.PreToolUse=[{matcher="Bash|apply_patch|create_goal",hooks=[{type="command",command=${JSON.stringify(hookCommand)}}]}]`];
38
+ // A worker may use its explicitly configured business MCP servers, but it
39
+ // must not inherit this supervisor and create a second orchestration tree.
40
+ configArgs.push(...supervisorMcpDisableArgs());
41
+ configArgs.push("-c", `sandbox_workspace_write.network_access=${record.guard_policy?.networkAccess === true}`);
42
+ if (writableRoots.length) configArgs.push("-c", `sandbox_workspace_write.writable_roots=${JSON.stringify(writableRoots)}`);
43
+ // Before the prompt/session positional argument that ends exec and resume.
44
+ return [...args.slice(0, -1), ...configArgs, args.at(-1)];
45
+ }
46
+
47
+ // Codex already prints the supervisor's event vocabulary.
48
+ toEvents(line) {
49
+ return [JSON.parse(line)];
50
+ }
51
+
52
+ nativeGoal(threadId) {
53
+ return readNativeGoal(threadId);
54
+ }
55
+
56
+ nativeGoalState(threadId) {
57
+ return readNativeGoalState(threadId);
58
+ }
59
+
60
+ // Only a thread with no native goal, or one explicitly stored as complete,
61
+ // can safely resume with a structured output schema. Paused, blocked,
62
+ // usage-limited and budget-limited goals are not complete; Codex can still
63
+ // activate their goal turn and reject the incompatible schema.
64
+ resumeAllowsOutputSchema(threadId) {
65
+ const goalRead = readNativeGoalState(threadId);
66
+ return ["missing_goal", "missing_database"].includes(goalRead.state)
67
+ || (goalRead.state === "available" && goalRead.goal?.storage_status === "complete");
11
68
  }
12
69
 
13
70
  resolveTarget() {
@@ -11,6 +11,10 @@ export function configuredMcpServers(configText) {
11
11
  return names;
12
12
  }
13
13
 
14
+ // The key path is written bare: `-c mcp_servers.name.enabled=false`. A
15
+ // quoted name (`mcp_servers."name".enabled`) is taken by codex as a new
16
+ // server literally called "name", quotes included, with no transport, and
17
+ // the whole config then fails to load.
14
18
  export function disableMcpServerArgs(configText, names = null) {
15
19
  const configured = configuredMcpServers(configText);
16
20
  const selected = names ? [...configured].filter((name) => names.has(name)) : [...configured];