Skip to content

fix(agent-core-v2): start Windows batch shim commands through cmd.exe - #4309

Closed
KaiOnCode wants to merge 3 commits into
MoonshotAI:mainfrom
KaiOnCode:fix/windows-stdio-spawn
Closed

KaiOnCode wants to merge 3 commits into
MoonshotAI:mainfrom
KaiOnCode:fix/windows-stdio-spawn

Conversation

@KaiOnCode

@KaiOnCode KaiOnCode commented Oct 21, 2026 •

Copy link
Copy Markdown

Requirement or Bug

Resolve #3236

Bug Reproduction Steps

Windows(10/11)+ v2 引擎(0.33.0 起默认):stdio MCP server 的 command 写成批处理 shim(npx、uvx、pnpm 等)时服务起不来。

{
  "mcpServers": {
    "probe": { "command": "npx", "args": ["--version"] }
  }
}

日志出现:

ERROR mcp server unavailable server=probe status=failed reason="spawn npx ENOENT"

在一台真实 Windows 机器(Windows 10 build 19045,Node v22.20.0)上把这一层拆开单独验证,三次结果完全一致:

spawn npx     (no shell) → error  code=ENOENT
spawn npx.cmd (no shell) → throw code=EINVAL
spawn cmd.exe /d /s /c npx --version → exit 0

Root Cause

根本修复。

v2 引擎的 stdio MCP 走 packages/agent-core-v2/src/mcpCore/client-stdio.ts 里自己实现的 RuntimeStdioTransport → lease.runtime.process.spawn → packages/agent-core-v2/src/os/backends/node-local/hostProcessService.ts 的原生 node:child_process.spawn。Windows 上 CreateProcess 只会自动补 .exe、不查 PATHEXT,所以裸 npx(实际是 npx.cmd)只能拿到 ENOENT;Node ≥ 20.12(CVE-2024-27980 之后)还会直接拒绝 .cmd/.bat(EINVAL)。同一棵树上,MCP SDK 自带的 stdio client 用的就是 cross-spawn(@modelcontextprotocol/sdk 的 client/stdio.js 第一行 import spawn from 'cross-spawn'),由它解析 PATHEXT 并经 cmd.exe 安全地启动批处理;v2 这条自研 transport 少了这一步。

本 PR 让 v2 的本地进程启动在 Windows 上遇到批处理 shim 时走同一条 cross-spawn 路径,其余命令逐字不变。

Code Changes

 HostProcessService.spawn
-  child = spawn(command, args, spawnOptions)        // 原生 spawn
-  await waitForSpawn(child)
+  先照旧原生 spawn;只有在 Windows 上它以 ENOENT / EINVAL 失败时,
+  才按 PATHEXT 去找同名 .bat/.cmd,找到就改由 cross-spawn 启动
+    resolveWindowsBatchCommand(command, env, cwd)
+      PATH / PATHEXT 按 Windows 语义不区分大小写地读取
+      按 (PATH 顺序 × PATHEXT 顺序) 找第一个存在的候选
+      候选是 .bat/.cmd → 返回它(交给 cross-spawn 经 cmd.exe 启动并转义参数)
+      候选是可执行文件 → 不处理(原生 spawn 本来就会成功,用不着回退)

 buildEnv(overrides)
-  { ...process.env, ...overrides }
+  Windows 上按不区分大小写合并:同名变量只保留一份,避免出现 PATH 与 Path 两个同名变量

要点:

  • 只在失败时回退:正常命令仍走原生 spawn,路径解析不进入热路径,非批处理命令的行为(包括错误码)完全不变。
  • 不改变选中的程序:回退只在原生 spawn 找不到任何 .exe 时发生,因此不会跑到与原来不同的可执行文件。
  • 为什么改在进程服务而不是只改 stdio transport:同一个 spawn 出口还服务 git 上下文、rg、外部 hook、workspace fs,Windows 上这些场景同样会被批处理 shim 卡住;只改 stdio transport 会把同一个坑留在别处。
  • 为什么不复用 apps/kimi-code/src/utils/process/resolve-command.ts:那个工具在 CLI 应用层,而 apps/kimi-code 按仓库约定不能依赖引擎包,引擎包也不能反向引用应用层,所以只能在本包内实现一份;语义保持一致(PATHEXT 顺序、显式后缀优先、Windows 上按文件存在性判断)。
  • 依赖:packages/agent-core-v2 增加 cross-spawn(仓库里已经通过 @modelcontextprotocol/sdk 间接使用同一个库)。

