codex-supervisor-mcp 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +80 -17
- package/package.json +4 -3
- package/src/bin-resolver.js +287 -0
- package/src/codex-runner.js +135 -33
- package/src/setup.js +64 -37
package/README.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# codex-supervisor-mcp
|
|
2
2
|
|
|
3
|
+
[](https://www.npmjs.com/package/codex-supervisor-mcp)
|
|
4
|
+
[](https://www.npmjs.com/package/codex-supervisor-mcp)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
[](https://github.com/zriyox/codex-supervisor-mcp/actions/workflows/ci.yml)
|
|
7
|
+
[](package.json)
|
|
8
|
+
|
|
3
9
|
让一个主线程(Claude Code、Codex、任何 MCP 客户端)同时指挥多个 Codex worker 干活。
|
|
4
10
|
|
|
5
11
|
一个 worker 一个独立 Git worktree,一个 worker 一个原生 Codex goal,状态全部落盘。主线程负责派单、等待、读结果、断线重连、取消。
|
|
@@ -33,31 +39,48 @@ Codex worker ──► data/runs/<taskId>.jsonl 原始 JSONL 事件流
|
|
|
33
39
|
|
|
34
40
|
## 安装
|
|
35
41
|
|
|
36
|
-
|
|
42
|
+
前置:**Node.js >= 22.13.0**(`node:sqlite` 在这个版本之前没有无 flag 的构建)和 `codex` CLI 在 `PATH` 里。macOS、Linux、Windows 都支持。
|
|
43
|
+
|
|
44
|
+
### 快速开始
|
|
37
45
|
|
|
38
46
|
```bash
|
|
47
|
+
# 1. 装
|
|
39
48
|
npm install -g codex-supervisor-mcp
|
|
49
|
+
|
|
50
|
+
# 2. 确认挂上了
|
|
51
|
+
claude mcp list | grep codex-supervisor
|
|
52
|
+
codex mcp list | grep codex-supervisor
|
|
40
53
|
```
|
|
41
54
|
|
|
42
|
-
|
|
55
|
+
全局安装的 `postinstall` 会自动做两件事,**不需要手动配置**:
|
|
43
56
|
|
|
44
57
|
1. 把配套 skill 装进检测到的客户端目录:`~/.claude/skills/`、`~/.agents/skills/`、`~/.codex/skills/`。
|
|
45
|
-
2. 用客户端自带的 CLI 注册 MCP:`claude mcp add -s user` / `codex mcp add
|
|
58
|
+
2. 用客户端自带的 CLI 注册 MCP:`claude mcp add -s user` / `codex mcp add`,注册的是 `node <包内绝对路径>`。
|
|
59
|
+
|
|
60
|
+
skill 已存在且内容不同时,先写一份 `SKILL.md.bak-<时间戳>` 再覆盖。任何一步失败都不会让安装失败。
|
|
61
|
+
|
|
62
|
+
### 手动挂载
|
|
46
63
|
|
|
47
|
-
|
|
64
|
+
`postinstall` 没跑到(`--ignore-scripts`、`npx`、pnpm 之类)时,自己补一条:
|
|
48
65
|
|
|
49
|
-
|
|
66
|
+
| 客户端 | 命令 |
|
|
67
|
+
|---|---|
|
|
68
|
+
| Claude Code | `claude mcp add -s user codex-supervisor -- npx -y codex-supervisor-mcp` |
|
|
69
|
+
| Codex | `codex mcp add codex-supervisor -- npx -y codex-supervisor-mcp` |
|
|
70
|
+
|
|
71
|
+
重跑、修复、只装某一个客户端,或者先看它打算干什么:
|
|
50
72
|
|
|
51
73
|
```bash
|
|
52
|
-
codex-supervisor-setup #
|
|
74
|
+
codex-supervisor-setup # 自动检测客户端,补装 skill + 注册 MCP
|
|
53
75
|
codex-supervisor-setup --target claude,codex
|
|
54
|
-
codex-supervisor-setup --skill-only # 只装 skill
|
|
55
|
-
codex-supervisor-setup --
|
|
76
|
+
codex-supervisor-setup --skill-only # 只装 skill,不碰 MCP 配置
|
|
77
|
+
codex-supervisor-setup --mcp-only # 只注册 MCP,不装 skill
|
|
78
|
+
codex-supervisor-setup --dry-run # 只打印计划,不改任何东西
|
|
56
79
|
```
|
|
57
80
|
|
|
58
|
-
|
|
81
|
+
### 挂到 GUI 客户端
|
|
59
82
|
|
|
60
|
-
|
|
83
|
+
自己建/改下面的配置文件,加这一段(GUI 客户端不会跑 `postinstall`):
|
|
61
84
|
|
|
62
85
|
```json
|
|
63
86
|
{
|
|
@@ -70,12 +93,47 @@ codex-supervisor-setup --dry-run # 只打印计划
|
|
|
70
93
|
}
|
|
71
94
|
```
|
|
72
95
|
|
|
73
|
-
|
|
96
|
+
| 客户端 | macOS | Windows | Linux |
|
|
97
|
+
|---|---|---|---|
|
|
98
|
+
| Claude Desktop | `~/Library/Application Support/Claude/claude_desktop_config.json` | `%APPDATA%\Claude\claude_desktop_config.json` | `~/.config/Claude/claude_desktop_config.json` |
|
|
99
|
+
| Cursor | `~/.cursor/mcp.json` | `%APPDATA%\Cursor\mcp.json` | `~/.config/cursor/mcp.json` |
|
|
100
|
+
| Windsurf | `~/.codeium/windsurf/mcp_config.json` | `%APPDATA%\Codeium\windsurf\mcp_config.json` | `~/.config/.codeium/windsurf/mcp_config.json` |
|
|
101
|
+
|
|
102
|
+
### npx 的坑
|
|
103
|
+
|
|
104
|
+
`npx` 不跑 `postinstall`,所以 **skill 不会自动装、MCP 也不会自动注册**,只有 MCP server 本身能起来。要用配套 skill 就还是得 `npm install -g`,或者手动跑一次 `codex-supervisor-setup`。
|
|
105
|
+
|
|
106
|
+
### 卸载
|
|
74
107
|
|
|
75
108
|
```bash
|
|
76
|
-
|
|
109
|
+
npm uninstall -g codex-supervisor-mcp
|
|
110
|
+
claude mcp remove -s user codex-supervisor
|
|
111
|
+
codex mcp remove codex-supervisor
|
|
112
|
+
rm -rf ~/.claude/skills/codex-supervisor ~/.agents/skills/codex-supervisor ~/.codex/skills/codex-supervisor
|
|
113
|
+
rm -rf ~/.codex-supervisor # 状态目录:sqlite、事件流、worktree 全在这
|
|
77
114
|
```
|
|
78
115
|
|
|
116
|
+
### Windows
|
|
117
|
+
|
|
118
|
+
三条实现细节值得知道:
|
|
119
|
+
|
|
120
|
+
- 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` 时同样处理。
|
|
121
|
+
- 跨进程取消用 `taskkill /PID <pid> /T /F` 结束整棵进程树;确认这个 pid 还是 Codex 用 PowerShell 的 `Get-CimInstance Win32_Process` 读命令行(拿不到时退到 `tasklist`)。`ps` 只在 macOS / Linux 上用。
|
|
122
|
+
- 除了 `PATH`,还会探 `%APPDATA%\npm`、`%LOCALAPPDATA%\pnpm`、`%LOCALAPPDATA%\Volta\bin`、`%ProgramFiles%\nodejs`。
|
|
123
|
+
|
|
124
|
+
自动安装只在**全局安装**时发生。`npx`、`--ignore-scripts`、以及被别人当项目依赖装的场景都不会触发。要跳过用 `CODEX_SUPERVISOR_SKIP_SETUP=1`。
|
|
125
|
+
|
|
126
|
+
### 疑难排查
|
|
127
|
+
|
|
128
|
+
| 症状 | 原因 | 处理 |
|
|
129
|
+
|---|---|---|
|
|
130
|
+
| `claude mcp list` 里没有 `codex-supervisor` | `npx` / `--ignore-scripts` 装法不跑 `postinstall` | 跑 `codex-supervisor-setup`,或用上面的手动挂载 |
|
|
131
|
+
| 派单报 `codex only resolved to a shell shim` | Windows 上只找到 `.cmd`,背后的 npm 包入口不在了 | 重装 `@openai/codex`,或把 `CODEX_BIN` 指到真正的可执行文件 / `codex.js` |
|
|
132
|
+
| worker 起来就 `failed`,错误是 `spawn codex ENOENT` | GUI 客户端启动的进程 `PATH` 里没有 `codex` | 在客户端配置里显式设 `CODEX_BIN` |
|
|
133
|
+
| `Cannot find module 'node:sqlite'` | Node < 22.13.0 | 升 Node |
|
|
134
|
+
| worker 卡在 `lost` | MCP 进程被 kill,worker 成了孤儿 | `list_codex_workers` 结算一次,或 `resume_codex_worker` 接回来 |
|
|
135
|
+
| 报 `ownedPaths overlap with active worker(s)` | 两个 worker 认领了同一片路径 | 换路径,或先 `cancel_codex_worker` 掉占用的那个 |
|
|
136
|
+
|
|
79
137
|
## 工具
|
|
80
138
|
|
|
81
139
|
13 个工具。
|
|
@@ -143,6 +201,8 @@ starting → thinking → command → editing → reporting
|
|
|
143
201
|
|
|
144
202
|
`failed` 和 `lost` 分开是有用的:前者要看日志找原因,后者直接重跑。
|
|
145
203
|
|
|
204
|
+
Windows 上没有信号,所以这两者在那里只有一种能判出来。libuv 杀进程走的是 `TerminateProcess(handle, 1)`,外部 kill 和进程自己 `exit(1)` 落到父进程手里完全一样(都是 `exit_code=1`、`signal=null`)。这种情况下报能证明的那个——`failed` 加退出码——而不是编一个平台根本没收到的信号名。Windows 上的 `lost` 仍然会发生,走的是 MCP 进程消失、下次启动结算孤儿那条路。
|
|
205
|
+
|
|
146
206
|
### goal 和 work 的映射
|
|
147
207
|
|
|
148
208
|
Codex 原生 goal 有六个状态,映射到 work 状态:
|
|
@@ -178,7 +238,7 @@ Codex 原生 goal 有六个状态,映射到 work 状态:
|
|
|
178
238
|
|---|---|---|
|
|
179
239
|
| `SUPERVISOR_HOME` | `~/.codex-supervisor` | 状态根目录(sqlite / 事件流 / worktree 都在它下面) |
|
|
180
240
|
| `CODEX_HOME` | `~/.codex` | 只读,用来读 Codex 原生的 `goals_1.sqlite` |
|
|
181
|
-
| `CODEX_BIN` | `codex`(走 `PATH`) | Codex CLI
|
|
241
|
+
| `CODEX_BIN` | `codex`(走 `PATH`) | Codex CLI 可执行文件路径。Windows 上给裸名字时会按 `PATHEXT` 展开,`.cmd` shim 会被自动绕开;指向 `.js` / `.cjs` / `.mjs` 时自动用 `node` 起它 |
|
|
182
242
|
| `GIT_BIN` | `git`(走 `PATH`) | Git 可执行文件路径 |
|
|
183
243
|
|
|
184
244
|
如果 MCP 客户端启动时 `PATH` 里没有 `codex`(GUI 启动的应用常见),显式设置 `CODEX_BIN`:
|
|
@@ -201,7 +261,7 @@ Codex 原生 goal 有六个状态,映射到 work 状态:
|
|
|
201
261
|
- **不往 Codex 原生 goal 写数据**:`goals_1.sqlite` 归 Codex 所有,本 MCP 只读。worker 起来后由它自己调 Codex 的 `create_goal` 建原生 goal,本 MCP 只负责在派单时把这段指令拼进 prompt。
|
|
202
262
|
- **原生 goal 依赖模型照做**:`codex exec` 不会自动建 goal,是派单时那段指令让 worker 建的。模型偶尔漏调,这时 `native_goal` 为 `null`,`get_worker_goal` 退回派单时记录的那份,不影响状态机。
|
|
203
263
|
- **`search_works` 是子串匹配,不是全文索引**:几百条 work 的规模下 `LIKE` 扫描足够快,也省掉一套索引的维护成本。上到几万条再谈别的。
|
|
204
|
-
- **跨进程取消按 pid
|
|
264
|
+
- **跨进程取消按 pid**:进程句柄不在本进程时,会先确认那个 pid 的命令行里含 `codex`(macOS / Linux 用 `ps`,Windows 用 CIM,退到 `tasklist`),再发 `SIGTERM`(Windows 上是 `taskkill /T /F`),避免误杀被复用的 pid。
|
|
205
265
|
- **`create_codex_followup_worker` 和 `resume_codex_worker` 不是一回事**:前者开新会话、靠文本重述上下文;后者接同一个会话。要细节不丢就用后者。
|
|
206
266
|
- **`session_id` 由派单方自己传,本 MCP 不生成**:一批活传同一个值,`get_session_works` 才能把它们归到一起。不传就是 `NULL`,事后按 session 找不回来。
|
|
207
267
|
|
|
@@ -215,8 +275,9 @@ Codex 原生 goal 有六个状态,映射到 work 状态:
|
|
|
215
275
|
6. ~~session 维度:`session_id` 落库 + `get_session_works` 断线重连~~
|
|
216
276
|
7. ~~按关键词找历史 work:`search_works`~~
|
|
217
277
|
8. ~~worker 原生 goal:派单时注入 `create_goal` 指令~~
|
|
218
|
-
9.
|
|
219
|
-
10.
|
|
278
|
+
9. ~~Windows 支持:`.cmd` shim 绕行、`taskkill` 进程树、跨平台 PATH / `PATHEXT`~~ ✅
|
|
279
|
+
10. 常驻 daemon:派单和进程生命周期从 MCP 进程里拿出来
|
|
280
|
+
11. React 实时看板
|
|
220
281
|
|
|
221
282
|
砍掉不做的(说明理由,免得以后又想起来):
|
|
222
283
|
|
|
@@ -247,7 +308,7 @@ skill 里写了派单流程、读结果该按什么顺序、`failed` 和 `lost`
|
|
|
247
308
|
|
|
248
309
|
```bash
|
|
249
310
|
npm install
|
|
250
|
-
npm test #
|
|
311
|
+
npm test # 确定性测试:截断、状态机、v1→v2 迁移、setup、Windows 路由、17 项端到端回归
|
|
251
312
|
npm run test:real # 用真 codex CLI 跑端到端(含跨进程 resume、worktree 隔离)
|
|
252
313
|
npm run smoke # 基础冒烟(真 codex)
|
|
253
314
|
npm run smoke:mcp # MCP 协议冒烟
|
|
@@ -256,6 +317,8 @@ npm run monitor # Ink 终端看板
|
|
|
256
317
|
|
|
257
318
|
`npm test` 用 `src/test-fixtures/fake-codex.js` 回放固定的 Codex 事件流,跑得快且确定。`npm run test:real` 会真的调 `codex exec`,慢一些,但它才是「跟最新 Codex 兼容」的证据。
|
|
258
319
|
|
|
320
|
+
CI 跑 Ubuntu / macOS / Windows 三个平台,另外单独跑一个 Node 22.13.0 的 job 卡住 `engines` 声明的下界(`node:sqlite` 在它之前没有无 flag 的构建)。Windows 那 4 项 `setup-windows-test.js` 用真实文件系统模拟 `%APPDATA%\npm` 下的 `.cmd` shim,验证自动注册 MCP 这条路真的走得通,而不只是「解析函数单测过了」。
|
|
321
|
+
|
|
259
322
|
## License
|
|
260
323
|
|
|
261
324
|
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-supervisor-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "MCP server that dispatches and supervises parallel Codex CLI workers, one isolated Git worktree each, with a persisted work state machine.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
},
|
|
29
29
|
"files": [
|
|
30
30
|
"src/mcp-server.js",
|
|
31
|
+
"src/bin-resolver.js",
|
|
31
32
|
"src/setup.js",
|
|
32
33
|
"src/codex-runner.js",
|
|
33
34
|
"src/task-store.js",
|
|
@@ -50,7 +51,7 @@
|
|
|
50
51
|
"start": "node ./src/mcp-server.js",
|
|
51
52
|
"monitor": "tsx ./src/monitor.jsx",
|
|
52
53
|
"cleanup": "node ./src/cleanup.js",
|
|
53
|
-
"test": "node ./src/truncate-test.js && node ./src/status-test.js && node ./src/migration-test.js && node ./src/setup-test.js && node ./src/regression-test.js",
|
|
54
|
+
"test": "node ./src/bin-resolver-test.js && node ./src/truncate-test.js && node ./src/status-test.js && node ./src/migration-test.js && node ./src/setup-test.js && node ./src/setup-windows-test.js && node ./src/regression-test.js",
|
|
54
55
|
"test:real": "node ./src/real-codex-test.js",
|
|
55
56
|
"smoke": "node ./src/smoke-test.js",
|
|
56
57
|
"smoke:followup": "node ./src/followup-smoke-test.js",
|
|
@@ -66,6 +67,6 @@
|
|
|
66
67
|
"tsx": "^4.21.0"
|
|
67
68
|
},
|
|
68
69
|
"engines": {
|
|
69
|
-
"node": ">=22"
|
|
70
|
+
"node": ">=22.13.0"
|
|
70
71
|
}
|
|
71
72
|
}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
// Turns a CLI name into something Node can actually spawn.
|
|
2
|
+
//
|
|
3
|
+
// Why this exists: on Windows npm installs a CLI as a `codex.cmd` / `codex.ps1`
|
|
4
|
+
// shim rather than an executable, and since the CVE-2024-27980 hardening in
|
|
5
|
+
// Node 18.20 / 20.12 `spawn` with shell:false refuses to run one (EINVAL), so
|
|
6
|
+
// the worker never starts. `shell: true` would "fix" that at the cost of the
|
|
7
|
+
// kill semantics this project depends on: the shell becomes the child, so
|
|
8
|
+
// cancelling a task kills cmd.exe and leaves the real Codex process running,
|
|
9
|
+
// which wedges the state machine in `running`.
|
|
10
|
+
//
|
|
11
|
+
// So instead of shelling out, resolve a spawnable target: a real .exe, or -
|
|
12
|
+
// for the npm shim case - the package's own entry point, run under node.
|
|
13
|
+
//
|
|
14
|
+
// Platform, env, filesystem probe and node path are all injectable, so the
|
|
15
|
+
// win32 branch is unit-testable from macOS and Linux.
|
|
16
|
+
import { existsSync } from "node:fs";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
|
|
20
|
+
/** Windows extensions Node/libuv can hand straight to CreateProcess. */
|
|
21
|
+
const DIRECT_EXTS = new Set([".exe", ".com"]);
|
|
22
|
+
/** Windows extensions that need an interpreter - the npm-shim case. */
|
|
23
|
+
const SHIM_EXTS = new Set([".cmd", ".bat", ".ps1"]);
|
|
24
|
+
/** Fallback when PATHEXT is unset, matching the Windows default. */
|
|
25
|
+
const DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD";
|
|
26
|
+
/** Extensions that need node in front of them on every platform. */
|
|
27
|
+
const JS_EXTS = new Set([".js", ".cjs", ".mjs"]);
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Well-known global install directories, probed after PATH. A CLI installed with
|
|
31
|
+
* a custom npm prefix or a version manager is usually absent from a
|
|
32
|
+
* non-interactive PATH, and without this it would look "not installed" even
|
|
33
|
+
* though the user runs it every day. The Windows entries are env-derived, so
|
|
34
|
+
* they simply drop out elsewhere.
|
|
35
|
+
*
|
|
36
|
+
* @param {Object} [options]
|
|
37
|
+
* @param {Record<string, string|undefined>} [options.env]
|
|
38
|
+
* @param {string} [options.home]
|
|
39
|
+
* @returns {string[]}
|
|
40
|
+
*/
|
|
41
|
+
export function defaultBinDirs(options = {}) {
|
|
42
|
+
const env = options.env ?? process.env;
|
|
43
|
+
const home = options.home ?? homedir();
|
|
44
|
+
const dirs = [
|
|
45
|
+
path.join(home, ".npm-global", "bin"),
|
|
46
|
+
path.join(home, ".local", "bin"),
|
|
47
|
+
path.join(home, ".bun", "bin"),
|
|
48
|
+
path.join(home, ".volta", "bin"),
|
|
49
|
+
path.join(home, "Library", "pnpm"),
|
|
50
|
+
"/opt/homebrew/bin",
|
|
51
|
+
"/usr/local/bin"
|
|
52
|
+
];
|
|
53
|
+
for (const [variable, ...segments] of [
|
|
54
|
+
["APPDATA", "npm"], // npm global prefix on Windows
|
|
55
|
+
["LOCALAPPDATA", "pnpm"],
|
|
56
|
+
["LOCALAPPDATA", "Volta", "bin"],
|
|
57
|
+
["ProgramFiles", "nodejs"] // nvm-windows and the official installer
|
|
58
|
+
]) {
|
|
59
|
+
const root = env[variable]?.trim();
|
|
60
|
+
if (root) dirs.push(path.join(root, ...segments));
|
|
61
|
+
}
|
|
62
|
+
return dirs;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const isWindows = (platform) => platform === "win32";
|
|
66
|
+
const pathImpl = (platform) => (isWindows(platform) ? path.win32 : path.posix);
|
|
67
|
+
const listSeparator = (platform) => (isWindows(platform) ? ";" : ":");
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @typedef {Object} NpmEntryHint
|
|
71
|
+
* @property {string} pkg npm package name, e.g. "@openai/codex"
|
|
72
|
+
* @property {string} bin entry path inside the package, e.g. "bin/codex.js"
|
|
73
|
+
*/
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @typedef {Object} SpawnTarget
|
|
77
|
+
* @property {string} cmd first argument to pass to spawn
|
|
78
|
+
* @property {string[]} prefixArgs args to prepend before the caller's own argv
|
|
79
|
+
* @property {boolean} shim true when the only match needs a shell we refuse to
|
|
80
|
+
* use - the caller should fail with an actionable message instead of spawning
|
|
81
|
+
*/
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Locate a CLI on PATH (plus optional extra directories) and return its real
|
|
85
|
+
* path, or null. On win32 the PATHEXT ladder is applied, so a bare `codex`
|
|
86
|
+
* resolves to `codex.cmd`; everywhere else the bare name is joined onto each
|
|
87
|
+
* PATH entry. A name carrying a path separator is probed as-is.
|
|
88
|
+
*
|
|
89
|
+
* @param {string} binary
|
|
90
|
+
* @param {Object} [options]
|
|
91
|
+
* @param {string} [options.platform]
|
|
92
|
+
* @param {Record<string, string|undefined>} [options.env]
|
|
93
|
+
* @param {(p: string) => boolean} [options.exists]
|
|
94
|
+
* @param {string[]} [options.extraDirs] well-known dirs to probe after PATH
|
|
95
|
+
* @returns {string|null}
|
|
96
|
+
*/
|
|
97
|
+
export function findBinaryPath(binary, options = {}) {
|
|
98
|
+
if (!binary) return null;
|
|
99
|
+
const platform = options.platform ?? process.platform;
|
|
100
|
+
const env = options.env ?? process.env;
|
|
101
|
+
const exists = options.exists ?? existsSync;
|
|
102
|
+
const extraDirs = options.extraDirs ?? [];
|
|
103
|
+
const p = pathImpl(platform);
|
|
104
|
+
|
|
105
|
+
if (binary.includes("/") || binary.includes("\\")) return exists(binary) ? binary : null;
|
|
106
|
+
|
|
107
|
+
const fromPath = String(env.PATH ?? env.Path ?? "")
|
|
108
|
+
.split(listSeparator(platform))
|
|
109
|
+
.filter(Boolean);
|
|
110
|
+
const dirs = [...fromPath, ...extraDirs];
|
|
111
|
+
const suffixes = isWindows(platform)
|
|
112
|
+
? String(env.PATHEXT || DEFAULT_PATHEXT)
|
|
113
|
+
.split(";")
|
|
114
|
+
.filter(Boolean)
|
|
115
|
+
.map((ext) => ext.toLowerCase())
|
|
116
|
+
: [""];
|
|
117
|
+
|
|
118
|
+
for (const dir of dirs) {
|
|
119
|
+
for (const suffix of suffixes) {
|
|
120
|
+
const candidate = p.join(dir, binary + suffix);
|
|
121
|
+
if (exists(candidate)) return candidate;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Resolve a command name into a spawnable target.
|
|
129
|
+
*
|
|
130
|
+
* A JS entry point (`.js` / `.cjs` / `.mjs`) is run under node on every
|
|
131
|
+
* platform, because a script is not something either kernel can spawn on its
|
|
132
|
+
* own: Windows refuses outright, and POSIX only manages it while the shebang
|
|
133
|
+
* and the executable bit survive - which a checkout or a copy can drop. This
|
|
134
|
+
* matters for `CODEX_BIN`, whose natural value is the npm package's own entry
|
|
135
|
+
* point (`node_modules/@openai/codex/bin/codex.js`) - the same file the shim
|
|
136
|
+
* bypass produces.
|
|
137
|
+
*
|
|
138
|
+
* Pass-through cases (behaviour identical to a bare `spawn(name, argv)`):
|
|
139
|
+
* - any other name containing a path separator - an explicit path is the
|
|
140
|
+
* caller's business, and the tests rely on this
|
|
141
|
+
* - any non-win32 platform - macOS and Linux behaviour must not change
|
|
142
|
+
* - win32 with no PATH match - preserve the ordinary ENOENT
|
|
143
|
+
*
|
|
144
|
+
* @param {string} name
|
|
145
|
+
* @param {Object} [options]
|
|
146
|
+
* @param {string} [options.platform]
|
|
147
|
+
* @param {Record<string, string|undefined>} [options.env]
|
|
148
|
+
* @param {(p: string) => boolean} [options.exists]
|
|
149
|
+
* @param {string} [options.nodePath]
|
|
150
|
+
* @param {NpmEntryHint} [options.npmEntry] enables the shim bypass
|
|
151
|
+
* @returns {SpawnTarget}
|
|
152
|
+
*/
|
|
153
|
+
export function resolveCommand(name, options = {}) {
|
|
154
|
+
const passthrough = { cmd: name, prefixArgs: [], shim: false };
|
|
155
|
+
if (typeof name !== "string" || !name) return passthrough;
|
|
156
|
+
|
|
157
|
+
const platform = options.platform ?? process.platform;
|
|
158
|
+
const nodePath = options.nodePath ?? process.execPath;
|
|
159
|
+
|
|
160
|
+
if (JS_EXTS.has(pathImpl(platform).extname(name).toLowerCase())) {
|
|
161
|
+
return { cmd: nodePath, prefixArgs: [name], shim: false };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (!isWindows(platform)) return passthrough;
|
|
165
|
+
|
|
166
|
+
const env = options.env ?? process.env;
|
|
167
|
+
const exists = options.exists ?? existsSync;
|
|
168
|
+
const bypass = (shimPath) => npmBypass(shimPath, options.npmEntry, exists, nodePath);
|
|
169
|
+
|
|
170
|
+
const dirs = String(env.PATH ?? env.Path ?? "")
|
|
171
|
+
.split(";")
|
|
172
|
+
.filter(Boolean);
|
|
173
|
+
const exts = String(env.PATHEXT || DEFAULT_PATHEXT)
|
|
174
|
+
.split(";")
|
|
175
|
+
.filter(Boolean);
|
|
176
|
+
|
|
177
|
+
// An explicitly named shim - `CODEX_BIN=codex.cmd`, or a full path to one.
|
|
178
|
+
// Handled before the separator pass-through below, because passing it through
|
|
179
|
+
// spawns a shim Node cannot execute and then tells the user to set CODEX_BIN,
|
|
180
|
+
// which is circular advice for someone who just did.
|
|
181
|
+
const namedExt = path.win32.extname(name).toLowerCase();
|
|
182
|
+
if (SHIM_EXTS.has(namedExt)) {
|
|
183
|
+
// A bare shim NAME still needs locating; only a path-bearing one is already
|
|
184
|
+
// located, and a global install's entry point lives beside the shim.
|
|
185
|
+
const located =
|
|
186
|
+
name.includes("/") || name.includes("\\") ? name : (findOnPath(name, dirs, exists) ?? name);
|
|
187
|
+
return bypass(located) ?? { cmd: located, prefixArgs: [], shim: true };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Any other explicit path (absolute or relative) is already a resolved target.
|
|
191
|
+
if (name.includes("/") || name.includes("\\")) return passthrough;
|
|
192
|
+
|
|
193
|
+
// FIRST MATCH WINS, in PATH order then PATHEXT order - the same precedence
|
|
194
|
+
// libuv and `where` apply. Preferring a real .exe from a LATER directory would
|
|
195
|
+
// silently run a different install than the one the user's own shell picks.
|
|
196
|
+
/** @type {string|null} */
|
|
197
|
+
let firstShim = null;
|
|
198
|
+
for (const dir of dirs) {
|
|
199
|
+
for (const raw of exts) {
|
|
200
|
+
// PATHEXT is conventionally UPPERCASE while npm writes `codex.cmd`.
|
|
201
|
+
// Windows is case-insensitive either way, but the lowercase form matches
|
|
202
|
+
// the file as it actually sits on disk, which keeps error messages honest.
|
|
203
|
+
const ext = raw.toLowerCase();
|
|
204
|
+
const candidate = path.win32.join(dir, name + ext);
|
|
205
|
+
if (!exists(candidate)) continue;
|
|
206
|
+
// A real executable is spawnable as-is.
|
|
207
|
+
if (DIRECT_EXTS.has(ext)) return { cmd: candidate, prefixArgs: [], shim: false };
|
|
208
|
+
if (!SHIM_EXTS.has(ext)) continue;
|
|
209
|
+
const viaNode = bypass(candidate);
|
|
210
|
+
if (viaNode) return viaNode;
|
|
211
|
+
// No entry point behind it - a broken or partial install. Keep scanning:
|
|
212
|
+
// anything usable further down PATH beats failing outright when a working
|
|
213
|
+
// install exists. The first shim is still what gets REPORTED if nothing
|
|
214
|
+
// usable turns up, since that is the one the user believes they run.
|
|
215
|
+
if (firstShim === null) firstShim = candidate;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (firstShim === null) return passthrough;
|
|
220
|
+
return { cmd: firstShim, prefixArgs: [], shim: true };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* One-line explanation for a `shim: true` resolution, so every caller says the
|
|
225
|
+
* same thing.
|
|
226
|
+
* @param {string} name the command that was looked up
|
|
227
|
+
* @param {string} shimPath the shim that was found
|
|
228
|
+
* @param {string} envVar the override the user can set, e.g. "CODEX_BIN"
|
|
229
|
+
* @returns {string}
|
|
230
|
+
*/
|
|
231
|
+
export function shimMessage(name, shimPath, envVar) {
|
|
232
|
+
return (
|
|
233
|
+
`${name} only resolved to a shell shim (${shimPath}), which Node cannot execute directly. ` +
|
|
234
|
+
`Set ${envVar} to the real executable, or reinstall ${name} so a .exe is on PATH.`
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Find an exact filename on PATH. No extension is appended.
|
|
240
|
+
* @param {string} file
|
|
241
|
+
* @param {string[]} dirs
|
|
242
|
+
* @param {(p: string) => boolean} exists
|
|
243
|
+
* @returns {string|null}
|
|
244
|
+
*/
|
|
245
|
+
function findOnPath(file, dirs, exists) {
|
|
246
|
+
for (const dir of dirs) {
|
|
247
|
+
const candidate = path.win32.join(dir, file);
|
|
248
|
+
if (exists(candidate)) return candidate;
|
|
249
|
+
}
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Turn an npm shim into a directly spawnable target, or null when there is no
|
|
255
|
+
* entry point behind it. The shim itself is never executed.
|
|
256
|
+
*
|
|
257
|
+
* Two layouts are probed, because both put a `.cmd` on a Windows machine:
|
|
258
|
+
* - global: <prefix>\codex.cmd -> <prefix>\node_modules\<pkg>\<bin>
|
|
259
|
+
* - local: <root>\node_modules\.bin\codex.cmd -> <root>\node_modules\<pkg>\<bin>
|
|
260
|
+
*
|
|
261
|
+
* A native entry (`bin/claude.exe`) is spawned directly; a JS entry gets node in
|
|
262
|
+
* front of it.
|
|
263
|
+
*
|
|
264
|
+
* @param {string} shimPath
|
|
265
|
+
* @param {NpmEntryHint|undefined} npmEntry
|
|
266
|
+
* @param {(p: string) => boolean} exists
|
|
267
|
+
* @param {string} nodePath
|
|
268
|
+
* @returns {SpawnTarget|null}
|
|
269
|
+
*/
|
|
270
|
+
function npmBypass(shimPath, npmEntry, exists, nodePath) {
|
|
271
|
+
if (!npmEntry?.pkg || !npmEntry?.bin) return null;
|
|
272
|
+
const dir = path.win32.dirname(shimPath);
|
|
273
|
+
const roots = [dir];
|
|
274
|
+
// npm puts a locally installed CLI's shim in node_modules/.bin, one level below the package.
|
|
275
|
+
if (path.win32.basename(dir).toLowerCase() === ".bin") {
|
|
276
|
+
roots.push(path.win32.dirname(path.win32.dirname(dir)));
|
|
277
|
+
}
|
|
278
|
+
for (const root of roots) {
|
|
279
|
+
const entry = path.win32.join(root, "node_modules", npmEntry.pkg, npmEntry.bin);
|
|
280
|
+
if (!exists(entry)) continue;
|
|
281
|
+
if (DIRECT_EXTS.has(path.win32.extname(entry).toLowerCase())) {
|
|
282
|
+
return { cmd: entry, prefixArgs: [], shim: false };
|
|
283
|
+
}
|
|
284
|
+
return { cmd: nodePath, prefixArgs: [entry], shim: false };
|
|
285
|
+
}
|
|
286
|
+
return null;
|
|
287
|
+
}
|
package/src/codex-runner.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { createWriteStream } from "node:fs";
|
|
1
|
+
import { createWriteStream, existsSync } from "node:fs";
|
|
2
2
|
import { mkdir, rm, stat } from "node:fs/promises";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
4
|
import { execFileSync, spawn } from "node:child_process";
|
|
5
|
-
import { join, resolve } from "node:path";
|
|
5
|
+
import { join, resolve, sep } from "node:path";
|
|
6
6
|
import {
|
|
7
7
|
appendTaskEvent,
|
|
8
8
|
getTask,
|
|
@@ -16,10 +16,11 @@ import { TERMINAL_STATUSES } from "./status.js";
|
|
|
16
16
|
import { worktreesDir } from "./paths.js";
|
|
17
17
|
import { withGoalPreamble } from "./prompt.js";
|
|
18
18
|
import { mergeChangedFiles, readWorktreeChanges } from "./worktree.js";
|
|
19
|
+
import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
|
|
19
20
|
|
|
20
21
|
const processes = new Map();
|
|
21
22
|
const cancelledTasks = new Set();
|
|
22
|
-
const
|
|
23
|
+
const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
|
|
23
24
|
const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
24
25
|
const allowedReasoningEfforts = new Set(["minimal", "low", "medium", "high"]);
|
|
25
26
|
|
|
@@ -41,7 +42,7 @@ async function exists(path) {
|
|
|
41
42
|
|
|
42
43
|
function runCommand(command, args, options = {}) {
|
|
43
44
|
return new Promise((resolvePromise, reject) => {
|
|
44
|
-
const child = spawn(command, args, { stdio: "ignore", ...options });
|
|
45
|
+
const child = spawn(command, args, { stdio: "ignore", windowsHide: true, ...options });
|
|
45
46
|
child.on("exit", (code) => {
|
|
46
47
|
if (code === 0) resolvePromise();
|
|
47
48
|
else reject(new Error(`${command} ${args.join(" ")} exited with ${code}`));
|
|
@@ -74,10 +75,17 @@ function normalizeOwnedPaths(ownedPaths, projectRoot) {
|
|
|
74
75
|
}
|
|
75
76
|
|
|
76
77
|
function pathOverlaps(left, right) {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
78
|
+
// Windows paths are case-insensitive and may mix separators, so compare on a
|
|
79
|
+
// normalized form there. macOS and Linux keep the exact previous comparison -
|
|
80
|
+
// a backslash is a legal filename character on those platforms.
|
|
81
|
+
const windows = process.platform === "win32";
|
|
82
|
+
const normalize = (value) => (windows ? value.replace(/[\\/]+/g, sep).toLowerCase() : value);
|
|
83
|
+
const mine = normalize(left);
|
|
84
|
+
const theirs = normalize(right);
|
|
85
|
+
if (mine === theirs) return true;
|
|
86
|
+
const minePrefix = mine.endsWith(sep) ? mine : `${mine}${sep}`;
|
|
87
|
+
const theirsPrefix = theirs.endsWith(sep) ? theirs : `${theirs}${sep}`;
|
|
88
|
+
return minePrefix.startsWith(theirsPrefix) || theirsPrefix.startsWith(minePrefix);
|
|
81
89
|
}
|
|
82
90
|
|
|
83
91
|
// Two workers claiming overlapping paths will collide when their branches are
|
|
@@ -115,11 +123,39 @@ function ownershipConflictError(conflicts) {
|
|
|
115
123
|
return error;
|
|
116
124
|
}
|
|
117
125
|
|
|
126
|
+
// The Codex CLI as a spawnable target. On Windows npm installs a `codex.cmd`
|
|
127
|
+
// shim that Node refuses to spawn directly, so bin-resolver.js steps over it and
|
|
128
|
+
// hands back `node <entry>` instead; on macOS and Linux this is the bare name,
|
|
129
|
+
// unchanged. Resolved per dispatch so a CLI installed later is picked up.
|
|
130
|
+
function codexTarget() {
|
|
131
|
+
const configured = process.env.CODEX_BIN?.trim();
|
|
132
|
+
const located = configured ? configured : (findBinaryPath("codex", { extraDirs: defaultBinDirs() }) ?? "codex");
|
|
133
|
+
const target = resolveCommand(located, { npmEntry: CODEX_NPM_ENTRY });
|
|
134
|
+
if (target.shim) return { error: shimMessage("codex", target.cmd, "CODEX_BIN") };
|
|
135
|
+
return { cmd: target.cmd, prefixArgs: target.prefixArgs };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function failedStart(record, reason) {
|
|
139
|
+
const now = new Date().toISOString();
|
|
140
|
+
return {
|
|
141
|
+
ok: false,
|
|
142
|
+
record: {
|
|
143
|
+
...record,
|
|
144
|
+
status: "failed",
|
|
145
|
+
phase: null,
|
|
146
|
+
pid: null,
|
|
147
|
+
error: reason,
|
|
148
|
+
completed_at: now,
|
|
149
|
+
updated_at: now
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
118
154
|
// Spawn can fail either by throwing synchronously, or by emitting "error"
|
|
119
155
|
// instead of "spawn". Both paths are handled so a bad CODEX_BIN marks the task
|
|
120
156
|
// failed instead of taking the whole MCP process down.
|
|
121
|
-
async function spawnAndAwaitStart(args, options) {
|
|
122
|
-
const child = spawn(
|
|
157
|
+
async function spawnAndAwaitStart(target, args, options) {
|
|
158
|
+
const child = spawn(target.cmd, [...target.prefixArgs, ...args], options);
|
|
123
159
|
const spawnError = await new Promise((resolvePromise) => {
|
|
124
160
|
let settled = false;
|
|
125
161
|
child.once("spawn", () => {
|
|
@@ -142,26 +178,18 @@ async function spawnAndAwaitStart(args, options) {
|
|
|
142
178
|
// Every write goes through one serialized chain so concurrent stdout/stderr
|
|
143
179
|
// callbacks cannot interleave and persist out of order.
|
|
144
180
|
async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {} }) {
|
|
145
|
-
const
|
|
181
|
+
const target = codexTarget();
|
|
182
|
+
if (target.error) return failedStart(record, target.error);
|
|
183
|
+
|
|
184
|
+
const { child, spawnError } = await spawnAndAwaitStart(target, args, {
|
|
146
185
|
stdio: ["pipe", "pipe", "pipe"],
|
|
147
186
|
env: { ...process.env, NO_COLOR: "1" },
|
|
187
|
+
windowsHide: true,
|
|
148
188
|
...spawnOptions
|
|
149
189
|
});
|
|
150
190
|
|
|
151
191
|
if (spawnError) {
|
|
152
|
-
|
|
153
|
-
return {
|
|
154
|
-
ok: false,
|
|
155
|
-
record: {
|
|
156
|
-
...record,
|
|
157
|
-
status: "failed",
|
|
158
|
-
phase: null,
|
|
159
|
-
pid: null,
|
|
160
|
-
error: `failed to spawn ${defaultCodexBin}: ${spawnError.message}`,
|
|
161
|
-
completed_at: now,
|
|
162
|
-
updated_at: now
|
|
163
|
-
}
|
|
164
|
-
};
|
|
192
|
+
return failedStart(record, `failed to spawn ${target.cmd}: ${spawnError.message}`);
|
|
165
193
|
}
|
|
166
194
|
|
|
167
195
|
const now = new Date().toISOString();
|
|
@@ -442,30 +470,104 @@ export async function resumeCodexWorker({ taskId, prompt }) {
|
|
|
442
470
|
return started.record;
|
|
443
471
|
}
|
|
444
472
|
|
|
445
|
-
|
|
473
|
+
// `powershell` by name is not always on PATH for a process a GUI client
|
|
474
|
+
// started, so prefer the copy that ships with Windows. Only the CIM path needs
|
|
475
|
+
// it; the rest of this file shells out to nothing but taskkill and git.
|
|
476
|
+
function powershellBin() {
|
|
477
|
+
const root = process.env.SystemRoot?.trim() || "C:\\Windows";
|
|
478
|
+
const full = join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
479
|
+
return existsSync(full) ? full : "powershell";
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// A pid recorded on disk is only signalled once it is confirmed to still be a
|
|
483
|
+
// Codex worker, so a recycled pid belonging to an unrelated process is never
|
|
484
|
+
// killed. Windows has no `ps`: CIM is the only reliable source for a full command
|
|
485
|
+
// line, and the full line matters because the npm shim is bypassed by running
|
|
486
|
+
// `node <entry>`, which puts the word "codex" in the arguments, not the image
|
|
487
|
+
// name. `tasklist` is the fallback when PowerShell is unavailable - it only
|
|
488
|
+
// reports the image name, so it can confirm a native codex.exe but never a
|
|
489
|
+
// `node <entry>` worker.
|
|
490
|
+
//
|
|
491
|
+
// The timeout is generous on purpose: this runs once per cross-process cancel,
|
|
492
|
+
// and a cold Windows PowerShell on a fresh machine routinely takes several
|
|
493
|
+
// seconds to print anything. A tight timeout here silently degrades to the
|
|
494
|
+
// useless tasklist probe, and the cancel comes back "process_not_found".
|
|
495
|
+
function describeProcess(pid) {
|
|
496
|
+
const options = { encoding: "utf8", timeout: 15000, windowsHide: true };
|
|
446
497
|
try {
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
498
|
+
if (process.platform === "win32") {
|
|
499
|
+
try {
|
|
500
|
+
const viaCim = execFileSync(
|
|
501
|
+
powershellBin(),
|
|
502
|
+
[
|
|
503
|
+
"-NoLogo",
|
|
504
|
+
"-NoProfile",
|
|
505
|
+
"-NonInteractive",
|
|
506
|
+
"-Command",
|
|
507
|
+
`(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine`
|
|
508
|
+
],
|
|
509
|
+
options
|
|
510
|
+
).trim();
|
|
511
|
+
if (viaCim) return viaCim;
|
|
512
|
+
} catch {
|
|
513
|
+
// fall through to the image-name probe below
|
|
514
|
+
}
|
|
515
|
+
return execFileSync("tasklist", ["/FI", `PID eq ${Number(pid)}`, "/FO", "CSV", "/NH"], options).trim();
|
|
516
|
+
}
|
|
517
|
+
return execFileSync("ps", ["-p", String(pid), "-o", "command="], options).trim();
|
|
452
518
|
} catch {
|
|
453
|
-
return
|
|
519
|
+
return "";
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function isLikelyCodexProcess(pid) {
|
|
524
|
+
const description = describeProcess(pid);
|
|
525
|
+
return description.includes("codex");
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// Ends a worker and, on Windows, its whole process tree: the direct child there
|
|
529
|
+
// is the JS wrapper around the native Codex binary, so terminating it alone
|
|
530
|
+
// would leave the real CLI running and the task stuck in `running`.
|
|
531
|
+
function terminateChild(child) {
|
|
532
|
+
if (process.platform === "win32" && child.pid) {
|
|
533
|
+
try {
|
|
534
|
+
execFileSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], {
|
|
535
|
+
stdio: "ignore",
|
|
536
|
+
timeout: 5000,
|
|
537
|
+
windowsHide: true
|
|
538
|
+
});
|
|
539
|
+
return;
|
|
540
|
+
} catch {
|
|
541
|
+
// fall back to the handle-based kill below
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
child.kill("SIGTERM");
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function terminatePid(pid) {
|
|
548
|
+
if (process.platform === "win32") {
|
|
549
|
+
execFileSync("taskkill", ["/PID", String(pid), "/T", "/F"], {
|
|
550
|
+
stdio: "ignore",
|
|
551
|
+
timeout: 5000,
|
|
552
|
+
windowsHide: true
|
|
553
|
+
});
|
|
554
|
+
return;
|
|
454
555
|
}
|
|
556
|
+
process.kill(pid, "SIGTERM");
|
|
455
557
|
}
|
|
456
558
|
|
|
457
559
|
export async function cancelCodexWorker(taskId) {
|
|
458
560
|
const child = processes.get(taskId);
|
|
459
561
|
if (child) {
|
|
460
562
|
cancelledTasks.add(taskId);
|
|
461
|
-
child
|
|
563
|
+
terminateChild(child);
|
|
462
564
|
return { cancelled: true, via: "process_handle", pid: child.pid ?? null };
|
|
463
565
|
}
|
|
464
566
|
// Another MCP process owns the handle; fall back to the pid recorded on disk.
|
|
465
567
|
const task = await getTask(taskId);
|
|
466
568
|
if (task?.pid && (await isPidAlive(task.pid)) && isLikelyCodexProcess(task.pid)) {
|
|
467
569
|
try {
|
|
468
|
-
|
|
570
|
+
terminatePid(task.pid);
|
|
469
571
|
return { cancelled: true, via: "pid", pid: task.pid };
|
|
470
572
|
} catch (error) {
|
|
471
573
|
return { cancelled: false, reason: "kill_failed", message: error.message, pid: task.pid };
|
package/src/setup.js
CHANGED
|
@@ -16,6 +16,12 @@ import { homedir } from "node:os";
|
|
|
16
16
|
import { dirname, join } from "node:path";
|
|
17
17
|
import { fileURLToPath } from "node:url";
|
|
18
18
|
import { promisify } from "node:util";
|
|
19
|
+
import {
|
|
20
|
+
defaultBinDirs,
|
|
21
|
+
findBinaryPath,
|
|
22
|
+
resolveCommand,
|
|
23
|
+
shimMessage
|
|
24
|
+
} from "./bin-resolver.js";
|
|
19
25
|
|
|
20
26
|
const run = promisify(execFile);
|
|
21
27
|
|
|
@@ -29,10 +35,27 @@ const CLIENT_TIMEOUT_MS = 60_000;
|
|
|
29
35
|
|
|
30
36
|
// A client is "present" when its binary is on PATH or its skill directory
|
|
31
37
|
// already exists. We never invent directories for clients the user does not run.
|
|
38
|
+
// `npmEntry` lets bin-resolver.js step over a Windows .cmd shim by pointing at
|
|
39
|
+
// the package's own entry point. `binEnv` is the override named in the repair
|
|
40
|
+
// message when that fails (only Codex has one).
|
|
32
41
|
const CLIENTS = [
|
|
33
|
-
{
|
|
42
|
+
{
|
|
43
|
+
id: "claude",
|
|
44
|
+
label: "Claude Code",
|
|
45
|
+
skillRoot: join(homedir(), ".claude", "skills"),
|
|
46
|
+
binary: "claude",
|
|
47
|
+
binEnv: null,
|
|
48
|
+
npmEntry: { pkg: "@anthropic-ai/claude-code", bin: "bin/claude.exe" }
|
|
49
|
+
},
|
|
34
50
|
{ id: "agents", label: "~/.agents", skillRoot: join(homedir(), ".agents", "skills"), binary: null },
|
|
35
|
-
{
|
|
51
|
+
{
|
|
52
|
+
id: "codex",
|
|
53
|
+
label: "Codex",
|
|
54
|
+
skillRoot: join(homedir(), ".codex", "skills"),
|
|
55
|
+
binary: "codex",
|
|
56
|
+
binEnv: "CODEX_BIN",
|
|
57
|
+
npmEntry: { pkg: "@openai/codex", bin: "bin/codex.js" }
|
|
58
|
+
}
|
|
36
59
|
];
|
|
37
60
|
|
|
38
61
|
function parseArgs(argv) {
|
|
@@ -99,35 +122,18 @@ Environment:
|
|
|
99
122
|
`);
|
|
100
123
|
}
|
|
101
124
|
|
|
102
|
-
// PATH first, then the well-known global bin directories
|
|
103
|
-
//
|
|
104
|
-
//
|
|
105
|
-
|
|
106
|
-
const EXTRA_BIN_DIRS = [
|
|
107
|
-
join(homedir(), ".npm-global", "bin"),
|
|
108
|
-
join(homedir(), ".local", "bin"),
|
|
109
|
-
join(homedir(), ".bun", "bin"),
|
|
110
|
-
join(homedir(), ".volta", "bin"),
|
|
111
|
-
join(homedir(), "Library", "pnpm"),
|
|
112
|
-
"/opt/homebrew/bin",
|
|
113
|
-
"/usr/local/bin"
|
|
114
|
-
];
|
|
125
|
+
// PATH first, then the well-known global bin directories (shared with the
|
|
126
|
+
// worker runner so both look in the same places), then the version managers,
|
|
127
|
+
// whose node bin directory is only discoverable by listing.
|
|
128
|
+
const EXTRA_BIN_DIRS = defaultBinDirs();
|
|
115
129
|
|
|
116
130
|
const VERSION_MANAGER_ROOTS = [
|
|
117
131
|
[join(homedir(), ".nvm", "versions", "node"), join("bin")],
|
|
118
132
|
[join(homedir(), ".fnm", "node-versions"), join("installation", "bin")]
|
|
119
133
|
];
|
|
120
134
|
|
|
121
|
-
function
|
|
122
|
-
|
|
123
|
-
if (!dir) continue;
|
|
124
|
-
const candidate = join(dir, binary);
|
|
125
|
-
if (existsSync(candidate)) return candidate;
|
|
126
|
-
}
|
|
127
|
-
for (const dir of EXTRA_BIN_DIRS) {
|
|
128
|
-
const candidate = join(dir, binary);
|
|
129
|
-
if (existsSync(candidate)) return candidate;
|
|
130
|
-
}
|
|
135
|
+
function versionManagerBinDirs() {
|
|
136
|
+
const dirs = [];
|
|
131
137
|
for (const [root, suffix] of VERSION_MANAGER_ROOTS) {
|
|
132
138
|
if (!existsSync(root)) continue;
|
|
133
139
|
let entries = [];
|
|
@@ -137,17 +143,34 @@ function onPath(binary) {
|
|
|
137
143
|
continue;
|
|
138
144
|
}
|
|
139
145
|
for (const entry of entries) {
|
|
140
|
-
|
|
141
|
-
if (existsSync(candidate)) return candidate;
|
|
146
|
+
dirs.push(join(root, entry, suffix));
|
|
142
147
|
}
|
|
143
148
|
}
|
|
144
|
-
return
|
|
149
|
+
return dirs;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Turns a client binary into a spawnable target, or null when the client is not
|
|
153
|
+
// installed. On Windows a bare `codex` resolves to `codex.cmd`, which Node
|
|
154
|
+
// refuses to execute directly, so the resolver hands back `cmd` + `prefixArgs`
|
|
155
|
+
// instead (see bin-resolver.js).
|
|
156
|
+
function locateClient(binary) {
|
|
157
|
+
if (!binary) return null;
|
|
158
|
+
const path = findBinaryPath(binary, {
|
|
159
|
+
extraDirs: [...EXTRA_BIN_DIRS, ...versionManagerBinDirs()]
|
|
160
|
+
});
|
|
161
|
+
if (!path) return null;
|
|
162
|
+
const target = resolveCommand(path, { npmEntry: CLIENTS.find((c) => c.binary === binary)?.npmEntry });
|
|
163
|
+
return { path, cmd: target.cmd, args: target.prefixArgs, shim: target.shim };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function runClient(target, args, options = {}) {
|
|
167
|
+
return run(target.cmd, [...target.args, ...args], { windowsHide: true, ...options });
|
|
145
168
|
}
|
|
146
169
|
|
|
147
170
|
function selectClients(options) {
|
|
148
171
|
return CLIENTS.filter((client) => {
|
|
149
172
|
if (options.targets && !options.targets.includes(client.id)) return false;
|
|
150
|
-
if (client.binary &&
|
|
173
|
+
if (client.binary && locateClient(client.binary)) return true;
|
|
151
174
|
return existsSync(client.skillRoot);
|
|
152
175
|
});
|
|
153
176
|
}
|
|
@@ -189,12 +212,10 @@ async function installSkill(client, options, log) {
|
|
|
189
212
|
return "installed";
|
|
190
213
|
}
|
|
191
214
|
|
|
192
|
-
async function mcpAlreadyRegistered(
|
|
215
|
+
async function mcpAlreadyRegistered(target, options) {
|
|
193
216
|
if (options.dryRun) return false;
|
|
194
|
-
const binary = onPath(client.binary);
|
|
195
|
-
if (!binary) return false;
|
|
196
217
|
try {
|
|
197
|
-
await
|
|
218
|
+
await runClient(target, ["mcp", "get", MCP_NAME], { timeout: CLIENT_TIMEOUT_MS });
|
|
198
219
|
return true;
|
|
199
220
|
} catch {
|
|
200
221
|
return false;
|
|
@@ -202,12 +223,18 @@ async function mcpAlreadyRegistered(client, options) {
|
|
|
202
223
|
}
|
|
203
224
|
|
|
204
225
|
async function registerMcp(client, options, log, warn) {
|
|
205
|
-
const
|
|
206
|
-
if (!
|
|
226
|
+
const target = locateClient(client.binary);
|
|
227
|
+
if (!target) {
|
|
207
228
|
log(`mcp ${client.label}: skipped (no ${client.binary} found)`);
|
|
208
229
|
return "skipped";
|
|
209
230
|
}
|
|
210
|
-
if (
|
|
231
|
+
if (target.shim) {
|
|
232
|
+
warn(
|
|
233
|
+
`mcp ${client.label}: ${shimMessage(client.binary, target.path, client.binEnv)}`
|
|
234
|
+
);
|
|
235
|
+
return "failed";
|
|
236
|
+
}
|
|
237
|
+
if (await mcpAlreadyRegistered(target, options)) {
|
|
211
238
|
log(`mcp ${client.label}: already registered`);
|
|
212
239
|
return "unchanged";
|
|
213
240
|
}
|
|
@@ -222,7 +249,7 @@ async function registerMcp(client, options, log, warn) {
|
|
|
222
249
|
return "would-register";
|
|
223
250
|
}
|
|
224
251
|
try {
|
|
225
|
-
await
|
|
252
|
+
await runClient(target, args, { timeout: CLIENT_TIMEOUT_MS });
|
|
226
253
|
log(`mcp ${client.label}: registered`);
|
|
227
254
|
return "registered";
|
|
228
255
|
} catch (error) {
|