codex-supervisor-mcp 0.13.5 → 0.14.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 (109) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/package.json +19 -63
  4. package/skills/codex-supervisor/SKILL.md +5 -4
  5. package/src/{acceptance.js → app/acceptance.js} +54 -68
  6. package/src/app/auto-cleanup.js +90 -0
  7. package/src/app/cancel.js +60 -0
  8. package/src/app/cleanup-facts.js +96 -0
  9. package/src/app/cleanup-plan.js +164 -0
  10. package/src/app/compose.js +7 -0
  11. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  12. package/src/app/dispatch.js +396 -0
  13. package/src/app/followup.js +98 -0
  14. package/src/app/land-chain.js +133 -0
  15. package/src/app/landing.js +357 -0
  16. package/src/app/ownership.js +57 -0
  17. package/src/app/rebase.js +216 -0
  18. package/src/app/restore-worktree.js +50 -0
  19. package/src/app/resume.js +181 -0
  20. package/src/app/run-state.js +26 -0
  21. package/src/app/settled.js +28 -0
  22. package/src/{side-chat.js → app/side-chat.js} +82 -265
  23. package/src/app/sse.js +20 -0
  24. package/src/app/start-run.js +77 -0
  25. package/src/app/verify-push.js +114 -0
  26. package/src/app/worktree-setup.js +176 -0
  27. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  28. package/src/domain/acceptance-spec.js +30 -0
  29. package/src/domain/cleanup-policy.js +44 -0
  30. package/src/domain/command-outcome.js +6 -0
  31. package/src/{overview-delta.js → domain/overview-delta.js} +7 -3
  32. package/src/domain/side-turn-view.js +73 -0
  33. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  34. package/src/{cleanup-hint.js → infra/cleanup-hint.js} +7 -8
  35. package/src/infra/git.js +30 -0
  36. package/src/infra/process.js +59 -0
  37. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  38. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  39. package/src/infra/store/db.js +265 -0
  40. package/src/infra/store/events.js +146 -0
  41. package/src/infra/store/facts.js +338 -0
  42. package/src/infra/store/reconcile.js +172 -0
  43. package/src/infra/store/records.js +171 -0
  44. package/src/infra/store/runner-readers.js +16 -0
  45. package/src/infra/store/schema.js +306 -0
  46. package/src/infra/store/sessions.js +138 -0
  47. package/src/infra/store/tasks.js +337 -0
  48. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  49. package/src/{auto-update.js → infra/update/auto-update.js} +3 -3
  50. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  51. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  52. package/src/{worktree.js → infra/worktree.js} +56 -41
  53. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  54. package/src/{cleanup.js → interface/bin/cleanup.js} +4 -3
  55. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  56. package/src/{setup.js → interface/bin/setup.js} +7 -6
  57. package/src/{stage.js → interface/bin/stage.js} +1 -1
  58. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  59. package/src/interface/mcp/meta.js +7 -0
  60. package/src/interface/mcp/result.js +34 -0
  61. package/src/interface/mcp/schemas.js +24 -0
  62. package/src/interface/mcp/server.js +94 -0
  63. package/src/interface/mcp/tools/delivery.js +197 -0
  64. package/src/interface/mcp/tools/dispatch.js +267 -0
  65. package/src/interface/mcp/tools/facts.js +239 -0
  66. package/src/interface/mcp/tools/overview.js +202 -0
  67. package/src/interface/mcp/tools/poll.js +58 -0
  68. package/src/interface/mcp/tools/results.js +284 -0
  69. package/src/interface/mcp/tools/review.js +135 -0
  70. package/src/interface/mcp/tools/wait.js +145 -0
  71. package/src/interface/mcp/update-state.js +34 -0
  72. package/src/interface/mcp/views/overview.js +183 -0
  73. package/src/interface/mcp/views/task.js +223 -0
  74. package/src/interface/web/app.js +226 -0
  75. package/src/interface/web/views.js +224 -0
  76. package/src/mcp-server.js +3 -2223
  77. package/src/run-host/entry.js +23 -0
  78. package/src/run-host/finalize.js +236 -0
  79. package/src/run-host/launch.js +63 -0
  80. package/src/run-host/live-run.js +73 -0
  81. package/src/run-host/outcome-facts.js +61 -0
  82. package/src/run-host/streams.js +76 -0
  83. package/src/run-host/track.js +128 -0
  84. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  85. package/src/runners/codex/chat-chunks.js +97 -0
  86. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  87. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  88. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  89. package/src/cleanup-plan.js +0 -158
  90. package/src/codex-runner.js +0 -1586
  91. package/src/landing.js +0 -507
  92. package/src/task-store.js +0 -1800
  93. package/src/web-app.js +0 -425
  94. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  95. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  96. /package/src/{prompt.js → domain/prompt.js} +0 -0
  97. /package/src/{status.js → domain/status.js} +0 -0
  98. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  99. /package/src/{truncate.js → domain/truncate.js} +0 -0
  100. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  101. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  102. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  103. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  104. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  105. /package/src/{external-output.js → infra/external-output.js} +0 -0
  106. /package/src/{handoff.js → infra/handoff.js} +0 -0
  107. /package/src/{paths.js → infra/paths.js} +0 -0
  108. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  109. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
