Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(subagent): resolve .cmd shims on Windows before spawning CLIs (#853)

zhourayme1cb7ebd2a56
diff --git a/deeptutor/services/subagent/models.py b/deeptutor/services/subagent/models.py
index f6357fdda..b2217ba0b 100644
--- a/deeptutor/services/subagent/models.py
+++ b/deeptutor/services/subagent/models.py
@@ -34,7 +34,7 @@ from pathlib import Path
import re
from typing import Any
-from deeptutor.services.subagent.process import probe_version
+from deeptutor.services.subagent.process import probe_version, resolve_cli_command
from deeptutor.services.subagent.registry import get_backend
logger = logging.getLogger(__name__)
@@ -241,6 +241,7 @@ async def _list_cli_models(cli_command: str, *, refresh: bool = False) -> list[M
cmd = [cli_command, "models"]
if refresh:
cmd.append("--refresh")
+ cmd = resolve_cli_command(cmd)
try:
process = await asyncio.create_subprocess_exec(
*cmd,
diff --git a/deeptutor/services/subagent/opencode_server.py b/deeptutor/services/subagent/opencode_server.py
index 9936745b1..77f63d4f0 100644
--- a/deeptutor/services/subagent/opencode_server.py
+++ b/deeptutor/services/subagent/opencode_server.py
@@ -31,6 +31,8 @@ import time
import httpx
+from deeptutor.services.subagent.process import resolve_cli_command
+
logger = logging.getLogger(__name__)
# How long a server may sit unused before the next acquire() reaps it.
@@ -102,8 +104,9 @@ async def _spawn(cli_command: str, *, cwd: str, env_prefix: str, username: str)
f"{env_prefix}_SERVER_PASSWORD": password,
f"{env_prefix}_SERVER_USERNAME": username,
}
+ cli = resolve_cli_command([cli_command], path=env.get("PATH"))[0]
process = await asyncio.create_subprocess_exec(
- cli_command,
+ cli,
"serve",
"--port",
str(port),
diff --git a/deeptutor/services/subagent/process.py b/deeptutor/services/subagent/process.py
index 47d468e04..605d089a1 100644
--- a/deeptutor/services/subagent/process.py
+++ b/deeptutor/services/subagent/process.py
@@ -20,9 +20,36 @@ from collections.abc import AsyncIterator, Mapping, Sequence
import contextlib
import logging
import os
+import shutil
logger = logging.getLogger(__name__)
+
+def resolve_cli_command(cmd: Sequence[str], *, path: str | None = None) -> list[str]:
+ """Resolve ``cmd[0]`` to a full path via PATH/PATHEXT before spawning.
+
+ On Windows, ``asyncio.create_subprocess_exec`` (and the underlying
+ ``CreateProcess``) only appends ``.exe`` when resolving a bare command
+ name, so CLIs installed by npm ship as ``.cmd``/``.bat``/``.ps1`` shims
+ (e.g. ``claude``/``codex``) are invisible and the spawn raises
+ ``FileNotFoundError`` — the backend then reports "not installed" even
+ though the CLI is on PATH. ``shutil.which`` honors ``PATHEXT`` (and a
+ caller-supplied PATH) and returns the shim's full path, so the spawn
+ finds it.
+
+ Returns the command unchanged when ``cmd`` is empty, when ``cmd[0]`` is
+ already an absolute path (resolved back to itself), or when nothing on
+ PATH matches — in that last case the OS spawn behaves exactly as before,
+ preserving the existing ``FileNotFoundError`` semantics callers handle.
+ """
+ if not cmd:
+ return list(cmd)
+ resolved = shutil.which(cmd[0], path=path)
+ if resolved:
+ return [resolved, *list(cmd[1:])]
+ return list(cmd)
+
+
# (channel, text) where channel is "stdout", "stderr", or "exit" (the final
# item, whose text is the integer return code as a string).
ProcessLine = tuple[str, str]
@@ -43,8 +70,9 @@ async def stream_process_lines(
arrival order via a shared queue.
"""
full_env = {**os.environ, **(env or {})}
+ resolved_cmd = resolve_cli_command(cmd, path=full_env.get("PATH"))
process = await asyncio.create_subprocess_exec(
- *cmd,
+ *resolved_cmd,
cwd=cwd or None,
env=full_env,
stdin=asyncio.subprocess.DEVNULL,
@@ -117,8 +145,9 @@ async def probe_version(cmd: Sequence[str], *, timeout: float = 8.0) -> tuple[bo
the no-timeout consult semantics — a probe that hangs is a failed probe.
"""
try:
+ resolved_cmd = resolve_cli_command(cmd)
process = await asyncio.create_subprocess_exec(
- *cmd,
+ *resolved_cmd,
stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
@@ -136,4 +165,4 @@ async def probe_version(cmd: Sequence[str], *, timeout: float = 8.0) -> tuple[bo
return process.returncode == 0, text
-__all__ = ["ProcessLine", "stream_process_lines", "probe_version"]
+__all__ = ["ProcessLine", "resolve_cli_command", "stream_process_lines", "probe_version"]
diff --git a/tests/services/test_subagent_backends.py b/tests/services/test_subagent_backends.py
index ef478b707..24f801742 100644
--- a/tests/services/test_subagent_backends.py
+++ b/tests/services/test_subagent_backends.py
@@ -13,6 +13,7 @@ import sys
import pytest
+from deeptutor.services.subagent import process as process_mod
from deeptutor.services.subagent.claude_code import ClaudeCodeBackend
from deeptutor.services.subagent.codex import CodexBackend
from deeptutor.services.subagent.config import (
@@ -22,7 +23,7 @@ from deeptutor.services.subagent.config import (
SubagentSettings,
settings_from_dict,
)
-from deeptutor.services.subagent.process import stream_process_lines
+from deeptutor.services.subagent.process import resolve_cli_command, stream_process_lines
from deeptutor.services.subagent.types import ConsultResult
# ---- command building --------------------------------------------------------
@@ -393,6 +394,52 @@ async def test_stream_process_lines_reports_nonzero_exit() -> None:
assert seen[-1] == ("exit", "3")
+# ---- command resolution (Windows .cmd shim fix, issue #759) -------------------
+
+
+def test_resolve_cli_command_passes_empty_through() -> None:
+ assert resolve_cli_command([]) == []
+
+
+def test_resolve_cli_command_returns_absolute_path_unchanged() -> None:
+ # An absolute path that exists (sys.executable) resolves back to itself,
+ # so the live-subprocess tests above are unaffected by the resolve step.
+ resolved = resolve_cli_command([sys.executable, "--version"])
+ assert resolved[0] == sys.executable
+ assert resolved[1] == "--version"
+
+
+def test_resolve_cli_command_resolves_bare_name_to_full_path(monkeypatch) -> None:
+ # On Windows, a bare npm-installed CLI name resolves only via PATHEXT to a
+ # ``.cmd`` shim; shutil.which is what honors PATHEXT, so we monkeypatch it
+ # to stand in for "the shim was found on PATH".
+ monkeypatch.setattr(process_mod.shutil, "which", lambda name, path=None: r"C:\npm\claude.cmd")
+ resolved = resolve_cli_command(["claude", "--version"])
+ assert resolved == [r"C:\npm\claude.cmd", "--version"]
+
+
+def test_resolve_cli_command_falls_back_when_unresolvable(monkeypatch) -> None:
+ # Nothing on PATH matches → return the command unchanged so the OS spawn
+ # (and its FileNotFoundError) behaves exactly as before the fix.
+ monkeypatch.setattr(process_mod.shutil, "which", lambda name, path=None: None)
+ resolved = resolve_cli_command(["nonexistent-cli", "--version"])
+ assert resolved == ["nonexistent-cli", "--version"]
+
+
+def test_resolve_cli_command_honors_caller_supplied_path(monkeypatch) -> None:
+ # stream_process_lines / _spawn pass the child env's PATH so a custom PATH
+ # is honored during resolution rather than only the parent process's PATH.
+ seen: dict[str, str | None] = {}
+
+ def fake_which(name: str, path: str | None = None) -> None:
+ seen["path"] = path
+ return None
+
+ monkeypatch.setattr(process_mod.shutil, "which", fake_which)
+ resolve_cli_command(["claude"], path="/custom/bin")
+ assert seen["path"] == "/custom/bin"
+
+
# ---- settings ----------------------------------------------------------------