测试(packages/agent-core-v2/test/os/backends/node-local/hostProcessService.test.ts):

  • 新增 16 条 resolveWindowsBatchCommand 用例(PATH/PATHEXT 顺序、显式路径、相对 PATH 按 spawn cwd 解析、带引号条目、PATH/PATHEXT 大小写不敏感、可执行文件优先、带后缀的命令名、相对路径按 spawn cwd 解析、不存在的候选等),在 Linux CI 上就会跑;
  • 新增 2 条只在真实 Windows 上跑的用例:写一个 .cmd shim,分别用显式路径和 PATH 上的裸命令名 spawn 它,断言 stdout 与退出码。

red→green 是在一台真实 Windows 机器(Windows 10 build 19045 / Node v24.15.0 / pnpm 10.33.0)上跑的:换回修复前的文件,该测试文件 24 个用例里 18 个失败(Windows 集成用例分别报 spawn EINVAL 与 spawn kimi-probe ENOENT);换回修复后的文件,24 个用例全绿。

需要说明的是,仓库当前把 Windows CI 关掉了(ci.yml 里 test-windows 是 if: false),所以那两条 Windows 专用用例在 CI 里不会自动执行——上面的红绿结果是我在真实 Windows 机器上跑出来的,解析逻辑的 14 条用例则会在 CI 里跑。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Windows 上以批处理 shim(npx、uvx、pnpm 等)为命令的本地进程启动 裸 spawn 得到 ENOENT / EINVAL,stdio MCP server 起不来 原生 spawn 失败后按 PATHEXT 找到同名 .bat/.cmd,经 cmd.exe 启动,命令正常执行 无——旧行为即 #3236 报告的 bug 无(bug 修复)
Windows 上以 .exe 或绝对路径形式的本地进程启动(git.exe、rg.exe 等) 正常 正常(原生 spawn 直接成功,不进入回退分支,命令与错误信息逐字不变) 依赖既有 Windows 行为的用户 —
POSIX(macOS/Linux)上的一切本地进程启动 node:child_process.spawn node:child_process.spawn(逐字不变) 全部 POSIX 用户 —
spawn 的错误语义 不存在的命令 → HostProcessError(os.process.spawn_failed, errno: ENOENT) 不变(找不到批处理 shim 时仍抛出原生 spawn 的 ENOENT) 依赖该错误码的调用方 —
Windows 上传入 env 覆盖时的合并方式 {...process.env, ...覆盖},大小写不同会留下两个同名变量(如 PATH 与 Path) 按 Windows 语义不区分大小写地覆盖,同名变量只保留一份 依赖"两个同名变量同时存在"的调用方(这种状态在 Windows 上本身没有定义) 无

受影响模块与测试覆盖:

  • packages/agent-core-v2/src/os/backends/node-local/hostProcessService.ts — 解析逻辑由 14 条新用例覆盖(Linux CI 也会跑);Windows 启动路径由那两条 Windows 专用用例覆盖(真实 Windows 机器 red→green)。
  • 同一条 spawn 出口同时服务 MCP stdio、git 上下文、rg、外部 hook、workspace fs,因此在 Windows 上这些场景一并受益。

一点已知限制:批处理经 cmd.exe 启动时,参数按控制台 ANSI 代码页传递(中文等非 ASCII 参数会按本地代码页编码),这是 cmd.exe 自身的既有行为,与在命令行里直接跑 .cmd 一致;ASCII 参数不受影响。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

@changeset-bot

changeset-bot Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 7c61858

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T03:02:20.206361Z 7c61858 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e532643892

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

.map((ext) => stripQuotes(ext.trim()).toLowerCase())
.filter((ext) => ext === '.bat' || ext === '.cmd');
if (pathExt.length === 0) return undefined;
const dirs = (env['PATH'] ?? '')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Look up Windows environment keys case-insensitively

When stdio MCP starts on a Windows environment whose inherited variable is named Path (the conventional casing), mergeStdioEnv() at client-stdio.ts:289-297 turns process.env into an ordinary case-sensitive record and always passes it here via line 188. Reading only env['PATH'] therefore produces an empty search list, so a config such as command: "npx" never finds npx.cmd and falls back to the same native-spawn ENOENT this change is meant to fix; resolve PATH (and PATHEXT at line 33) case-insensitively before scanning.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