@@ -22,19 +22,15 @@
22
22
  // turn failed / timed out / stopped error on the turn, session still usable
23
23
  // board restarted mid-turn ........ turn marked interrupted
24
24
  // session ended ................... fork deleted, history cleared
25
+ import { ensureTaskWorktree } from "./restore-worktree.js";
26
+ import "./compose.js";
27
+ import { answerOf, partsFromChunks, turnView } from "../domain/side-turn-view.js";
28
+ import { closeSideSession, getSideSession, insertSideTurn, interruptRunningSideTurns, openSideSession, readSideTurns, setSideSessionFork, updateSideTurn } from "../infra/store/sessions.js";
29
+ import { codexRunner } from "../runners/codex/adapter.js";
30
+ import { chunksFor } from "../runners/codex/chat-chunks.js";
31
+ import { codexConfigText, disableMcpServerArgs } from "../runners/codex/mcp-config.js";
32
+ import { endStream, sseHead, writeChunk } from "./sse.js";
25
33
  import { randomUUID } from "node:crypto";
26
- import { codexConfigText, disableMcpServerArgs } from "./mcp-config.js";
27
- import { codexRunner } from "./runner-adapter.js";
28
- import {
29
- closeSideSession,
30
- getSideSession,
31
- insertSideTurn,
32
- interruptRunningSideTurns,
33
- openSideSession,
34
- readSideTurns,
35
- setSideSessionFork,
36
- updateSideTurn
37
- } from "./task-store.js";
38
34
 
39
35
  const TURN_TIMEOUT_MS = 10 * 60 * 1000;
40
36
 
@@ -90,7 +86,6 @@ export async function prepareSideSession(task, { fresh = false } = {}) {
90
86
  }
91
87
  return { session, refreshed };
92
88
  }
93
- const OUTPUT_CLIP = 4000;
94
89
 
95
90
  // taskId -> { turnId, child, chunks, watchers: Set<res>, startedAt, question, state }
96
91
  const running = new Map();
@@ -102,168 +97,6 @@ async function sweepOnce() {
102
97
  await interruptRunningSideTurns();
103
98
  }
104
99
 
