codex-supervisor-mcp 0.14.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.en.md +34 -45
  2. package/README.md +34 -45
  3. package/package.json +1 -1
  4. package/skills/codex-supervisor/SKILL.md +86 -90
  5. package/src/app/acceptance.js +5 -5
  6. package/src/app/auto-cleanup.js +6 -5
  7. package/src/app/cleanup-facts.js +7 -4
  8. package/src/app/cleanup-plan.js +3 -2
  9. package/src/app/context-compiler.js +2 -1
  10. package/src/app/dispatch.js +17 -15
  11. package/src/app/followup.js +5 -4
  12. package/src/app/land-chain.js +5 -4
  13. package/src/app/landing.js +8 -8
  14. package/src/app/ownership.js +1 -1
  15. package/src/app/rebase.js +1 -1
  16. package/src/app/restore-worktree.js +2 -1
  17. package/src/app/resume.js +6 -5
  18. package/src/app/worktree-setup.js +15 -14
  19. package/src/domain/acceptance-spec.js +1 -1
  20. package/src/domain/failure-class.js +2 -2
  21. package/src/domain/prompt.js +7 -7
  22. package/src/domain/status.js +9 -0
  23. package/src/domain/thread-health.js +2 -2
  24. package/src/domain/worker-branch.js +6 -0
  25. package/src/domain/worker-changes.js +3 -3
  26. package/src/infra/cleanup-hint.js +1 -1
  27. package/src/infra/external-output.js +2 -2
  28. package/src/infra/sandbox-roots.js +1 -1
  29. package/src/infra/store/events.js +2 -1
  30. package/src/infra/store/reconcile.js +4 -3
  31. package/src/infra/store/tasks.js +1 -1
  32. package/src/infra/update/auto-update-worker.js +3 -3
  33. package/src/infra/update/auto-update.js +4 -4
  34. package/src/infra/update/update-check.js +3 -3
  35. package/src/infra/workspace-kind.js +8 -8
  36. package/src/infra/worktree.js +4 -3
  37. package/src/interface/bin/acceptance-cli.js +4 -4
  38. package/src/interface/bin/monitor.jsx +6 -6
  39. package/src/interface/bin/setup.js +3 -3
  40. package/src/interface/bin/stage.js +2 -2
  41. package/src/interface/mcp/{tools → handlers}/delivery.js +30 -62
  42. package/src/interface/mcp/handlers/dispatch.js +233 -0
  43. package/src/interface/mcp/{tools → handlers}/facts.js +30 -65
  44. package/src/interface/mcp/handlers/overview.js +103 -0
  45. package/src/interface/mcp/{tools → handlers}/results.js +31 -60
  46. package/src/interface/mcp/{tools → handlers}/review.js +16 -36
  47. package/src/interface/mcp/{tools → handlers}/wait.js +8 -14
  48. package/src/interface/mcp/server.js +18 -51
  49. package/src/interface/mcp/tools/deliver.js +48 -0
  50. package/src/interface/mcp/tools/dispatch.js +78 -257
  51. package/src/interface/mcp/tools/optional.js +57 -0
  52. package/src/interface/mcp/tools/read.js +115 -0
  53. package/src/interface/mcp/tools/run.js +57 -0
  54. package/src/interface/mcp/tools/shapes.js +66 -0
  55. package/src/interface/mcp/tools/track.js +84 -0
  56. package/src/interface/mcp/views/task.js +8 -7
  57. package/src/interface/web/views.js +2 -1
  58. package/src/run-host/launch.js +7 -7
  59. package/src/runners/codex/tool-guard.js +6 -6
  60. package/src/domain/overview-delta.js +0 -77
  61. package/src/interface/mcp/tools/overview.js +0 -202
  62. package/src/interface/mcp/tools/poll.js +0 -58
