codex-supervisor-mcp 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,7 +33,7 @@ Codex worker ──► data/runs/<taskId>.jsonl 原始 JSONL 事件流
33
33
 
34
34
  ## 安装
35
35
 
36
- 需要 Node.js >= 22 和 `codex` CLI 在 `PATH` 里。
36
+ 需要 Node.js >= 22 和 `codex` CLI 在 `PATH` 里。macOS、Linux、Windows 都支持。
37
37
 
38
38
  ```bash
39
39
  npm install -g codex-supervisor-mcp
@@ -55,6 +55,15 @@ codex-supervisor-setup --skill-only # 只装 skill
55
55
  codex-supervisor-setup --dry-run # 只打印计划
56
56
  ```
57
57
 
58
+ ### Windows
59
+
60
+ 支持 Windows,两条实现细节值得知道:
61
+
62
+ - 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` 起它。
63
+ - 跨进程取消用 `taskkill /PID <pid> /T /F` 结束整棵进程树;确认这个 pid 还是 Codex 用 PowerShell 的 `Get-CimInstance Win32_Process` 读命令行(拿不到时退到 `tasklist`)。`ps` 只在 macOS / Linux 上用。
64
+
65
+ 除了 `PATH`,还会探 `%APPDATA%\npm`、`%LOCALAPPDATA%\pnpm`、`%LOCALAPPDATA%\Volta\bin`、`%ProgramFiles%\nodejs`。
66
+
58
67
  自动安装只在**全局安装**时发生。`npx`、`--ignore-scripts`、以及被别人当项目依赖装的场景都不会触发。要跳过用 `CODEX_SUPERVISOR_SKIP_SETUP=1`;要补装手动跑一次 `codex-supervisor-setup`。
59
68
 
60
69
  ### 手动配置到 Claude Code
@@ -178,7 +187,7 @@ Codex 原生 goal 有六个状态,映射到 work 状态:
178
187
  |---|---|---|
179
188
  | `SUPERVISOR_HOME` | `~/.codex-supervisor` | 状态根目录(sqlite / 事件流 / worktree 都在它下面) |
180
189
  | `CODEX_HOME` | `~/.codex` | 只读,用来读 Codex 原生的 `goals_1.sqlite` |
181
- | `CODEX_BIN` | `codex`(走 `PATH`) | Codex CLI 可执行文件路径 |
190
+ | `CODEX_BIN` | `codex`(走 `PATH`) | Codex CLI 可执行文件路径。Windows 上给裸名字时会按 `PATHEXT` 展开,`.cmd` shim 会被自动绕开 |
182
191
  | `GIT_BIN` | `git`(走 `PATH`) | Git 可执行文件路径 |
183
192
 
184
193
  如果 MCP 客户端启动时 `PATH` 里没有 `codex`(GUI 启动的应用常见),显式设置 `CODEX_BIN`:
@@ -201,7 +210,7 @@ Codex 原生 goal 有六个状态,映射到 work 状态:
201
210
  - **不往 Codex 原生 goal 写数据**:`goals_1.sqlite` 归 Codex 所有,本 MCP 只读。worker 起来后由它自己调 Codex 的 `create_goal` 建原生 goal,本 MCP 只负责在派单时把这段指令拼进 prompt。
202
211
  - **原生 goal 依赖模型照做**:`codex exec` 不会自动建 goal,是派单时那段指令让 worker 建的。模型偶尔漏调,这时 `native_goal` 为 `null`,`get_worker_goal` 退回派单时记录的那份,不影响状态机。
203
212
  - **`search_works` 是子串匹配,不是全文索引**:几百条 work 的规模下 `LIKE` 扫描足够快,也省掉一套索引的维护成本。上到几万条再谈别的。
204
- - **跨进程取消按 pid**:进程句柄不在本进程时,会用落库的 pid 发 `SIGTERM`,并且要求 `ps` 里那个 pid 的命令行包含 `codex`,避免误杀被复用的 pid。
213
+ - **跨进程取消按 pid**:进程句柄不在本进程时,会先确认那个 pid 的命令行里含 `codex`(macOS / Linux 用 `ps`,Windows 用 CIM,退到 `tasklist`),再发 `SIGTERM`(Windows 上是 `taskkill /T /F`),避免误杀被复用的 pid。
205
214
  - **`create_codex_followup_worker` 和 `resume_codex_worker` 不是一回事**:前者开新会话、靠文本重述上下文;后者接同一个会话。要细节不丢就用后者。
206
215
  - **`session_id` 由派单方自己传,本 MCP 不生成**:一批活传同一个值,`get_session_works` 才能把它们归到一起。不传就是 `NULL`,事后按 session 找不回来。
207
216
 
@@ -215,8 +224,9 @@ Codex 原生 goal 有六个状态,映射到 work 状态:
215
224
  6. ~~session 维度:`session_id` 落库 + `get_session_works` 断线重连~~
216
225
  7. ~~按关键词找历史 work:`search_works`~~
217
226
  8. ~~worker 原生 goal:派单时注入 `create_goal` 指令~~
218
- 9. 常驻 daemon:派单和进程生命周期从 MCP 进程里拿出来
219
- 10. React 实时看板
227
+ 9. ~~Windows 支持:`.cmd` shim 绕行、`taskkill` 进程树、跨平台 PATH / `PATHEXT`~~ ✅
228
+ 10. 常驻 daemon:派单和进程生命周期从 MCP 进程里拿出来
229
+ 11. React 实时看板
220
230
 
221
231
  砍掉不做的(说明理由,免得以后又想起来):
222
232
 
@@ -247,7 +257,7 @@ skill 里写了派单流程、读结果该按什么顺序、`failed` 和 `lost`
247
257
 
248
258
  ```bash
