Skip to content

fix(agent-core-v2): spawn Windows batch script commands through cmd.exe - #4791

Merged
liruifengv merged 11 commits into
mainfrom
fix/win32-spawn-cmd-shim
Nov 10, 2026
Merged

liruifengv merged 11 commits into
mainfrom
fix/win32-spawn-cmd-shim

Conversation

@liruifengv

Copy link
Copy Markdown
Collaborator

Requirement or Bug

Windows 上,凡是以脚本型命令(npx、npm、uvx 等,磁盘实体是 .cmd/.bat)声明的 stdio MCP 服务器都无法启动,服务器状态为 failed,日志报 spawn npx ENOENT。官方文档的 mcp.json 示例("command": "npx")以及插件清单里声明的 MCP 服务器(如 Chrome DevTools MCP)在 Windows 上全部命中此问题。本 PR 让这些配置在 Windows 上无需改写即可使用。

Bug Reproduction Steps

  1. Windows 机器上在 ~/.kimi-code/mcp.json 配置一个 stdio 服务器:"command": "npx", "args": ["-y", "[email protected]"]。
  2. 启动客户端,/mcp 显示该服务器 failed;kimi-code.log 出现 mcp server unavailable ... reason="spawn npx ENOENT"。
  3. 把 command 改写成 npx.cmd 全路径也不行:Node 会同步抛出 EINVAL。

Root Cause

Windows 上 npx 的实体是 npx.cmd,而 HostProcessService.spawn() 直接裸调 node:child_process 的 spawn:

  • 裸命令名 npx → CreateProcess 只在无扩展名时自动补 .exe,不做 PATHEXT 查找,因此 ENOENT;
  • 显式写 npx.cmd → Node ≥ 18.20.2 / 20.12.2(CVE-2024-27980)禁止无 shell 直接执行批处理文件,同步抛 EINVAL,且该同步异常此前不在 HostProcessError 的错误分类链路里。

本 PR 是根本修复:在本地进程派生的唯一入口补上 Windows 批处理解析与 cmd.exe 包装,而不是在 MCP 调用侧做特例绕过。远程 exec-server 复用同一 node-local 后端,因此远程 Windows 目标机上的 stdio 派生一并修好。

Code Changes

核心思路:只在「此前必然失败」的场景里插入一个转换层——Windows 且调用方未指定 shell 时,按 PATH + PATHEXT 解析裸命令名,若胜出者是 .cmd/.bat,则改写为 cmd.exe /d /s /c "<转义后的命令行>"(带 windowsVerbatimArguments);解析到 .exe/.com 或找不到命令时原样放行,现有成功路径与 ENOENT 错误链路完全不变。

 HostProcessService.spawn(command, args, options)
-  child = spawn(command, args, spawnOptions)          # 裸 spawn,无平台处理
+  target = win32 && shell 未指定 ? prepareWindowsSpawnTarget(command, args, env) : undefined
+  child = spawn(target?.command ?? command, target?.args ?? args, spawnOptions)
+  spawn 的同步异常与 waitForSpawn 失败统一归为 HostProcessError(SpawnFailed)

新增 src/os/backends/node-local/windowsCommand.ts 提供纯函数转换;hostProcessService.ts 接入并统一同步/异步两类 spawn 失败的错误形态。

关键决策:

决策 选择 没选 理由
修复层级 HostProcessService(中央 spawn 入口) client-stdio.ts 里做 MCP 特例 所有本地/远程 Windows 的 stdio 派生走同一入口,修一处全覆盖
第三方依赖 手写约百行转换逻辑 引入 cross-spawn exec-server 的 lint:imports 要求远程执行器只用 node 内置模块,而本文件在其依赖图内
处理范围 仅 .cmd/.bat 胜出时包装 所有命令统一走 shell .exe 等现有成功路径保持 CreateProcess 原语义,零回归面
包装方式 cmd.exe /d /s /c + 逐 token 转义 shell: true shell: true 对 args 只做朴素拼接,带空格/引号参数会碎且有注入面

已知限制:参数中的 cmd 元字符(%VAR% 展开等)不做逐字符转义,与计划文档中声明的范围一致;.ps1 不在处理范围。

