Skip to content

The agent that grows with you

fix: Hermes's own lint, activate, tui and MCP launchers use PM's node/npx/uv, never the user's

teknium1e0fae5566afd
diff --git a/hermes_platform/resolver/known_dirs.py b/hermes_platform/resolver/known_dirs.py
index 6901e195696..d22fe0ac13e 100644
--- a/hermes_platform/resolver/known_dirs.py
+++ b/hermes_platform/resolver/known_dirs.py
@@ -25,17 +25,6 @@ def rust_tool_dirs() -> tuple[str, ...]:
return ("~/.cargo/bin",) if _POSIX else ("%USERPROFILE%/.cargo/bin",)
-def uv_tool_dirs() -> tuple[str, ...]:
- """uv's install locations outside PATH, in uv's own install order: the per-user
- installer's ``~/.local/bin`` (every OS — that is where uv's docs put it), then
- Homebrew (Apple Silicon ``/opt``, Intel / from-source ``/usr/local``). The tilde
- form is deliberate: callers that only ``expanduser`` (the stdio launcher
- fallback) get the same result as ``locate_command``'s expandvars+expanduser."""
- if _POSIX:
- return ("~/.local/bin", "/opt/homebrew/bin", "/usr/local/bin")
- return ("~/.local/bin",)
-
-
def node_tool_dirs() -> tuple[str, ...]:
return ("~/.npm-global/bin", "~/.bun/bin", "~/.volta/bin") if _POSIX else ("%APPDATA%/npm", "%USERPROFILE%/.bun/bin", "%LOCALAPPDATA%/Volta/bin")
diff --git a/pm/__init__.py b/pm/__init__.py
index acb3ece6795..b738469c816 100644
--- a/pm/__init__.py
+++ b/pm/__init__.py
@@ -22,7 +22,7 @@ import sys
_EXPORTS = {
"pm.install": (
"activate", "check", "drift", "enabled_extras", "env_for", "is_installed",
- "installed_package", "lazy_installs_allowed",
+ "installed_package", "lazy_installs_allowed", "store_first_path", "uv_launcher",
),
"pm.client": (
"ensure", "sync_venv", "build_environment", "lock_project", "stage_manager_runtime",
diff --git a/pm/install.py b/pm/install.py
index a9575adb236..8baef8d5ab3 100644
--- a/pm/install.py
+++ b/pm/install.py
@@ -114,6 +114,23 @@ def installed_package(name: str, *, allow_outdated: bool = False) -> InstalledPa
return InstalledPackage(entry, fact["version"], package.binary(entry, target))
+def uv_launcher(name: str) -> Path | None:
+ """PM's installed ``uv``/``uvx`` for a user-declared MCP stdio ``command:``, so a bare
+ ``uvx`` server runs the packaged uv, never the user's. Read-only; Hermes's own Python
+ work still goes through PM operations, not this executable."""
+ if name not in ("uv", "uvx"):
+ raise ValueError(f"{name!r} is not a uv launcher")
+ package = get_package("uv")
+ target = current_target()
+ location = _installed_location(package, _lockfile(), target)
+ if location is None:
+ return None
+ facts, store = location
+ binary = package.binary(store.entry(facts.get("uv")["entry"]), target)
+ launcher = binary.with_name(name + binary.suffix) if binary is not None else None
+ return launcher if launcher is not None and launcher.is_file() else None
+
+
def _identity(lockfile: Lockfile, name: str, target: str):
"""The identity the lock currently pins for `name` on `target`:
(target, tuple(artifact sha256s)) — or None when the lock pins no
@@ -822,14 +839,24 @@ def _store_path_dirs() -> list[str]:
"""Composed PATH dirs of all installed (non-internal, on_path) store
packages, deps-first, deduped. Includes optional packages that are
*installed* (facts say so) — an installed git/gh must be on PATH even
- though it's not in the root closure. Never installs."""
+ though it's not in the root closure. A package whose dependency chain is
+ not fully installed contributes nothing: store npm over a missing store
+ node would run the user's node, a partial toolchain. Never installs."""
lockfile = _lockfile()
target = current_target()
+ locations: dict[str, object] = {}
+
+ def located(package):
+ if package.name not in locations:
+ locations[package.name] = _installed_location(package, lockfile, target)
+ return locations[package.name]
+
dirs: list[str] = []
for name in lockfile.names():
try:
package = get_package(name)
+ chain = walk([name])
except KeyError:
continue
if package.internal:
@@ -838,8 +865,9 @@ def _store_path_dirs() -> list[str]:
continue
if package.missing_reason(target) is not None:
continue
- location = _installed_location(package, lockfile, target)
- if location is None:
+ location = located(package)
+ if location is None or any(located(dep) is None for dep in chain
+ if dep.missing_reason(target) is None):
continue
facts, store = location
env = facts.env_for(name, store.root)
@@ -853,16 +881,19 @@ def _store_path_dirs() -> list[str]:
def activate(*, allow_incomplete: bool = False) -> list[str]:
- """Make the installed store usable: prepend its tool dirs to
- os.environ['PATH'] so reactive `shutil.which('git'|'bash'|'ffmpeg'|...)`
- resolves the bundled binaries. The gate is `check()` — if the store is
- broken, refuse to inject (fail fast rather than serving a partial PATH).
- Return the check's problems, or an empty list on success, so startup
+ """Make the installed store usable: put its tool dirs at the FRONT of
+ os.environ['PATH'] so reactive `shutil.which('git'|'node'|'ffmpeg'|...)`
+ resolves the bundled binaries, never a user copy that sorts earlier.
+ Return `check()`'s problems, or an empty list on success, so startup
callers can report the verdict without checking the store twice.
+ Drift still activates every package whose whole chain is installed
+ (`_store_path_dirs`): refusing all of them handed every tool to the
+ user's PATH copies. A damaged package, and anything depending on it,
+ stays off PATH so no toolchain is served half from the store.
+
``allow_incomplete`` is the install-time exception: tools are published
- before the venv sync, so a missing venv must not hide the tools the sync
- is about to build against. A missing tool still refuses.
+ before the venv sync, so the venv verdict is not computed at all.
This is the ONE sanctioned global PATH write: PATH is the discovery
contract every `which` reads, not a tool-specific env leak. Store-first
@@ -873,15 +904,21 @@ def activate(*, allow_incomplete: bool = False) -> list[str]:
# The venv verdict is discarded here, and computing it imports application
# config readers (ruamel) that the bare update interpreter does not carry.
problems = check(include_venv=not allow_incomplete)
- if problems:
- return problems
+ path = os.environ.get("PATH", "")
+ first = store_first_path(path)
+ if first != path:
+ os.environ["PATH"] = first
+ return problems
+
+
+def store_first_path(path: str) -> str:
+ """``path`` with the installed store's tool dirs moved to the front, for
+ Hermes's own children whose PATH gets other dirs prepended after activate."""
+ import os
+
dirs = _store_path_dirs()
if not dirs:
- return []
- existing = os.environ.get("PATH", "")
- prefix = os.pathsep.join(dirs)
- existing_lower = {p.lower() for p in existing.split(os.pathsep) if p}
- missing = [d for d in dirs if d.lower() not in existing_lower]
- if missing:
- os.environ["PATH"] = os.pathsep.join([*missing, existing]) if existing else os.pathsep.join(missing)
- return []
+ return path
+ store = {d.lower() for d in dirs}
+ rest = [p for p in path.split(os.pathsep) if p and p.lower() not in store]
+ return os.pathsep.join([*dirs, *rest])
diff --git a/tests/fixtures/resolution_allowlist.json b/tests/fixtures/resolution_allowlist.json
index 126be7fd5e5..ea84b0db5e7 100644
--- a/tests/fixtures/resolution_allowlist.json
+++ b/tests/fixtures/resolution_allowlist.json
@@ -534,6 +534,11 @@
"symbol": "_resolve_stdio_command",
"kind": "bare_which"
},
+ {
+ "path": "tools/mcp_tool_config.py",
+ "symbol": "_managed_launcher",
+ "kind": "bare_which"
+ },
{
"path": "tools/process_registry.py",
"symbol": "_build_systemd_scope_argv",
@@ -678,5 +683,10 @@
"path": "tools/bot_desktop/runtime.py",
"symbol": "installable",
"kind": "bare_which"
+ },
+ {
+ "path": "tools/file_operations_lint.py",
+ "symbol": "LintMixin._run_managed_node_linter",
+ "kind": "bare_which"
}
]
diff --git a/tests/gateway/test_tui_slash_worker_path.py b/tests/gateway/test_tui_slash_worker_path.py
index 3bc314808b2..ceae0bdf2ee 100644
--- a/tests/gateway/test_tui_slash_worker_path.py
+++ b/tests/gateway/test_tui_slash_worker_path.py
@@ -39,3 +39,15 @@ class TestPrependToolPaths:
assert parts[0] == str(tmp_path / "hh" / "bin")
assert str(Path(sys.executable).parent) in parts
assert str(Path.home() / ".local" / "bin") in parts
+
+ def test_pm_store_dirs_go_ahead_of_user_local_bin(self, monkeypatch, tmp_path):
+ """A user's node/uv in ~/.local/bin must never shadow Hermes's PM toolchain."""
+ store_dir = str(tmp_path / "store" / "node" / "bin")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hh"))
+ monkeypatch.setattr("pm.install._store_path_dirs", lambda: [store_dir])
+ result = tui_server._prepend_tool_paths({"PATH": os.pathsep.join(["/usr/bin", store_dir])})
+
+ parts = result["PATH"].split(os.pathsep)
+ assert parts[0] == store_dir
+ assert parts.count(store_dir) == 1
+ assert parts.index(str(Path.home() / ".local" / "bin")) > 0
diff --git a/tests/pm/test_startup_activation.py b/tests/pm/test_startup_activation.py
index ad377c0da99..c24b9f724cd 100644
--- a/tests/pm/test_startup_activation.py
+++ b/tests/pm/test_startup_activation.py
@@ -1,4 +1,4 @@
-"""Startup consumes one real PM verdict without activating a partial store."""
+"""Startup consumes one real PM verdict; activation never serves a partial toolchain."""
import importlib
import os
@@ -26,7 +26,7 @@ def checked_store(tmp_path, monkeypatch, served):
docroot, url = served
lock = Lockfile(paths.lockfile_path())
binaries = []
- for name in ("first", "second"):
+ for name in ("first", "second", "third"):
package = BinaryPackage()
package.name = name
package.probe_version = False
@@ -53,24 +53,33 @@ def checked_store(tmp_path, monkeypatch, served):
return binaries, checks
-def test_activate_returns_live_verdict_without_partial_environment(checked_store, monkeypatch):
+def test_activate_moves_store_dirs_ahead_of_user_dirs(checked_store, monkeypatch):
binaries, checks = checked_store
- original_path = os.environ["PATH"]
- monkeypatch.setenv("PATH", original_path)
+ store = [str(binary.parent) for binary in binaries]
+ user_dir = os.path.join(os.sep, "user", "bin")
+ # A store dir already on PATH behind a user dir must still end up in front of it.
+ monkeypatch.setenv("PATH", os.pathsep.join([user_dir, store[1]]))
assert pm.activate() == []
assert checks == [[]]
- active_path = os.environ["PATH"].split(os.pathsep)
- assert all(str(binary.parent) in active_path for binary in binaries)
+ assert os.environ["PATH"].split(os.pathsep) == [*store, user_dir]
+
+
+def test_drift_activates_intact_chains_and_reports_the_live_verdict(checked_store, monkeypatch):
+ binaries, checks = checked_store
+ user_dir = os.path.join(os.sep, "user", "bin")
+ monkeypatch.setattr(registry._packages["third"], "deps", ("second",))
+ assert pm.activate() == []
# A second invocation must observe fresh damage, even after healthy activation.
- monkeypatch.setenv("PATH", original_path)
+ monkeypatch.setenv("PATH", user_dir)
binaries[1].unlink()
- before = dict(os.environ)
problems = pm.activate()
assert problems == ["second: not installed or outdated"]
assert checks == [[], problems]
- assert dict(os.environ) == before
+ # Intact first stays ahead of the user's copies; damaged second and third, which
+ # depends on it, stay off PATH so no toolchain is served half from the store.
+ assert os.environ["PATH"].split(os.pathsep) == [str(binaries[0].parent), user_dir]
@pytest.mark.parametrize("surface", ["gateway", "cli"])
@@ -115,7 +124,8 @@ def test_startup_uses_one_verdict(checked_store, monkeypatch, capsys, caplog, su
assert checks == [expected]
diagnostics = capsys.readouterr().err + caplog.text
if damaged:
- assert os.environ["PATH"] == original_path
+ assert os.environ["PATH"].split(os.pathsep)[0] == str(binaries[0].parent)
+ assert str(binaries[1].parent) not in os.environ["PATH"].split(os.pathsep)
assert "install out of sync (second: not installed or outdated)" in diagnostics
else:
assert all(str(binary.parent) in os.environ["PATH"].split(os.pathsep) for binary in binaries)
diff --git a/tests/tools/test_file_operations_edge_cases.py b/tests/tools/test_file_operations_edge_cases.py
index 5224ddfe171..bbf0cf8dc8d 100644
--- a/tests/tools/test_file_operations_edge_cases.py
+++ b/tests/tools/test_file_operations_edge_cases.py
@@ -5,6 +5,9 @@ Covers:
- ``_check_lint()`` robustness against file paths containing curly braces
"""
+import os
+import sys
+
import pytest
from unittest.mock import MagicMock, patch
@@ -110,6 +113,37 @@ class TestCheckLintBracePaths:
assert "SyntaxError" in result.output
[email protected](sys.platform == "win32", reason="POSIX sh stand-ins for node")
+def test_local_js_lint_runs_pm_node_never_the_users(tmp_path, monkeypatch):
+ """Hermes's own post-write lint uses PM's Node even when the user's node sorts first on
+ PATH, and skips (never falls back to the user's) when PM has no Node."""
+ import hermes_constants
+ from tools.environments.local import LocalEnvironment
+
+ def node_stand_in(directory, label):
+ directory.mkdir()
+ node = directory / "node"
+ node.write_text(f'#!/bin/sh\necho {label} "$@"\nexit 1\n', encoding="utf-8")
+ node.chmod(0o755)
+ return str(directory)
+
+ user_bin = node_stand_in(tmp_path / "user-bin", "user-node")
+ store_dirs = [node_stand_in(tmp_path / "store-node", "pm-node")]
+ monkeypatch.setenv("PATH", os.pathsep.join([user_bin, os.environ.get("PATH", "")]))
+ monkeypatch.setattr(hermes_constants, "with_hermes_node_path", lambda env: {
+ **env, "PATH": os.pathsep.join([*store_dirs, env.get("PATH", "")]).strip(os.pathsep)})
+ target = tmp_path / "a.js"
+ target.write_text("x\n", encoding="utf-8")
+ ops = ShellFileOperations(LocalEnvironment(cwd=str(tmp_path)), cwd=str(tmp_path))
+
+ result = ops._check_lint(str(target))
+ assert result.output == f"pm-node --check {target}"
+
+ store_dirs.clear()
+ result = ops._check_lint(str(target))
+ assert result.skipped and "Hermes-managed Node" in result.message
+
+
class TestCheckLintInproc:
"""Verify in-process linters (.py via ast.parse, .json, .yaml, .toml).
diff --git a/tests/tools/test_mcp_tool.py b/tests/tools/test_mcp_tool.py
index ef85312acfd..96e1c6c7305 100644
--- a/tests/tools/test_mcp_tool.py
+++ b/tests/tools/test_mcp_tool.py
@@ -1069,6 +1069,11 @@ class TestDiscoverAndRegister:
class TestMCPServerTask:
"""Test the MCPServerTask lifecycle with mocked MCP SDK."""
+ @pytest.fixture(autouse=True)
+ def _no_pm_launcher(self, monkeypatch):
+ # Launcher resolution is not under test here, and a CI host has no PM-managed Node.
+ monkeypatch.setattr("tools.mcp_tool_config._managed_launcher", lambda command: None)
+
def _mock_stdio_and_session(self, session):
"""Return patches for stdio_client and ClientSession as async CMs."""
mock_read, mock_write = MagicMock(), MagicMock()
diff --git a/tests/tools/test_mcp_tool_issue_948.py b/tests/tools/test_mcp_tool_issue_948.py
index cf4ce059145..b1f13b1e7d0 100644
--- a/tests/tools/test_mcp_tool_issue_948.py
+++ b/tests/tools/test_mcp_tool_issue_948.py
@@ -8,7 +8,7 @@ import pytest
from tools.mcp_tool import MCPServerTask, _MCP_AVAILABLE
from tools.mcp_tool_errors import _format_connect_error
-from tools.mcp_tool_config import _node_fallback, _resolve_stdio_command
+from tools.mcp_tool_config import _resolve_stdio_command
from tools.mcp_tool_config import _which_with_config_pathext
# Ensure the mcp module symbols exist for patching even when the SDK isn't installed
@@ -22,162 +22,6 @@ if not _MCP_AVAILABLE:
_mcp_mod.ClientSession = MagicMock
-def test_resolve_stdio_command_falls_back_to_hermes_node_bin(tmp_path):
- node_bin = tmp_path / "node" / "bin"
- node_bin.mkdir(parents=True)
- npx_path = node_bin / "npx"
- npx_path.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
- npx_path.chmod(0o755)
-
- with patch("tools.mcp_tool_config.shutil.which", return_value=None), \
- patch.dict("os.environ", {"HERMES_HOME": str(tmp_path)}, clear=False):
- command, env = _resolve_stdio_command("npx", {"PATH": "/usr/bin"})
-
- assert command == str(npx_path)
- assert env["PATH"].split(os.pathsep)[0] == str(node_bin)
-
-
-def test_windows_managed_node_root_prefers_cmd_launchers(tmp_path):
- """Managed Windows Node lives directly in ``<HERMES_HOME>/node`` (no ``bin``) as ``npx.cmd`` /
- ``npm.cmd`` / ``node.exe``; a bare ``command: npx`` must resolve to those launchers (#111937).
- The extensionless POSIX sibling is a shell script Windows cannot spawn, so it must never win."""
- node_root = tmp_path / "node"
- node_root.mkdir()
- for name in ("npx", "npm", "npx.cmd", "npm.cmd", "node.exe"):
- launcher = node_root / name
- launcher.write_text("@echo off\r\n", encoding="utf-8")
- launcher.chmod(0o755)
-
- with patch.dict("os.environ", {"HERMES_HOME": str(tmp_path)}, clear=False):
- assert _node_fallback("npx", windows=True) == str(node_root / "npx.cmd")
- assert _node_fallback("npm", windows=True) == str(node_root / "npm.cmd")
- assert _node_fallback("node", windows=True) == str(node_root / "node.exe")
-
-
-def test_node_fallback_uses_active_profile_home(tmp_path, monkeypatch):
- """The managed-Node lookup follows ``get_hermes_home()`` (context override), not raw ``HERMES_HOME``:
- a multiplexed profile whose home differs from the launch env must find ITS managed Node."""
- from hermes_constants import reset_hermes_home_override, set_hermes_home_override
-
- profile_home = tmp_path / "profile"
- npx_path = profile_home / "node" / "bin" / "npx"
- npx_path.parent.mkdir(parents=True)
- npx_path.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
- npx_path.chmod(0o755)
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "launch-home"))
- monkeypatch.setenv("HOME", str(tmp_path / "user")) # keep a real ~/.local/bin/npx out of the picture
-
- token = set_hermes_home_override(profile_home)
- try:
- with patch("tools.mcp_tool_config.shutil.which", return_value=None):
- command, _env = _resolve_stdio_command("npx", {"PATH": "/usr/bin"})
- finally:
- reset_hermes_home_override(token)
- assert command == str(npx_path)
-
-
-def test_resolve_stdio_command_falls_back_to_usr_local_bin():
- """When ``npx`` isn't on the filtered PATH and isn't under ``$HERMES_HOME/node/bin``
- or ``~/.local/bin``, the resolver should still locate it at ``/usr/local/bin/npx``.
-
- This is the canonical install location for Node on Linux from-source builds,
- the upstream ``node:bookworm-slim`` image (which the Hermes Docker image
- copies ``node + npm + corepack`` from since #4977), and macOS Homebrew on
- Intel. Without this candidate, MCP servers run with an ``env.PATH`` that
- omits ``/usr/local/bin`` (common when users hand-author PATH for sandboxing)
- fail with ENOENT at ``execvp``.
- """
- target = os.path.join(os.sep, "usr", "local", "bin", "npx")
-
- # Pretend ONLY the /usr/local/bin/npx candidate exists and is executable —
- # the other candidates ($HERMES_HOME/node/bin/npx and ~/.local/bin/npx)
- # should fail isfile() and the resolver must fall through to /usr/local/bin.
- def _fake_isfile(path):
- return path == target
-
- def _fake_access(path, _mode):
- return path == target
-
- with patch("tools.mcp_tool_config.shutil.which", return_value=None), \
- patch("tools.mcp_tool.os.path.isfile", side_effect=_fake_isfile), \
- patch("tools.mcp_tool.os.access", side_effect=_fake_access):
- command, env = _resolve_stdio_command("npx", {"PATH": "/opt/data/bin:/usr/bin:/bin"})
-
- assert command == target
- # /usr/local/bin must be prepended so npx's shebang (`/usr/bin/env node`)
- # can find node in the same directory.
- assert env["PATH"].split(os.pathsep)[0] == os.path.dirname(target)
-
-
-# ---------------------------------------------------------------------------
-# #37589: Desktop/launchd processes inherit a minimal PATH on macOS that does
-# not include ~/.local/bin, /opt/homebrew/bin, or /usr/local/bin. The resolver
-# must locate bare uv/uvx (the dominant Python MCP-server runtime) under those
-# locations instead of failing with ENOENT at execvp.
-# ---------------------------------------------------------------------------
-
-
-def test_resolve_stdio_command_finds_uvx_in_user_local_bin(tmp_path, monkeypatch):
- """uv's official installer drops uv/uvx at ``~/.local/bin/uvx`` on macOS and
- Linux. The resolver must pick it up when the GUI PATH doesn't include that
- directory (#37589)."""
- local_bin = tmp_path / ".local" / "bin"
- local_bin.mkdir(parents=True)
- uvx_path = local_bin / "uvx"
- uvx_path.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
- uvx_path.chmod(0o755)
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
- monkeypatch.setenv("HOME", str(tmp_path))
-
- with patch("tools.mcp_tool_config.shutil.which", return_value=None):
- command, env = _resolve_stdio_command("uvx", {"PATH": "/usr/bin:/bin:/usr/sbin:/sbin"})
-
- assert command == str(uvx_path)
- # The resolver prepended the chosen bin so uvx's sibling `uv` and its
- # shebang-resolved children resolve in the same directory.
- assert env["PATH"].split(os.pathsep)[0] == str(local_bin)
-
-
-def test_resolve_stdio_command_uv_fallback_order(tmp_path, monkeypatch):
- """Bare uv/uvx probe the well-known install dirs in uv's install order:
- managed ``<HERMES_HOME>/bin`` first, then ``~/.local/bin``, then Homebrew
- (Apple Silicon, then Intel/from-source)."""
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
- monkeypatch.setenv("HOME", str(tmp_path / "user"))
- monkeypatch.setattr("tools.mcp_tool_config.os.path.expanduser", lambda p: p.replace("~", str(tmp_path / "user")) if p.startswith("~") else p)
-
- candidates = [
- os.path.join(str(tmp_path / "hermes"), "bin", "uvx"),
- os.path.join(str(tmp_path / "user"), ".local", "bin", "uvx"),
- os.path.join(os.sep, "opt", "homebrew", "bin", "uvx"),
- os.path.join(os.sep, "usr", "local", "bin", "uvx"),
- ]
- seen = []
-
- def _fake_access(path, mode):
- assert mode == os.X_OK
- seen.append(path)
- return path == candidates[-1] # only /usr/local/bin exists
-
- with patch("tools.mcp_tool_config.shutil.which", return_value=None), \
- patch("tools.mcp_tool_config.os.path.isfile", return_value=True), \
- patch("tools.mcp_tool_config.os.access", side_effect=_fake_access):
- command, _env = _resolve_stdio_command("uvx", {"PATH": "/usr/bin"})
-
- assert seen == candidates # every dir probed, in install order
- assert command == candidates[-1]
-
-
-def test_resolve_stdio_command_uvx_unchanged_when_already_on_path():
- """A shutil.which hit still takes precedence — don't double-resolve a working
- bare command on the child's own PATH into something else."""
- resolved_path = "/some/custom/bin/uvx"
- with patch("tools.mcp_tool_config.shutil.which", return_value=resolved_path):
- command, _env = _resolve_stdio_command("uvx", {"PATH": "/usr/bin"})
-
- assert command == resolved_path
-
-
@pytest.mark.platforms("posix")
def test_resolve_stdio_command_keeps_the_child_path_order(tmp_path):
"""A command found later on the child's PATH must not pull its directory ahead of
@@ -213,18 +57,12 @@ def test_resolve_stdio_command_skips_unknown_commands():
def test_resolve_stdio_command_absent_path_is_a_miss(tmp_path, monkeypatch):
"""A server env without PATH must not resolve commands against the PARENT's PATH:
the child would be spawned without it and the lookup would pass on an env the
- child never sees. Bare ``node`` still reaches the explicit well-known dirs."""
+ child never sees."""
parent_bin = tmp_path / "parent-bin"
parent_bin.mkdir()
server_tool = parent_bin / "some-mcp-server"
server_tool.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
server_tool.chmod(0o755)
- node_tool = tmp_path / "node" / "bin" / "node"
- node_tool.parent.mkdir(parents=True)
- node_tool.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
- node_tool.chmod(0o755)
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- # the parent PATH contains BOTH names: an ambient hit would resolve either
monkeypatch.setenv("PATH", str(parent_bin))
command, _env = _resolve_stdio_command("some-mcp-server", {"OTHER": "1"})
@@ -232,10 +70,6 @@ def test_resolve_stdio_command_absent_path_is_a_miss(tmp_path, monkeypatch):
# absent child PATH: honest miss, not an ambient hit
assert command == "some-mcp-server"
- with patch.dict("os.environ", {"PATH": str(parent_bin)}):
- command, _env = _resolve_stdio_command("node", {"OTHER": "1"})
- assert command == str(node_tool) # the explicit Node fallback dirs stay reachable
-
def test_resolve_stdio_command_empty_path_is_a_miss(monkeypatch, tmp_path):
"""An explicitly empty child PATH keeps its cwd-only meaning (never the parent's PATH):
@@ -321,6 +155,7 @@ def test_run_stdio_malware_check_does_not_block_event_loop():
async def _test():
with patch("tools.osv_check.check_package_for_malware", side_effect=slow_check), \
+ patch("tools.mcp_tool_config._managed_launcher", return_value=None), \
patch("tools.mcp_tool.StdioServerParameters"), \
patch("tools.mcp_tool.stdio_client", return_value=mock_stdio_cm), \
patch("tools.mcp_tool.ClientSession", return_value=mock_session_cm):
@@ -349,6 +184,7 @@ def test_run_stdio_malware_check_times_out_fail_open():
async def _test():
with patch("tools.osv_check.check_package_for_malware", side_effect=hung_check), \
patch("tools.mcp_tool._OSV_MALWARE_CHECK_TIMEOUT_S", 0.2), \
+ patch("tools.mcp_tool_config._managed_launcher", return_value=None), \
patch("tools.mcp_tool.StdioServerParameters"), \
patch("tools.mcp_tool.stdio_client", return_value=mock_stdio_cm), \
patch("tools.mcp_tool.ClientSession", return_value=mock_session_cm):
@@ -361,3 +197,51 @@ def test_run_stdio_malware_check_times_out_fail_open():
assert elapsed < 1.0, f"startup did not fail-open promptly ({elapsed:.1f}s)"
asyncio.run(_test())
+
+
+def _toolchain_bin(root, *names):
+ root.mkdir(parents=True)
+ for name in names:
+ for spelling in (name, name + ".cmd"):
+ launcher = root / spelling
+ launcher.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
+ launcher.chmod(0o755)
+ return root
+
+
+def _pm_ships(monkeypatch, *, node_dirs=(), uv=None):
+ import hermes_constants
+ import pm
+
+ monkeypatch.setattr(pm, "ensure", lambda name, **kw: None)
+ monkeypatch.setattr(hermes_constants, "with_hermes_node_path",
+ lambda env: {**env, "PATH": os.pathsep.join(map(str, node_dirs))})
+ monkeypatch.setattr(pm, "uv_launcher", lambda name: uv.with_name(name) if uv else None)
+
+
+def test_bare_node_launchers_resolve_pm_node_ahead_of_the_users(tmp_path, monkeypatch):
+ """The packaged-toolchain rule: a bare ``npx`` runs Hermes's PM npx, with PM's npm and node
+ dirs first on the child PATH (npx's ``env node``), even when the user's Node sorts first."""
+ user_bin = _toolchain_bin(tmp_path / "user-node", "npx", "node")
+ npm_bin = _toolchain_bin(tmp_path / "store" / "npm" / "bin", "npx", "npm")
+ node_bin = _toolchain_bin(tmp_path / "store" / "node" / "bin", "node")
+ _pm_ships(monkeypatch, node_dirs=(npm_bin, node_bin))
+
+ command, env = _resolve_stdio_command("npx", {"PATH": os.pathsep.join([str(user_bin), "/usr/bin"])})
+
+ assert os.path.dirname(command) == str(npm_bin)
+ assert env["PATH"].split(os.pathsep) == [str(npm_bin), str(node_bin), str(user_bin), "/usr/bin"]
+
+
+def test_bare_uvx_resolves_pm_uv_and_an_absolute_command_stays_the_users(tmp_path, monkeypatch):
+ user_bin = _toolchain_bin(tmp_path / "user" / ".local" / "bin", "uvx")
+ uv_dir = _toolchain_bin(tmp_path / "store" / "uv-0.1", "uv", "uvx")
+ _pm_ships(monkeypatch, uv=uv_dir / "uv")
+
+ command, env = _resolve_stdio_command("uvx", {"PATH": str(user_bin)})
+ assert os.path.dirname(command) == str(uv_dir)
+ assert env["PATH"].split(os.pathsep)[0] == str(uv_dir)
+
+ explicit = str(user_bin / "uvx")
+ command, _env = _resolve_stdio_command(explicit, {"PATH": "/usr/bin"})
+ assert command == explicit
diff --git a/tools/file_operations_lint.py b/tools/file_operations_lint.py
index 816254c7e14..a183b29a344 100644
--- a/tools/file_operations_lint.py
+++ b/tools/file_operations_lint.py
@@ -10,7 +10,7 @@ import os
import tomllib
from typing import Callable, Dict, Optional
-from tools.file_operations_common import LintResult
+from tools.file_operations_common import ExecuteResult, LintResult
# Shell linters by extension (external toolchain). ``.tsx`` is deliberately absent:
# it hits the "No linter" skip and LSP covers it when enabled.
@@ -22,6 +22,11 @@ LINTERS = {
'.rs': 'rustfmt --check {file} 2>&1',
}
+# Node linters Hermes runs on the host (local backend) under its PM-managed Node,
+# never the user's: the terminal PATH puts the user's dirs first, and ``npx tsc``
+# re-execs ``env node`` through that PATH.
+_MANAGED_NODE_LINTERS = {'.js': ('node', '--check'), '.ts': ('npx', 'tsc', '--noEmit')}
+
# Per-file shell linters that flood phantom errors on real projects (single-file
# ``tsc`` ignores tsconfig, ``go vet`` fails outside a module, ``rustfmt --check``
# is style-only): skipped when an LSP server claims the file. py_compile /
@@ -158,12 +163,18 @@ class LintMixin:
))
if ext in _SHELL_LINTER_LSP_REDUNDANT and self._lsp_will_handle(path):
return LintResult(skipped=True, message=f"LSP server handles {ext} — shell linter skipped")
- linter_cmd = LINTERS[ext]
- base_cmd = linter_cmd.split()[0]
- if not self._has_command(base_cmd):
- return LintResult(skipped=True, message=f"{base_cmd} not available")
- # Native Windows binaries need C:/... not MSYS /c/... (→ phantom ENOENT).
- result = self._exec(linter_cmd.replace("{file}", self._escape_native_tool_arg(path)), timeout=30)
+ if ext in _MANAGED_NODE_LINTERS and self._lsp_local_only():
+ base_cmd = _MANAGED_NODE_LINTERS[ext][0]
+ result = self._run_managed_node_linter(ext, path)
+ if result is None:
+ return LintResult(skipped=True, message=f"{base_cmd} not available (Hermes-managed Node not installed)")
+ else:
+ linter_cmd = LINTERS[ext]
+ base_cmd = linter_cmd.split()[0]
+ if not self._has_command(base_cmd):
+ return LintResult(skipped=True, message=f"{base_cmd} not available")
+ # Native Windows binaries need C:/... not MSYS /c/... (→ phantom ENOENT).
+ result = self._exec(linter_cmd.replace("{file}", self._escape_native_tool_arg(path)), timeout=30)
if result.exit_code != 0 and _looks_like_linter_unusable(base_cmd, result.stdout):
from tools.ansi_strip import strip_ansi
cleaned = strip_ansi(result.stdout).strip()
@@ -172,6 +183,31 @@ class LintMixin:
return LintResult(skipped=True, message=f"{base_cmd} not usable: {first_line[:200]}")
return LintResult(success=result.exit_code == 0, output=result.stdout.strip())
+ def _run_managed_node_linter(self, ext: str, path: str) -> Optional[ExecuteResult]:
+ """Run the ``ext`` Node linter on the host under PM's Node; None when PM has none."""
+ import shutil
+ import subprocess
+
+ from hermes_cli._subprocess_compat import windows_hide_flags
+ from hermes_constants import with_hermes_node_path
+ from tools.environments.local import _IS_WINDOWS, _msys_to_windows_path, hermes_subprocess_env
+
+ tool, *args = _MANAGED_NODE_LINTERS[ext]
+ executable = shutil.which(tool, path=with_hermes_node_path({"PATH": ""})["PATH"])
+ if executable is None:
+ return None
+ cwd = getattr(self.env, "cwd", None) or self.cwd
+ if _IS_WINDOWS:
+ path, cwd = _msys_to_windows_path(path), cwd and _msys_to_windows_path(cwd)
+ try:
+ proc = subprocess.run(
+ [executable, *args, path], cwd=cwd or None, env=with_hermes_node_path(hermes_subprocess_env()),
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+ text=True, encoding="utf-8", errors="replace", timeout=30, creationflags=windows_hide_flags())
+ except subprocess.TimeoutExpired:
+ return ExecuteResult(stdout=f"{tool} timed out after 30s", exit_code=124)
+ return ExecuteResult(stdout=proc.stdout or "", exit_code=proc.returncode)
+
def _check_lint_delta(self, path: str, pre_content: Optional[str],
post_content: Optional[str] = None) -> LintResult:
"""Post-write lint; when it fails and ``pre_content`` is known, report only
diff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.py
index d59d1be9f9e..33330e8510b 100644
--- a/tools/mcp_tool_config.py
+++ b/tools/mcp_tool_config.py
@@ -196,55 +196,55 @@ def _which_with_config_pathext(command: str, path_arg, env: dict):
return None
-def _launcher_fallback(command: str, *, windows: Optional[bool] = None) -> str:
- """Well-known install locations for bare launcher commands; *command* unchanged when none exists.
-
- One resolver for two launcher families. ``npx``/``npm``/``node``: the managed tree comes from
- ``iter_hermes_node_dirs`` (Windows unpacks into ``<home>\\node``, POSIX into ``<home>/node/bin``)
- under the active profile's ``get_hermes_home()``; on Windows the real files are
- ``npx.cmd``/``node.exe`` (``windows`` injectable, as for ``_npx_bin_candidates``).
- ``uv``/``uvx``: GUI launches (the Electron desktop app, macOS LaunchAgents) inherit the bare
- ``/usr/bin:/bin:/usr/sbin:/sbin`` PATH, which carries none of uv's install locations, so a bare
- ``command: uvx`` MCP server fails with ENOENT at ``execvp`` from Desktop even though it works
- from an interactive terminal (#37589). The directory table lives in
- ``hermes_platform.resolver.known_dirs.uv_tool_dirs`` (probed in the order uv's own docs install
- it: the per-user installer first, then Homebrew); the Hermes-managed ``<home>/bin`` is probed
- before it."""
- from hermes_constants import get_hermes_home
- from hermes_platform.resolver.known_dirs import uv_tool_dirs
- home = os.path.expanduser("~")
- if command in {"uv", "uvx"}:
- # expanduser: the table carries the ``~`` form so both this walk and
- # locate_command's expandvars+expanduser agree on one spelling.
- directories = [os.path.join(str(get_hermes_home()), "bin"),
- *(os.path.expanduser(d) for d in uv_tool_dirs())]
- else:
- from hermes_constants import iter_hermes_node_dirs
- # /usr/local/bin: canonical Node location (from-source Linux, Hermes Docker image, Intel
- # Homebrew), needed when a hand-authored env.PATH omits it — npx's shebang re-execs
- # /usr/bin/env node.
- directories = [*map(str, iter_hermes_node_dirs(get_hermes_home())),
- os.path.join(home, ".local", "bin"), os.path.join(os.sep, "usr", "local", "bin")]
- candidates = (c for d in directories for c in _npx_bin_candidates(d, command, windows=windows))
- return next((c for c in candidates if os.path.isfile(c) and os.access(c, os.X_OK)), command)
+# Bare MCP launchers Hermes ships through PM, keyed to the package that provides them.
+_MANAGED_LAUNCHERS = {"npx": "npm", "npm": "npm", "node": "npm", "uv": "uv", "uvx": "uv"}
+
+
+def _managed_launcher(command: str) -> Optional[tuple[str, list[str]]]:
+ """PM's executable for a bare launcher name and the toolchain dirs its children need first on
+ PATH (npx's ``env node``, uvx's sibling uv). Never the user's copy: a missing managed tool is
+ provisioned through PM, which raises naming the remedy when it may not. None only when PM
+ ships no build for this platform (Termux), where the platform's own copy IS the toolchain."""
+ import pm
+ package = _MANAGED_LAUNCHERS[command]
+ if pm.get_package(package).missing_reason(pm.current_target()) is not None:
+ return None
+ pm.ensure(package)
+ if package == "uv":
+ launcher = pm.uv_launcher(command)
+ dirs = [str(launcher.parent)] if launcher is not None else []
+ else:
+ from hermes_constants import with_hermes_node_path
-# Historical name (tests and external callers import _node_fallback).
-_node_fallback = _launcher_fallback
+ dirs = [d for d in with_hermes_node_path({"PATH": ""})["PATH"].split(os.pathsep) if d]
+ executable = shutil.which(command, path=os.pathsep.join(dirs)) if dirs else None
+ if executable is None:
+ raise RuntimeError(f"Hermes-managed {command} is not installed; run `hermes pm install {package}`")
+ return executable, dirs
def _resolve_stdio_command(command: str, env: dict) -> tuple[str, dict]:
"""Resolve a stdio command against the exact subprocess env (bare launchers under a filtered PATH).
- A ``PATH`` lookup only runs when the child env actually carries one: ``shutil.which`` with
+ Bare ``npx``/``npm``/``node``/``uv``/``uvx`` resolve to Hermes's PM-managed copies with their
+ toolchain dirs first on the child PATH, never the user's (an absolute ``command:`` stays the
+ user's choice). Anything else resolves on the child env's PATH only: ``shutil.which`` with
``path=None`` silently falls back to the PARENT's ``os.environ["PATH"]``, letting a command
"resolve" against an env the child will never be spawned with. An absent child PATH is a
miss; an explicitly empty one keeps its cwd-only meaning (same distinction the child's
- ``execvp`` will see). Bare ``npx``/``npm``/``node``/``uv``/``uvx`` still fall through to
- their explicit well-known install directories, everything else stays as-written for an
- honest spawn failure."""
+ ``execvp`` will see); a miss stays as-written for an honest spawn failure."""
resolved_command = os.path.expanduser(str(command).strip())
resolved_env = dict(env or {})
+ launcher = re.sub(r"\.(cmd|exe)$", "", resolved_command, flags=re.IGNORECASE) # Windows spellings
+ managed = _managed_launcher(launcher) if launcher in _MANAGED_LAUNCHERS else None
+ if managed is not None:
+ resolved_command, dirs = managed
+ # Moved to the front even when already on PATH behind a user's copy.
+ keys = {os.path.normcase(d) for d in dirs}
+ rest = [p for p in resolved_env.get("PATH", "").split(os.pathsep) if p and os.path.normcase(p) not in keys]
+ resolved_env["PATH"] = os.pathsep.join([*dirs, *rest])
+ return resolved_command, resolved_env
if os.sep not in resolved_command:
path_arg = resolved_env.get("PATH")
which_hit = shutil.which(resolved_command, path=path_arg) if path_arg is not None else None
@@ -252,8 +252,6 @@ def _resolve_stdio_command(command: str, env: dict) -> tuple[str, dict]:
which_hit = _which_with_config_pathext(resolved_command, path_arg, resolved_env)
if which_hit:
resolved_command = which_hit
- elif resolved_command in {"npx", "npm", "node", "uv", "uvx"}:
- resolved_command = _launcher_fallback(resolved_command)
command_dir = os.path.dirname(resolved_command)
if command_dir:
resolved_env = _prepend_path(resolved_env, command_dir)
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index bad2a42ba70..466f3becd40 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -218,14 +218,19 @@ _detached_ws_transport = _DropTransport()
def _prepend_tool_paths(env: dict[str, str]) -> dict[str, str]:
- """Prepend managed bin (first: managed-first policy for the Browser Use CLI), venv bin and
- ~/.local/bin to PATH so slash_worker children resolve Hermes-managed CLIs under the Desktop's minimal PATH."""
+ """Prepend managed bin (managed-first policy for the Browser Use CLI), venv bin and
+ ~/.local/bin to PATH so slash_worker children resolve Hermes-managed CLIs under the Desktop's minimal PATH.
+ The PM store dirs go in front of all of them: a user's node/uv in ~/.local/bin never wins."""
managed_bin = ""
with contextlib.suppress(Exception):
managed_bin = str(Path(get_hermes_home()) / "bin")
venv_bin = str(Path(sys.executable).parent) # <venv>/bin (POSIX) or <venv>/Scripts (Windows)
parts = [p for p in (managed_bin, venv_bin, str(Path.home() / ".local" / "bin"), env.get("PATH") or "") if p]
env["PATH"] = os.pathsep.join(parts)
+ with contextlib.suppress(Exception):
+ import pm
+
+ env["PATH"] = pm.store_first_path(env["PATH"])
return env