codex-supervisor-mcp 0.7.0 → 0.7.2
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 +99 -195
- package/README.md +72 -168
- package/package.json +1 -1
- package/skills/codex-supervisor/SKILL.md +53 -126
- package/src/landing.js +63 -4
- package/src/mcp-server.js +9 -7
- package/src/side-chat.js +87 -9
- package/src/task-store.js +17 -5
|
@@ -9,152 +9,79 @@ description: 把 Codex CLI 当并行 worker 派活、盯进度、收结果。用
|
|
|
9
9
|
|
|
10
10
|
## 什么时候用
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
- 活偏大,不想让它占自己的上下文
|
|
14
|
-
- 跑到一半可能断,需要能接回来
|
|
12
|
+
一批能拆开的活、活偏大不想占自己的上下文、跑到一半可能断要能接回来。一个文件的小改、纯问答、要来回确认的活,自己干更快。
|
|
15
13
|
|
|
16
|
-
|
|
14
|
+
## 派单
|
|
17
15
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
3. `create_codex_worker` 派出去。返回的是一张精简回执(`id`、`worktree_path`、`branch`、`owned_paths`、`status`),任务原文不回传,派十一路也不会把你的提示词抄十一遍。
|
|
23
|
-
4. 派完就 `wait_codex_workers` 等。默认只等 2 分钟,到点返回进度快照,worker 照跑;拿同一批 `task_ids` 接着调,直到 `timed_out: false`。默认**不带**事件(`includeEvents: false`),返回只够看状态,要事件得自己开。
|
|
24
|
-
5. 收结果走 `get_worker_result`,拿完整汇报,别一上来读事件流。
|
|
25
|
-
|
|
26
|
-
`ownedPaths` 和 `goal` 必填,不是可选项。
|
|
27
|
-
|
|
28
|
-
`wait_codex_workers` 的等待预算管的是这一次调用,不是 worker。返回里 `still_running: true` 是等满了,不是活挂了,按 `next_step` 接着调就行。别把 `timeoutMinutes` 开到超过客户端的 MCP 工具超时——那样被掐掉的是这次调用,丢的是这次的结果。
|
|
29
|
-
|
|
30
|
-
## 长任务怎么等
|
|
31
|
-
|
|
32
|
-
一路活要跑二十分钟、一小时,正确的等法只有一种:**反复调 `wait_codex_workers`**,每次默认 2 分钟,回来看一眼 `still_running`,没完就再调。只想知道完没完,带 `compact: true`,每路一行。中间想省一点上下文就改调 `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`。
|
|
16
|
+
1. 先 `search_works` 搜一下,别重复派。
|
|
17
|
+
2. 拆活。每路写清楚:干什么、能写哪些文件、怎么算做完。改同一批文件就串行,文件完全不重叠才并行。
|
|
18
|
+
3. `create_codex_worker` 派出去。回执只有 `id`、`worktree_path`、`branch`、`owned_paths`、`status`,不回传任务原文。
|
|
19
|
+
4. `wait_codex_workers` 等。默认 2 分钟,到点返回快照,worker 照跑;拿同一批 `task_ids` 接着调到 `timed_out: false`。只想知道完没完带 `compact: true`。
|
|
41
20
|
|
|
42
21
|
| 参数 | 怎么填 |
|
|
43
22
|
|---|---|
|
|
44
|
-
| `task` |
|
|
45
|
-
| `cwd` | 项目根目录。worker
|
|
46
|
-
| `ownedPaths` |
|
|
47
|
-
| `goal.objective` |
|
|
48
|
-
| `session_id` |
|
|
49
|
-
| `
|
|
50
|
-
| `
|
|
51
|
-
| `
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
## 看到 `update` 字段就转告用户
|
|
61
|
-
|
|
62
|
-
`get_orchestration_overview`、派单回执、`wait_codex_workers` 的返回里出现 `update` 且 `update_available: true`(或 `integrity_matches: false`)时,当轮回复里告诉用户一句,内容照 `notice` 说。`auto_update.state` 是 `started`、`running` 或 `done` 时,新版已经在后台装或装好了,用户只需要重开会话;`install_command` 有值才让用户自己跑它再重启 Claude Code / Codex。只说一次,不要每轮重复。用户让你查时调 `check_for_update`。
|
|
63
|
-
|
|
64
|
-
## 读结果别把上下文撑爆
|
|
65
|
-
|
|
66
|
-
按这个顺序读,能不动后面就别动:
|
|
67
|
-
|
|
68
|
-
| 想干什么 | 用哪个 | 代价 |
|
|
69
|
-
|---|---|---|
|
|
70
|
-
| 看全部 worker 现在什么状态 | `get_orchestration_overview` | ~1750 token,封顶 |
|
|
71
|
-
| 收一路活的完整结论 | `get_worker_result` | 汇报全文,大活可能上万字 |
|
|
72
|
-
| 只想知道活着还是完了 | `get_worker_summary` | 一段话 |
|
|
73
|
-
| 看某个 worker 干了什么 | `get_codex_worker_events` | 用 `limit` / `kinds` / `maxChars` 压 |
|
|
74
|
-
| 看某个 worker 的状态 | `get_codex_worker_status` | 比 overview 一行细,命令和 prompt 都裁过 |
|
|
75
|
-
| 看 goal 和 token 消耗 | `get_worker_goal` | 很小 |
|
|
76
|
-
|
|
77
|
-
**收结论必须走 `get_worker_result`。** `wait_codex_workers` 返回里的 `last_message` 会被截到 400 字只留开头,`get_orchestration_overview` 干脆不给这一列。拿截断版当结论,后面的证据、数字和结论全会漏掉。`get_worker_result` 还会带回 `status`、`exit_code`、`changed_files`,顺便就能判断是真跑完还是崩了。
|
|
78
|
-
|
|
79
|
-
**默认读回来的长文本都是裁过的**,别把裁剪当成"活没干":`current_action` 截 300 字(一条 heredoc 命令能写一整个文件,原样回传一次就是几万字)、`get_codex_worker_status` 的 `prompt` 截 300 字(要全文传 `includePrompt: true`)、`last_message` 在 overview 和 wait 里截 400 字、在 status 里截 4000 字。全量在库里:命令流看 `get_codex_worker_events`,结论看 `get_worker_result`。
|
|
80
|
-
|
|
81
|
-
`get_codex_worker_events` 的三个闸门:`kinds` 先过滤再取 `limit`;`maxChars` 把超长字符串中间截断;不知道有哪些 `kinds` 时先看返回里的 `available_kinds`。
|
|
82
|
-
|
|
83
|
-
**别做**:一次 `limit: 200` 拉全量事件。那是几万 token。
|
|
23
|
+
| `task` | 这一路具体干什么。要能直接开工,别写"优化一下" |
|
|
24
|
+
| `cwd` | 项目根目录。worker 在自己的 worktree 里干活,不动你的工作区 |
|
|
25
|
+
| `ownedPaths` | 必填。这路允许写的路径,和在跑的 worker 重叠会被拒。冲突是好事,说明该改拆法 |
|
|
26
|
+
| `goal.objective` | 必填。一句话说目标,worker 会建成 Codex 原生 goal |
|
|
27
|
+
| `session_id` | 同一批传同一个值。第一路顺手带 `session_title`(30 字内,看板和 `get_session_works` 显示它),漏了用 `describe_session` 补 |
|
|
28
|
+
| `dependsOn` | 有先后依赖填上游的 `task_id` |
|
|
29
|
+
| `baseRef` | worktree 从哪个提交切,默认 `HEAD`。第 N+1 步要建立在第 N 步上,填 `codex/<第 N 步 task_id>` |
|
|
30
|
+
| `sandbox` | 默认 `workspace-write`,worker 提交不了(Codex 把 `.git` 设成只读)。要它自己提交就 `danger-full-access`,否则收活时让 supervisor 替它提交 |
|
|
31
|
+
|
|
32
|
+
等待的几条规矩:
|
|
33
|
+
|
|
34
|
+
- 等待预算管这次调用,不管 worker。`still_running: true` 是等满了不是挂了,按 `next_step` 再调。
|
|
35
|
+
- `timeoutMinutes` 别超过客户端的 MCP 工具超时,否则被掐的是这次调用。
|
|
36
|
+
- **不要自己写 shell 循环 grep `data/runs/*.jsonl`**。进程被杀、`failed`、`lost`、`exit_code` 只有状态机知道,文件里没有;resume 过的 worker 文件里有多条 `turn.completed`;用户在终端里看到的是一行黑盒。
|
|
37
|
+
- 想省上下文改调 `get_orchestration_overview`,封顶 7000 字节。
|
|
84
38
|
|
|
85
39
|
## 收活:先看证据,再问,再改,再落
|
|
86
40
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
4. 要它改:`resume_codex_worker`,提示词里写清问题在哪,让它改完 `git commit --amend --no-edit` 并进原来那个提交,保持一步一个提交。旁路只读,改东西永远走 resume。
|
|
93
|
-
5. 过了:`land_codex_worker` 把 `codex/<id>` 上的提交 cherry-pick 到派单目录的当前分支。目标脏了、分支不对、冲突,都会拒绝并原样退回,不留半截;未提交的改动只报不落。
|
|
94
|
-
|
|
95
|
-
串行做活(第 N+1 步建立在第 N 步上)两种走法:落完第 N 步再派第 N+1 步;或者第 N+1 步派单时 `baseRef: "codex/<第 N 步的 task_id>"`,直接从它的分支开,最后只落最后一路。
|
|
96
|
-
|
|
97
|
-
## 中断了怎么接
|
|
98
|
-
|
|
99
|
-
先分清是哪种断:
|
|
100
|
-
|
|
101
|
-
| 情况 | 用什么 | 效果 |
|
|
102
|
-
|---|---|---|
|
|
103
|
-
| 想接着**同一个** Codex 会话干 | `resume_codex_worker` | 上下文不丢,`thread_id` 不变 |
|
|
104
|
-
| 想开**新会话**,带着老活的摘要干 | `create_codex_followup_worker` | 新线程,靠文本重述 |
|
|
105
|
-
| 主线程自己挂了,要找回那批活 | `get_session_works` | 按 `session_id` 列全部 |
|
|
106
|
-
|
|
107
|
-
主线程重启后第一件事:`get_session_works({ session_id })`。一次拿到那批活的清单和状态,不用凭记忆猜。
|
|
108
|
-
|
|
109
|
-
`resume_codex_worker` 只有在原任务记了 `thread_id` 时能用。没记过就用 `create_codex_followup_worker`。
|
|
110
|
-
|
|
111
|
-
## 找以前的活
|
|
41
|
+
1. `get_worker_result`:它说自己做了什么。`wait` 和 overview 里的 `last_message` 是截过的,结论必须走这里。
|
|
42
|
+
2. `get_worker_diff`:它实际做了什么。起点到工作区的全部改动,提交没提交都算;`maxChars` 管总量,`paths` 缩范围。它说过了不算,diff 对得上才算。
|
|
43
|
+
3. 对不上、看不懂为什么:`ask_codex_worker` 带 `question` 问它。fork 出一个只读旁路,worker 自己的线程不动;fork 没网络没 MCP 工具,问"改了什么、为什么、在哪",别问要联网才能答的事。超时回 `running`,只带 `task_id` 再调拿答案。worker 被 resume 过后下一问自动换新 fork,`fresh: true` 强制换,问完 `end: true` 删。
|
|
44
|
+
4. 要它改:`resume_codex_worker`,写清问题在哪,让它改完 `git commit --amend --no-edit` 并进原来那个提交。旁路只读,改东西永远走 resume。
|
|
45
|
+
5. 过了:`land_codex_worker` 把 `codex/<id>` 上的提交 cherry-pick 到派单目录当前分支。目标脏了、分支不对、冲突都拒绝并原样退回。worker 没提交(默认沙箱提交不了)就带 `commitMessage`,supervisor 在它分支上替它提交一笔再落。
|
|
112
46
|
|
|
113
|
-
`
|
|
47
|
+
一批活全部到终态后:`get_orchestration_overview` 确认没有 `needs_attention`,再逐路走上面五步。合不合、怎么合由主线程定。
|
|
114
48
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
## 状态怎么读
|
|
118
|
-
|
|
119
|
-
`status` 是生命周期,一个 work 一个值:`queued` / `running` / `completed` / `failed` / `cancelled` / `lost`。
|
|
49
|
+
## 读结果别把上下文撑爆
|
|
120
50
|
|
|
121
|
-
|
|
51
|
+
| 想干什么 | 用哪个 |
|
|
52
|
+
|---|---|
|
|
53
|
+
| 全部 worker 的状态 | `get_orchestration_overview` |
|
|
54
|
+
| 一路的完整结论 | `get_worker_result` |
|
|
55
|
+
| 一路改了什么 | `get_worker_diff` |
|
|
56
|
+
| 活着还是完了 | `get_worker_summary` |
|
|
57
|
+
| 过程 | `get_codex_worker_events`,`kinds` 先滤、`limit` 限条数、`maxChars` 截长串,先看 `available_kinds` |
|
|
58
|
+
| 一路的状态细节 | `get_codex_worker_status`,`current_action` 是它正在跑的命令 |
|
|
122
59
|
|
|
123
|
-
|
|
60
|
+
默认读回来的长文本都是裁过的(`current_action` 300 字、`prompt` 300 字、`last_message` 400 字),别把裁剪当成活没干。全量在库里。别一次 `limit: 200` 拉全量事件。
|
|
124
61
|
|
|
125
|
-
|
|
126
|
-
- `lost`:进程被外部信号杀了,或者 MCP 进程自己没了。什么都没说。**直接重跑**,不用查日志。
|
|
62
|
+
## 断了怎么接
|
|
127
63
|
|
|
128
|
-
|
|
64
|
+
| 情况 | 用什么 |
|
|
65
|
+
|---|---|
|
|
66
|
+
| 主线程自己挂了 | 先 `get_session_works({ session_id })`,一次拿回那批活 |
|
|
67
|
+
| worker 变 `lost`(MCP 进程没了把它带走了,或被信号杀了) | `resume_codex_worker`。worktree 里的改动和 `thread_id` 都在,同一线程接着干;被杀时正在做的那一步可能要重做 |
|
|
68
|
+
| worker `failed` | 看 `error` 和日志,查完再 resume 或重派 |
|
|
69
|
+
| 没记到 `thread_id` 的老行 | `create_codex_followup_worker`,新线程靠文本重述 |
|
|
129
70
|
|
|
130
|
-
|
|
71
|
+
`status` 是生命周期:`queued` / `running` / `completed` / `failed` / `cancelled` / `lost`。`phase` 只在跑着时有值:`starting` → `thinking` → `command` → `editing` → `reporting`。`completed` 配 `exit_code: null` 是中间态,`wait` 会等到退出码落了再返回。goal 的 `paused` / `blocked` 不是结束,是等人管,overview 会列进 `needs_attention`。
|
|
131
72
|
|
|
132
|
-
|
|
73
|
+
## 看到 `update` 字段就转告用户
|
|
133
74
|
|
|
134
|
-
|
|
135
|
-
- Go 到 Codex 界面上能直接看到这个 goal
|
|
136
|
-
- `resume_codex_worker` **不会**再建 goal(有未完成 goal 时 `create_goal` 会失败)
|
|
75
|
+
overview、派单回执、`wait` 返回里出现 `update` 且 `update_available: true` 时,当轮回复里照 `notice` 告诉用户一句。`auto_update.state` 是 `started` / `running` / `done` 时新版已在后台装,重开会话即可;`install_command` 有值才让用户自己跑。只说一次。
|
|
137
76
|
|
|
138
77
|
## 常见坑
|
|
139
78
|
|
|
140
|
-
-
|
|
141
|
-
-
|
|
142
|
-
-
|
|
143
|
-
-
|
|
144
|
-
-
|
|
145
|
-
- **`ownedPaths` 是派单前的冲突检测,不是运行时的沙箱**。它只挡「两路活登记写同一个文件」,拦不住 worker 在自己 worktree 里新建清单外的文件——sandbox 是 `workspace-write`,写自己 worktree 里的任何路径都合法。收活时该看 diff 还得看:`get_worker_result` / `get_worker_summary` 里的 `changed_files` 已经包含 worker 在自己分支上 commit 过的文件(按 `base_commit` 和 `HEAD` 比),不用再去 worktree 里跑 `git show --stat`。
|
|
146
|
-
- **worktree 只隔离工作区,不隔离端口和数据库**。多路活要是都会连同一个 dev server 或同一个库,得自己错开。
|
|
147
|
-
- **`cancel_codex_worker` 跨进程靠 pid**。要求那个 pid 的命令行里带 `codex`,防止误杀复用 pid 的进程。
|
|
79
|
+
- worktree 从一个提交切,你工作区里没 commit 的东西 worker 看不到。要让它读到就给绝对路径或先 commit。
|
|
80
|
+
- 它只管"跑完了"不管"对不对",`exit_code: 0` 只说明没崩,验收自己做。
|
|
81
|
+
- `ownedPaths` 是派单前的冲突检测,不是运行时沙箱,拦不住 worker 新建清单外的文件。收活看 diff。
|
|
82
|
+
- worktree 只隔离工作区,端口和数据库是共用的。
|
|
83
|
+
- `resume_codex_worker` 不会再建 goal。`cancel_codex_worker` 跨进程靠 pid,要求那个 pid 的命令行里带 `codex`。
|
|
148
84
|
|
|
149
85
|
## 看板
|
|
150
86
|
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
## 收尾
|
|
154
|
-
|
|
155
|
-
一批活全部到终态后:
|
|
156
|
-
|
|
157
|
-
1. `get_orchestration_overview` 确认没有 `needs_attention`
|
|
158
|
-
2. 逐路 `get_worker_result` 拿完整汇报,对着验收标准核内容
|
|
159
|
-
3. 失败的区分 `failed`(查原因)和 `lost`(重跑)
|
|
160
|
-
4. 改动在各自 worktree 的 `codex/<taskId>` 分支上,合并由主线程决定
|
|
87
|
+
用户想用眼睛看就让他起 `codex-supervisor-web`(或 `npx -p codex-supervisor-mcp codex-supervisor-web`),开 `http://127.0.0.1:7877`。按 session 分组,每路有「旁问」tab,用户可以自己问 worker。
|
package/src/landing.js
CHANGED
|
@@ -12,12 +12,44 @@ import { parsePorcelainLine, resolveWorktreeBase, worktreeRef } from "./worktree
|
|
|
12
12
|
|
|
13
13
|
const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
14
14
|
|
|
15
|
+
// A commit needs a committer. On a machine where git has no user.name or
|
|
16
|
+
// user.email (CI runners, a fresh box, a GUI-launched MCP with no HOME
|
|
17
|
+
// config), cherry-pick and commit both die with "empty ident name", so a
|
|
18
|
+
// stand-in identity is supplied through the environment for that one
|
|
19
|
+
// directory. An identity git already has is used untouched.
|
|
20
|
+
const FALLBACK_IDENTITY = { name: "codex-supervisor", email: "codex-supervisor@localhost" };
|
|
21
|
+
const identityCache = new Map();
|
|
22
|
+
function identityEnv(cwd) {
|
|
23
|
+
if (identityCache.has(cwd)) return identityCache.get(cwd);
|
|
24
|
+
let name = "";
|
|
25
|
+
let email = "";
|
|
26
|
+
try {
|
|
27
|
+
name = execFileSync(defaultGitBin, ["-C", cwd, "config", "user.name"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10000 }).trim();
|
|
28
|
+
} catch {
|
|
29
|
+
// unset
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
email = execFileSync(defaultGitBin, ["-C", cwd, "config", "user.email"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10000 }).trim();
|
|
33
|
+
} catch {
|
|
34
|
+
// unset
|
|
35
|
+
}
|
|
36
|
+
const env = {};
|
|
37
|
+
if (!name || !email) {
|
|
38
|
+
env.GIT_AUTHOR_NAME = name || FALLBACK_IDENTITY.name;
|
|
39
|
+
env.GIT_AUTHOR_EMAIL = email || FALLBACK_IDENTITY.email;
|
|
40
|
+
env.GIT_COMMITTER_NAME = name || FALLBACK_IDENTITY.name;
|
|
41
|
+
env.GIT_COMMITTER_EMAIL = email || FALLBACK_IDENTITY.email;
|
|
42
|
+
}
|
|
43
|
+
identityCache.set(cwd, env);
|
|
44
|
+
return env;
|
|
45
|
+
}
|
|
46
|
+
|
|
15
47
|
function git(cwd, args, { timeout = 60000 } = {}) {
|
|
16
48
|
return execFileSync(defaultGitBin, ["-C", cwd, "-c", "core.quotePath=false", ...args], {
|
|
17
49
|
encoding: "utf8",
|
|
18
50
|
timeout,
|
|
19
51
|
stdio: ["ignore", "pipe", "pipe"],
|
|
20
|
-
env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_EDITOR: "true" }
|
|
52
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_EDITOR: "true", ...identityEnv(cwd) }
|
|
21
53
|
});
|
|
22
54
|
}
|
|
23
55
|
|
|
@@ -39,9 +71,15 @@ function currentBranch(cwd) {
|
|
|
39
71
|
// Lands task's commits onto the current branch of its dispatch directory
|
|
40
72
|
// (task.project_root: the row's cwd is the worktree the worker ran in).
|
|
41
73
|
// `onto`, when given, must name that branch: it is a guard, not a switch.
|
|
74
|
+
//
|
|
75
|
+
// `commitMessage` commits what the worker left uncommitted in its worktree
|
|
76
|
+
// first, as one commit on codex/<id>. A worker in Codex's workspace-write
|
|
77
|
+
// sandbox cannot commit at all (the sandbox keeps .git read-only), so this
|
|
78
|
+
// is how "one step, one commit" is kept without giving workers full access.
|
|
79
|
+
//
|
|
42
80
|
// Returns { landed: [{ sha, original, subject }], onto, head } on success;
|
|
43
81
|
// otherwise { error, reason, ... } with nothing changed in the target.
|
|
44
|
-
export function landWorker(task, { onto = null } = {}) {
|
|
82
|
+
export function landWorker(task, { onto = null, commitMessage = null } = {}) {
|
|
45
83
|
const target = task.project_root;
|
|
46
84
|
if (!task.worktree_path || !existsSync(task.worktree_path)) {
|
|
47
85
|
return { error: "no_worktree", reason: "this worker has no worktree (it ran in place), so there is nothing on a codex/ branch to land" };
|
|
@@ -72,9 +110,29 @@ export function landWorker(task, { onto = null } = {}) {
|
|
|
72
110
|
} catch (error) {
|
|
73
111
|
return { error: "no_base_commit", reason: `the base ${base} no longer resolves in the worktree: ${error.message.split("\n")[0]}` };
|
|
74
112
|
}
|
|
75
|
-
|
|
113
|
+
let uncommitted = porcelainPaths(git(task.worktree_path, ["--no-optional-locks", "status", "--porcelain"]));
|
|
114
|
+
let committedForWorker = null;
|
|
115
|
+
if (uncommitted.length > 0 && commitMessage) {
|
|
116
|
+
try {
|
|
117
|
+
git(task.worktree_path, ["add", "-A"]);
|
|
118
|
+
git(task.worktree_path, ["commit", "-q", "-m", commitMessage]);
|
|
119
|
+
} catch (error) {
|
|
120
|
+
const tail = `${error.stdout ?? ""}${error.stderr ?? ""}`.trim().split("\n").slice(-3).join("\n");
|
|
121
|
+
return { error: "commit_failed", reason: `could not commit the worker's uncommitted edits in ${task.worktree_path}: ${tail || error.message.split("\n")[0]}`, uncommitted };
|
|
122
|
+
}
|
|
123
|
+
committedForWorker = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();
|
|
124
|
+
commits.push(committedForWorker);
|
|
125
|
+
uncommitted = [];
|
|
126
|
+
}
|
|
76
127
|
if (commits.length === 0) {
|
|
77
|
-
return {
|
|
128
|
+
return {
|
|
129
|
+
error: "nothing_to_land",
|
|
130
|
+
reason: uncommitted.length > 0
|
|
131
|
+
? "the worker made no commits on its branch (a workspace-write worker cannot: the sandbox keeps .git read-only); pass commitMessage to commit its edits as one commit and land that"
|
|
132
|
+
: "the worker made no commits and left no edits on its branch",
|
|
133
|
+
uncommitted,
|
|
134
|
+
base_commit: base
|
|
135
|
+
};
|
|
78
136
|
}
|
|
79
137
|
|
|
80
138
|
const before = git(target, ["rev-parse", "HEAD"]).trim();
|
|
@@ -112,6 +170,7 @@ export function landWorker(task, { onto = null } = {}) {
|
|
|
112
170
|
base_commit: base,
|
|
113
171
|
head: landed.at(-1) ?? before,
|
|
114
172
|
landed: landed.map((sha, index) => ({ sha, original: commits[index] ?? null, subject: subjectOf.get(sha) ?? null })),
|
|
173
|
+
committed_for_worker: committedForWorker,
|
|
115
174
|
uncommitted
|
|
116
175
|
};
|
|
117
176
|
}
|
package/src/mcp-server.js
CHANGED
|
@@ -909,16 +909,17 @@ server.registerTool(
|
|
|
909
909
|
{
|
|
910
910
|
title: "Ask a worker on the side",
|
|
911
911
|
description:
|
|
912
|
-
"Ask a finished or running worker a question without touching its thread: the worker's Codex thread is forked once into a read-only side session (like Codex's own /btw), the question is asked there, and later questions resume that fork. The fork carries everything the worker saw and did, so 'why did you change X' or 'where is Y handled' costs one short answer instead of a read of the event stream.
|
|
912
|
+
"Ask a finished or running worker a question without touching its thread: the worker's Codex thread is forked once into a read-only side session (like Codex's own /btw), the question is asked there, and later questions resume that fork. The fork carries everything the worker saw and did, so 'why did you change X' or 'where is Y handled' costs one short answer instead of a read of the event stream. The fork has no network and no MCP tools and is told so; it answers from its context and the worktree. Once the worker has been resumed, the next question automatically takes a new fork from the updated thread (refreshed: \"worker_resumed\"); fresh: true forces a new fork. Changes still go through resume_codex_worker. Without a question it returns the latest side turn (for an answer that outran timeoutMs). end: true deletes the fork.",
|
|
913
913
|
inputSchema: {
|
|
914
914
|
task_id: z.string().min(1),
|
|
915
915
|
question: z.string().min(1).optional(),
|
|
916
916
|
timeoutMs: z.number().int().min(1000).max(600000).default(110000),
|
|
917
917
|
maxChars: z.number().int().min(0).max(1000000).default(8000),
|
|
918
|
+
fresh: z.boolean().default(false),
|
|
918
919
|
end: z.boolean().default(false)
|
|
919
920
|
}
|
|
920
921
|
},
|
|
921
|
-
async ({ task_id, question, timeoutMs, maxChars, end }) => {
|
|
922
|
+
async ({ task_id, question, timeoutMs, maxChars, fresh, end }) => {
|
|
922
923
|
const task = await getTask(task_id);
|
|
923
924
|
if (!task) return textResult({ error: "task_not_found", task_id });
|
|
924
925
|
const clipAnswer = (state) => {
|
|
@@ -933,7 +934,7 @@ server.registerTool(
|
|
|
933
934
|
return textResult({ task_id, ...clipAnswer(await latestSideTurn(task_id)) });
|
|
934
935
|
}
|
|
935
936
|
try {
|
|
936
|
-
const state = clipAnswer(await askWorker({ task, question, timeoutMs }));
|
|
937
|
+
const state = clipAnswer(await askWorker({ task, question, timeoutMs, fresh }));
|
|
937
938
|
const next = state.timed_out
|
|
938
939
|
? `The side turn is still running; call ask_codex_worker again with only task_id to read the answer when it lands.`
|
|
939
940
|
: null;
|
|
@@ -952,16 +953,17 @@ server.registerTool(
|
|
|
952
953
|
{
|
|
953
954
|
title: "Land a worker's commits",
|
|
954
955
|
description:
|
|
955
|
-
"Cherry-pick the commits a worker made on its codex/<taskId> branch onto the current branch of the directory it was dispatched from
|
|
956
|
+
"Cherry-pick the commits a worker made on its codex/<taskId> branch onto the current branch of the directory it was dispatched from. The target must be clean and is never switched to another branch; `onto` is a guard that names the branch you expect to be on. A conflict aborts the cherry-pick, lists the files, and leaves the target as it was. A worker in the workspace-write sandbox cannot commit (Codex keeps .git read-only there): pass commitMessage and its uncommitted edits are committed as one commit on its branch first, then landed. Without commitMessage uncommitted edits are reported, not landed. Check the work first with get_worker_result and get_worker_diff; land once it passes.",
|
|
956
957
|
inputSchema: {
|
|
957
958
|
task_id: z.string().min(1),
|
|
958
|
-
onto: z.string().min(1).optional()
|
|
959
|
+
onto: z.string().min(1).optional(),
|
|
960
|
+
commitMessage: z.string().min(1).optional()
|
|
959
961
|
}
|
|
960
962
|
},
|
|
961
|
-
async ({ task_id, onto }) => {
|
|
963
|
+
async ({ task_id, onto, commitMessage }) => {
|
|
962
964
|
const task = await getTask(task_id);
|
|
963
965
|
if (!task) return textResult({ error: "task_not_found", task_id });
|
|
964
|
-
return textResult({ task_id, title: task.title, status: task.status, branch: `codex/${task.id}`, ...landWorker(task, { onto }) });
|
|
966
|
+
return textResult({ task_id, title: task.title, status: task.status, branch: `codex/${task.id}`, ...landWorker(task, { onto, commitMessage: commitMessage ?? null }) });
|
|
965
967
|
}
|
|
966
968
|
);
|
|
967
969
|
|
package/src/side-chat.js
CHANGED
|
@@ -24,6 +24,9 @@
|
|
|
24
24
|
// session ended ................... fork deleted, history cleared
|
|
25
25
|
import { execFileSync, spawn } from "node:child_process";
|
|
26
26
|
import { randomUUID } from "node:crypto";
|
|
27
|
+
import { readFileSync } from "node:fs";
|
|
28
|
+
import { join } from "node:path";
|
|
29
|
+
import { codexHome } from "./paths.js";
|
|
27
30
|
import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
|
|
28
31
|
import {
|
|
29
32
|
closeSideSession,
|
|
@@ -38,6 +41,77 @@ import {
|
|
|
38
41
|
|
|
39
42
|
const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
|
|
40
43
|
const TURN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
44
|
+
|
|
45
|
+
// What a side question is, said to the fork every time. Without it the fork
|
|
46
|
+
// treats the question as a new task: one real fork spent its whole turn
|
|
47
|
+
// trying to ssh to a build host from inside the read-only sandbox, probing
|
|
48
|
+
// the network, and finally reaching for an MCP tool.
|
|
49
|
+
const SIDE_PREAMBLE = `This is a side question about the work you did in this thread, asked from a read-only fork. Rules for this turn:
|
|
50
|
+
- Answer from what you already know from this thread. You may read files in the working directory to check.
|
|
51
|
+
- The sandbox is read-only and has no network: do not try ssh, curl, builds, tests, package installs or writes; they will fail and waste the turn. MCP tools are disabled here.
|
|
52
|
+
- If answering properly needs something you cannot check from here (a remote machine, a running service, a command), say exactly what and stop; do not retry.
|
|
53
|
+
- Nothing you do here changes the work. If the work needs changing, say what should change; the main thread will ask the worker itself.
|
|
54
|
+
- Be direct and short. Lead with the answer.`;
|
|
55
|
+
|
|
56
|
+
export function sideQuestionText(question) {
|
|
57
|
+
return `${SIDE_PREAMBLE}\n\nQuestion:\n${question}`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// The fork inherits the worker's MCP servers. A side question must not be
|
|
61
|
+
// able to dispatch, resume or cancel anything through them, and a fork that
|
|
62
|
+
// waits on a tool it cannot use burns its turn; every server named in the
|
|
63
|
+
// Codex config is switched off for the turn. Sub-tables
|
|
64
|
+
// ([mcp_servers.x.env]) are not servers and are skipped.
|
|
65
|
+
//
|
|
66
|
+
// The key path is written bare: `-c mcp_servers.name.enabled=false`. A
|
|
67
|
+
// quoted name (`mcp_servers."name".enabled`) is taken by codex as a new
|
|
68
|
+
// server literally called "name", quotes included, with no transport, and
|
|
69
|
+
// the whole config then fails to load.
|
|
70
|
+
export function sideTurnConfigArgs(configText) {
|
|
71
|
+
const names = new Set();
|
|
72
|
+
for (const line of String(configText ?? "").split("\n")) {
|
|
73
|
+
const match = line.match(/^\s*\[mcp_servers\.(?:"([^"]+)"|([^\].]+))\]\s*(?:#.*)?$/);
|
|
74
|
+
if (match) names.add(match[1] ?? match[2]);
|
|
75
|
+
}
|
|
76
|
+
const args = [];
|
|
77
|
+
for (const name of names) {
|
|
78
|
+
if (!/^[A-Za-z0-9_-]+$/.test(name)) continue; // a name codex cannot take bare on the command line
|
|
79
|
+
args.push("-c", `mcp_servers.${name}.enabled=false`);
|
|
80
|
+
}
|
|
81
|
+
return args;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function codexConfigText() {
|
|
85
|
+
try {
|
|
86
|
+
return readFileSync(join(codexHome, "config.toml"), "utf8");
|
|
87
|
+
} catch {
|
|
88
|
+
return "";
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// The session to ask on. A fork taken before the worker was resumed no
|
|
93
|
+
// longer reflects the worker's thread; it is dropped and a new one taken
|
|
94
|
+
// from the current thread. `fresh` forces that. Returns the session and why
|
|
95
|
+
// it was (re)opened: "requested", "worker_resumed", "first" or null.
|
|
96
|
+
export async function prepareSideSession(task, { fresh = false } = {}) {
|
|
97
|
+
let session = await getSideSession(task.id);
|
|
98
|
+
let refreshed = null;
|
|
99
|
+
const stale =
|
|
100
|
+
session?.fork_thread_id &&
|
|
101
|
+
session.worker_run_count !== null &&
|
|
102
|
+
session.worker_run_count !== undefined &&
|
|
103
|
+
(task.run_count ?? 0) > session.worker_run_count;
|
|
104
|
+
if (session && (fresh || stale)) {
|
|
105
|
+
await endSideSession(task.id);
|
|
106
|
+
session = null;
|
|
107
|
+
refreshed = fresh ? "requested" : "worker_resumed";
|
|
108
|
+
}
|
|
109
|
+
if (!session) {
|
|
110
|
+
session = await openSideSession(task.id, task.run_count ?? 0);
|
|
111
|
+
refreshed = refreshed ?? "first";
|
|
112
|
+
}
|
|
113
|
+
return { session, refreshed };
|
|
114
|
+
}
|
|
41
115
|
const OUTPUT_CLIP = 4000;
|
|
42
116
|
|
|
43
117
|
// taskId -> { turnId, child, chunks, watchers: Set<res>, startedAt, question, state }
|
|
@@ -280,19 +354,19 @@ export function attachToTurn(taskId, res) {
|
|
|
280
354
|
|
|
281
355
|
// Start a turn. `res` (optional) becomes the first watcher. Resolves when the
|
|
282
356
|
// turn has ended, however it ended.
|
|
283
|
-
export async function runSideTurn({ task, text, res = null }) {
|
|
357
|
+
export async function runSideTurn({ task, text, res = null, fresh = false }) {
|
|
284
358
|
await sweepOnce();
|
|
285
359
|
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
360
|
if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
|
|
287
361
|
const target = codexTarget();
|
|
288
362
|
if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
|
|
289
363
|
|
|
290
|
-
|
|
291
|
-
if (!session) session = await openSideSession(task.id);
|
|
364
|
+
const { session, refreshed } = await prepareSideSession(task, { fresh });
|
|
292
365
|
|
|
293
366
|
const args = session.fork_thread_id
|
|
294
367
|
? ["exec", "resume", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"']
|
|
295
368
|
: ["exec", "fork", "--json", "--skip-git-repo-check", "-c", 'sandbox_mode="read-only"'];
|
|
369
|
+
args.push(...sideTurnConfigArgs(codexConfigText()));
|
|
296
370
|
if (task.model) args.push("-m", task.model);
|
|
297
371
|
args.push(session.fork_thread_id ?? task.thread_id, "-");
|
|
298
372
|
|
|
@@ -369,7 +443,7 @@ export async function runSideTurn({ task, text, res = null }) {
|
|
|
369
443
|
stderr = (stderr + chunk).slice(-4000);
|
|
370
444
|
});
|
|
371
445
|
child.stdin.on("error", () => {});
|
|
372
|
-
child.stdin.end(text);
|
|
446
|
+
child.stdin.end(sideQuestionText(text));
|
|
373
447
|
|
|
374
448
|
return new Promise((resolve) => {
|
|
375
449
|
const finish = async (code, signal) => {
|
|
@@ -400,7 +474,7 @@ export async function runSideTurn({ task, text, res = null }) {
|
|
|
400
474
|
live.watchers.clear();
|
|
401
475
|
running.delete(task.id);
|
|
402
476
|
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 });
|
|
477
|
+
resolve({ status, turnId, forkThreadId: session.fork_thread_id, refreshed });
|
|
404
478
|
};
|
|
405
479
|
child.on("error", (error) => {
|
|
406
480
|
stderr += `\nfailed to start codex: ${error.message}`;
|
|
@@ -451,7 +525,10 @@ export async function latestSideTurn(taskId) {
|
|
|
451
525
|
// Ask the worker a question on the side, without touching its own thread,
|
|
452
526
|
// and wait up to `timeoutMs` for the answer. A turn that outlives the budget
|
|
453
527
|
// keeps running in this process; the caller reads it back with latestSideTurn.
|
|
454
|
-
export async function askWorker({ task, question, timeoutMs = 110000 }) {
|
|
528
|
+
export async function askWorker({ task, question, timeoutMs = 110000, fresh = false }) {
|
|
529
|
+
// Decided here, before the race, so a turn that outruns the budget still
|
|
530
|
+
// reports whether the fork was taken anew.
|
|
531
|
+
const { refreshed } = await prepareSideSession(task, { fresh });
|
|
455
532
|
const turn = runSideTurn({ task, text: question });
|
|
456
533
|
// runSideTurn throws synchronously-ish (rejected promise) for no_thread,
|
|
457
534
|
// busy and codex_missing before anything starts; surface those as-is.
|
|
@@ -463,11 +540,11 @@ export async function askWorker({ task, question, timeoutMs = 110000 }) {
|
|
|
463
540
|
const outcome = await Promise.race([turn.then((r) => ({ timedOut: false, ...r })), budget]);
|
|
464
541
|
if (!outcome.timedOut) {
|
|
465
542
|
const state = await latestSideTurn(task.id);
|
|
466
|
-
return { ...state, timed_out: false };
|
|
543
|
+
return { ...state, timed_out: false, refreshed };
|
|
467
544
|
}
|
|
468
545
|
turn.catch(() => {});
|
|
469
546
|
const state = await latestSideTurn(task.id);
|
|
470
|
-
return { ...state, timed_out: true };
|
|
547
|
+
return { ...state, timed_out: true, refreshed };
|
|
471
548
|
} finally {
|
|
472
549
|
clearTimeout(timer);
|
|
473
550
|
}
|
|
@@ -492,7 +569,8 @@ export async function endSideSession(taskId) {
|
|
|
492
569
|
const target = codexTarget();
|
|
493
570
|
if (!target.error) {
|
|
494
571
|
deleted = await new Promise((resolve) => {
|
|
495
|
-
|
|
572
|
+
// --force: without a terminal codex asks for confirmation and exits.
|
|
573
|
+
const child = spawn(target.cmd, [...target.prefixArgs, "delete", "--force", row.fork_thread_id], { stdio: "ignore", windowsHide: true, env: { ...process.env, NO_COLOR: "1" } });
|
|
496
574
|
const t = setTimeout(() => { killTree(child); resolve(false); }, 15000);
|
|
497
575
|
child.on("exit", (code) => { clearTimeout(t); resolve(code === 0); });
|
|
498
576
|
child.on("error", () => { clearTimeout(t); resolve(false); });
|
package/src/task-store.js
CHANGED
|
@@ -180,7 +180,8 @@ const SIDE_DDL = `
|
|
|
180
180
|
task_id TEXT PRIMARY KEY,
|
|
181
181
|
fork_thread_id TEXT,
|
|
182
182
|
created_at TEXT NOT NULL,
|
|
183
|
-
ended_at TEXT
|
|
183
|
+
ended_at TEXT,
|
|
184
|
+
worker_run_count INTEGER
|
|
184
185
|
);
|
|
185
186
|
CREATE TABLE IF NOT EXISTS side_turns (
|
|
186
187
|
id TEXT PRIMARY KEY,
|
|
@@ -231,6 +232,15 @@ function initializeSchema(dbInstance) {
|
|
|
231
232
|
dbInstance.exec(TASKS_SESSION_INDEX_DDL);
|
|
232
233
|
dbInstance.exec(SESSIONS_DDL);
|
|
233
234
|
dbInstance.exec(SIDE_DDL);
|
|
235
|
+
// Rows written before 0.7.1 have no worker_run_count: the fork is then
|
|
236
|
+
|
|
237
|
+
// never judged stale, which is what those rows did before.
|
|
238
|
+
|
|
239
|
+
if (!dbInstance.prepare("PRAGMA table_info(side_sessions)").all().some((column) => column.name === "worker_run_count")) {
|
|
240
|
+
|
|
241
|
+
dbInstance.exec("ALTER TABLE side_sessions ADD COLUMN worker_run_count INTEGER;");
|
|
242
|
+
|
|
243
|
+
}
|
|
234
244
|
dbInstance.exec("COMMIT;");
|
|
235
245
|
} catch (error) {
|
|
236
246
|
try {
|
|
@@ -470,13 +480,15 @@ export async function getSideSession(taskId) {
|
|
|
470
480
|
return openDb().prepare("SELECT * FROM side_sessions WHERE task_id = ? AND ended_at IS NULL").get(taskId) ?? null;
|
|
471
481
|
}
|
|
472
482
|
|
|
473
|
-
|
|
483
|
+
// `workerRunCount` is the worker's run_count when the fork is taken; a
|
|
484
|
+
// worker resumed after that has a thread the fork no longer reflects.
|
|
485
|
+
export async function openSideSession(taskId, workerRunCount = null) {
|
|
474
486
|
await ensureFilesystem();
|
|
475
487
|
const now = new Date().toISOString();
|
|
476
488
|
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);
|
|
489
|
+
.prepare(`INSERT INTO side_sessions (task_id, fork_thread_id, created_at, ended_at, worker_run_count) VALUES (?, NULL, ?, NULL, ?)
|
|
490
|
+
ON CONFLICT(task_id) DO UPDATE SET fork_thread_id = NULL, created_at = excluded.created_at, ended_at = NULL, worker_run_count = excluded.worker_run_count`)
|
|
491
|
+
.run(taskId, now, workerRunCount);
|
|
480
492
|
return getSideSession(taskId);
|
|
481
493
|
}
|
|
482
494
|
|