codex-supervisor-mcp 0.13.5 → 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 (101) hide show
  1. package/package.json +18 -63
  2. package/src/{acceptance.js → app/acceptance.js} +54 -68
  3. package/src/app/cancel.js +60 -0
  4. package/src/{cleanup-plan.js → app/cleanup-plan.js} +11 -12
  5. package/src/app/compose.js +7 -0
  6. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  7. package/src/app/dispatch.js +396 -0
  8. package/src/app/followup.js +98 -0
  9. package/src/app/land-chain.js +124 -0
  10. package/src/app/landing.js +357 -0
  11. package/src/app/ownership.js +57 -0
  12. package/src/app/rebase.js +216 -0
  13. package/src/app/resume.js +164 -0
  14. package/src/app/run-state.js +26 -0
  15. package/src/app/settled.js +28 -0
  16. package/src/{side-chat.js → app/side-chat.js} +79 -265
  17. package/src/app/sse.js +20 -0
  18. package/src/app/start-run.js +77 -0
  19. package/src/app/verify-push.js +119 -0
  20. package/src/app/worktree-setup.js +176 -0
  21. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  22. package/src/domain/acceptance-spec.js +30 -0
  23. package/src/domain/command-outcome.js +6 -0
  24. package/src/{overview-delta.js → domain/overview-delta.js} +5 -1
  25. package/src/domain/side-turn-view.js +73 -0
  26. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  27. package/src/infra/git.js +30 -0
  28. package/src/infra/process.js +59 -0
  29. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  30. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  31. package/src/infra/store/db.js +265 -0
  32. package/src/infra/store/events.js +146 -0
  33. package/src/infra/store/facts.js +338 -0
  34. package/src/infra/store/reconcile.js +172 -0
  35. package/src/infra/store/records.js +160 -0
  36. package/src/infra/store/runner-readers.js +16 -0
  37. package/src/infra/store/schema.js +306 -0
  38. package/src/infra/store/sessions.js +138 -0
  39. package/src/infra/store/tasks.js +307 -0
  40. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  41. package/src/{auto-update.js → infra/update/auto-update.js} +3 -3
  42. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  43. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  44. package/src/{worktree.js → infra/worktree.js} +56 -41
  45. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  46. package/src/{cleanup.js → interface/bin/cleanup.js} +3 -2
  47. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  48. package/src/{setup.js → interface/bin/setup.js} +7 -6
  49. package/src/{stage.js → interface/bin/stage.js} +1 -1
  50. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  51. package/src/interface/mcp/meta.js +7 -0
  52. package/src/interface/mcp/result.js +34 -0
  53. package/src/interface/mcp/schemas.js +24 -0
  54. package/src/interface/mcp/server.js +94 -0
  55. package/src/interface/mcp/tools/delivery.js +197 -0
  56. package/src/interface/mcp/tools/dispatch.js +267 -0
  57. package/src/interface/mcp/tools/facts.js +239 -0
  58. package/src/interface/mcp/tools/overview.js +202 -0
  59. package/src/interface/mcp/tools/poll.js +62 -0
  60. package/src/interface/mcp/tools/results.js +270 -0
  61. package/src/interface/mcp/tools/review.js +135 -0
  62. package/src/interface/mcp/tools/wait.js +145 -0
  63. package/src/interface/mcp/update-state.js +34 -0
  64. package/src/interface/mcp/views/overview.js +183 -0
  65. package/src/interface/mcp/views/task.js +223 -0
  66. package/src/interface/web/app.js +226 -0
  67. package/src/interface/web/views.js +224 -0
  68. package/src/mcp-server.js +3 -2223
  69. package/src/run-host/entry.js +23 -0
  70. package/src/run-host/finalize.js +236 -0
  71. package/src/run-host/launch.js +63 -0
  72. package/src/run-host/live-run.js +73 -0
  73. package/src/run-host/outcome-facts.js +61 -0
  74. package/src/run-host/streams.js +76 -0
  75. package/src/run-host/track.js +128 -0
  76. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  77. package/src/runners/codex/chat-chunks.js +97 -0
  78. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  79. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  80. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  81. package/src/codex-runner.js +0 -1586
  82. package/src/landing.js +0 -507
  83. package/src/task-store.js +0 -1800
  84. package/src/web-app.js +0 -425
  85. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  86. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  87. /package/src/{prompt.js → domain/prompt.js} +0 -0
  88. /package/src/{status.js → domain/status.js} +0 -0
  89. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  90. /package/src/{truncate.js → domain/truncate.js} +0 -0
  91. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  92. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  93. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  94. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  95. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  96. /package/src/{cleanup-hint.js → infra/cleanup-hint.js} +0 -0
  97. /package/src/{external-output.js → infra/external-output.js} +0 -0
  98. /package/src/{handoff.js → infra/handoff.js} +0 -0
  99. /package/src/{paths.js → infra/paths.js} +0 -0
  100. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  101. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