阅读顺序:先看 windowsCommand.ts 理解解析与转义规则,再看 hostProcessService.ts 的接入点(约 15 行),测试与 changeset 可略读。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Windows 上 spawn 裸批处理命令名(如 npx) ENOENT 失败 经 cmd.exe 包装正常启动 无——该路径此前必然失败,包括 desktop/web 的 MCP 用户与插件清单声明的服务器 none
Windows 上 spawn 显式带 .cmd/.bat 扩展名的命令 同步 EINVAL 逃逸 经 cmd.exe 包装正常启动 无——该路径此前必然失败 none
spawn 的同步异常 原始异常逃逸,不进 HostProcessError 分类 统一归为 HostProcessError(SpawnFailed) 无既有调用方依赖同步异常形态(此前仅异步失败有分类) none
.exe/.com 命令、POSIX 平台、显式 shell 选项、找不到的命令 现状 不变 全部现有用户;找不到命令仍走原 ENOENT → McpClassifiedStartupError('config') 链路 n/a

受影响模块与测试覆盖:

  • os/backends/node-local:新增 6 个 mock 用例(裸名包装、带扩展名包装、路径形式包装、.exe 胜出不动、未知命令不动、显式 shell 不动)+ 1 个真实 .cmd 端到端用例(含带空格/引号参数 round-trip),钉住「不变」人群的旧行为。
  • mcpCore(消费方):逻辑未改,其测试在 Windows 上的存量失败与本 PR 无关(见折叠块)。

验证结论:目标测试 13/13 通过,typecheck 干净,check-no-comments 通过;lint:imports 的 1 处违规为存量问题(src/human/agent/origin.ts)。

存量失败的对照验证过程
  • mcpCore/client-stdio.test.ts 等 4 个文件共 44 个失败,报错为 cwd 拼接(/OpenSource/... 与 D:\OpenSource\... 混拼)与 symlink 权限等 Windows 环境问题。
  • 通过 git stash -u 在干净 main 上重跑:client-stdio.test.ts 同样 17 failed / 5 passed,与带本 PR 改动时一致,确认非本次回归。
  • lint:imports 违规位于 src/human/agent/origin.ts(human kernel import 边界),本次 diff 未触及该文件。

Checklist

  • I have read the CONTRIBUTING document.
  • 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.

Copilot AI lite review requested due to automatic review settings November 10, 2026 07:49
@changeset-bot

changeset-bot Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: f830e76

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 Nov 10, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T10:57:01.978697Z f830e76 Manual request
ℹ️ 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.

@pkg-pr-new

pkg-pr-new Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@f830e76
npx https://pkg.pr.new/@moonshot-ai/kimi-code@f830e76

commit: f830e76

Copilot AI 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.

🟡 Changes recommended

Unresolved Windows command handling defects can cause valid relative batch commands to fail and allow shell metacharacters to execute unintended commands.

3 open issues
What changed in this PR

该 PR 修复 Windows 上通过 npx、npm、uvx 等 .cmd/.bat 脚本启动 stdio MCP 服务失败的问题,并在统一的 node-local 进程派生入口中处理本地及远程 Windows 执行环境。

Changes:

  • 新增 Windows PATH/PATHEXT 解析及批处理命令识别逻辑,并通过 cmd.exe /d /s /c 启动脚本。
  • 在 HostProcessService 中接入批处理包装,并统一同步与异步 spawn 失败的错误分类。
  • 增加批处理命令解析、扩展名、路径、PATH 优先级和显式 shell 行为测试,并添加 changeset。
File Description
packages/​agent-core-v2/​test/​os/​backends/​node-local/​hostProcessService.test.ts 增加 Windows 批处理命令包装、路径和 shell 行为的测试覆盖。
packages/​agent-core-v2/​src/​os/​backends/​node-local/​windowsCommand.ts 实现 Windows PATH/PATHEXT 解析、批处理脚本识别及 cmd.exe 参数构造。
packages/​agent-core-v2/​src/​os/​backends/​node-local/​hostProcessService.ts 在中央进程派生入口接入 Windows 批处理包装并归一化 spawn 错误。
.changeset/​win32-batch-script-spawn.md 记录 Windows stdio MCP 脚本命令启动修复。

Review effort: Lite

@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: 4cdc791752

ℹ️ 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".

@liruifengv

Copy link
Copy Markdown
Collaborator Author