249
259
  npm install
250
- npm test # 确定性测试:截断移植、状态机、v1→v2 迁移、13 项端到端回归
260
+ npm test # 确定性测试:截断移植、状态机、v1→v2 迁移、setup、Windows 解析器、17 项端到端回归
251
261
  npm run test:real # 用真 codex CLI 跑端到端(含跨进程 resume、worktree 隔离)
252
262
  npm run smoke # 基础冒烟(真 codex)
253
263
  npm run smoke:mcp # MCP 协议冒烟
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-supervisor-mcp",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "MCP server that dispatches and supervises parallel Codex CLI workers, one isolated Git worktree each, with a persisted work state machine.",
6
6
  "license": "MIT",
@@ -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/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",
@@ -0,0 +1,272 @@
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
+
27
+ /**
28
+ * Well-known global install directories, probed after PATH. A CLI installed with
29
+ * a custom npm prefix or a version manager is usually absent from a
30
+ * non-interactive PATH, and without this it would look "not installed" even
31
+ * though the user runs it every day. The Windows entries are env-derived, so
32
+ * they simply drop out elsewhere.
33
+ *
34
+ * @param {Object} [options]
35
+ * @param {Record<string, string|undefined>} [options.env]
36
+ * @param {string} [options.home]
37
+ * @returns {string[]}
38
+ */
39
+ export function defaultBinDirs(options = {}) {
40
+ const env = options.env ?? process.env;
41
+ const home = options.home ?? homedir();
42
+ const dirs = [
43
+ path.join(home, ".npm-global", "bin"),
44
+ path.join(home, ".local", "bin"),
45
+ path.join(home, ".bun", "bin"),
46
+ path.join(home, ".volta", "bin"),
47
+ path.join(home, "Library", "pnpm"),
48
+ "/opt/homebrew/bin",
49
+ "/usr/local/bin"
50
+ ];
51
+ for (const [variable, ...segments] of [
52
+ ["APPDATA", "npm"], // npm global prefix on Windows
53
+ ["LOCALAPPDATA", "pnpm"],
54
+ ["LOCALAPPDATA", "Volta", "bin"],
55
+ ["ProgramFiles", "nodejs"] // nvm-windows and the official installer
56
+ ]) {
57
+ const root = env[variable]?.trim();
58
+ if (root) dirs.push(path.join(root, ...segments));
59
+ }
60
+ return dirs;
61
+ }
62
+
63
+ const isWindows = (platform) => platform === "win32";
64
+ const pathImpl = (platform) => (isWindows(platform) ? path.win32 : path.posix);
65
+ const listSeparator = (platform) => (isWindows(platform) ? ";" : ":");
66
+
67
+ /**
68
+ * @typedef {Object} NpmEntryHint
69
+ * @property {string} pkg npm package name, e.g. "@openai/codex"
70
+ * @property {string} bin entry path inside the package, e.g. "bin/codex.js"
71
+ */
72
+
73
+ /**
74
+ * @typedef {Object} SpawnTarget
75
+ * @property {string} cmd first argument to pass to spawn
76
+ * @property {string[]} prefixArgs args to prepend before the caller's own argv
77
+ * @property {boolean} shim true when the only match needs a shell we refuse to
78
+ * use - the caller should fail with an actionable message instead of spawning
79
+ */
80
+
81
+ /**
82
+ * Locate a CLI on PATH (plus optional extra directories) and return its real
83
+ * path, or null. On win32 the PATHEXT ladder is applied, so a bare `codex`
84
+ * resolves to `codex.cmd`; everywhere else the bare name is joined onto each
85
+ * PATH entry. A name carrying a path separator is probed as-is.
86
+ *
87
+ * @param {string} binary
88
+ * @param {Object} [options]
89
+ * @param {string} [options.platform]
90
+ * @param {Record<string, string|undefined>} [options.env]
91
+ * @param {(p: string) => boolean} [options.exists]
92
+ * @param {string[]} [options.extraDirs] well-known dirs to probe after PATH
93
+ * @returns {string|null}
94
+ */
95
+ export function findBinaryPath(binary, options = {}) {
96
+ if (!binary) return null;
97
+ const platform = options.platform ?? process.platform;
98
+ const env = options.env ?? process.env;
99
+ const exists = options.exists ?? existsSync;
100
+ const extraDirs = options.extraDirs ?? [];
101
+ const p = pathImpl(platform);
102
+
103
+ if (binary.includes("/") || binary.includes("\\")) return exists(binary) ? binary : null;
104
+
105
+ const fromPath = String(env.PATH ?? env.Path ?? "")
106
+ .split(listSeparator(platform))
107
+ .filter(Boolean);
108
+ const dirs = [...fromPath, ...extraDirs];
109
+ const suffixes = isWindows(platform)
110
+ ? String(env.PATHEXT || DEFAULT_PATHEXT)
111
+ .split(";")
112
+ .filter(Boolean)
113
+ .map((ext) => ext.toLowerCase())
114
+ : [""];
115
+
116
+ for (const dir of dirs) {
117
+ for (const suffix of suffixes) {
118
+ const candidate = p.join(dir, binary + suffix);
119
+ if (exists(candidate)) return candidate;
120
+ }
121
+ }
122
+ return null;
123
+ }
124
+
125
+ /**
126
+ * Resolve a command name into a spawnable target.
127
+ *
128
+ * Pass-through cases (behaviour identical to a bare `spawn(name, argv)`):
129
+ * - any name containing a path separator - an explicit path is the caller's
130
+ * business, and the tests rely on this
131
+ * - any non-win32 platform - macOS and Linux behaviour must not change
132
+ * - win32 with no PATH match - preserve the ordinary ENOENT
133
+ *
134
+ * @param {string} name
135
+ * @param {Object} [options]
136
+ * @param {string} [options.platform]
137
+ * @param {Record<string, string|undefined>} [options.env]
138
+ * @param {(p: string) => boolean} [options.exists]
139
+ * @param {string} [options.nodePath]
140
+ * @param {NpmEntryHint} [options.npmEntry] enables the shim bypass
141
+ * @returns {SpawnTarget}
142
+ */
143
+ export function resolveCommand(name, options = {}) {
144
+ const passthrough = { cmd: name, prefixArgs: [], shim: false };
145
+ if (typeof name !== "string" || !name) return passthrough;
146
+
147
+ const platform = options.platform ?? process.platform;
148
+ if (!isWindows(platform)) return passthrough;
149
+
150
+ const env = options.env ?? process.env;
151
+ const exists = options.exists ?? existsSync;
152
+ const nodePath = options.nodePath ?? process.execPath;
153
+ const bypass = (shimPath) => npmBypass(shimPath, options.npmEntry, exists, nodePath);
154
+
155
+ const dirs = String(env.PATH ?? env.Path ?? "")
156
+ .split(";")
157
+ .filter(Boolean);
158
+ const exts = String(env.PATHEXT || DEFAULT_PATHEXT)
159
+ .split(";")
160
+ .filter(Boolean);
161
+
162
+ // An explicitly named shim - `CODEX_BIN=codex.cmd`, or a full path to one.
163
+ // Handled before the separator pass-through below, because passing it through
164
+ // spawns a shim Node cannot execute and then tells the user to set CODEX_BIN,
165
+ // which is circular advice for someone who just did.
166
+ const namedExt = path.win32.extname(name).toLowerCase();
167
+ if (SHIM_EXTS.has(namedExt)) {
168
+ // A bare shim NAME still needs locating; only a path-bearing one is already
169
+ // located, and a global install's entry point lives beside the shim.
170
+ const located =
171
+ name.includes("/") || name.includes("\\") ? name : (findOnPath(name, dirs, exists) ?? name);
172
+ return bypass(located) ?? { cmd: located, prefixArgs: [], shim: true };
173
+ }
174
+
175
+ // Any other explicit path (absolute or relative) is already a resolved target.
176
+ if (name.includes("/") || name.includes("\\")) return passthrough;
177
+
178
+ // FIRST MATCH WINS, in PATH order then PATHEXT order - the same precedence
179
+ // libuv and `where` apply. Preferring a real .exe from a LATER directory would
180
+ // silently run a different install than the one the user's own shell picks.
181
+ /** @type {string|null} */
182
+ let firstShim = null;
183
+ for (const dir of dirs) {
184
+ for (const raw of exts) {
185
+ // PATHEXT is conventionally UPPERCASE while npm writes `codex.cmd`.
186
+ // Windows is case-insensitive either way, but the lowercase form matches
187
+ // the file as it actually sits on disk, which keeps error messages honest.
188
+ const ext = raw.toLowerCase();
189
+ const candidate = path.win32.join(dir, name + ext);
190
+ if (!exists(candidate)) continue;
191
+ // A real executable is spawnable as-is.
192
+ if (DIRECT_EXTS.has(ext)) return { cmd: candidate, prefixArgs: [], shim: false };
193
+ if (!SHIM_EXTS.has(ext)) continue;
194
+ const viaNode = bypass(candidate);
195
+ if (viaNode) return viaNode;
196
+ // No entry point behind it - a broken or partial install. Keep scanning:
197
+ // anything usable further down PATH beats failing outright when a working
198
+ // install exists. The first shim is still what gets REPORTED if nothing
199
+ // usable turns up, since that is the one the user believes they run.
200
+ if (firstShim === null) firstShim = candidate;
201
+ }
202
+ }
203
+
204
+ if (firstShim === null) return passthrough;
205
+ return { cmd: firstShim, prefixArgs: [], shim: true };
206
+ }
207
+
208
+ /**
209
+ * One-line explanation for a `shim: true` resolution, so every caller says the
210
+ * same thing.
211
+ * @param {string} name the command that was looked up
212
+ * @param {string} shimPath the shim that was found
213
+ * @param {string} envVar the override the user can set, e.g. "CODEX_BIN"
214
+ * @returns {string}
215
+ */
216
+ export function shimMessage(name, shimPath, envVar) {
217
+ return (
218
+ `${name} only resolved to a shell shim (${shimPath}), which Node cannot execute directly. ` +
219
+ `Set ${envVar} to the real executable, or reinstall ${name} so a .exe is on PATH.`
220
+ );
221
+ }
222
+
223
+ /**
224
+ * Find an exact filename on PATH. No extension is appended.
225
+ * @param {string} file
226
+ * @param {string[]} dirs
227
+ * @param {(p: string) => boolean} exists
228
+ * @returns {string|null}
229
+ */
230
+ function findOnPath(file, dirs, exists) {
231
+ for (const dir of dirs) {
232
+ const candidate = path.win32.join(dir, file);
233
+ if (exists(candidate)) return candidate;
234
+ }
235
+ return null;
236
+ }
237
+
238
+ /**
239
+ * Turn an npm shim into a directly spawnable target, or null when there is no
240
+ * entry point behind it. The shim itself is never executed.
241
+ *
242
+ * Two layouts are probed, because both put a `.cmd` on a Windows machine:
243
+ * - global: <prefix>\codex.cmd -> <prefix>\node_modules\<pkg>\<bin>
244
+ * - local: <root>\node_modules\.bin\codex.cmd -> <root>\node_modules\<pkg>\<bin>
245
+ *
246
+ * A native entry (`bin/claude.exe`) is spawned directly; a JS entry gets node in
247
+ * front of it.
248
+ *
249
+ * @param {string} shimPath
250
+ * @param {NpmEntryHint|undefined} npmEntry
251
+ * @param {(p: string) => boolean} exists
252
+ * @param {string} nodePath
253
+ * @returns {SpawnTarget|null}
254
+ */
255
+ function npmBypass(shimPath, npmEntry, exists, nodePath) {
256
+ if (!npmEntry?.pkg || !npmEntry?.bin) return null;
257
+ const dir = path.win32.dirname(shimPath);
258
+ const roots = [dir];
259
+ // npm puts a locally installed CLI's shim in node_modules/.bin, one level below the package.
260
+ if (path.win32.basename(dir).toLowerCase() === ".bin") {
261
+ roots.push(path.win32.dirname(path.win32.dirname(dir)));
262
+ }
263
+ for (const root of roots) {
264
+ const entry = path.win32.join(root, "node_modules", npmEntry.pkg, npmEntry.bin);
265
+ if (!exists(entry)) continue;
266
+ if (DIRECT_EXTS.has(path.win32.extname(entry).toLowerCase())) {
267
+ return { cmd: entry, prefixArgs: [], shim: false };
268
+ }
269
+ return { cmd: nodePath, prefixArgs: [entry], shim: false };
270
+ }
271
+ return null;
272
+ }
@@ -2,7 +2,7 @@ import { createWriteStream } 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 defaultCodexBin = process.env.CODEX_BIN?.trim() || "codex";
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
- if (left === right) return true;
78
- const leftPrefix = left.endsWith("/") ? left : `${left}/`;
79
- const rightPrefix = right.endsWith("/") ? right : `${right}/`;
80
- return leftPrefix.startsWith(rightPrefix) || rightPrefix.startsWith(leftPrefix);
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(defaultCodexBin, args, options);
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 { child, spawnError } = await spawnAndAwaitStart(args, {
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
- const now = new Date().toISOString();
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,87 @@ export async function resumeCodexWorker({ taskId, prompt }) {
442
470
  return started.record;
443
471
  }
444
472
 
445
- function isLikelyCodexProcess(pid) {
473
+ // A pid recorded on disk is only signalled once it is confirmed to still be a
474
+ // Codex worker, so a recycled pid belonging to an unrelated process is never
475
+ // killed. Windows has no `ps`: CIM is the only reliable source for a full command
476
+ // line, and the full line matters because the npm shim is bypassed by running
477
+ // `node <entry>`, which puts the word "codex" in the arguments, not the image
478
+ // name. `tasklist` is the fallback when PowerShell is unavailable.
479
+ function describeProcess(pid) {
480
+ const options = { encoding: "utf8", timeout: 2000, windowsHide: true };
446
481
  try {
447
- const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], {
448
- encoding: "utf8",
449
- timeout: 2000
450
- }).trim();
451
- return command.includes("codex");
482
+ if (process.platform === "win32") {
483
+ try {
484
+ const viaCim = execFileSync(
485
+ "powershell",
486
+ [
487
+ "-NoProfile",
488
+ "-NonInteractive",
489
+ "-Command",
490
+ `(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine`
491
+ ],
492
+ options
493
+ ).trim();
494
+ if (viaCim) return viaCim;
495
+ } catch {
496
+ // fall through to the image-name probe below
497
+ }
498
+ return execFileSync("tasklist", ["/FI", `PID eq ${Number(pid)}`, "/FO", "CSV", "/NH"], options).trim();
499
+ }
500
+ return execFileSync("ps", ["-p", String(pid), "-o", "command="], options).trim();
452
501
  } catch {
453
- return false;
502
+ return "";
503
+ }
504
+ }
505
+
506
+ function isLikelyCodexProcess(pid) {
507
+ const description = describeProcess(pid);
508
+ return description.includes("codex");
509
+ }
510
+
511
+ // Ends a worker and, on Windows, its whole process tree: the direct child there
512
+ // is the JS wrapper around the native Codex binary, so terminating it alone
513
+ // would leave the real CLI running and the task stuck in `running`.
514
+ function terminateChild(child) {
515
+ if (process.platform === "win32" && child.pid) {
516
+ try {
517
+ execFileSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], {
518
+ stdio: "ignore",
519
+ timeout: 5000,
520
+ windowsHide: true
521
+ });
522
+ return;
523
+ } catch {
524
+ // fall back to the handle-based kill below
525
+ }
526
+ }
527
+ child.kill("SIGTERM");
528
+ }
529
+
530
+ function terminatePid(pid) {
531
+ if (process.platform === "win32") {
532
+ execFileSync("taskkill", ["/PID", String(pid), "/T", "/F"], {
533
+ stdio: "ignore",
534
+ timeout: 5000,
535
+ windowsHide: true
536
+ });
537
+ return;
454
538
  }
539
+ process.kill(pid, "SIGTERM");
455
540
  }
