codex-supervisor-mcp 0.5.9 → 0.6.1

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.
package/README.en.md CHANGED
@@ -84,7 +84,7 @@ Open `http://127.0.0.1:7877`. The left column lists sessions with the title give
84
84
 
85
85
  Which store it opens: `SUPERVISOR_HOME` from the environment if set; otherwise the nearest `.mcp.json` above the current directory, if its `codex-supervisor` entry sets `SUPERVISOR_HOME`; otherwise the default `~/.codex-supervisor`. The startup line says which one and where it came from, so running it inside the project directory is enough.
86
86
 
87
- `SUPERVISOR_WEB_PORT` changes the port. A taken port (usually a board that is already running) is reported in one line and the process exits. The board reads. It does not dispatch or cancel.
87
+ `SUPERVISOR_WEB_PORT` changes the port. A taken port (usually a board that is already running) is reported in one line and the process exits. The board does not dispatch or cancel; the ask tab starts a read-only Codex side session, described below.
88
88
 
89
89
  ## What the board shows
90
90
 
@@ -93,9 +93,10 @@ Which store it opens: `SUPERVISOR_HOME` from the environment if set; otherwise t
93
93
  | Left column | One line per session: title (the `session_title` from dispatch, or a line built from the workers' goals when none was given), worker count, how many are running, last activity. The current version and any update notice sit at the bottom |
94
94
  | Session page | Title, note, first dispatch and last activity; a count line (total / running / completed / failed / lost); while workers run, the command each one is executing; when idle, the last report |
95
95
  | Worker ledger | One row per worker: status, title, the running command or the last line reported, time taken, files changed (the worktree's real diff, committed work included), commands run, last update. Hovering the title shows the full goal, the owned paths and the branch |
96
- | Worker drawer | Duration / exit code / run count; model, tokens, sandbox, thread, session; branch, base commit, worktree path; Codex startup notices folded away; five tabs: report (rendered markdown), changes, commands, events (virtualized), task text |
96
+ | Worker drawer | Status, title, goal, the running command and one line of numbers (duration / files / commands / tokens / exit code) at the top; seven tabs below: overview (start and end, model, sandbox, thread, branch, base commit, worktree, owned paths), report (rendered markdown), changes, commands, events (virtualized), task text, ask. The divider between the main column and the drawer drags; double-click resets it |
97
+ | Ask | A side question about this worker, the way Codex's own `/btw` works: its Codex thread is forked into a read-only side session that answers. The fork can read the worktree and any file on disk, changes nothing, and never touches the worker's own thread, running or not. The first question forks, later ones `resume` the same side session, so it is multi-turn; reasoning, the commands it ran (with exit code and output) and the answer appear step by step as Codex finishes them. Every turn's question and output is stored in the `side_turns` table: switching tabs, closing the drawer or reloading never cuts a turn off, the page re-attaches and replays; another tab can attach too, or stop it; a turn nobody watches still runs to the end and keeps its answer; a turn that was running when the board restarted is marked interrupted. "End" runs `codex delete` on the side session and clears the history. Workers dispatched before 0.5 recorded no thread id and cannot be asked |
97
98
 
98
- Light and dark follow the system. System fonts only, nothing fetched from the network.
99
+ Lists load lazily: 20 sessions per page in the rail, 40 workers per page in the ledger, the next page fetched as you scroll to the end; while something runs the loaded pages refresh every 2.5 seconds. Light and dark follow the system. System fonts only, nothing fetched from the network.
99
100
 
100
101
  ## Tools
101
102
 
package/README.md CHANGED
@@ -84,7 +84,7 @@ npx -p codex-supervisor-mcp codex-supervisor-web
84
84
 
85
85
  它读哪个状态目录:环境里有 `SUPERVISOR_HOME` 就用它;没有就从当前目录往上找 `.mcp.json`,里面 `codex-supervisor` 配了 `SUPERVISOR_HOME` 就用那个;都没有才用默认的 `~/.codex-supervisor`。启动时会打印用的是哪个、从哪来的。在项目目录里敲一下就对上了,不用再传路径。
86
86
 
87
- 端口用 `SUPERVISOR_WEB_PORT` 改。端口被占(多半是已经有一个看板在跑)会直接说明并退出。看板只读,不派单也不取消。
87
+ 端口用 `SUPERVISOR_WEB_PORT` 改。端口被占(多半是已经有一个看板在跑)会直接说明并退出。看板不派单也不取消;「旁问」会起一个只读的 Codex 旁路会话,见下面。
88
88
 
89
89
  ## 看板里有什么
90
90
 
@@ -93,7 +93,8 @@ npx -p codex-supervisor-mcp codex-supervisor-web
93
93
  | 左栏 | 每个 session 一行:标题(派单时的 `session_title`,没写就用各路 goal 拼一句)、worker 数、几路在跑、最近活动时间。左下角是当前版本和更新提示 |
94
94
  | session 页 | 标题、说明、首次派单和最近活动时间;一行统计(总数 / 运行中 / 完成 / 失败 / 丢失);有 worker 在跑时列出每路正在执行的命令,静止时给最近一条汇报 |
95
95
  | worker 台账 | 一行一路:状态、标题、正在跑的命令或最后一句汇报、耗时、改了几个文件(按 worktree 真实 diff 算,含已 commit 的)、跑了几条命令、更新时间。鼠标停在标题上弹出 goal 全文、负责的路径、分支 |
96
- | worker 抽屉 | 耗时 / 退出码 / 运行次数;模型、token、沙箱、thread、session;分支、基线提交、worktree 路径;Codex 启动提示折叠;下面五个 tab:汇报(markdown 渲染)、改动、命令、事件(虚拟滚动)、任务书 |
96
+ | worker 抽屉 | 顶上是状态、标题、goal、正在跑的命令和一行关键数字(耗时 / 文件 / 命令 / token / 退出码);下面七个 tab:概览(开始结束、模型、沙箱、thread、分支、基线、worktree、负责的路径)、汇报(markdown 渲染)、改动、命令、事件(虚拟滚动)、任务书、旁问。抽屉和中间那条分隔线可以拖,双击还原 |
97
+ | 旁问 | 对这路 worker 提问,就是 Codex 自己的 `/btw`:从它的 Codex 线程 `fork` 出一个只读旁路会话来答,能读它的 worktree 和磁盘上任何文件,改不了东西,也不碰它正在跑的活。第一问 fork,后面几问 `resume` 同一个旁路会话,可以多轮;思考、跑的命令(带退出码和输出)、答案按步骤实时出现。每一轮的问题和输出落在 sqlite 的 `side_turns` 表里:切 tab、关抽屉、刷新页面都不会断,回来自动接上回放;另一个标签页也能接上看或者停掉它;没人看的一轮照样跑完,结果留着;看板重启时正在跑的一轮标成「中断」。「结束并清空」会 `codex delete` 掉旁路会话并清掉记录。0.5 之前派的 worker 没记 thread id,问不了 |
97
98
 
98
99
  浅色深色跟系统走。只用系统字体,没有外网资源。
99
100
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-supervisor-mcp",
3
- "version": "0.5.9",
3
+ "version": "0.6.1",
4
4
  "type": "module",
5
5
  "description": "MCP server that dispatches and supervises parallel Codex CLI workers, one isolated Git worktree each, with a persisted work state machine.",
6
6
  "license": "MIT",
@@ -44,6 +44,7 @@
44
44
  "src/monitor.jsx",
45
45
  "src/web-server.js",
46
46
  "src/web-app.js",
47
+ "src/side-chat.js",
47
48
  "src/update-check.js",
48
49
  "web/dist/",
49
50
  "skills/",
@@ -27,6 +27,18 @@ description: 把 Codex CLI 当并行 worker 派活、盯进度、收结果。用
27
27
 
28
28
  `wait_codex_workers` 的等待预算管的是这一次调用,不是 worker。返回里 `still_running: true` 是等满了,不是活挂了,按 `next_step` 接着调就行。别把 `timeoutMinutes` 开到超过客户端的 MCP 工具超时——那样被掐掉的是这次调用,丢的是这次的结果。
29
29
 
30
+ ## 长任务怎么等
31
+
32
+ 一路活要跑二十分钟、一小时,正确的等法只有一种:**反复调 `wait_codex_workers`**,每次默认 2 分钟,回来看一眼 `still_running`,没完就再调。中间想省一点上下文就改调 `get_orchestration_overview`。
33
+
34
+ **不要自己写 shell 循环去 `grep` / `tail` `data/runs/<taskId>.jsonl`**,哪怕看起来更省事。原因:
35
+
36
+ - 那个文件只是 Codex 的原始输出。进程被杀、`failed`、`lost`、`exit_code` 这些只有状态机知道,文件里没有。你的循环会在一个已经死掉的 worker 上一直 `sleep`。
37
+ - `turn.completed` 出现不等于活完成:进程退出后 `exit_code` 才落,`wait` 等的是这个;resume 过的 worker 文件里有多条 `turn.completed`,按条数判断会误判。
38
+ - 用户在终端里看到的是一行 `until grep ... sleep 15` 的黑盒,不知道你在等什么、等了多久;`wait` 的返回有每路的状态和进度。
39
+
40
+ 要盯某一路的具体动作,用 `get_codex_worker_status`(`current_action` 是它正在跑的命令);要看它说了什么,用 `get_worker_result`。
41
+
30
42
  | 参数 | 怎么填 |
31
43
  |---|---|
32
44
  | `task` | 这一路具体干什么。要能让对方直接开工,别写"优化一下" |
@@ -124,7 +136,7 @@ wait_codex_workers (task_ids: [...], mode: "all")
124
136
 
125
137
  ## 看板
126
138
 
127
- 用户想用眼睛看这批活在干什么时,告诉他起 `codex-supervisor-web`(全局装过)或 `npx -p codex-supervisor-mcp codex-supervisor-web`,开 `http://127.0.0.1:7877`。看板按 session 分组,显示的就是派单时记的 `session_title`,所以标题要写得让人一眼看懂。
139
+ 用户想用眼睛看这批活在干什么时,告诉他起 `codex-supervisor-web`(全局装过)或 `npx -p codex-supervisor-mcp codex-supervisor-web`,开 `http://127.0.0.1:7877`。看板按 session 分组,显示的就是派单时记的 `session_title`,所以标题要写得让人一眼看懂。看板里每路 worker 有个「旁问」tab,用户可以直接问它(fork 出只读旁路会话,不影响 worker),所以不用替用户去 resume 一路 worker 就为了问个问题。
128
140
 
129
141
  ## 收尾
130
142
 
@@ -226,6 +226,9 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
226
226
  }
227
227
 
228
228
  const now = new Date().toISOString();
229
+ // A new run starts clean. A resumed worker used to carry the error from
230
+ // the run that was lost, so a worker that was plainly running still showed
231
+ // "process disappeared" until it finished.
229
232
  let live = {
230
233
  ...record,
231
234
  status: "running",
@@ -235,6 +238,9 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
235
238
  completed_at: null,
236
239
  exit_code: null,
237
240
  signal: null,
241
+ error: null,
242
+ current_action: null,
243
+ current_command: null,
238
244
  run_count: (record.run_count ?? 0) + 1,
239
245
  updated_at: now
240
246
  };
@@ -0,0 +1,440 @@
1
+ // Side questions about a worker, the way Codex's own /btw (/side) does it:
2
+ // the worker's thread is forked into a separate session, the question is
3
+ // asked there, and the worker's thread is never touched. The fork runs in
4
+ // the worker's worktree with a read-only sandbox, so it can read anything on
5
+ // disk and change nothing. One side session per worker; the first turn forks,
6
+ // later turns resume the fork, "end" deletes the fork.
7
+ //
8
+ // A turn is streamed to the page as an AI SDK UI message stream (SSE). The
9
+ // page is only a viewer: every chunk is also kept on the turn row, so a page
10
+ // that left (tab switched, drawer closed, reload) comes back, replays what it
11
+ // missed and keeps receiving; a turn nobody watches still runs to the end and
12
+ // its answer is there when someone looks. Only an explicit stop kills a turn.
13
+ //
14
+ // States a page has to handle:
15
+ // worker without thread_id ........ cannot ask
16
+ // no side session ................. first question forks
17
+ // session idle .................... next question resumes the fork
18
+ // turn running, page attached ..... streaming
19
+ // turn running, nobody attached ... attach: replay + tail
20
+ // turn running, other page asked .. attach the same way, or stop it
21
+ // turn finished unwatched ......... answer in the history
22
+ // turn failed / timed out / stopped error on the turn, session still usable
23
+ // board restarted mid-turn ........ turn marked interrupted
24
+ // session ended ................... fork deleted, history cleared
25
+ import { execFileSync, spawn } from "node:child_process";
26
+ import { randomUUID } from "node:crypto";
27
+ import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.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
+
39
+ const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
40
+ const TURN_TIMEOUT_MS = 10 * 60 * 1000;
41
+ const OUTPUT_CLIP = 4000;
42
+
43
+ // taskId -> { turnId, child, chunks, watchers: Set<res>, startedAt, question, state }
44
+ const running = new Map();
45
+
46
+ let swept = false;
47
+ async function sweepOnce() {
48
+ if (swept) return;
49
+ swept = true;
50
+ await interruptRunningSideTurns();
51
+ }
52
+
53
+ function codexTarget() {
54
+ const configured = process.env.CODEX_BIN?.trim();
55
+ const located = configured ? configured : (findBinaryPath("codex", { extraDirs: defaultBinDirs() }) ?? "codex");
56
+ const target = resolveCommand(located, { npmEntry: CODEX_NPM_ENTRY });
57
+ if (target.shim) return { error: shimMessage("codex", target.cmd, "CODEX_BIN") };
58
+ return { cmd: target.cmd, prefixArgs: target.prefixArgs };
59
+ }
60
+
61
+ // Stop a side turn and everything under it. On Windows the direct child is
62
+ // the JS wrapper around the native Codex binary; killing the wrapper alone
63
+ // leaves the real CLI running, so the whole tree goes through taskkill.
64
+ function killTree(child) {
65
+ if (process.platform === "win32" && child.pid) {
66
+ try {
67
+ execFileSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", timeout: 5000, windowsHide: true });
68
+ return;
69
+ } catch {
70
+ // fall back to the handle below
71
+ }
72
+ }
73
+ child.kill("SIGTERM");
74
+ }
75
+
76
+ function clip(text, max = OUTPUT_CLIP) {
77
+ if (typeof text !== "string") return text ?? null;
78
+ return text.length <= max ? text : `${text.slice(0, max)}\n…(${text.length - max} more characters)`;
79
+ }
80
+
81
+ // ---- Codex event -> UI message stream chunks
82
+
83
+ function chunksFor(event, state) {
84
+ const item = event.item ?? {};
85
+ const out = [];
86
+ switch (event.type) {
87
+ case "thread.started":
88
+ if (event.thread_id) out.push({ type: "data-session", data: { fork_thread_id: event.thread_id } });
89
+ break;
90
+ case "turn.started":
91
+ out.push({ type: "start-step" });
92
+ break;
93
+ case "item.started":
94
+ case "item.updated":
95
+ if (item.type === "command_execution" && !state.toolsSeen.has(item.id)) {
96
+ state.toolsSeen.add(item.id);
97
+ out.push({ type: "tool-input-available", toolCallId: item.id, toolName: "shell", input: { command: item.command ?? "" } });
98
+ }
99
+ break;
100
+ case "item.completed":
101
+ switch (item.type) {
102
+ case "reasoning": {
103
+ const id = `r-${item.id}`;
104
+ out.push({ type: "reasoning-start", id }, { type: "reasoning-delta", id, delta: item.text ?? "" }, { type: "reasoning-end", id });
105
+ break;
106
+ }
107
+ case "agent_message": {
108
+ const id = `t-${item.id}`;
109
+ out.push({ type: "text-start", id }, { type: "text-delta", id, delta: item.text ?? "" }, { type: "text-end", id });
110
+ break;
111
+ }
112
+ case "command_execution":
113
+ if (!state.toolsSeen.has(item.id)) {
114
+ state.toolsSeen.add(item.id);
115
+ out.push({ type: "tool-input-available", toolCallId: item.id, toolName: "shell", input: { command: item.command ?? "" } });
116
+ }
117
+ out.push({
118
+ type: "tool-output-available",
119
+ toolCallId: item.id,
120
+ output: { exit_code: item.exit_code ?? null, status: item.status ?? null, output: clip(item.aggregated_output ?? "") }
121
+ });
122
+ break;
123
+ case "file_change":
124
+ out.push(
125
+ { type: "tool-input-available", toolCallId: item.id, toolName: "edit", input: { changes: item.changes ?? [] } },
126
+ { type: "tool-output-available", toolCallId: item.id, output: { status: item.status ?? "completed" } }
127
+ );
128
+ break;
129
+ case "web_search":
130
+ case "mcp_tool_call":
131
+ out.push(
132
+ { type: "tool-input-available", toolCallId: item.id, toolName: item.type, input: { ...item, id: undefined, type: undefined } },
133
+ { type: "tool-output-available", toolCallId: item.id, output: { status: item.status ?? "completed" } }
134
+ );
135
+ break;
136
+ case "error":
137
+ // Startup notices (unknown config keys, missing model metadata) come
138
+ // through as error items. They are not the answer failing.
139
+ out.push({ type: "data-notice", data: { message: item.message ?? item.text ?? "" } });
140
+ break;
141
+ default:
142
+ break;
143
+ }
144
+ break;
145
+ case "turn.completed":
146
+ out.push({ type: "finish-step" });
147
+ if (event.usage) {
148
+ out.push({ type: "data-usage", data: event.usage });
149
+ state.usage = event.usage;
150
+ }
151
+ state.completed = true;
152
+ break;
153
+ case "turn.failed":
154
+ out.push({ type: "error", errorText: event.error?.message ?? event.error ?? event.message ?? "Codex turn failed" });
155
+ state.failed = true;
156
+ break;
157
+ case "error":
158
+ out.push({ type: "data-notice", data: { message: event.message ?? event.error ?? "" } });
159
+ break;
160
+ default:
161
+ break;
162
+ }
163
+ return out;
164
+ }
165
+
166
+ // ---- stream plumbing
167
+
168
+ function sseHead(res) {
169
+ res.writeHead(200, {
170
+ "content-type": "text/event-stream; charset=utf-8",
171
+ "cache-control": "no-cache, no-transform",
172
+ connection: "keep-alive",
173
+ "x-vercel-ai-ui-message-stream": "v1",
174
+ "x-accel-buffering": "no"
175
+ });
176
+ }
177
+
178
+ function writeChunk(res, chunk) {
179
+ if (!res.writableEnded) res.write(`data: ${JSON.stringify(chunk)}\n\n`);
180
+ }
181
+
182
+ function endStream(res) {
183
+ if (!res.writableEnded) res.end("data: [DONE]\n\n");
184
+ }
185
+
186
+ // Chunks of a turn, assembled into the UIMessage parts the page shows for a
187
+ // finished (or interrupted) turn. The page rebuilds history from this.
188
+ export function partsFromChunks(chunks) {
189
+ const parts = [];
190
+ const open = new Map(); // id -> part for text / reasoning
191
+ const tools = new Map(); // toolCallId -> part
192
+ for (const c of chunks) {
193
+ switch (c.type) {
194
+ case "text-start":
195
+ open.set(c.id, { type: "text", text: "", state: "streaming" });
196
+ parts.push(open.get(c.id));
197
+ break;
198
+ case "text-delta":
199
+ if (open.has(c.id)) open.get(c.id).text += c.delta ?? "";
200
+ break;
201
+ case "text-end":
202
+ if (open.has(c.id)) open.get(c.id).state = "done";
203
+ break;
204
+ case "reasoning-start":
205
+ open.set(c.id, { type: "reasoning", text: "", state: "streaming" });
206
+ parts.push(open.get(c.id));
207
+ break;
208
+ case "reasoning-delta":
209
+ if (open.has(c.id)) open.get(c.id).text += c.delta ?? "";
210
+ break;
211
+ case "reasoning-end":
212
+ if (open.has(c.id)) open.get(c.id).state = "done";
213
+ break;
214
+ case "tool-input-available": {
215
+ const part = { type: `tool-${c.toolName}`, toolCallId: c.toolCallId, state: "input-available", input: c.input };
216
+ tools.set(c.toolCallId, part);
217
+ parts.push(part);
218
+ break;
219
+ }
220
+ case "tool-output-available":
221
+ if (tools.has(c.toolCallId)) {
222
+ tools.get(c.toolCallId).state = "output-available";
223
+ tools.get(c.toolCallId).output = c.output;
224
+ }
225
+ break;
226
+ case "data-notice":
227
+ case "data-usage":
228
+ case "data-session":
229
+ parts.push({ type: c.type, data: c.data });
230
+ break;
231
+ default:
232
+ break;
233
+ }
234
+ }
235
+ return parts;
236
+ }
237
+
238
+ // ---- public API
239
+
240
+ export async function sideSessionState(taskId) {
241
+ await sweepOnce();
242
+ const session = await getSideSession(taskId);
243
+ const live = running.get(taskId) ?? null;
244
+ const turns = (await readSideTurns(taskId)).map((t) => ({
245
+ id: t.id,
246
+ question: t.question,
247
+ status: t.status,
248
+ started_at: t.started_at,
249
+ ended_at: t.ended_at,
250
+ usage: t.usage,
251
+ error: t.error,
252
+ parts: partsFromChunks(t.chunks)
253
+ }));
254
+ return {
255
+ active: Boolean(session),
256
+ fork_thread_id: session?.fork_thread_id ?? null,
257
+ busy: Boolean(live),
258
+ busy_since: live?.startedAt ?? null,
259
+ busy_turn_id: live?.turnId ?? null,
260
+ watchers: live ? live.watchers.size : 0,
261
+ turns
262
+ };
263
+ }
264
+
265
+ // Attach a page to the running turn: replay what it has produced so far,
266
+ // then keep it in the audience. 204 when nothing is running.
267
+ export function attachToTurn(taskId, res) {
268
+ const live = running.get(taskId);
269
+ if (!live) {
270
+ res.writeHead(204);
271
+ res.end();
272
+ return false;
273
+ }
274
+ sseHead(res);
275
+ for (const chunk of live.chunks) writeChunk(res, chunk);
276
+ live.watchers.add(res);
277
+ res.on("close", () => live.watchers.delete(res));
278
+ return true;
279
+ }
280
+
281
+ // Start a turn. `res` (optional) becomes the first watcher. Resolves when the
282
+ // turn has ended, however it ended.
283
+ export async function runSideTurn({ task, text, res = null }) {
284
+ await sweepOnce();
285
+ 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" });
286
+ if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
287
+ const target = codexTarget();
288
+ if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
289
+
290
+ let session = await getSideSession(task.id);
291
+ if (!session) session = await openSideSession(task.id);
292
+
293
+ const args = session.fork_thread_id
294
+ ? ["exec", "resume", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"']
295
+ : ["exec", "fork", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"'];
296
+ if (task.model) args.push("-m", task.model);
297
+ args.push(session.fork_thread_id ?? task.thread_id, "-");
298
+
299
+ const cwd = task.worktree_path || task.project_root || process.cwd();
300
+ const child = spawn(target.cmd, [...target.prefixArgs, ...args], {
301
+ cwd,
302
+ stdio: ["pipe", "pipe", "pipe"],
303
+ env: { ...process.env, NO_COLOR: "1" },
304
+ windowsHide: true
305
+ });
306
+
307
+ const turnId = `turn-${Date.now()}-${randomUUID().slice(0, 8)}`;
308
+ const startedAt = new Date().toISOString();
309
+ const live = { turnId, child, chunks: [], watchers: new Set(), startedAt, question: text, state: { toolsSeen: new Set(), completed: false, failed: false, usage: null } };
310
+ running.set(task.id, live);
311
+ await insertSideTurn({ id: turnId, task_id: task.id, question: text, status: "running", chunks: [], started_at: startedAt });
312
+
313
+ let persistTimer = null;
314
+ const persistSoon = () => {
315
+ if (persistTimer) return;
316
+ persistTimer = setTimeout(() => {
317
+ persistTimer = null;
318
+ updateSideTurn(turnId, { chunks: live.chunks }).catch(() => {});
319
+ }, 250);
320
+ };
321
+ const broadcast = (chunk) => {
322
+ live.chunks.push(chunk);
323
+ for (const w of live.watchers) writeChunk(w, chunk);
324
+ persistSoon();
325
+ };
326
+
327
+ if (res) {
328
+ sseHead(res);
329
+ live.watchers.add(res);
330
+ res.on("close", () => live.watchers.delete(res));
331
+ }
332
+ broadcast({ type: "start", messageId: turnId });
333
+
334
+ let rest = "";
335
+ let stderr = "";
336
+ let stoppedBy = null;
337
+ const timer = setTimeout(() => {
338
+ stoppedBy = "timeout";
339
+ killTree(child);
340
+ }, TURN_TIMEOUT_MS);
341
+ live.stop = (reason) => {
342
+ stoppedBy = reason;
343
+ killTree(child);
344
+ };
345
+
346
+ child.stdout.setEncoding("utf8");
347
+ child.stdout.on("data", (chunk) => {
348
+ rest += chunk;
349
+ let nl;
350
+ while ((nl = rest.indexOf("\n")) !== -1) {
351
+ const line = rest.slice(0, nl).trim();
352
+ rest = rest.slice(nl + 1);
353
+ if (!line) continue;
354
+ let event;
355
+ try {
356
+ event = JSON.parse(line);
357
+ } catch {
358
+ continue;
359
+ }
360
+ if (event.type === "thread.started" && !session.fork_thread_id && event.thread_id) {
361
+ session.fork_thread_id = event.thread_id;
362
+ setSideSessionFork(task.id, event.thread_id).catch(() => {});
363
+ }
364
+ for (const part of chunksFor(event, live.state)) broadcast(part);
365
+ }
366
+ });
367
+ child.stderr.setEncoding("utf8");
368
+ child.stderr.on("data", (chunk) => {
369
+ stderr = (stderr + chunk).slice(-4000);
370
+ });
371
+ child.stdin.on("error", () => {});
372
+ child.stdin.end(text);
373
+
374
+ return new Promise((resolve) => {
375
+ const finish = async (code, signal) => {
376
+ clearTimeout(timer);
377
+ if (persistTimer) clearTimeout(persistTimer);
378
+ let status = "completed";
379
+ let error = null;
380
+ if (live.state.failed) {
381
+ status = "failed";
382
+ error = live.chunks.find((c) => c.type === "error")?.errorText ?? "Codex turn failed";
383
+ } else if (!live.state.completed) {
384
+ if (stoppedBy === "timeout") {
385
+ status = "timed_out";
386
+ error = `the side turn ran past ${TURN_TIMEOUT_MS / 60000} minutes and was stopped`;
387
+ } else if (stoppedBy) {
388
+ status = "stopped";
389
+ error = "stopped";
390
+ } else {
391
+ status = "failed";
392
+ const tail = stderr.trim().split("\n").filter((l) => !l.includes("rmcp::transport")).slice(-3).join("\n");
393
+ const why = signal ? `stopped by ${signal}` : `codex exited with code ${code}`;
394
+ error = tail ? `${why}: ${tail}` : why;
395
+ }
396
+ broadcast({ type: "error", errorText: error });
397
+ }
398
+ broadcast({ type: "finish" });
399
+ for (const w of live.watchers) endStream(w);
400
+ live.watchers.clear();
401
+ running.delete(task.id);
402
+ await updateSideTurn(turnId, { status, chunks: live.chunks, usage: live.state.usage, error, ended_at: new Date().toISOString() }).catch(() => {});
403
+ resolve({ status, turnId, forkThreadId: session.fork_thread_id });
404
+ };
405
+ child.on("error", (error) => {
406
+ stderr += `\nfailed to start codex: ${error.message}`;
407
+ finish(-1, null);
408
+ });
409
+ child.on("exit", finish);
410
+ });
411
+ }
412
+
413
+ export function stopSideTurn(taskId) {
414
+ const live = running.get(taskId);
415
+ if (!live) return { stopped: false };
416
+ live.stop("user");
417
+ return { stopped: true, turn_id: live.turnId };
418
+ }
419
+
420
+ // Close the side session: stop a running turn, delete the fork so it does
421
+ // not pile up in Codex's session list, forget the history.
422
+ export async function endSideSession(taskId) {
423
+ const live = running.get(taskId);
424
+ if (live) live.stop("ended");
425
+ const row = await closeSideSession(taskId);
426
+ if (!row) return { ended: false };
427
+ let deleted = false;
428
+ if (row.fork_thread_id) {
429
+ const target = codexTarget();
430
+ if (!target.error) {
431
+ deleted = await new Promise((resolve) => {
432
+ const child = spawn(target.cmd, [...target.prefixArgs, "delete", row.fork_thread_id], { stdio: "ignore", windowsHide: true, env: { ...process.env, NO_COLOR: "1" } });
433
+ const t = setTimeout(() => { killTree(child); resolve(false); }, 15000);
434
+ child.on("exit", (code) => { clearTimeout(t); resolve(code === 0); });
435
+ child.on("error", () => { clearTimeout(t); resolve(false); });
436
+ });
437
+ }
438
+ }
439
+ return { ended: true, fork_thread_id: row.fork_thread_id, deleted };
440
+ }
package/src/task-store.js CHANGED
@@ -171,6 +171,31 @@ const SESSIONS_DDL = `
171
171
  );
172
172
  `;
173
173
 
174
+ // Side questions asked from the board. One side session per worker (the
175
+ // forked Codex thread), many turns under it. A turn keeps the stream chunks
176
+ // it produced, so a page that comes back can replay what it missed and the
177
+ // conversation survives a board restart.
178
+ const SIDE_DDL = `
179
+ CREATE TABLE IF NOT EXISTS side_sessions (
180
+ task_id TEXT PRIMARY KEY,
181
+ fork_thread_id TEXT,
182
+ created_at TEXT NOT NULL,
183
+ ended_at TEXT
184
+ );
185
+ CREATE TABLE IF NOT EXISTS side_turns (
186
+ id TEXT PRIMARY KEY,
187
+ task_id TEXT NOT NULL,
188
+ question TEXT NOT NULL,
189
+ status TEXT NOT NULL,
190
+ chunks TEXT NOT NULL DEFAULT '[]',
191
+ usage TEXT,
192
+ error TEXT,
193
+ started_at TEXT NOT NULL,
194
+ ended_at TEXT
195
+ );
196
+ CREATE INDEX IF NOT EXISTS idx_side_turns_task ON side_turns(task_id, started_at);
197
+ `;
198
+
174
199
  function sleepSync(ms) {
175
200
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
176
201
  }
@@ -205,6 +230,7 @@ function initializeSchema(dbInstance) {
205
230
  dbInstance.exec(TASK_EVENTS_INDEX_DDL);
206
231
  dbInstance.exec(TASKS_SESSION_INDEX_DDL);
207
232
  dbInstance.exec(SESSIONS_DDL);
233
+ dbInstance.exec(SIDE_DDL);
208
234
  dbInstance.exec("COMMIT;");
209
235
  } catch (error) {
210
236
  try {
@@ -437,6 +463,85 @@ export async function readSessions() {
437
463
  return openDb().prepare("SELECT * FROM sessions").all();
438
464
  }
439
465
 
466
+ // ---- side sessions and turns
467
+
468
+ export async function getSideSession(taskId) {
469
+ await ensureFilesystem();
470
+ return openDb().prepare("SELECT * FROM side_sessions WHERE task_id = ? AND ended_at IS NULL").get(taskId) ?? null;
471
+ }
472
+
473
+ export async function openSideSession(taskId) {
474
+ await ensureFilesystem();
475
+ const now = new Date().toISOString();
476
+ openDb()
477
+ .prepare(`INSERT INTO side_sessions (task_id, fork_thread_id, created_at, ended_at) VALUES (?, NULL, ?, NULL)
478
+ ON CONFLICT(task_id) DO UPDATE SET fork_thread_id = NULL, created_at = excluded.created_at, ended_at = NULL`)
479
+ .run(taskId, now);
480
+ return getSideSession(taskId);
481
+ }
482
+
483
+ export async function setSideSessionFork(taskId, forkThreadId) {
484
+ await ensureFilesystem();
485
+ openDb().prepare("UPDATE side_sessions SET fork_thread_id = ? WHERE task_id = ? AND ended_at IS NULL").run(forkThreadId, taskId);
486
+ }
487
+
488
+ export async function closeSideSession(taskId) {
489
+ await ensureFilesystem();
490
+ const db = openDb();
491
+ const row = db.prepare("SELECT * FROM side_sessions WHERE task_id = ? AND ended_at IS NULL").get(taskId) ?? null;
492
+ const now = new Date().toISOString();
493
+ db.prepare("UPDATE side_sessions SET ended_at = ? WHERE task_id = ? AND ended_at IS NULL").run(now, taskId);
494
+ db.prepare("DELETE FROM side_turns WHERE task_id = ?").run(taskId);
495
+ return row;
496
+ }
497
+
498
+ export async function insertSideTurn(turn) {
499
+ await ensureFilesystem();
500
+ openDb()
501
+ .prepare(`INSERT INTO side_turns (id, task_id, question, status, chunks, usage, error, started_at, ended_at)
502
+ VALUES (@id, @task_id, @question, @status, @chunks, @usage, @error, @started_at, @ended_at)`)
503
+ .run({
504
+ id: turn.id,
505
+ task_id: turn.task_id,
506
+ question: turn.question,
507
+ status: turn.status,
508
+ chunks: JSON.stringify(turn.chunks ?? []),
509
+ usage: turn.usage ? JSON.stringify(turn.usage) : null,
510
+ error: turn.error ?? null,
511
+ started_at: turn.started_at,
512
+ ended_at: turn.ended_at ?? null
513
+ });
514
+ }
515
+
516
+ export async function updateSideTurn(id, fields) {
517
+ await ensureFilesystem();
518
+ const sets = [];
519
+ const params = { id };
520
+ for (const [key, value] of Object.entries(fields)) {
521
+ sets.push(`${key} = @${key}`);
522
+ params[key] = key === "chunks" || key === "usage" ? (value === null ? null : JSON.stringify(value)) : value;
523
+ }
524
+ if (sets.length === 0) return;
525
+ openDb().prepare(`UPDATE side_turns SET ${sets.join(", ")} WHERE id = @id`).run(params);
526
+ }
527
+
528
+ export async function readSideTurns(taskId) {
529
+ await ensureFilesystem();
530
+ return openDb()
531
+ .prepare("SELECT * FROM side_turns WHERE task_id = ? ORDER BY started_at ASC")
532
+ .all(taskId)
533
+ .map((row) => ({ ...row, chunks: decodeJson(row.chunks, []), usage: row.usage ? decodeJson(row.usage, null) : null }));
534
+ }
535
+
536
+ // A board that restarts cannot own a turn that was running when it died.
537
+ export async function interruptRunningSideTurns() {
538
+ await ensureFilesystem();
539
+ const now = new Date().toISOString();
540
+ return openDb()
541
+ .prepare("UPDATE side_turns SET status = 'interrupted', error = COALESCE(error, 'the board restarted while this turn was running'), ended_at = ? WHERE status = 'running'")
542
+ .run(now).changes;
543
+ }
544
+
440
545
  export async function getTasks(taskIds) {
441
546
  await ensureFilesystem();
442
547
  return taskIds.map((taskId) => {