codex-supervisor-mcp 0.13.4 → 0.13.6

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 (103) hide show
  1. package/README.en.md +101 -297
  2. package/README.md +99 -310
  3. package/package.json +24 -63
  4. package/src/{acceptance.js → app/acceptance.js} +54 -68
  5. package/src/app/cancel.js +60 -0
  6. package/src/{cleanup-plan.js → app/cleanup-plan.js} +13 -14
  7. package/src/app/compose.js +7 -0
  8. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  9. package/src/app/dispatch.js +396 -0
  10. package/src/app/followup.js +98 -0
  11. package/src/app/land-chain.js +124 -0
  12. package/src/app/landing.js +357 -0
  13. package/src/app/ownership.js +57 -0
  14. package/src/app/rebase.js +216 -0
  15. package/src/app/resume.js +164 -0
  16. package/src/app/run-state.js +26 -0
  17. package/src/app/settled.js +28 -0
  18. package/src/{side-chat.js → app/side-chat.js} +79 -266
  19. package/src/app/sse.js +20 -0
  20. package/src/app/start-run.js +77 -0
  21. package/src/app/verify-push.js +119 -0
  22. package/src/app/worktree-setup.js +176 -0
  23. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  24. package/src/domain/acceptance-spec.js +30 -0
  25. package/src/domain/command-outcome.js +6 -0
  26. package/src/{overview-delta.js → domain/overview-delta.js} +5 -1
  27. package/src/domain/side-turn-view.js +73 -0
  28. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  29. package/src/infra/git.js +30 -0
  30. package/src/infra/process.js +59 -0
  31. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  32. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  33. package/src/infra/store/db.js +265 -0
  34. package/src/infra/store/events.js +146 -0
  35. package/src/infra/store/facts.js +338 -0
  36. package/src/infra/store/reconcile.js +172 -0
  37. package/src/infra/store/records.js +160 -0
  38. package/src/infra/store/runner-readers.js +16 -0
  39. package/src/infra/store/schema.js +306 -0
  40. package/src/infra/store/sessions.js +138 -0
  41. package/src/infra/store/tasks.js +307 -0
  42. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  43. package/src/{auto-update.js → infra/update/auto-update.js} +3 -4
  44. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  45. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  46. package/src/{worktree.js → infra/worktree.js} +57 -42
  47. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  48. package/src/{cleanup.js → interface/bin/cleanup.js} +3 -2
  49. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  50. package/src/{setup.js → interface/bin/setup.js} +9 -8
  51. package/src/{stage.js → interface/bin/stage.js} +1 -1
  52. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  53. package/src/interface/mcp/meta.js +7 -0
  54. package/src/interface/mcp/result.js +34 -0
  55. package/src/interface/mcp/schemas.js +24 -0
  56. package/src/interface/mcp/server.js +94 -0
  57. package/src/interface/mcp/tools/delivery.js +197 -0
  58. package/src/interface/mcp/tools/dispatch.js +267 -0
  59. package/src/interface/mcp/tools/facts.js +239 -0
  60. package/src/interface/mcp/tools/overview.js +202 -0
  61. package/src/interface/mcp/tools/poll.js +62 -0
  62. package/src/interface/mcp/tools/results.js +270 -0
  63. package/src/interface/mcp/tools/review.js +135 -0
  64. package/src/interface/mcp/tools/wait.js +145 -0
  65. package/src/interface/mcp/update-state.js +34 -0
  66. package/src/interface/mcp/views/overview.js +183 -0
  67. package/src/interface/mcp/views/task.js +223 -0
  68. package/src/interface/web/app.js +226 -0
  69. package/src/interface/web/views.js +224 -0
  70. package/src/mcp-server.js +3 -2223
  71. package/src/run-host/entry.js +23 -0
  72. package/src/run-host/finalize.js +236 -0
  73. package/src/run-host/launch.js +63 -0
  74. package/src/run-host/live-run.js +73 -0
  75. package/src/run-host/outcome-facts.js +61 -0
  76. package/src/run-host/streams.js +76 -0
  77. package/src/run-host/track.js +128 -0
  78. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  79. package/src/runners/codex/chat-chunks.js +97 -0
  80. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  81. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  82. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  83. package/src/codex-runner.js +0 -1586
  84. package/src/landing.js +0 -507
  85. package/src/task-store.js +0 -1800
  86. package/src/web-app.js +0 -425
  87. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  88. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  89. /package/src/{prompt.js → domain/prompt.js} +0 -0
  90. /package/src/{status.js → domain/status.js} +0 -0
  91. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  92. /package/src/{truncate.js → domain/truncate.js} +0 -0
  93. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  94. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  95. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  96. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  97. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  98. /package/src/{cleanup-hint.js → infra/cleanup-hint.js} +0 -0
  99. /package/src/{external-output.js → infra/external-output.js} +0 -0
  100. /package/src/{handoff.js → infra/handoff.js} +0 -0
  101. /package/src/{paths.js → infra/paths.js} +0 -0
  102. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  103. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