说得对,这条我原来的写法在真实 Windows 上会直接失效:环境变量名不区分大小写,而 mergeStdioEnv() 产出的是普通对象,env['PATH'] 取不到 Path。

已按新提交的 c0ffb77 改掉两点:

  1. 读取 PATH/PATHEXT 时按 Windows 语义不区分大小写地找(同名变量取后写入的那个,即覆盖值优先);
  2. buildEnv() 在 Windows 上也改成不区分大小写地合并覆盖——原来 {...process.env, ...覆盖} 会留下 PATH 与 Path 两个同名变量,谁生效取决于顺序,这本身在 Windows 上就没有定义。

另外整条路径改成了"先照旧原生 spawn,只有它以 ENOENT/EINVAL 失败时才回退",所以正常命令根本不会进入解析逻辑。

新增用例覆盖了这一点:reads PATH and PATHEXT case-insensitively(用 Path/PathExt 拼写)以及一条只在真实 Windows 上跑的集成用例——把 .cmd 放在 PATH 上、用 Path 大小写传 env、spawn 裸命令名,断言能跑通。在 Windows 10(build 19045 / Node v24.15.0)上,这条用例在修复前报 spawn kimi-probe ENOENT,修复后通过。

const pathExt = (env['PATHEXT'] ?? '.COM;.EXE;.BAT;.CMD')
.split(';')
.map((ext) => stripQuotes(ext.trim()).toLowerCase())
.filter((ext) => ext === '.bat' || ext === '.cmd');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Honor executable matches before later batch shims

On Windows, when PATH=D1;D2, PATHEXT=.COM;.EXE;.BAT;.CMD, D1\tool.exe exists, and D2\tool.cmd also exists, this filter deletes .EXE before the directory walk; the new branch therefore bypasses the executable that native spawn('tool') used before and runs the later batch file. This can execute a different program for existing callers even though the change declares native executables unchanged; walk the full PATHEXT order and only dispatch through crossSpawn when the first existing candidate is a batch file.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这条也成立,原来的实现确实可能在 D1\tool.exe 与 D2\tool.cmd 同时存在时改跑后者。

新提交 c0ffb77 换了个思路,从根本上避免这个问题:现在先照旧原生 spawn,只有它以 ENOENT / EINVAL 失败时才回退到批处理路径。CreateProcess 自己会补 .exe 并在整个 PATH 上找,所以只要存在可执行文件,原生 spawn 就成功、根本不会进入回退分支——选中的程序因此不会变。

回退时的解析也按 (PATH 顺序 × PATHEXT 顺序) 取第一个存在的候选,候选是 .bat/.cmd 才交给 cross-spawn;是别的扩展名就放弃回退、保留原生 spawn 的错误。