@@ -0,0 +1,84 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { sweepCleanup } from "../../../app/auto-cleanup.js";
4
+ import { recoverEligibleRuns } from "../../../app/resume.js";
5
+ import { ACTIVE_STATUSES, TASK_STATUSES } from "../../../domain/status.js";
6
+ import { collectWorkerChanges } from "../../../domain/worker-changes.js";
7
+ import { cleanupHint } from "../../../infra/cleanup-hint.js";
8
+ import { reconcileDetachedActiveTasks } from "../../../infra/store/reconcile.js";
9
+ import { readObserverCursor, readTasks, writeObserverCursor } from "../../../infra/store/tasks.js";
10
+ import { waitCodexWorkersOp } from "../handlers/wait.js";
11
+ import { packageVersion } from "../meta.js";
12
+ import { updateField, updateState } from "../update-state.js";
13
+ import { buildOverview } from "../views/overview.js";
14
+ import { defineTool, run } from "./run.js";
15
+
16
+ // Polls from one process run one at a time: recovery and cleanup must not overlap themselves.
17
+ let pollChain = Promise.resolve();
18
+
19
+ // With a cursor this is the loop tick: it reports what changed and does the
20
+ // housekeeping a loop is for (one recovery of a dead first run, cleanup).
21
+ // Without one it is a plain read of the table and starts nothing.
22
+ async function pollOnce({ cursor, status, limit }) {
23
+ await reconcileDetachedActiveTasks();
24
+ if (cursor) {
25
+ const recoveries = await recoverEligibleRuns();
26
+ const cleaned = await sweepCleanup();
27
+ const cleanup = await cleanupHint();
28
+ const tasks = await readTasks();
29
+ const changes = collectWorkerChanges(tasks, await readObserverCursor(cursor));
30
+ await writeObserverCursor(cursor, changes.cursor);
31
+ return {
32
+ generated_at: new Date().toISOString(),
33
+ quiet: changes.quiet && recoveries.length === 0 && cleaned.length === 0,
34
+ active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
35
+ transitions: changes.transitions,
36
+ attention: changes.attention,
37
+ recoveries,
38
+ ...(cleaned.length ? { cleaned } : {}),
39
+ ...(cleanup ? { cleanup } : {}),
40
+ next_cursor: cursor
41
+ };
42
+ }
43
+ const tasks = await readTasks();
44
+ // The cursor handed out here makes the next poll report only what changes from now on.
45
+ const token = `poll-${randomUUID().slice(0, 12)}`;
46
+ await writeObserverCursor(token, collectWorkerChanges(tasks, {}).cursor);
47
+ const shown = (status ? tasks.filter((task) => task.status === status) : tasks).slice(-limit);
48
+ const update = updateField() ?? { update_available: false, installed_version: packageVersion, checked: updateState?.source ?? "pending" };
49
+ return buildOverview(shown, { version: packageVersion, update, next_cursor: token });
50
+ }
51
+
52
+ export const pollWorkersTool = defineTool("poll_workers", {
53
+ title: "See what the workers are doing",
54
+ description: "The main thread's read. Without cursor: a compact table of every worker and a next_cursor. With that cursor: only what happened since, as transitions (finished, failed, needs attention) with the next step; quiet when nothing did. A poll with a cursor also recovers a dead first run once and removes safe worktrees (listed under cleaned). Call it from a loop.",
55
+ inputSchema: {
56
+ cursor: z.string().optional().describe("next_cursor from the previous poll"),
57
+ status: z.enum(TASK_STATUSES).optional().describe("Filter the full table"),
58
+ limit: z.number().int().min(1).max(200).default(50).describe("Rows in the full table, newest last")
59
+ }
60
+ }, (args) => {
61
+ const poll = pollChain.then(() => pollOnce(args));
62
+ pollChain = poll.catch(() => {});
63
+ return poll;
64
+ });
65
+
66
+ export const waitWorkersTool = defineTool("wait_workers", {
67
+ title: "Wait for workers to finish",
68
+ description: "Block until the given workers settle (process exited and acceptance run), then return one row each. A call waits 60 seconds at most and says so in timed_out; call again with the same ids. allow_long_wait lifts the cap only when the client's own tool timeout is known to be longer.",
69
+ inputSchema: {
70
+ task_ids: z.array(z.string()).min(1),
71
+ mode: z.enum(["any", "all"]).default("all"),
72
+ timeout_ms: z.number().int().min(1000).max(21600000).optional(),
73
+ allow_long_wait: z.boolean().default(false),
74
+ emit_progress: z.boolean().default(false).describe("Send progress notifications while waiting"),
75
+ compact: z.boolean().optional().describe("One short row per worker; the default unless include_events"),
76
+ include_events: z.boolean().default(false),
77
+ event_limit: z.number().int().min(1).max(50).default(10),
78
+ poll_ms: z.number().int().min(250).max(10000).optional()
79
+ }
80
+ }, (args, extra) => run(waitCodexWorkersOp, {
81
+ task_ids: args.task_ids, mode: args.mode, timeoutMs: args.timeout_ms ?? 60000, allowLongWait: args.allow_long_wait, emitProgress: args.emit_progress,
82
+ compact: args.compact, includeEvents: args.include_events, eventLimit: args.event_limit,
83
+ pollMs: args.poll_ms
84
+ }, extra));
@@ -1,3 +1,4 @@
1
+ import { branchOf } from "../../../domain/worker-branch.js";
1
2
  import { acceptanceVerdict } from "../../../app/acceptance.js";
