codex-supervisor-mcp 0.13.4 → 0.13.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.en.md +101 -297
  2. package/README.md +99 -310
  3. package/package.json +24 -63
  4. package/src/{acceptance.js → app/acceptance.js} +54 -68
  5. package/src/app/cancel.js +60 -0
  6. package/src/{cleanup-plan.js → app/cleanup-plan.js} +13 -14
  7. package/src/app/compose.js +7 -0
  8. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  9. package/src/app/dispatch.js +396 -0
  10. package/src/app/followup.js +98 -0
  11. package/src/app/land-chain.js +124 -0
  12. package/src/app/landing.js +357 -0
  13. package/src/app/ownership.js +57 -0
  14. package/src/app/rebase.js +216 -0
  15. package/src/app/resume.js +164 -0
  16. package/src/app/run-state.js +26 -0
  17. package/src/app/settled.js +28 -0
  18. package/src/{side-chat.js → app/side-chat.js} +79 -266
  19. package/src/app/sse.js +20 -0
  20. package/src/app/start-run.js +77 -0
  21. package/src/app/verify-push.js +119 -0
  22. package/src/app/worktree-setup.js +176 -0
  23. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  24. package/src/domain/acceptance-spec.js +30 -0
  25. package/src/domain/command-outcome.js +6 -0
  26. package/src/{overview-delta.js → domain/overview-delta.js} +5 -1
  27. package/src/domain/side-turn-view.js +73 -0
  28. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  29. package/src/infra/git.js +30 -0
  30. package/src/infra/process.js +59 -0
  31. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  32. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  33. package/src/infra/store/db.js +265 -0
  34. package/src/infra/store/events.js +146 -0
  35. package/src/infra/store/facts.js +338 -0
  36. package/src/infra/store/reconcile.js +172 -0
  37. package/src/infra/store/records.js +160 -0
  38. package/src/infra/store/runner-readers.js +16 -0
  39. package/src/infra/store/schema.js +306 -0
  40. package/src/infra/store/sessions.js +138 -0
  41. package/src/infra/store/tasks.js +307 -0
  42. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  43. package/src/{auto-update.js → infra/update/auto-update.js} +3 -4
  44. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  45. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  46. package/src/{worktree.js → infra/worktree.js} +57 -42
  47. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  48. package/src/{cleanup.js → interface/bin/cleanup.js} +3 -2
  49. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  50. package/src/{setup.js → interface/bin/setup.js} +9 -8
  51. package/src/{stage.js → interface/bin/stage.js} +1 -1
  52. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  53. package/src/interface/mcp/meta.js +7 -0
  54. package/src/interface/mcp/result.js +34 -0
  55. package/src/interface/mcp/schemas.js +24 -0
  56. package/src/interface/mcp/server.js +94 -0
  57. package/src/interface/mcp/tools/delivery.js +197 -0
  58. package/src/interface/mcp/tools/dispatch.js +267 -0
  59. package/src/interface/mcp/tools/facts.js +239 -0
  60. package/src/interface/mcp/tools/overview.js +202 -0
  61. package/src/interface/mcp/tools/poll.js +62 -0
  62. package/src/interface/mcp/tools/results.js +270 -0
  63. package/src/interface/mcp/tools/review.js +135 -0
  64. package/src/interface/mcp/tools/wait.js +145 -0
  65. package/src/interface/mcp/update-state.js +34 -0
  66. package/src/interface/mcp/views/overview.js +183 -0
  67. package/src/interface/mcp/views/task.js +223 -0
  68. package/src/interface/web/app.js +226 -0
  69. package/src/interface/web/views.js +224 -0
  70. package/src/mcp-server.js +3 -2223
  71. package/src/run-host/entry.js +23 -0
  72. package/src/run-host/finalize.js +236 -0
  73. package/src/run-host/launch.js +63 -0
  74. package/src/run-host/live-run.js +73 -0
  75. package/src/run-host/outcome-facts.js +61 -0
  76. package/src/run-host/streams.js +76 -0
  77. package/src/run-host/track.js +128 -0
  78. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  79. package/src/runners/codex/chat-chunks.js +97 -0
  80. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  81. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  82. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  83. package/src/codex-runner.js +0 -1586
  84. package/src/landing.js +0 -507
  85. package/src/task-store.js +0 -1800
  86. package/src/web-app.js +0 -425
  87. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  88. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  89. /package/src/{prompt.js → domain/prompt.js} +0 -0
  90. /package/src/{status.js → domain/status.js} +0 -0
  91. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  92. /package/src/{truncate.js → domain/truncate.js} +0 -0
  93. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  94. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  95. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  96. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  97. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  98. /package/src/{cleanup-hint.js → infra/cleanup-hint.js} +0 -0
  99. /package/src/{external-output.js → infra/external-output.js} +0 -0
  100. /package/src/{handoff.js → infra/handoff.js} +0 -0
  101. /package/src/{paths.js → infra/paths.js} +0 -0
  102. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  103. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