@@ -0,0 +1,239 @@
1
+ import { git } from "../../../app/land-chain.js";
2
+ import { appendTaskEvent, readTaskEventRecords } from "../../../infra/store/events.js";
3
+ import { countVerifiedFacts, getFact, getFactEffectiveState, getTaskForWorkItem, isFactRevoked, latestContextSnapshotForTask, listContextFacts, promoteCandidateFact, revokeFact } from "../../../infra/store/facts.js";
4
+ import { getArtifact, listArtifactsForTask, readArtifact } from "../../../infra/store/records.js";
5
+ import { getTask } from "../../../infra/store/tasks.js";
6
+ import { runIdFor } from "../../../infra/store/db.js";
7
+ import { clip, errorResult, textResult } from "../result.js";
8
+ import { z } from "zod";
9
+
10
+ export const getContextSnapshotMetaTool = [
11
+ "get_context_snapshot_meta",
12
+ {
13
+ title: "Get worker context snapshot metadata",
14
+ 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.",
15
+ inputSchema: { task_id: z.string().min(1) }
16
+ },
17
+ async ({ task_id }) => {
18
+ const task = await getTask(task_id);
19
+ if (!task) return textResult({ error: "task_not_found", task_id });
20
+ const snapshot = await latestContextSnapshotForTask(task_id);
21
+ if (!snapshot) return textResult({ task_id, snapshot: null });
22
+ return textResult({
23
+ task_id,
24
+ snapshot: {
25
+ id: snapshot.id,
26
+ run_id: snapshot.run_id,
27
+ recipient: snapshot.recipient,
28
+ fact_ids: JSON.parse(snapshot.fact_versions),
29
+ base_sha: snapshot.base_sha,
30
+ prompt_sha256: snapshot.prompt_sha256,
31
+ estimated_tokens: snapshot.estimated_tokens,
32
+ excluded: JSON.parse(snapshot.excluded_json),
33
+ created_at: snapshot.created_at
34
+ }
35
+ });
36
+ }
37
+ ];
38
+
39
+ export const getFactTool = [
40
+ "get_fact",
41
+ {
42
+ title: "Get one verified or candidate fact",
43
+ description: "Read one fact by ID for audit. Facts are never automatically expanded into the main thread's context.",
44
+ inputSchema: { fact_id: z.string().uuid() }
45
+ },
46
+ async ({ fact_id }) => {
47
+ const fact = await getFact(fact_id);
48
+ if (!fact) return textResult({ error: "fact_not_found", fact_id });
49
+ return textResult({ fact, effective_state: await getFactEffectiveState(fact_id) ?? fact.state });
50
+ }
51
+ ];
52
+
53
+ export const getArtifactTool = [
54
+ "get_artifact",
55
+ {
56
+ title: "Get one retained evidence artifact",
57
+ 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.",
58
+ inputSchema: { artifact_id: z.string().uuid(), maxChars: z.number().int().min(0).max(100000).default(12000) }
59
+ },
60
+ async ({ artifact_id, maxChars }) => {
61
+ const artifact = await getArtifact(artifact_id);
62
+ if (!artifact) return textResult({ error: "artifact_not_found", artifact_id });
63
+ return textResult({ artifact: await readArtifact(artifact_id, maxChars) });
64
+ }
65
+ ];
66
+
67
+ export const promoteWorkerFactTool = [
68
+ "promote_worker_fact",
69
+ {
70
+ title: "Promote a candidate worker fact",
71
+ 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.",
72
+ inputSchema: {
73
+ fact_id: z.string().uuid(),
74
+ scope: z.enum(["work_item", "repo_verified"]).default("work_item"),
75
+ watchedPaths: z.array(z.string().min(1)).max(100).optional(),
76
+ expiresAt: z.string().datetime().optional()
77
+ }
78
+ },
79
+ async ({ fact_id, scope, watchedPaths, expiresAt }) => {
80
+ try {
81
+ const source = await getFact(fact_id);
82
+ if (!source) return textResult({ error: "fact_not_found", fact_id });
83
+ if (await isFactRevoked(fact_id)) return textResult({ error: "fact_already_revoked", fact_id });
84
+ const task = await getTaskForWorkItem(source.work_item_id);
85
+ if (!task) return textResult({ error: "fact_task_not_found", fact_id });
86
+ 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 }, {
87
+ runId: runIdFor(task.id, task.run_count ?? 1), actor: "main_thread"
88
+ });
89
+ const fact = await promoteCandidateFact({
90
+ factId: fact_id,
91
+ scopeType: scope,
92
+ watchedPaths,
93
+ expiresAt: expiresAt ?? null,
94
+ sourceEventId: event.id,
95
+ verifiedBy: "main_thread"
96
+ });
97
+ return textResult({ fact, source_fact_id: fact_id });
98
+ } catch (error) {
99
+ return errorResult(error);
100
+ }
101
+ }
102
+ ];
103
+
104
+ export const revokeWorkerFactTool = [
105
+ "revoke_worker_fact",
106
+ {
107
+ title: "Revoke a candidate or verified worker fact",
108
+ 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.",
109
+ inputSchema: { fact_id: z.string().uuid(), reason: z.string().min(1).max(2000) }
110
+ },
111
+ async ({ fact_id, reason }) => {
112
+ try {
113
+ const source = await getFact(fact_id);
114
+ if (!source) return textResult({ error: "fact_not_found", fact_id });
115
+ const task = await getTaskForWorkItem(source.work_item_id);
116
+ if (!task) return textResult({ error: "fact_task_not_found", fact_id });
117
+ const revoked = await revokeFact(fact_id);
118
+ await appendTaskEvent(task.id, { type: "supervisor.fact_revoked", fact_id, reason }, {
119
+ runId: runIdFor(task.id, task.run_count ?? 1), actor: "main_thread"
120
+ });
121
+ return textResult({ fact: revoked, reason });
122
+ } catch (error) {
123
+ return errorResult(error);
124
+ }
125
+ }
126
+ ];
127
+
128
+ export const getWorkerEvidenceTool = [
129
+ "get_worker_evidence",
130
+ {
131
+ title: "Get a worker evidence index",
132
+ 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.",
133
+ inputSchema: { task_id: z.string().min(1), limit: z.number().int().min(1).max(100).default(30) }
134
+ },
135
+ async ({ task_id, limit }) => {
136
+ const task = await getTask(task_id);
137
+ if (!task) return textResult({ error: "task_not_found", task_id });
138
+ const events = await readTaskEventRecords(task_id, limit);
139
+ const artifacts = await listArtifactsForTask(task_id, limit);
140
+ return textResult({
141
+ task_id,
142
+ events: events.map((event) => ({
143
+ id: event.id, run_id: event.run_id, type: event.event_type, actor: event.actor,
144
+ payload_sha256: event.payload_sha256, created_at: event.created_at
145
+ })),
146
+ artifacts: artifacts.map((artifact) => ({
147
+ id: artifact.id, run_id: artifact.run_id, type: artifact.type, sha256: artifact.sha256,
148
+ security_class: artifact.security_class, retention: artifact.retention, created_at: artifact.created_at
149
+ }))
150
+ });
151
+ }
152
+ ];
153
+
154
+ function decodeFactCursor(cursor, taskId, query) {
155
+ if (!cursor) return 0;
156
+ try {
157
+ const payload = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
158
+ if (payload.task_id !== taskId || payload.query !== query || !Number.isInteger(payload.offset) || payload.offset < 0) throw new Error("mismatch");
159
+ return payload.offset;
160
+ } catch {
161
+ const error = new Error("fact cursor does not match this task and query");
162
+ error.code = "invalid_fact_cursor";
163
+ throw error;
164
+ }
165
+ }
166
+
167
+ function encodeFactCursor(taskId, query, offset) {
168
+ return Buffer.from(JSON.stringify({ task_id: taskId, query, offset })).toString("base64url");
169
+ }
170
+
171
+ function factFreshForTask(task, fact) {
172
+ if (!fact.valid_for_sha || !task.base_commit) return true;
173
+ try {
174
+ git(task.project_root, ["merge-base", "--is-ancestor", fact.valid_for_sha, task.base_commit]);
175
+ return true;
176
+ } catch {
177
+ return false;
178
+ }
179
+ }
180
+
181
+ export const searchWorkerFactsTool = [
182
+ "search_worker_facts",
183
+ {
184
+ title: "Search verified worker facts in scope",
185
+ 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.",
186
+ inputSchema: {
187
+ task_id: z.string().min(1),
188
+ query: z.string().max(500).default(""),
189
+ limit: z.number().int().min(1).max(50).default(20),
190
+ cursor: z.string().min(1).optional()
191
+ }
192
+ },
193
+ async ({ task_id, query, limit, cursor }) => {
194
+ const task = await getTask(task_id);
195
+ if (!task) return textResult({ error: "task_not_found", task_id });
196
+ try {
197
+ const normalizedQuery = query.trim().toLocaleLowerCase();
198
+ const offset = decodeFactCursor(cursor, task_id, normalizedQuery);
199
+ const scoped = (await listContextFacts({
200
+ taskId: task_id,
201
+ baseSha: task.base_commit ?? null,
202
+ ownedPaths: task.owned_paths ?? [],
203
+ dependencyTaskIds: task.depends_on ?? []
204
+ })).filter((fact) => factFreshForTask(task, fact));
205
+ const matching = scoped.filter((fact) => !normalizedQuery || `${fact.key}\n${JSON.stringify(fact.value)}`.toLocaleLowerCase().includes(normalizedQuery));
206
+ const page = matching.slice(offset, offset + limit);
207
+ const nextOffset = offset + page.length;
208
+ const totalVerified = await countVerifiedFacts();
209
+ return textResult({
210
+ task_id,
211
+ facts: page.map((fact) => ({
212
+ id: fact.id,
213
+ key: fact.key,
214
+ summary: clip(typeof fact.value === "string" ? fact.value : JSON.stringify(fact.value), 360),
215
+ state: fact.state,
216
+ scope: fact.scope_type,
217
+ valid_for_sha: fact.valid_for_sha ?? null,
218
+ freshness: "current",
219
+ source_refs: [
220
+ ...(fact.source_event_id ? [`event:${fact.source_event_id}`] : []),
221
+ ...(fact.source_artifact_id ? [`artifact:${fact.source_artifact_id}`] : [])
222
+ ]
223
+ })),
224
+ coverage: {
225
+ scope: "current_work+explicit_dependencies+path_matched_repo_facts",
226
+ included_count: scoped.length,
227
+ matched_count: matching.length,
228
+ omitted: [
229
+ { reason: "other_verified_scopes_excluded", count: Math.max(0, totalVerified - scoped.length) },
230
+ { reason: "candidate_and_nonverified_facts_excluded", count: null }
231
+ ]
232
+ },
233
+ next_cursor: nextOffset < matching.length ? encodeFactCursor(task_id, normalizedQuery, nextOffset) : null
234
+ });
235
+ } catch (error) {
236
+ return errorResult(error);
237
+ }
238
+ }
239
+ ];
@@ -0,0 +1,202 @@
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
+ ];
@@ -0,0 +1,62 @@
1
+ import { createCleanupPlan } from "../../../app/cleanup-plan.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. 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 candidateIds = tasks.filter((task) => task.delivery_state === "cleanup_eligible").map((task) => task.id);
29
+ const cleanupReadiness = candidateIds.length > 0
30
+ ? await createCleanupPlan({ taskIds: candidateIds, revalidateRemote: false })
31
+ : null;
32
+ const readyToCleanTaskIds = cleanupReadiness
33
+ ? new Set(cleanupReadiness.items.filter((item) => item.verdict === "safe").map((item) => item.task_id))
34
+ : new Set();
35
+ const result = buildOverviewDelta(tasks, previous, { readyToCleanTaskIds });
36
+ await writeObserverCursor(deltaObserverId, result.cursor);
37
+ const { cursor: nextCursor, ...reply } = result;
38
+ return textResult({ ...reply, next_cursor: nextCursor });
39
+ });
40
+ deltaRead = read.catch(() => {});
41
+ return read;
42
+ }
43
+ ];
44
+ export const checkWorkersTool = ["check_workers", {
45
+ title: "Check changed workers",
46
+ 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.",
47
+ inputSchema: {}
48
+ }, async () => {
49
+ const read = observerRead.then(async () => {
50
+ await reconcileDetachedActiveTasks();
51
+ const recoveries = await recoverEligibleRuns();
52
+ const result = collectWorkerChanges(await readTasks(), await readObserverCursor(observerId));
53
+ await writeObserverCursor(observerId, result.cursor);
54
+ const { cursor, ...reply } = result;
55
+ // The cleanup hint rides along without touching quiet: it is a standing fact
56
+ // about the store, not a new worker event.
57
+ const cleanup = await cleanupHint();
58
+ return textResult({ ...reply, quiet: reply.quiet && recoveries.length === 0, recoveries, ...(cleanup ? { cleanup } : {}) });
59
+ });
60
+ observerRead = read.catch(() => {});
61
+ return read;
62
+ }];