agent-supervisor-mcp 0.0.0-stage → 2.0.1

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,24 @@
1
+ import { z } from "zod";
2
+
3
+ const acceptanceFailureRecord = z.object({
4
+ test_id: z.string().min(1), kind: z.enum(["failure", "error"]), signature: z.string().min(1)
5
+ }).strict();
6
+ export const acceptanceCheck = z.union([
7
+ z.string().min(1),
8
+ z.object({
9
+ command: z.string().min(1), reportPath: z.string().min(1),
10
+ baseline: z.object({
11
+ identity: z.object({ base_commit: z.string().min(1) }).catchall(z.string().min(1)),
12
+ failures: z.array(acceptanceFailureRecord), required: z.array(z.string().min(1))
13
+ }).strict()
14
+ }).strict()
15
+ ]);
16
+ export const acceptanceInput = z.union([z.string().min(1), z.array(acceptanceCheck).max(10)]);
17
+ export const workspaceSetupInput = z.object({
18
+ links: z.array(z.object({
19
+ path: z.string().min(1),
20
+ source: z.string().min(1)
21
+ }).strict()).max(20).optional(),
22
+ submodules: z.boolean().optional(),
23
+ commands: z.array(z.string().min(1)).max(20).optional()
24
+ }).strict();
@@ -0,0 +1,64 @@
1
+ #!/usr/bin/env node
2
+ import "../../app/compose.js";
3
+ import { installCrashGuard } from "../../infra/crash-guard.js";
4
+ import { syncSkills } from "../../infra/skill-sync.js";
5
+ import { packageVersion } from "./meta.js";
6
+ import { refreshUpdateState, UPDATE_RECHECK_MS } from "./update-state.js";
7
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
8
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
9
+ import { cancelWorkerTool, createWorkerTool, preflightWorkerTool, resumeWorkerTool } from "./tools/dispatch.js";
10
+ import { cleanupTool, landWorkerTool, verifyPushTool } from "./tools/deliver.js";
11
+ import { factsTool, getArtifactTool, reviewTool } from "./tools/optional.js";
12
+ import { askWorkerTool, describeSessionTool, findWorksTool, getWorkerDiffTool, getWorkerTool } from "./tools/read.js";
13
+ import { pollWorkersTool, waitWorkersTool } from "./tools/track.js";
14
+
15
+ installCrashGuard("mcp-server");
16
+
17
+ const server = new McpServer({
18
+ name: "agent-supervisor",
19
+ version: packageVersion
20
+ });
21
+
22
+ refreshUpdateState();
23
+ setInterval(() => refreshUpdateState({ force: true }), UPDATE_RECHECK_MS).unref();
24
+
25
+ // The skill describes this tool surface, so it moves with the server: a
26
+ // server fetched by `npx -y agent-supervisor-mcp@latest` never ran postinstall,
27
+ // and a global install only synced the skill on the day it was installed.
28
+ // Runs in the background; a client that cannot write its skill directory
29
+ // only costs a line on stderr.
30
+ if (!process.env.AGENT_SUPERVISOR_SKIP_SKILL_SYNC) {
31
+ syncSkills()
32
+ .then((result) => {
33
+ const changed = [...result.installed, ...result.updated];
34
+ if (changed.length > 0) {
35
+ process.stderr.write(
36
+ `[agent-supervisor] skill synced for ${changed.join(", ")}; a session that already loaded the skill keeps the old text until it loads it again\n`
37
+ );
38
+ }
39
+ for (const failure of result.failed) {
40
+ process.stderr.write(`[agent-supervisor] skill sync failed: ${failure}\n`);
41
+ }
42
+ })
43
+ .catch((error) => {
44
+ process.stderr.write(`[agent-supervisor] skill sync failed: ${error.message}\n`);
45
+ });
46
+ }
47
+
48
+ // The order is the order tools/list returns, which is the order a model reads
49
+ // them in: the path of a batch from preflight to cleanup.
50
+ const TOOLS = [
51
+ preflightWorkerTool, createWorkerTool, resumeWorkerTool, cancelWorkerTool,
52
+ pollWorkersTool, waitWorkersTool,
53
+ getWorkerTool, getWorkerDiffTool, askWorkerTool,
54
+ landWorkerTool, verifyPushTool, cleanupTool,
55
+ findWorksTool, describeSessionTool
56
+ ];
57
+ // The fact ledger, independent review and raw artifacts are rarely needed and
58
+ // cost context in every session, so they are opt-in.
59
+ const OPTIONAL_TOOLS = [factsTool, reviewTool, getArtifactTool];
60
+ const enabled = process.env.AGENT_SUPERVISOR_TOOLS === "all" ? [...TOOLS, ...OPTIONAL_TOOLS] : TOOLS;
61
+ for (const tool of enabled) server.registerTool(...tool);
62
+
63
+ const transport = new StdioServerTransport();
64
+ await server.connect(transport);
@@ -0,0 +1,48 @@
1
+ import { z } from "zod";
2
+ import { applyCleanupOp, cleanupHistoryOp, cleanupPlanOp, landCodexWorkerOp, verifyDeliveryPushOp } from "../handlers/delivery.js";
3
+ import { defineTool, run } from "./run.js";
4
+
5
+ export const landWorkerTool = defineTool("land_worker", {
6
+ title: "Land a worker's commits",
7
+ description: "Cherry-pick the worker's commits onto the branch checked out where it was dispatched. commit_message first commits its uncommitted edits, which is how a sandboxed worker's work gets committed. Refused when acceptance failed or has not run, the target is dirty, or the diff leaves owned_paths; a conflict leaves the target as it was. Read get_worker_diff first.",
8
+ inputSchema: {
9
+ task_id: z.string(),
10
+ commit_message: z.string().optional(),
11
+ onto: z.string().optional().describe("Refuse unless the target is on this branch"),
12
+ include_followup_parents: z.boolean().default(false).describe("Land the whole follow-up chain, root first"),
13
+ commit_messages: z.record(z.string(), z.string()).optional().describe("Task id to commit message, for the chain"),
14
+ ignore_acceptance: z.boolean().default(false).describe("Only when the user said so"),
15
+ allow_outside_owned: z.boolean().default(false).describe("Only when the user said so")
16
+ }
17
+ }, (args) => run(landCodexWorkerOp, {
18
+ task_id: args.task_id, onto: args.onto, commitMessage: args.commit_message, includeFollowupParents: args.include_followup_parents,
19
+ commitMessages: args.commit_messages, ignoreAcceptance: args.ignore_acceptance, allowOutsideOwned: args.allow_outside_owned
20
+ }));
21
+
22
+ export const verifyPushTool = defineTool("verify_push", {
23
+ title: "Prove landed work is on the remote",
24
+ description: "Fetch a remote branch and check the landed commit is reachable from it. It only verifies: it never pushes or deploys. Landing is local; this is the proof the work left the machine.",
25
+ inputSchema: {
26
+ task_id: z.string(),
27
+ remote: z.string().default("origin"),
28
+ branch: z.string().optional().describe("Default: the branch the work landed on")
29
+ }
30
+ }, (args) => run(verifyDeliveryPushOp, args));
31
+
32
+ export const cleanupTool = defineTool("cleanup", {
33
+ title: "Inspect or force worktree cleanup",
34
+ description: "Cleanup is automatic during poll_workers: landed or unchanged work goes at once, unlanded work after a hold period, with uncommitted edits committed to the worker's branch first; branches and evidence stay. Use this to see why a worktree is still there (plan), remove SAFE ones now (apply, with plan_id and item_ids), or read what was removed (history).",
35
+ inputSchema: {
36
+ action: z.enum(["plan", "apply", "history"]),
37
+ task_ids: z.array(z.string()).max(200).optional().describe("plan: limit to these workers; history: the first one"),
38
+ project_root: z.string().optional(),
39
+ plan_id: z.string().optional(),
40
+ item_ids: z.array(z.string()).max(200).optional(),
41
+ limit: z.number().int().min(1).max(500).optional()
42
+ }
43
+ }, (args) => {
44
+ if (args.action === "plan") return run(cleanupPlanOp, { task_ids: args.task_ids, project_root: args.project_root });
45
+ if (args.action === "history") return run(cleanupHistoryOp, { task_id: args.task_ids?.[0], limit: args.limit });
46
+ if (!args.plan_id || !args.item_ids?.length) return { error: "invalid_arguments", message: "apply needs plan_id and item_ids from a plan" };
47
+ return run(applyCleanupOp, { plan_id: args.plan_id, item_ids: args.item_ids });
48
+ });
@@ -0,0 +1,90 @@
1
+ import { z } from "zod";
2
+ import { cancelCodexWorkerOp } from "../handlers/delivery.js";
3
+ import { checkAcceptanceOp, createCodexFollowupWorkerOp, createCodexWorkerOp, preflightCodexWorkerOp, resumeCodexWorkerOp } from "../handlers/dispatch.js";
4
+ import { defineTool, run } from "./run.js";
5
+ import { acceptanceCommands, acceptanceShape, contextShape, dispatchOptions, group, limitsShape, only, sandboxShape, workspaceShape } from "./shapes.js";
6
+
7
+ const effort = z.enum(["minimal", "low", "medium", "high"]).optional();
8
+
9
+ export const preflightWorkerTool = defineTool("preflight_worker", {
10
+ title: "Check a worker's environment before dispatch",
11
+ description: "Prove the environment before spending a worker. probe_commands starts a short probe worker under the same workspace, sandbox and guard and returns its id: read it with get_worker include preflight, then pass it as preflight_id to create_worker with the same arguments. acceptance alone runs those commands in cwd now and returns their results.",
12
+ inputSchema: {
13
+ cwd: z.string(),
14
+ probe_commands: z.array(z.string()).min(1).max(20).optional().describe("Commands the probe must run"),
15
+ acceptance: acceptanceShape,
16
+ owned_paths: z.array(z.string()).optional().describe("Required with probe_commands"),
17
+ title: z.string().optional(),
18
+ runner: z.string().optional(),
19
+ model: z.string().optional(),
20
+ reasoning_effort: effort,
21
+ workspace: workspaceShape,
22
+ sandbox: sandboxShape,
23
+ context: contextShape,
24
+ limits: limitsShape
25
+ }
26
+ }, async (args) => {
27
+ const check = args.acceptance
28
+ ? await run(checkAcceptanceOp, {
29
+ cwd: args.cwd, acceptance: acceptanceCommands(args.acceptance.commands), baseRef: args.workspace?.base_ref, timeoutMs: args.acceptance.timeout_ms
30
+ })
31
+ : null;
32
+ if (!args.probe_commands) return check ?? { error: "invalid_arguments", message: "give probe_commands, acceptance, or both" };
33
+ if (check?.error) return check;
34
+ const probe = await run(preflightCodexWorkerOp, only(preflightCodexWorkerOp, { ...dispatchOptions(args), probeCommands: args.probe_commands }));
35
+ return check ? { ...probe, acceptance_check: check } : probe;
36
+ });
37
+
38
+ export const createWorkerTool = defineTool("create_worker", {
39
+ title: "Dispatch a worker",
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.",
41
+ inputSchema: {
42
+ task: z.string(),
43
+ cwd: z.string().optional().describe("Repository. 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"),
45
+ goal: group("{objective, token_budget}. Required unless followup_of"),
46
+ title: z.string().optional(),
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(),
51
+ model: z.string().optional(),
52
+ reasoning_effort: effort,
53
+ session: group("{id, title, note}: one id per batch"),
54
+ workspace: workspaceShape,
55
+ sandbox: sandboxShape,
56
+ context: contextShape,
57
+ acceptance: acceptanceShape,
58
+ limits: limitsShape
59
+ }
60
+ }, async (args) => {
61
+ const options = dispatchOptions(args);
62
+ if (args.followup_of) {
63
+ return run(createCodexFollowupWorkerOp, only(createCodexFollowupWorkerOp, { ...options, task_id: args.followup_of, followup_prompt: args.task }));
64
+ }
65
+ for (const name of ["cwd", "owned_paths", "goal"]) {
66
+ if (args[name] === undefined) return { error: "invalid_arguments", message: `${name} is required unless followup_of is given` };
67
+ }
68
+ return run(createCodexWorkerOp, only(createCodexWorkerOp, { ...options, task: args.task, preflight_id: args.preflight_id, dependsOn: args.depends_on }));
69
+ });
70
+
71
+ export const resumeWorkerTool = defineTool("resume_worker", {
72
+ title: "Continue a worker",
73
+ description: "Continue the same worker session with a new instruction, in its worktree; the thread keeps its history. Use it to fix what review found before landing. rebase_onto first moves the worktree onto a newer commit and refuses on conflict. A worktree removed by cleanup is restored from the worker's branch.",
74
+ inputSchema: {
75
+ task_id: z.string(),
76
+ prompt: z.string(),
77
+ rebase_onto: z.string().optional().describe("Commit or branch to rebase the worktree onto before continuing"),
78
+ context_files: z.array(z.object({ path: z.string(), sha256: z.string().optional() })).max(20).optional().describe("Replaces the worker's context files"),
79
+ acceptance: acceptanceShape.describe("Replaces the stored acceptance commands; an empty list clears them")
80
+ }
81
+ }, (args) => run(resumeCodexWorkerOp, {
82
+ task_id: args.task_id, prompt: args.prompt, rebaseOnto: args.rebase_onto, context: args.context_files,
83
+ acceptance: acceptanceCommands(args.acceptance?.commands)
84
+ }));
85
+
86
+ export const cancelWorkerTool = defineTool("cancel_worker", {
87
+ title: "Stop a worker",
88
+ description: "Stop a running worker or its acceptance run. Its worktree and what it changed so far stay.",
89
+ inputSchema: { task_id: z.string() }
90
+ }, (args) => run(cancelCodexWorkerOp, { task_id: args.task_id }));
@@ -0,0 +1,57 @@
1
+ // Tools most batches never need: the fact ledger, independent review and raw
2
+ // artifacts. They are registered only when AGENT_SUPERVISOR_TOOLS=all.
3
+ import { z } from "zod";
4
+ import { getArtifactOp, getFactOp, promoteWorkerFactOp, revokeWorkerFactOp, searchWorkerFactsOp } from "../handlers/facts.js";
5
+ import { createIndependentVerifierOp, getIndependentReviewOp, recordIndependentFindingOp, resolveIndependentFindingOp } from "../handlers/review.js";
6
+ import { defineTool, run } from "./run.js";
7
+
8
+ const FACT_ACTIONS = {
9
+ search: (args) => run(searchWorkerFactsOp, { task_id: args.task_id, query: args.query, limit: args.limit, cursor: args.cursor }),
10
+ get: (args) => run(getFactOp, { fact_id: args.fact_id }),
11
+ promote: (args) => run(promoteWorkerFactOp, { fact_id: args.fact_id, scope: args.scope, watchedPaths: args.watched_paths, expiresAt: args.expires_at }),
12
+ revoke: (args) => run(revokeWorkerFactOp, { fact_id: args.fact_id, reason: args.reason })
13
+ };
14
+
15
+ export const factsTool = defineTool("facts", {
16
+ title: "Read and manage verified facts",
17
+ description: "The ledger of what workers established. search: verified facts visible to a worker (its own, its dependencies', and repository facts whose watched paths and base still match). get: one fact with its versions. promote: the main thread turns a worker's candidate into a verified fact. revoke: withdraw one, with a reason. A worker cannot promote its own claims.",
18
+ inputSchema: {
19
+ action: z.enum(["search", "get", "promote", "revoke"]),
20
+ task_id: z.string().optional().describe("search"),
21
+ fact_id: z.string().optional().describe("get, promote, revoke"),
22
+ query: z.string().optional(),
23
+ limit: z.number().int().min(1).max(100).optional(),
24
+ cursor: z.string().optional(),
25
+ scope: z.enum(["work_item", "repo_verified"]).optional().describe("promote"),
26
+ watched_paths: z.array(z.string()).optional().describe("promote to repo_verified: paths whose change expires the fact"),
27
+ expires_at: z.string().optional(),
28
+ reason: z.string().optional().describe("revoke")
29
+ }
30
+ }, (args) => FACT_ACTIONS[args.action](args));
31
+
32
+ const REVIEW_ACTIONS = {
33
+ start: (args) => run(createIndependentVerifierOp, { task_id: args.task_id, title: args.title }),
34
+ record: (args) => run(recordIndependentFindingOp, { verifier_task_id: args.verifier_task_id, verdict: args.verdict, reason: args.reason }),
35
+ resolve: (args) => run(resolveIndependentFindingOp, { verifier_task_id: args.verifier_task_id, resolution: args.resolution }),
36
+ get: (args) => run(getIndependentReviewOp, { verifier_task_id: args.verifier_task_id })
37
+ };
38
+
39
+ export const reviewTool = defineTool("review", {
40
+ title: "Have settled work checked independently",
41
+ description: "start: dispatch a read-only, offline verifier that sees the goal and the worktree but not the worker's own report. record: store its verdict. resolve: store how a finding was closed. get: the whole trail.",
42
+ inputSchema: {
43
+ action: z.enum(["start", "record", "resolve", "get"]),
44
+ task_id: z.string().optional().describe("start: the worker to verify"),
45
+ verifier_task_id: z.string().optional().describe("record, resolve, get"),
46
+ title: z.string().optional(),
47
+ verdict: z.enum(["passes", "fails", "inconclusive"]).optional(),
48
+ reason: z.string().optional(),
49
+ resolution: z.string().optional()
50
+ }
51
+ }, (args) => REVIEW_ACTIONS[args.action](args));
52
+
53
+ export const getArtifactTool = defineTool("get_artifact", {
54
+ title: "Read a stored evidence artifact",
55
+ description: "One artifact the supervisor kept (a push proof, a review finding), by the id found in get_worker evidence.",
56
+ inputSchema: { artifact_id: z.string(), max_chars: z.number().int().min(0).max(1000000).optional() }
57
+ }, (args) => run(getArtifactOp, { artifact_id: args.artifact_id, maxChars: args.max_chars }));
@@ -0,0 +1,115 @@
1
+ import { z } from "zod";
2
+ import { getWorkerPreflightOp } from "../handlers/dispatch.js";
3
+ import { getContextSnapshotMetaOp, getWorkerEvidenceOp } from "../handlers/facts.js";
4
+ import { describeSessionOp, getCodexWorkerEventsOp, getCodexWorkerStatusOp, getSessionWorksOp, searchWorksOp } from "../handlers/overview.js";
5
+ import { askCodexWorkerOp, getWorkerDiffOp, getWorkerGoalOp, getWorkerResultOp, getWorkerSummaryOp } from "../handlers/results.js";
6
+ import { asData, defineTool, isFailure, run } from "./run.js";
7
+ import { acceptanceCommands } from "./shapes.js";
8
+
9
+ const PARTS = ["status", "result", "goal", "events", "evidence", "context", "preflight", "prompt"];
10
+
11
+ // A read that found the worker returns its row, which always has a status;
12
+ // "task_not_found" and the like do not. Only the former is data.
13
+ const row = async (reading) => {
14
+ const payload = await reading;
15
+ return payload?.status === undefined ? payload : asData(payload);
16
+ };
17
+
18
+ // Each part of a worker and the operation that reads it.
19
+ const READERS = {
20
+ status: (args) => row(run(getCodexWorkerStatusOp, { task_id: args.task_id, includePrompt: args.include.includes("prompt") })),
21
+ result: (args) => row(run(getWorkerResultOp, {
22
+ task_id: args.task_id, maxChars: args.max_chars, limit: args.result_limit, includeFiles: args.include_files
23
+ })),
24
+ goal: (args) => run(getWorkerGoalOp, { task_id: args.task_id }),
25
+ events: (args) => run(getCodexWorkerEventsOp, { task_id: args.task_id, limit: args.event_limit, kinds: args.event_kinds, maxChars: args.max_chars }),
26
+ evidence: (args) => run(getWorkerEvidenceOp, { task_id: args.task_id }),
27
+ context: (args) => run(getContextSnapshotMetaOp, { task_id: args.task_id }),
28
+ preflight: (args) => row(run(getWorkerPreflightOp, { task_id: args.task_id }))
29
+ };
30
+
31
+ export const getWorkerTool = defineTool("get_worker", {
32
+ title: "Read one worker",
33
+ description: "One worker, in the parts you ask for. No include: a one-paragraph summary; one part: that part; several: an object keyed by part. result: its report, the supervisor's acceptance verdict and the commands it really ran. status: live state. events: the raw stream. goal: objective and token use. preflight: a probe's verdict. evidence, context: what was recorded and given. prompt: the task text. A report is a claim; acceptance and get_worker_diff are the evidence.",
34
+ inputSchema: {
35
+ task_id: z.string(),
36
+ include: z.array(z.enum(PARTS)).default([]),
37
+ max_chars: z.number().int().min(0).max(1000000).optional().describe("Cap on report or event text; default 6000 for result"),
38
+ event_limit: z.number().int().min(1).max(1000).optional(),
39
+ event_kinds: z.array(z.string()).optional(),
40
+ result_limit: z.number().int().min(1).max(20).optional().describe("Earlier runs too"),
41
+ include_files: z.boolean().optional().describe("List changed files")
42
+ }
43
+ }, async (args) => {
44
+ const wanted = args.include.includes("prompt") && !args.include.includes("status") ? [...args.include, "status"] : args.include;
45
+ const parts = wanted.filter((part) => READERS[part]);
46
+ if (parts.length === 0) return row(run(getWorkerSummaryOp, { task_id: args.task_id }));
47
+ // One part comes back as itself; several come back keyed by part.
48
+ if (parts.length === 1) return READERS[parts[0]]({ ...args, include: wanted });
49
+ const out = { task_id: args.task_id };
50
+ for (const part of parts) {
51
+ const payload = await READERS[part]({ ...args, include: wanted });
52
+ if (isFailure(payload)) return payload;
53
+ out[part] = payload;
54
+ }
55
+ return out;
56
+ });
57
+
58
+ export const getWorkerDiffTool = defineTool("get_worker_diff", {
59
+ title: "Read what a worker changed",
60
+ description: "The worker's actual changes against its base, committed or not. Without file: the list of files with line counts and hunk counts. With file: that file's patch, paged by hunk (cursor from the previous page). Read this before landing; it is what the worker did, whatever it reported.",
61
+ inputSchema: {
62
+ task_id: z.string(),
63
+ file: z.string().optional(),
64
+ hunk: z.number().int().min(0).optional().describe("Start at this hunk of the file"),
65
+ page_size: z.number().int().min(1).max(20).default(4).describe("Hunks per page"),
66
+ cursor: z.string().optional(),
67
+ max_chars: z.number().int().min(0).max(1000000).optional().describe("With no file: return every patch in one reply, capped at this size"),
68
+ paths: z.array(z.string()).optional().describe("Limit the diff to these paths")
69
+ }
70
+ }, (args) => run(getWorkerDiffOp, {
71
+ task_id: args.task_id, file: args.file, hunk: args.hunk, pageSize: args.page_size, cursor: args.cursor, maxChars: args.max_chars, paths: args.paths
72
+ }));
73
+
74
+ export const askWorkerTool = defineTool("ask_worker", {
75
+ title: "Ask a worker a side question",
76
+ description: "Ask the worker why it did something without touching its work: its thread is forked into a read-only session with no network and no MCP tools, and the fork answers. Follow-up questions continue that fork; fresh starts a new one from the worker's current thread, end deletes it.",
77
+ inputSchema: {
78
+ task_id: z.string(),
79
+ question: z.string().optional(),
80
+ timeout_ms: z.number().int().min(1000).max(600000).default(110000),
81
+ max_chars: z.number().int().min(0).max(1000000).default(8000),
82
+ fresh: z.boolean().default(false),
83
+ end: z.boolean().default(false)
84
+ }
85
+ }, (args) => run(askCodexWorkerOp, {
86
+ task_id: args.task_id, question: args.question, timeoutMs: args.timeout_ms, maxChars: args.max_chars, fresh: args.fresh, end: args.end
87
+ }));
88
+
89
+ export const findWorksTool = defineTool("find_works", {
90
+ title: "Find earlier work",
91
+ description: "Every worker of one session, or a substring search over titles, goals, prompts and last messages, newest first. Use it before dispatching to see whether the work was already done, and after a restart to pick a batch up again.",
92
+ inputSchema: {
93
+ session_id: z.string().optional(),
94
+ query: z.string().optional(),
95
+ limit: z.number().int().min(1).max(100).optional()
96
+ }
97
+ }, (args) => {
98
+ if (args.session_id) return run(getSessionWorksOp, { session_id: args.session_id });
99
+ if (args.query) return run(searchWorksOp, { query: args.query, limit: args.limit });
100
+ return { error: "invalid_arguments", message: "give session_id or query" };
101
+ });
102
+
103
+ export const describeSessionTool = defineTool("describe_session", {
104
+ title: "Describe a batch",
105
+ description: "Record what a session is for and the rules its workers share: a title and note, an objective, acceptance commands added to every worker of the session, and an approval state. waiting_user stops dispatch, resume and landing in the session until it is approved again.",
106
+ inputSchema: {
107
+ session_id: z.string(),
108
+ title: z.string().max(120).optional(),
109
+ note: z.string().max(2000).optional(),
110
+ objective: z.string().max(5000).optional(),
111
+ default_acceptance: z.array(z.union([z.string(), z.record(z.string(), z.unknown())])).max(10).optional(),
112
+ approval_state: z.enum(["approved", "waiting_user"]).optional(),
113
+ expected_revision: z.number().int().nonnegative().optional().describe("Refuse the change if the session policy moved past this revision")
114
+ }
115
+ }, (args) => run(describeSessionOp, { ...args, default_acceptance: acceptanceCommands(args.default_acceptance) }));
@@ -0,0 +1,57 @@
1
+ // How a public tool reaches the operation behind it. An operation validates
2
+ // its own input and answers with a text result; a tool maps the public
3
+ // arguments onto it and shapes the reply.
4
+ import { z } from "zod";
5
+ import { textResult } from "../result.js";
6
+
7
+ const defined = (object) => Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined));
8
+
9
+ // Runs one operation and returns its payload as a plain value.
10
+ export async function run(op, args, extra) {
11
+ const parsed = op.input.safeParse(defined(args));
12
+ if (!parsed.success) {
13
+ const issue = parsed.error.issues[0];
14
+ return { error: "invalid_arguments", message: `${issue.path.join(".") || "arguments"}: ${issue.message}` };
15
+ }
16
+ const result = await op.handler(parsed.data, extra);
17
+ const text = result?.content?.[0]?.text ?? "null";
18
+ try {
19
+ return JSON.parse(text);
20
+ } catch {
21
+ return text;
22
+ }
23
+ }
24
+
25
+ // A worker's row has an `error` field of its own: the text of what went wrong
26
+ // with the worker. Reading a failed worker is a successful call, so a payload
27
+ // that is such a row is marked as data and its `error` is left alone.
28
+ const DATA = Symbol("data");
29
+
30
+ export function asData(payload) {
31
+ if (payload && typeof payload === "object") Object.defineProperty(payload, DATA, { value: true });
32
+ return payload;
33
+ }
34
+
35
+ export const isFailure = (payload) => Boolean(payload) && typeof payload === "object" && typeof payload.error === "string" && !payload[DATA];
36
+
37
+ // A payload whose top level carries `error` is a failed call, and says so in
38
+ // the protocol as well as in the text.
39
+ export function reply(payload) {
40
+ const result = textResult(payload);
41
+ if (isFailure(payload)) result.isError = true;
42
+ return result;
43
+ }
44
+
45
+ // Unknown arguments are refused, not dropped: a caller still using a name from
46
+ // an older version gets told so instead of running with a silent default.
47
+ export function defineTool(name, config, handler) {
48
+ return [name, { ...config, inputSchema: z.strictObject(config.inputSchema) }, async (args, extra) => {
49
+ try {
50
+ return reply(await handler(args ?? {}, extra));
51
+ } catch (error) {
52
+ return reply({ error: error.code ?? "internal_error", message: error.message });
53
+ }
54
+ }];
55
+ }
56
+
57
+ export { defined };
@@ -0,0 +1,67 @@
1
+ // The argument groups dispatch and preflight share, and the mapping from the
2
+ // public names onto the operations' own.
3
+ import { z } from "zod";
4
+
5
+ // The public schema describes each group in one line instead of spelling out
6
+ // every nested field: the nested JSON Schema cost more context than every
7
+ // other tool put together. The operation behind the tool validates the
8
+ // fields strictly, so a wrong key or value still comes back as a clear error.
9
+ export const group = (text) => z.looseObject({}).optional().describe(text);
10
+
11
+ export const sandboxShape = group("{mode: read-only | workspace-write (default) | danger-full-access, network_access, writable_roots: [abs dirs], allowed_commands: [commands; trailing * = prefix], forbid: [paths or commands]}");
12
+
13
+ export const workspaceShape = group("{kind: git_worktree (default) | read_only_in_place | scratch | in_place_write, base_ref, setup: {links: [{path, source}], submodules, commands} run first, in_place_authorization, external_outputs: [{path}]}");
14
+
15
+ export const contextShape = group("{files: [{path}] abs paths to read, contracts: [binding statements]}");
16
+
17
+ export const acceptanceShape = group("{commands, timeout_ms}: shell commands the supervisor runs in the worktree after the worker exits; all must exit 0");
18
+
19
+ export const limitsShape = group("{max_run_ms, max_total_ms}");
20
+
21
+ const check = (entry) => (typeof entry === "string" ? entry : { command: entry.command, reportPath: entry.report_path ?? entry.reportPath, baseline: entry.baseline });
22
+
23
+ // Public acceptance commands -> the operations' shape.
24
+ export function acceptanceCommands(commands) {
25
+ if (commands === undefined) return undefined;
26
+ return Array.isArray(commands) ? commands.map(check) : commands;
27
+ }
28
+
29
+ // Public dispatch arguments -> the flat names the operations take.
30
+ export function dispatchOptions(args) {
31
+ const { sandbox = {}, workspace = {}, context = {}, acceptance, limits = {}, session = {}, goal } = args;
32
+ return {
33
+ title: args.title,
34
+ runner: args.runner,
35
+ cwd: args.cwd,
36
+ model: args.model,
37
+ reasoningEffort: args.reasoning_effort,
38
+ ownedPaths: args.owned_paths,
39
+ goal: goal ? { objective: goal.objective, tokenBudget: goal.token_budget } : undefined,
40
+ session_id: session.id,
41
+ session_title: session.title,
42
+ session_note: session.note,
43
+ sandbox: sandbox.mode,
44
+ networkAccess: sandbox.network_access,
45
+ writableRoots: sandbox.writable_roots,
46
+ allowedCommands: sandbox.allowed_commands,
47
+ forbid: sandbox.forbid,
48
+ workspaceKind: workspace.kind,
49
+ baseRef: workspace.base_ref,
50
+ workspaceSetup: workspace.setup,
51
+ inPlaceAuthorization: workspace.in_place_authorization,
52
+ skipGitRepoCheck: workspace.skip_git_repo_check,
53
+ externalOutputs: workspace.external_outputs,
54
+ context: context.files,
55
+ contracts: context.contracts,
56
+ acceptance: acceptanceCommands(acceptance?.commands),
57
+ acceptanceTimeoutMs: acceptance?.timeout_ms,
58
+ maxRunMs: limits.max_run_ms,
59
+ maxTotalMs: limits.max_total_ms
60
+ };
61
+ }
62
+
63
+ // Keeps only the names an operation knows, so one mapping serves several.
64
+ export function only(op, options) {
65
+ const known = new Set(Object.keys(op.input.shape));
66
+ return Object.fromEntries(Object.entries(options).filter(([key, value]) => known.has(key) && value !== undefined));
67
+ }
@@ -0,0 +1,84 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { sweepCleanup } from "../../../app/auto-cleanup.js";
4
+ import { recoverEligibleRuns } from "../../../app/resume.js";
5
+ import { ACTIVE_STATUSES, TASK_STATUSES } from "../../../domain/status.js";
6
+ import { collectWorkerChanges } from "../../../domain/worker-changes.js";
7
+ import { cleanupHint } from "../../../infra/cleanup-hint.js";
8
+ import { reconcileDetachedActiveTasks } from "../../../infra/store/reconcile.js";
9
+ import { readObserverCursor, readTasks, writeObserverCursor } from "../../../infra/store/tasks.js";
10
+ import { waitCodexWorkersOp } from "../handlers/wait.js";
11
+ import { packageVersion } from "../meta.js";
12
+ import { updateField, updateState } from "../update-state.js";
13
+ import { buildOverview } from "../views/overview.js";
14
+ import { defineTool, run } from "./run.js";
15
+
16
+ // Polls from one process run one at a time: recovery and cleanup must not overlap themselves.
17
+ let pollChain = Promise.resolve();
18
+
19
+ // With a cursor this is the loop tick: it reports what changed and does the
20
+ // housekeeping a loop is for (one recovery of a dead first run, cleanup).
21
+ // Without one it is a plain read of the table and starts nothing.
22
+ async function pollOnce({ cursor, status, limit }) {
23
+ await reconcileDetachedActiveTasks();
24
+ if (cursor) {
25
+ const recoveries = await recoverEligibleRuns();
26
+ const cleaned = await sweepCleanup();
27
+ const cleanup = await cleanupHint();
28
+ const tasks = await readTasks();
29
+ const changes = collectWorkerChanges(tasks, await readObserverCursor(cursor));
30
+ await writeObserverCursor(cursor, changes.cursor);
31
+ return {
32
+ generated_at: new Date().toISOString(),
33
+ quiet: changes.quiet && recoveries.length === 0 && cleaned.length === 0,
34
+ active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
35
+ transitions: changes.transitions,
36
+ attention: changes.attention,
37
+ recoveries,
38
+ ...(cleaned.length ? { cleaned } : {}),
39
+ ...(cleanup ? { cleanup } : {}),
40
+ next_cursor: cursor
41
+ };
42
+ }
43
+ const tasks = await readTasks();
44
+ // The cursor handed out here makes the next poll report only what changes from now on.
45
+ const token = `poll-${randomUUID().slice(0, 12)}`;
46
+ await writeObserverCursor(token, collectWorkerChanges(tasks, {}).cursor);
47
+ const shown = (status ? tasks.filter((task) => task.status === status) : tasks).slice(-limit);
48
+ const update = updateField() ?? { update_available: false, installed_version: packageVersion, checked: updateState?.source ?? "pending" };
49
+ return buildOverview(shown, { version: packageVersion, update, next_cursor: token });
50
+ }
51
+
52
+ export const pollWorkersTool = defineTool("poll_workers", {
53
+ title: "See what the workers are doing",
54
+ description: "The main thread's read. Without cursor: a compact table of every worker and a next_cursor. With that cursor: only what happened since, as transitions (finished, failed, needs attention) with the next step; quiet when nothing did. A poll with a cursor also recovers a dead first run once and removes safe worktrees (listed under cleaned). Call it from a loop.",
55
+ inputSchema: {
56
+ cursor: z.string().optional().describe("next_cursor from the previous poll"),
57
+ status: z.enum(TASK_STATUSES).optional().describe("Filter the full table"),
58
+ limit: z.number().int().min(1).max(200).default(50).describe("Rows in the full table, newest last")
59
+ }
60
+ }, (args) => {
61
+ const poll = pollChain.then(() => pollOnce(args));
62
+ pollChain = poll.catch(() => {});
63
+ return poll;
64
+ });
65
+
66
+ export const waitWorkersTool = defineTool("wait_workers", {
67
+ title: "Wait for workers to finish",
68
+ description: "Block until the given workers settle (process exited and acceptance run), then return one row each. A call waits 60 seconds at most and says so in timed_out; call again with the same ids. allow_long_wait lifts the cap only when the client's own tool timeout is known to be longer.",
69
+ inputSchema: {
70
+ task_ids: z.array(z.string()).min(1),
71
+ mode: z.enum(["any", "all"]).default("all"),
72
+ timeout_ms: z.number().int().min(1000).max(21600000).optional(),
73
+ allow_long_wait: z.boolean().default(false),
74
+ emit_progress: z.boolean().default(false).describe("Send progress notifications while waiting"),
75
+ compact: z.boolean().optional().describe("One short row per worker; the default unless include_events"),
76
+ include_events: z.boolean().default(false),
77
+ event_limit: z.number().int().min(1).max(50).default(10),
78
+ poll_ms: z.number().int().min(250).max(10000).optional()
79
+ }
80
+ }, (args, extra) => run(waitCodexWorkersOp, {
81
+ task_ids: args.task_ids, mode: args.mode, timeoutMs: args.timeout_ms ?? 60000, allowLongWait: args.allow_long_wait, emitProgress: args.emit_progress,
82
+ compact: args.compact, includeEvents: args.include_events, eventLimit: args.event_limit,
83
+ pollMs: args.poll_ms
84
+ }, extra));
@@ -0,0 +1,34 @@
1
+ import { maybeAutoUpdate } from "../../infra/update/auto-update.js";
2
+ import { checkForUpdate, updateNotice } from "../../infra/update/update-check.js";
3
+
4
+ // Nobody should keep running an old build without hearing about it. The
5
+ // registry is asked once at start and every six hours after; the answer
6
+ // rides along in the overview, the dispatch receipt and the wait response,
7
+ // which are the calls every orchestrating session makes.
8
+ export const UPDATE_RECHECK_MS = 6 * 60 * 60 * 1000;
9
+ export let updateState = null;
10
+ // The last word from auto-update.js: null until a check found a newer
11
+ // version, then started | running | done | failed | skipped.
12
+ export let autoUpdateState = null;
13
+ export async function refreshUpdateState({ force = false } = {}) {
14
+ try {
15
+ updateState = await checkForUpdate({ force });
16
+ autoUpdateState = await maybeAutoUpdate(updateState);
17
+ const notice = updateNotice(updateState, autoUpdateState)?.notice;
18
+ if (notice) process.stderr.write(`[agent-supervisor] ${notice}\n`);
19
+ } catch (error) {
20
+ process.stderr.write(`[agent-supervisor] update check failed: ${error.message}\n`);
21
+ }
22
+ return updateState;
23
+ }
24
+
25
+ // The short form for tool results: null when the install is current.
26
+ export function updateField() {
27
+ return updateNotice(updateState, autoUpdateState);
28
+ }
29
+
30
+ // Spread into a result: adds `update` only when there is something to say.
31
+ export function withUpdate(payload) {
32
+ const update = updateField();
33
+ return update ? { ...payload, update } : payload;
34
+ }