@@ -0,0 +1,164 @@
1
+ import "./compose.js";
2
+ import { frameWorkerPrompt } from "../domain/prompt.js";
3
+ import { ACTIVE_STATUSES } from "../domain/status.js";
4
+ import { buildHandoff } from "../infra/handoff.js";
5
+ import { appendTaskEvent } from "../infra/store/events.js";
6
+ import { getSession } from "../infra/store/sessions.js";
7
+ import { claimTaskRun, getTask, readTasks, releaseTaskRun, upsertTask } from "../infra/store/tasks.js";
8
+ import { codexRunner } from "../runners/codex/adapter.js";
9
+ import { readNativeGoalState } from "../runners/codex/goal-store.js";
10
+ import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, normalizeAcceptance } from "./acceptance.js";
11
+ import { isPidAlive } from "./cancel.js";
12
+ import { rebaseWorktree } from "./rebase.js";
13
+ import { processes } from "./run-state.js";
14
+ import { startTrackedRun } from "./start-run.js";
15
+ import { exists, resolveCommit } from "./worktree-setup.js";
16
+ import { appendFile } from "node:fs/promises";
17
+
18
+ // Continue the *same* Codex session. The worktree, thread id, ownership and
19
+ // goal are all inherited from the original task, and the row is reused so one
20
+ // logical piece of work stays one row.
21
+ //
22
+ // `rebaseOnto` names a ref, resolved in the project directory (HEAD, main, a
23
+ // sha): the worktree is moved onto it first so the worker continues on
24
+ // current code, and base_commit is recorded before the worker starts so a
25
+ // spawn failure cannot leave the row describing the old base. A rebase that
26
+ // does not go through puts the worktree back and throws with the file list;
27
+ // the worker is not started. Refused while the worker is still running.
28
+ function coded(code, message, details = undefined) {
29
+ const error = new Error(message);
30
+ error.code = code;
31
+ if (details !== undefined) error.details = details;
32
+ return error;
33
+ }
34
+
35
+ // `acceptance` replaces the stored commands when given; an empty list
36
+ // clears them. Left out, the stored commands stay.
37
+ async function refreshAcceptance(task, session, acceptance) {
38
+ const inheritedAcceptance = task.session_policy_revision == null ? task.acceptance : task.acceptance_local;
39
+ const localAcceptance = acceptance === undefined ? inheritedAcceptance : normalizeAcceptance(acceptance);
40
+ if (acceptance === undefined && !session) return task;
41
+ const commands = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(localAcceptance ?? [])]);
42
+ const updated = {
43
+ ...task,
44
+ acceptance: commands,
45
+ acceptance_local: localAcceptance,
46
+ session_policy_revision: session?.policy_revision ?? null,
47
+ acceptance_timeout_ms: commands ? (task.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS) : null,
48
+ updated_at: new Date().toISOString()
49
+ };
50
+ await upsertTask(updated);
51
+ return updated;
52
+ }
53
+
54
+ // Moves the worktree onto a newer base before the worker continues. A conflict
55
+ // is thrown back with the details and no worker is started.
56
+ async function rebaseBeforeResume(task, rebaseOnto) {
57
+ if (ACTIVE_STATUSES.has(task.status) || processes.has(task.id)) {
58
+ throw coded("worker_active", `task ${task.id} is still ${task.status}; wait for it to settle (or cancel it) before rebasing its worktree`);
59
+ }
60
+ if (!task.worktree_path) throw coded("no_worktree", `task ${task.id} ran in place and has no worktree to rebase`);
61
+ let ontoCommit;
62
+ try {
63
+ ontoCommit = resolveCommit(task.project_root, rebaseOnto);
64
+ } catch {
65
+ throw coded("invalid_rebase_onto", `rebaseOnto "${rebaseOnto}" does not resolve to a commit in ${task.project_root}`);
66
+ }
67
+ const rebase = rebaseWorktree(task, ontoCommit);
68
+ if (rebase.error) throw coded(rebase.error, rebase.reason, rebase);
69
+ if (rebase.noop || rebase.base_commit === task.base_commit) return { task, rebase };
70
+ const moved = { ...task, base_commit: rebase.base_commit, updated_at: new Date().toISOString() };
71
+ await upsertTask(moved);
72
+ return { task: moved, rebase };
73
+ }
74
+
75
+ // Only a thread with no native goal, or one explicitly stored as complete,
76
+ // can safely resume with a structured output schema. Paused, blocked,
77
+ // usage-limited and budget-limited goals are not complete; Codex can still
78
+ // activate their goal turn and reject the incompatible schema.
79
+ function resumeAllowsOutputSchema(threadId) {
80
+ const goalRead = readNativeGoalState(threadId);
81
+ return ["missing_goal", "missing_database"].includes(goalRead.state)
82
+ || (goalRead.state === "available" && goalRead.goal?.storage_status === "complete");
83
+ }
84
+
85
+ async function resumeClaimed(claimed, { prompt, rebaseOnto, acceptance }) {
86
+ const session = claimed.session_id ? await getSession(claimed.session_id) : null;
87
+ if (session?.approval_state === "waiting_user") throw coded("session_waiting_user", "session is waiting for user approval; do not resume");
88
+ let task = await refreshAcceptance(claimed, session, acceptance);
89
+ if (!task.thread_id) {
90
+ throw new Error(
91
+ `task ${task.id} has no Codex thread_id recorded. Only workers created by this version of codex-supervisor-mcp can be resumed; use create_codex_followup_worker otherwise.`
92
+ );
93
+ }
94
+ let rebase = null;
95
+ if (rebaseOnto) ({ task, rebase } = await rebaseBeforeResume(task, rebaseOnto));
96
+
97
+ const cwd = (await exists(task.cwd)) ? task.cwd : task.project_root;
98
+ const args = codexRunner.resumeArgs(task);
99
+ const outputSchema = resumeAllowsOutputSchema(task.thread_id);
100
+ const started = await startTrackedRun({
101
+ record: { ...task, resumed_from: task.resumed_from ?? task.id },
102
+ args,
103
+ prompt: frameWorkerPrompt(prompt, {
104
+ objective: task.goal_objective ?? task.title ?? task.id,
105
+ resume: true
106
+ }, { acceptance: task.acceptance, outputSchema }),
107
+ logPath: task.run_log,
108
+ outputSchema,
109
+ spawnOptions: { cwd }
110
+ });
111
+ return rebase ? { ...started.record, rebase } : started.record;
112
+ }
113
+
114
+ export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acceptance = undefined, context = undefined }) {
115
+ if (!prompt || typeof prompt !== "string") throw new Error("prompt is required");
116
+ let task = await getTask(taskId);
117
+ if (!task) throw new Error(`task not found: ${taskId}`);
118
+ if (task.guard_policy?.maxTotalMs && Date.now() - Date.parse(task.created_at) >= task.guard_policy.maxTotalMs) {
119
+ throw coded("time_quota_exceeded", "total time quota exceeded; inspect partial work and explicitly dispatch a revised budget");
120
+ }
121
+ if (context !== undefined) {
122
+ await buildHandoff({ context });
123
+ task = { ...task, input_context: { ...task.input_context, context } };
124
+ }
125
+ const claim = await claimTaskRun(taskId, task.run_count ?? 0);
126
+ if (!claim) throw coded("worker_active", `task ${taskId} is active or already claimed by another dispatcher; wait for it to settle`);
127
+ try {
128
+ return await resumeClaimed(task, { prompt, rebaseOnto, acceptance });
129
+ } finally {
130
+ await releaseTaskRun(taskId, claim);
131
+ }
132
+ }
133
+
134
+ export async function recoverEligibleRuns() {
135
+ const recovered = [];
136
+ for (const task of await readTasks()) {
137
+ if (task.guard_policy?.preflight) continue;
138
+ if ((task.run_count ?? 0) !== 1 || !task.thread_id
139
+ || !(task.run_evidence?.run === 1 || (task.run_host_pid && task.started_at)) || !task.guard_policy
140
+ || !(task.status === "lost" || task.attention_reason === "no_work" || task.attention_reason === "invalid_report")
141
+ || ["blocked", "paused", "budget_limited", "usage_limited"].includes(task.goal_status)
142
+ || /401|403|unauthori[sz]ed|not logged|permission denied|approval|rate.?limit|429/i.test(task.error ?? "")
143
+ || /time_limit|quota/.test(`${task.attention_reason ?? ""} ${task.error ?? ""}`)
144
+ || await isPidAlive(task.pid) || await isPidAlive(task.run_host_pid)) continue;
145
+ const session = task.session_id ? await getSession(task.session_id) : null;
146
+ if (session?.approval_state === "waiting_user") continue;
147
+ try {
148
+ const result = await resumeCodexWorker({ taskId: task.id,
149
+ prompt: task.attention_reason === "invalid_report"
150
+ ? "Your run finished, but the final message was not the required bare JSON report. Do not redo the work and do not edit files: reply with ONLY the JSON object with result (string), verification (string[]) and not_done (string[]), describing what you already did. No code fences, nothing before or after it."
151
+ : `One automatic recovery after ${task.attention_reason ?? task.status}. Original task: ${task.prompt}\nContinue from files already present; do not repeat completed edits. Make concrete progress, run declared checks, and report remaining blockers accurately. This is the only automatic retry.` });
152
+ const event = { type: "supervisor.recovery", automatic: true, from_run: 1, to_run: result.run_count,
153
+ reason: task.attention_reason ?? task.status, started_at: new Date().toISOString() };
154
+ await appendTaskEvent(task.id, event);
155
+ await appendFile(task.run_log, `${JSON.stringify(event)}\n`);
156
+ recovered.push({ id: task.id, run: result.run_count, reason: event.reason });
157
+ } catch (error) {
158
+ if (!["worker_active", "session_waiting_user"].includes(error.code)) {
159
+ await appendTaskEvent(task.id, { type: "supervisor.recovery_refused", reason: error.code ?? "resume_failed" });
160
+ }
161
+ }
162
+ }
163
+ return recovered;
164
+ }
@@ -0,0 +1,26 @@
1
+
2
+ export const processes = new Map();
3
+ // taskId -> control object of an acceptance run in progress ({ kill, cancelled }).
4
+ export const acceptanceRuns = new Map();
5
+ export const cancelledTasks = new Set();
6
+ export const allowedReasoningEfforts = new Set(["minimal", "low", "medium", "high"]);
7
+ export const MAX_RUN_HOST_PROMPT_BYTES = 4 * 1024 * 1024;
8
+ export const RUN_HOST_STARTUP_TIMEOUT_MS = process.platform === "win32" ? 120000 : 30000;
9
+ export const WORKTREE_LOCK_TIMEOUT_MS = 120000;
10
+
11
+ export function failedStart(record, reason) {
12
+ const now = new Date().toISOString();
13
+ return {
14
+ ok: false,
15
+ record: {
16
+ ...record,
17
+ status: "failed",
18
+ phase: null,
19
+ pid: null,
20
+ error: reason,
21
+ attention_reason: "start_failed",
22
+ completed_at: now,
23
+ updated_at: now
24
+ }
25
+ };
26
+ }
@@ -0,0 +1,28 @@
1
+ import "./compose.js";
2
+ import { readPreflightResult } from "../domain/worker-preflight.js";
3
+ import { TERMINAL_STATUSES } from "../domain/status.js";
4
+ import { isPidAlive } from "../infra/store/tasks.js";
5
+
6
+ // A terminal status is written in two steps. Codex's turn.completed event
7
+ // flips status to completed while the process is still alive and exit_code is
8
+ // still null; the process exit then writes exit_code. A wait that returned on
9
+ // the first step handed the caller a snapshot with exit_code: null, and the
10
+ // next read said 0 - two answers for one worker. A row counts as settled once
11
+ // the exit is recorded, or once nobody is left to record it.
12
+ export function isSettled(task) {
13
+ if (!TERMINAL_STATUSES.has(task.status)) return false;
14
+ if (task.attention_reason === "start_failed") return true;
15
+ if (task.guard_policy?.preflight && readPreflightResult(task).status === "passed") return true;
16
+ if (task.status !== "completed" && task.status !== "failed") return true;
17
+ // Acceptance is running in the supervisor process that owned the worker;
18
+ // the codex pid is already dead, so that process is what to wait on.
19
+ if (task.acceptance_results?.status === "running") return !isPidAlive(task.acceptance_results.supervisor_pid);
20
+ if (["interrupted", "cancelled"].includes(task.acceptance_results?.status)) {
21
+ return task.exit_code !== null && task.exit_code !== undefined;
22
+ }
23
+ if (task.exit_code !== null && task.exit_code !== undefined) return true;
24
+ // A dead Codex pid does not prove that its owner's close handler finished
25
+ // draining the stream and writing the exit status. Leave the half-written
26
+ // row for reconciliation after a short grace period, never return it.
27
+ return false;
28
+ }
@@ -22,20 +22,14 @@
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 { execFileSync, spawn } from "node:child_process";
25
+ import "./compose.js";
26
+ import { answerOf, partsFromChunks, turnView } from "../domain/side-turn-view.js";
27
+ import { closeSideSession, getSideSession, insertSideTurn, interruptRunningSideTurns, openSideSession, readSideTurns, setSideSessionFork, updateSideTurn } from "../infra/store/sessions.js";
28
+ import { codexRunner } from "../runners/codex/adapter.js";
29
+ import { chunksFor } from "../runners/codex/chat-chunks.js";
30
+ import { codexConfigText, disableMcpServerArgs } from "../runners/codex/mcp-config.js";
31
+ import { endStream, sseHead, writeChunk } from "./sse.js";
26
32
  import { randomUUID } from "node:crypto";
