The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(windows): packaged-npx install failures degrade to plain npx; payload venv must be real
ethernet84e2250b1065
diff --git a/tests/tools/test_local_env_blocklist.py b/tests/tools/test_local_env_blocklist.pyindex 8211fc249cf..85406883727 100644--- a/tests/tools/test_local_env_blocklist.py+++ b/tests/tools/test_local_env_blocklist.py@@ -674,6 +674,24 @@ def test_sealed_payload_venv_is_runtime_provenance_without_facts(tmp_path, monkeassert result["PYTHONPATH"] == str(user_site)[email protected]("child_env")[email protected]("shipped", ["phantom", "escapes-root"])+def test_payload_venv_that_is_not_real_is_not_provenance(tmp_path, monkeypatch, shipped):+ """A stray manifest.json can name a venv that does not exist, or one that escapes its root:+ neither may be trusted (a phantom path would shadow the user's own venv) or raise."""+ def payload_venv(repo):+ if shipped == "escapes-root":+ raise RuntimeError("payload environment escapes its root")+ return tmp_path / "no-such-venv"++ monkeypatch.setattr("pm.environments.install_state_dir", lambda repo: tmp_path / "payload/state")+ monkeypatch.setattr("pm.environments.payload_venv", payload_venv)+ monkeypatch.setattr(local, "_hermes_repo_root_aliases", ())+ from tools.environments.local_pythonpath import _validated_runtime_venv++ assert _validated_runtime_venv({}) is None++@pytest.mark.parametrize("existing,expected", [(["/usr/bin", "/bin"], ["/opt/hermes/bin", "/usr/bin", "/bin"]),(["/usr/bin", "/opt/hermes/bin"], ["/usr/bin", "/opt/hermes/bin"]),diff --git a/tests/tools/test_mcp_tool_issue_948.py b/tests/tools/test_mcp_tool_issue_948.pyindex a5b84d1d4fa..3bee64afa6e 100644--- a/tests/tools/test_mcp_tool_issue_948.py+++ b/tests/tools/test_mcp_tool_issue_948.py@@ -1,6 +1,8 @@import asyncioimport os+import subprocessimport sys+from pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patch@@ -233,41 +235,110 @@ def test_bare_node_launchers_resolve_pm_node_ahead_of_the_users(tmp_path, monkeyassert env["PATH"].split(os.pathsep) == [str(npm_bin), str(node_bin), str(user_bin), "/usr/bin"]-def test_packaged_npx_runs_the_package_bin_on_the_packaged_node(tmp_path, monkeypatch):- """With only the payload's Node, npx's cmd.exe hop always dies, so Hermes installs the- package (scripts off) and runs its bin script on the packaged node instead."""+def _sealed_npx(tmp_path, monkeypatch):+ """A sealed payload's npm + node dirs, with `node` a real file for `which` on every OS."""import pm.user_facing- from tools.mcp_tool_config import _packaged_npx_entrynpm_bin = _toolchain_bin(tmp_path / "store" / "npm", "npx")(npm_bin / "node_modules" / "npm" / "bin").mkdir(parents=True)(npm_bin / "node_modules" / "npm" / "bin" / "npm-cli.js").write_text("", encoding="utf-8")node_bin = tmp_path / "store" / "node"node_bin.mkdir(parents=True)- calls = tmp_path / "npm-calls.txt"- node = node_bin / "node"- # Stands in for `node npm-cli.js install --prefix <p> ... <spec>`: records argv, lays out the package.- node.write_text(- "#!/bin/sh\n"- f'echo "$@" >> "{calls}"\n'- 'pkg="$4/node_modules/@scope/srv"; mkdir -p "$pkg"\n'- "echo '{\"bin\": {\"srv\": \"dist/index.js\"}}' > \"$pkg/package.json\"\n",- encoding="utf-8")- node.chmod(0o755)+ node = _bare_exe(node_bin, "node")monkeypatch.setattr(pm.user_facing, "applies", lambda: True)sealed = {"node": [str(node_bin)], "npm": [str(npm_bin)]}monkeypatch.setattr(pm.user_facing, "_sealed_dirs", lambda name: sealed.get(name, []))+ return npm_bin, node+++def test_packaged_npx_runs_the_package_bin_on_the_packaged_node(tmp_path, monkeypatch):+ """With only the payload's Node, npx's cmd.exe hop always dies, so Hermes installs the+ package (scripts off) and runs its bin script on the packaged node instead."""+ import subprocess++ from tools.mcp_tool_config import _packaged_npx_entry++ npm_bin, node = _sealed_npx(tmp_path, monkeypatch)+ calls = []++ def fake_install(argv, **kwargs):+ # Stands in for `node npm-cli.js install --prefix <p> ... <spec>`: records argv, lays out the package.+ calls.append(argv)+ pkg = Path(argv[argv.index("--prefix") + 1]) / "node_modules" / "@scope" / "srv"+ pkg.mkdir(parents=True, exist_ok=True)+ (pkg / "package.json").write_text('{"bin": {"srv": "dist/index.js"}}', encoding="utf-8")+ return subprocess.CompletedProcess(argv, 0, "", "")++ monkeypatch.setattr(subprocess, "run", fake_install)args = ["-y", "@scope/srv", "--port", "1"]command, argv = _packaged_npx_entry(str(npm_bin / "npx.cmd"), args)- assert command == str(node)+ # which() reports the PATHEXT spelling (node.EXE), so compare case-normalised.+ assert os.path.normcase(command) == os.path.normcase(str(node))assert argv[1:] == ["--port", "1"] and argv[0].endswith(os.path.join("@scope", "srv", "dist", "index.js"))- assert "--ignore-scripts" in calls.read_text(encoding="utf-8-sig").split()+ assert "--ignore-scripts" in calls[0]+ assert calls[0][0] == command+ # Like npx: an unpinned spec re-resolves on every start, an exact version is reused.assert _packaged_npx_entry(str(npm_bin / "npx.cmd"), args) == (command, argv)- assert len(calls.read_text(encoding="utf-8-sig").splitlines()) == 1+ assert len(calls) == 2+ pinned = ["-y", "@scope/[email protected]"]+ assert _packaged_npx_entry(str(npm_bin / "npx.cmd"), pinned) == _packaged_npx_entry(str(npm_bin / "npx.cmd"), pinned)+ assert len(calls) == 3+ # npm installs a git/URL/path spec under a name the spec does not show: plain npx, no install.+ assert _packaged_npx_entry(str(npm_bin / "npx.cmd"), ["-y", "github:u/r"]) is None+ assert len(calls) == 3assert _packaged_npx_entry(str(tmp_path / "user-node" / "npx.cmd"), args) is None[email protected]("failure", [+ subprocess.TimeoutExpired("node", 600),+ PermissionError(13, "Access is denied"),+ subprocess.CompletedProcess([], 1, "", "npm ERR!"),+], ids=["timeout", "oserror", "nonzero-exit"])+def test_packaged_npx_install_failure_degrades_to_plain_npx(tmp_path, monkeypatch, failure):+ """A hung, unstartable or failing install must return None (plain npx, an honest failure),+ never raise into the MCP connect loop where it would burn the server's retry budget."""+ from tools.mcp_tool_config import _packaged_npx_entry++ npm_bin, _node = _sealed_npx(tmp_path, monkeypatch)++ def fail(argv, **kwargs):+ if isinstance(failure, BaseException):+ raise failure+ return failure++ monkeypatch.setattr(subprocess, "run", fail)+ assert _packaged_npx_entry(str(npm_bin / "npx.cmd"), ["-y", "@scope/srv"]) is None++ # A refresh that fails (offline) keeps the package an earlier start installed.+ from hermes_constants import get_hermes_home+ import hashlib+ pkg = (Path(get_hermes_home()) / "cache" / "mcp-npx" / hashlib.sha256(b"@scope/srv").hexdigest()[:16]+ / "node_modules" / "@scope" / "srv")+ pkg.mkdir(parents=True)+ (pkg / "package.json").write_text('{"bin": "cli.js"}', encoding="utf-8")+ assert _packaged_npx_entry(str(npm_bin / "npx.cmd"), ["-y", "@scope/srv"])[1] == [str(pkg / "cli.js")]+++def test_outside_package_swaps_the_sealed_dirs_for_pm_copies(tmp_path, monkeypatch):+ """A bare npx/npm/node on a sealed payload resolves in PM's writable copy (npm starts each+ bin through cmd.exe, which cannot start the packaged node); outside a payload it is untouched."""+ import pm.user_facing+ from tools.mcp_tool_config import _outside_package++ sealed_dir = str(tmp_path / "sealed")+ copy = _toolchain_bin(tmp_path / "copy", "npx")+ managed = str(tmp_path / "sealed" / "npx")++ monkeypatch.setattr(pm.user_facing, "copies", lambda dirs: [str(copy)])+ launcher, dirs = _outside_package("npx", managed, [sealed_dir])+ assert dirs == [str(copy)]+ assert os.path.dirname(launcher) == str(copy)++ monkeypatch.setattr(pm.user_facing, "copies", lambda dirs: list(dirs))+ assert _outside_package("npx", managed, [sealed_dir]) == (managed, [sealed_dir])++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")diff --git a/tools/environments/local_pythonpath.py b/tools/environments/local_pythonpath.pyindex 5c2c1c08cfa..15f7c498a25 100644--- a/tools/environments/local_pythonpath.py+++ b/tools/environments/local_pythonpath.py@@ -81,8 +81,13 @@ def _validated_runtime_venv(env: dict) -> Path | None:root = Path(__file__).resolve().parents[2]if runtime_facts_path(root).is_file():return selected_venv(root)- shipped = payload_venv(root)- if shipped is not None:+ try:+ shipped = payload_venv(root)+ except (RuntimeError, OSError): # a manifest that escapes its root reads as "not a payload"+ shipped = None+ # Require the real venv, as the VIRTUAL_ENV branch does: a stray manifest.json beside a+ # checkout must not hand back a phantom path that shadows the user's own venv.+ if shipped is not None and (shipped / "pyvenv.cfg").is_file():return shippedcandidate = Path(env.get("VIRTUAL_ENV") or "")if not env.get("VIRTUAL_ENV") or not any(diff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.pyindex cfbb9240895..1ce25c1825b 100644--- a/tools/mcp_tool_config.py+++ b/tools/mcp_tool_config.py@@ -272,6 +272,8 @@ def _outside_package(launcher: str, managed: str, dirs: list[str]) -> tuple[str,moved = copies(dirs)if moved == dirs:return managed, dirs+ # Plain which(): Hermes's own copy dirs hold one real node.exe/npx.cmd, so the parent's+ # PATHEXT is the right question (unlike a user server's config env, see _which_with_config_pathext).return shutil.which(launcher, path=os.pathsep.join(moved)) or managed, moved@@ -470,7 +472,12 @@ def _packaged_npx_entry(command: str, args: list) -> Optional[tuple]:a copy that PM may make. The payload's Python CAN start the packaged ``node.exe``, so thepackage is installed with npm's own script and the bin's script runs on that node.Install scripts stay off, because npm runs them through cmd.exe too. None keeps plain- npx (an honest failure) for any other argv shape, a failed install, or an unclear bin.+ npx (an honest failure) for any other argv shape, a non-registry spec (git, URL, path:+ npm installs those under a name the spec does not show), a failed install, or an+ unclear bin.++ Like npx, only an exact version is reused as installed. Any other spec re-resolves on+ each start and keeps the previous install when npm cannot run (offline)."""from pm.user_facing import _sealed_dirs, applies@@ -488,27 +495,35 @@ def _packaged_npx_entry(command: str, args: list) -> Optional[tuple]:spec = str(rest[0]) if rest else ""if not spec or spec.startswith("-") or any(str(a) in ("-y", "--yes") for a in rest[1:]):return None+ if ":" in spec or spec.startswith((".", "/", "\\", "~")) or ("/" in spec and not spec.startswith("@")):+ return Nonescope, _, bare = spec.rpartition("/") if spec.startswith("@") else ("", "", spec)- name = (f"{scope}/" if scope else "") + bare.split("@", 1)[0]+ base, _, version = bare.partition("@")+ name = (f"{scope}/" if scope else "") + basefrom hermes_constants import get_hermes_homeprefix = Path(get_hermes_home()) / "cache" / "mcp-npx" / hashlib.sha256(spec.encode()).hexdigest()[:16]manifest = prefix / "node_modules" / name / "package.json"- if not manifest.is_file():+ exact = re.fullmatch(r"\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?", version) is not None+ if not (exact and manifest.is_file()):install = [node, npm_cli, "install", "--prefix", str(prefix), "--no-save", "--ignore-scripts","--no-audit", "--no-fund", "--loglevel=error", spec]- result = subprocess.run(install, capture_output=True, text=True, encoding="utf-8", errors="replace",- stdin=subprocess.DEVNULL, timeout=600, check=False)+ try:+ result = subprocess.run(install, capture_output=True, text=True, encoding="utf-8", errors="replace",+ stdin=subprocess.DEVNULL, timeout=600, check=False)+ except (subprocess.SubprocessError, OSError) as exc: # hang, unwritable prefix, AV lock, node not startable+ result = subprocess.CompletedProcess(install, 1, "", str(exc))if result.returncode != 0 or not manifest.is_file():logger.warning("npm install of %s with the packaged node failed: %s", spec,(result.stderr or result.stdout).strip()[-500:])- return None+ if not manifest.is_file():+ return Nonetry:bin_field = (json.loads(manifest.read_text(encoding="utf-8-sig")) or {}).get("bin")except (OSError, ValueError):return Noneif isinstance(bin_field, dict):- bin_field = bin_field.get(bare.split("@", 1)[0]) or (+ bin_field = bin_field.get(base) or (next(iter(bin_field.values())) if len(bin_field) == 1 else None)if not isinstance(bin_field, str):return None