2
3
  import { classifyFailure } from "../../../domain/failure-class.js";
3
4
  import { ACTIVE_STATUSES, isGoalNeedingAttention } from "../../../domain/status.js";
@@ -11,14 +12,14 @@ import { clip } from "../result.js";
11
12
  // writes a whole file. Returning it whole put tens of thousands of characters
12
13
  // into every wait response, which then blew past the client's MCP output cap
13
14
  // and came back a second time as a notification. The full command stays in
14
- // current_command / commands and is readable through get_codex_worker_events.
15
+ // current_command / commands and is readable through get_worker (include events).
15
16
  export const ACTION_PREVIEW_CHARS = 300;
16
17
  const COMMAND_PREVIEW_CHARS = 300;
17
18
  const COMMAND_TAIL = 20;
18
19
  const PROMPT_PREVIEW_CHARS = 300;
19
20
  // The single-worker status read is the drill-in for one worker, so its copy of
20
21
  // the last message stays much larger than the overview's 400. The full report
21
- // is still get_worker_result's job.
22
+ // is still get_worker (include result)'s job.
22
23
  const STATUS_MESSAGE_CHARS = 4000;
23
24
 
24
25
  // Codex emits nothing while a command runs and nothing while the model
@@ -70,7 +71,7 @@ export function compactLiveness(task) {
70
71
  };
71
72
  }
72
73
 
73
- // The acceptance verdict as get_worker_result reports it, with the one
74
+ // The acceptance verdict as get_worker (include result) reports it, with the one
74
75
  // contradiction a tool can see spelled out: checks passed, worker says
75
76
  // otherwise (the "it was never built" case, where it was).