105
- function clip(text, max = OUTPUT_CLIP) {
106
- if (typeof text !== "string") return text ?? null;
107
- return text.length <= max ? text : `${text.slice(0, max)}\n…(${text.length - max} more characters)`;
108
- }
109
-
110
- // ---- Codex event -> UI message stream chunks
111
-
112
- function chunksFor(event, state) {
113
- const item = event.item ?? {};
114
- const out = [];
115
- switch (event.type) {
116
- case "thread.started":
117
- if (event.thread_id) out.push({ type: "data-session", data: { fork_thread_id: event.thread_id } });
118
- break;
119
- case "turn.started":
120
- out.push({ type: "start-step" });
121
- break;
122
- case "item.started":
123
- case "item.updated":
124
- if (item.type === "command_execution" && !state.toolsSeen.has(item.id)) {
125
- state.toolsSeen.add(item.id);
126
- out.push({ type: "tool-input-available", toolCallId: item.id, toolName: "shell", input: { command: item.command ?? "" } });
127
- }
128
- break;
129
- case "item.completed":
130
- switch (item.type) {
131
- case "reasoning": {
132
- const id = `r-${item.id}`;
133
- out.push({ type: "reasoning-start", id }, { type: "reasoning-delta", id, delta: item.text ?? "" }, { type: "reasoning-end", id });
134
- break;
135
- }
136
- case "agent_message": {
137
- const id = `t-${item.id}`;
138
- out.push({ type: "text-start", id }, { type: "text-delta", id, delta: item.text ?? "" }, { type: "text-end", id });
139
- break;
140
- }
141
- case "command_execution":
142
- if (!state.toolsSeen.has(item.id)) {
143
- state.toolsSeen.add(item.id);
144
- out.push({ type: "tool-input-available", toolCallId: item.id, toolName: "shell", input: { command: item.command ?? "" } });
145
- }
146
- out.push({
147
- type: "tool-output-available",
148
- toolCallId: item.id,
149
- output: { exit_code: item.exit_code ?? null, status: item.status ?? null, output: clip(item.aggregated_output ?? "") }
150
- });
151
- break;
152
- case "file_change":
153
- out.push(
154
- { type: "tool-input-available", toolCallId: item.id, toolName: "edit", input: { changes: item.changes ?? [] } },
155
- { type: "tool-output-available", toolCallId: item.id, output: { status: item.status ?? "completed" } }
156
- );
157
- break;
158
- case "web_search":
159
- case "mcp_tool_call":
160
- out.push(
161
- { type: "tool-input-available", toolCallId: item.id, toolName: item.type, input: { ...item, id: undefined, type: undefined } },
162
- { type: "tool-output-available", toolCallId: item.id, output: { status: item.status ?? "completed" } }
163
- );
164
- break;
165
- case "error":
166
- // Startup notices (unknown config keys, missing model metadata) come
167
- // through as error items. They are not the answer failing.
168
- out.push({ type: "data-notice", data: { message: item.message ?? item.text ?? "" } });
169
- break;
170
- default:
171
- break;
172
- }
173
- break;
174
- case "turn.completed":
175
- out.push({ type: "finish-step" });
176
- if (event.usage) {
177
- out.push({ type: "data-usage", data: event.usage });
178
- state.usage = event.usage;
179
- }
180
- state.completed = true;
181
- break;
182
- case "turn.failed":
183
- out.push({ type: "error", errorText: event.error?.message ?? event.error ?? event.message ?? "Codex turn failed" });
184
- state.failed = true;
185
- break;
186
- case "error":
187
- out.push({ type: "data-notice", data: { message: event.message ?? event.error ?? "" } });
188
- break;
189
- default:
190
- break;
191
- }
192
- return out;
193
- }
194
-
195
- // ---- stream plumbing
196
-
197
- function sseHead(res) {
198
- res.writeHead(200, {
199
- "content-type": "text/event-stream; charset=utf-8",
200
- "cache-control": "no-cache, no-transform",
201
- connection: "keep-alive",
202
- "x-vercel-ai-ui-message-stream": "v1",
203
- "x-accel-buffering": "no"
204
- });
205
- }
206
-
207
- function writeChunk(res, chunk) {
208
- if (!res.writableEnded) res.write(`data: ${JSON.stringify(chunk)}\n\n`);
209
- }
210
-
211
- function endStream(res) {
212
- if (!res.writableEnded) res.end("data: [DONE]\n\n");
213
- }
214
-
215
- // Chunks of a turn, assembled into the UIMessage parts the page shows for a
216
- // finished (or interrupted) turn. The page rebuilds history from this.
217
- export function partsFromChunks(chunks) {
218
- const parts = [];
219
- const open = new Map(); // id -> part for text / reasoning
220
- const tools = new Map(); // toolCallId -> part
221
- for (const c of chunks) {
222
- switch (c.type) {
223
- case "text-start":
224
- open.set(c.id, { type: "text", text: "", state: "streaming" });
225
- parts.push(open.get(c.id));
226
- break;
227
- case "text-delta":
228
- if (open.has(c.id)) open.get(c.id).text += c.delta ?? "";
229
- break;
230
- case "text-end":
231
- if (open.has(c.id)) open.get(c.id).state = "done";
232
- break;
233
- case "reasoning-start":
234
- open.set(c.id, { type: "reasoning", text: "", state: "streaming" });
235
- parts.push(open.get(c.id));
236
- break;
237
- case "reasoning-delta":
238
- if (open.has(c.id)) open.get(c.id).text += c.delta ?? "";
239
- break;
240
- case "reasoning-end":
241
- if (open.has(c.id)) open.get(c.id).state = "done";
242
- break;
243
- case "tool-input-available": {
244
- const part = { type: `tool-${c.toolName}`, toolCallId: c.toolCallId, state: "input-available", input: c.input };
245
- tools.set(c.toolCallId, part);
246
- parts.push(part);
247
- break;
248
- }
249
- case "tool-output-available":
250
- if (tools.has(c.toolCallId)) {
251
- tools.get(c.toolCallId).state = "output-available";
252
- tools.get(c.toolCallId).output = c.output;
253
- }
254
- break;
255
- case "data-notice":
256
- case "data-usage":
257
- case "data-session":
258
- parts.push({ type: c.type, data: c.data });
259
- break;
260
- default:
261
- break;
262
- }
263
- }
264
- return parts;
265
- }
266
-
267
100
  // ---- public API
