agent-supervisor-mcp 0.0.0-stage → 2.0.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 (122) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +208 -0
  3. package/README.md +206 -2
  4. package/package.json +76 -4
  5. package/skills/agent-supervisor/SKILL.md +139 -0
  6. package/src/app/acceptance.js +263 -0
  7. package/src/app/auto-cleanup.js +91 -0
  8. package/src/app/cancel.js +57 -0
  9. package/src/app/cleanup-facts.js +101 -0
  10. package/src/app/cleanup-plan.js +166 -0
  11. package/src/app/compose.js +17 -0
  12. package/src/app/context-compiler.js +83 -0
  13. package/src/app/dispatch.js +398 -0
  14. package/src/app/followup.js +104 -0
  15. package/src/app/land-chain.js +134 -0
  16. package/src/app/landing.js +357 -0
  17. package/src/app/ownership.js +57 -0
  18. package/src/app/rebase.js +216 -0
  19. package/src/app/restore-worktree.js +51 -0
  20. package/src/app/resume.js +179 -0
  21. package/src/app/run-state.js +26 -0
  22. package/src/app/settled.js +28 -0
  23. package/src/app/side-chat.js +370 -0
  24. package/src/app/sse.js +20 -0
  25. package/src/app/start-run.js +77 -0
  26. package/src/app/verify-push.js +114 -0
  27. package/src/app/worktree-setup.js +218 -0
  28. package/src/domain/acceptance-baseline.js +65 -0
  29. package/src/domain/acceptance-spec.js +30 -0
  30. package/src/domain/cleanup-policy.js +44 -0
  31. package/src/domain/command-outcome.js +6 -0
  32. package/src/domain/failure-class.js +63 -0
  33. package/src/domain/owned-changes.js +27 -0
  34. package/src/domain/prompt.js +161 -0
  35. package/src/domain/side-turn-view.js +73 -0
  36. package/src/domain/status.js +50 -0
  37. package/src/domain/thread-health.js +33 -0
  38. package/src/domain/truncate.js +148 -0
  39. package/src/domain/worker-branch.js +6 -0
  40. package/src/domain/worker-changes.js +58 -0
  41. package/src/domain/worker-env.js +14 -0
  42. package/src/domain/worker-preflight.js +167 -0
  43. package/src/domain/worker-report.js +85 -0
  44. package/src/domain/worker-report.schema.json +10 -0
  45. package/src/infra/bin-resolver.js +287 -0
  46. package/src/infra/cleanup-hint.js +29 -0
  47. package/src/infra/crash-guard.js +44 -0
  48. package/src/infra/external-output.js +29 -0
  49. package/src/infra/git.js +61 -0
  50. package/src/infra/handoff.js +38 -0
  51. package/src/infra/paths.js +34 -0
  52. package/src/infra/process.js +59 -0
  53. package/src/infra/sandbox-roots.js +106 -0
  54. package/src/infra/skill-sync.js +109 -0
  55. package/src/infra/stage-store.js +39 -0
  56. package/src/infra/store/db.js +265 -0
  57. package/src/infra/store/event-body.js +82 -0
  58. package/src/infra/store/events.js +149 -0
  59. package/src/infra/store/facts.js +338 -0
  60. package/src/infra/store/reconcile.js +173 -0
  61. package/src/infra/store/records.js +171 -0
  62. package/src/infra/store/runner-readers.js +16 -0
  63. package/src/infra/store/schema.js +306 -0
  64. package/src/infra/store/sessions.js +138 -0
  65. package/src/infra/store/tasks.js +351 -0
  66. package/src/infra/update/auto-update-worker.js +186 -0
  67. package/src/infra/update/auto-update.js +143 -0
  68. package/src/infra/update/update-check.js +246 -0
  69. package/src/infra/workspace-kind.js +165 -0
  70. package/src/infra/worktree.js +361 -0
  71. package/src/interface/bin/acceptance-cli.js +62 -0
  72. package/src/interface/bin/cleanup.js +81 -0
  73. package/src/interface/bin/monitor.jsx +301 -0
  74. package/src/interface/bin/setup.js +342 -0
  75. package/src/interface/bin/stage.js +17 -0
  76. package/src/interface/bin/web-server.js +53 -0
  77. package/src/interface/mcp/handlers/delivery.js +165 -0
  78. package/src/interface/mcp/handlers/dispatch.js +236 -0
  79. package/src/interface/mcp/handlers/facts.js +204 -0
  80. package/src/interface/mcp/handlers/overview.js +106 -0
  81. package/src/interface/mcp/handlers/results.js +262 -0
  82. package/src/interface/mcp/handlers/review.js +115 -0
  83. package/src/interface/mcp/handlers/wait.js +141 -0
  84. package/src/interface/mcp/meta.js +7 -0
  85. package/src/interface/mcp/result.js +34 -0
  86. package/src/interface/mcp/schemas.js +24 -0
  87. package/src/interface/mcp/server.js +64 -0
  88. package/src/interface/mcp/tools/deliver.js +48 -0
  89. package/src/interface/mcp/tools/dispatch.js +90 -0
  90. package/src/interface/mcp/tools/optional.js +57 -0
  91. package/src/interface/mcp/tools/read.js +115 -0
  92. package/src/interface/mcp/tools/run.js +57 -0
  93. package/src/interface/mcp/tools/shapes.js +67 -0
  94. package/src/interface/mcp/tools/track.js +84 -0
  95. package/src/interface/mcp/update-state.js +34 -0
  96. package/src/interface/mcp/views/overview.js +183 -0
  97. package/src/interface/mcp/views/task.js +224 -0
  98. package/src/interface/web/app.js +226 -0
  99. package/src/interface/web/views.js +227 -0
  100. package/src/mcp-server.js +4 -0
  101. package/src/run-host/entry.js +26 -0
  102. package/src/run-host/finalize.js +243 -0
  103. package/src/run-host/launch.js +49 -0
  104. package/src/run-host/live-run.js +76 -0
  105. package/src/run-host/outcome-facts.js +61 -0
  106. package/src/run-host/streams.js +102 -0
  107. package/src/run-host/track.js +132 -0
  108. package/src/runners/claude/adapter.js +118 -0
  109. package/src/runners/claude/events.js +100 -0
  110. package/src/runners/claude/tool-guard.js +48 -0
  111. package/src/runners/codex/adapter.js +157 -0
  112. package/src/runners/codex/chat-chunks.js +97 -0
  113. package/src/runners/codex/event-parser.js +266 -0
  114. package/src/runners/codex/goal-store.js +54 -0
  115. package/src/runners/codex/mcp-config.js +39 -0
  116. package/src/runners/codex/tool-guard.js +184 -0
  117. package/src/runners/contract-check.js +82 -0
  118. package/src/runners/contract.js +53 -0
  119. package/src/runners/registry.js +45 -0
  120. package/web/dist/assets/index-D-A2xlpx.js +154 -0
  121. package/web/dist/assets/index-f8esISCp.css +2 -0
  122. package/web/dist/index.html +15 -0