456
541
 
457
542
  export async function cancelCodexWorker(taskId) {
458
543
  const child = processes.get(taskId);
459
544
  if (child) {
460
545
  cancelledTasks.add(taskId);
461
- child.kill("SIGTERM");
546
+ terminateChild(child);
462
547
  return { cancelled: true, via: "process_handle", pid: child.pid ?? null };
463
548
  }
464
549
  // Another MCP process owns the handle; fall back to the pid recorded on disk.
465
550
  const task = await getTask(taskId);
466
551
  if (task?.pid && (await isPidAlive(task.pid)) && isLikelyCodexProcess(task.pid)) {
467
552
  try {
468
- process.kill(task.pid, "SIGTERM");
553
+ terminatePid(task.pid);
469
554
  return { cancelled: true, via: "pid", pid: task.pid };
470
555
  } catch (error) {
471
556
  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
- { id: "claude", label: "Claude Code", skillRoot: join(homedir(), ".claude", "skills"), binary: "claude" },
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
- { id: "codex", label: "Codex", skillRoot: join(homedir(), ".codex", "skills"), binary: "codex" }
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. A client installed
103
- // with a custom npm prefix (npm config set prefix ~/.npm-global) or a version
104
- // manager is usually absent from a non-interactive PATH, and without this the
105
- // client would look "not installed" even though the user runs it every day.
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 onPath(binary) {
122
- for (const dir of (process.env.PATH ?? "").split(":")) {
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
- const candidate = join(root, entry, suffix, binary);
141
- if (existsSync(candidate)) return candidate;
146
+ dirs.push(join(root, entry, suffix));
142
147
  }
143
148
  }
144
- return null;
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 && onPath(client.binary)) return true;
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(client, options) {
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 run(binary, ["mcp", "get", MCP_NAME], { timeout: CLIENT_TIMEOUT_MS });
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 binary = onPath(client.binary);
206
- if (!binary) {
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 (await mcpAlreadyRegistered(client, options)) {
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 run(binary, args, { timeout: CLIENT_TIMEOUT_MS });
252
+ await runClient(target, args, { timeout: CLIENT_TIMEOUT_MS });
226
253
  log(`mcp ${client.label}: registered`);
227
254
  return "registered";
228
255
  } catch (error) {