已在 efe2e5a 中处理全部评审意见:

  1. cmd.exe 元字符转义:采用 cross-spawn 的完整转义算法——参数无条件加引号,随后对所有元字符(含引号、&、|、^、% 等)做 ^ 转义;node_modules/.bin 下的 cmd shim 做二次转义。新增 metacharacter 用例。
  2. 相对路径按 cwd 解析:options.cwd 传入解析器,path 形式的相对命令按它 resolve(没有采用 cross-spawn 的 process.chdir 方式,避免全局状态)。
  3. 显式批处理扩展名:命令含点号时先按原名探测,与 PATHEXT 是否包含 .CMD/.BAT 无关(对齐 which 的行为)。新增自定义 PATHEXT 用例。
  4. exe 跨目录优先级:解析改为两遍——先按 CreateProcess 语义在 cwd + 全部 PATH 目录找 .exe,找到即原样放行;只有全找不到时才考虑批处理包装。即批处理 shim 只在「此前必然失败」的场景触发,不改变任何既有成功路径。新增跨目录 exe/cmd 优先级用例。

补充说明:第 4 点 cross-spawn/which 同样是目录优先、会选中前面目录的 .cmd(其面向 npm shim 场景,无需保持 CreateProcess 语义);这里刻意比 cross-spawn 更保守。

测试:hostProcessService 17/17 通过(含 4 个新增评审用例与真实 .cmd 端到端 round-trip),typecheck / check-no-comments 干净。

@liruifengv

Copy link
Copy Markdown
Collaborator Author

@codex

@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: efe2e5aab9

ℹ️ 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".

@liruifengv

Copy link
Copy Markdown
Collaborator Author

复审意见已处理(6bf2300a6):裸命令的原生查找保护从 .exe 扩展到 .com,与 libuv 实际行为一致(已在本机实测:PATH 上仅有 .com 时裸命令可正常执行)。新增对应用例,hostProcessService 测试 18/18 通过。

@liruifengv

Copy link
Copy Markdown
Collaborator Author

@codex

@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: 6bf2300a66

ℹ️ 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".

@liruifengv

Copy link
Copy Markdown
Collaborator Author

第三轮复审意见已处理(743e70dad):

  1. 换行符注入(P1):批处理包装前拒绝命令或参数中的 \r/\n(此类字符无法安全转义,直接抛错,不启动进程)。
  2. env 大小写赢家(P1):PATH/PATHEXT/ComSpec 的取值改为在继承与配置两个来源中按键名词典序取最小者,与 Node 在 Windows 上的行为一致;新增用例覆盖「继承 PATH vs 配置 Path」的场景。
  3. 搜索根统一(P2):原生与批处理探测共用一份以 options.cwd 为根的搜索列表,裸批处理命令也会搜索 cwd,相对 PATH 目录按 cwd resolve。

hostProcessService 测试 21/21 通过,typecheck / check-no-comments 干净。

@liruifengv

Copy link
Copy Markdown
Collaborator Author

@codex

@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: 743e70dada

ℹ️ 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".

@liruifengv

Copy link
Copy Markdown
Collaborator Author

实现方式调整(2770e276c):按维护者决定,移除自实现的 Windows 解析/转义模块(windowsCommand.ts,净删 363 行),主路径直接改用 cross-spawn。跨目录 exe/com 优先级、换行符拒绝、env 词典序赢家等自实现语义随之移除,PR 描述中已列出与 cross-spawn 语义绑定的取舍表;唯一行为变化是 Windows 上未知裸命令改为经 cmd.exe 运行时报错(退出码 1),不再在 spawn 阶段抛 ENOENT,对应存量测试已按平台分流。测试 8 通过 + 1 平台跳过,typecheck / lint 干净。

@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

❌ Nix build failed

Hash mismatch in pnpmDeps:

Hash
specified sha256-Ufuz0jPfe8R3jOtkEn4VxgkqfLJ2xanDRbcdqYlbx4M=
got sha256-Jo/qTBS8SwKNTmSnwTjxBjlwmJ6GpnfyzB6r0iiihSY=

Please update flake.nix with the got hash.

@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: 5400d8c5de

ℹ️ 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".

@liruifengv

Copy link
Copy Markdown
Collaborator Author

spawn 阶段 ENOENT 分类问题已按方案 B 修复(72f57d1d4):cross-spawn 对未解析到命令的进程会以退出码 1 退出并补发带 code: 'ENOENT' 的 error(见其 lib/enoent.js),StdioMcpClient.connect() 失败时现在会把 transport 记录到的 ENOENT 家族错误同样归类为 McpClassifiedStartupError('config'),与 spawn 阶段的 ENOENT 走同一分类,避免被当作可重试的传输故障无限重连。spawn 层无任何自实现逻辑。新增用例模拟进程级 ENOENT 验证分类结果。