@@ -0,0 +1,61 @@
1
+ // A finished run's report becomes a candidate fact; acceptance passing turns
2
+ // it into the work item's verified outcome.
3
+ import { appendTaskEvent } from "../infra/store/events.js";
4
+ import { getWorkItemForTask, recordFact } from "../infra/store/facts.js";
5
+ import { updateWorkItemDelivery } from "../infra/store/records.js";
6
+
7
+ async function recordOutcomeFacts({ task, runId, report, reportEventId = null, acceptanceEventId = null, acceptancePassed = false }) {
8
+ if (!report?.valid) return;
9
+ const workItem = await getWorkItemForTask(task.id);
10
+ if (!workItem) return;
11
+ const validForManifestHash = task.run_evidence?.workspace?.after_manifest?.sha256 ?? null;
12
+ const candidate = await recordFact({
13
+ workItemId: workItem.id,
14
+ scopeType: "run",
15
+ scopeId: runId,
16
+ key: "worker_outcome",
17
+ value: report.report,
18
+ state: "candidate",
19
+ sourceEventId: reportEventId,
20
+ validForSha: task.base_commit ?? null,
21
+ validForContentHash: task.input_context?.content_hash ?? null,
22
+ validForManifestHash,
23
+ watchedPaths: task.owned_paths ?? []
24
+ });
25
+ if (!acceptancePassed || report.format === "text") return;
26
+ await recordFact({
27
+ workItemId: workItem.id,
28
+ scopeType: "work_item",
29
+ scopeId: workItem.id,
30
+ key: "accepted_outcome",
31
+ value: report.report,
32
+ state: "verified",
33
+ sourceEventId: acceptanceEventId,
34
+ validForSha: task.base_commit ?? null,
35
+ validForContentHash: task.input_context?.content_hash ?? null,
36
+ validForManifestHash,
37
+ watchedPaths: task.owned_paths ?? [],
38
+ supersedesId: candidate.id,
39
+ verifiedBy: "supervisor.acceptance"
40
+ });
41
+ await updateWorkItemDelivery(task.id, "verified");
42
+ }
43
+
44
+ // Fact projection is secondary evidence: a failure is recorded and reported,
45
+ // and never turns completed work into lost work.
46
+ export async function projectOutcomeFacts(run, finalRecord, { acceptanceEventId = null, acceptancePassed = false } = {}) {
47
+ try {
48
+ await recordOutcomeFacts({
49
+ task: finalRecord,
50
+ runId: run.runId,
51
+ report: finalRecord.run_evidence?.structured_report,
52
+ reportEventId: run.rawReportEventId,
53
+ acceptanceEventId,
54
+ acceptancePassed
55
+ });
56
+ } catch (error) {
57
+ await appendTaskEvent(finalRecord.id, { type: "supervisor.fact_record_failed", error: error.message, run: run.live.run_count },
58
+ { runId: run.runId, actor: "supervisor" }).catch(() => null);
59
+ process.stderr.write(`[agent-supervisor] fact projection failed for ${finalRecord.id}: ${error.message}\n`);
60
+ }
61
+ }
@@ -0,0 +1,102 @@
1
+ // Reads the worker's output: stdout lines become stored events and move the
2
+ // task row forward, stderr keeps a tail on the row.
3
+ import { splitLines } from "../app/worktree-setup.js";
4
+ import { appendTaskEvents } from "../infra/store/events.js";
5
+ import { runnerOf } from "../runners/registry.js";
6
+ import { persist } from "./live-run.js";
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
+
23
+ async function handleLines(run, lines) {
24
+ const runner = runnerOf(run.record);
25
+ const events = [];
26
+ const logged = [];
27
+ for (const line of lines) {
28
+ try {
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
+ }
34
+ } catch (error) {
35
+ logLine(run, `${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
36
+ }
37
+ }
38
+ if (events.length === 0) return;
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
+ });
45
+ let next = run.live;
46
+ for (const [index, event] of events.entries()) {
47
+ if (event.type === "item.completed" && event.item?.type === "agent_message") {
48
+ run.rawReport = event.item.text;
49
+ run.rawReportEventId = storedEvents[index].id;
50
+ }
51
+ if (["turn.completed", "turn.failed"].includes(event.type)) run.terminalEvent = true;
52
+ next = runner.parseEvent(next, event);
53
+ }
54
+ await persist(run, next);
55
+ }
56
+
57
+ // Lines that arrive in one tick are stored and applied as one batch.
58
+ export function queueEventLines(run, lines) {
59
+ run.pendingLines.push(...lines);
60
+ if (run.eventFlushPending) return;
61
+ run.eventFlushPending = true;
62
+ run.eventChain = run.eventChain.then(async () => {
63
+ await new Promise((resolveFlush) => setImmediate(resolveFlush));
64
+ const batch = run.pendingLines;
65
+ run.pendingLines = [];
66
+ run.eventFlushPending = false;
67
+ await handleLines(run, batch);
68
+ }).catch((error) => {
69
+ process.stderr.write(`[agent-supervisor] event handling failed for ${run.record.id}: ${error.message}\n`);
70
+ });
71
+ }
72
+
73
+ export function attachStreams(run, earlyOutput) {
74
+ const { child } = run;
75
+ const handleStdoutChunk = (chunk) => {
76
+ const split = splitLines(run.stdoutRest, chunk.toString("utf8"));
77
+ run.stdoutRest = split.rest;
78
+ const lines = split.lines.filter((line) => line.trim());
79
+ if (lines.length) queueEventLines(run, lines);
80
+ };
81
+ earlyOutput.capture = false;
82
+ for (const chunk of earlyOutput.stdout) handleStdoutChunk(chunk);
83
+ child.stdout.on("data", handleStdoutChunk);
84
+ child.stdout.on("error", () => {});
85
+
86
+ run.stderr = earlyOutput.stderr.map((chunk) => chunk.toString("utf8")).join("").slice(-STDERR_KEEP);
87
+ child.stderr.on("data", (chunk) => {
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);
91
+ persist(run, { ...run.live, stderr_tail: run.stderr.slice(-4000), updated_at: new Date().toISOString() });
92
+ });
93
+ child.stderr.on("error", () => {});
94
+
95
+ child.on("error", (error) => {
96
+ persist(run, {
97
+ ...run.live,
98
+ error: run.live.error ?? `codex process error: ${error.message}`,
99
+ updated_at: new Date().toISOString()
100
+ });
101
+ });
102
+ }
@@ -0,0 +1,132 @@
1
+ // Starts one worker process and tracks it to the end. Runs inside the detached
2
+ // run host, so the worker's output, exit and acceptance are recorded even when
3
+ // the MCP server that dispatched it is gone.
4
+ import "../app/compose.js";
5
+ import { failedStart, processes } from "../app/run-state.js";
6
+ import { captureExternalOutputs } from "../infra/external-output.js";
7
+ import { spawnProcess } from "../infra/process.js";
8
+ import { clearStage } from "../infra/stage-store.js";
9
+ import { appendTaskEvent, ensureRunRecord } from "../infra/store/events.js";
10
+ import { getTask } from "../infra/store/tasks.js";
11
+ import { snapshotTaskOutput } from "../infra/worktree.js";
12
+ import { loadRunner } from "../runners/registry.js";
13
+ import { finalizeChild } from "./finalize.js";
14
+ import { buildLaunch } from "./launch.js";
15
+ import { persist, startingRow, watchQuota } from "./live-run.js";
16
+ import { attachStreams } from "./streams.js";
17
+ import { createWriteStream, statSync } from "node:fs";
18
+
19
+ // Spawn can fail either by throwing synchronously, or by emitting "error"
20
+ // instead of "spawn". Both paths are handled so a bad CODEX_BIN marks the task
21
+ // failed instead of taking the whole MCP process down.
22
+ async function spawnAndAwaitStart(target, args, options) {
23
+ const child = spawnProcess(target.cmd, [...target.prefixArgs, ...args], options);
24
+ const earlyOutput = { stdout: [], stderr: [], capture: true };
25
+ child.stdout?.on("data", (chunk) => { if (earlyOutput.capture) earlyOutput.stdout.push(chunk); });
26
+ child.stderr?.on("data", (chunk) => { if (earlyOutput.capture) earlyOutput.stderr.push(chunk); });
27
+ const spawnError = await new Promise((resolvePromise) => {
28
+ let settled = false;
29
+ child.once("spawn", () => {
30
+ if (!settled) {
31
+ settled = true;
32
+ resolvePromise(null);
33
+ }
34
+ });
35
+ child.once("error", (error) => {
36
+ if (!settled) {
37
+ settled = true;
38
+ resolvePromise(error);
39
+ }
40
+ });
41
+ });
42
+ return { child, spawnError, earlyOutput };
43
+ }
44
+
45
+ // Everything the handlers of one run share. `live` is the task row as last
46
+ // written; the chains serialize row writes and event handling.
47
+ function openRun({ record, child, outputSchema, logPath, before, now }) {
48
+ return {
49
+ record, child, outputSchema, logPath, ...before,
50
+ priorAttemptFingerprint: record.run_evidence?.attempt_fingerprint ?? null,
51
+ reportOnlyRecovery: record.attention_reason === "invalid_report",
52
+ live: startingRow(record, child, outputSchema, now),
53
+ quotaReason: null, quotaWatch: null,
54
+ writeChain: Promise.resolve(), eventChain: Promise.resolve(),
55
+ terminalEvent: false, rawReport: null, rawReportEventId: null,
56
+ stdoutRest: "", pendingLines: [], eventFlushPending: false, stderr: "",
57
+ childSettled: false, runId: null, logStream: null
58
+ };
59
+ }
60
+
61
+ // A child that exits early makes a stdin write fail with EPIPE. That must not
62
+ // reach the process level, or one oversized prompt kills the run host.
63
+ function noteStdinFailure(run, error) {
64
+ return persist(run, {
65
+ ...run.live,
66
+ error: run.live.error ?? `stdin write failed: ${error.message}`,
67
+ updated_at: new Date().toISOString()
68
+ });
69
+ }
70
+
71
+ // finalizeChild runs detached from any caller. A rejection there would end the
72
+ // run host as an unhandled rejection, so it is reported and recorded instead.
73
+ // The note goes onto the row as it is stored now, not onto this process's last
74
+ // snapshot: another process may already have closed the row, and writing an
75
+ // older "running" snapshot over it would reopen a finished worker.
76
+ async function noteFinalizeFailure(run, error) {
77
+ process.stderr.write(`[agent-supervisor] finalize failed for ${run.record.id}: ${error.stack ?? error.message}\n`);
78
+ await appendTaskEvent(run.record.id, { type: "supervisor.finalize_failed", error: error.message, stack: String(error.stack ?? "").slice(0, 2000), run: run.live.run_count },
79
+ { runId: run.runId, actor: "supervisor" }).catch(() => null);
80
+ const stored = await getTask(run.record.id).catch(() => null);
81
+ const base = stored ?? run.live;
82
+ await persist(run, { ...base, error: base.error ?? `supervisor could not finish recording this run: ${error.message}`, updated_at: new Date().toISOString() });
83
+ }
84
+
85
+ export async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}, outputSchema = true }) {
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();
88
+ if (!capability.ok) return failedStart(record, capability.error);
89
+ const target = capability.target;
90
+ const before = {
91
+ outputBefore: snapshotTaskOutput(record),
92
+ workspaceBefore: record.workspace_metadata?.before_manifest ?? null,
93
+ externalBefore: await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [], { checkBaseline: (record.run_count ?? 0) === 0 })
94
+ };
95
+ const launch = buildLaunch({ record, args, prompt, outputSchema, externalBefore: before.externalBefore });
96
+ clearStage(record.id);
97
+
98
+ const { child, spawnError, earlyOutput } = await spawnAndAwaitStart(target, launch.guardedArgs, {
99
+ stdio: ["pipe", "pipe", "pipe"],
100
+ env: launch.env(),
101
+ windowsHide: true,
102
+ ...spawnOptions
103
+ });
104
+ if (spawnError) return failedStart(record, `failed to spawn ${target.cmd}: ${spawnError.message}`);
105
+
106
+ const now = new Date().toISOString();
107
+ const run = openRun({ record, child, outputSchema, logPath, before, now });
108
+ processes.set(record.id, child);
109
+ run.quotaWatch = watchQuota(run, now);
110
+ await persist(run, run.live);
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;
114
+ run.logStream = createWriteStream(logPath, { flags: "a" });
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; });
117
+ child.stdin.on("error", (error) => { noteStdinFailure(run, error); });
118
+ attachStreams(run, earlyOutput);
119
+
120
+ let settleRun;
121
+ const settled = new Promise((resolveSettled) => { settleRun = resolveSettled; });
122
+ const finalize = (code, signal) => { void finalizeChild(run, code, signal).catch((error) => noteFinalizeFailure(run, error)).finally(settleRun); };
123
+ child.once("close", finalize);
124
+ if (child.exitCode !== null || child.signalCode !== null) setImmediate(() => finalize(child.exitCode, child.signalCode));
125
+
126
+ try {
127
+ child.stdin.end(launch.prompt);
128
+ } catch (error) {
129
+ await noteStdinFailure(run, error);
130
+ }
131
+ return { ok: true, record: run.live, child, settled };
132
+ }
@@ -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
+ }