27
- import { codexConfigText, disableMcpServerArgs } from "./mcp-config.js";
28
- import { codexRunner } from "./runner-adapter.js";
29
- import {
30
- closeSideSession,
31
- getSideSession,
32
- insertSideTurn,
33
- interruptRunningSideTurns,
34
- openSideSession,
35
- readSideTurns,
36
- setSideSessionFork,
37
- updateSideTurn
38
- } from "./task-store.js";
39
33
 
40
34
  const TURN_TIMEOUT_MS = 10 * 60 * 1000;
41
35
 
@@ -91,7 +85,6 @@ export async function prepareSideSession(task, { fresh = false } = {}) {
91
85
  }
92
86
  return { session, refreshed };
93
87
  }
94
- const OUTPUT_CLIP = 4000;
95
88
 
96
89
  // taskId -> { turnId, child, chunks, watchers: Set<res>, startedAt, question, state }
97
90
  const running = new Map();
@@ -103,168 +96,6 @@ async function sweepOnce() {
103
96
  await interruptRunningSideTurns();
104
97
  }
105
98
 
106
- function clip(text, max = OUTPUT_CLIP) {
107
- if (typeof text !== "string") return text ?? null;
108
- return text.length <= max ? text : `${text.slice(0, max)}\n…(${text.length - max} more characters)`;
109
- }
110
-
111
- // ---- Codex event -> UI message stream chunks
112
-
113
- function chunksFor(event, state) {
114
- const item = event.item ?? {};
115
- const out = [];
116
- switch (event.type) {
117
- case "thread.started":
118
- if (event.thread_id) out.push({ type: "data-session", data: { fork_thread_id: event.thread_id } });
119
- break;
120
- case "turn.started":
121
- out.push({ type: "start-step" });
122
- break;
123
- case "item.started":
124
- case "item.updated":
125
- if (item.type === "command_execution" && !state.toolsSeen.has(item.id)) {
126
- state.toolsSeen.add(item.id);
127
- out.push({ type: "tool-input-available", toolCallId: item.id, toolName: "shell", input: { command: item.command ?? "" } });
128
- }
129
- break;
130
- case "item.completed":
131
- switch (item.type) {
132
- case "reasoning": {
133
- const id = `r-${item.id}`;
134
- out.push({ type: "reasoning-start", id }, { type: "reasoning-delta", id, delta: item.text ?? "" }, { type: "reasoning-end", id });
135
- break;
136
- }
137
- case "agent_message": {
138
- const id = `t-${item.id}`;
139
- out.push({ type: "text-start", id }, { type: "text-delta", id, delta: item.text ?? "" }, { type: "text-end", id });
140
- break;
141
- }
142
- case "command_execution":
143
- if (!state.toolsSeen.has(item.id)) {
144
- state.toolsSeen.add(item.id);
145
- out.push({ type: "tool-input-available", toolCallId: item.id, toolName: "shell", input: { command: item.command ?? "" } });
146
- }
147
- out.push({
148
- type: "tool-output-available",
149
- toolCallId: item.id,
150
- output: { exit_code: item.exit_code ?? null, status: item.status ?? null, output: clip(item.aggregated_output ?? "") }
151
- });
152
- break;
153
- case "file_change":
154
- out.push(
155
- { type: "tool-input-available", toolCallId: item.id, toolName: "edit", input: { changes: item.changes ?? [] } },
156
- { type: "tool-output-available", toolCallId: item.id, output: { status: item.status ?? "completed" } }
157
- );
158
- break;
159
- case "web_search":
160
- case "mcp_tool_call":
161
- out.push(
162
- { type: "tool-input-available", toolCallId: item.id, toolName: item.type, input: { ...item, id: undefined, type: undefined } },
163
- { type: "tool-output-available", toolCallId: item.id, output: { status: item.status ?? "completed" } }
164
- );
165
- break;
166
- case "error":
167
- // Startup notices (unknown config keys, missing model metadata) come
168
- // through as error items. They are not the answer failing.
169
- out.push({ type: "data-notice", data: { message: item.message ?? item.text ?? "" } });
170
- break;
171
- default:
172
- break;
173
- }
174
- break;
175
- case "turn.completed":
176
- out.push({ type: "finish-step" });
177
- if (event.usage) {
178
- out.push({ type: "data-usage", data: event.usage });
179
- state.usage = event.usage;
180
- }
181
- state.completed = true;
182
- break;
183
- case "turn.failed":
184
- out.push({ type: "error", errorText: event.error?.message ?? event.error ?? event.message ?? "Codex turn failed" });
185
- state.failed = true;
186
- break;
187
- case "error":
188
- out.push({ type: "data-notice", data: { message: event.message ?? event.error ?? "" } });
189
- break;
190
- default:
191
- break;
192
- }
193
- return out;
194
- }
195
-
196
- // ---- stream plumbing
197
-
198
- function sseHead(res) {
199
- res.writeHead(200, {
200
- "content-type": "text/event-stream; charset=utf-8",
201
- "cache-control": "no-cache, no-transform",
202
- connection: "keep-alive",
203
- "x-vercel-ai-ui-message-stream": "v1",
204
- "x-accel-buffering": "no"
205
- });
206
- }
207
-
208
- function writeChunk(res, chunk) {
209
- if (!res.writableEnded) res.write(`data: ${JSON.stringify(chunk)}\n\n`);
210
- }
211
-
212
- function endStream(res) {
213
- if (!res.writableEnded) res.end("data: [DONE]\n\n");
214
- }
215
-
216
- // Chunks of a turn, assembled into the UIMessage parts the page shows for a
217
- // finished (or interrupted) turn. The page rebuilds history from this.
218
- export function partsFromChunks(chunks) {
219
- const parts = [];
220
- const open = new Map(); // id -> part for text / reasoning
221
- const tools = new Map(); // toolCallId -> part
222
- for (const c of chunks) {
223
- switch (c.type) {
224
- case "text-start":
225
- open.set(c.id, { type: "text", text: "", state: "streaming" });
226
- parts.push(open.get(c.id));
227
- break;
228
- case "text-delta":
229
- if (open.has(c.id)) open.get(c.id).text += c.delta ?? "";
230
- break;
231
- case "text-end":
232
- if (open.has(c.id)) open.get(c.id).state = "done";
233
- break;
234
- case "reasoning-start":
235
- open.set(c.id, { type: "reasoning", text: "", state: "streaming" });
236
- parts.push(open.get(c.id));
237
- break;
238
- case "reasoning-delta":
239
- if (open.has(c.id)) open.get(c.id).text += c.delta ?? "";
240
- break;
241
- case "reasoning-end":
242
- if (open.has(c.id)) open.get(c.id).state = "done";
243
- break;
244
- case "tool-input-available": {
245
- const part = { type: `tool-${c.toolName}`, toolCallId: c.toolCallId, state: "input-available", input: c.input };
246
- tools.set(c.toolCallId, part);
247
- parts.push(part);
248
- break;
249
- }
250
- case "tool-output-available":
251
- if (tools.has(c.toolCallId)) {
252
- tools.get(c.toolCallId).state = "output-available";
253
- tools.get(c.toolCallId).output = c.output;
254
- }
255
- break;
256
- case "data-notice":
257
- case "data-usage":
258
- case "data-session":
259
- parts.push({ type: c.type, data: c.data });
260
- break;
261
- default:
262
- break;
263
- }
264
- }
265
- return parts;
266
- }
267
-
268
99
  // ---- public API