package/src/mcp-server.js CHANGED
@@ -1,2224 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync, readFileSync } from "node:fs";
3
- import { execFileSync } from "node:child_process";
4
- import { createHash, randomUUID } from "node:crypto";
5
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
- import { z } from "zod";
8
- import {
9
- cancelCodexWorker,
10
- recoverEligibleRuns,
11
- createCodexWorker,
12
- createFollowupWorker,
13
- resumeCodexWorker
14
- } from "./codex-runner.js";
15
- import {
16
- getSession,
17
- getArtifact,
18
- getFact,
19
- getFactEffectiveState,
20
- isFactRevoked,
21
- getReviewByVerifierTask,
22
- getTaskForWorkItem,
23
- getWorkItemForTask,
24
- getTask,
25
- getTasks,
26
- isPidAlive,
27
- listTaskEventKinds,
28
- listArtifactsForTask,
29
- listContextFacts,
30
- countVerifiedFacts,
31
- readArtifact,
32
- readTaskEventRecords,
33
- readAgentMessages,
34
- readTaskEvents,
35
- readTasks,
36
- readObserverCursor,
37
- writeObserverCursor,
38
- readTasksBySession,
39
- latestContextSnapshotForTask,
40
- reconcileDetachedActiveTasks,
41
- recordTerminalChangedFiles,
42
- searchTasks,
43
- upsertSession,
44
- upsertTask,
45
- appendTaskEvent,
46
- recordFact,
47
- recordJsonArtifact,
48
- createReviewAssignment,
49
- recordReviewFinding,
50
- resolveReviewFinding,
51
- promoteCandidateFact,
52
- revokeFact,
53
- runIdFor,
54
- updateWorkItemDelivery,
55
- saveCleanupPlan,
56
- getCleanupPlan,
57
- readCleanupHistory
58
- } from "./task-store.js";
59
- import { readNativeGoal, readNativeGoalState } from "./goal-store.js";
60
- import { collectWorkerChanges } from "./worker-changes.js";
61
- import { buildHostGoalSync } from "./prompt.js";
62
- import { baseBehind, readTaskChanges, readWorktreeDiff, splitPatchHunks, workspaceSetupIgnorePaths, worktreeRef } from "./worktree.js";
63
- import { summarizeVerification } from "./event-parser.js";
64
- import { readPreflightResult } from "./worker-preflight.js";
65
- import { acceptanceVerdict, runAcceptance } from "./acceptance.js";
66
- import { classifyFailure } from "./failure-class.js";
67
- import { threadHealth } from "./thread-health.js";
68
- import { readStage } from "./stage-store.js";
69
- import { ACTIVE_STATUSES, TERMINAL_STATUSES, TASK_STATUSES, isGoalNeedingAttention } from "./status.js";
70
- import { approxTokenCount, truncateEventStrings, truncateMiddleChars, truncateReport } from "./truncate.js";
71
- import { checkForUpdate, updateNotice } from "./update-check.js";
72
- import { syncSkills } from "./skill-sync.js";
73
- import { maybeAutoUpdate } from "./auto-update.js";
74
- import { askWorker, endSideSession, latestSideTurn } from "./side-chat.js";
75
- import { landWorker } from "./landing.js";
76
- import { cleanupHint } from "./cleanup-hint.js";
77
- import { applyCleanupPlan, createCleanupPlan } from "./cleanup-plan.js";
78
- import { buildOverviewDelta } from "./overview-delta.js";
79
-
80
- // Report the real package version. This string had drifted to 0.4.0 while the
81
- // package shipped 0.5.x, so the handshake named a version nobody was running.
82
- const packageVersion = JSON.parse(
83
- readFileSync(new URL("../package.json", import.meta.url), "utf8")
84
- ).version;
85
-
86
- const server = new McpServer({
87
- name: "codex-supervisor",
88
- version: packageVersion
89
- });
90
-
91
- // Nobody should keep running an old build without hearing about it. The
92
- // registry is asked once at start and every six hours after; the answer
93
- // rides along in the overview, the dispatch receipt and the wait response,
94
- // which are the calls every orchestrating session makes.
95
- const UPDATE_RECHECK_MS = 6 * 60 * 60 * 1000;
96
- let updateState = null;
97
- // The last word from auto-update.js: null until a check found a newer
98
- // version, then started | running | done | failed | skipped.
99
- let autoUpdateState = null;
100
- async function refreshUpdateState({ force = false } = {}) {
101
- try {
102
- updateState = await checkForUpdate({ force });
103
- autoUpdateState = await maybeAutoUpdate(updateState);
104
- const notice = updateNotice(updateState, autoUpdateState)?.notice;
105
- if (notice) process.stderr.write(`[codex-supervisor] ${notice}\n`);
106
- } catch (error) {
107
- process.stderr.write(`[codex-supervisor] update check failed: ${error.message}\n`);
108
- }
109
- return updateState;
110
- }
111
- refreshUpdateState();
112
- setInterval(() => refreshUpdateState({ force: true }), UPDATE_RECHECK_MS).unref();
113
-
114
- // The skill describes this tool surface, so it moves with the server: a
115
- // server fetched by `npx -y codex-supervisor-mcp@latest` never ran postinstall,
116
- // and a global install only synced the skill on the day it was installed.
117
- // Runs in the background; a client that cannot write its skill directory
118
- // only costs a line on stderr.
119
- if (!process.env.CODEX_SUPERVISOR_SKIP_SKILL_SYNC) {
120
- syncSkills()
121
- .then((result) => {
122
- const changed = [...result.installed, ...result.updated];
123
- if (changed.length > 0) {
124
- process.stderr.write(
125
- `[codex-supervisor] skill synced for ${changed.join(", ")}; a session that already loaded the skill keeps the old text until it loads it again\n`
126
- );
127
- }
128
- for (const failure of result.failed) {
129
- process.stderr.write(`[codex-supervisor] skill sync failed: ${failure}\n`);
130
- }
131
- })
132
- .catch((error) => {
133
- process.stderr.write(`[codex-supervisor] skill sync failed: ${error.message}\n`);
134
- });
135
- }
136
-
137
- // The short form for tool results: null when the install is current.
138
- function updateField() {
139
- return updateNotice(updateState, autoUpdateState);
140
- }
141
-
142
- // Spread into a result: adds `update` only when there is something to say.
143
- function withUpdate(payload) {
144
- const update = updateField();
145
- return update ? { ...payload, update } : payload;
146
- }
147
-
148
- const OVERVIEW_BYTE_BUDGET = 7000;
149
- const OVERVIEW_CAP_LEVELS = [
150
- { title: 40, goal: 60, action: 60, path: 60 },
151
- { title: 28, goal: 40, action: 40, path: 40 },
152
- { title: 18, goal: 24, action: 24, path: 24 },
153
- { title: 12, goal: 16, action: 16, path: 16 },
154
- { title: 8, goal: 8, action: 8, path: 8 },
155
- { title: 0, goal: 0, action: 0, path: 0 }
156
- ];
157
-
158
- function git(cwd, args) {
159
- return execFileSync(process.env.GIT_BIN?.trim() || "git", ["-C", cwd, ...args], {
160
- encoding: "utf8",
161
- timeout: 60000,
162
- stdio: ["ignore", "pipe", "pipe"]
163
- }).trim();
164
- }
165
-
166
- // `current_action` is "Running <command>", and a command can be a heredoc that
167
- // writes a whole file. Returning it whole put tens of thousands of characters
168
- // into every wait response, which then blew past the client's MCP output cap
169
- // and came back a second time as a notification. The full command stays in
170
- // current_command / commands and is readable through get_codex_worker_events.
171
- const ACTION_PREVIEW_CHARS = 300;
172
- const COMMAND_PREVIEW_CHARS = 300;
173
- const COMMAND_TAIL = 20;
174
- const PROMPT_PREVIEW_CHARS = 300;
175
- // The single-worker status read is the drill-in for one worker, so its copy of
176
- // the last message stays much larger than the overview's 400. The full report
177
- // is still get_worker_result's job.
178
- const STATUS_MESSAGE_CHARS = 4000;
179
-
180
- function textResult(value) {
181
- return {
182
- content: [
183
- {
184
- type: "text",
185
- text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
186
- }
187
- ]
188
- };
189
- }
190
-
191
- function clip(value, maxChars) {
192
- if (value === null || value === undefined) return null;
193
- const text = String(value);
194
- return text.length <= maxChars ? text : `${text.slice(0, maxChars)}…`;
195
- }
196
-
197
- function sleep(ms) {
198
- return new Promise((resolve) => setTimeout(resolve, ms));
199
- }
200
-
201
- // A terminal status is written in two steps. Codex's turn.completed event
202
- // flips status to completed while the process is still alive and exit_code is
203
- // still null; the process exit then writes exit_code. A wait that returned on
204
- // the first step handed the caller a snapshot with exit_code: null, and the
205
- // next read said 0 - two answers for one worker. A row counts as settled once
206
- // the exit is recorded, or once nobody is left to record it.
207
- function isSettled(task) {
208
- if (!TERMINAL_STATUSES.has(task.status)) return false;
209
- if (task.attention_reason === "start_failed") return true;
210
- if (task.guard_policy?.preflight && readPreflightResult(task).status === "passed") return true;
211
- if (task.status !== "completed" && task.status !== "failed") return true;
212
- // Acceptance is running in the supervisor process that owned the worker;
213
- // the codex pid is already dead, so that process is what to wait on.
214
- if (task.acceptance_results?.status === "running") return !isPidAlive(task.acceptance_results.supervisor_pid);
215
- if (["interrupted", "cancelled"].includes(task.acceptance_results?.status)) {
216
- return task.exit_code !== null && task.exit_code !== undefined;
217
- }
218
- if (task.exit_code !== null && task.exit_code !== undefined) return true;
219
- // A dead Codex pid does not prove that its owner's close handler finished
220
- // draining the stream and writing the exit status. Leave the half-written
221
- // row for reconciliation after a short grace period, never return it.
222
- return false;
223
- }
224
-
225
- async function recordWorkerLanded(task, { head, branch, target, source = "git_land", alreadyLanded = [] }) {
226
- const now = new Date().toISOString();
227
- const landed = { ...task, landed_at: now, landed_head: head ?? null, landed_branch: branch ?? null, updated_at: now };
228
- await upsertTask(landed);
229
- await updateWorkItemDelivery(task.id, "landed");
230
- const event = await appendTaskEvent(task.id, {
231
- type: "supervisor.landed",
232
- head: head ?? null,
233
- branch: branch ?? null,
234
- target: target ?? null,
235
- source,
236
- already_landed: alreadyLanded,
237
- landed_at: now
238
- }, { runId: runIdFor(task.id, task.run_count ?? 1), actor: "supervisor" });
239
- const workItem = await getWorkItemForTask(task.id);
240
- if (workItem && head) {
241
- await recordFact({
242
- workItemId: workItem.id,
243
- scopeType: "work_item",
244
- scopeId: workItem.id,
245
- key: "landed",
246
- value: { head, branch: branch ?? null, source },
247
- state: "verified",
248
- sourceEventId: event.id,
249
- validForSha: head,
250
- watchedPaths: task.owned_paths ?? [],
251
- verifiedBy: `supervisor.${source}`
252
- });
253
- await recordFact({
254
- workItemId: workItem.id,
255
- scopeType: "dependency",
256
- scopeId: workItem.id,
257
- key: "landed_delivery_summary",
258
- value: { task_id: task.id, landed_head: head, branch: branch ?? null, acceptance: task.acceptance_results?.passed === true ? "passed" : "not_configured_or_not_passed", source },
259
- state: "verified",
260
- sourceEventId: event.id,
261
- validForSha: head,
262
- watchedPaths: task.owned_paths ?? [],
263
- verifiedBy: `supervisor.${source}`
264
- });
265
- }
266
- return { landed, event };
267
- }
268
-
269
- async function landOneWorkerTask(taskId, { onto = null, commitMessage = null, ignoreAcceptance = false, allowOutsideOwned = false, skipAlreadyLanded = false } = {}) {
270
- const task = await getTask(taskId);
271
- if (!task) return { error: "task_not_found", task_id: taskId };
272
- if (task.workspace_kind && task.workspace_kind !== "legacy" && task.workspace_kind !== "git_worktree") {
273
- return { error: "workspace_kind_not_landable", task_id: taskId, workspace_kind: task.workspace_kind, reason: `${task.workspace_kind} does not create a Git worktree and cannot be landed` };
274
- }
275
- const session = task.session_id ? await getSession(task.session_id) : null;
276
- if (!isSettled(task)) return { error: "worker_active", task_id: taskId, reason: "wait for this run and acceptance to settle before landing" };
277
- if (session?.approval_state === "waiting_user") return { error: "session_waiting_user", task_id: taskId, reason: "session requires user approval before landing" };
278
- if (session && task.session_policy_revision !== session.policy_revision) return { error: "session_policy_stale", task_id: taskId, current_revision: session.policy_revision, checked_revision: task.session_policy_revision, reason: "requirements changed; resume with the current objective and rerun acceptance before landing" };
279
- if (skipAlreadyLanded && task.landed_at && (!task.worktree_path || !existsSync(task.worktree_path))) {
280
- try {
281
- const targetBranch = git(task.project_root, ["symbolic-ref", "--short", "HEAD"]);
282
- if (onto && onto !== targetBranch) return { error: "wrong_branch", task_id: taskId, current_branch: targetBranch };
283
- if (!ignoreAcceptance && task.acceptance?.length && task.acceptance_results?.passed !== true) {
284
- return { error: "acceptance_not_run", task_id: taskId };
285
- }
286
- git(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, "HEAD"]);
287
- return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, skipped: "already_landed", landed_at: task.landed_at, landed_head: task.landed_head };
288
- } catch {
289
- return { error: "landed_commit_unreachable", task_id: taskId, reason: "the removed ancestor worktree cannot be skipped without proving its landed commit is on the current target" };
290
- }
291
- }
292
- const outcome = landWorker(task, { onto, commitMessage, ignoreAcceptance, allowOutsideOwned });
293
- if (outcome.error === "nothing_to_land" && outcome.already_landed?.length > 0
294
- && (outcome.uncommitted ?? []).length === 0) {
295
- const alreadyRecorded = task.landed_at && task.landed_head === outcome.matched_head;
296
- if (!alreadyRecorded && outcome.matched_head) {
297
- await recordWorkerLanded(task, {
298
- head: outcome.matched_head,
299
- branch: outcome.onto,
300
- target: outcome.target,
301
- source: "patch_equivalent",
302
- alreadyLanded: outcome.already_landed
303
- });
304
- }
305
- return {
306
- task_id: taskId,
307
- title: task.title,
308
- status: task.status,
309
- branch: `codex/${task.id}`,
310
- ...outcome,
311
- skipped: "already_in_target",
312
- lifecycle_recorded: !alreadyRecorded && Boolean(outcome.matched_head)
313
- };
314
- }
315
- if (outcome.error) return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, ...outcome };
316
- await recordWorkerLanded(task, { head: outcome.head, branch: outcome.onto, target: outcome.target, alreadyLanded: outcome.already_landed ?? [] });
317
- return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, ...outcome };
318
- }
319
-
320
- async function followupChainIds(taskId) {
321
- const ids = [];
322
- const seen = new Set();
323
- let current = taskId;
324
- for (;;) {
325
- if (seen.has(current)) throw new Error(`followup cycle detected at ${current}`);
326
- seen.add(current);
327
- const task = await getTask(current);
328
- if (!task) throw new Error(`task not found: ${current}`);
329
- ids.unshift(current);
330
- if (!task.followup_of) return ids;
331
- current = task.followup_of;
332
- }
333
- }
334
-
335
- // Codex emits nothing while a command runs and nothing while the model
336
- // thinks, so a snapshot that has not moved for ten minutes looks the same
337
- // either way. These three fields tell them apart: current_command is set
338
- // from the command's item.started until its item.completed, so a long idle
339
- // with a command is a long command, and a long idle without one is the model
340
- // (or a stuck process, which reconcile turns into lost on its own).
341
- const LIVE_COMMAND_PREVIEW_CHARS = 120;
342
- function liveness(task) {
343
- if (!ACTIVE_STATUSES.has(task.status)) {
344
- const stage = readStage(task.id);
345
- return {
346
- idle_seconds: null,
347
- command_running: false,
348
- current_command: null,
349
- current_stage: null,
350
- current_stage_detail: null,
351
- last_stage: stage?.stage ?? null,
352
- stage_updated_at: stage?.updated_at ?? null
353
- };
354
- }
355
- const since = Date.parse(task.last_event_at ?? task.started_at ?? "");
356
- const idle = Number.isFinite(since) ? Math.max(0, Math.floor((Date.now() - since) / 1000)) : null;
357
- const command = task.current_command ? clip(task.current_command, LIVE_COMMAND_PREVIEW_CHARS) : null;
358
- const stage = readStage(task.id);
359
- const active = ACTIVE_STATUSES.has(task.status);
360
- return {
361
- idle_seconds: idle,
362
- command_running: Boolean(task.current_command),
363
- current_command: command,
364
- current_stage: active ? stage?.stage ?? null : null,
365
- current_stage_detail: active ? stage?.detail ?? null : null,
366
- last_stage: active ? null : stage?.stage ?? null,
367
- stage_updated_at: stage?.updated_at ?? null
368
- };
369
- }
370
-
371
- function compactLiveness(task) {
372
- const live = liveness(task);
373
- return {
374
- idle_seconds: live.idle_seconds,
375
- command_running: live.command_running,
376
- current_command: live.current_command,
377
- ...(live.current_stage ? { current_stage: live.current_stage } : {}),
378
- ...(live.current_stage_detail ? { current_stage_detail: live.current_stage_detail } : {}),
379
- ...(live.last_stage ? { last_stage: live.last_stage } : {}),
380
- ...(live.stage_updated_at ? { stage_updated_at: live.stage_updated_at } : {})
381
- };
382
- }
383
-
384
- // The acceptance verdict as get_worker_result reports it, with the one
385
- // contradiction a tool can see spelled out: checks passed, worker says
386
- // otherwise (the "it was never built" case, where it was).
387
- function acceptanceView(task, behind) {
388
- const configured = Array.isArray(task.acceptance) && task.acceptance.length > 0;
389
- const results = task.acceptance_results ?? null;
390
- const view = {
391
- configured,
392
- commands: configured ? task.acceptance : [],
393
- status: results?.status ?? null,
394
- passed: results?.passed ?? null,
395
- run: results?.run ?? null,
396
- checks: results?.checks ?? [],
397
- error: results?.error ?? null,
398
- // Drift matters only before the work is landed: once it is on the
399
- // branch, the branch having moved is expected.
400
- stale: Boolean(results && behind && behind.behind > 0 && !(task.landed_at && task.landed_at >= (results.finished_at ?? ""))),
401
- next_step: null
402
- };
403
- if (!configured) return view;
404
- if (view.status === "failed") {
405
- const failing = view.checks.find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out) ?? null;
406
- view.next_step = failing
407
- ? `acceptance failed: ${clip(failing.command, 120)} failed ${failing.error ?? (failing.baseline?.passed === false ? "baseline/evidence mismatch" : failing.timed_out ? "by timeout" : `exit ${failing.exit_code}`)}; resume the worker with checks[].output_tail in the prompt, or fix it yourself. Do not land until it passes.`
408
- : `acceptance could not run (${view.error ?? "unknown"}); fix that first`;
409
- } else if (view.status === "passed") {
410
- const verification = summarizeVerification(task);
411
- const workerSaysNo = task.status === "failed" || isGoalNeedingAttention(task.goal_status) || verification.last_command_failed;
412
- if (workerSaysNo) view.next_step = "the checks passed but the worker reports otherwise; trust the checks and read the diff";
413
- else if (view.stale) view.next_step = "the checks passed on the old base and the project has moved since; resume with rebaseOnto to re-run them on current code before landing";
414
- } else if (view.status === "running") {
415
- view.next_step = "acceptance is still running in the supervisor; wait_codex_workers returns when it is done";
416
- } else if (view.status === "interrupted") {
417
- view.next_step = "the supervisor exited while running acceptance; resume the worker (or cancel and redispatch) to run it again";
418
- } else if (view.status === "cancelled") {
419
- view.next_step = "acceptance was cancelled; resume the worker to run it again";
420
- } else if (view.status === null) {
421
- view.next_step = "acceptance has not run yet for this worker";
422
- }
423
- return view;
424
- }
425
-
426
- function summarizeTask(task) {
427
- return {
428
- id: task.id,
429
- title: task.title,
430
- worker: task.worker,
431
- status: task.status,
432
- phase: task.phase ?? null,
433
- cwd: task.cwd,
434
- project_root: task.project_root,
435
- workspace_kind: task.workspace_kind ?? "legacy",
436
- sandbox: task.sandbox,
437
- model: task.model,
438
- reasoning_effort: task.reasoning_effort ?? "high",
439
- thread_id: task.thread_id,
440
- followup_of: task.followup_of,
441
- resumed_from: task.resumed_from,
442
- depends_on: task.depends_on ?? [],
443
- owned_paths: task.owned_paths ?? [],
444
- worktree_path: task.worktree_path,
445
- goal_objective: task.goal_objective,
446
- goal_token_budget: task.goal_token_budget,
447
- goal_status: task.goal_status,
448
- goal_tokens_used: task.goal_tokens_used ?? null,
449
- thread_health: threadHealth(task),
450
- attention_reason: task.attention_reason ?? null,
451
- failure: classifyFailure(task),
452
- changed_file_count: (task.changed_files ?? []).length,
453
- command_count: (task.commands ?? []).length,
454
- run_count: task.run_count ?? 0,
455
- acceptance: acceptanceVerdict(task),
456
- landed_at: task.landed_at ?? null,
457
- current_action: clip(task.current_action, ACTION_PREVIEW_CHARS),
458
- ...liveness(task),
459
- last_event_at: task.last_event_at ?? null,
460
- last_event_type: task.last_event_type,
461
- last_message: clip(task.last_message, 400),
462
- notices: clip(task.notices, 400),
463
- error: task.error,
464
- created_at: task.created_at,
465
- updated_at: task.updated_at,
466
- started_at: task.started_at,
467
- completed_at: task.completed_at,
468
- exit_code: task.exit_code
469
- };
470
- }
471
-
472
- // The status read used to hand back the stored row verbatim. For a follow-up
473
- // worker that row carries the parent prompt plus the whole command history and
474
- // the events folded into it; one real call returned 180k characters, past the
475
- // client's MCP output cap, so the reply landed on disk and had to be grepped.
476
- // This is the same status surface the other reads use, plus explicitly bounded
477
- // extras. includePrompt is the escape hatch for the full task text.
478
- function statusView(task, { includePrompt, promptMaxChars }) {
479
- const promptText = task.prompt ?? null;
480
- const promptBudget = includePrompt ? promptMaxChars : PROMPT_PREVIEW_CHARS;
481
- const commands = (task.commands ?? []).slice(-COMMAND_TAIL);
482
- return {
483
- ...summarizeTask(task),
484
- last_message: clip(task.last_message, STATUS_MESSAGE_CHARS),
485
- session_id: task.session_id ?? null,
486
- pid: task.pid ?? null,
487
- run_log: task.run_log ?? null,
488
- base_commit: task.base_commit ?? null,
489
- changed_files: readTaskChanges(task),
490
- current_command: clip(task.current_command, COMMAND_PREVIEW_CHARS),
491
- commands: commands.map((entry) => ({ ...entry, command: clip(entry.command, COMMAND_PREVIEW_CHARS) })),
492
- prompt: clip(promptText, promptBudget),
493
- prompt_truncated: Boolean(promptText) && String(promptText).length > promptBudget
494
- };
495
- }
496
-
497
- // The dispatch receipt. Dispatch used to return the whole task record, which
498
- // echoes the task text - and for a follow-up, the parent prompt plus 20 raw
499
- // events - back to the caller on every call. Dispatching eleven workers made
500
- // the main thread pay for its own instructions eleven times, and pushed the
501
- // result into the client's MCP output cap. Read the rest per worker with
502
- // get_worker_summary / get_worker_result when you actually need it.
503
- function receipt(task) {
504
- return {
505
- id: task.id,
506
- title: task.title,
507
- worker: task.worker,
508
- status: task.status,
509
- phase: task.phase ?? null,
510
- cwd: task.cwd,
511
- project_root: task.project_root,
512
- workspace_kind: task.workspace_kind ?? "legacy",
513
- worktree_path: task.worktree_path,
514
- branch: task.worktree_path ? `codex/${task.id}` : null,
515
- base_commit: task.base_commit ?? null,
516
- sandbox: task.sandbox,
517
- model: task.model,
518
- reasoning_effort: task.reasoning_effort,
519
- thread_id: task.thread_id,
520
- session_id: task.session_id ?? null,
521
- followup_of: task.followup_of,
522
- resumed_from: task.resumed_from,
523
- depends_on: task.depends_on ?? [],
524
- owned_paths: task.owned_paths ?? [],
525
- goal_objective: task.goal_objective,
526
- goal_token_budget: task.goal_token_budget,
527
- error: task.error ?? null,
528
- failure: classifyFailure(task),
529
- run_count: task.run_count ?? 0,
530
- run_log: task.run_log,
531
- created_at: task.created_at,
532
- updated_at: task.updated_at
533
- };
534
- }
535
-
536
- function overviewRow(task, caps) {
537
- const live = liveness(task);
538
- return {
539
- id: task.id,
540
- title: clip(task.title, caps.title),
541
- status: task.status,
542
- phase: task.phase ?? null,
543
- goal: clip(task.goal_objective, caps.goal),
544
- goal_status: task.goal_status ?? null,
545
- last_action: clip(task.current_action, caps.action),
546
- idle_seconds: live.idle_seconds,
547
- command_running: Boolean(task.current_command) && ACTIVE_STATUSES.has(task.status),
548
- ...(live.current_stage ? { current_stage: live.current_stage } : {}),
549
- ...(live.last_stage ? { last_stage: live.last_stage } : {}),
550
- acceptance: acceptanceVerdict(task),
551
- ...(classifyFailure(task)?.code ? { failure_code: classifyFailure(task).code } : {}),
552
- ...(threadHealth(task).state === "handoff_recommended" ? { handoff_recommended: true } : {}),
553
- changed_files: (task.changed_files ?? []).length,
554
- depends_on: task.depends_on ?? [],
555
- owned_paths: (task.owned_paths ?? []).map((entry) => clip(entry, caps.path))
556
- };
557
- }
558
-
559
- // One line per work for the listing tools. Kept deliberately small: the caller
560
- // is usually a main thread that will drill into at most one of these.
561
- function workRow(task) {
562
- return {
563
- id: task.id,
564
- title: task.title,
565
- status: task.status,
566
- phase: task.phase ?? null,
567
- goal: task.goal_objective ?? null,
568
- session_id: task.session_id ?? null,
569
- thread_id: task.thread_id ?? null,
570
- created_at: task.created_at,
571
- updated_at: task.updated_at
572
- };
573
- }
574
-
575
- // The overview is the tool the orchestrator calls by default, so it has to fit
576
- // a fixed budget no matter how long titles and goals are. Field caps are
577
- // lowered until the payload fits, and the payload reports what it cost.
578
- function settleTokenCount(payload) {
579
- // The reported cost has to include the field that reports it, so iterate to
580
- // a fixed point instead of measuring a payload that lacks the number.
581
- let tokens = 0;
582
- for (let attempt = 0; attempt < 6; attempt += 1) {
583
- payload.approx_tokens = tokens;
584
- const next = approxTokenCount(JSON.stringify(payload));
585
- if (next === tokens) break;
586
- tokens = next;
587
- }
588
- payload.approx_tokens = tokens;
589
- return Buffer.byteLength(JSON.stringify(payload), "utf8");
590
- }
591
-
592
- function buildOverview(tasks, extras = {}) {
593
- let payload;
594
- for (const [index, caps] of OVERVIEW_CAP_LEVELS.entries()) {
595
- payload = {
596
- generated_at: new Date().toISOString(),
597
- ...extras,
598
- total: tasks.length,
599
- active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
600
- needs_attention: tasks
601
- .filter((task) => isGoalNeedingAttention(task.goal_status) || task.attention_reason)
602
- .map((task) => task.id),
603
- // Terminal rows whose acceptance run failed. Kept apart from
604
- // needs_attention, which means "running and stuck"; this means
605
- // "finished and wrong", and the next step is a resume with the output.
606
- acceptance_failed: tasks.filter((task) => task.acceptance_results?.passed === false).map((task) => task.id),
607
- workers: tasks.map((task) => overviewRow(task, caps))
608
- };
609
- const bytes = settleTokenCount(payload);
610
- if (bytes <= OVERVIEW_BYTE_BUDGET) return payload;
611
- if (index === OVERVIEW_CAP_LEVELS.length - 1) {
612
- payload.budget_exceeded = true;
613
- payload.truncated_fields = true;
614
- settleTokenCount(payload);
615
- return payload;
616
- }
617
- delete payload.approx_tokens;
618
- }
619
- return payload;
620
- }
621
-
622
- function acceptanceLine(task) {
623
- if (!Array.isArray(task.acceptance) || task.acceptance.length === 0) return "acceptance: none configured";
624
- const results = task.acceptance_results;
625
- if (!results) return `acceptance: ${task.acceptance.length} configured, not run yet`;
626
- const ran = results.checks?.length ?? 0;
627
- const ok = (results.checks ?? []).filter((check) => check.passed !== false && check.exit_code === 0 && !check.timed_out).length;
628
- const failing = (results.checks ?? []).find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out);
629
- return `acceptance: ${results.status}, ${ok}/${task.acceptance.length} passed (${ran} ran)${failing ? `, first failure: ${clip(failing.command, 80)} exit ${failing.timed_out ? "timeout" : failing.exit_code}` : ""}`;
630
- }
631
-
632
- function buildWorkerSummary(task, nativeGoal) {
633
- // Read the worktree too: a worker that edits via shell commands emits no
634
- // file_change events, so the checkout is the authoritative diff.
635
- const changed = readTaskChanges(task);
636
- const commands = task.commands ?? [];
637
- const lines = [
638
- `${task.title ?? task.id} — status=${task.status}${task.phase ? `, phase=${task.phase}` : ""}`,
639
- `goal: ${task.goal_objective ?? "-"}${task.goal_token_budget ? ` (budget ${task.goal_token_budget} tokens)` : ""}`,
640
- nativeGoal
641
- ? `codex goal: ${nativeGoal.status}, ${nativeGoal.tokens_used} tokens used, ${nativeGoal.time_used_seconds}s elapsed`
642
- : "codex goal: none recorded for this thread",
643
- `changed files (${changed.length}): ${changed.slice(0, 10).join(", ") || "-"}`,
644
- `last command: ${commands.at(-1)?.command ?? "-"}`,
645
- acceptanceLine(task),
646
- `last action: ${clip(task.current_action, ACTION_PREVIEW_CHARS) ?? "-"}`,
647
- `runs: ${task.run_count ?? 0}${task.resumed_from ? `, resumed from ${task.resumed_from}` : ""}`,
648
- task.error ? `error: ${task.error}` : null
649
- ].filter(Boolean);
650
-
651
- return {
652
- id: task.id,
653
- title: task.title,
654
- status: task.status,
655
- phase: task.phase ?? null,
656
- thread_id: task.thread_id,
657
- goal_objective: task.goal_objective,
658
- goal_token_budget: task.goal_token_budget,
659
- goal_status: task.goal_status,
660
- native_goal: nativeGoal,
661
- owned_paths: task.owned_paths ?? [],
662
- depends_on: task.depends_on ?? [],
663
- run_count: task.run_count ?? 0,
664
- changed_files: changed,
665
- command_count: commands.length,
666
- last_command: commands.at(-1)?.command ?? null,
667
- last_message: task.last_message ?? null,
668
- notices: task.notices ?? null,
669
- error: task.error ?? null,
670
- created_at: task.created_at,
671
- updated_at: task.updated_at,
672
- completed_at: task.completed_at,
673
- summary: lines.join("\n")
674
- };
675
- }
676
-
677
- function errorResult(error) {
678
- return textResult({
679
- error: error.code ?? "error",
680
- message: error.message,
681
- ...(error.conflicts ? { conflicts: error.conflicts } : {}),
682
- ...(error.details?.preflight ? { preflight: error.details.preflight } : {}),
683
- ...(error.details ? { files: error.details.files ?? [], git: error.details.git ?? null, base_commit: error.details.base_commit ?? null, head: error.details.head ?? null } : {})
684
- });
685
- }
686
-
687
- function externalOutputView(task, maxChars = 6000) {
688
- const outputs = task.run_evidence?.external_outputs ?? [];
689
- const perContent = Math.floor(maxChars / Math.max(1, outputs.length * 2));
690
- return outputs.map((entry) => ({ ...entry, before: { ...entry.before, content: clip(entry.before.content, perContent) },
691
- after: { ...entry.after, content: clip(entry.after.content, perContent) } }));
692
- }
693
-
694
- function reportView(task, maxChars) {
695
- const value = task.run_evidence?.structured_report;
696
- if (!value) return { format: "legacy_text", valid: null };
697
- if (!value.valid || !maxChars) return value;
698
- const report = value.report;
699
- const perEntry = Math.floor(maxChars / Math.max(1, 2 + report.verification.length + report.not_done.length));
700
- return { ...value, report: { result: clip(report.result, perEntry * 2),
701
- verification: report.verification.map((entry) => clip(entry, perEntry)),
702
- not_done: report.not_done.map((entry) => clip(entry, perEntry)) } };
703
- }
704
-
705
- function runEvidenceView(task) {
706
- if (!task.run_evidence) return null;
707
- const { structured_report, external_outputs, ...evidence } = task.run_evidence;
708
- return { ...evidence, external_changed_count: (external_outputs ?? []).filter((entry) => entry.changed).length };
709
- }
710
-
711
- const acceptanceFailureRecord = z.object({
712
- test_id: z.string().min(1), kind: z.enum(["failure", "error"]), signature: z.string().min(1)
713
- }).strict();
714
- const acceptanceCheck = z.union([
715
- z.string().min(1),
716
- z.object({
717
- command: z.string().min(1), reportPath: z.string().min(1),
718
- baseline: z.object({
719
- identity: z.object({ base_commit: z.string().min(1) }).catchall(z.string().min(1)),
720
- failures: z.array(acceptanceFailureRecord), required: z.array(z.string().min(1))
721
- }).strict()
722
- }).strict()
723
- ]);
724
- const acceptanceInput = z.union([z.string().min(1), z.array(acceptanceCheck).max(10)]);
725
- const workspaceSetupInput = z.object({
726
- links: z.array(z.object({
727
- path: z.string().min(1),
728
- source: z.string().min(1)
729
- }).strict()).max(20).optional(),
730
- submodules: z.boolean().optional(),
731
- commands: z.array(z.string().min(1)).max(20).optional()
732
- }).strict();
733
-
734
- const observerId = process.env.CODEX_SUPERVISOR_OBSERVER_ID?.trim() || `mcp-${randomUUID()}`;
735
- const deltaObserverId = process.env.CODEX_SUPERVISOR_DELTA_OBSERVER_ID?.trim() || `${observerId}:delta`;
736
- let observerRead = Promise.resolve();
737
- let deltaRead = Promise.resolve();
738
- server.registerTool(
739
- "overview_delta",
740
- {
741
- title: "Get orchestration delta",
742
- description: "Return a small cursor-based orchestration view: active, needs_attention, ready_to_land, ready_to_clean and changed task summaries. It never returns full history, prompts, diffs, events or worker capsules.",
743
- inputSchema: { cursor: z.record(z.string(), z.string()).optional() }
744
- },
745
- async ({ cursor }) => {
746
- const read = deltaRead.then(async () => {
747
- await reconcileDetachedActiveTasks();
748
- const tasks = await readTasks();
749
- const previous = cursor ?? await readObserverCursor(deltaObserverId);
750
- const candidateIds = tasks.filter((task) => task.delivery_state === "cleanup_eligible").map((task) => task.id);
751
- const cleanupReadiness = candidateIds.length > 0
752
- ? await createCleanupPlan({ taskIds: candidateIds, revalidateRemote: false })
753
- : null;
754
- const readyToCleanTaskIds = cleanupReadiness
755
- ? new Set(cleanupReadiness.items.filter((item) => item.verdict === "safe").map((item) => item.task_id))
756
- : new Set();
757
- const result = buildOverviewDelta(tasks, previous, { readyToCleanTaskIds });
758
- await writeObserverCursor(deltaObserverId, result.cursor);
759
- const { cursor: nextCursor, ...reply } = result;
760
- return textResult({ ...reply, next_cursor: nextCursor });
761
- });
762
- deltaRead = read.catch(() => {});
763
- return read;
764
- }
765
- );
766
- server.registerTool("check_workers", {
767
- title: "Check changed workers",
768
- description: "Check newly settled runs, actionable failures and active threads crossing the handoff threshold; automatically resume a dead lost/no_work first run once, except approval, authentication, permission and quota waits. Handoff reminders occur once per run and never cancel, replace or resume a live worker. Unchanged state is quiet. Call from a host-scheduled loop; it cannot wake a closed host. Set a distinct CODEX_SUPERVISOR_OBSERVER_ID per main thread to retain its cursor across restarts.",
769
- inputSchema: {}
770
- }, async () => {
771
- const read = observerRead.then(async () => {
772
- await reconcileDetachedActiveTasks();
773
- const recoveries = await recoverEligibleRuns();
774
- const result = collectWorkerChanges(await readTasks(), await readObserverCursor(observerId));
775
- await writeObserverCursor(observerId, result.cursor);
776
- const { cursor, ...reply } = result;
777
- // The cleanup hint rides along without touching quiet: it is a standing fact
778
- // about the store, not a new worker event.
779
- const cleanup = await cleanupHint();
780
- return textResult({ ...reply, quiet: reply.quiet && recoveries.length === 0, recoveries, ...(cleanup ? { cleanup } : {}) });
781
- });
782
- observerRead = read.catch(() => {});
783
- return read;
784
- });
785
-
786
- server.registerTool(
787
- "check_acceptance",
788
- {
789
- title: "Check acceptance commands",
790
- description: "Run explicitly supplied acceptance commands in the requested project before dispatch. This executes the commands with supervisor privileges and can have their side effects; it creates no worker and does not prove worker completion. Structured checks require fresh execution evidence, while failure-count greps are flagged as insufficient baseline evidence.",
791
- inputSchema: {
792
- cwd: z.string().min(1), acceptance: acceptanceInput,
793
- baseRef: z.string().min(1).optional(), timeoutMs: z.number().int().min(1000).max(1800000).default(600000)
794
- }
795
- },
796
- async ({ cwd, acceptance, baseRef = "HEAD", timeoutMs }) => {
797
- let base;
798
- try {
799
- base = execFileSync("git", ["-C", cwd, "rev-parse", "--verify", `${baseRef}^{commit}`], { encoding: "utf8", timeout: 10000, stdio: ["ignore", "pipe", "pipe"] }).trim();
800
- } catch {
801
- return textResult({ error: "invalid_base_ref", phase: "preflight", reason: `baseRef does not resolve in ${cwd}`, proves_worker_completion: false });
802
- }
803
- try {
804
- const commands = Array.isArray(acceptance) ? acceptance : [acceptance];
805
- const warnings = commands.filter((check) => typeof check === "string" && /(?:failures|errors)\s*=\s*\d/.test(check)).map(() => "failure-count checks do not prove baseline test identities or required execution; use structured evidence");
806
- const result = await runAcceptance(commands, { cwd, timeoutMs, baseCommit: base, taskId: `preflight-${randomUUID()}` });
807
- return textResult({ ...result, phase: "preflight", base_commit: base, proves_worker_completion: false, warnings });
808
- } catch (error) {
809
- return errorResult(error);
810
- }
811
- }
812
- );
813
-
814
- server.registerTool(
815
- "preflight_codex_worker",
816
- {
817
- title: "Preflight Codex worker environment",
818
- description:
819
- "Launch a short-lived Codex probe worker in the same base commit, sandbox, guard, network and writable-root configuration intended for a later write worker. The probe must run every requested command in the actual worker environment. Read get_worker_preflight after it settles, then pass its task_id as create_codex_worker.preflight_id; a changed runtime contract is refused.",
820
- inputSchema: {
821
- title: z.string().optional(),
822
- cwd: z.string().min(1),
823
- sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).default("workspace-write"),
824
- model: z.string().optional(),
825
- reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
826
- skipGitRepoCheck: z.boolean().default(true),
827
- ownedPaths: z.array(z.string().min(1)),
828
- forbid: z.array(z.string().min(1)).max(100).optional(),
829
- allowedCommands: z.array(z.string().min(1)).max(100).optional(),
830
- context: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
831
- contracts: z.array(z.string().min(1).max(2000)).max(20).optional(),
832
- networkAccess: z.boolean().default(false),
833
- writableRoots: z.array(z.string().min(1)).max(20).optional(),
834
- maxRunMs: z.number().int().min(1000).max(86400000).optional(),
835
- maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
836
- baseRef: z.string().min(1).optional(),
837
- workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
838
- inPlaceAuthorization: z.string().min(1).max(2000).optional(),
839
- workspaceSetup: workspaceSetupInput.optional(),
840
- probeCommands: z.array(z.string().min(1)).min(1).max(20)
841
- }
842
- },
843
- async (input) => {
844
- try {
845
- const task = [
846
- "Runtime environment preflight. Do not edit files, create files, install packages, dispatch workers or call MCP tools.",
847
- "Run every command below exactly once, in the listed order, without wrapping it in another shell command.",
848
- "If any command is denied, missing, times out or exits nonzero, stop and quote the raw error under Not done / risks.",
849
- "Commands:",
850
- ...input.probeCommands.map((command) => `- ${command}`)
851
- ].join("\n");
852
- const record = await createCodexWorker({
853
- ...input,
854
- title: input.title ? `Preflight: ${input.title}` : "Runtime environment preflight",
855
- task,
856
- goal: { objective: `Prove the requested Codex worker runtime environment before dispatching ${input.title ?? "the dependent worker"}` },
857
- acceptance: null,
858
- preflight: { probeCommands: input.probeCommands }
859
- });
860
- return textResult(withUpdate({ ...receipt(record), preflight: { status: "running", probe_commands: input.probeCommands } }));
861
- } catch (error) {
862
- return errorResult(error);
863
- }
864
- }
865
- );
866
-
867
- server.registerTool(
868
- "get_worker_preflight",
869
- {
870
- title: "Get worker preflight result",
871
- description: "Read whether a preflight probe ran every required command successfully in the tracked worker environment, plus the immutable runtime contract hash required by create_codex_worker.preflight_id.",
872
- inputSchema: { task_id: z.string().min(1) }
873
- },
874
- async ({ task_id }) => {
875
- const task = await getTask(task_id);
876
- if (!task) return textResult({ error: "task_not_found", task_id });
877
- return textResult(readPreflightResult(task));
878
- }
879
- );
880
-
881
- server.registerTool(
882
- "create_codex_worker",
883
- {
884
- title: "Create Codex worker",
885
- description:
886
- "Launch a Codex CLI worker with codex exec --json and track its events. workspaceKind controls where it runs: Git work writes only in an isolated git_worktree; read_only_in_place cannot write or use network; scratch writes only under SUPERVISOR_HOME and never lands; in_place_write is only for an explicitly authorized non-Git directory with ownedPaths and acceptance. A non-Git worker may never write the user directory by default. ownedPaths reserves files a landable worker may write; reading is never exclusive. acceptance is the list of shell commands that decide whether the work is done: the supervisor runs them after Codex exits, and workers run the same contract with codex-supervisor-accept. In a Git package project, acceptance using local JavaScript tooling requires workspaceSetup so node_modules and generated prepare files exist before dispatch. The worker's sandbox may write its execution directory, the temp directory and the OS cache directory; a toolchain whose cache lives elsewhere needs writableRoots, a list of existing absolute directories.",
887
- inputSchema: {
888
- title: z.string().optional(),
889
- task: z.string().min(1),
890
- cwd: z.string().min(1),
891
- session_id: z.string().min(1).optional(),
892
- // What this batch is about, in one line, so a reader of the store sees
893
- // "给 12 个接口补单测" instead of a bare session id. Set it on
894
- // the first dispatch of a session; later dispatches may omit it.
895
- session_title: z.string().min(1).max(120).optional(),
896
- session_note: z.string().min(1).max(2000).optional(),
897
- sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).default("workspace-write"),
898
- model: z.string().optional(),
899
- reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
900
- skipGitRepoCheck: z.boolean().default(true),
901
- // Empty is the promise that nothing lands: a read-only verifier, or a
902
- // research worker that reads, fetches and reports but merges nothing.
903
- ownedPaths: z.array(z.string().min(1)),
904
- forbid: z.array(z.string().min(1)).max(100).optional(),
905
- allowedCommands: z.array(z.string().min(1)).max(100).optional(),
906
- context: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
907
- contracts: z.array(z.string().min(1).max(2000)).max(20).optional(),
908
- externalOutputs: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
909
- networkAccess: z.boolean().default(false),
910
- // Extra absolute directories the sandbox may write. The OS cache
911
- // directory is already writable; this is for toolchains that keep a
912
- // cache somewhere else (~/.m2, ~/.gradle, a vendored mirror).
913
- writableRoots: z.array(z.string().min(1)).max(20).optional(),
914
- maxRunMs: z.number().int().min(1000).max(86400000).optional(),
915
- maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
916
- goal: z.object({
917
- objective: z.string().min(1),
918
- tokenBudget: z.number().int().positive().optional()
919
- }),
920
- dependsOn: z.array(z.string().min(1)).optional(),
921
- // Which commit the worktree is cut from. Defaults to the repository's
922
- // HEAD; pass a branch, tag or sha to build on work that is not on the
923
- // main line yet (for example another worker's codex/<id> branch).
924
- baseRef: z.string().min(1).optional(),
925
- workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
926
- inPlaceAuthorization: z.string().min(1).max(2000).optional(),
927
- workspaceSetup: workspaceSetupInput.optional(),
928
- // A successful preflight_codex_worker task id. When present, this worker
929
- // is refused unless base commit and the complete runtime contract match.
930
- preflight_id: z.string().min(1).optional(),
931
- // Shell commands that decide whether the work is done. The supervisor
932
- // runs them in the worktree after codex exits; each must exit 0.
933
- acceptance: acceptanceInput.optional(),
934
- acceptanceTimeoutMs: z.number().int().min(1000).max(1800000).optional()
935
- }
936
- },
937
- async (input) => {
938
- try {
939
- const record = await createCodexWorker({
940
- ...input,
941
- preflightId: input.preflight_id ?? null,
942
- sessionId: input.session_id ?? null,
943
- sessionTitle: input.session_title ?? null,
944
- sessionNote: input.session_note ?? null
945
- });
946
- return textResult(withUpdate(receipt(record)));
947
- } catch (error) {
948
- return errorResult(error);
949
- }
950
- }
951
- );
952
-
953
- server.registerTool(
954
- "create_codex_followup_worker",
955
- {
956
- title: "Create Codex follow-up worker",
957
- description:
958
- "Start a NEW Codex session seeded with the previous worker's prompt, status, and recent events. Unlanded parents contribute their current codex/<parent> checkpoint; landed parents use the current target HEAD. Explicit baseRef overrides either; uncommitted parent edits are not copied. To continue the same session instead, use resume_codex_worker.",
959
- inputSchema: {
960
- task_id: z.string().min(1),
961
- followup_prompt: z.string().min(1),
962
- session_id: z.string().min(1).optional(),
963
- session_title: z.string().min(1).max(120).optional(),
964
- session_note: z.string().min(1).max(2000).optional(),
965
- title: z.string().optional(),
966
- cwd: z.string().optional(),
967
- sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).optional(),
968
- model: z.string().optional(),
969
- reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
970
- ownedPaths: z.array(z.string().min(1)).optional(),
971
- forbid: z.array(z.string().min(1)).max(100).optional(),
972
- allowedCommands: z.array(z.string().min(1)).max(100).optional(),
973
- context: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
974
- contracts: z.array(z.string().min(1).max(2000)).max(20).optional(),
975
- externalOutputs: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
976
- networkAccess: z.boolean().optional(),
977
- writableRoots: z.array(z.string().min(1)).max(20).optional(),
978
- maxRunMs: z.number().int().min(1000).max(86400000).optional(),
979
- maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
980
- workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
981
- inPlaceAuthorization: z.string().min(1).max(2000).optional(),
982
- workspaceSetup: workspaceSetupInput.optional(),
983
- goal: z
984
- .object({
985
- objective: z.string().min(1),
986
- tokenBudget: z.number().int().positive().optional()
987
- })
988
- .optional(),
989
- baseRef: z.string().min(1).optional(),
990
- // Left out, the parent's acceptance commands are inherited; given, they
991
- // replace them, and an empty list clears them.
992
- acceptance: acceptanceInput.optional(),
993
- acceptanceTimeoutMs: z.number().int().min(1000).max(1800000).optional()
994
- }
995
- },
996
- async ({ task_id, followup_prompt, session_id, session_title, session_note, ...options }) => {
997
- try {
998
- const record = await createFollowupWorker({
999
- taskId: task_id,
1000
- followupPrompt: followup_prompt,
1001
- sessionId: session_id ?? null,
1002
- sessionTitle: session_title ?? null,
1003
- sessionNote: session_note ?? null,
1004
- ...options
1005
- });
1006
- return textResult(receipt(record));
1007
- } catch (error) {
1008
- return errorResult(error);
1009
- }
1010
- }
1011
- );
1012
-
1013
- server.registerTool(
1014
- "resume_codex_worker",
1015
- {
1016
- title: "Resume Codex worker",
1017
- description:
1018
- "Continue the SAME Codex session for an existing worker via `codex exec resume <thread_id>`. Works from a different MCP process or a fresh client session as long as the task recorded a thread_id. The worktree stays on the commit it was cut from unless rebaseOnto names a ref (resolved in the project directory, e.g. HEAD or main): uncommitted edits are stashed, the worker's own commits are replayed onto it, the stash comes back and base_commit moves, so the worker continues on current code. A conflict in either step puts the worktree back as it was, lists the files and does not start the worker. The receipt carries base_behind: how many commits the project's HEAD is past the worktree's base. acceptance replaces the worker's acceptance commands when the ones given at dispatch were wrong; the supervisor runs them again after this run.",
1019
- inputSchema: {
1020
- task_id: z.string().min(1),
1021
- prompt: z.string().min(1),
1022
- rebaseOnto: z.string().min(1).optional(),
1023
- context: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
1024
- // Replaces the stored acceptance commands for this and later runs; an
1025
- // empty list clears them. Left out, the stored commands stay.
1026
- acceptance: acceptanceInput.optional()
1027
- }
1028
- },
1029
- async ({ task_id, prompt, rebaseOnto, acceptance, context }) => {
1030
- try {
1031
- const record = await resumeCodexWorker({ taskId: task_id, prompt, rebaseOnto: rebaseOnto ?? null, acceptance, context });
1032
- return textResult({ ...receipt(record), rebase: record.rebase ?? null, base_behind: baseBehind(record.project_root, record.base_commit) });
1033
- } catch (error) {
1034
- return errorResult(error);
1035
- }
1036
- }
1037
- );
1038
-
1039
- server.registerTool(
1040
- "list_codex_workers",
1041
- {
1042
- title: "List Codex workers",
1043
- description: "List tracked Codex workers. Defaults to active workers only.",
1044
- inputSchema: {
1045
- status: z.enum(TASK_STATUSES).optional(),
1046
- includeHistory: z.boolean().default(false),
1047
- includeDetails: z.boolean().default(false)
1048
- }
1049
- },
1050
- async ({ status, includeHistory, includeDetails } = {}) => {
1051
- await reconcileDetachedActiveTasks();
1052
- const tasks = await readTasks();
1053
- const filtered = status
1054
- ? tasks.filter((task) => task.status === status)
1055
- : includeHistory
1056
- ? tasks
1057
- : tasks.filter((task) => ACTIVE_STATUSES.has(task.status));
1058
- return textResult(includeDetails ? filtered : filtered.map(summarizeTask));
1059
- }
1060
- );
1061
-
1062
- server.registerTool(
1063
- "get_orchestration_overview",
1064
- {
1065
- title: "Get orchestration overview",
1066
- description:
1067
- "Compact status table for every worker, budgeted to stay under ~2k tokens. This is the default read for an orchestrating main thread; fetch details per worker only when needed.",
1068
- inputSchema: {
1069
- status: z.enum(TASK_STATUSES).optional(),
1070
- limit: z.number().int().min(1).max(200).default(50)
1071
- }
1072
- },
1073
- async ({ status, limit } = {}) => {
1074
- await reconcileDetachedActiveTasks();
1075
- const tasks = await readTasks();
1076
- const filtered = (status ? tasks.filter((task) => task.status === status) : tasks).slice(-limit);
1077
- // version and update ride inside the budgeted payload so approx_tokens
1078
- // still reports the real cost of the whole reply.
1079
- return textResult(
1080
- buildOverview(filtered, {
1081
- version: packageVersion,
1082
- update: updateField() ?? { update_available: false, installed_version: packageVersion, checked: updateState?.source ?? "pending" }
1083
- })
1084
- );
1085
- }
1086
- );
1087
-
1088
- server.registerTool(
1089
- "wait_codex_workers",
1090
- {
1091
- title: "Wait for Codex workers",
1092
- description:
1093
- "Block until selected Codex workers reach a terminal status, then return summaries. Each call is capped at 60 seconds unless allowLongWait is explicitly true and the caller has verified its MCP timeout supports the requested budget. A spent wait budget returns a snapshot while workers continue; reuse the same task_ids or schedule check_workers for longer monitoring. compact: true returns one line per worker with status, phase, exit_code, changed_file_count, acceptance and liveness. command_running means a command may still be working despite a long idle interval.",
1094
- inputSchema: {
1095
- task_ids: z.array(z.string().min(1)).min(1),
1096
- mode: z.enum(["any", "all"]).default("all"),
1097
- timeoutMinutes: z.number().int().min(1).max(360).default(1),
1098
- timeoutMs: z.number().int().min(1000).max(21600000).optional(),
1099
- allowLongWait: z.boolean().default(false),
1100
- pollMs: z.number().int().min(250).max(10000).default(1000),
1101
- emitProgress: z.boolean().default(false),
1102
- // Off by default. A wait is the call clients background and then replay
1103
- // as a notification, so its payload has to stay small; ten events per
1104
- // worker was the bulk of it. Ask for events explicitly, or read
1105
- // get_codex_worker_events for one worker.
1106
- includeEvents: z.boolean().default(false),
1107
- eventLimit: z.number().int().min(1).max(50).default(10),
1108
- // Events used to come back whole: one command event can carry a heredoc
1109
- // that is tens of KB, and ten of those made a single wait response
1110
- // unreadable. The default bounds each string; pass a bigger number when
1111
- // you actually want the raw text.
1112
- eventMaxChars: z.number().int().min(0).max(1000000).default(800),
1113
- eventKinds: z.array(z.string().min(1)).optional(),
1114
- // The smallest useful answer: one line per worker, for a caller that
1115
- // only wants to know who is done. Everything else comes from
1116
- // get_worker_result / get_worker_diff afterwards.
1117
- compact: z.boolean().optional()
1118
- }
1119
- },
1120
- async ({
1121
- task_ids,
1122
- mode,
1123
- timeoutMinutes,
1124
- timeoutMs,
1125
- allowLongWait,
1126
- pollMs,
1127
- emitProgress,
1128
- includeEvents,
1129
- eventLimit,
1130
- eventMaxChars,
1131
- eventKinds,
1132
- compact: requestedCompact
1133
- }, extra) => {
1134
- const compact = requestedCompact ?? !includeEvents;
1135
- const startedAt = Date.now();
1136
- const requestedTimeoutMs = timeoutMs ?? timeoutMinutes * 60 * 1000;
1137
- const effectiveTimeoutMs = allowLongWait ? requestedTimeoutMs : Math.min(requestedTimeoutMs, 60000);
1138
- let tasks = [];
1139
- const progressToken = extra?._meta?.progressToken;
1140
- let lastProgressAt = -Infinity;
1141
-
1142
- let clientCancelled = false;
1143
- while (Date.now() - startedAt < effectiveTimeoutMs) {
1144
- if (extra?.signal.aborted) { clientCancelled = true; break; }
1145
- await reconcileDetachedActiveTasks();
1146
- tasks = (await getTasks(task_ids)).filter(Boolean);
1147
- const settledCount = tasks.filter(isSettled).length;
1148
- const isDone = mode === "any" ? settledCount > 0 : settledCount === task_ids.length;
1149
- if (isDone) break;
1150
- const elapsed = Date.now() - startedAt;
1151
- if (emitProgress && progressToken != null && elapsed - lastProgressAt >= 30000) {
1152
- await extra.sendNotification({ method: "notifications/progress", params: {
1153
- progressToken, progress: elapsed, total: effectiveTimeoutMs,
1154
- message: `${settledCount}/${task_ids.length} workers settled; wait budget only`
1155
- } }).catch(() => {});
1156
- lastProgressAt = elapsed;
1157
- }
1158
- await sleep(Math.min(pollMs, Math.max(0, effectiveTimeoutMs - (Date.now() - startedAt))));
1159
- }
1160
-
1161
- await reconcileDetachedActiveTasks();
1162
- tasks = (await getTasks(task_ids)).filter(Boolean);
1163
- const missingIds = task_ids.filter((taskId) => !tasks.some((task) => task.id === taskId));
1164
- const settledTasks = tasks.filter(isSettled);
1165
- const timedOut =
1166
- mode === "any" ? settledTasks.length === 0 : settledTasks.length !== task_ids.length;
1167
-
1168
- const summaries = await Promise.all(
1169
- tasks.map(async (task) => ({
1170
- ...summarizeTask(task),
1171
- recent_events: includeEvents
1172
- ? await readTaskEvents(task.id, eventLimit, eventKinds ?? null).then((events) =>
1173
- eventMaxChars === undefined ? events : events.map((event) => truncateEventStrings(event, eventMaxChars))
1174
- )
1175
- : undefined
1176
- }))
1177
- );
1178
-
1179
- const budgetLabel =
1180
- effectiveTimeoutMs >= 60000
1181
- ? `${Math.round(effectiveTimeoutMs / 60000)}-minute`
1182
- : `${Math.round(effectiveTimeoutMs / 1000)}-second`;
1183
-
1184
- return textResult(withUpdate({
1185
- mode,
1186
- timed_out: timedOut,
1187
- still_running: timedOut,
1188
- termination_reason: clientCancelled ? "client_cancelled" : timedOut ? "budget_exhausted" : "settled",
1189
- next_step: timedOut
1190
- ? `Workers are still running; the ${budgetLabel} wait budget ran out. Reuse the same task_ids for a short wait, or schedule check_workers for long monitoring. Set allowLongWait only after verifying the client's MCP timeout supports the requested budget; do not start another long wait while a background wait is active.`
1191
- : null,
1192
- waited_ms: Date.now() - startedAt,
1193
- timeout_ms: effectiveTimeoutMs,
1194
- requested_timeout_ms: requestedTimeoutMs,
1195
- timeout_capped: effectiveTimeoutMs !== requestedTimeoutMs,
1196
- timeout_minutes: Math.round(effectiveTimeoutMs / 60000),
1197
- missing_ids: missingIds,
1198
- completed_count: tasks.filter((task) => task.status === "completed").length,
1199
- failed_count: tasks.filter((task) => task.status === "failed").length,
1200
- cancelled_count: tasks.filter((task) => task.status === "cancelled").length,
1201
- lost_count: tasks.filter((task) => task.status === "lost").length,
1202
- active_count: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
1203
- acceptance_failed_count: tasks.filter((task) => task.acceptance_results?.passed === false).length,
1204
- workers: compact
1205
- ? tasks.map((task) => ({
1206
- id: task.id,
1207
- title: clip(task.title, 60),
1208
- status: task.status,
1209
- phase: task.phase ?? null,
1210
- exit_code: task.exit_code ?? null,
1211
- changed_file_count: readTaskChanges(task).length,
1212
- acceptance: acceptanceVerdict(task),
1213
- ...compactLiveness(task),
1214
- updated_at: task.updated_at ?? null
1215
- }))
1216
- : summaries
1217
- }));
1218
- }
1219
- );
1220
-
1221
- server.registerTool(
1222
- "get_session_works",
1223
- {
1224
- title: "Get session works",
1225
- description:
1226
- "Every worker dispatched under one session_id, oldest first. This is the reconnect path: a main-thread session that died can list the whole batch it started without holding any of it in context.",
1227
- inputSchema: {
1228
- session_id: z.string().min(1)
1229
- }
1230
- },
1231
- async ({ session_id }) => {
1232
- const tasks = await readTasksBySession(session_id);
1233
- const meta = await getSession(session_id);
1234
- return textResult({
1235
- session_id,
1236
- title: meta?.title ?? null,
1237
- note: meta?.note ?? null,
1238
- objective: meta?.objective ?? null,
1239
- default_acceptance: meta?.default_acceptance ?? [],
1240
- approval_state: meta?.approval_state ?? "approved",
1241
- policy_revision: meta?.policy_revision ?? 0,
1242
- count: tasks.length,
1243
- active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
1244
- works: tasks.map(workRow)
1245
- });
1246
- }
1247
- );
1248
-
1249
- server.registerTool(
1250
- "check_for_update",
1251
- {
1252
- title: "Check for update",
1253
- description:
1254
- "Ask the npm registry whether a newer codex-supervisor-mcp is published, and whether the installed files match the published tarball. Returns installed and latest version, integrity check, and the install command. The same check runs on startup; call this to force a fresh one.",
1255
- inputSchema: {
1256
- force: z.boolean().default(true)
1257
- }
1258
- },
1259
- async ({ force }) => {
1260
- const result = await refreshUpdateState({ force });
1261
- if (!result) return textResult({ error: "update_check_failed" });
1262
- return textResult({ ...result, auto_update: autoUpdateState });
1263
- }
1264
- );
1265
-
1266
- server.registerTool(
1267
- "describe_session",
1268
- {
1269
- title: "Describe session",
1270
- description:
1271
- "Record what a session is about: a one-line title and an optional note. Readers of the store (the web view, get_session_works) show these instead of the bare session id. Fields you omit are kept.",
1272
- inputSchema: {
1273
- session_id: z.string().min(1),
1274
- title: z.string().min(1).max(120).optional(),
1275
- note: z.string().min(1).max(2000).optional(),
1276
- objective: z.string().min(1).max(5000).optional(),
1277
- default_acceptance: z.array(acceptanceCheck).max(10).optional(),
1278
- approval_state: z.enum(["approved", "waiting_user"]).optional(),
1279
- expected_revision: z.number().int().nonnegative().optional()
1280
- }
1281
- },
1282
- async ({ session_id, title, note, objective, default_acceptance, approval_state, expected_revision }) => {
1283
- try {
1284
- const row = await upsertSession({ id: session_id, title: title ?? null, note: note ?? null, objective, defaultAcceptance: default_acceptance, approvalState: approval_state, expectedRevision: expected_revision });
1285
- return textResult({ ...row, session_id, host_goal_sync: buildHostGoalSync(row) });
1286
- } catch (error) { return errorResult(error); }
1287
- }
1288
- );
1289
-
1290
- server.registerTool(
1291
- "search_works",
1292
- {
1293
- title: "Search works",
1294
- description:
1295
- "Substring search over title, goal, prompt and last message of every tracked worker, newest first. Use it to find an earlier work by keyword instead of paging through history.",
1296
- inputSchema: {
1297
- query: z.string().min(1),
1298
- limit: z.number().int().positive().max(100).default(20)
1299
- }
1300
- },
1301
- async ({ query, limit }) => {
1302
- const tasks = await searchTasks(query, limit);
1303
- return textResult({
1304
- query,
1305
- count: tasks.length,
1306
- works: tasks.map(workRow)
1307
- });
1308
- }
1309
- );
1310
-
1311
- server.registerTool(
1312
- "get_codex_worker_status",
1313
- {
1314
- title: "Get Codex worker status",
1315
- description:
1316
- "Read the latest normalized status for one Codex worker: lifecycle, phase, current action, changed files, goal, recent commands, and the task prompt (clipped by default). Set includePrompt to read the prompt in full, or use get_codex_worker_events for the raw stream.",
1317
- inputSchema: {
1318
- task_id: z.string().min(1),
1319
- includePrompt: z.boolean().default(false),
1320
- promptMaxChars: z.number().int().min(0).max(1000000).default(5000)
1321
- }
1322
- },
1323
- async ({ task_id, includePrompt, promptMaxChars }) => {
1324
- const task = await getTask(task_id);
1325
- if (!task) return textResult({ error: "task_not_found", task_id });
1326
- return textResult(statusView(task, { includePrompt, promptMaxChars }));
1327
- }
1328
- );
1329
-
1330
- server.registerTool(
1331
- "get_codex_worker_events",
1332
- {
1333
- title: "Get Codex worker events",
1334
- description:
1335
- "Read recent raw Codex JSONL events for one worker. limit, maxChars and kinds keep the read inside a context budget; maxChars truncates the middle of oversized strings the same way Codex truncates its own output.",
1336
- inputSchema: {
1337
- task_id: z.string().min(1),
1338
- limit: z.number().int().min(1).max(1000).default(100),
1339
- maxChars: z.number().int().min(0).max(1000000).optional(),
1340
- kinds: z.array(z.string().min(1)).optional()
1341
- }
1342
- },
1343
- async ({ task_id, limit, maxChars, kinds }) => {
1344
- const task = await getTask(task_id);
1345
- if (!task) return textResult({ error: "task_not_found", task_id });
1346
- const events = await readTaskEvents(task_id, limit, kinds ?? null);
1347
- const trimmed = maxChars === undefined ? events : events.map((event) => truncateEventStrings(event, maxChars));
1348
- return textResult({
1349
- task_id,
1350
- count: trimmed.length,
1351
- available_kinds: await listTaskEventKinds(task_id),
1352
- events: trimmed
1353
- });
1354
- }
1355
- );
1356
-
1357
- server.registerTool(
1358
- "get_context_snapshot_meta",
1359
- {
1360
- title: "Get worker context snapshot metadata",
1361
- description: "Read the latest worker-only context snapshot metadata for one task. Returns fact IDs, token estimate and excluded categories, never the capsule text or raw history.",
1362
- inputSchema: { task_id: z.string().min(1) }
1363
- },
1364
- async ({ task_id }) => {
1365
- const task = await getTask(task_id);
1366
- if (!task) return textResult({ error: "task_not_found", task_id });
1367
- const snapshot = await latestContextSnapshotForTask(task_id);
1368
- if (!snapshot) return textResult({ task_id, snapshot: null });
1369
- return textResult({
1370
- task_id,
1371
- snapshot: {
1372
- id: snapshot.id,
1373
- run_id: snapshot.run_id,
1374
- recipient: snapshot.recipient,
1375
- fact_ids: JSON.parse(snapshot.fact_versions),
1376
- base_sha: snapshot.base_sha,
1377
- prompt_sha256: snapshot.prompt_sha256,
1378
- estimated_tokens: snapshot.estimated_tokens,
1379
- excluded: JSON.parse(snapshot.excluded_json),
1380
- created_at: snapshot.created_at
1381
- }
1382
- });
1383
- }
1384
- );
1385
-
1386
- server.registerTool(
1387
- "get_fact",
1388
- {
1389
- title: "Get one verified or candidate fact",
1390
- description: "Read one fact by ID for audit. Facts are never automatically expanded into the main thread's context.",
1391
- inputSchema: { fact_id: z.string().uuid() }
1392
- },
1393
- async ({ fact_id }) => {
1394
- const fact = await getFact(fact_id);
1395
- if (!fact) return textResult({ error: "fact_not_found", fact_id });
1396
- return textResult({ fact, effective_state: await getFactEffectiveState(fact_id) ?? fact.state });
1397
- }
1398
- );
1399
-
1400
- server.registerTool(
1401
- "get_artifact",
1402
- {
1403
- title: "Get one retained evidence artifact",
1404
- description: "Read one supervisor-managed artifact by ID for audit. This is explicit evidence retrieval and never expands a worker context capsule into the main thread.",
1405
- inputSchema: { artifact_id: z.string().uuid(), maxChars: z.number().int().min(0).max(100000).default(12000) }
1406
- },
1407
- async ({ artifact_id, maxChars }) => {
1408
- const artifact = await getArtifact(artifact_id);
1409
- if (!artifact) return textResult({ error: "artifact_not_found", artifact_id });
1410
- return textResult({ artifact: await readArtifact(artifact_id, maxChars) });
1411
- }
1412
- );
1413
-
1414
- server.registerTool(
1415
- "promote_worker_fact",
1416
- {
1417
- title: "Promote a candidate worker fact",
1418
- description: "Explicitly promote one candidate fact after main-thread review. The worker cannot call this: promotion writes a new verified fact with an audit event; repo scope requires watched paths.",
1419
- inputSchema: {
1420
- fact_id: z.string().uuid(),
1421
- scope: z.enum(["work_item", "repo_verified"]).default("work_item"),
1422
- watchedPaths: z.array(z.string().min(1)).max(100).optional(),
1423
- expiresAt: z.string().datetime().optional()
1424
- }
1425
- },
1426
- async ({ fact_id, scope, watchedPaths, expiresAt }) => {
1427
- try {
1428
- const source = await getFact(fact_id);
1429
- if (!source) return textResult({ error: "fact_not_found", fact_id });
1430
- if (await isFactRevoked(fact_id)) return textResult({ error: "fact_already_revoked", fact_id });
1431
- const task = await getTaskForWorkItem(source.work_item_id);
1432
- if (!task) return textResult({ error: "fact_task_not_found", fact_id });
1433
- const event = await appendTaskEvent(task.id, { type: "supervisor.fact_promoted", source_fact_id: fact_id, scope, watched_paths: watchedPaths ?? source.watched_paths ?? [], expires_at: expiresAt ?? null }, {
1434
- runId: runIdFor(task.id, task.run_count ?? 1), actor: "main_thread"
1435
- });
1436
- const fact = await promoteCandidateFact({
1437
- factId: fact_id,
1438
- scopeType: scope,
1439
- watchedPaths,
1440
- expiresAt: expiresAt ?? null,
1441
- sourceEventId: event.id,
1442
- verifiedBy: "main_thread"
1443
- });
1444
- return textResult({ fact, source_fact_id: fact_id });
1445
- } catch (error) {
1446
- return errorResult(error);
1447
- }
1448
- }
1449
- );
1450
-
1451
- server.registerTool(
1452
- "revoke_worker_fact",
1453
- {
1454
- title: "Revoke a candidate or verified worker fact",
1455
- description: "Explicitly revoke one candidate or verified fact after audit. Revoked facts are excluded from search and worker capsules; the revocation is appended to the worker event log.",
1456
- inputSchema: { fact_id: z.string().uuid(), reason: z.string().min(1).max(2000) }
1457
- },
1458
- async ({ fact_id, reason }) => {
1459
- try {
1460
- const source = await getFact(fact_id);
1461
- if (!source) return textResult({ error: "fact_not_found", fact_id });
1462
- const task = await getTaskForWorkItem(source.work_item_id);
1463
- if (!task) return textResult({ error: "fact_task_not_found", fact_id });
1464
- const revoked = await revokeFact(fact_id);
1465
- await appendTaskEvent(task.id, { type: "supervisor.fact_revoked", fact_id, reason }, {
1466
- runId: runIdFor(task.id, task.run_count ?? 1), actor: "main_thread"
1467
- });
1468
- return textResult({ fact: revoked, reason });
1469
- } catch (error) {
1470
- return errorResult(error);
1471
- }
1472
- }
1473
- );
1474
-
1475
- server.registerTool(
1476
- "get_worker_evidence",
1477
- {
1478
- title: "Get a worker evidence index",
1479
- description: "Return bounded event metadata and retained artifact IDs for one worker. It does not return raw history, prompts or a worker context capsule; use get_artifact or get_codex_worker_events for a selected item.",
1480
- inputSchema: { task_id: z.string().min(1), limit: z.number().int().min(1).max(100).default(30) }
1481
- },
1482
- async ({ task_id, limit }) => {
1483
- const task = await getTask(task_id);
1484
- if (!task) return textResult({ error: "task_not_found", task_id });
1485
- const events = await readTaskEventRecords(task_id, limit);
1486
- const artifacts = await listArtifactsForTask(task_id, limit);
1487
- return textResult({
1488
- task_id,
1489
- events: events.map((event) => ({ id: event.id, run_id: event.run_id, type: event.event_type, actor: event.actor, payload_sha256: event.payload_sha256, created_at: event.created_at })),
1490
- artifacts: artifacts.map((artifact) => ({ id: artifact.id, run_id: artifact.run_id, type: artifact.type, sha256: artifact.sha256, security_class: artifact.security_class, retention: artifact.retention, created_at: artifact.created_at }))
1491
- });
1492
- }
1493
- );
1494
-
1495
- function decodeFactCursor(cursor, taskId, query) {
1496
- if (!cursor) return 0;
1497
- try {
1498
- const payload = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
1499
- if (payload.task_id !== taskId || payload.query !== query || !Number.isInteger(payload.offset) || payload.offset < 0) throw new Error("mismatch");
1500
- return payload.offset;
1501
- } catch {
1502
- const error = new Error("fact cursor does not match this task and query");
1503
- error.code = "invalid_fact_cursor";
1504
- throw error;
1505
- }
1506
- }
1507
-
1508
- function encodeFactCursor(taskId, query, offset) {
1509
- return Buffer.from(JSON.stringify({ task_id: taskId, query, offset })).toString("base64url");
1510
- }
1511
-
1512
- function factFreshForTask(task, fact) {
1513
- if (!fact.valid_for_sha || !task.base_commit) return true;
1514
- try {
1515
- git(task.project_root, ["merge-base", "--is-ancestor", fact.valid_for_sha, task.base_commit]);
1516
- return true;
1517
- } catch {
1518
- return false;
1519
- }
1520
- }
1521
-
1522
- server.registerTool(
1523
- "search_worker_facts",
1524
- {
1525
- title: "Search verified worker facts in scope",
1526
- description: "Search only verified facts relevant to one task: its own work, explicit dependencies and path-matched repository facts. Returns compact summaries, coverage and a cursor; never raw events, reports, prompts or worker capsules.",
1527
- inputSchema: {
1528
- task_id: z.string().min(1),
1529
- query: z.string().max(500).default(""),
1530
- limit: z.number().int().min(1).max(50).default(20),
1531
- cursor: z.string().min(1).optional()
1532
- }
1533
- },
1534
- async ({ task_id, query, limit, cursor }) => {
1535
- const task = await getTask(task_id);
1536
- if (!task) return textResult({ error: "task_not_found", task_id });
1537
- try {
1538
- const normalizedQuery = query.trim().toLocaleLowerCase();
1539
- const offset = decodeFactCursor(cursor, task_id, normalizedQuery);
1540
- const scoped = (await listContextFacts({
1541
- taskId: task_id,
1542
- baseSha: task.base_commit ?? null,
1543
- ownedPaths: task.owned_paths ?? [],
1544
- dependencyTaskIds: task.depends_on ?? []
1545
- })).filter((fact) => factFreshForTask(task, fact));
1546
- const matching = scoped.filter((fact) => !normalizedQuery || `${fact.key}\n${JSON.stringify(fact.value)}`.toLocaleLowerCase().includes(normalizedQuery));
1547
- const page = matching.slice(offset, offset + limit);
1548
- const nextOffset = offset + page.length;
1549
- const totalVerified = await countVerifiedFacts();
1550
- return textResult({
1551
- task_id,
1552
- facts: page.map((fact) => ({
1553
- id: fact.id,
1554
- key: fact.key,
1555
- summary: clip(typeof fact.value === "string" ? fact.value : JSON.stringify(fact.value), 360),
1556
- state: fact.state,
1557
- scope: fact.scope_type,
1558
- valid_for_sha: fact.valid_for_sha ?? null,
1559
- freshness: "current",
1560
- source_refs: [
1561
- ...(fact.source_event_id ? [`event:${fact.source_event_id}`] : []),
1562
- ...(fact.source_artifact_id ? [`artifact:${fact.source_artifact_id}`] : [])
1563
- ]
1564
- })),
1565
- coverage: {
1566
- scope: "current_work+explicit_dependencies+path_matched_repo_facts",
1567
- included_count: scoped.length,
1568
- matched_count: matching.length,
1569
- omitted: [
1570
- { reason: "other_verified_scopes_excluded", count: Math.max(0, totalVerified - scoped.length) },
1571
- { reason: "candidate_and_nonverified_facts_excluded", count: null }
1572
- ]
1573
- },
1574
- next_cursor: nextOffset < matching.length ? encodeFactCursor(task_id, normalizedQuery, nextOffset) : null
1575
- });
1576
- } catch (error) {
1577
- return errorResult(error);
1578
- }
1579
- }
1580
- );
1581
-
1582
- server.registerTool(
1583
- "create_independent_verifier",
1584
- {
1585
- title: "Create an independent read-only verifier",
1586
- description: "Create a fresh read-only verifier for one settled worker. It receives the target objective and current worktree path, never the target report or candidate facts, has no network and cannot dispatch workers. The review relation is persisted for later finding and resolution.",
1587
- inputSchema: { task_id: z.string().min(1), title: z.string().min(1).max(120).optional() }
1588
- },
1589
- async ({ task_id, title }) => {
1590
- try {
1591
- const subject = await getTask(task_id);
1592
- if (!subject) return textResult({ error: "task_not_found", task_id });
1593
- if (!isSettled(subject)) return textResult({ error: "review_subject_active", task_id, reason: "wait for the worker and any acceptance to settle before independent review" });
1594
- const sourceRoot = subject.worktree_path ?? subject.project_root;
1595
- const verifier = await createCodexWorker({
1596
- title: title ?? `Independent review: ${subject.title ?? subject.id}`,
1597
- task: [
1598
- "Independently verify the target worker's objective from the current source tree and Git state.",
1599
- `Target task ID: ${subject.id}`,
1600
- `Target objective: ${subject.goal_objective ?? subject.title ?? "unspecified"}`,
1601
- `Inspect root: ${sourceRoot}`,
1602
- "Do not trust or request the target worker's report. Do not inspect candidate facts. Do not edit files, use network, create workers or call MCP tools.",
1603
- "Return whether the stated objective is met, the exact evidence you inspected, and any unresolved gap."
1604
- ].join("\n"),
1605
- cwd: sourceRoot,
1606
- workspaceKind: "read_only_in_place",
1607
- sandbox: "read-only",
1608
- ownedPaths: [],
1609
- networkAccess: false,
1610
- goal: { objective: `Independently verify worker ${subject.id} without relying on its self-report` }
1611
- });
1612
- const fingerprint = createHash("sha256").update(JSON.stringify({
1613
- task_id: subject.id,
1614
- run: subject.run_count ?? 0,
1615
- base_sha: subject.base_commit ?? null,
1616
- worktree: sourceRoot,
1617
- updated_at: subject.updated_at ?? null,
1618
- changed_files: subject.changed_files ?? []
1619
- })).digest("hex");
1620
- const review = await createReviewAssignment({
1621
- subjectTaskId: subject.id,
1622
- verifierTaskId: verifier.id,
1623
- subjectRunId: runIdFor(subject.id, subject.run_count ?? 1),
1624
- subjectBaseSha: subject.base_commit ?? null,
1625
- subjectFingerprint: fingerprint
1626
- });
1627
- return textResult({ ...receipt(verifier), review });
1628
- } catch (error) {
1629
- return errorResult(error);
1630
- }
1631
- }
1632
- );
1633
-
1634
- server.registerTool(
1635
- "record_independent_finding",
1636
- {
1637
- title: "Record an independent verifier finding",
1638
- description: "After a verifier settles, record its passes/fails/inconclusive verdict with a concise reason. The supervisor stores a retained finding artifact and appends an event to the reviewed worker; this does not change the reviewed worker's delivery state automatically.",
1639
- inputSchema: { verifier_task_id: z.string().min(1), verdict: z.enum(["passes", "fails", "inconclusive"]), reason: z.string().min(1).max(4000) }
1640
- },
1641
- async ({ verifier_task_id, verdict, reason }) => {
1642
- try {
1643
- const review = await getReviewByVerifierTask(verifier_task_id);
1644
- if (!review) return textResult({ error: "review_not_found", verifier_task_id });
1645
- if (review.status !== "pending") return textResult({ error: "review_not_pending", verifier_task_id, status: review.status });
1646
- const verifier = await getTask(verifier_task_id);
1647
- if (!verifier || !isSettled(verifier)) return textResult({ error: "verifier_not_settled", verifier_task_id });
1648
- const subject = await getTask(review.subject_task_id);
1649
- if (!subject) return textResult({ error: "review_subject_not_found", task_id: review.subject_task_id });
1650
- const artifact = await recordJsonArtifact({
1651
- runId: runIdFor(verifier.id, verifier.run_count ?? 1),
1652
- type: "independent_review_finding",
1653
- value: { review_id: review.id, subject_task_id: subject.id, verifier_task_id, verdict, reason, verifier_run: verifier.run_count ?? 1, recorded_at: new Date().toISOString() },
1654
- securityClass: "internal"
1655
- });
1656
- const event = await appendTaskEvent(subject.id, { type: "supervisor.independent_finding", review_id: review.id, verifier_task_id, verdict, reason, artifact_id: artifact.id }, {
1657
- runId: review.subject_run_id ?? runIdFor(subject.id, subject.run_count ?? 1), actor: "main_thread"
1658
- });
1659
- const recorded = await recordReviewFinding({ verifierTaskId: verifier_task_id, verdict, reason, evidenceArtifactId: artifact.id, findingEventId: event.id });
1660
- return textResult({ review: recorded, artifact_id: artifact.id });
1661
- } catch (error) {
1662
- return errorResult(error);
1663
- }
1664
- }
1665
- );
1666
-
1667
- server.registerTool(
1668
- "resolve_independent_finding",
1669
- {
1670
- title: "Resolve an independent verifier finding",
1671
- description: "Record how a previously recorded independent finding was resolved. This is an audit transition only; it does not hide the finding or alter worker code.",
1672
- inputSchema: { verifier_task_id: z.string().min(1), resolution: z.string().min(1).max(4000) }
1673
- },
1674
- async ({ verifier_task_id, resolution }) => {
1675
- try {
1676
- const review = await resolveReviewFinding({ verifierTaskId: verifier_task_id, resolution });
1677
- if (!review) return textResult({ error: "review_not_recorded", verifier_task_id });
1678
- const subject = await getTask(review.subject_task_id);
1679
- if (subject) await appendTaskEvent(subject.id, { type: "supervisor.independent_finding_resolved", review_id: review.id, verifier_task_id, resolution }, {
1680
- runId: review.subject_run_id ?? runIdFor(subject.id, subject.run_count ?? 1), actor: "main_thread"
1681
- });
1682
- return textResult({ review });
1683
- } catch (error) {
1684
- return errorResult(error);
1685
- }
1686
- }
1687
- );
1688
-
1689
- server.registerTool(
1690
- "get_independent_review",
1691
- {
1692
- title: "Get one independent review relation",
1693
- description: "Read the persisted subject/verifier/finding/resolution relation for a verifier task. Use get_artifact for the retained finding evidence.",
1694
- inputSchema: { verifier_task_id: z.string().min(1) }
1695
- },
1696
- async ({ verifier_task_id }) => {
1697
- const review = await getReviewByVerifierTask(verifier_task_id);
1698
- return textResult(review ? { review } : { error: "review_not_found", verifier_task_id });
1699
- }
1700
- );
1701
-
1702
- server.registerTool(
1703
- "get_worker_goal",
1704
- {
1705
- title: "Get worker goal",
1706
- description:
1707
- "Read the goal recorded for a worker, plus the native Codex thread goal when the thread has one (status, tokens used, time used).",
1708
- inputSchema: {
1709
- task_id: z.string().min(1)
1710
- }
1711
- },
1712
- async ({ task_id }) => {
1713
- const task = await getTask(task_id);
1714
- if (!task) return textResult({ error: "task_not_found", task_id });
1715
- return textResult({
1716
- task_id,
1717
- thread_id: task.thread_id,
1718
- status: task.status,
1719
- objective: task.goal_objective,
1720
- token_budget: task.goal_token_budget,
1721
- goal_status: task.goal_status,
1722
- needs_attention: isGoalNeedingAttention(task.goal_status),
1723
- native_goal: readNativeGoal(task.thread_id),
1724
- native_goal_read: readNativeGoalState(task.thread_id)
1725
- });
1726
- }
1727
- );
1728
-
1729
- server.registerTool(
1730
- "get_worker_summary",
1731
- {
1732
- title: "Get worker summary",
1733
- description:
1734
- "One compact summary per worker: goal, status, changed files, last command, last message. Cheap enough for a main thread to read every worker at the end of a run.",
1735
- inputSchema: {
1736
- task_id: z.string().min(1)
1737
- }
1738
- },
1739
- async ({ task_id }) => {
1740
- const task = await getTask(task_id);
1741
- if (!task) return textResult({ error: "task_not_found", task_id });
1742
- const summary = buildWorkerSummary(task, readNativeGoal(task.thread_id));
1743
- // Cache the worktree diff on the row once the worker is done, so the
1744
- // overview's count stops lagging. A running row is the runner's to write.
1745
- if (TERMINAL_STATUSES.has(task.status) && summary.changed_files.length !== (task.changed_files ?? []).length) {
1746
- await recordTerminalChangedFiles(task.id, summary.changed_files);
1747
- }
1748
- return textResult(summary);
1749
- }
1750
- );
1751
-
1752
- server.registerTool(
1753
- "get_worker_result",
1754
- {
1755
- title: "Get worker result",
1756
- description:
1757
- "Read a worker's own final report. The overview and the wait response clip the last message; this is the door for the actual conclusion. Returns the last N agent messages (each clipped past maxChars, default 6000 bytes, with truncated: true and the full size so you can re-read it whole), the status fields that tell a real finish from a crash, verification (the commands the worker ran, their exit codes and the tail of any failing output, to hold its report against), acceptance (the supervisor's own run of the dispatch-time acceptance commands, independent of the report: configured, passed, and each check's exit code and output tail; passed: false means resume the worker with that output instead of reading its report, passed: true against a report that says blocked or not done means trust the checks and read the diff), changed_file_count, and base_behind (how many commits the project's HEAD is past the worktree's base; resume with rebaseOnto when it is not 0). includeFiles: true adds the changed_files list; get_worker_diff is the ground truth for what changed.",
1758
- inputSchema: {
1759
- task_id: z.string().min(1),
1760
- limit: z.number().int().min(1).max(20).default(1),
1761
- // Per report, UTF-8 bytes. 0 means no clipping.
1762
- maxChars: z.number().int().min(0).max(1000000).default(6000),
1763
- includeFiles: z.boolean().default(false)
1764
- }
1765
- },
1766
- async ({ task_id, limit, maxChars, includeFiles }) => {
1767
- const task = await getTask(task_id);
1768
- if (!task) return textResult({ error: "task_not_found", task_id });
1769
- let reports = await readAgentMessages(task_id, limit);
1770
- let source = "event_stream";
1771
- if (reports.length === 0 && task.last_message) {
1772
- // Older rows can predate this tool, but the task row keeps the newest
1773
- // report even when the stream query finds nothing.
1774
- reports = [task.last_message];
1775
- source = "task_row";
1776
- }
1777
- const reportBytes = reports.map((text) => Buffer.byteLength(text, "utf8"));
1778
- const clipped = maxChars === 0 ? reports : reports.map((text) => truncateReport(text, maxChars));
1779
- const truncated = clipped.some((text, index) => text !== reports[index]);
1780
- const changed = readTaskChanges(task);
1781
- const behind = task.worktree_path ? baseBehind(task.project_root, task.base_commit) : null;
1782
- // A worker that ran in place has no worktree to diff, so this list is
1783
- // the only record of what it touched; it is never hidden for those.
1784
- const listFiles = includeFiles || !task.worktree_path;
1785
- return textResult({
1786
- task_id,
1787
- title: task.title,
1788
- status: task.status,
1789
- phase: task.phase ?? null,
1790
- exit_code: task.exit_code ?? null,
1791
- thread_id: task.thread_id,
1792
- session_id: task.session_id ?? null,
1793
- workspace_kind: task.workspace_kind ?? "legacy",
1794
- worktree_path: task.worktree_path,
1795
- goal_status: task.goal_status,
1796
- attention_reason: task.attention_reason ?? null,
1797
- run_evidence: runEvidenceView(task),
1798
- structured_report: reportView(task, maxChars),
1799
- input_context: task.input_context ?? null,
1800
- external_outputs: externalOutputView(task, maxChars || 6000),
1801
- changed_file_count: changed.length,
1802
- changed_files: listFiles ? changed : undefined,
1803
- base_commit: task.base_commit ?? null,
1804
- base_behind: behind,
1805
- landed: task.landed_at ? { at: task.landed_at, head: task.landed_head ?? null } : null,
1806
- acceptance: acceptanceView(task, behind),
1807
- verification: summarizeVerification(task),
1808
- report_count: clipped.length,
1809
- report_bytes: reportBytes,
1810
- truncated,
1811
- next_step: truncated
1812
- ? `a report was clipped to ${maxChars} bytes; call again with maxChars: ${Math.max(...reportBytes)} (or 0) to read it whole`
1813
- : null,
1814
- reports: clipped,
1815
- source,
1816
- error: task.error ?? null,
1817
- completed_at: task.completed_at ?? null
1818
- });
1819
- }
1820
- );
1821
-
1822
- server.registerTool(
1823
- "get_worker_diff",
1824
- {
1825
- title: "Get worker diff",
1826
- description:
1827
- "The worker's actual changes. By default this is a complete file/hunk index; request one file to page through hunks with pageSize or cursor. Supplying maxChars without file preserves the legacy bounded full-diff response. This is the ground truth to check a worker's report against.",
1828
- inputSchema: {
1829
- task_id: z.string().min(1),
1830
- maxChars: z.number().int().min(0).max(1000000).optional(),
1831
- file: z.string().min(1).optional(),
1832
- hunk: z.number().int().min(0).optional(),
1833
- pageSize: z.number().int().min(1).max(20).default(4),
1834
- cursor: z.string().min(1).optional(),
1835
- paths: z.array(z.string().min(1)).optional()
1836
- }
1837
- },
1838
- async ({ task_id, maxChars, file, hunk, pageSize, cursor, paths }) => {
1839
- const task = await getTask(task_id);
1840
- if (!task) return textResult({ error: "task_not_found", task_id });
1841
- if (!task.worktree_path) {
1842
- return textResult({ error: "no_worktree", task_id, external_outputs: externalOutputView(task, maxChars), reason: "this worker ran in place (its cwd is not a git repository or the worktree could not be created), so there is no isolated diff to read; call get_worker_result with includeFiles: true for the files it touched" });
1843
- }
1844
- if (!file && maxChars !== undefined) {
1845
- const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars, paths: paths ?? [], ignorePaths: workspaceSetupIgnorePaths(task) });
1846
- return textResult({
1847
- task_id,
1848
- title: task.title,
1849
- status: task.status,
1850
- worktree_path: task.worktree_path,
1851
- branch: `codex/${task.id}`,
1852
- ...diff,
1853
- external_outputs: externalOutputView(task, maxChars)
1854
- });
1855
- }
1856
- const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars: 10_000_000, paths: paths ?? [], ignorePaths: workspaceSetupIgnorePaths(task) });
1857
- if (diff.error) return textResult({ ...diff, task_id });
1858
- const files = diff.files.map((entry) => {
1859
- const parsed = splitPatchHunks(entry);
1860
- return { path: entry.path, status: entry.status, from: entry.from, additions: entry.additions, deletions: entry.deletions, hunk_count: parsed.hunks.length };
1861
- });
1862
- const base = {
1863
- task_id,
1864
- title: task.title,
1865
- status: task.status,
1866
- worktree_path: task.worktree_path,
1867
- branch: `codex/${task.id}`,
1868
- ...diff,
1869
- files,
1870
- external_outputs: externalOutputView(task, maxChars || 6000)
1871
- };
1872
- if (!file) return textResult({ ...base, summary_only: true, next_step: "choose files[].path, then request file plus hunk or cursor" });
1873
- const selected = diff.files.find((entry) => entry.path === file);
1874
- if (!selected) return textResult({ error: "diff_file_not_found", task_id, file, files });
1875
- const parsed = splitPatchHunks(selected);
1876
- let offset = 0;
1877
- if (cursor) {
1878
- try {
1879
- const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
1880
- if (value.task_id !== task_id || value.file !== file || !Number.isInteger(value.offset) || value.offset < 0) throw new Error("mismatch");
1881
- offset = value.offset;
1882
- } catch {
1883
- return textResult({ error: "invalid_diff_cursor", task_id, file });
1884
- }
1885
- }
1886
- if (hunk !== undefined) offset = hunk;
1887
- if (offset >= parsed.hunks.length) return textResult({ error: "diff_hunk_not_found", task_id, file, hunk: offset, hunk_count: parsed.hunks.length });
1888
- let remaining = maxChars ?? 24000;
1889
- const hunks = [];
1890
- for (let index = offset; index < parsed.hunks.length && hunks.length < pageSize; index += 1) {
1891
- if (remaining <= 0) break;
1892
- const item = parsed.hunks[index];
1893
- const patchText = item.patch.length > remaining ? truncateMiddleChars(item.patch, remaining) : item.patch;
1894
- hunks.push({ ...item, patch: patchText, truncated: patchText.length < item.patch.length });
1895
- remaining -= patchText.length;
1896
- }
1897
- const nextOffset = offset + hunks.length;
1898
- const nextCursor = nextOffset < parsed.hunks.length
1899
- ? Buffer.from(JSON.stringify({ task_id, file, offset: nextOffset })).toString("base64url")
1900
- : null;
1901
- return textResult({
1902
- ...base,
1903
- file: { path: selected.path, status: selected.status, from: selected.from, additions: selected.additions, deletions: selected.deletions, hunk_count: parsed.hunks.length },
1904
- hunks,
1905
- next_cursor: nextCursor,
1906
- summary_only: false
1907
- });
1908
- }
1909
- );
1910
-
1911
- server.registerTool(
1912
- "ask_codex_worker",
1913
- {
1914
- title: "Ask a worker on the side",
1915
- description:
1916
- "Ask a finished or running worker a question without touching its thread: the worker's Codex thread is forked once into a read-only side session (like Codex's own /btw), the question is asked there, and later questions resume that fork. The fork carries everything the worker saw and did, so 'why did you change X' or 'where is Y handled' costs one short answer instead of a read of the event stream. The fork has no network and no MCP tools and is told so; it answers from its context and the worktree. Once the worker has been resumed, the next question automatically takes a new fork from the updated thread (refreshed: \"worker_resumed\"); fresh: true forces a new fork. Changes still go through resume_codex_worker. Without a question it returns the latest side turn (for an answer that outran timeoutMs). end: true deletes the fork.",
1917
- inputSchema: {
1918
- task_id: z.string().min(1),
1919
- question: z.string().min(1).optional(),
1920
- timeoutMs: z.number().int().min(1000).max(600000).default(110000),
1921
- maxChars: z.number().int().min(0).max(1000000).default(8000),
1922
- fresh: z.boolean().default(false),
1923
- end: z.boolean().default(false)
1924
- }
1925
- },
1926
- async ({ task_id, question, timeoutMs, maxChars, fresh, end }) => {
1927
- const task = await getTask(task_id);
1928
- if (!task) return textResult({ error: "task_not_found", task_id });
1929
- const clipAnswer = (state) => {
1930
- if (state?.turn?.answer && maxChars !== undefined) state.turn.answer = truncateMiddleChars(state.turn.answer, maxChars);
1931
- return state;
1932
- };
1933
- if (end) {
1934
- const ended = await endSideSession(task_id);
1935
- return textResult({ task_id, ...ended });
1936
- }
1937
- if (!question) {
1938
- return textResult({ task_id, ...clipAnswer(await latestSideTurn(task_id)) });
1939
- }
1940
- try {
1941
- const state = clipAnswer(await askWorker({ task, question, timeoutMs, fresh }));
1942
- const next = state.timed_out
1943
- ? `The side turn is still running; call ask_codex_worker again with only task_id to read the answer when it lands.`
1944
- : null;
1945
- return textResult({ task_id, ...state, next_step: next });
1946
- } catch (error) {
1947
- if (error.code === "busy") {
1948
- return textResult({ task_id, error: "busy", reason: error.message, ...clipAnswer(await latestSideTurn(task_id)) });
1949
- }
1950
- return textResult({ task_id, error: error.code ?? "side_turn_failed", reason: error.message });
1951
- }
1952
- }
1953
- );
1954
-
1955
- server.registerTool(
1956
- "land_codex_worker",
1957
- {
1958
- title: "Land a worker's commits",
1959
- description:
1960
- "Cherry-pick the commits a worker made on its codex/<taskId> branch onto the current branch of the directory it was dispatched from. The target must be clean and is never switched to another branch; `onto` is a guard that names the branch you expect to be on. A conflict aborts the cherry-pick, lists the files, and leaves the target as it was. A worker in the workspace-write sandbox cannot commit (Codex keeps .git read-only there): pass commitMessage and its uncommitted edits are committed as one commit on its branch first, then landed. Without commitMessage uncommitted edits are reported, not landed. includeFollowupParents lands an unlanded followup chain root-first; commitMessages supplies a per-task checkpoint message when an ancestor has uncommitted edits. Check the work first with get_worker_result and get_worker_diff; land once it passes. A malformed report summary is attention, not a separate landing veto when the same run's acceptance passed and the reviewed diff is sound. Refuses with acceptance_failed while the worker's last acceptance run failed (and acceptance_not_run while one is running or was interrupted): resume it with the failing output, land once it passes. ignoreAcceptance: true lands anyway; use it only when the user said to land regardless.",
1961
- inputSchema: {
1962
- task_id: z.string().min(1),
1963
- onto: z.string().min(1).optional(),
1964
- commitMessage: z.string().min(1).optional(),
1965
- includeFollowupParents: z.boolean().default(false),
1966
- commitMessages: z.record(z.string(), z.string().min(1)).optional(),
1967
- ignoreAcceptance: z.boolean().default(false),
1968
- allowOutsideOwned: z.boolean().default(false)
1969
- }
1970
- },
1971
- async ({ task_id, onto, commitMessage, includeFollowupParents, commitMessages, ignoreAcceptance, allowOutsideOwned }) => {
1972
- if (!includeFollowupParents) {
1973
- const task = await getTask(task_id);
1974
- if (task?.followup_of) {
1975
- let ids;
1976
- try { ids = await followupChainIds(task_id); }
1977
- catch (error) { return textResult({ error: "invalid_followup_chain", task_id, reason: error.message }); }
1978
- const unlanded = [];
1979
- for (const id of ids.slice(0, -1)) {
1980
- const ancestor = await getTask(id);
1981
- if (ancestor) {
1982
- try {
1983
- if (!ancestor.landed_at || !ancestor.landed_head) throw new Error("parent not landed");
1984
- git(task.project_root, ["merge-base", "--is-ancestor", ancestor.landed_head, "HEAD"]);
1985
- } catch { unlanded.push(id); }
1986
- }
1987
- }
1988
- if (unlanded.length) {
1989
- return textResult({
1990
- error: "followup_parents_not_landed",
1991
- task_id,
1992
- unlanded,
1993
- reason: "this follow-up starts from its parent branch; landing only the leaf would integrate a partial chain. Use includeFollowupParents: true after reviewing every task's acceptance and diff."
1994
- });
1995
- }
1996
- }
1997
- return textResult(await landOneWorkerTask(task_id, { onto, commitMessage, ignoreAcceptance, allowOutsideOwned }));
1998
- }
1999
- let ids;
2000
- try { ids = await followupChainIds(task_id); }
2001
- catch (error) { return textResult({ error: "invalid_followup_chain", task_id, reason: error.message }); }
2002
- const chain = [];
2003
- for (const id of ids) {
2004
- let result;
2005
- try { result = await landOneWorkerTask(id, {
2006
- onto,
2007
- commitMessage: commitMessages?.[id] ?? (id === task_id ? commitMessage : null),
2008
- ignoreAcceptance: id === task_id && ignoreAcceptance,
2009
- allowOutsideOwned: id === task_id && allowOutsideOwned,
2010
- skipAlreadyLanded: true
2011
- }); } catch (error) {
2012
- result = { task_id: id, error: "landing_failed", reason: error.message };
2013
- }
2014
- if (id !== task_id && result.error === "nothing_to_land"
2015
- && (result.uncommitted ?? []).length === 0 && !(result.already_landed?.length)) {
2016
- chain.push({ ...result, error: null, skipped: "no_changes" });
2017
- continue;
2018
- }
2019
- if (result.skipped === "already_in_target" && (result.uncommitted ?? []).length === 0) {
2020
- chain.push({ ...result, error: null, skipped: "already_in_target" });
2021
- continue;
2022
- }
2023
- chain.push(result);
2024
- if (result.error) {
2025
- return textResult({ error: "followup_chain_land_failed", task_id, failed_task_id: id, chain });
2026
- }
2027
- }
2028
- return textResult({ task_id, chain });
2029
- }
2030
- );
2031
-
2032
- server.registerTool(
2033
- "verify_delivery_push",
2034
- {
2035
- title: "Verify landed work reached a remote branch",
2036
- description: "Fetch a remote branch and prove the worker's landed_head is reachable from it. This never pushes or deploys. A passing check records push_verified; cleanup eligibility may depend on this evidence.",
2037
- inputSchema: {
2038
- task_id: z.string().min(1),
2039
- remote: z.string().min(1).default("origin"),
2040
- branch: z.string().min(1).optional()
2041
- }
2042
- },
2043
- async ({ task_id, remote, branch }) => {
2044
- const task = await getTask(task_id);
2045
- if (!task) return textResult({ error: "task_not_found", task_id });
2046
- const targetBranch = branch ?? task.landed_branch;
2047
- if (!task.landed_at || !task.landed_head || !targetBranch) {
2048
- return textResult({ error: "not_landed", task_id, reason: "land the worker first; this task has no landed head and branch to verify" });
2049
- }
2050
- try {
2051
- git(task.project_root, ["remote", "get-url", remote]);
2052
- git(task.project_root, ["fetch", "--no-tags", remote, `refs/heads/${targetBranch}`]);
2053
- const remoteHead = git(task.project_root, ["rev-parse", "FETCH_HEAD"]);
2054
- try {
2055
- git(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, remoteHead]);
2056
- } catch {
2057
- return textResult({
2058
- error: "not_pushed",
2059
- task_id,
2060
- remote,
2061
- branch: targetBranch,
2062
- landed_head: task.landed_head,
2063
- remote_head: remoteHead,
2064
- reason: "landed_head is not reachable from the fetched remote branch"
2065
- });
2066
- }
2067
- const now = new Date().toISOString();
2068
- const verified = { ...task, push_verified_at: now, push_remote: remote, push_branch: targetBranch, push_remote_head: remoteHead, updated_at: now };
2069
- await upsertTask(verified);
2070
- await updateWorkItemDelivery(task_id, "push_verified");
2071
- const event = await appendTaskEvent(task_id, {
2072
- type: "supervisor.push_verified",
2073
- remote,
2074
- branch: targetBranch,
2075
- landed_head: task.landed_head,
2076
- remote_head: remoteHead,
2077
- verified_at: now
2078
- }, { runId: runIdFor(task_id, task.run_count ?? 1), actor: "supervisor" });
2079
- const artifact = await recordJsonArtifact({
2080
- runId: runIdFor(task_id, task.run_count ?? 1),
2081
- type: "push_proof",
2082
- value: { remote, branch: targetBranch, landed_head: task.landed_head, remote_head: remoteHead, verified_at: now, event_id: event.id },
2083
- securityClass: "internal"
2084
- });
2085
- const workItem = await getWorkItemForTask(task_id);
2086
- if (workItem) {
2087
- await recordFact({
2088
- workItemId: workItem.id,
2089
- scopeType: "work_item",
2090
- scopeId: workItem.id,
2091
- key: "push_verified",
2092
- value: { remote, branch: targetBranch, landed_head: task.landed_head, remote_head: remoteHead },
2093
- state: "verified",
2094
- sourceEventId: event.id,
2095
- sourceArtifactId: artifact.id,
2096
- validForSha: task.landed_head,
2097
- watchedPaths: task.owned_paths ?? [],
2098
- verifiedBy: "supervisor.remote_readback"
2099
- });
2100
- await recordFact({
2101
- workItemId: workItem.id,
2102
- scopeType: "dependency",
2103
- scopeId: workItem.id,
2104
- key: "push_delivery_summary",
2105
- value: { task_id, landed_head: task.landed_head, remote, branch: targetBranch, remote_head: remoteHead },
2106
- state: "verified",
2107
- sourceEventId: event.id,
2108
- sourceArtifactId: artifact.id,
2109
- validForSha: task.landed_head,
2110
- watchedPaths: task.owned_paths ?? [],
2111
- verifiedBy: "supervisor.remote_readback"
2112
- });
2113
- }
2114
- const cleanupPlan = await createCleanupPlan({ taskIds: [task_id] });
2115
- await saveCleanupPlan(cleanupPlan);
2116
- return textResult({
2117
- task_id,
2118
- remote,
2119
- branch: targetBranch,
2120
- landed_head: task.landed_head,
2121
- remote_head: remoteHead,
2122
- artifact_id: artifact.id,
2123
- push_verified_at: now,
2124
- cleanup_plan: { id: cleanupPlan.id, summary: cleanupPlan.summary, expires_at: cleanupPlan.expires_at, next_step: "Review SAFE items, then call apply_cleanup with their item IDs; cleanup is never automatic." }
2125
- });
2126
- } catch (error) {
2127
- return textResult({ error: "push_verification_failed", task_id, remote, branch: targetBranch, reason: error.message.split("\n")[0] });
2128
- }
2129
- }
2130
- );
2131
-
2132
- server.registerTool(
2133
- "cleanup_plan",
2134
- {
2135
- title: "Plan safe worktree cleanup",
2136
- description: "Classify managed worktrees as safe, review or blocked. The plan is read-only, expires after 15 minutes, estimates reclaimable bytes and never deletes branches, task rows, events, JSONL logs or artifacts.",
2137
- inputSchema: {
2138
- task_ids: z.array(z.string().min(1)).max(200).optional(),
2139
- project_root: z.string().min(1).optional()
2140
- }
2141
- },
2142
- async ({ task_ids, project_root }) => {
2143
- try {
2144
- const plan = await createCleanupPlan({ taskIds: task_ids ?? null, projectRoot: project_root ?? null });
2145
- await saveCleanupPlan(plan);
2146
- return textResult({
2147
- plan_id: plan.id,
2148
- generated_at: plan.generated_at,
2149
- expires_at: plan.expires_at,
2150
- policy: plan.policy,
2151
- summary: plan.summary,
2152
- items: plan.items
2153
- });
2154
- } catch (error) {
2155
- return errorResult(error);
2156
- }
2157
- }
2158
- );
2159
-
2160
- server.registerTool(
2161
- "apply_cleanup",
2162
- {
2163
- title: "Apply a safe cleanup plan",
2164
- description: "Remove only selected SAFE worktrees from an unexpired cleanup plan after a second proof check. Uses git worktree remove and prune only; retains the branch, task row, event stream, JSONL log and artifacts.",
2165
- inputSchema: {
2166
- plan_id: z.string().uuid(),
2167
- item_ids: z.array(z.string().uuid()).min(1).max(200)
2168
- }
2169
- },
2170
- async ({ plan_id, item_ids }) => {
2171
- const plan = await getCleanupPlan(plan_id);
2172
- if (!plan) return textResult({ error: "cleanup_plan_not_found", plan_id });
2173
- if (Date.parse(plan.expires_at) <= Date.now()) return textResult({ error: "cleanup_plan_expired", plan_id, expires_at: plan.expires_at });
2174
- return textResult(await applyCleanupPlan({ plan, itemIds: item_ids, actor: "main_thread" }));
2175
- }
2176
- );
2177
-
2178
- server.registerTool(
2179
- "cleanup_history",
2180
- {
2181
- title: "Read cleanup history",
2182
- description: "Read cleanup plan decisions and applied worktree removals, including safe/review/blocked reasons. This is audit history, not a delete command.",
2183
- inputSchema: { task_id: z.string().min(1).optional(), limit: z.number().int().min(1).max(500).default(100) }
2184
- },
2185
- async ({ task_id, limit }) => textResult({ items: await readCleanupHistory(task_id ?? null, limit) })
2186
- );
2187
-
2188
- server.registerTool(
2189
- "cancel_codex_worker",
2190
- {
2191
- title: "Cancel Codex worker",
2192
- description:
2193
- "Terminate a running Codex worker. Uses the in-process handle when available, otherwise the pid recorded on disk so a different MCP session can still cancel it.",
2194
- inputSchema: {
2195
- task_id: z.string().min(1)
2196
- }
2197
- },
2198
- async ({ task_id }) => {
2199
- const now = new Date().toISOString();
2200
- const task = await getTask(task_id);
2201
- // The marker is persisted before the signal is sent so the process that
2202
- // owns the worker reports "cancelled" instead of "lost" when it exits.
2203
- if (task && ACTIVE_STATUSES.has(task.status)) {
2204
- await upsertTask({ ...task, cancel_requested_at: now, updated_at: now });
2205
- }
2206
- const result = await cancelCodexWorker(task_id);
2207
- // A cancel that stopped an acceptance run leaves the worker's own
2208
- // terminal status in place; the exit handler records the verdict.
2209
- if (result.cancelled && task && result.via !== "acceptance") {
2210
- await upsertTask({
2211
- ...task,
2212
- status: "cancelled",
2213
- phase: null,
2214
- cancel_requested_at: now,
2215
- updated_at: now,
2216
- completed_at: task.completed_at ?? now
2217
- });
2218
- }
2219
- return textResult(result);
2220
- }
2221
- );
2222
-
2223
- const transport = new StdioServerTransport();
2224
- await server.connect(transport);
2
+ // Stable entry point. Client registrations store this absolute path, so it stays
3
+ // here; the server itself lives in interface/mcp.
4
+ import "./interface/mcp/server.js";