268
101
 
269
102
  export async function sideSessionState(taskId) {
@@ -307,67 +140,48 @@ export function attachToTurn(taskId, res) {
307
140
  return true;
308
141
  }
309
142
 
310
- // Start a turn. `res` (optional) becomes the first watcher. Resolves when the
311
- // turn has ended, however it ended.
312
- export async function runSideTurn({ task, text, res = null, fresh = false }) {
313
- await sweepOnce();
314
- if (!task.thread_id) throw Object.assign(new Error("this worker recorded no thread_id, so there is no Codex thread to fork"), { code: "no_thread" });
315
- if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
316
- const target = codexRunner.resolveTarget();
317
- if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
318
-
319
- const { session, refreshed } = await prepareSideSession(task, { fresh });
320
-
143
+ function startSideChild(target, task, session) {
321
144
  const args = codexRunner.forkSideArgs({ forkThreadId: session.fork_thread_id, workerThreadId: task.thread_id, model: task.model });
322
145
  args.splice(-2, 0, ...sideTurnConfigArgs(codexConfigText()));
323
-
324
146
  const cwd = task.worktree_path || task.project_root || process.cwd();
325
- const child = codexRunner.start(target, args, {
147
+ return codexRunner.start(target, args, {
326
148
  cwd,
327
149
  stdio: ["pipe", "pipe", "pipe"],
328
150
  env: { ...process.env, NO_COLOR: "1" },
329
151
  windowsHide: true
330
152
  });
153
+ }
331
154
 
155
+ // The in-memory side of a running turn: its chunks so far, who is watching,
156
+ // and how it was stopped. Chunks are written through to the store in batches.
157
+ async function openLiveTurn(task, text, child) {
332
158
  const turnId = `turn-${Date.now()}-${randomUUID().slice(0, 8)}`;
333
159
  const startedAt = new Date().toISOString();
334
- const live = { turnId, child, chunks: [], watchers: new Set(), startedAt, question: text, state: { toolsSeen: new Set(), completed: false, failed: false, usage: null } };
335
- running.set(task.id, live);
336
- await insertSideTurn({ id: turnId, task_id: task.id, question: text, status: "running", chunks: [], started_at: startedAt });
337
-
338
- let persistTimer = null;
160
+ const state = { toolsSeen: new Set(), completed: false, failed: false, usage: null };
161
+ const live = { turnId, child, chunks: [], watchers: new Set(), startedAt, question: text, state, stderr: "", stoppedBy: null, persistTimer: null };
339
162
  const persistSoon = () => {
340
- if (persistTimer) return;
341
- persistTimer = setTimeout(() => {
342
- persistTimer = null;
163
+ if (live.persistTimer) return;
164
+ live.persistTimer = setTimeout(() => {
165
+ live.persistTimer = null;
343
166
  updateSideTurn(turnId, { chunks: live.chunks }).catch(() => {});
344
167
  }, 250);
345
168
  };
346
- const broadcast = (chunk) => {
169
+ live.broadcast = (chunk) => {
347
170
  live.chunks.push(chunk);
348
171
  for (const w of live.watchers) writeChunk(w, chunk);
349
172
  persistSoon();
350
173
  };
351
-
352
- if (res) {
353
- sseHead(res);
354
- live.watchers.add(res);
355
- res.on("close", () => live.watchers.delete(res));
356
- }
357
- broadcast({ type: "start", messageId: turnId });
358
-
359
- let rest = "";
360
- let stderr = "";
361
- let stoppedBy = null;
362
- const timer = setTimeout(() => {
363
- stoppedBy = "timeout";
364
- codexRunner.cancelChild(child);
365
- }, TURN_TIMEOUT_MS);
366
174
  live.stop = (reason) => {
367
- stoppedBy = reason;
175
+ live.stoppedBy = reason;
368
176
  codexRunner.cancelChild(child);
369
177
  };
178
+ running.set(task.id, live);
179
+ await insertSideTurn({ id: turnId, task_id: task.id, question: text, status: "running", chunks: [], started_at: startedAt });
180
+ return live;
181
+ }
370
182
 
183
+ function pipeSideOutput(child, live, session, taskId) {
184
+ let rest = "";
371
185
  child.stdout.setEncoding("utf8");
372
186
  child.stdout.on("data", (chunk) => {
373
187
  rest += chunk;
@@ -384,78 +198,81 @@ export async function runSideTurn({ task, text, res = null, fresh = false }) {
384
198
  }
385
199
  if (event.type === "thread.started" && !session.fork_thread_id && event.thread_id) {
386
200
  session.fork_thread_id = event.thread_id;
387
- setSideSessionFork(task.id, event.thread_id).catch(() => {});
201
+ setSideSessionFork(taskId, event.thread_id).catch(() => {});
388
202
  }
389
- for (const part of chunksFor(event, live.state)) broadcast(part);
203
+ for (const part of chunksFor(event, live.state)) live.broadcast(part);
390
204
  }
391
205
  });
392
206
  child.stderr.setEncoding("utf8");
393
207
  child.stderr.on("data", (chunk) => {
394
- stderr = (stderr + chunk).slice(-4000);
208
+ live.stderr = (live.stderr + chunk).slice(-4000);
395
209
  });
210
+ }
211
+
212
+ // How the turn ended, and the error to show when it did not complete.
213
+ function sideTurnOutcome(live, code, signal) {
214
+ if (live.state.failed) return { status: "failed", error: live.chunks.find((c) => c.type === "error")?.errorText ?? "Codex turn failed", announce: false };
215
+ if (live.state.completed) return { status: "completed", error: null, announce: false };
216
+ if (live.stoppedBy === "timeout") {
217
+ return { status: "timed_out", error: `the side turn ran past ${TURN_TIMEOUT_MS / 60000} minutes and was stopped`, announce: true };
218
+ }
219
+ if (live.stoppedBy) return { status: "stopped", error: "stopped", announce: true };
220
+ const tail = live.stderr.trim().split("\n").filter((l) => !l.includes("rmcp::transport")).slice(-3).join("\n");
221
+ const why = signal ? `stopped by ${signal}` : `codex exited with code ${code}`;
222
+ return { status: "failed", error: tail ? `${why}: ${tail}` : why, announce: true };
223
+ }
224
+
225
+ async function settleSideTurn(live, taskId, code, signal) {
226
+ if (live.persistTimer) clearTimeout(live.persistTimer);
227
+ const { status, error, announce } = sideTurnOutcome(live, code, signal);
228
+ if (announce) live.broadcast({ type: "error", errorText: error });
229
+ live.broadcast({ type: "finish" });
230
+ for (const w of live.watchers) endStream(w);
231
+ live.watchers.clear();
232
+ running.delete(taskId);
233
+ await updateSideTurn(live.turnId, { status, chunks: live.chunks, usage: live.state.usage, error, ended_at: new Date().toISOString() }).catch(() => {});
234
+ return status;
235
+ }
236
+
237
+ // Start a turn. `res` (optional) becomes the first watcher. Resolves when the
238
+ // turn has ended, however it ended.
239
+ export async function runSideTurn({ task, text, res = null, fresh = false }) {
240
+ await sweepOnce();
241
+ if (!task.thread_id) throw Object.assign(new Error("this worker recorded no thread_id, so there is no Codex thread to fork"), { code: "no_thread" });
242
+ if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
243
+ const target = codexRunner.resolveTarget();
244
+ if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
245
+
246
+ const { session, refreshed } = await prepareSideSession(task, { fresh });
247
+ // The fork reads the worker's files; a cleaned-up worktree comes back from its branch.
248
+ await ensureTaskWorktree(task);
249
+ const child = startSideChild(target, task, session);
250
+ const live = await openLiveTurn(task, text, child);
251
+ if (res) {
252
+ sseHead(res);
253
+ live.watchers.add(res);
254
+ res.on("close", () => live.watchers.delete(res));
255
+ }
256
+ live.broadcast({ type: "start", messageId: live.turnId });
257
+ const timer = setTimeout(() => live.stop("timeout"), TURN_TIMEOUT_MS);
258
+ pipeSideOutput(child, live, session, task.id);
396
259
  child.stdin.on("error", () => {});
397
260
  child.stdin.end(sideQuestionText(text));
398
261
 
399
262
  return new Promise((resolve) => {
400
263
  const finish = async (code, signal) => {
401
264
  clearTimeout(timer);
402
- if (persistTimer) clearTimeout(persistTimer);
403
- let status = "completed";
404
- let error = null;
405
- if (live.state.failed) {
406
- status = "failed";
407
- error = live.chunks.find((c) => c.type === "error")?.errorText ?? "Codex turn failed";
408
- } else if (!live.state.completed) {
409
- if (stoppedBy === "timeout") {
410
- status = "timed_out";
411
- error = `the side turn ran past ${TURN_TIMEOUT_MS / 60000} minutes and was stopped`;
412
- } else if (stoppedBy) {
413
- status = "stopped";
414
- error = "stopped";
415
- } else {
416
- status = "failed";
417
- const tail = stderr.trim().split("\n").filter((l) => !l.includes("rmcp::transport")).slice(-3).join("\n");
418
- const why = signal ? `stopped by ${signal}` : `codex exited with code ${code}`;
419
- error = tail ? `${why}: ${tail}` : why;
420
- }
421
- broadcast({ type: "error", errorText: error });
422
- }
423
- broadcast({ type: "finish" });
424
- for (const w of live.watchers) endStream(w);
425
- live.watchers.clear();
426
- running.delete(task.id);
427
- await updateSideTurn(turnId, { status, chunks: live.chunks, usage: live.state.usage, error, ended_at: new Date().toISOString() }).catch(() => {});
428
- resolve({ status, turnId, forkThreadId: session.fork_thread_id, refreshed });
265
+ const status = await settleSideTurn(live, task.id, code, signal);
266
+ resolve({ status, turnId: live.turnId, forkThreadId: session.fork_thread_id, refreshed });
429
267
  };
430
268
  child.on("error", (error) => {
431
- stderr += `\nfailed to start codex: ${error.message}`;
269
+ live.stderr += `\nfailed to start codex: ${error.message}`;
432
270
  finish(-1, null);
433
271
  });
434
272
  child.on("exit", finish);
435
273
  });
436
274
  }
437
275
 
438
- // The answer of a turn, as the text parts joined; null while nothing has
439
- // been said yet.
440
- function answerOf(turn) {
441
- const parts = partsFromChunks(turn.chunks ?? []);
442
- const text = parts.filter((p) => p.type === "text").map((p) => p.text).join("\n").trim();
443
- return text || null;
444
- }
445
-
446
- function turnView(turn) {
447
- return {
448
- turn_id: turn.id,
449
- question: turn.question,
450
- status: turn.status,
451
- answer: answerOf(turn),
452
- usage: turn.usage ?? null,
453
- error: turn.error ?? null,
454
- started_at: turn.started_at ?? null,
455
- ended_at: turn.ended_at ?? null
456
- };
457
- }
458
-
459
276
  // The newest side turn of a worker, for a caller that asked earlier and
460
277
  // comes back for the answer. Null when nothing was ever asked.
461
278
  export async function latestSideTurn(taskId) {
package/src/app/sse.js ADDED
@@ -0,0 +1,20 @@
1
+ // Server-sent events plumbing for the side chat stream.
2
+ // ---- stream plumbing
3
+
4
+ export function sseHead(res) {
5
+ res.writeHead(200, {
6
+ "content-type": "text/event-stream; charset=utf-8",
7
+ "cache-control": "no-cache, no-transform",
8
+ connection: "keep-alive",
9
+ "x-vercel-ai-ui-message-stream": "v1",
10
+ "x-accel-buffering": "no"
11
+ });
12
+ }
13
+
14
+ export function writeChunk(res, chunk) {
15
+ if (!res.writableEnded) res.write(`data: ${JSON.stringify(chunk)}\n\n`);
16
+ }
17
+
18
+ export function endStream(res) {
19
+ if (!res.writableEnded) res.end("data: [DONE]\n\n");
20
+ }
@@ -0,0 +1,77 @@
1
+ import "./compose.js";
2
+ import { spawnProcess } from "../infra/process.js";
3
+ import { upsertTask } from "../infra/store/tasks.js";
4
+ import { compileWorkerContext } from "./context-compiler.js";
5
+ import { failedStart, MAX_RUN_HOST_PROMPT_BYTES, RUN_HOST_STARTUP_TIMEOUT_MS } from "./run-state.js";
6
+ import { closeSync, openSync } from "node:fs";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ // The MCP client may disappear at any point. A detached process owns the
10
+ // streams, exit write and acceptance until all three settle; IPC is only a
11
+ // startup handshake and never the channel carrying worker results.
12
+ export async function startTrackedRun(job) {
13
+ if (Buffer.byteLength(String(job.prompt ?? ""), "utf8") > MAX_RUN_HOST_PROMPT_BYTES) {
14
+ const result = failedStart(job.record, `worker prompt is too large for the detached run host IPC channel (maximum ${MAX_RUN_HOST_PROMPT_BYTES} bytes); reduce task text and move materials to context files`);
15
+ await upsertTask(result.record);
16
+ return result;
17
+ }
18
+ const compiled = await compileWorkerContext(job.record, { attempt: (job.record.run_count ?? 0) + 1 });
19
+ job.record = {
20
+ ...job.record,
21
+ input_context: {
22
+ ...job.record.input_context,
23
+ context: compiled.sourceRefs,
24
+ source_refs: compiled.sourceRefs,
25
+ content_hash: compiled.contentHash,
26
+ context_snapshot_id: compiled.snapshot.id,
27
+ context_snapshot_tokens: compiled.snapshot.estimated_tokens,
28
+ context_fact_count: compiled.factCount
29
+ }
30
+ };
31
+ job.prompt = `${compiled.text}\n\n${job.prompt}\n\nRequired input refs (read-only): ${JSON.stringify(compiled.sourceRefs)}\nRequired contracts: ${JSON.stringify(job.record.input_context.contracts ?? [])}`;
32
+ const hostLogPath = job.logPath.endsWith(".jsonl")
33
+ ? job.logPath.replace(/\.jsonl$/, ".host.log")
34
+ : `${job.logPath}.host.log`;
35
+ let hostLogFd;
36
+ try {
37
+ hostLogFd = openSync(hostLogPath, "a");
38
+ } catch (error) {
39
+ const result = failedStart(job.record, `cannot open run host log ${hostLogPath}: ${error.message}`);
40
+ await upsertTask(result.record);
41
+ return result;
42
+ }
43
+ let host;
44
+ try {
45
+ host = spawnProcess(process.execPath, [fileURLToPath(new URL("../run-host/entry.js", import.meta.url)), "--run-host"], {
46
+ detached: true, stdio: ["ignore", hostLogFd, hostLogFd, "ipc"],
47
+ env: process.env, windowsHide: true
48
+ });
49
+ } finally {
50
+ closeSync(hostLogFd);
51
+ }
52
+ const started = await new Promise((resolveStart) => {
53
+ let settled = false;
54
+ const finish = (result) => {
55
+ if (settled) return;
56
+ settled = true;
57
+ clearTimeout(timer);
58
+ host.removeAllListeners("message");
59
+ host.removeAllListeners("exit");
60
+ if (host.connected) host.disconnect();
61
+ host.unref();
62
+ resolveStart(result);
63
+ };
64
+ const timer = setTimeout(() => {
65
+ host.kill();
66
+ finish(failedStart(job.record, "run host startup timed out"));
67
+ }, RUN_HOST_STARTUP_TIMEOUT_MS);
68
+ host.once("message", finish);
69
+ host.once("error", (error) => finish(failedStart(job.record, `run host startup failed: ${error.message}`)));
70
+ host.once("exit", (code) => finish(failedStart(job.record, `run host exited before startup: ${code}`)));
71
+ host.send(job, (error) => {
72
+ if (error) finish(failedStart(job.record, `run host IPC failed: ${error.message}`));
73
+ });
74
+ });
75
+ if (!started.ok) await upsertTask(started.record);
76
+ return started;
77
+ }
@@ -0,0 +1,114 @@
1
+ // Proves a landed commit is on a remote branch. Read-only towards the remote:
2
+ // it fetches and compares, and never pushes or deploys.
3
+ import "./compose.js";
4
+ import { runGit } from "../infra/git.js";
5
+ import { appendTaskEvent } from "../infra/store/events.js";
6
+ import { getWorkItemForTask, recordFact } from "../infra/store/facts.js";
7
+ import { recordJsonArtifact, updateWorkItemDelivery } from "../infra/store/records.js";
8
+ import { getTask, upsertTask } from "../infra/store/tasks.js";
9
+ import { runIdFor } from "../infra/store/db.js";
10
+
11
+ const git = (cwd, args) => runGit(cwd, args, { timeout: 60000 });
12
+
13
+ async function recordPushFacts(task, proof, { eventId, artifactId }) {
14
+ const workItem = await getWorkItemForTask(task.id);
15
+ if (!workItem) return;
16
+ const { remote, branch, remoteHead } = proof;
17
+ const shared = {
18
+ workItemId: workItem.id,
19
+ scopeId: workItem.id,
20
+ state: "verified",
21
+ sourceEventId: eventId,
22
+ sourceArtifactId: artifactId,
23
+ validForSha: task.landed_head,
24
+ watchedPaths: task.owned_paths ?? [],
25
+ verifiedBy: "supervisor.remote_readback"
26
+ };
27
+ await recordFact({
28
+ ...shared,
29
+ scopeType: "work_item",
30
+ key: "push_verified",
31
+ value: { remote, branch, landed_head: task.landed_head, remote_head: remoteHead }
32
+ });
33
+ await recordFact({
34
+ ...shared,
35
+ scopeType: "dependency",
36
+ key: "push_delivery_summary",
37
+ value: { task_id: task.id, landed_head: task.landed_head, remote, branch, remote_head: remoteHead }
38
+ });
39
+ }
40
+
41
+ // Writes the task row, the delivery state, the event, the proof artifact and the facts.
42
+ async function recordPushVerified(task, proof) {
43
+ const { remote, branch, remoteHead } = proof;
44
+ const now = new Date().toISOString();
45
+ await upsertTask({ ...task, push_verified_at: now, push_remote: remote, push_branch: branch, push_remote_head: remoteHead, updated_at: now });
46
+ await updateWorkItemDelivery(task.id, "push_verified");
47
+ const runId = runIdFor(task.id, task.run_count ?? 1);
48
+ const event = await appendTaskEvent(task.id, {
49
+ type: "supervisor.push_verified",
50
+ remote,
51
+ branch,
52
+ landed_head: task.landed_head,
53
+ remote_head: remoteHead,
54
+ verified_at: now
55
+ }, { runId, actor: "supervisor" });
56
+ const artifact = await recordJsonArtifact({
57
+ runId,
58
+ type: "push_proof",
59
+ value: { remote, branch, landed_head: task.landed_head, remote_head: remoteHead, verified_at: now, event_id: event.id },
60
+ securityClass: "internal"
61
+ });
62
+ await recordPushFacts(task, proof, { eventId: event.id, artifactId: artifact.id });
63
+ return { now, artifact };
64
+ }
65
+
66
+ function remoteHeadOf(task, remote, branch) {
67
+ git(task.project_root, ["remote", "get-url", remote]);
68
+ git(task.project_root, ["fetch", "--no-tags", remote, `refs/heads/${branch}`]);
69
+ return git(task.project_root, ["rev-parse", "FETCH_HEAD"]);
70
+ }
71
+
72
+ function reaches(task, remoteHead) {
73
+ try {
74
+ git(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, remoteHead]);
75
+ return true;
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+
81
+ export async function verifyDeliveryPush({ taskId, remote, branch }) {
82
+ const task = await getTask(taskId);
83
+ if (!task) return { error: "task_not_found", task_id: taskId };
84
+ const targetBranch = branch ?? task.landed_branch;
85
+ if (!task.landed_at || !task.landed_head || !targetBranch) {
86
+ return { error: "not_landed", task_id: taskId, reason: "land the worker first; this task has no landed head and branch to verify" };
87
+ }
88
+ try {
89
+ const remoteHead = remoteHeadOf(task, remote, targetBranch);
90
+ if (!reaches(task, remoteHead)) {
91
+ return {
92
+ error: "not_pushed",
93
+ task_id: taskId,
94
+ remote,
95
+ branch: targetBranch,
96
+ landed_head: task.landed_head,
97
+ remote_head: remoteHead,
98
+ reason: "landed_head is not reachable from the fetched remote branch"
99
+ };
100
+ }
101
+ const { now, artifact } = await recordPushVerified(task, { remote, branch: targetBranch, remoteHead });
102
+ return {
103
+ task_id: taskId,
104
+ remote,
105
+ branch: targetBranch,
106
+ landed_head: task.landed_head,
107
+ remote_head: remoteHead,
108
+ artifact_id: artifact.id,
109
+ push_verified_at: now
110
+ };
111
+ } catch (error) {
112
+ return { error: "push_verification_failed", task_id: taskId, remote, branch: targetBranch, reason: error.message.split("\n")[0] };
113
+ }
114
+ }