对应的用例:keeps a later executable ahead of an earlier batch shim(前面的目录有 .exe 时解析结果为空、不接管)与 falls through to a batch shim when no earlier candidate exists。

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c0ffb77caa

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

): string | undefined {
const lowerCommand = command.toLowerCase();
if (lowerCommand.endsWith('.bat') || lowerCommand.endsWith('.cmd')) {
return isFile(command) ? command : undefined;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve suffixed batch commands using the spawn roots

When a Windows MCP or hook config names a batch with its suffix but relies on spawn search semantics—for example command: "npx.cmd" with the shim on PATH, or command: ".\\tools\\server.cmd" with options.cwd—the native attempt reaches the ENOENT/EINVAL fallback, but this check stats the name relative to the Kimi process's own cwd and returns before either env or the supplied cwd is used. The service therefore still throws SpawnFailed although the requested shim exists; resolve suffixed names from the spawn cwd and PATH before retrying.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这条对,原来的写法确实只 stat 了名字(相对 Kimi 进程自己的 cwd),既没看 spawn 的 cwd,也没走 PATH。

新提交 9954862 改了:

  • 带后缀的名字(npx.cmd)先按"带路径"处理——相对 spawn 的 cwd 解析并检查存在性;不带路径时按原名在 PATH 上逐个目录找;
  • 裸命令名仍走 PATHEXT 展开那条路径。

新增用例:resolves a suffixed batch command found on PATH(kimi-probe.cmd 只存在于 PATH 上时能被解析出来)与 resolves a relative batch path against the spawn cwd(tools/kimi-probe.cmd 相对 spawn cwd 解析)。

另外顺带修了 process.cwd() 的时机问题:cwd 只在 Windows 回退分支里才算,且包了 try/catch——之前是每次 spawn 都先算 cwd,进程 cwd 被删掉时会把本来能跑的原生 spawn 变成一个裸的 cwd 错误。

const spawnOptions = buildSpawnOptions(options);
const child = spawn(command, args as string[], spawnOptions);
const env = buildEnv(options.env) ?? process.env;
const cwd = resolve(options.cwd ?? process.cwd());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Defer cwd lookup until the Windows fallback

When running on POSIX from a directory that is removed after startup and a caller spawns without options.cwd (even an absolute executable), this eager process.cwd() throws ENOENT before spawnProcess enters the try; Node's native spawn can still launch an absolute program while the inherited cwd is unlinked, so the previously working native-spawn path now fails with a raw cwd error. Compute the cwd only after a retryable Windows failure.

AGENTS.md reference: AGENTS.md:L112-L112

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

同意,这个 eager 的 process.cwd() 是个真回归:进程 cwd 被删掉后,process.cwd() 自己就抛 ENOENT,于是在原生 spawn 之前就失败了——而 Node 的原生 spawn 在这种情况下仍然能启动绝对路径的程序。

新提交 9954862 把 cwd 的计算推迟到 Windows 回退分支内部(spawnCwd(),并包了 try/catch),POSIX 路径上完全不再触碰 process.cwd(),行为回到改动前。

On Windows, CreateProcess only appends .exe to a bare command name and
never consults PATHEXT, so a batch shim such as npx.cmd cannot be started
from a bare name; Node >= 20.12 also refuses .cmd/.bat outright. Every
local spawn that goes through the host process service therefore fails
with ENOENT or EINVAL on Windows, which takes stdio MCP servers (and any
other local command) down with it.

Resolve batch shims on Windows through PATHEXT and start them with
cross-spawn, the same mechanism the MCP SDK uses for its stdio client.
Commands that are not batch shims keep the native spawn path, so POSIX
behavior, the spawn error contract and the reported command stay
unchanged.
Windows resolves a bare command name through CreateProcess, which only
appends .exe and never consults PATHEXT, so a batch shim such as npx.cmd
cannot start from a bare name; Node >= 20.12 also refuses .cmd/.bat
outright. Every local spawn through the host process service therefore
fails with ENOENT or EINVAL on Windows, which takes stdio MCP servers
(and any other local command) down with it.

Keep the native spawn as the first attempt and only fall back when it
fails that way: resolve the command through PATHEXT and, when the first
existing candidate is a .bat/.cmd, start it with cross-spawn, the same
mechanism the MCP SDK uses for its stdio client. Commands that resolve to
an executable keep the native path, so the selected program, the POSIX
behavior and the spawn error contract stay unchanged.

Windows environment names are case-insensitive, so merge overrides
case-insensitively as well: inheriting PATH while an override spells it
Path used to leave two same-named variables behind and the later one
shadowed the other.
A config that spells the batch suffix itself (`command: "npx.cmd"`) or
points at one relative to the workspace (`command: "./tools/server.cmd"`)
still failed: the resolver stat'ed the name against the Kimi process cwd
instead of the spawn cwd and the PATH search, so it gave up before either
root was consulted.

Resolve suffixed names against the spawn cwd when they carry a path, and
search PATH for them by their exact name; keep the PATHEXT walk for bare
command names.

Also defer the cwd lookup to the Windows fallback: computing it up front
turned a spawn that used to work after the process cwd was removed into a
raw cwd error, because the lookup itself throws before the native spawn
is attempted.
@KaiOnCode

Copy link
Copy Markdown
Author

Closing: the same problem was fixed upstream by #4791 (merged 2026-11-10), which routes Windows batch-script commands through cross-spawn inside HostProcessService.spawn — the same entry point this PR targeted.

Anyone landing here for #3236 should look at #4791 (and the windowsCommand/cross-spawn wiring it left in packages/agent-core-v2/src/os/backends/node-local/hostProcessService.ts).

Thanks to the Codex review for the four findings along the way — the case-insensitive PATH/PATHEXT lookup and the executable-before-batch precedence were both real defects in the first revision of this branch.

@KaiOnCode KaiOnCode closed this Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Windows: stdio MCP servers fail with "spawn npx ENOENT" (v2 engine regression)

1 participant