269
100
 
270
101
  export async function sideSessionState(taskId) {
@@ -308,67 +139,48 @@ export function attachToTurn(taskId, res) {
308
139
  return true;
309
140
  }
310
141
 
311
- // Start a turn. `res` (optional) becomes the first watcher. Resolves when the
312
- // turn has ended, however it ended.
313
- export async function runSideTurn({ task, text, res = null, fresh = false }) {
314
- await sweepOnce();
315
- 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" });
316
- if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
317
- const target = codexRunner.resolveTarget();
318
- if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
319
-
320
- const { session, refreshed } = await prepareSideSession(task, { fresh });
321
-
142
+ function startSideChild(target, task, session) {
322
143
  const args = codexRunner.forkSideArgs({ forkThreadId: session.fork_thread_id, workerThreadId: task.thread_id, model: task.model });
323
144
  args.splice(-2, 0, ...sideTurnConfigArgs(codexConfigText()));
324
-
325
145
  const cwd = task.worktree_path || task.project_root || process.cwd();
326
- const child = codexRunner.start(target, args, {
146
+ return codexRunner.start(target, args, {
327
147
  cwd,
328
148
  stdio: ["pipe", "pipe", "pipe"],
329
149
  env: { ...process.env, NO_COLOR: "1" },
330
150
  windowsHide: true
331
151
  });
152
+ }
332
153
 
154
+ // The in-memory side of a running turn: its chunks so far, who is watching,
155
+ // and how it was stopped. Chunks are written through to the store in batches.
156
+ async function openLiveTurn(task, text, child) {
333
157
  const turnId = `turn-${Date.now()}-${randomUUID().slice(0, 8)}`;
334
158
  const startedAt = new Date().toISOString();
335
- const live = { turnId, child, chunks: [], watchers: new Set(), startedAt, question: text, state: { toolsSeen: new Set(), completed: false, failed: false, usage: null } };
336
- running.set(task.id, live);
337
- await insertSideTurn({ id: turnId, task_id: task.id, question: text, status: "running", chunks: [], started_at: startedAt });
338
-
339
- let persistTimer = null;
159
+ const state = { toolsSeen: new Set(), completed: false, failed: false, usage: null };
160
+ const live = { turnId, child, chunks: [], watchers: new Set(), startedAt, question: text, state, stderr: "", stoppedBy: null, persistTimer: null };
340
161
  const persistSoon = () => {
341
- if (persistTimer) return;
342
- persistTimer = setTimeout(() => {
343
- persistTimer = null;
162
+ if (live.persistTimer) return;
163
+ live.persistTimer = setTimeout(() => {
164
+ live.persistTimer = null;
344
165
  updateSideTurn(turnId, { chunks: live.chunks }).catch(() => {});
345
166
  }, 250);
346
167
  };
347
- const broadcast = (chunk) => {
168
+ live.broadcast = (chunk) => {
348
169
  live.chunks.push(chunk);
349
170
  for (const w of live.watchers) writeChunk(w, chunk);
350
171
  persistSoon();
351
172
  };
352
-
353
- if (res) {
354
- sseHead(res);
355
- live.watchers.add(res);
356
- res.on("close", () => live.watchers.delete(res));
357
- }
358
- broadcast({ type: "start", messageId: turnId });
359
-
360
- let rest = "";
361
- let stderr = "";
362
- let stoppedBy = null;
363
- const timer = setTimeout(() => {
364
- stoppedBy = "timeout";
365
- codexRunner.cancelChild(child);
366
- }, TURN_TIMEOUT_MS);
367
173
  live.stop = (reason) => {
368
- stoppedBy = reason;
174
+ live.stoppedBy = reason;
369
175
  codexRunner.cancelChild(child);
370
176
  };
177
+ running.set(task.id, live);
178
+ await insertSideTurn({ id: turnId, task_id: task.id, question: text, status: "running", chunks: [], started_at: startedAt });
179
+ return live;
180
+ }
371
181
 
182
+ function pipeSideOutput(child, live, session, taskId) {
183
+ let rest = "";
372
184
  child.stdout.setEncoding("utf8");
373
185
  child.stdout.on("data", (chunk) => {
374
186
  rest += chunk;
@@ -385,78 +197,79 @@ export async function runSideTurn({ task, text, res = null, fresh = false }) {
385
197
  }
386
198
  if (event.type === "thread.started" && !session.fork_thread_id && event.thread_id) {
387
199
  session.fork_thread_id = event.thread_id;
388
- setSideSessionFork(task.id, event.thread_id).catch(() => {});
200
+ setSideSessionFork(taskId, event.thread_id).catch(() => {});
389
201
  }
390
- for (const part of chunksFor(event, live.state)) broadcast(part);
202
+ for (const part of chunksFor(event, live.state)) live.broadcast(part);
391
203
  }
392
204
  });
393
205
  child.stderr.setEncoding("utf8");
394
206
  child.stderr.on("data", (chunk) => {
395
- stderr = (stderr + chunk).slice(-4000);
207
+ live.stderr = (live.stderr + chunk).slice(-4000);
396
208
  });
209
+ }
210
+
211
+ // How the turn ended, and the error to show when it did not complete.
212
+ function sideTurnOutcome(live, code, signal) {
213
+ if (live.state.failed) return { status: "failed", error: live.chunks.find((c) => c.type === "error")?.errorText ?? "Codex turn failed", announce: false };
214
+ if (live.state.completed) return { status: "completed", error: null, announce: false };
215
+ if (live.stoppedBy === "timeout") {
216
+ return { status: "timed_out", error: `the side turn ran past ${TURN_TIMEOUT_MS / 60000} minutes and was stopped`, announce: true };
217
+ }
218
+ if (live.stoppedBy) return { status: "stopped", error: "stopped", announce: true };
219
+ const tail = live.stderr.trim().split("\n").filter((l) => !l.includes("rmcp::transport")).slice(-3).join("\n");
220
+ const why = signal ? `stopped by ${signal}` : `codex exited with code ${code}`;
221
+ return { status: "failed", error: tail ? `${why}: ${tail}` : why, announce: true };
222
+ }
223
+
224
+ async function settleSideTurn(live, taskId, code, signal) {
225
+ if (live.persistTimer) clearTimeout(live.persistTimer);
226
+ const { status, error, announce } = sideTurnOutcome(live, code, signal);
227
+ if (announce) live.broadcast({ type: "error", errorText: error });
228
+ live.broadcast({ type: "finish" });
229
+ for (const w of live.watchers) endStream(w);
230
+ live.watchers.clear();
231
+ running.delete(taskId);
232
+ await updateSideTurn(live.turnId, { status, chunks: live.chunks, usage: live.state.usage, error, ended_at: new Date().toISOString() }).catch(() => {});
233
+ return status;
234
+ }
235
+
236
+ // Start a turn. `res` (optional) becomes the first watcher. Resolves when the
237
+ // turn has ended, however it ended.
238
+ export async function runSideTurn({ task, text, res = null, fresh = false }) {
239
+ await sweepOnce();
240
+ 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" });
241
+ if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
242
+ const target = codexRunner.resolveTarget();
243
+ if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
244
+
245
+ const { session, refreshed } = await prepareSideSession(task, { fresh });
246
+ const child = startSideChild(target, task, session);
247
+ const live = await openLiveTurn(task, text, child);
248
+ if (res) {
249
+ sseHead(res);
250
+ live.watchers.add(res);
251
+ res.on("close", () => live.watchers.delete(res));
252
+ }
253
+ live.broadcast({ type: "start", messageId: live.turnId });
254
+ const timer = setTimeout(() => live.stop("timeout"), TURN_TIMEOUT_MS);
255
+ pipeSideOutput(child, live, session, task.id);
397
256
  child.stdin.on("error", () => {});
398
257
  child.stdin.end(sideQuestionText(text));
399
258
 
400
259
  return new Promise((resolve) => {
401
260
  const finish = async (code, signal) => {
402
261
  clearTimeout(timer);
403
- if (persistTimer) clearTimeout(persistTimer);
404
- let status = "completed";
405
- let error = null;
406
- if (live.state.failed) {
407
- status = "failed";
408
- error = live.chunks.find((c) => c.type === "error")?.errorText ?? "Codex turn failed";
409
- } else if (!live.state.completed) {
410
- if (stoppedBy === "timeout") {
411
- status = "timed_out";
412
- error = `the side turn ran past ${TURN_TIMEOUT_MS / 60000} minutes and was stopped`;
413
- } else if (stoppedBy) {
414
- status = "stopped";
415
- error = "stopped";
416
- } else {
417
- status = "failed";
418
- const tail = stderr.trim().split("\n").filter((l) => !l.includes("rmcp::transport")).slice(-3).join("\n");
419
- const why = signal ? `stopped by ${signal}` : `codex exited with code ${code}`;
420
- error = tail ? `${why}: ${tail}` : why;
421
- }
422
- broadcast({ type: "error", errorText: error });
423
- }
424
- broadcast({ type: "finish" });
425
- for (const w of live.watchers) endStream(w);
426
- live.watchers.clear();
427
- running.delete(task.id);
428
- await updateSideTurn(turnId, { status, chunks: live.chunks, usage: live.state.usage, error, ended_at: new Date().toISOString() }).catch(() => {});
429
- resolve({ status, turnId, forkThreadId: session.fork_thread_id, refreshed });
262
+ const status = await settleSideTurn(live, task.id, code, signal);
263
+ resolve({ status, turnId: live.turnId, forkThreadId: session.fork_thread_id, refreshed });
430
264
  };
431
265
  child.on("error", (error) => {
432
- stderr += `\nfailed to start codex: ${error.message}`;
266
+ live.stderr += `\nfailed to start codex: ${error.message}`;
433
267
  finish(-1, null);
434
268
  });
435
269
  child.on("exit", finish);
436
270
  });
437
271
  }
438
272
 
439
- // The answer of a turn, as the text parts joined; null while nothing has
440
- // been said yet.
441
- function answerOf(turn) {
442
- const parts = partsFromChunks(turn.chunks ?? []);
443
- const text = parts.filter((p) => p.type === "text").map((p) => p.text).join("\n").trim();
444
- return text || null;
445
- }
446
-
447
- function turnView(turn) {
448
- return {
449
- turn_id: turn.id,
450
- question: turn.question,
451
- status: turn.status,
452
- answer: answerOf(turn),
453
- usage: turn.usage ?? null,
454
- error: turn.error ?? null,
455
- started_at: turn.started_at ?? null,
456
- ended_at: turn.ended_at ?? null
457
- };
458
- }
459
-
460
273
  // The newest side turn of a worker, for a caller that asked earlier and
461
274
  // comes back for the answer. Null when nothing was ever asked.
462
275
  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
+ }