codex-supervisor-mcp 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +6 -1
- package/README.md +6 -1
- package/package.json +2 -2
- package/skills/codex-supervisor/SKILL.md +4 -2
- package/src/app/cancel.js +11 -14
- package/src/app/cleanup-facts.js +14 -12
- package/src/app/cleanup-plan.js +19 -18
- package/src/app/compose.js +13 -3
- package/src/app/dispatch.js +12 -12
- package/src/app/followup.js +5 -0
- package/src/app/resume.js +15 -18
- package/src/app/side-chat.js +41 -20
- package/src/app/worktree-setup.js +43 -2
- package/src/domain/failure-class.js +34 -2
- package/src/domain/prompt.js +7 -3
- package/src/domain/status.js +8 -4
- package/src/domain/worker-preflight.js +6 -2
- package/src/infra/crash-guard.js +44 -0
- package/src/infra/git.js +35 -4
- package/src/infra/stage-store.js +1 -1
- package/src/infra/store/event-body.js +82 -0
- package/src/infra/store/events.js +7 -5
- package/src/infra/store/runner-readers.js +1 -1
- package/src/infra/store/tasks.js +15 -1
- package/src/infra/worktree.js +25 -5
- package/src/interface/bin/web-server.js +2 -0
- package/src/interface/mcp/handlers/dispatch.js +3 -0
- package/src/interface/mcp/handlers/overview.js +4 -1
- package/src/interface/mcp/handlers/results.js +11 -4
- package/src/interface/mcp/handlers/wait.js +5 -3
- package/src/interface/mcp/server.js +3 -0
- package/src/interface/mcp/tools/dispatch.js +7 -5
- package/src/interface/mcp/tools/shapes.js +1 -0
- package/src/interface/web/app.js +2 -2
- package/src/interface/web/views.js +5 -3
- package/src/run-host/entry.js +3 -0
- package/src/run-host/finalize.js +8 -1
- package/src/run-host/launch.js +5 -19
- package/src/run-host/live-run.js +4 -1
- package/src/run-host/streams.js +35 -9
- package/src/run-host/track.js +8 -4
- package/src/runners/claude/adapter.js +118 -0
- package/src/runners/claude/events.js +100 -0
- package/src/runners/claude/tool-guard.js +48 -0
- package/src/runners/codex/adapter.js +57 -0
- package/src/runners/codex/mcp-config.js +4 -0
- package/src/runners/contract-check.js +82 -0
- package/src/runners/contract.js +53 -0
- package/src/runners/registry.js +45 -0
- package/web/dist/assets/{index-fJQbspTY.js → index-BnV-AYYI.js} +1 -1
- package/web/dist/assets/index-f8esISCp.css +2 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-DI1hLMxE.css +0 -2
|
@@ -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];
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The checks every runner has to pass, built in or not. It needs no test
|
|
2
|
+
// framework: give it the runner and a transcript (lines the CLI printed for
|
|
3
|
+
// one finished run) and it returns the problems it found, none when the
|
|
4
|
+
// runner is sound. docs/runner.md shows it inside a test.
|
|
5
|
+
import { assertRunner, CAPABILITIES } from "./contract.js";
|
|
6
|
+
|
|
7
|
+
const EVENT_TYPES = new Set(["thread.started", "turn.started", "turn.completed", "turn.failed", "item.started", "item.updated", "item.completed", "error"]);
|
|
8
|
+
const isStrings = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
9
|
+
|
|
10
|
+
function checkArgs(runner, problems) {
|
|
11
|
+
const start = runner.startArgs({ cwd: process.cwd(), sandbox: "workspace-write", model: null, reasoningEffort: "high", skipGitRepoCheck: true });
|
|
12
|
+
if (!isStrings(start)) problems.push("startArgs() must return an array of strings");
|
|
13
|
+
const record = { id: "contract-1", cwd: process.cwd(), sandbox: "workspace-write", guard_policy: {} };
|
|
14
|
+
for (const outputSchema of [true, false]) {
|
|
15
|
+
const launch = runner.launchArgs({ args: isStrings(start) ? start : [], record, outputSchema, writableRoots: [] });
|
|
16
|
+
if (!isStrings(launch)) problems.push(`launchArgs({ outputSchema: ${outputSchema} }) must return an array of strings`);
|
|
17
|
+
}
|
|
18
|
+
if (runner.capabilities.resume) {
|
|
19
|
+
const resume = runner.resumeArgs({ ...record, thread_id: "thread-1", model: null, reasoning_effort: "high" });
|
|
20
|
+
if (!isStrings(resume)) problems.push("resumeArgs() must return an array of strings");
|
|
21
|
+
else if (!resume.includes("thread-1")) problems.push("resumeArgs() must pass the stored thread_id to the CLI");
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function checkTranscript(runner, transcript, problems) {
|
|
26
|
+
const events = [];
|
|
27
|
+
for (const line of transcript) {
|
|
28
|
+
let produced;
|
|
29
|
+
try {
|
|
30
|
+
produced = runner.toEvents(line);
|
|
31
|
+
} catch (error) {
|
|
32
|
+
problems.push(`toEvents() threw on a transcript line: ${error.message}`);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (!Array.isArray(produced)) problems.push("toEvents() must return an array");
|
|
36
|
+
else events.push(...produced);
|
|
37
|
+
}
|
|
38
|
+
for (const event of events) {
|
|
39
|
+
if (!EVENT_TYPES.has(event?.type)) problems.push(`toEvents() produced an event outside the vocabulary: ${JSON.stringify(event).slice(0, 120)}`);
|
|
40
|
+
}
|
|
41
|
+
const started = events.find((event) => event.type === "thread.started");
|
|
42
|
+
if (!started?.thread_id) problems.push("the transcript must yield thread.started with a thread_id");
|
|
43
|
+
if (!["turn.completed", "turn.failed"].includes(events.at(-1)?.type)) problems.push("the transcript must end in turn.completed or turn.failed");
|
|
44
|
+
if (!events.some((event) => event.type === "item.completed" && event.item?.type === "agent_message" && typeof event.item.text === "string")) {
|
|
45
|
+
problems.push("the transcript must yield the worker's final message as an agent_message item");
|
|
46
|
+
}
|
|
47
|
+
let task = { id: "contract-1", status: "queued", commands: [], changed_files: [] };
|
|
48
|
+
try {
|
|
49
|
+
for (const event of events) task = runner.parseEvent(task, event);
|
|
50
|
+
if (started?.thread_id && task.thread_id !== started.thread_id) problems.push("parseEvent() must record the thread_id");
|
|
51
|
+
if (events.at(-1)?.type === "turn.completed" && task.status !== "completed") problems.push("parseEvent() must end a completed turn in status completed");
|
|
52
|
+
} catch (error) {
|
|
53
|
+
problems.push(`parseEvent() threw: ${error.message}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function checkRunner(runner, { transcript = [] } = {}) {
|
|
58
|
+
try {
|
|
59
|
+
assertRunner(runner);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
return [error.message];
|
|
62
|
+
}
|
|
63
|
+
const problems = [];
|
|
64
|
+
try {
|
|
65
|
+
checkArgs(runner, problems);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
problems.push(`building arguments threw: ${error.message}`);
|
|
68
|
+
}
|
|
69
|
+
let threw = false;
|
|
70
|
+
try {
|
|
71
|
+
runner.toEvents("this is not what the CLI prints {");
|
|
72
|
+
} catch {
|
|
73
|
+
threw = true;
|
|
74
|
+
}
|
|
75
|
+
// A line that is not an event is reported by the core; swallowing it would hide a broken CLI.
|
|
76
|
+
if (!threw) problems.push("toEvents() must throw on a line it cannot read");
|
|
77
|
+
if (transcript.length > 0) checkTranscript(runner, transcript, problems);
|
|
78
|
+
else problems.push("give a transcript: the lines the CLI printed for one finished run");
|
|
79
|
+
return problems;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export { CAPABILITIES };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// What a runner is. A runner is the only code that knows one CLI: its
|
|
2
|
+
// arguments, its output, how it is stopped. The core asks for these members
|
|
3
|
+
// and nothing else, and reads `capabilities` before using an optional one.
|
|
4
|
+
//
|
|
5
|
+
// Events. Whatever the CLI prints, `toEvents(line)` returns events in the
|
|
6
|
+
// supervisor's vocabulary, which is what is stored and what every reader
|
|
7
|
+
// understands:
|
|
8
|
+
//
|
|
9
|
+
// { type: "thread.started", thread_id }
|
|
10
|
+
// { type: "turn.started" }
|
|
11
|
+
// { type: "item.started" | "item.completed", item: { id, type, ... } }
|
|
12
|
+
// item.type "agent_message" { text }
|
|
13
|
+
// item.type "command_execution" { command, aggregated_output, exit_code, status }
|
|
14
|
+
// item.type "file_change" { changes: [{ path, kind }] }
|
|
15
|
+
// { type: "turn.completed", usage? }
|
|
16
|
+
// { type: "turn.failed", error: { message } }
|
|
17
|
+
//
|
|
18
|
+
// docs/runner.md walks through writing one.
|
|
19
|
+
export const CAPABILITIES = ["os_sandbox", "resume", "side_chat", "tool_guard", "structured_report", "native_goal"];
|
|
20
|
+
|
|
21
|
+
const REQUIRED = ["resolveTarget", "capabilityPreflight", "startArgs", "launchArgs", "toEvents", "parseEvent", "cancelChild", "cancelPid", "ownsPid"];
|
|
22
|
+
// Members a runner must have once it declares the capability.
|
|
23
|
+
const BY_CAPABILITY = { resume: ["resumeArgs"], side_chat: ["sideChat", "start"], native_goal: ["nativeGoal", "nativeGoalState"] };
|
|
24
|
+
|
|
25
|
+
// Throws with every problem at once, so a runner author fixes them in one pass.
|
|
26
|
+
export function assertRunner(runner, source = "runner") {
|
|
27
|
+
const problems = [];
|
|
28
|
+
if (!runner || typeof runner !== "object") throw new Error(`${source} does not export a runner object`);
|
|
29
|
+
if (typeof runner.name !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(runner.name)) problems.push("name must be a short lowercase identifier");
|
|
30
|
+
const capabilities = runner.capabilities ?? {};
|
|
31
|
+
for (const key of CAPABILITIES) if (typeof capabilities[key] !== "boolean") problems.push(`capabilities.${key} must be true or false`);
|
|
32
|
+
for (const key of Object.keys(capabilities)) if (!CAPABILITIES.includes(key)) problems.push(`capabilities.${key} is not a known capability`);
|
|
33
|
+
for (const member of REQUIRED) if (typeof runner[member] !== "function") problems.push(`${member}() is missing`);
|
|
34
|
+
for (const [capability, members] of Object.entries(BY_CAPABILITY)) {
|
|
35
|
+
if (capabilities[capability] !== true) continue;
|
|
36
|
+
for (const member of members) if (runner[member] == null) problems.push(`${member} is required by capabilities.${capability}`);
|
|
37
|
+
}
|
|
38
|
+
if (problems.length > 0) throw new Error(`${source} is not a valid runner: ${problems.join("; ")}`);
|
|
39
|
+
return runner;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// The error a caller gets for asking a runner for something it cannot do.
|
|
43
|
+
export function unsupported(runner, capability, what) {
|
|
44
|
+
return Object.assign(new Error(`${what} is not supported by the ${runner.name} runner (no ${capability})`), { code: "unsupported", capability, runner: runner.name });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Without an OS sandbox nothing but the worktree confines what a worker
|
|
48
|
+
// writes, so such a runner gets a worktree or a read-only run and nothing else.
|
|
49
|
+
export function assertWorkspaceAllowed(runnerName, confined, workspaceKind) {
|
|
50
|
+
if (confined !== false || ["git_worktree", "read_only_in_place"].includes(workspaceKind)) return;
|
|
51
|
+
throw Object.assign(new Error(`the ${runnerName} runner has no OS sandbox, so it can only run in a git_worktree or read_only_in_place workspace, not ${workspaceKind}`),
|
|
52
|
+
{ code: "unsupported", capability: "os_sandbox", runner: runnerName });
|
|
53
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Finds a runner by name. The two built in are always there; any other is a
|
|
2
|
+
// package named agent-supervisor-runner-<name>, or a file named by
|
|
3
|
+
// AGENT_SUPERVISOR_RUNNER_<NAME>, loaded the first time it is asked for.
|
|
4
|
+
import { assertRunner } from "./contract.js";
|
|
5
|
+
import { claudeRunner } from "./claude/adapter.js";
|
|
6
|
+
import { codexRunner } from "./codex/adapter.js";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_RUNNER = "codex";
|
|
10
|
+
const runners = new Map([[codexRunner.name, assertRunner(codexRunner, "codex")], [claudeRunner.name, assertRunner(claudeRunner, "claude")]]);
|
|
11
|
+
|
|
12
|
+
export const runnerNames = () => [...runners.keys()];
|
|
13
|
+
|
|
14
|
+
// For code that already has a task: the runner was loaded when it was dispatched
|
|
15
|
+
// in this process, or is loaded by loadRunner at the entry that reads the task.
|
|
16
|
+
export function getRunner(name = DEFAULT_RUNNER) {
|
|
17
|
+
const runner = runners.get(name ?? DEFAULT_RUNNER);
|
|
18
|
+
if (!runner) throw Object.assign(new Error(`runner "${name}" is not loaded`), { code: "runner_not_loaded" });
|
|
19
|
+
return runner;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export const runnerOf = (task) => getRunner(task?.worker ?? DEFAULT_RUNNER);
|
|
23
|
+
|
|
24
|
+
function externalSource(name) {
|
|
25
|
+
const fromEnv = process.env[`AGENT_SUPERVISOR_RUNNER_${name.toUpperCase().replace(/-/g, "_")}`]?.trim();
|
|
26
|
+
return fromEnv ? { specifier: pathToFileURL(fromEnv).href, label: fromEnv } : { specifier: `agent-supervisor-runner-${name}`, label: `agent-supervisor-runner-${name}` };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function loadRunner(name = DEFAULT_RUNNER) {
|
|
30
|
+
const wanted = name ?? DEFAULT_RUNNER;
|
|
31
|
+
if (runners.has(wanted)) return runners.get(wanted);
|
|
32
|
+
if (!/^[a-z][a-z0-9-]{0,31}$/.test(wanted)) throw Object.assign(new Error(`"${wanted}" is not a runner name`), { code: "runner_unknown" });
|
|
33
|
+
const { specifier, label } = externalSource(wanted);
|
|
34
|
+
let loaded;
|
|
35
|
+
try {
|
|
36
|
+
loaded = await import(specifier);
|
|
37
|
+
} catch (error) {
|
|
38
|
+
throw Object.assign(new Error(`runner "${wanted}" is not available: could not load ${label} (${error.message.split("\n")[0]}). Built in: ${runnerNames().join(", ")}`),
|
|
39
|
+
{ code: "runner_unknown" });
|
|
40
|
+
}
|
|
41
|
+
const runner = assertRunner(loaded.runner ?? loaded.default, label);
|
|
42
|
+
if (runner.name !== wanted) throw Object.assign(new Error(`${label} exports a runner named "${runner.name}", not "${wanted}"`), { code: "runner_unknown" });
|
|
43
|
+
runners.set(wanted, runner);
|
|
44
|
+
return runner;
|
|
45
|
+
}
|