76
77
  export function acceptanceView(task, behind) {
@@ -99,9 +100,9 @@ export function acceptanceView(task, behind) {
99
100
  const verification = summarizeVerification(task);
100
101
  const workerSaysNo = task.status === "failed" || isGoalNeedingAttention(task.goal_status) || verification.last_command_failed;
101
102
  if (workerSaysNo) view.next_step = "the checks passed but the worker reports otherwise; trust the checks and read the diff";
102
- 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";
103
+ else if (view.stale) view.next_step = "the checks passed on the old base and the project has moved since; resume with rebase_onto to re-run them on current code before landing";
103
104
  } else if (view.status === "running") {
104
- view.next_step = "acceptance is still running in the supervisor; wait_codex_workers returns when it is done";
105
+ view.next_step = "acceptance is still running in the supervisor; wait_workers returns when it is done";
105
106
  } else if (view.status === "interrupted") {
106
107
  view.next_step = "the supervisor exited while running acceptance; resume the worker (or cancel and redispatch) to run it again";
107
108
  } else if (view.status === "cancelled") {
@@ -188,7 +189,7 @@ export function statusView(task, { includePrompt, promptMaxChars }) {
188
189
  // events - back to the caller on every call. Dispatching eleven workers made
189
190
  // the main thread pay for its own instructions eleven times, and pushed the
190
191
  // result into the client's MCP output cap. Read the rest per worker with
191
- // get_worker_summary / get_worker_result when you actually need it.
192
+ // get_worker / get_worker (include result) when you actually need it.
192
193
  export function receipt(task) {
193
194
  return {
194
195
  id: task.id,
@@ -200,7 +201,7 @@ export function receipt(task) {
200
201
  project_root: task.project_root,
201
202
  workspace_kind: task.workspace_kind ?? "legacy",
202
203
  worktree_path: task.worktree_path,
203
- branch: task.worktree_path ? `codex/${task.id}` : null,
204
+ branch: task.worktree_path ? branchOf(task) : null,
204
205
  base_commit: task.base_commit ?? null,
205
206
  sandbox: task.sandbox,
206
207
  model: task.model,
@@ -1,4 +1,5 @@
1
1
  // What the board shows: session and worker rows built from the store, read-only.
2
+ import { branchOf } from "../../domain/worker-branch.js";
2
3
  import { ACTIVE_STATUSES } from "../../domain/status.js";
3
4
  import { supervisorRoot } from "../../infra/paths.js";
4
5
  import { listTaskEventKinds, readAgentMessages, readTaskEvents } from "../../infra/store/events.js";
@@ -40,7 +41,7 @@ function workerRow(task) {
40
41
  sandbox: task.sandbox,
41
42
  project_root: task.project_root,
42
43
  worktree_path: task.worktree_path ?? null,
43
- branch: task.worktree_path ? `codex/${task.id}` : null,
44
+ branch: task.worktree_path ? branchOf(task) : null,
44
45
  base_commit: task.base_commit ?? null,
45
46
  owned_paths: task.owned_paths ?? [],
46
47
  depends_on: task.depends_on ?? [],
@@ -23,8 +23,8 @@ function guardPolicyFor(record, externalBefore, outputSchema) {
23
23
  // This CLI writes only data/stages/<this task>.json. It is part of the
24
24
  // runtime contract, not an ad-hoc command the model must declare. The
25
25
  // task id comes from the injected environment; stage.js has no override.
26
- 'node "$CODEX_SUPERVISOR_STAGE_CLI"*',
27
- 'node "$CODEX_SUPERVISOR_ACCEPTANCE_CLI"*'
26
+ 'node "$AGENT_SUPERVISOR_STAGE_CLI"*',
27
+ 'node "$AGENT_SUPERVISOR_ACCEPTANCE_CLI"*'
28
28
  ] };
29
29
  }
30
30
 
@@ -54,10 +54,10 @@ export function buildLaunch({ record, args, prompt, outputSchema, externalBefore
54
54
  const configArgs = configArgsFor(record, externalBefore, outputSchema);
55
55
  // Insert before the prompt/session positional arguments for exec/resume.
56
56
  const guardedArgs = [...args.slice(0, -1), ...configArgs, args.at(-1)];
57
- const env = () => withWorkerToolPath({ ...process.env, NO_COLOR: "1", CODEX_SUPERVISOR_TASK_ID: record.id,
58
- CODEX_SUPERVISOR_BASE_COMMIT: record.base_commit ?? "",
59
- CODEX_SUPERVISOR_STAGE_CLI: stageCli,
60
- CODEX_SUPERVISOR_ACCEPTANCE_CLI: acceptanceCli,
61
- CODEX_SUPERVISOR_RUN: String((record.run_count ?? 0) + 1), CODEX_SUPERVISOR_GUARD_POLICY: JSON.stringify(guardPolicy) });
57
+ const env = () => withWorkerToolPath({ ...process.env, NO_COLOR: "1", AGENT_SUPERVISOR_TASK_ID: record.id,
58
+ AGENT_SUPERVISOR_BASE_COMMIT: record.base_commit ?? "",
59
+ AGENT_SUPERVISOR_STAGE_CLI: stageCli,
60
+ AGENT_SUPERVISOR_ACCEPTANCE_CLI: acceptanceCli,
61
+ AGENT_SUPERVISOR_RUN: String((record.run_count ?? 0) + 1), AGENT_SUPERVISOR_GUARD_POLICY: JSON.stringify(guardPolicy) });
62
62
  return { guardedArgs, prompt: `${buildGuardPreamble(guardPolicy)}\n\n${prompt}`, env };
63
63
  }
@@ -54,13 +54,13 @@ function judgePatch(paths, { event, policy, readOnly, deny }) {
54
54
  if (readOnly) return deny("read-only worker: the sandbox denies every write, including the temp directory; report the change instead of editing");
55
55
  if (!paths.length) return deny("patch has no recognized file paths");
56
56
  try {
57
- // With no ownedPaths the worker may still keep scratch notes, but only
57
+ // With no owned_paths the worker may still keep scratch notes, but only
58
58
  // inside its own worktree, which is never landed.
59
59
  const owners = policy.ownedPaths.length ? policy.ownedPaths.map(canonical) : [canonical(policy.worktree ?? policy.cwd)];
60
60
  for (const path of paths) {
61
61
  const target = canonical(resolve(event.cwd ?? policy.cwd, path));
62
62
  if (!owners.some((owner) => inside(target, owner))) return deny(policy.ownedPaths.length
63
- ? "outside ownedPaths: " + path
63
+ ? "outside owned_paths: " + path
64
64
  : "outside this worker's own worktree: " + path);
65
65
  }
66
66
  } catch (error) { return deny("cannot prove patch ownership: " + error.message); }
@@ -105,9 +105,9 @@ export function evaluateToolUse(event, policy) {
105
105
  const deny = (reason) => ({ allow: false, reason });
106
106
  if (!policy || !Array.isArray(policy.ownedPaths) || !policy.cwd) return deny("missing supervisor guard policy");
107
107
  // Who needs the shell allowlist? It exists to stop a writing worker from
108
- // going around ownedPaths. Two shapes have no landable write boundary left:
108
+ // going around owned_paths. Two shapes have no landable write boundary left:
109
109
  // the read-only sandbox denies every file write, temp directory included, and
110
- // a workspace-write worker with no ownedPaths can only write its own throwaway
110
+ // a workspace-write worker with no owned_paths can only write its own throwaway
111
111
  // worktree, its temp dir and the OS cache dir while land refuses everything it
112
112
  // produced. Both are what a research worker looks like, and the allowlist would
113
113
  // only stop it from running curl, gh or python.
@@ -146,7 +146,7 @@ export function evaluateToolUse(event, policy) {
146
146
  const shellPatch = patchFromHeredoc(command);
147
147
  if (shellPatch) return judgePatch(patchPaths(shellPatch), { event, policy, readOnly, deny });
148
148
  // Reading is never exclusive: no branch below looks at another worker's
149
- // ownedPaths, so two workers may read the same file at the same time.
149
+ // owned_paths, so two workers may read the same file at the same time.
150
150
  if (landsNothing) return { allow: true, reason: readOnly
151
151
  ? "read-only sandbox: every write is denied by the OS, so shell commands need no allowlist"
152
152
  : "no landable path: writes stay in this worker's own worktree" };
@@ -176,7 +176,7 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
176
176
  let input = "";
177
177
  for await (const chunk of process.stdin) input += chunk;
178
178
  let decision;
179
- try { decision = evaluateToolUse(JSON.parse(input), JSON.parse(process.env.CODEX_SUPERVISOR_GUARD_POLICY ?? "null")); }
179
+ try { decision = evaluateToolUse(JSON.parse(input), JSON.parse(process.env.AGENT_SUPERVISOR_GUARD_POLICY ?? "null")); }
180
180
  catch (error) { decision = { allow: false, reason: "invalid supervisor guard input: " + error.message }; }
181
181
  process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse",
182
182
  permissionDecision: decision.allow ? "allow" : "deny", permissionDecisionReason: decision.reason } }) + "\n");
@@ -1,77 +0,0 @@
1
- import { ACTIVE_STATUSES, isGoalNeedingAttention } from "./status.js";
2
- import { classifyFailure } from "./failure-class.js";
3
- import { threadHealth } from "./thread-health.js";
4
-
5
- function readyToLand(task) {
6
- return task.status === "completed" && task.exit_code === 0 && (!task.acceptance_results || task.acceptance_results.passed === true) && !task.landed_at;
7
- }
8
-
9
- function readyToClean(task, readyToCleanTaskIds = null) {
10
- if (readyToCleanTaskIds) return readyToCleanTaskIds.has(task.id);
11
- return task.delivery_state === "cleanup_eligible";
12
- }
13
-
14
- function attentionReason(task) {
15
- if (task.attention_reason) return String(task.attention_reason).slice(0, 180);
16
- if (task.acceptance_results?.passed === false) return "acceptance_failed";
17
- if (isGoalNeedingAttention(task.goal_status)) return `goal_${task.goal_status}`;
18
- return null;
19
- }
20
-
21
- function nextAction(task, { attention, readyToLand, readyToClean }) {
22
- if (attention) return "inspect the worker evidence and resolve the recorded blocker";
23
- if (task.delivery_state === "cleanup_eligible" && !readyToClean) return "rerun cleanup_plan; the previous cleanup proof is no longer current";
24
- if (readyToLand) return "review the diff and acceptance, then land the worker";
25
- if (readyToClean) return "nothing to do: the worktree is removed on a later poll, and its branch is kept";
26
- if (task.status === "completed" && !task.landed_at) return "review the worker result and decide whether to land it";
27
- return null;
28
- }
29
-
30
- export function buildOverviewDelta(tasks, cursor = {}, { readyToCleanTaskIds = null } = {}) {
31
- const active = tasks.filter((task) => ACTIVE_STATUSES.has(task.status));
32
- const attention = tasks.filter((task) => isGoalNeedingAttention(task.goal_status) || task.attention_reason || task.acceptance_results?.passed === false);
33
- const land = tasks.filter(readyToLand);
34
- const clean = tasks.filter((task) => readyToClean(task, readyToCleanTaskIds));
35
- const nextCursor = {};
36
- const changes = [];
37
- for (const task of tasks) {
38
- const isAttention = attention.some((item) => item.id === task.id);
39
- const isReadyToLand = land.some((item) => item.id === task.id);
40
- const isReadyToClean = clean.some((item) => item.id === task.id);
41
- const reason = attentionReason(task);
42
- const failure = classifyFailure(task);
43
- const health = threadHealth(task);
44
- const fingerprint = JSON.stringify([
45
- task.run_count ?? 0, task.status, task.exit_code ?? null, task.attention_reason ?? null, task.landed_head ?? null,
46
- task.push_verified_at ?? null, task.delivery_state ?? null, isReadyToClean, reason, task.goal_tokens_used ?? null,
47
- health.state, task.updated_at
48
- ]);
49
- nextCursor[task.id] = fingerprint;
50
- if (cursor[task.id] !== fingerprint) {
51
- changes.push({
52
- id: task.id,
53
- title: task.title ?? task.id,
54
- status: task.status,
55
- delivery_state: task.delivery_state ?? "draft",
56
- attention: isAttention,
57
- attention_reason: reason,
58
- failure_source: failure?.source ?? null,
59
- failure_code: failure?.code ?? null,
60
- handoff_recommended: health.state === "handoff_recommended",
61
- ready_to_land: isReadyToLand,
62
- ready_to_clean: isReadyToClean,
63
- next_action: nextAction(task, { attention: isAttention, readyToLand: isReadyToLand, readyToClean: isReadyToClean }),
64
- updated_at: task.updated_at
65
- });
66
- }
67
- }
68
- return {
69
- generated_at: new Date().toISOString(),
70
- active: active.length,
71
- needs_attention: attention.length,
72
- ready_to_land: land.length,
73
- ready_to_clean: clean.length,
74
- changes,
75
- cursor: nextCursor
76
- };
77
- }
@@ -1,202 +0,0 @@
1
- import { buildHostGoalSync } from "../../../domain/prompt.js";
2
- import { ACTIVE_STATUSES, TASK_STATUSES } from "../../../domain/status.js";
3
- import { truncateEventStrings } from "../../../domain/truncate.js";
4
- import { getSession, upsertSession } from "../../../infra/store/sessions.js";
5
- import { getTask, readTasks, readTasksBySession, searchTasks } from "../../../infra/store/tasks.js";
6
- import { listTaskEventKinds, readTaskEvents } from "../../../infra/store/events.js";
7
- import { reconcileDetachedActiveTasks } from "../../../infra/store/reconcile.js";
8
- import { packageVersion } from "../meta.js";
9
- import { errorResult, textResult } from "../result.js";
10
- import { acceptanceCheck } from "../schemas.js";
11
- import { autoUpdateState, refreshUpdateState, updateField, updateState } from "../update-state.js";
12
- import { buildOverview, workRow } from "../views/overview.js";
13
- import { statusView, summarizeTask } from "../views/task.js";
14
- import { z } from "zod";
15
-
16
- export const listCodexWorkersTool = [
17
- "list_codex_workers",
18
- {
19
- title: "List Codex workers",
20
- description: "List tracked Codex workers. Defaults to active workers only.",
21
- inputSchema: {
22
- status: z.enum(TASK_STATUSES).optional(),
23
- includeHistory: z.boolean().default(false),
24
- includeDetails: z.boolean().default(false)
25
- }
26
- },
27
- async ({ status, includeHistory, includeDetails } = {}) => {
28
- await reconcileDetachedActiveTasks();
29
- const tasks = await readTasks();
30
- const filtered = status
31
- ? tasks.filter((task) => task.status === status)
32
- : includeHistory
33
- ? tasks
34
- : tasks.filter((task) => ACTIVE_STATUSES.has(task.status));
35
- return textResult(includeDetails ? filtered : filtered.map(summarizeTask));
36
- }
37
- ];
38
-
39
- export const getOrchestrationOverviewTool = [
40
- "get_orchestration_overview",
41
- {
42
- title: "Get orchestration overview",
43
- description:
44
- "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.",
45
- inputSchema: {
46
- status: z.enum(TASK_STATUSES).optional(),
47
- limit: z.number().int().min(1).max(200).default(50)
48
- }
49
- },
50
- async ({ status, limit } = {}) => {
51
- await reconcileDetachedActiveTasks();
52
- const tasks = await readTasks();
53
- const filtered = (status ? tasks.filter((task) => task.status === status) : tasks).slice(-limit);
54
- // version and update ride inside the budgeted payload so approx_tokens
55
- // still reports the real cost of the whole reply.
56
- return textResult(
57
- buildOverview(filtered, {
58
- version: packageVersion,
59
- update: updateField() ?? { update_available: false, installed_version: packageVersion, checked: updateState?.source ?? "pending" }
60
- })
61
- );
62
- }
63
- ];
64
-
65
- export const getSessionWorksTool = [
66
- "get_session_works",
67
- {
68
- title: "Get session works",
69
- description:
70
- "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.",
71
- inputSchema: {
72
- session_id: z.string().min(1)
73
- }
74
- },
75
- async ({ session_id }) => {
76
- const tasks = await readTasksBySession(session_id);
77
- const meta = await getSession(session_id);
78
- return textResult({
79
- session_id,
80
- title: meta?.title ?? null,
81
- note: meta?.note ?? null,
82
- objective: meta?.objective ?? null,
83
- default_acceptance: meta?.default_acceptance ?? [],
84
- approval_state: meta?.approval_state ?? "approved",
85
- policy_revision: meta?.policy_revision ?? 0,
86
- count: tasks.length,
87
- active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
88
- works: tasks.map(workRow)
89
- });
90
- }
91
- ];
92
-
93
- export const checkForUpdateTool = [
94
- "check_for_update",
95
- {
96
- title: "Check for update",
97
- description:
98
- "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.",
99
- inputSchema: {
100
- force: z.boolean().default(true)
101
- }
102
- },
103
- async ({ force }) => {
104
- const result = await refreshUpdateState({ force });
105
- if (!result) return textResult({ error: "update_check_failed" });
106
- return textResult({ ...result, auto_update: autoUpdateState });
107
- }
108
- ];
109
-
110
- export const describeSessionTool = [
111
- "describe_session",
112
- {
113
- title: "Describe session",
114
- description:
115
- "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.",
116
- inputSchema: {
117
- session_id: z.string().min(1),
118
- title: z.string().min(1).max(120).optional(),
119
- note: z.string().min(1).max(2000).optional(),
120
- objective: z.string().min(1).max(5000).optional(),
121
- default_acceptance: z.array(acceptanceCheck).max(10).optional(),
122
- approval_state: z.enum(["approved", "waiting_user"]).optional(),
123
- expected_revision: z.number().int().nonnegative().optional()
124
- }
125
- },
126
- async ({ session_id, title, note, objective, default_acceptance, approval_state, expected_revision }) => {
127
- try {
128
- const row = await upsertSession({
129
- id: session_id, title: title ?? null, note: note ?? null, objective,
130
- defaultAcceptance: default_acceptance, approvalState: approval_state, expectedRevision: expected_revision
131
- });
132
- return textResult({ ...row, session_id, host_goal_sync: buildHostGoalSync(row) });
133
- } catch (error) { return errorResult(error); }
134
- }
135
- ];
136
-
137
- export const searchWorksTool = [
138
- "search_works",
139
- {
140
- title: "Search works",
141
- description:
142
- "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.",
143
- inputSchema: {
144
- query: z.string().min(1),
145
- limit: z.number().int().positive().max(100).default(20)
146
- }
147
- },
148
- async ({ query, limit }) => {
149
- const tasks = await searchTasks(query, limit);
150
- return textResult({
151
- query,
152
- count: tasks.length,
153
- works: tasks.map(workRow)
154
- });
155
- }
156
- ];
157
-
158
- export const getCodexWorkerStatusTool = [
159
- "get_codex_worker_status",
160
- {
161
- title: "Get Codex worker status",
162
- description:
163
- "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.",
164
- inputSchema: {
165
- task_id: z.string().min(1),
166
- includePrompt: z.boolean().default(false),
167
- promptMaxChars: z.number().int().min(0).max(1000000).default(5000)
168
- }
169
- },
170
- async ({ task_id, includePrompt, promptMaxChars }) => {
171
- const task = await getTask(task_id);
172
- if (!task) return textResult({ error: "task_not_found", task_id });
173
- return textResult(statusView(task, { includePrompt, promptMaxChars }));
174
- }
175
- ];
176
-
177
- export const getCodexWorkerEventsTool = [
178
- "get_codex_worker_events",
179
- {
180
- title: "Get Codex worker events",
181
- description:
182
- "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.",
183
- inputSchema: {
184
- task_id: z.string().min(1),
185
- limit: z.number().int().min(1).max(1000).default(100),
186
- maxChars: z.number().int().min(0).max(1000000).optional(),
187
- kinds: z.array(z.string().min(1)).optional()
188
- }
189
- },
190
- async ({ task_id, limit, maxChars, kinds }) => {
191
- const task = await getTask(task_id);
192
- if (!task) return textResult({ error: "task_not_found", task_id });
193
- const events = await readTaskEvents(task_id, limit, kinds ?? null);
194
- const trimmed = maxChars === undefined ? events : events.map((event) => truncateEventStrings(event, maxChars));
195
- return textResult({
196
- task_id,
197
- count: trimmed.length,
198
- available_kinds: await listTaskEventKinds(task_id),
199
- events: trimmed
200
- });
201
- }
202
- ];
@@ -1,58 +0,0 @@
1
- import { sweepCleanup } from "../../../app/auto-cleanup.js";
2
- import { recoverEligibleRuns } from "../../../app/resume.js";
3
- import { buildOverviewDelta } from "../../../domain/overview-delta.js";
4
- import { collectWorkerChanges } from "../../../domain/worker-changes.js";
5
- import { cleanupHint } from "../../../infra/cleanup-hint.js";
6
- import { readObserverCursor, readTasks, writeObserverCursor } from "../../../infra/store/tasks.js";
7
- import { reconcileDetachedActiveTasks } from "../../../infra/store/reconcile.js";
8
- import { textResult } from "../result.js";
9
- import { randomUUID } from "node:crypto";
10
- import { z } from "zod";
11
-
12
- const observerId = process.env.CODEX_SUPERVISOR_OBSERVER_ID?.trim() || `mcp-${randomUUID()}`;
13
- const deltaObserverId = process.env.CODEX_SUPERVISOR_DELTA_OBSERVER_ID?.trim() || `${observerId}:delta`;
14
- let observerRead = Promise.resolve();
15
- let deltaRead = Promise.resolve();
16
- export const overviewDeltaTool = [
17
- "overview_delta",
18
- {
19
- title: "Get orchestration delta",
20
- description: "Return a small cursor-based orchestration view: active, needs_attention, ready_to_land, ready_to_clean and changed task summaries, plus `cleaned` when safe worktrees were removed on this call. It never returns full history, prompts, diffs, events or worker capsules.",
21
- inputSchema: { cursor: z.record(z.string(), z.string()).optional() }
22
- },
23
- async ({ cursor }) => {
24
- const read = deltaRead.then(async () => {
25
- await reconcileDetachedActiveTasks();
26
- const tasks = await readTasks();
27
- const previous = cursor ?? await readObserverCursor(deltaObserverId);
28
- const cleaned = await sweepCleanup();
29
- const result = buildOverviewDelta(cleaned.length ? await readTasks() : tasks, previous);
30
- await writeObserverCursor(deltaObserverId, result.cursor);
31
- const { cursor: nextCursor, ...reply } = result;
32
- return textResult({ ...reply, next_cursor: nextCursor, ...(cleaned.length ? { cleaned } : {}) });
33
- });
34
- deltaRead = read.catch(() => {});
35
- return read;
36
- }
37
- ];
38
- export const checkWorkersTool = ["check_workers", {
39
- title: "Check changed workers",
40
- 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. Safe worktrees are removed along the way and listed under `cleaned`. 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.",
41
- inputSchema: {}
42
- }, async () => {
43
- const read = observerRead.then(async () => {
44
- await reconcileDetachedActiveTasks();
45
- const recoveries = await recoverEligibleRuns();
46
- const result = collectWorkerChanges(await readTasks(), await readObserverCursor(observerId));
47
- await writeObserverCursor(observerId, result.cursor);
48
- const { cursor, ...reply } = result;
49
- // The cleanup hint rides along without touching quiet: it is a standing fact
50
- // about the store, not a new worker event.
51
- const cleaned = await sweepCleanup();
52
- const cleanup = await cleanupHint();
53
- const extras = { ...(cleaned.length ? { cleaned } : {}), ...(cleanup ? { cleanup } : {}) };
54
- return textResult({ ...reply, quiet: reply.quiet && recoveries.length === 0, recoveries, ...extras });
55
- });
56
- observerRead = read.catch(() => {});
57
- return read;
58
- }];