codex-supervisor-mcp 0.5.2 → 0.5.3
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 +375 -0
- package/README.md +53 -6
- package/package.json +1 -1
- package/src/event-parser.js +11 -0
- package/src/mcp-server.js +102 -9
- package/src/task-store.js +26 -0
package/README.en.md
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
# codex-supervisor-mcp
|
|
2
|
+
|
|
3
|
+
English | [中文](README.md)
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/codex-supervisor-mcp)
|
|
6
|
+
[](https://www.npmjs.com/package/codex-supervisor-mcp)
|
|
7
|
+
[](LICENSE)
|
|
8
|
+
[](https://github.com/zriyox/codex-supervisor-mcp/actions/workflows/ci.yml)
|
|
9
|
+
[](package.json)
|
|
10
|
+
|
|
11
|
+
Let one main thread (Claude Code, Codex, any MCP client) run several Codex workers at once.
|
|
12
|
+
|
|
13
|
+

|
|
14
|
+
|
|
15
|
+
*30 seconds, recorded live rather than staged: the Claude Code main thread calls `create_codex_worker` three times, the workers run in parallel in their own worktrees, then the main thread collects three diffs and merges them into one commit.*
|
|
16
|
+
|
|
17
|
+
One worker per Git worktree, one worker per native Codex goal, every state written to disk. The main thread dispatches, waits, reads results back, reconnects after a crash, and cancels.
|
|
18
|
+
|
|
19
|
+
## What this solves
|
|
20
|
+
|
|
21
|
+
Point several agents at one repo and they overwrite each other, and afterwards nobody can tell who changed what. This MCP moves dispatch and bookkeeping out of the model context and onto disk:
|
|
22
|
+
|
|
23
|
+
| Problem | How it's handled |
|
|
24
|
+
|---|---|
|
|
25
|
+
| Workers stepping on each other's files | One Git worktree per worker; `ownedPaths` conflicts are checked before dispatch |
|
|
26
|
+
| The main thread can't hold every worker's output | Events go to `data/runs/<taskId>.jsonl`; reading them has three gates: `limit`, `maxChars`, `kinds` |
|
|
27
|
+
| One read blows up the main thread's context | `get_orchestration_overview` squeezes every worker under 2k tokens |
|
|
28
|
+
| After a restart you don't know what's still running | One row per work in `supervisor.sqlite`, `thread_id` included |
|
|
29
|
+
| A new session can't pick up an old worker | `resume_codex_worker` runs `codex exec resume <thread_id>`, which reattaches the same Codex session |
|
|
30
|
+
| "It failed" and "the process is gone" look alike | The state machine keeps `failed` and `lost` apart |
|
|
31
|
+
|
|
32
|
+
## How is this different from Claude Code subagents?
|
|
33
|
+
|
|
34
|
+
One thing that used to be a difference is not one anymore: a Claude Code subagent can run in its own worktree (`isolation: worktree`; see "Isolate subagents with worktrees" in the [official worktrees docs](https://docs.claude.com/en/docs/claude-code/worktrees)). File isolation is built in now, so don't install this plugin for that.
|
|
35
|
+
|
|
36
|
+
The real gap is the model. A subagent's `model` field takes a Claude alias or a full Claude model ID (`sonnet` / `opus` / `haiku` / `inherit`); a non-Claude model like DeepSeek has no way in, and every token is billed at Anthropic's rates. Dispatch three and you pay for three.
|
|
37
|
+
|
|
38
|
+
What gets dispatched here is a `codex exec` subprocess, and the `model` argument is passed straight through to the Codex CLI (`src/codex-runner.js:336`). A worker's model has nothing to do with the main thread's. Keep the main thread on Claude for judgment, put the workers on DeepSeek, and configure the provider in Codex's `config.toml`. The token-heavy work lands on the workers. The main thread reads the `get_orchestration_overview` table, and pulls a diff from the worker's worktree when it wants one.
|
|
39
|
+
|
|
40
|
+
| | Claude Code subagent | codex-supervisor worker |
|
|
41
|
+
|---|---|---|
|
|
42
|
+
| Models it can run | Claude only: an alias or a full Claude model ID | `model` goes to the Codex CLI, so DeepSeek works |
|
|
43
|
+
| What does the work | Claude Code itself | A separate `codex exec` process |
|
|
44
|
+
| Working directory | Shared with the main thread by default, or `isolation: worktree` | One Git worktree per worker |
|
|
45
|
+
| Two workers writing the same file | Separated by worktrees, with no declared paths and no conflict check | `ownedPaths` is intersected before dispatch; on overlap no worktree is created and you get `ownership_conflict` |
|
|
46
|
+
| Main thread context | Subagent results come back into it | Events go to `data/runs/<taskId>.jsonl`; the overview runs on a hard 7000-byte budget (`src/mcp-server.js:32`) |
|
|
47
|
+
| Main thread process dies | Workers die with it | `thread_id` is in sqlite; `resume_codex_worker` reattaches the same session |
|
|
48
|
+
| What can drive it | Claude Code only | Any MCP client |
|
|
49
|
+
| Watching a worker work | Only the conclusion it returns | Raw JSONL, read through `kinds` / `limit` / `maxChars` |
|
|
50
|
+
|
|
51
|
+
## Architecture
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
MCP client (Claude Code / Codex / ...)
|
|
55
|
+
│ stdio (MCP)
|
|
56
|
+
▼
|
|
57
|
+
codex-supervisor-mcp
|
|
58
|
+
│ spawn: codex exec --json
|
|
59
|
+
▼
|
|
60
|
+
Codex worker ──► data/runs/<taskId>.jsonl raw JSONL event stream
|
|
61
|
+
──► supervisor.sqlite tasks + task_events
|
|
62
|
+
──► worktrees/<taskId>/ the worker's own Git worktree
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Install
|
|
66
|
+
|
|
67
|
+
Requirements: **Node.js >= 22.13.0** (`node:sqlite` had no unflagged build before that) and the `codex` CLI on `PATH`. macOS, Linux, and Windows are all supported.
|
|
68
|
+
|
|
69
|
+
### Quick start
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
# 1. install
|
|
73
|
+
npm install -g codex-supervisor-mcp
|
|
74
|
+
|
|
75
|
+
# 2. confirm it registered
|
|
76
|
+
claude mcp list | grep codex-supervisor
|
|
77
|
+
codex mcp list | grep codex-supervisor
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
A global install runs `postinstall`, which does two things with **no manual configuration**:
|
|
81
|
+
|
|
82
|
+
1. Copies the bundled skill into whichever client directories it finds: `~/.claude/skills/`, `~/.agents/skills/`, `~/.codex/skills/`.
|
|
83
|
+
2. Registers the MCP server through the client's own CLI: `claude mcp add -s user` / `codex mcp add`, pointing at `node <absolute path inside the package>`.
|
|
84
|
+
|
|
85
|
+
If a skill already exists with different content, it writes `SKILL.md.bak-<timestamp>` first and then overwrites. A failure in either step does not fail the install.
|
|
86
|
+
|
|
87
|
+
### Registering by hand
|
|
88
|
+
|
|
89
|
+
When `postinstall` doesn't run (`--ignore-scripts`, `npx`, pnpm, and similar), add the line yourself:
|
|
90
|
+
|
|
91
|
+
| Client | Command |
|
|
92
|
+
|---|---|
|
|
93
|
+
| Claude Code | `claude mcp add -s user codex-supervisor -- npx -y codex-supervisor-mcp` |
|
|
94
|
+
| Codex | `codex mcp add codex-supervisor -- npx -y codex-supervisor-mcp` |
|
|
95
|
+
|
|
96
|
+
To re-run it, repair it, target one client only, or just see what it plans to do:
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
codex-supervisor-setup # detect clients, install skill + register MCP
|
|
100
|
+
codex-supervisor-setup --target claude,codex
|
|
101
|
+
codex-supervisor-setup --skill-only # skill only, leave MCP config alone
|
|
102
|
+
codex-supervisor-setup --mcp-only # register MCP only, no skill
|
|
103
|
+
codex-supervisor-setup --dry-run # print the plan, change nothing
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### GUI clients
|
|
107
|
+
|
|
108
|
+
Write the config file yourself and add this block. GUI clients never run `postinstall`:
|
|
109
|
+
|
|
110
|
+
```json
|
|
111
|
+
{
|
|
112
|
+
"mcpServers": {
|
|
113
|
+
"codex-supervisor": {
|
|
114
|
+
"command": "npx",
|
|
115
|
+
"args": ["-y", "codex-supervisor-mcp"]
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
| Client | macOS | Windows | Linux |
|
|
122
|
+
|---|---|---|---|
|
|
123
|
+
| Claude Desktop | `~/Library/Application Support/Claude/claude_desktop_config.json` | `%APPDATA%\Claude\claude_desktop_config.json` | `~/.config/Claude/claude_desktop_config.json` |
|
|
124
|
+
| Cursor | `~/.cursor/mcp.json` | `%APPDATA%\Cursor\mcp.json` | `~/.config/cursor/mcp.json` |
|
|
125
|
+
| Windsurf | `~/.codeium/windsurf/mcp_config.json` | `%APPDATA%\Codeium\windsurf\mcp_config.json` | `~/.config/.codeium/windsurf/mcp_config.json` |
|
|
126
|
+
|
|
127
|
+
### The npx gotcha
|
|
128
|
+
|
|
129
|
+
`npx` does not run `postinstall`, so **the skill is not installed and the MCP server is not registered**. Only the server itself will start. If you want the bundled skill, either `npm install -g` or run `codex-supervisor-setup` once by hand.
|
|
130
|
+
|
|
131
|
+
### Upgrading
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
npm install -g codex-supervisor-mcp@latest
|
|
135
|
+
npm ls -g --depth=0 | grep codex-supervisor # confirm the version actually changed
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
`postinstall` runs again: it compares the skill by content, backs up to `SKILL.md.bak-<timestamp>` when it differs, and skips clients that already have the MCP registered.
|
|
139
|
+
|
|
140
|
+
Three known traps:
|
|
141
|
+
|
|
142
|
+
- **A freshly published version lags a few minutes behind the registry's `latest`.** If the version number didn't move, wait and reinstall, or pin it: `npm install -g codex-supervisor-mcp@0.5.3`.
|
|
143
|
+
- **`npm link` / `npm i -g .` produce a symlink.** Editing `src/` takes effect immediately, but editing `skills/SKILL.md` does not sync on its own; run `codex-supervisor-setup` once. To go back to a normal install, `npm install -g codex-supervisor-mcp@latest` overwrites the symlink.
|
|
144
|
+
- **Switching Node versions breaks the registration.** What gets registered is an absolute path (`~/.nvm/versions/node/<version>/lib/node_modules/...`), and `postinstall` sees "already registered" and skips, so the path is never rewritten. Remove it first, then install:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
claude mcp remove -s user codex-supervisor
|
|
148
|
+
codex mcp remove codex-supervisor
|
|
149
|
+
npm install -g codex-supervisor-mcp@latest
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
To re-run the installer without upgrading, use `codex-supervisor-setup`.
|
|
153
|
+
|
|
154
|
+
### Uninstall
|
|
155
|
+
|
|
156
|
+
```bash
|
|
157
|
+
npm uninstall -g codex-supervisor-mcp
|
|
158
|
+
claude mcp remove -s user codex-supervisor
|
|
159
|
+
codex mcp remove codex-supervisor
|
|
160
|
+
rm -rf ~/.claude/skills/codex-supervisor ~/.agents/skills/codex-supervisor ~/.codex/skills/codex-supervisor
|
|
161
|
+
rm -rf ~/.codex-supervisor # state directory: sqlite, event streams, worktrees
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
### Windows
|
|
165
|
+
|
|
166
|
+
- An npm-installed CLI on Windows is `codex.cmd`, not an executable, and Node refuses to `spawn` it directly since 18.20 / 20.12 (the behavior after CVE-2024-27980, reported as `EINVAL`). This package does not fall back to `shell: true` — that turns the shell into a child process, so cancelling kills the shell while the real Codex keeps running and the state machine sticks on `running`. Instead it goes around the shim to the npm package's own entry point (`node_modules/@openai/codex/bin/codex.js`) and starts it with `node`. The same path is taken when `CODEX_BIN` points at a `.js` file.
|
|
167
|
+
- Cross-process cancel uses `taskkill /PID <pid> /T /F` to take down the whole tree. Confirming that pid is still Codex reads its command line through PowerShell's `Get-CimInstance Win32_Process`, falling back to `tasklist`. `ps` is only used on macOS and Linux.
|
|
168
|
+
- Besides `PATH`, it probes `%APPDATA%\npm`, `%LOCALAPPDATA%\pnpm`, `%LOCALAPPDATA%\Volta\bin`, and `%ProgramFiles%\nodejs`.
|
|
169
|
+
|
|
170
|
+
Auto-install only happens on a **global install**. `npx`, `--ignore-scripts`, and being installed as someone else's dependency all skip it. Set `CODEX_SUPERVISOR_SKIP_SETUP=1` to opt out.
|
|
171
|
+
|
|
172
|
+
### Troubleshooting
|
|
173
|
+
|
|
174
|
+
| Symptom | Cause | Fix |
|
|
175
|
+
|---|---|---|
|
|
176
|
+
| `claude mcp list` has no `codex-supervisor` | `npx` / `--ignore-scripts` installs don't run `postinstall` | Run `codex-supervisor-setup`, or register by hand above |
|
|
177
|
+
| Dispatch fails with `codex only resolved to a shell shim` | On Windows only the `.cmd` was found and the npm package entry point behind it is gone | Reinstall `@openai/codex`, or point `CODEX_BIN` at the real executable / `codex.js` |
|
|
178
|
+
| A worker goes `failed` immediately with `spawn codex ENOENT` | The process started by a GUI client has no `codex` on `PATH` | Set `CODEX_BIN` explicitly in the client config |
|
|
179
|
+
| `Cannot find module 'node:sqlite'` | Node < 22.13.0 | Upgrade Node |
|
|
180
|
+
| A worker is stuck in `lost` | The MCP process was killed and the worker was orphaned | Let `list_codex_workers` settle it, or pick it back up with `resume_codex_worker` |
|
|
181
|
+
| `ownedPaths overlap with active worker(s)` | Two workers claimed the same path | Change the path, or `cancel_codex_worker` whichever is holding it |
|
|
182
|
+
|
|
183
|
+
## Tools
|
|
184
|
+
|
|
185
|
+
Fourteen of them.
|
|
186
|
+
|
|
187
|
+
| Tool | Arguments | What it does |
|
|
188
|
+
|---|---|---|
|
|
189
|
+
| `create_codex_worker` | `task`, `cwd`, **`ownedPaths`**, **`goal`**, `session_id`, `dependsOn`, `sandbox`, `model`, `reasoningEffort`, `title`, `skipGitRepoCheck` | Start a worker |
|
|
190
|
+
| `create_codex_followup_worker` | `task_id`, `followup_prompt`, `session_id`, plus the same arguments | Start a **new session**, seeded with the old worker's prompt, status, and recent events |
|
|
191
|
+
| `resume_codex_worker` | `task_id`, `prompt` | Continue the **same** Codex session |
|
|
192
|
+
| `list_codex_workers` | `status`, `includeHistory`, `includeDetails` | List workers; running ones only by default |
|
|
193
|
+
| `get_orchestration_overview` | `status`, `limit` | A compact status table for every worker, meant for the main thread |
|
|
194
|
+
| `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `timeoutMs`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | Wait for a terminal state, then return summaries. The default wait is 2 minutes: when it runs out you get a progress snapshot and the workers keep going, so call it again |
|
|
195
|
+
| `get_codex_worker_status` | `task_id` | The full record for one worker |
|
|
196
|
+
| `get_codex_worker_events` | `task_id`, `limit`, `maxChars`, `kinds` | Read the raw event stream |
|
|
197
|
+
| `get_worker_goal` | `task_id` | Read a worker's goal (supervisor side and native Codex side) |
|
|
198
|
+
| `get_worker_summary` | `task_id` | One paragraph about a worker; what the main thread reads when wrapping up |
|
|
199
|
+
| `get_worker_result` | `task_id`, `limit`, `maxChars` | A worker's own final report, in full. The overview and `wait_codex_workers` clip the last message to 400 characters and keep only the head; read this for the conclusion |
|
|
200
|
+
| `get_session_works` | `session_id` | Every worker dispatched under one session, oldest first. This is how a dead main thread finds its batch again |
|
|
201
|
+
| `search_works` | `query`, `limit` | Substring match over title / goal / prompt / last_message, newest first |
|
|
202
|
+
| `cancel_codex_worker` | `task_id` | Stop a worker; falls back to the pid when the process handle isn't in this process |
|
|
203
|
+
|
|
204
|
+
### Why `ownedPaths` and `goal` are required
|
|
205
|
+
|
|
206
|
+
- `ownedPaths`: the paths this worker is allowed to write, relative to `cwd` or absolute. Before dispatch it is intersected against every running worker; on overlap the dispatch is refused and the conflicting `task_id` comes back. No worktree gets created and then thrown away.
|
|
207
|
+
- `goal`: `{ objective, tokenBudget? }`. This anchors the main thread's L1 summary and decides when the work should stop.
|
|
208
|
+
|
|
209
|
+
`dependsOn` records the dependency edges between workers. It's stored, so the main thread can see who is waiting on whom.
|
|
210
|
+
|
|
211
|
+
### Three gates on reading events
|
|
212
|
+
|
|
213
|
+
`get_codex_worker_events` keeps the cost of a read under control with three arguments:
|
|
214
|
+
|
|
215
|
+
| Argument | Effect |
|
|
216
|
+
|---|---|
|
|
217
|
+
| `limit` | At most this many events |
|
|
218
|
+
| `maxChars` | Long strings inside a single event are truncated in the middle, keeping head and tail |
|
|
219
|
+
| `kinds` | Only these event types; the filter runs before `limit` is applied |
|
|
220
|
+
|
|
221
|
+
The truncation rule copies Codex's own `TruncationPolicy::Bytes`: cut the middle, keep both ends, and prefix with
|
|
222
|
+
|
|
223
|
+
```
|
|
224
|
+
Warning: truncated output (original token count: N)
|
|
225
|
+
Total output lines: M
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
`get_orchestration_overview` has the same kind of hard guarantee. Field limits tighten step by step until the whole JSON payload fits in 7000 bytes (about 1750 tokens). The `approx_tokens` it returns is its own real cost.
|
|
229
|
+
|
|
230
|
+
## The work state machine
|
|
231
|
+
|
|
232
|
+
`status` is the lifecycle. One value per work, never overwritten by progress:
|
|
233
|
+
|
|
234
|
+
| Value | Meaning |
|
|
235
|
+
|---|---|
|
|
236
|
+
| `queued` | Dispatched, not started |
|
|
237
|
+
| `running` | Running |
|
|
238
|
+
| `completed` | Succeeded |
|
|
239
|
+
| `failed` | Failed (non-zero exit code, `turn.failed`, spawn failure) |
|
|
240
|
+
| `cancelled` | Interrupted by `cancel_codex_worker` |
|
|
241
|
+
| `lost` | Killed by an external signal, or the MCP process vanished without writing a terminal event |
|
|
242
|
+
|
|
243
|
+
`phase` only has a value while `running`, and goes back to `null` at a terminal state:
|
|
244
|
+
|
|
245
|
+
```
|
|
246
|
+
starting → thinking → command → editing → reporting
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
Keeping `failed` and `lost` apart is useful: the first sends you to the logs, the second means just run it again.
|
|
250
|
+
|
|
251
|
+
Windows has no signals, so only one of the two is decidable there. libuv kills a process with `TerminateProcess(handle, 1)`, and an external kill looks exactly like the process calling `exit(1)` from the parent's point of view: `exit_code=1`, `signal=null` in both cases. In that situation it reports the one it can prove, `failed` plus an exit code, rather than inventing a signal name the platform never delivered. `lost` still happens on Windows, through the MCP process disappearing and orphans being settled on the next start.
|
|
252
|
+
|
|
253
|
+
### Goal states mapped to work states
|
|
254
|
+
|
|
255
|
+
A native Codex goal has six states. They map onto work status like this:
|
|
256
|
+
|
|
257
|
+
| Goal state | Work status | Note |
|
|
258
|
+
|---|---|---|
|
|
259
|
+
| `active` | `running` | Progressing normally |
|
|
260
|
+
| `paused` | `running` | Paused, waiting on a person |
|
|
261
|
+
| `blocked` | `running` | Stuck, needs the main thread to step in |
|
|
262
|
+
| `usageLimited` / `usage_limited` | `failed` | Quota exhausted |
|
|
263
|
+
| `budgetLimited` / `budget_limited` | `failed` | Budget exhausted |
|
|
264
|
+
| `complete` | `completed` | Done |
|
|
265
|
+
|
|
266
|
+
`paused` and `blocked` are not endings. They mean someone needs to look. `get_orchestration_overview` lists both under `needs_attention`, so you don't have to guess with a timeout.
|
|
267
|
+
|
|
268
|
+
## Where state lives
|
|
269
|
+
|
|
270
|
+
By default under `~/.codex-supervisor/`:
|
|
271
|
+
|
|
272
|
+
| File | Contents |
|
|
273
|
+
|---|---|
|
|
274
|
+
| `data/supervisor.sqlite` | `tasks` (one row per work) and `task_events` (structured events with a `seq`) |
|
|
275
|
+
| `data/runs/<taskId>.jsonl` | Codex `--json` raw output, one event per line |
|
|
276
|
+
| `worktrees/<taskId>/` | That worker's own Git worktree |
|
|
277
|
+
|
|
278
|
+
A database from 0.1.x migrates automatically the first time it's opened. Process values that used to live in `status` (`editing`, `command`, `command_completed`, `reporting`) move into `phase`, and `status` becomes `running`. Nothing is dropped. The migration runs inside one `BEGIN IMMEDIATE` transaction, so if several processes start at once only one of them actually migrates.
|
|
279
|
+
|
|
280
|
+
`changed_files` has two sources: Codex's `file_change` events, and reading `git status --porcelain` in the worker's own worktree after it exits. The second exists because a worker that edits files through a shell command (`printf > file`) never emits a `file_change` event, and only the worktree knows the truth.
|
|
281
|
+
|
|
282
|
+
## Environment variables
|
|
283
|
+
|
|
284
|
+
| Variable | Default | Effect |
|
|
285
|
+
|---|---|---|
|
|
286
|
+
| `SUPERVISOR_HOME` | `~/.codex-supervisor` | State root. sqlite, event streams, and worktrees all live under it |
|
|
287
|
+
| `CODEX_HOME` | `~/.codex` | Read-only. Used to read Codex's own `goals_1.sqlite` |
|
|
288
|
+
| `CODEX_BIN` | `codex` (via `PATH`) | Path to the Codex CLI. On Windows a bare name is expanded through `PATHEXT` and the `.cmd` shim is stepped over automatically; a `.js` / `.cjs` / `.mjs` target is started with `node` |
|
|
289
|
+
| `GIT_BIN` | `git` (via `PATH`) | Path to the Git executable |
|
|
290
|
+
|
|
291
|
+
When the MCP client starts without `codex` on `PATH`, which is common for GUI-launched apps, set `CODEX_BIN` explicitly:
|
|
292
|
+
|
|
293
|
+
```json
|
|
294
|
+
{
|
|
295
|
+
"mcpServers": {
|
|
296
|
+
"codex-supervisor": {
|
|
297
|
+
"command": "npx",
|
|
298
|
+
"args": ["-y", "codex-supervisor-mcp"],
|
|
299
|
+
"env": { "CODEX_BIN": "/usr/local/bin/codex" }
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
## Known limitations
|
|
306
|
+
|
|
307
|
+
- **A worker's lifetime is tied to the MCP process.** `codex` is a child of the MCP process, so killing the MCP process leaves workers behind. They get settled as `lost` on the next `list_codex_workers` / `get_orchestration_overview`. The real fix is a resident daemon, see the Roadmap.
|
|
308
|
+
- **The worktree is created from `HEAD`, so uncommitted work isn't in it.** `ensureWorktree` runs `git worktree add --detach <dir> HEAD` (`src/codex-runner.js:64`). Modified and untracked files sitting in the main thread's checkout don't exist inside the worker's worktree. Give the task absolute paths, or commit first. The worker's own changes land on the `codex/<taskId>` branch and never touch the main checkout.
|
|
309
|
+
- **Only the working directory is isolated.** Temp directories (`TMPDIR`), databases, and ports are process-level resources and stay shared, so two workers writing the same temp file still collide. Give each one its own paths, database name, and port in the task if you need that.
|
|
310
|
+
- **It reports "it finished", not "it's correct".** Terminal states come from Codex's `turn.completed` and the process exit code; `exit_code: 0` only means it didn't crash. Judging the output is the main thread's job: run the checks, spot-read the content.
|
|
311
|
+
- **Don't expect one `wait_codex_workers` call to cover a long job.** Your client's MCP tool timeout is a hard wall (the `timeout` field in `.mcp.json`, or `MCP_TOOL_TIMEOUT`), and hitting it kills the call. The default wait returns after 2 minutes with a progress snapshot; loop instead of waiting once.
|
|
312
|
+
- **Nothing is written to Codex's native goal store.** `goals_1.sqlite` belongs to Codex and this MCP only reads it. Once a worker starts, it calls Codex's own `create_goal`; this MCP only splices that instruction into the prompt at dispatch time.
|
|
313
|
+
- **Native goals depend on the model complying.** `codex exec` does not create a goal on its own; the instruction at dispatch time is what makes the worker create one. The model occasionally skips it, in which case `native_goal` is `null` and `get_worker_goal` falls back to the copy recorded at dispatch. The state machine is unaffected.
|
|
314
|
+
- **`search_works` is substring matching, not a full-text index.** At a few hundred works, a `LIKE` scan is fast enough and costs nothing to maintain. Talk about something else at tens of thousands.
|
|
315
|
+
- **Cross-process cancel goes through the pid.** When the process handle isn't in this process, it first confirms the pid's command line contains `codex` (`ps` on macOS and Linux, CIM on Windows, `tasklist` as a fallback), then sends `SIGTERM` (`taskkill /T /F` on Windows), so a recycled pid doesn't get killed by mistake.
|
|
316
|
+
- **`create_codex_followup_worker` and `resume_codex_worker` are not the same thing.** The first opens a new session and restates the context in prose; the second reattaches the same session. Use the second when details matter.
|
|
317
|
+
- **`session_id` comes from the dispatcher; this MCP doesn't generate it.** Pass the same value for a batch of work and `get_session_works` can group it afterwards. Without it the column is `NULL` and the batch is unrecoverable by session.
|
|
318
|
+
|
|
319
|
+
## Roadmap
|
|
320
|
+
|
|
321
|
+
1. ~~De-personalize: `CODEX_BIN` / `SUPERVISOR_HOME` / `GIT_BIN` environment variables~~ ✅
|
|
322
|
+
2. ~~Work state machine: split `status` and `phase`, add `lost`~~ ✅
|
|
323
|
+
3. ~~Tool surface: `ownedPaths` / `goal` / `dependsOn`, four new tools, event gates~~ ✅
|
|
324
|
+
4. ~~Cross-session continuation: persist `thread_id` + `resume_codex_worker`~~ ✅
|
|
325
|
+
5. ~~Concurrency stability: two crash points, ownership conflicts, multi-process writes~~ ✅
|
|
326
|
+
6. ~~Session dimension: persist `session_id` + `get_session_works` for reconnects~~
|
|
327
|
+
7. ~~Find past work by keyword: `search_works`~~
|
|
328
|
+
8. ~~Worker-native goals: inject a `create_goal` instruction at dispatch~~
|
|
329
|
+
9. ~~Windows support: `.cmd` shim bypass, `taskkill` process tree, cross-platform `PATH` / `PATHEXT`~~ ✅
|
|
330
|
+
10. Resident daemon: move dispatch and process lifetime out of the MCP process
|
|
331
|
+
11. A live React board
|
|
332
|
+
|
|
333
|
+
Rejected, with the reasoning, so nobody brings them up again:
|
|
334
|
+
|
|
335
|
+
| Idea | Why not |
|
|
336
|
+
|---|---|
|
|
337
|
+
| Vector search | `search_works` substring matching is faster and needs zero maintenance at a few hundred works. Both vendors' official memory systems (Codex `memories`, Claude auto-memory) are file search too, not vectors |
|
|
338
|
+
| Sorting by `usage_count` | Measured: of 80 works, only 2 were ever referenced again. Every counter sat at 0 or 1, so sorting did nothing |
|
|
339
|
+
| Reusing Codex's `usage_count` | That number counts how often a memory entry was cited, which is a different question from how often the main thread looked it up |
|
|
340
|
+
| A three-layer memory index | The current data volume can't justify one layer. `get_worker_summary` is enough |
|
|
341
|
+
|
|
342
|
+
## Using the bundled skill
|
|
343
|
+
|
|
344
|
+
The repo ships `skills/codex-supervisor/SKILL.md`. After installing, drop it into the main thread's skill directory so it knows when to dispatch:
|
|
345
|
+
|
|
346
|
+
```bash
|
|
347
|
+
# Claude Code
|
|
348
|
+
mkdir -p ~/.claude/skills/codex-supervisor
|
|
349
|
+
cp "$(npm root -g)/codex-supervisor-mcp/skills/codex-supervisor/SKILL.md" ~/.claude/skills/codex-supervisor/
|
|
350
|
+
|
|
351
|
+
# Codex / any client that reads ~/.agents/skills
|
|
352
|
+
mkdir -p ~/.agents/skills/codex-supervisor
|
|
353
|
+
cp "$(npm root -g)/codex-supervisor-mcp/skills/codex-supervisor/SKILL.md" ~/.agents/skills/codex-supervisor/
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
The skill covers the dispatch flow, the order to read results in, how to tell `failed` from `lost`, and how to reconnect after a crash.
|
|
357
|
+
|
|
358
|
+
## Development
|
|
359
|
+
|
|
360
|
+
```bash
|
|
361
|
+
npm install
|
|
362
|
+
npm test # deterministic: truncation, state machine, v1→v2 migration, setup, Windows routing, 17 end-to-end regression cases
|
|
363
|
+
npm run test:real # end-to-end against the real codex CLI (includes cross-process resume and worktree isolation)
|
|
364
|
+
npm run smoke # basic smoke test (real codex)
|
|
365
|
+
npm run smoke:mcp # MCP protocol smoke test
|
|
366
|
+
npm run monitor # Ink terminal board
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
`npm test` replays a fixed Codex event stream through `src/test-fixtures/fake-codex.js`, so it's fast and deterministic. `npm run test:real` actually invokes `codex exec`. It's slower, but it's the evidence that this still works against the current Codex.
|
|
370
|
+
|
|
371
|
+
CI runs on Ubuntu, macOS, and Windows, plus a separate Node 22.13.0 job that pins the lower bound declared in `engines`, since `node:sqlite` had no unflagged build before it. The four `setup-windows-test.js` cases use a real filesystem to simulate the `.cmd` shim under `%APPDATA%\npm`, verifying that automatic MCP registration genuinely works rather than just passing a parser unit test.
|
|
372
|
+
|
|
373
|
+
## License
|
|
374
|
+
|
|
375
|
+
MIT
|
package/README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# codex-supervisor-mcp
|
|
2
2
|
|
|
3
|
+
[English](README.en.md) | 中文
|
|
4
|
+
|
|
3
5
|
[](https://www.npmjs.com/package/codex-supervisor-mcp)
|
|
4
6
|
[](https://www.npmjs.com/package/codex-supervisor-mcp)
|
|
5
7
|
[](LICENSE)
|
|
@@ -27,6 +29,25 @@
|
|
|
27
29
|
| 换个会话就接不上之前的 worker | `resume_codex_worker` 走 `codex exec resume <thread_id>`,接的是同一个 Codex 会话 |
|
|
28
30
|
| 分不清「跑失败了」和「进程没了」 | 状态机把 `failed` 和 `lost` 分开 |
|
|
29
31
|
|
|
32
|
+
## 和 Claude Code 的 subagent 有什么区别
|
|
33
|
+
|
|
34
|
+
先说一条已经不是差异的:Claude Code 的 subagent 现在能自己开 worktree 了(`isolation: worktree`,见 [官方 worktrees 文档](https://docs.claude.com/en/docs/claude-code/worktrees) 里的 "Isolate subagents with worktrees")。文件隔离这件事官方已经做了,别为了这个装本插件。
|
|
35
|
+
|
|
36
|
+
真正的差别在模型。subagent 的 `model` 字段只能填 Claude 的别名或完整 Claude 模型 ID(`sonnet` / `opus` / `haiku` / `inherit`),DeepSeek 这类非 Claude 模型填不进去,账单也全走 Anthropic 的价目表,派三个就是三份。
|
|
37
|
+
|
|
38
|
+
派出去的是 `codex exec` 子进程,`model` 参数原样透传给 Codex CLI(`src/codex-runner.js:336`)。worker 用什么模型跟主线程没关系:主线程留在 Claude 上做判断,worker 可以挂 DeepSeek,在 Codex 的 `config.toml` 里配好 provider 就行。重活都在 worker 那边,主线程读的是 `get_orchestration_overview` 那张表,要看 diff 自己去 worker 的 worktree 里取。
|
|
39
|
+
|
|
40
|
+
| | Claude Code subagent | codex-supervisor worker |
|
|
41
|
+
|---|---|---|
|
|
42
|
+
| 能跑什么模型 | 只能选 Claude:别名或完整 Claude 模型 ID | `model` 透传给 Codex CLI,DeepSeek 也能挂 |
|
|
43
|
+
| 干活的是谁 | Claude Code 自己 | 独立的 `codex exec` 进程 |
|
|
44
|
+
| 工作目录 | 默认和主线程同一个,可设 `isolation: worktree` | 一个 worker 一个 Git worktree |
|
|
45
|
+
| 两个 worker 写同一个文件 | 靠 worktree 隔开,没有路径声明和冲突检查 | 派单前求 `ownedPaths` 交集,重叠就不建 worktree,报 `ownership_conflict` |
|
|
46
|
+
| 主线程上下文 | subagent 的结果回到主线程 | 事件写 `data/runs/<taskId>.jsonl`,总览走 7000 字节硬预算(`src/mcp-server.js:32`) |
|
|
47
|
+
| 主线程进程挂了 | worker 一起没 | `thread_id` 落 sqlite,`resume_codex_worker` 接回同一个会话 |
|
|
48
|
+
| 谁能驱动 | 只有 Claude Code | 任意 MCP 客户端 |
|
|
49
|
+
| 看 worker 干活的过程 | 只有它返回的结论 | 原始 JSONL 按 `kinds` / `limit` / `maxChars` 读 |
|
|
50
|
+
|
|
30
51
|
## 架构
|
|
31
52
|
|
|
32
53
|
```
|
|
@@ -107,6 +128,29 @@ codex-supervisor-setup --dry-run # 只打印计划,不改任何东
|
|
|
107
128
|
|
|
108
129
|
`npx` 不跑 `postinstall`,所以 **skill 不会自动装、MCP 也不会自动注册**,只有 MCP server 本身能起来。要用配套 skill 就还是得 `npm install -g`,或者手动跑一次 `codex-supervisor-setup`。
|
|
109
130
|
|
|
131
|
+
### 更新
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
npm install -g codex-supervisor-mcp@latest
|
|
135
|
+
npm ls -g --depth=0 | grep codex-supervisor # 确认版本号真的变了
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
`postinstall` 会重跑一遍:skill 按内容比对,不一样就备份 `SKILL.md.bak-<时间戳>` 再覆盖;MCP 已经注册过的客户端跳过。
|
|
139
|
+
|
|
140
|
+
三个已知的坑:
|
|
141
|
+
|
|
142
|
+
- **刚发布的版本,registry 的 `latest` 会延迟几分钟**。装完发现版本号没变,就等一会儿再装,或者直接写死版本:`npm install -g codex-supervisor-mcp@0.5.3`。
|
|
143
|
+
- **`npm link` / `npm i -g .` 装出来的是软链**。这种情况改 `src/` 立即生效,但改 `skills/SKILL.md` 不会自动同步,要手动跑一次 `codex-supervisor-setup`。想换回正式安装,直接 `npm install -g codex-supervisor-mcp@latest` 就会覆盖掉软链。
|
|
144
|
+
- **换 Node 版本会让注册失效**。注册的是绝对路径(`~/.nvm/versions/node/<版本>/lib/node_modules/...`),而 `postinstall` 看到「已注册」就跳过,不会改写路径。这时先摘掉再装:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
claude mcp remove -s user codex-supervisor
|
|
148
|
+
codex mcp remove codex-supervisor
|
|
149
|
+
npm install -g codex-supervisor-mcp@latest
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
只想重跑安装、不升级版本,用 `codex-supervisor-setup`。
|
|
153
|
+
|
|
110
154
|
### 卸载
|
|
111
155
|
|
|
112
156
|
```bash
|
|
@@ -119,13 +163,11 @@ rm -rf ~/.codex-supervisor # 状态目录:sqlite、事件流、worktree
|
|
|
119
163
|
|
|
120
164
|
### Windows
|
|
121
165
|
|
|
122
|
-
三条实现细节值得知道:
|
|
123
|
-
|
|
124
166
|
- npm 装的 CLI 在 Windows 上是 `codex.cmd` 而不是可执行文件,Node 从 18.20 / 20.12 起拒绝直接 `spawn` 它(CVE-2024-27980 之后的行为,报 `EINVAL`)。这里不用 `shell: true` 绕——那样 shell 会变成子进程,取消时只杀掉 shell 而真正的 Codex 还在跑,状态机会卡在 `running`。做法是绕到 npm 包自己的入口(`node_modules/@openai/codex/bin/codex.js`),用 `node` 起它;`CODEX_BIN` 指向 `.js` 时同样处理。
|
|
125
167
|
- 跨进程取消用 `taskkill /PID <pid> /T /F` 结束整棵进程树;确认这个 pid 还是 Codex 用 PowerShell 的 `Get-CimInstance Win32_Process` 读命令行(拿不到时退到 `tasklist`)。`ps` 只在 macOS / Linux 上用。
|
|
126
168
|
- 除了 `PATH`,还会探 `%APPDATA%\npm`、`%LOCALAPPDATA%\pnpm`、`%LOCALAPPDATA%\Volta\bin`、`%ProgramFiles%\nodejs`。
|
|
127
169
|
|
|
128
|
-
自动安装只在**全局安装**时发生。`npx`、`--ignore-scripts
|
|
170
|
+
自动安装只在**全局安装**时发生。`npx`、`--ignore-scripts`、以及被别人当项目依赖装的场景都不会触发。想跳过就设 `CODEX_SUPERVISOR_SKIP_SETUP=1`。
|
|
129
171
|
|
|
130
172
|
### 疑难排查
|
|
131
173
|
|
|
@@ -140,7 +182,7 @@ rm -rf ~/.codex-supervisor # 状态目录:sqlite、事件流、worktree
|
|
|
140
182
|
|
|
141
183
|
## 工具
|
|
142
184
|
|
|
143
|
-
|
|
185
|
+
14 个工具。
|
|
144
186
|
|
|
145
187
|
| 工具 | 入参 | 作用 |
|
|
146
188
|
|---|---|---|
|
|
@@ -149,11 +191,12 @@ rm -rf ~/.codex-supervisor # 状态目录:sqlite、事件流、worktree
|
|
|
149
191
|
| `resume_codex_worker` | `task_id`, `prompt` | 接**同一个** Codex 会话继续跑 |
|
|
150
192
|
| `list_codex_workers` | `status`, `includeHistory`, `includeDetails` | 列出 worker,默认只看在跑的 |
|
|
151
193
|
| `get_orchestration_overview` | `status`, `limit` | 全部 worker 的紧凑状态表,默认给主线程用 |
|
|
152
|
-
| `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` |
|
|
194
|
+
| `wait_codex_workers` | `task_ids`, `mode`(any/all), `timeoutMinutes`, `timeoutMs`, `includeEvents`, `eventLimit`, `eventMaxChars`, `eventKinds` | 等终态,回摘要。默认只等 2 分钟,到点带进度快照返回,worker 照跑;接着调同一个工具继续等 |
|
|
153
195
|
| `get_codex_worker_status` | `task_id` | 单个 worker 的完整记录 |
|
|
154
196
|
| `get_codex_worker_events` | `task_id`, `limit`, `maxChars`, `kinds` | 读原始事件流 |
|
|
155
197
|
| `get_worker_goal` | `task_id` | 读 worker 的 goal(supervisor 侧 + Codex 原生) |
|
|
156
198
|
| `get_worker_summary` | `task_id` | 单个 worker 的一段话总结,主线程收尾时读这个 |
|
|
199
|
+
| `get_worker_result` | `task_id`, `limit`, `maxChars` | 读 worker 自己的完整收尾汇报。总览和 `wait_codex_workers` 把最后一条消息截到 400 字只留开头,要结论读这个 |
|
|
157
200
|
| `get_session_works` | `session_id` | 一个 session 派出去的全部 worker,按时间升序。主线程挂了之后靠它找回那批活 |
|
|
158
201
|
| `search_works` | `query`, `limit` | 在 title / goal / prompt / last_message 里做子串匹配,从新到旧 |
|
|
159
202
|
| `cancel_codex_worker` | `task_id` | 终止 worker,进程句柄不在本进程时按 pid 兜底 |
|
|
@@ -205,7 +248,7 @@ starting → thinking → command → editing → reporting
|
|
|
205
248
|
|
|
206
249
|
`failed` 和 `lost` 分开是有用的:前者要看日志找原因,后者直接重跑。
|
|
207
250
|
|
|
208
|
-
Windows
|
|
251
|
+
Windows 上没有信号,所以这两个状态只判得出一个。libuv 杀进程走的是 `TerminateProcess(handle, 1)`,外部 kill 和进程自己 `exit(1)` 落到父进程手里完全一样(都是 `exit_code=1`、`signal=null`)。这种情况下报能证明的那个——`failed` 加退出码——而不是编一个平台根本没收到的信号名。Windows 上的 `lost` 仍然会发生,走的是 MCP 进程消失、下次启动结算孤儿那条路。
|
|
209
252
|
|
|
210
253
|
### goal 和 work 的映射
|
|
211
254
|
|
|
@@ -262,6 +305,10 @@ Codex 原生 goal 有六个状态,映射到 work 状态:
|
|
|
262
305
|
## 已知限制
|
|
263
306
|
|
|
264
307
|
- **worker 的生命周期绑在 MCP 进程上**:`codex` 是 MCP 进程的子进程,MCP 被 kill 时 worker 会被留下。这些 worker 会在下一次 `list_codex_workers` / `get_orchestration_overview` 时被结算成 `lost`。真正的解法是常驻 daemon,见 Roadmap。
|
|
308
|
+
- **worktree 从 `HEAD` 建,未提交的改动不在里面**:`ensureWorktree` 走的是 `git worktree add --detach <dir> HEAD`(`src/codex-runner.js:64`)。主线程工作区里没 commit 的修改和未跟踪文件,worker 在自己的 worktree 里看不到。要让它读写这些文件,就在 task 里给绝对路径,或者先把改动 commit。worker 的改动落在 `codex/<taskId>` 分支上,不碰主线程的工作区。
|
|
309
|
+
- **只隔离工作目录**:临时目录(`TMPDIR`)、数据库、端口这些进程级资源是共用的,多个 worker 同时写同一个临时文件照样互相踩。要隔开得自己在 task 里指定各自的临时目录、库名和端口。
|
|
310
|
+
- **只管「跑完了」,不管写得对不对**:终态来自 Codex 的 `turn.completed` 和进程退出码,`exit_code: 0` 只说明它没崩。产出对不对得主线程自己核,跑校验、抽看内容。
|
|
311
|
+
- **长任务别指望一次 `wait_codex_workers` 等到底**:客户端给 MCP 工具调用设的超时是硬墙(`.mcp.json` 里的 `timeout`,或 `MCP_TOOL_TIMEOUT`),撞上就把这次调用掐掉。默认 2 分钟带进度返回,靠反复调而不是一次等到黑。
|
|
265
312
|
- **不往 Codex 原生 goal 写数据**:`goals_1.sqlite` 归 Codex 所有,本 MCP 只读。worker 起来后由它自己调 Codex 的 `create_goal` 建原生 goal,本 MCP 只负责在派单时把这段指令拼进 prompt。
|
|
266
313
|
- **原生 goal 依赖模型照做**:`codex exec` 不会自动建 goal,是派单时那段指令让 worker 建的。模型偶尔漏调,这时 `native_goal` 为 `null`,`get_worker_goal` 退回派单时记录的那份,不影响状态机。
|
|
267
314
|
- **`search_works` 是子串匹配,不是全文索引**:几百条 work 的规模下 `LIKE` 扫描足够快,也省掉一套索引的维护成本。上到几万条再谈别的。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-supervisor-mcp",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.3",
|
|
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",
|
package/src/event-parser.js
CHANGED
|
@@ -20,6 +20,17 @@ function inferAgentMessage(item) {
|
|
|
20
20
|
return item?.text ?? item?.message ?? item?.content ?? item?.output_text ?? null;
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
// The stored event stream is raw Codex JSONL, so reading a worker's own report
|
|
24
|
+
// back out means walking `item.completed` events whose item is an
|
|
25
|
+
// agent_message. The live state machine and the on-demand result reader share
|
|
26
|
+
// this one extraction.
|
|
27
|
+
export function extractAgentMessage(event) {
|
|
28
|
+
const item = getItem(event);
|
|
29
|
+
const itemType = item?.type ?? item?.kind ?? item?.name ?? null;
|
|
30
|
+
if (itemType !== "agent_message") return null;
|
|
31
|
+
return inferAgentMessage(item);
|
|
32
|
+
}
|
|
33
|
+
|
|
23
34
|
// Codex reports edits as {"changes":[{"path": "...", "kind": "add"}]}. The
|
|
24
35
|
// older flat shapes are kept for compatibility with other event producers.
|
|
25
36
|
function inferChangedFiles(item) {
|
package/src/mcp-server.js
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
getTask,
|
|
13
13
|
getTasks,
|
|
14
14
|
listTaskEventKinds,
|
|
15
|
+
readAgentMessages,
|
|
15
16
|
readTaskEvents,
|
|
16
17
|
readTasks,
|
|
17
18
|
readTasksBySession,
|
|
@@ -22,7 +23,7 @@ import {
|
|
|
22
23
|
import { readNativeGoal } from "./goal-store.js";
|
|
23
24
|
import { mergeChangedFiles, readWorktreeChanges } from "./worktree.js";
|
|
24
25
|
import { ACTIVE_STATUSES, TERMINAL_STATUSES, TASK_STATUSES, isGoalNeedingAttention } from "./status.js";
|
|
25
|
-
import { approxTokenCount, truncateEventStrings } from "./truncate.js";
|
|
26
|
+
import { approxTokenCount, truncateEventStrings, truncateMiddleChars } from "./truncate.js";
|
|
26
27
|
|
|
27
28
|
const server = new McpServer({
|
|
28
29
|
name: "codex-supervisor",
|
|
@@ -95,6 +96,42 @@ function summarizeTask(task) {
|
|
|
95
96
|
};
|
|
96
97
|
}
|
|
97
98
|
|
|
99
|
+
// The dispatch receipt. Dispatch used to return the whole task record, which
|
|
100
|
+
// echoes the task text - and for a follow-up, the parent prompt plus 20 raw
|
|
101
|
+
// events - back to the caller on every call. Dispatching eleven workers made
|
|
102
|
+
// the main thread pay for its own instructions eleven times, and pushed the
|
|
103
|
+
// result into the client's MCP output cap. Read the rest per worker with
|
|
104
|
+
// get_worker_summary / get_worker_result when you actually need it.
|
|
105
|
+
function receipt(task) {
|
|
106
|
+
return {
|
|
107
|
+
id: task.id,
|
|
108
|
+
title: task.title,
|
|
109
|
+
worker: task.worker,
|
|
110
|
+
status: task.status,
|
|
111
|
+
phase: task.phase ?? null,
|
|
112
|
+
cwd: task.cwd,
|
|
113
|
+
project_root: task.project_root,
|
|
114
|
+
worktree_path: task.worktree_path,
|
|
115
|
+
branch: task.worktree_path ? `codex/${task.id}` : null,
|
|
116
|
+
sandbox: task.sandbox,
|
|
117
|
+
model: task.model,
|
|
118
|
+
reasoning_effort: task.reasoning_effort,
|
|
119
|
+
thread_id: task.thread_id,
|
|
120
|
+
session_id: task.session_id ?? null,
|
|
121
|
+
followup_of: task.followup_of,
|
|
122
|
+
resumed_from: task.resumed_from,
|
|
123
|
+
depends_on: task.depends_on ?? [],
|
|
124
|
+
owned_paths: task.owned_paths ?? [],
|
|
125
|
+
goal_objective: task.goal_objective,
|
|
126
|
+
goal_token_budget: task.goal_token_budget,
|
|
127
|
+
error: task.error ?? null,
|
|
128
|
+
run_count: task.run_count ?? 0,
|
|
129
|
+
run_log: task.run_log,
|
|
130
|
+
created_at: task.created_at,
|
|
131
|
+
updated_at: task.updated_at
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
98
135
|
function overviewRow(task, caps) {
|
|
99
136
|
return {
|
|
100
137
|
id: task.id,
|
|
@@ -245,7 +282,8 @@ server.registerTool(
|
|
|
245
282
|
},
|
|
246
283
|
async (input) => {
|
|
247
284
|
try {
|
|
248
|
-
|
|
285
|
+
const record = await createCodexWorker({ ...input, sessionId: input.session_id ?? null });
|
|
286
|
+
return textResult(receipt(record));
|
|
249
287
|
} catch (error) {
|
|
250
288
|
return errorResult(error);
|
|
251
289
|
}
|
|
@@ -278,14 +316,13 @@ server.registerTool(
|
|
|
278
316
|
},
|
|
279
317
|
async ({ task_id, followup_prompt, session_id, ...options }) => {
|
|
280
318
|
try {
|
|
281
|
-
|
|
282
|
-
await createFollowupWorker({
|
|
319
|
+
const record = await createFollowupWorker({
|
|
283
320
|
taskId: task_id,
|
|
284
321
|
followupPrompt: followup_prompt,
|
|
285
322
|
sessionId: session_id ?? null,
|
|
286
323
|
...options
|
|
287
|
-
})
|
|
288
|
-
);
|
|
324
|
+
});
|
|
325
|
+
return textResult(receipt(record));
|
|
289
326
|
} catch (error) {
|
|
290
327
|
return errorResult(error);
|
|
291
328
|
}
|
|
@@ -305,7 +342,8 @@ server.registerTool(
|
|
|
305
342
|
},
|
|
306
343
|
async ({ task_id, prompt }) => {
|
|
307
344
|
try {
|
|
308
|
-
|
|
345
|
+
const record = await resumeCodexWorker({ taskId: task_id, prompt });
|
|
346
|
+
return textResult(receipt(record));
|
|
309
347
|
} catch (error) {
|
|
310
348
|
return errorResult(error);
|
|
311
349
|
}
|
|
@@ -358,11 +396,12 @@ server.registerTool(
|
|
|
358
396
|
"wait_codex_workers",
|
|
359
397
|
{
|
|
360
398
|
title: "Wait for Codex workers",
|
|
361
|
-
description:
|
|
399
|
+
description:
|
|
400
|
+
"Block until selected Codex workers reach a terminal status, then return summaries. The wait budget bounds this call, not the workers: when it runs out you get a progress snapshot and the workers keep running, so call this again with the same task_ids to keep waiting. Keep the budget under your client's MCP tool timeout, or the client kills the call instead of the wait returning.",
|
|
362
401
|
inputSchema: {
|
|
363
402
|
task_ids: z.array(z.string().min(1)).min(1),
|
|
364
403
|
mode: z.enum(["any", "all"]).default("all"),
|
|
365
|
-
timeoutMinutes: z.number().int().min(1).max(360).default(
|
|
404
|
+
timeoutMinutes: z.number().int().min(1).max(360).default(2),
|
|
366
405
|
timeoutMs: z.number().int().min(1000).max(21600000).optional(),
|
|
367
406
|
pollMs: z.number().int().min(250).max(10000).default(1000),
|
|
368
407
|
includeEvents: z.boolean().default(true),
|
|
@@ -413,9 +452,18 @@ server.registerTool(
|
|
|
413
452
|
}))
|
|
414
453
|
);
|
|
415
454
|
|
|
455
|
+
const budgetLabel =
|
|
456
|
+
effectiveTimeoutMs >= 60000
|
|
457
|
+
? `${Math.round(effectiveTimeoutMs / 60000)}-minute`
|
|
458
|
+
: `${Math.round(effectiveTimeoutMs / 1000)}-second`;
|
|
459
|
+
|
|
416
460
|
return textResult({
|
|
417
461
|
mode,
|
|
418
462
|
timed_out: timedOut,
|
|
463
|
+
still_running: timedOut,
|
|
464
|
+
next_step: timedOut
|
|
465
|
+
? `Workers are still running; the ${budgetLabel} wait budget ran out, not the workers. Call wait_codex_workers again with the same task_ids, or use get_orchestration_overview for a cheap progress read. Raise timeoutMinutes only if your client's MCP tool timeout allows it.`
|
|
466
|
+
: null,
|
|
419
467
|
waited_ms: Date.now() - startedAt,
|
|
420
468
|
timeout_ms: effectiveTimeoutMs,
|
|
421
469
|
timeout_minutes: Math.round(effectiveTimeoutMs / 60000),
|
|
@@ -562,6 +610,51 @@ server.registerTool(
|
|
|
562
610
|
}
|
|
563
611
|
);
|
|
564
612
|
|
|
613
|
+
server.registerTool(
|
|
614
|
+
"get_worker_result",
|
|
615
|
+
{
|
|
616
|
+
title: "Get worker result",
|
|
617
|
+
description:
|
|
618
|
+
"Read a worker's own final report in full. The overview and the wait response clip the last message so a batch stays inside a context budget; this is the door for the actual conclusion. Returns the last N agent messages plus the status fields needed to tell a real finish from a crash.",
|
|
619
|
+
inputSchema: {
|
|
620
|
+
task_id: z.string().min(1),
|
|
621
|
+
limit: z.number().int().min(1).max(20).default(1),
|
|
622
|
+
maxChars: z.number().int().min(0).max(1000000).optional()
|
|
623
|
+
}
|
|
624
|
+
},
|
|
625
|
+
async ({ task_id, limit, maxChars }) => {
|
|
626
|
+
const task = await getTask(task_id);
|
|
627
|
+
if (!task) return textResult({ error: "task_not_found", task_id });
|
|
628
|
+
let reports = await readAgentMessages(task_id, limit);
|
|
629
|
+
let source = "event_stream";
|
|
630
|
+
if (reports.length === 0 && task.last_message) {
|
|
631
|
+
// Older rows can predate this tool, but the task row keeps the newest
|
|
632
|
+
// report even when the stream query finds nothing.
|
|
633
|
+
reports = [task.last_message];
|
|
634
|
+
source = "task_row";
|
|
635
|
+
}
|
|
636
|
+
const truncated = maxChars === undefined ? reports : reports.map((text) => truncateMiddleChars(text, maxChars));
|
|
637
|
+
const changed = mergeChangedFiles(task.changed_files, readWorktreeChanges(task.worktree_path));
|
|
638
|
+
return textResult({
|
|
639
|
+
task_id,
|
|
640
|
+
title: task.title,
|
|
641
|
+
status: task.status,
|
|
642
|
+
phase: task.phase ?? null,
|
|
643
|
+
exit_code: task.exit_code ?? null,
|
|
644
|
+
thread_id: task.thread_id,
|
|
645
|
+
session_id: task.session_id ?? null,
|
|
646
|
+
worktree_path: task.worktree_path,
|
|
647
|
+
goal_status: task.goal_status,
|
|
648
|
+
changed_files: changed,
|
|
649
|
+
report_count: truncated.length,
|
|
650
|
+
reports: truncated,
|
|
651
|
+
source,
|
|
652
|
+
error: task.error ?? null,
|
|
653
|
+
completed_at: task.completed_at ?? null
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
);
|
|
657
|
+
|
|
565
658
|
server.registerTool(
|
|
566
659
|
"cancel_codex_worker",
|
|
567
660
|
{
|
package/src/task-store.js
CHANGED
|
@@ -2,6 +2,7 @@ import { mkdir } from "node:fs/promises";
|
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { DatabaseSync } from "node:sqlite";
|
|
4
4
|
import { dataDir, dbPath, runsDir } from "./paths.js";
|
|
5
|
+
import { extractAgentMessage } from "./event-parser.js";
|
|
5
6
|
import { ACTIVE_STATUSES, PHASES } from "./status.js";
|
|
6
7
|
|
|
7
8
|
let db;
|
|
@@ -406,6 +407,31 @@ export async function listTaskEventKinds(taskId) {
|
|
|
406
407
|
`).all(taskId);
|
|
407
408
|
}
|
|
408
409
|
|
|
410
|
+
// A worker's report is the only thing a supervisor usually wants back, and the
|
|
411
|
+
// task row keeps just the most recent one. This reads them out of the raw
|
|
412
|
+
// stream newest-first: `payload LIKE` is a cheap prefilter, and every row that
|
|
413
|
+
// survives it is verified through the same extraction the state machine uses.
|
|
414
|
+
export async function readAgentMessages(taskId, limit = 1) {
|
|
415
|
+
await ensureFilesystem();
|
|
416
|
+
const rows = openDb().prepare(`
|
|
417
|
+
SELECT payload FROM task_events
|
|
418
|
+
WHERE task_id = ? AND event_type = 'item.completed' AND payload LIKE '%"agent_message"%'
|
|
419
|
+
ORDER BY seq DESC LIMIT ?
|
|
420
|
+
`).all(taskId, limit * 5 + 10);
|
|
421
|
+
const messages = [];
|
|
422
|
+
for (const row of rows) {
|
|
423
|
+
let text = null;
|
|
424
|
+
try {
|
|
425
|
+
text = extractAgentMessage(JSON.parse(row.payload));
|
|
426
|
+
} catch {
|
|
427
|
+
text = null;
|
|
428
|
+
}
|
|
429
|
+
if (text) messages.push(text);
|
|
430
|
+
if (messages.length >= limit) break;
|
|
431
|
+
}
|
|
432
|
+
return messages.reverse();
|
|
433
|
+
}
|
|
434
|
+
|
|
409
435
|
export async function taskCount() {
|
|
410
436
|
await ensureFilesystem();
|
|
411
437
|
const row = openDb().prepare("SELECT COUNT(*) AS count FROM tasks").get();
|