codex-supervisor-mcp 0.5.8 → 0.6.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.
- package/README.en.md +8 -4
- package/README.md +7 -3
- package/package.json +3 -1
- package/skills/codex-supervisor/SKILL.md +13 -1
- package/src/codex-runner.js +6 -0
- package/src/side-chat.js +425 -0
- package/src/task-store.js +105 -0
- package/src/web-app.js +422 -0
- package/src/web-server.js +39 -292
- package/web/dist/assets/index-DI1hLMxE.css +2 -0
- package/web/dist/assets/index-Dne-82WY.js +154 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-DPTvsjxI.js +0 -85
- package/web/dist/assets/index-DnCjDsN6.css +0 -2
package/README.en.md
CHANGED
|
@@ -82,7 +82,9 @@ npx -p codex-supervisor-mcp codex-supervisor-web
|
|
|
82
82
|
|
|
83
83
|
Open `http://127.0.0.1:7877`. The left column lists sessions with the title given at dispatch and how many workers are still running; a session opens into its worker ledger; a worker opens a drawer with its full report, change list, commands, event stream, task text and token usage. It refreshes every 2.5 seconds while something runs, every 8 seconds otherwise.
|
|
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
|
+
|
|
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.
|
|
86
88
|
|
|
87
89
|
## What the board shows
|
|
88
90
|
|
|
@@ -91,9 +93,10 @@ Open `http://127.0.0.1:7877`. The left column lists sessions with the title give
|
|
|
91
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 |
|
|
92
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 |
|
|
93
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 |
|
|
94
|
-
| Worker drawer |
|
|
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 |
|
|
95
98
|
|
|
96
|
-
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.
|
|
97
100
|
|
|
98
101
|
## Tools
|
|
99
102
|
|
|
@@ -284,7 +287,8 @@ rm -rf ~/.codex-supervisor
|
|
|
284
287
|
| `Cannot find module 'node:sqlite'` | Node older than 22.13.0 | Upgrade Node |
|
|
285
288
|
| Worker stuck in `lost` | The MCP process was killed and the worker orphaned | `resume_codex_worker`, or dispatch again |
|
|
286
289
|
| `ownedPaths overlap with active worker(s)` | Two workers claimed the same paths | Split differently, or cancel the one holding them |
|
|
287
|
-
| The board is empty | The board and the MCP use different `SUPERVISOR_HOME`s | Start
|
|
290
|
+
| The board is empty | The board and the MCP use different `SUPERVISOR_HOME`s | Start it inside a project with a `.mcp.json`, or pass the same `SUPERVISOR_HOME`; the second startup line names the store in use |
|
|
291
|
+
| `port 7877 ... is already in use` | A board is already running | Open `http://127.0.0.1:7877`, or start a second one with `SUPERVISOR_WEB_PORT=8080` |
|
|
288
292
|
|
|
289
293
|
## Known limitations
|
|
290
294
|
|
package/README.md
CHANGED
|
@@ -82,7 +82,9 @@ npx -p codex-supervisor-mcp codex-supervisor-web
|
|
|
82
82
|
|
|
83
83
|
打开 `http://127.0.0.1:7877`。左栏按 session 列,显示派单时写的标题和还有几路在跑;点进去是这个 session 的 worker 台账;再点一路,右边抽屉是它的完整汇报、改动清单、命令、事件流、任务书和 token 消耗。有 worker 在跑时 2.5 秒刷一次,静止时 8 秒。
|
|
84
84
|
|
|
85
|
-
|
|
85
|
+
它读哪个状态目录:环境里有 `SUPERVISOR_HOME` 就用它;没有就从当前目录往上找 `.mcp.json`,里面 `codex-supervisor` 配了 `SUPERVISOR_HOME` 就用那个;都没有才用默认的 `~/.codex-supervisor`。启动时会打印用的是哪个、从哪来的。在项目目录里敲一下就对上了,不用再传路径。
|
|
86
|
+
|
|
87
|
+
端口用 `SUPERVISOR_WEB_PORT` 改。端口被占(多半是已经有一个看板在跑)会直接说明并退出。看板不派单也不取消;「旁问」会起一个只读的 Codex 旁路会话,见下面。
|
|
86
88
|
|
|
87
89
|
## 看板里有什么
|
|
88
90
|
|
|
@@ -91,7 +93,8 @@ npx -p codex-supervisor-mcp codex-supervisor-web
|
|
|
91
93
|
| 左栏 | 每个 session 一行:标题(派单时的 `session_title`,没写就用各路 goal 拼一句)、worker 数、几路在跑、最近活动时间。左下角是当前版本和更新提示 |
|
|
92
94
|
| session 页 | 标题、说明、首次派单和最近活动时间;一行统计(总数 / 运行中 / 完成 / 失败 / 丢失);有 worker 在跑时列出每路正在执行的命令,静止时给最近一条汇报 |
|
|
93
95
|
| worker 台账 | 一行一路:状态、标题、正在跑的命令或最后一句汇报、耗时、改了几个文件(按 worktree 真实 diff 算,含已 commit 的)、跑了几条命令、更新时间。鼠标停在标题上弹出 goal 全文、负责的路径、分支 |
|
|
94
|
-
| worker 抽屉 |
|
|
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,问不了 |
|
|
95
98
|
|
|
96
99
|
浅色深色跟系统走。只用系统字体,没有外网资源。
|
|
97
100
|
|
|
@@ -284,7 +287,8 @@ rm -rf ~/.codex-supervisor
|
|
|
284
287
|
| `Cannot find module 'node:sqlite'` | Node 低于 22.13.0 | 升 Node |
|
|
285
288
|
| worker 卡在 `lost` | MCP 进程被杀,worker 成孤儿 | `resume_codex_worker` 接回,或重派 |
|
|
286
289
|
| `ownedPaths overlap with active worker(s)` | 两路认领了同一片路径 | 改拆法,或先取消占着的那路 |
|
|
287
|
-
| 看板打开是空的 | 看板和 MCP 的 `SUPERVISOR_HOME` 不是同一个 |
|
|
290
|
+
| 看板打开是空的 | 看板和 MCP 的 `SUPERVISOR_HOME` 不是同一个 | 在配了 `.mcp.json` 的项目目录里起,或者显式传同一个 `SUPERVISOR_HOME`;启动日志第二行写了它用的哪个 |
|
|
291
|
+
| `port 7877 ... is already in use` | 已经有一个看板在跑 | 直接开 `http://127.0.0.1:7877`,或 `SUPERVISOR_WEB_PORT=8080` 再起一个 |
|
|
288
292
|
|
|
289
293
|
## 已知限制
|
|
290
294
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-supervisor-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
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",
|
|
@@ -43,6 +43,8 @@
|
|
|
43
43
|
"src/cleanup.js",
|
|
44
44
|
"src/monitor.jsx",
|
|
45
45
|
"src/web-server.js",
|
|
46
|
+
"src/web-app.js",
|
|
47
|
+
"src/side-chat.js",
|
|
46
48
|
"src/update-check.js",
|
|
47
49
|
"web/dist/",
|
|
48
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
|
|
package/src/codex-runner.js
CHANGED
|
@@ -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
|
};
|
package/src/side-chat.js
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
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 { 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
|
+
function clip(text, max = OUTPUT_CLIP) {
|
|
62
|
+
if (typeof text !== "string") return text ?? null;
|
|
63
|
+
return text.length <= max ? text : `${text.slice(0, max)}\n…(${text.length - max} more characters)`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ---- Codex event -> UI message stream chunks
|
|
67
|
+
|
|
68
|
+
function chunksFor(event, state) {
|
|
69
|
+
const item = event.item ?? {};
|
|
70
|
+
const out = [];
|
|
71
|
+
switch (event.type) {
|
|
72
|
+
case "thread.started":
|
|
73
|
+
if (event.thread_id) out.push({ type: "data-session", data: { fork_thread_id: event.thread_id } });
|
|
74
|
+
break;
|
|
75
|
+
case "turn.started":
|
|
76
|
+
out.push({ type: "start-step" });
|
|
77
|
+
break;
|
|
78
|
+
case "item.started":
|
|
79
|
+
case "item.updated":
|
|
80
|
+
if (item.type === "command_execution" && !state.toolsSeen.has(item.id)) {
|
|
81
|
+
state.toolsSeen.add(item.id);
|
|
82
|
+
out.push({ type: "tool-input-available", toolCallId: item.id, toolName: "shell", input: { command: item.command ?? "" } });
|
|
83
|
+
}
|
|
84
|
+
break;
|
|
85
|
+
case "item.completed":
|
|
86
|
+
switch (item.type) {
|
|
87
|
+
case "reasoning": {
|
|
88
|
+
const id = `r-${item.id}`;
|
|
89
|
+
out.push({ type: "reasoning-start", id }, { type: "reasoning-delta", id, delta: item.text ?? "" }, { type: "reasoning-end", id });
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
case "agent_message": {
|
|
93
|
+
const id = `t-${item.id}`;
|
|
94
|
+
out.push({ type: "text-start", id }, { type: "text-delta", id, delta: item.text ?? "" }, { type: "text-end", id });
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
case "command_execution":
|
|
98
|
+
if (!state.toolsSeen.has(item.id)) {
|
|
99
|
+
state.toolsSeen.add(item.id);
|
|
100
|
+
out.push({ type: "tool-input-available", toolCallId: item.id, toolName: "shell", input: { command: item.command ?? "" } });
|
|
101
|
+
}
|
|
102
|
+
out.push({
|
|
103
|
+
type: "tool-output-available",
|
|
104
|
+
toolCallId: item.id,
|
|
105
|
+
output: { exit_code: item.exit_code ?? null, status: item.status ?? null, output: clip(item.aggregated_output ?? "") }
|
|
106
|
+
});
|
|
107
|
+
break;
|
|
108
|
+
case "file_change":
|
|
109
|
+
out.push(
|
|
110
|
+
{ type: "tool-input-available", toolCallId: item.id, toolName: "edit", input: { changes: item.changes ?? [] } },
|
|
111
|
+
{ type: "tool-output-available", toolCallId: item.id, output: { status: item.status ?? "completed" } }
|
|
112
|
+
);
|
|
113
|
+
break;
|
|
114
|
+
case "web_search":
|
|
115
|
+
case "mcp_tool_call":
|
|
116
|
+
out.push(
|
|
117
|
+
{ type: "tool-input-available", toolCallId: item.id, toolName: item.type, input: { ...item, id: undefined, type: undefined } },
|
|
118
|
+
{ type: "tool-output-available", toolCallId: item.id, output: { status: item.status ?? "completed" } }
|
|
119
|
+
);
|
|
120
|
+
break;
|
|
121
|
+
case "error":
|
|
122
|
+
// Startup notices (unknown config keys, missing model metadata) come
|
|
123
|
+
// through as error items. They are not the answer failing.
|
|
124
|
+
out.push({ type: "data-notice", data: { message: item.message ?? item.text ?? "" } });
|
|
125
|
+
break;
|
|
126
|
+
default:
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
break;
|
|
130
|
+
case "turn.completed":
|
|
131
|
+
out.push({ type: "finish-step" });
|
|
132
|
+
if (event.usage) {
|
|
133
|
+
out.push({ type: "data-usage", data: event.usage });
|
|
134
|
+
state.usage = event.usage;
|
|
135
|
+
}
|
|
136
|
+
state.completed = true;
|
|
137
|
+
break;
|
|
138
|
+
case "turn.failed":
|
|
139
|
+
out.push({ type: "error", errorText: event.error?.message ?? event.error ?? event.message ?? "Codex turn failed" });
|
|
140
|
+
state.failed = true;
|
|
141
|
+
break;
|
|
142
|
+
case "error":
|
|
143
|
+
out.push({ type: "data-notice", data: { message: event.message ?? event.error ?? "" } });
|
|
144
|
+
break;
|
|
145
|
+
default:
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ---- stream plumbing
|
|
152
|
+
|
|
153
|
+
function sseHead(res) {
|
|
154
|
+
res.writeHead(200, {
|
|
155
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
156
|
+
"cache-control": "no-cache, no-transform",
|
|
157
|
+
connection: "keep-alive",
|
|
158
|
+
"x-vercel-ai-ui-message-stream": "v1",
|
|
159
|
+
"x-accel-buffering": "no"
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function writeChunk(res, chunk) {
|
|
164
|
+
if (!res.writableEnded) res.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function endStream(res) {
|
|
168
|
+
if (!res.writableEnded) res.end("data: [DONE]\n\n");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Chunks of a turn, assembled into the UIMessage parts the page shows for a
|
|
172
|
+
// finished (or interrupted) turn. The page rebuilds history from this.
|
|
173
|
+
export function partsFromChunks(chunks) {
|
|
174
|
+
const parts = [];
|
|
175
|
+
const open = new Map(); // id -> part for text / reasoning
|
|
176
|
+
const tools = new Map(); // toolCallId -> part
|
|
177
|
+
for (const c of chunks) {
|
|
178
|
+
switch (c.type) {
|
|
179
|
+
case "text-start":
|
|
180
|
+
open.set(c.id, { type: "text", text: "", state: "streaming" });
|
|
181
|
+
parts.push(open.get(c.id));
|
|
182
|
+
break;
|
|
183
|
+
case "text-delta":
|
|
184
|
+
if (open.has(c.id)) open.get(c.id).text += c.delta ?? "";
|
|
185
|
+
break;
|
|
186
|
+
case "text-end":
|
|
187
|
+
if (open.has(c.id)) open.get(c.id).state = "done";
|
|
188
|
+
break;
|
|
189
|
+
case "reasoning-start":
|
|
190
|
+
open.set(c.id, { type: "reasoning", text: "", state: "streaming" });
|
|
191
|
+
parts.push(open.get(c.id));
|
|
192
|
+
break;
|
|
193
|
+
case "reasoning-delta":
|
|
194
|
+
if (open.has(c.id)) open.get(c.id).text += c.delta ?? "";
|
|
195
|
+
break;
|
|
196
|
+
case "reasoning-end":
|
|
197
|
+
if (open.has(c.id)) open.get(c.id).state = "done";
|
|
198
|
+
break;
|
|
199
|
+
case "tool-input-available": {
|
|
200
|
+
const part = { type: `tool-${c.toolName}`, toolCallId: c.toolCallId, state: "input-available", input: c.input };
|
|
201
|
+
tools.set(c.toolCallId, part);
|
|
202
|
+
parts.push(part);
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
case "tool-output-available":
|
|
206
|
+
if (tools.has(c.toolCallId)) {
|
|
207
|
+
tools.get(c.toolCallId).state = "output-available";
|
|
208
|
+
tools.get(c.toolCallId).output = c.output;
|
|
209
|
+
}
|
|
210
|
+
break;
|
|
211
|
+
case "data-notice":
|
|
212
|
+
case "data-usage":
|
|
213
|
+
case "data-session":
|
|
214
|
+
parts.push({ type: c.type, data: c.data });
|
|
215
|
+
break;
|
|
216
|
+
default:
|
|
217
|
+
break;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return parts;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ---- public API
|
|
224
|
+
|
|
225
|
+
export async function sideSessionState(taskId) {
|
|
226
|
+
await sweepOnce();
|
|
227
|
+
const session = await getSideSession(taskId);
|
|
228
|
+
const live = running.get(taskId) ?? null;
|
|
229
|
+
const turns = (await readSideTurns(taskId)).map((t) => ({
|
|
230
|
+
id: t.id,
|
|
231
|
+
question: t.question,
|
|
232
|
+
status: t.status,
|
|
233
|
+
started_at: t.started_at,
|
|
234
|
+
ended_at: t.ended_at,
|
|
235
|
+
usage: t.usage,
|
|
236
|
+
error: t.error,
|
|
237
|
+
parts: partsFromChunks(t.chunks)
|
|
238
|
+
}));
|
|
239
|
+
return {
|
|
240
|
+
active: Boolean(session),
|
|
241
|
+
fork_thread_id: session?.fork_thread_id ?? null,
|
|
242
|
+
busy: Boolean(live),
|
|
243
|
+
busy_since: live?.startedAt ?? null,
|
|
244
|
+
busy_turn_id: live?.turnId ?? null,
|
|
245
|
+
watchers: live ? live.watchers.size : 0,
|
|
246
|
+
turns
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Attach a page to the running turn: replay what it has produced so far,
|
|
251
|
+
// then keep it in the audience. 204 when nothing is running.
|
|
252
|
+
export function attachToTurn(taskId, res) {
|
|
253
|
+
const live = running.get(taskId);
|
|
254
|
+
if (!live) {
|
|
255
|
+
res.writeHead(204);
|
|
256
|
+
res.end();
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
sseHead(res);
|
|
260
|
+
for (const chunk of live.chunks) writeChunk(res, chunk);
|
|
261
|
+
live.watchers.add(res);
|
|
262
|
+
res.on("close", () => live.watchers.delete(res));
|
|
263
|
+
return true;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Start a turn. `res` (optional) becomes the first watcher. Resolves when the
|
|
267
|
+
// turn has ended, however it ended.
|
|
268
|
+
export async function runSideTurn({ task, text, res = null }) {
|
|
269
|
+
await sweepOnce();
|
|
270
|
+
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" });
|
|
271
|
+
if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
|
|
272
|
+
const target = codexTarget();
|
|
273
|
+
if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
|
|
274
|
+
|
|
275
|
+
let session = await getSideSession(task.id);
|
|
276
|
+
if (!session) session = await openSideSession(task.id);
|
|
277
|
+
|
|
278
|
+
const args = session.fork_thread_id
|
|
279
|
+
? ["exec", "resume", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"']
|
|
280
|
+
: ["exec", "fork", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"'];
|
|
281
|
+
if (task.model) args.push("-m", task.model);
|
|
282
|
+
args.push(session.fork_thread_id ?? task.thread_id, "-");
|
|
283
|
+
|
|
284
|
+
const cwd = task.worktree_path || task.project_root || process.cwd();
|
|
285
|
+
const child = spawn(target.cmd, [...target.prefixArgs, ...args], {
|
|
286
|
+
cwd,
|
|
287
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
288
|
+
env: { ...process.env, NO_COLOR: "1" },
|
|
289
|
+
windowsHide: true
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
const turnId = `turn-${Date.now()}-${randomUUID().slice(0, 8)}`;
|
|
293
|
+
const startedAt = new Date().toISOString();
|
|
294
|
+
const live = { turnId, child, chunks: [], watchers: new Set(), startedAt, question: text, state: { toolsSeen: new Set(), completed: false, failed: false, usage: null } };
|
|
295
|
+
running.set(task.id, live);
|
|
296
|
+
await insertSideTurn({ id: turnId, task_id: task.id, question: text, status: "running", chunks: [], started_at: startedAt });
|
|
297
|
+
|
|
298
|
+
let persistTimer = null;
|
|
299
|
+
const persistSoon = () => {
|
|
300
|
+
if (persistTimer) return;
|
|
301
|
+
persistTimer = setTimeout(() => {
|
|
302
|
+
persistTimer = null;
|
|
303
|
+
updateSideTurn(turnId, { chunks: live.chunks }).catch(() => {});
|
|
304
|
+
}, 250);
|
|
305
|
+
};
|
|
306
|
+
const broadcast = (chunk) => {
|
|
307
|
+
live.chunks.push(chunk);
|
|
308
|
+
for (const w of live.watchers) writeChunk(w, chunk);
|
|
309
|
+
persistSoon();
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
if (res) {
|
|
313
|
+
sseHead(res);
|
|
314
|
+
live.watchers.add(res);
|
|
315
|
+
res.on("close", () => live.watchers.delete(res));
|
|
316
|
+
}
|
|
317
|
+
broadcast({ type: "start", messageId: turnId });
|
|
318
|
+
|
|
319
|
+
let rest = "";
|
|
320
|
+
let stderr = "";
|
|
321
|
+
let stoppedBy = null;
|
|
322
|
+
const timer = setTimeout(() => {
|
|
323
|
+
stoppedBy = "timeout";
|
|
324
|
+
child.kill("SIGTERM");
|
|
325
|
+
}, TURN_TIMEOUT_MS);
|
|
326
|
+
live.stop = (reason) => {
|
|
327
|
+
stoppedBy = reason;
|
|
328
|
+
child.kill("SIGTERM");
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
child.stdout.setEncoding("utf8");
|
|
332
|
+
child.stdout.on("data", (chunk) => {
|
|
333
|
+
rest += chunk;
|
|
334
|
+
let nl;
|
|
335
|
+
while ((nl = rest.indexOf("\n")) !== -1) {
|
|
336
|
+
const line = rest.slice(0, nl).trim();
|
|
337
|
+
rest = rest.slice(nl + 1);
|
|
338
|
+
if (!line) continue;
|
|
339
|
+
let event;
|
|
340
|
+
try {
|
|
341
|
+
event = JSON.parse(line);
|
|
342
|
+
} catch {
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
if (event.type === "thread.started" && !session.fork_thread_id && event.thread_id) {
|
|
346
|
+
session.fork_thread_id = event.thread_id;
|
|
347
|
+
setSideSessionFork(task.id, event.thread_id).catch(() => {});
|
|
348
|
+
}
|
|
349
|
+
for (const part of chunksFor(event, live.state)) broadcast(part);
|
|
350
|
+
}
|
|
351
|
+
});
|
|
352
|
+
child.stderr.setEncoding("utf8");
|
|
353
|
+
child.stderr.on("data", (chunk) => {
|
|
354
|
+
stderr = (stderr + chunk).slice(-4000);
|
|
355
|
+
});
|
|
356
|
+
child.stdin.on("error", () => {});
|
|
357
|
+
child.stdin.end(text);
|
|
358
|
+
|
|
359
|
+
return new Promise((resolve) => {
|
|
360
|
+
const finish = async (code, signal) => {
|
|
361
|
+
clearTimeout(timer);
|
|
362
|
+
if (persistTimer) clearTimeout(persistTimer);
|
|
363
|
+
let status = "completed";
|
|
364
|
+
let error = null;
|
|
365
|
+
if (live.state.failed) {
|
|
366
|
+
status = "failed";
|
|
367
|
+
error = live.chunks.find((c) => c.type === "error")?.errorText ?? "Codex turn failed";
|
|
368
|
+
} else if (!live.state.completed) {
|
|
369
|
+
if (stoppedBy === "timeout") {
|
|
370
|
+
status = "timed_out";
|
|
371
|
+
error = `the side turn ran past ${TURN_TIMEOUT_MS / 60000} minutes and was stopped`;
|
|
372
|
+
} else if (stoppedBy) {
|
|
373
|
+
status = "stopped";
|
|
374
|
+
error = "stopped";
|
|
375
|
+
} else {
|
|
376
|
+
status = "failed";
|
|
377
|
+
const tail = stderr.trim().split("\n").filter((l) => !l.includes("rmcp::transport")).slice(-3).join("\n");
|
|
378
|
+
const why = signal ? `stopped by ${signal}` : `codex exited with code ${code}`;
|
|
379
|
+
error = tail ? `${why}: ${tail}` : why;
|
|
380
|
+
}
|
|
381
|
+
broadcast({ type: "error", errorText: error });
|
|
382
|
+
}
|
|
383
|
+
broadcast({ type: "finish" });
|
|
384
|
+
for (const w of live.watchers) endStream(w);
|
|
385
|
+
live.watchers.clear();
|
|
386
|
+
running.delete(task.id);
|
|
387
|
+
await updateSideTurn(turnId, { status, chunks: live.chunks, usage: live.state.usage, error, ended_at: new Date().toISOString() }).catch(() => {});
|
|
388
|
+
resolve({ status, turnId, forkThreadId: session.fork_thread_id });
|
|
389
|
+
};
|
|
390
|
+
child.on("error", (error) => {
|
|
391
|
+
stderr += `\nfailed to start codex: ${error.message}`;
|
|
392
|
+
finish(-1, null);
|
|
393
|
+
});
|
|
394
|
+
child.on("exit", finish);
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
export function stopSideTurn(taskId) {
|
|
399
|
+
const live = running.get(taskId);
|
|
400
|
+
if (!live) return { stopped: false };
|
|
401
|
+
live.stop("user");
|
|
402
|
+
return { stopped: true, turn_id: live.turnId };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// Close the side session: stop a running turn, delete the fork so it does
|
|
406
|
+
// not pile up in Codex's session list, forget the history.
|
|
407
|
+
export async function endSideSession(taskId) {
|
|
408
|
+
const live = running.get(taskId);
|
|
409
|
+
if (live) live.stop("ended");
|
|
410
|
+
const row = await closeSideSession(taskId);
|
|
411
|
+
if (!row) return { ended: false };
|
|
412
|
+
let deleted = false;
|
|
413
|
+
if (row.fork_thread_id) {
|
|
414
|
+
const target = codexTarget();
|
|
415
|
+
if (!target.error) {
|
|
416
|
+
deleted = await new Promise((resolve) => {
|
|
417
|
+
const child = spawn(target.cmd, [...target.prefixArgs, "delete", row.fork_thread_id], { stdio: "ignore", windowsHide: true, env: { ...process.env, NO_COLOR: "1" } });
|
|
418
|
+
const t = setTimeout(() => { child.kill("SIGTERM"); resolve(false); }, 15000);
|
|
419
|
+
child.on("exit", (code) => { clearTimeout(t); resolve(code === 0); });
|
|
420
|
+
child.on("error", () => { clearTimeout(t); resolve(false); });
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return { ended: true, fork_thread_id: row.fork_thread_id, deleted };
|
|
425
|
+
}
|