@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: 72f57d1d46

ℹ️ 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".

@liruifengv

Copy link
Copy Markdown
Collaborator Author

关于显式空 PATH 的评审意见,做了真机验证,决定不处理:

which 的 opt.path || process.env.PATH 回退确实存在,但它只影响 cross-spawn「是否需要 cmd.exe 包装」的判断——cross-spawn 最终 spawn 的是原始命令名,真正的命令解析发生在子进程里,而子进程拿到的 PATH 是调用方显式设置的空值。实测:父 PATH 放入 fake-tool.cmd,以 env: { PATH: '' } spawn 裸命令,结果是退出码 1、stderr 'fake-tool' 不是内部或外部命令,被排除的程序并未执行,调用方的排除意图是成立的。

残留差异仅在错误分类:此场景 which 用父 PATH 解析到了文件,enoent.js 的 !parsed.file 条件不命中,失败会落在可重试传输故障而非配置错误。考虑到显式将 PATH 置空的 MCP 配置极为罕见,且不存在执行非预期程序的安全问题,此处接受 cross-spawn 的既有语义,不额外加分支。

@liruifengv

Copy link
Copy Markdown
Collaborator Author

@codex

@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: f591b6a6cd

ℹ️ 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".

@liruifengv

Copy link
Copy Markdown
Collaborator Author

显式 shell 命令的退出码问题已修复(1b846c2c9):options.shell 未指定时才委托 cross-spawn,显式 shell: true 的 spawn 保留原生 node:child_process 路径,避免 cross-spawn 的 ENOENT hook 因 parsed.file 未设置而把正常的退出码 1 误报为命令不存在。外部 hooks(shell: true)行为不变。新增用例验证显式 shell 不经过 cross-spawn;真机探针确认 exit 1 的 shell 命令 wait() 以退出码 1 正常返回。测试 9 通过 + 1 平台跳过,typecheck 干净。

@liruifengv

Copy link
Copy Markdown
Collaborator Author

exit-error 等待的挂死风险已修复(f830e76a4):exitError() 现在带 1 秒有界回退——进程关闭 stdout 但仍存活的场景下,transport 的 finish() 已清空进程句柄,close 无法再 kill,无界等待会导致 connect 永远挂起;超时后回退为 undefined,按原始启动错误正常报错。新增用例模拟「进程不死但 stdout 关闭」,验证 connect 正常失败不挂死;此前的 ENOENT 分类用例不受影响,两个用例均通过。

@liruifengv

Copy link
Copy Markdown
Collaborator Author

@codex

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: f830e76a45

ℹ️ 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".

@liruifengv
liruifengv merged commit 4d44cc6 into main Nov 10, 2026
16 checks passed
@liruifengv
liruifengv deleted the fix/win32-spawn-cmd-shim branch November 10, 2026 11:00
liruifengv added a commit that referenced this pull request Nov 10, 2026
…xe (#4791) (#4804)

* fix(agent-core-v2): spawn Windows batch script commands through cmd.exe

* fix(agent-core-v2): harden Windows batch spawn escaping and resolution

* fix(agent-core-v2): preserve native .com precedence in Windows spawn resolution

* fix(agent-core-v2): reject line breaks and align env and cwd resolution in Windows batch spawn

* refactor(agent-core-v2): replace custom Windows batch spawn handling with cross-spawn

* chore: update lockfile for cross-spawn

* chore: update nix pnpmDeps hash for cross-spawn

* fix(agent-core-v2): classify process-level ENOENT during MCP startup as config error

* fix(agent-core-v2): await transport exit error before classifying MCP startup failure

* fix(agent-core-v2): keep native spawn for explicit-shell commands on Windows

* fix(agent-core-v2): bound the MCP transport exit-error wait
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 11, 2026
…nfig errors

Port upstream MoonshotAI#4791. Capture the transport exit error and pass it to
classifyStdioStartupError so a process-level permanent errno during
startup surfaces as a configuration error with its cause. The Windows
batch-script spawn routing from the same PR is already equivalent via
the Bun findWindowsScript path. Record the B4 ledger verdicts.
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.

3 participants