The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): harden subprocess Python runtime ownership
Xinyu Du6e9eeb54130e
diff --git a/tests/tools/test_local_env_blocklist.py b/tests/tools/test_local_env_blocklist.pyindex 0f081be9e3c..7fe7bf9d008 100644--- a/tests/tools/test_local_env_blocklist.py+++ b/tests/tools/test_local_env_blocklist.py@@ -23,6 +23,14 @@ from tools.environments.local import ()+def _running_venv_site_packages() -> Path:+ """Independently construct the host-native venv site-packages path."""+ if sys.platform == "win32":+ return Path(sys.prefix) / "Lib" / "site-packages"+ pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"+ return Path(sys.prefix) / "lib" / pyver / "site-packages"++def _make_fake_popen(captured: dict):"""Return a fake Popen constructor that records the env kwarg."""def fake_popen(cmd, **kwargs):@@ -331,15 +339,11 @@ class TestPythonpathSelectiveStrip:def test_hermes_venv_site_packages_stripped(self):"""A site-packages entry under the Hermes venv is removed."""from tools.environments.local import _strip_hermes_owned_pythonpath- import sys# Construct a path that looks like the Hermes venv site-packages.# Use the running interpreter's version so it hits the Hermes-venv# ownership check, not a user-path case.- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"- venv_sp = str(- __import__("pathlib").Path(sys.prefix) / "lib" / pyver / "site-packages"- )+ venv_sp = str(_running_venv_site_packages())env = {"PYTHONPATH": os.pathsep.join([venv_sp, "/home/user/my-lib"]),}@@ -349,6 +353,18 @@ class TestPythonpathSelectiveStrip:assert venv_sp not in entriesassert "/home/user/my-lib" in entries+ def test_hermes_site_packages_descendant_preserved(self):+ """Only the exact producer entry is owned; descendants are user paths."""+ from tools.environments.local import _strip_hermes_owned_pythonpath++ venv_sp = _running_venv_site_packages()+ descendant = str(venv_sp / "some-user-path")+ env = {"PYTHONPATH": os.pathsep.join([descendant, "/home/user/my-lib"])}++ _strip_hermes_owned_pythonpath(env)++ assert env["PYTHONPATH"].split(os.pathsep) == [descendant, "/home/user/my-lib"]+def test_user_pythonpath_preserved(self):"""User PYTHONPATH entries pass through untouched."""from tools.environments.local import _strip_hermes_owned_pythonpath@@ -357,6 +373,17 @@ class TestPythonpathSelectiveStrip:_strip_hermes_owned_pythonpath(env)assert env.get("PYTHONPATH") == user_pp+ def test_nix_store_path_without_provenance_preserved(self):+ """Path shape alone cannot distinguish a Nix user path from Hermes."""+ from tools.environments.local import _strip_hermes_owned_pythonpath++ nix_path = "/nix/store/abc123-user-plugin/lib/python3.12/site-packages"+ env = {"PYTHONPATH": nix_path}++ _strip_hermes_owned_pythonpath(env)++ assert env["PYTHONPATH"] == nix_path+def test_other_version_site_packages_preserved(self):"""A user's pythonX.Y/site-packages entry is preserved even when itsversion differs from the Hermes backend interpreter.@@ -419,7 +446,7 @@ class TestPythonpathSelectiveStrip:On Windows, os.pathsep is ';'. We mock it so the test runscorrectly on POSIX CI. On a POSIX host a backslash path is a- single path component, so _is_path_under cannot identify it as+ single path component, so ``Path`` cannot identify it asHermes-owned — the critical invariant is that user Windows paths(including site-packages paths for another Python version) arenever destroyed. On a real Windows host, Path splits on@@ -454,14 +481,10 @@ class TestPythonpathSelectiveStrip:not split on backslashes, so this cannot be meaningfully simulatedon a POSIX host."""from tools.environments.local import _strip_hermes_owned_pythonpath- import sys- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"- venv_sp = str(- __import__("pathlib").Path(sys.prefix) / "Lib" / "site-packages"- )+ venv_sp = str(_running_venv_site_packages())# Windows form: C:\...\venv\Lib\site-packages (backslashes)- hermes_win = venv_sp.replace("\\", "\\\\").replace("/", "\\\\")+ hermes_win = venv_spuser_win = "D:\\\\user\\\\lib"env = {"PYTHONPATH": ";".join([hermes_win, user_win]),@@ -480,16 +503,39 @@ class TestPythonpathSelectiveStrip:# modifying the dict. The key stays as-is (empty string).assert env.get("PYTHONPATH") == ""+ def test_empty_component_preserved(self):+ """An empty component means cwd and must survive unchanged."""+ from tools.environments.local import _strip_hermes_owned_pythonpath++ user_pp = os.pathsep.join(["/foo", "", "/bar"])+ env = {"PYTHONPATH": user_pp}++ _strip_hermes_owned_pythonpath(env)++ assert env["PYTHONPATH"] == user_pp++ def test_raw_user_spelling_preserved(self):+ """The sanitizer does not trim, normalize, or deduplicate user entries."""+ from tools.environments.local import _strip_hermes_owned_pythonpath++ user_pp = os.pathsep.join([+ " /opt/user-lib ",+ "relative/../lib",+ "",+ "/opt/user-lib",+ "/opt/user-lib",+ ])+ env = {"PYTHONPATH": user_pp}++ _strip_hermes_owned_pythonpath(env)++ assert env["PYTHONPATH"] == user_pp+def test_mixed_ordering_user_and_hermes_preserves_user_order(self):- """Mixed user/Hermes/user entries: user entries survive in their- original relative order after Hermes-owned entries are removed."""+ """Mixed entries retain raw user order, including an empty component."""from tools.environments.local import _strip_hermes_owned_pythonpath- import sys- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"- venv_sp = str(- __import__("pathlib").Path(sys.prefix) / "lib" / pyver / "site-packages"- )+ venv_sp = str(_running_venv_site_packages())local_file = Path(__import__("tools.environments.local", fromlist=["__file__"]).__file__).resolve()@@ -498,26 +544,81 @@ class TestPythonpathSelectiveStrip:"PYTHONPATH": os.pathsep.join(["/first/user/lib",repo_root,- "/second/user/lib",+ "",venv_sp,- "/third/user/lib",+ "/second/user/lib",]),}_strip_hermes_owned_pythonpath(env)- pp = env.get("PYTHONPATH", "")- entries = pp.split(os.pathsep) if pp else []- assert entries == ["/first/user/lib", "/second/user/lib", "/third/user/lib"]+ assert env["PYTHONPATH"].split(os.pathsep) == [+ "/first/user/lib",+ "",+ "/second/user/lib",+ ]++ def test_base_python_sanitizer_uses_validated_separate_runtime_venv(self, tmp_path, monkeypatch):+ """A base interpreter strips the exact Windows runtime site-packages.++ This deliberately uses a synthetic Hermes venv separate from the test+ runner: sys.prefix represents base Python, while validated VIRTUAL_ENV+ identifies ``<repo>/venv`` as the Hermes runtime producer contract.+ """+ import tools.environments.local as local++ repo_root = tmp_path / "hermes-agent"+ runtime_venv = repo_root / "venv"+ runtime_sp = runtime_venv / "Lib" / "site-packages"+ runtime_sp.mkdir(parents=True)+ (runtime_venv / "pyvenv.cfg").write_text("version = 3.11\n", encoding="utf-8")+ base_prefix = tmp_path / "base-python"+ unrelated = "/custom/lib/python3.13/site-packages"++ monkeypatch.setattr(local, "_hermes_repo_root_aliases", (repo_root,))+ monkeypatch.setattr(local, "_in_venv", False)+ monkeypatch.setattr(local, "_hermes_site_packages", None)+ monkeypatch.setattr(local.sys, "prefix", str(base_prefix))+ monkeypatch.setattr(local.sys, "base_prefix", str(base_prefix))++ env = {+ "VIRTUAL_ENV": str(runtime_venv),+ "PYTHONPATH": os.pathsep.join([str(runtime_sp), unrelated]),+ }+ result = local._sanitize_subprocess_env(env)++ assert Path(local.sys.prefix) == base_prefix+ assert runtime_venv != Path(local.sys.prefix)+ assert result["PYTHONPATH"] == unrelated+ assert "VIRTUAL_ENV" not in result++ def test_unrelated_virtual_env_is_not_runtime_provenance(self, tmp_path, monkeypatch):+ """An arbitrary inherited VIRTUAL_ENV cannot claim PYTHONPATH ownership."""+ import tools.environments.local as local++ repo_root = tmp_path / "hermes-agent"+ repo_root.mkdir()+ unrelated_venv = tmp_path / "user-venv"+ unrelated_sp = unrelated_venv / "Lib" / "site-packages"+ unrelated_sp.mkdir(parents=True)+ (unrelated_venv / "pyvenv.cfg").write_text("version = 3.13\n", encoding="utf-8")++ monkeypatch.setattr(local, "_hermes_repo_root_aliases", (repo_root,))+ monkeypatch.setattr(local, "_in_venv", False)+ monkeypatch.setattr(local, "_hermes_site_packages", None)++ env = {+ "VIRTUAL_ENV": str(unrelated_venv),+ "PYTHONPATH": str(unrelated_sp),+ }+ local._strip_hermes_owned_pythonpath(env)++ assert env["PYTHONPATH"] == str(unrelated_sp)def test_duplicate_hermes_entries_all_stripped(self):"""Every duplicate Hermes-owned entry is removed; user duplicatesfollow the existing contract (no unrelated dedup)."""from tools.environments.local import _strip_hermes_owned_pythonpath- import sys- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"- venv_sp = str(- __import__("pathlib").Path(sys.prefix) / "lib" / pyver / "site-packages"- )+ venv_sp = str(_running_venv_site_packages())local_file = Path(__import__("tools.environments.local", fromlist=["__file__"]).__file__).resolve()@@ -546,12 +647,8 @@ class TestPythonpathSelectiveStrip:"""If all entries are Hermes-owned and stripped, PYTHONPATH key isremoved entirely."""from tools.environments.local import _strip_hermes_owned_pythonpath- import sys- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"- venv_sp = str(- __import__("pathlib").Path(sys.prefix) / "lib" / pyver / "site-packages"- )+ venv_sp = str(_running_venv_site_packages())env = {"PYTHONPATH": venv_sp}_strip_hermes_owned_pythonpath(env)@@ -560,12 +657,8 @@ class TestPythonpathSelectiveStrip:def test_make_run_env_strips_hermes_venv_pythonpath(self):"""_make_run_env strips Hermes venv site-packages from PYTHONPATH."""from tools.environments.local import _make_run_env- import sys- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"- venv_sp = str(- __import__("pathlib").Path(sys.prefix) / "lib" / pyver / "site-packages"- )+ venv_sp = str(_running_venv_site_packages())with patch.dict(os.environ, {"PATH": "/usr/bin:/bin","PYTHONPATH": os.pathsep.join([venv_sp, "/home/user/my-lib"]),@@ -579,12 +672,8 @@ class TestPythonpathSelectiveStrip:def test_sanitize_subprocess_env_strips_hermes_venv_pythonpath(self):"""_sanitize_subprocess_env strips Hermes venv site-packages."""from tools.environments.local import _sanitize_subprocess_env- import sys- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"- venv_sp = str(- __import__("pathlib").Path(sys.prefix) / "lib" / pyver / "site-packages"- )+ venv_sp = str(_running_venv_site_packages())base = {"PATH": "/usr/bin","HOME": "/home/user",@@ -599,12 +688,8 @@ class TestPythonpathSelectiveStrip:def test_hermes_subprocess_env_strips_hermes_venv_pythonpath(self):"""hermes_subprocess_env strips Hermes venv site-packages."""from tools.environments.local import hermes_subprocess_env- import sys- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"- venv_sp = str(- __import__("pathlib").Path(sys.prefix) / "lib" / pyver / "site-packages"- )+ venv_sp = str(_running_venv_site_packages())with patch.dict(os.environ, {"PATH": "/usr/bin:/bin","HOME": "/home/user",@@ -624,12 +709,8 @@ class TestPythonpathSelectiveStrip:"""from tools.code_execution_tool import _scrub_child_envfrom tools.environments.local import _strip_hermes_owned_pythonpath- import sys- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"- venv_sp = str(- __import__("pathlib").Path(sys.prefix) / "lib" / pyver / "site-packages"- )+ venv_sp = str(_running_venv_site_packages())other_sp = "/opt/other-venv/lib/python3.99/site-packages"source = {"PATH": "/usr/bin",@@ -679,7 +760,8 @@ class TestPythonpathSelectiveStrip:"""A direct child of the repo root (depth=1) is PRESERVED.Independent audit of every real launcher producer (Electron- ``electron-main.mjs``, ``gateway/run.py::_ensure_windows_gateway_venv_imports``,+ ``apps/desktop/electron/main.ts``,+ ``gateway/run.py::_ensure_windows_gateway_venv_imports``,``cron/scheduler.py::_windows_cron_python_invocation``,``tui_gateway/host_supervisor.py``) shows they all inject the exactrepo root and/or the venv site-packages — none injects@@ -702,47 +784,43 @@ class TestPythonpathSelectiveStrip:assert direct_child in entriesassert "/home/user/my-lib" in entries- def test_repo_root_junction_alias_stripped(self):- """A PYTHONPATH entry using the unresolved (HERMES_HOME/junction)- spelling of the repo root is stripped.-- On Windows the gateway launcher renders Hermes-owned paths under the- configured HERMES_HOME spelling, which may be a symlink/junction to- another drive (``_preserve_hermes_home_path`` in- ``hermes_cli/gateway_windows.py``). ``_hermes_repo_root`` is the- RESOLVED physical path, so the launcher's spelling differs lexically;- the alias set must still recognize it as Hermes-owned. This test- monkeypatches the aliases to a pair whose lexical forms differ, the- way a junction would, and verifies the launcher's spelling is- stripped while a nested user path under the same prefix is not.- """- from tools.environments.local import (- _strip_hermes_owned_pythonpath,- _hermes_repo_root_aliases,+ def test_configured_home_alias_matches_launcher_output(self, tmp_path, monkeypatch):+ """The real producer spelling is derived and consumed end to end."""+ import tools.environments.local as local+ from hermes_cli.gateway_windows import _preserve_hermes_home_path++ physical_home = tmp_path / "physical-home"+ physical_root = physical_home / "hermes-agent"+ physical_root.mkdir(parents=True)+ configured_home = tmp_path / "configured-home"+ configured_home.symlink_to(physical_home, target_is_directory=True)+ monkeypatch.setenv("HERMES_HOME", str(configured_home))++ launcher_entry = Path(_preserve_hermes_home_path(physical_root))+ aliases = local._build_hermes_repo_root_aliases(+ physical_root.resolve(),+ physical_root,+ configured_home,)- from pathlib import Path as _Path- resolved_root = _Path("/data/hermes/hermes-agent")- junction_root = _Path("/home/u/AppData/Local/hermes/hermes-agent")- with patch(- "tools.environments.local._hermes_repo_root_aliases",- (resolved_root, junction_root),- ):- # Launcher spelling (junction form) of the exact repo root.- env = {"PYTHONPATH": str(junction_root)}- _strip_hermes_owned_pythonpath(env)- assert "PYTHONPATH" not in env+ assert launcher_entry == configured_home / "hermes-agent"+ assert launcher_entry in aliases- # Nested user path under the same junction prefix survives.- env = {"PYTHONPATH": os.pathsep.join([- str(junction_root / "user-data"),+ monkeypatch.setattr(local, "_hermes_repo_root_aliases", aliases)+ nested_user_path = launcher_entry / "user-data"+ env = {+ "PYTHONPATH": os.pathsep.join([+ str(launcher_entry),+ str(nested_user_path),"/home/user/my-lib",- ])}- _strip_hermes_owned_pythonpath(env)- pp = env.get("PYTHONPATH", "")- entries = pp.split(os.pathsep) if pp else []- assert str(junction_root / "user-data") in entries- assert "/home/user/my-lib" in entries+ ])+ }+ local._strip_hermes_owned_pythonpath(env)++ assert env["PYTHONPATH"].split(os.pathsep) == [+ str(nested_user_path),+ "/home/user/my-lib",+ ]def test_deep_path_under_repo_root_preserved(self):"""A deeper path under the repo root (depth=2) is preserved.diff --git a/tools/environments/local.py b/tools/environments/local.pyindex 4ea5f53c388..017cc3e82a4 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -14,6 +14,7 @@ import timefrom collections.abc import Mappingfrom pathlib import Path+from hermes_constants import get_process_hermes_homefrom tools.environments.base import BaseEnvironment, _pipe_stdinfrom hermes_cli._subprocess_compat import windows_hide_flags@@ -516,11 +517,15 @@ def _sanitize_subprocess_env(base_env: dict | None, extra_env: dict | None = Non# spawn path (process_registry.spawn_local builds env via this function)._inject_session_context_env(sanitized)+ # Filter PYTHONPATH before removing VIRTUAL_ENV: legacy Windows launchers+ # can run the gateway under a base interpreter while VIRTUAL_ENV identifies+ # the separate Hermes runtime venv. The filter validates that relationship+ # against the repo layout before trusting it.+ _strip_hermes_owned_pythonpath(sanitized)+for _marker in _ACTIVE_VENV_MARKER_VARS:sanitized.pop(_marker, None)- _strip_hermes_owned_pythonpath(sanitized)-_apply_windows_msys_bash_env_defaults(sanitized)sanitized = _scrub_delegated_child_kanban_env(sanitized)@@ -646,12 +651,12 @@ def hermes_subprocess_env(*, inherit_credentials: bool = False) -> dict[str, strfrom hermes_constants import apply_subprocess_home_envapply_subprocess_home_env(env)+ _strip_hermes_owned_pythonpath(env)+# Active-venv markers must not clobber another project's environment.for _marker in _ACTIVE_VENV_MARKER_VARS:env.pop(_marker, None)- _strip_hermes_owned_pythonpath(env)-_apply_windows_msys_bash_env_defaults(env)# Cross-session leak guard, same as the terminal spawn paths: this helper@@ -1335,11 +1340,11 @@ def _make_run_env(env: dict) -> dict:# engaged so a sibling session's os.environ mirror can't leak in)._inject_session_context_env(run_env)+ _strip_hermes_owned_pythonpath(run_env)+for _marker in _ACTIVE_VENV_MARKER_VARS:run_env.pop(_marker, None)- _strip_hermes_owned_pythonpath(run_env)-_apply_windows_msys_bash_env_defaults(run_env)run_env = _scrub_delegated_child_kanban_env(run_env)@@ -1347,31 +1352,48 @@ def _make_run_env(env: dict) -> dict:return run_env-def _is_path_under(child: Path, parent: Path) -> bool:- """Return True if *child* is the same as or under *parent*.+def _same_path(left: Path, right: Path) -> bool:+ """Compare path spellings with host filesystem case semantics."""+ left_parts = [os.path.normcase(part) for part in left.parts]+ right_parts = [os.path.normcase(part) for part in right.parts]+ return left_parts == right_parts+++def _build_hermes_repo_root_aliases(+ resolved_root: Path,+ lexical_root: Path,+ configured_home: Path,+) -> tuple[Path, ...]:+ """Return exact repo-root spellings emitted by Hermes launchers.- Uses ``os.path.normcase`` so the comparison is case-insensitive on- Windows (NTFS is case-insensitive by default) and case-sensitive on- POSIX, matching filesystem semantics. Paths are NOT resolved against- disk (no ``.resolve()``) so non-existent paths - common in test mocks- and in PYTHONPATH entries pointing at yet-to-be-created dirs - work- correctly. ``Path.resolve(strict=False)`` would also touch the- filesystem to resolve symlinks, which we deliberately avoid.+ ``gateway_windows._preserve_hermes_home_path`` maps a physical path under+ the resolved HERMES_HOME back onto the configured HERMES_HOME spelling.+ Mirror that producer contract here so a junction-backed install is matched+ without treating arbitrary descendants of HERMES_HOME as Hermes-owned."""- c_parts = [os.path.normcase(p) for p in child.parts]- p_parts = [os.path.normcase(p) for p in parent.parts]- if len(c_parts) < len(p_parts):- return False- return c_parts[: len(p_parts)] == p_parts+ aliases: list[Path] = []+ def add(candidate: Path) -> None:+ if not any(_same_path(candidate, existing) for existing in aliases):+ aliases.append(candidate)-# --- Hermes venv / repo-root detection (module-level, computed once) ---+ add(resolved_root)+ add(lexical_root)-#: The running interpreter's own venv root. On a venv Python ``sys.prefix``-#: points at the venv root (e.g. ``.../venv``); on a system Python it points-#: at ``/usr`` or similar. We only strip site-packages under this path when-#: the interpreter is actually inside a venv (``sys.prefix != sys.base_prefix``).-_hermes_venv_root: Path = Path(sys.prefix)+ try:+ resolved_home = configured_home.resolve()+ home_key = os.path.normcase(str(resolved_home))+ root_key = os.path.normcase(str(resolved_root))+ if os.path.commonpath([home_key, root_key]) == home_key:+ relative_root = os.path.relpath(str(resolved_root), str(resolved_home))+ add(configured_home / relative_root)+ except (OSError, ValueError):+ pass++ return tuple(aliases)+++# --- Hermes venv / repo-root detection (module-level, computed once) ---#: The Hermes repository root - three levels up from this file#: (``tools/environments/local.py`` -> ``tools/environments`` -> ``tools``@@ -1389,9 +1411,10 @@ _hermes_repo_root: Path = Path(__file__).resolve().parents[2]#: ``Path(__file__)`` (unresolved) keeps that spelling, so a PYTHONPATH#: entry written by the launcher still matches even though it differs#: lexically from the resolved root.-_hermes_repo_root_aliases: tuple[Path, ...] = (+_hermes_repo_root_aliases: tuple[Path, ...] = _build_hermes_repo_root_aliases(_hermes_repo_root,- Path(__file__).parents[2],+ Path(__file__).absolute().parents[2],+ get_process_hermes_home(),)#: Whether the current interpreter is running inside a venv. On Python 3.3+@@ -1409,45 +1432,75 @@ _in_venv: bool = (_hermes_site_packages: list[Path] | None = None-def _get_hermes_site_packages() -> list[Path]:- """Return the site-packages dirs of the running interpreter's venv.+def _validated_runtime_venv(env: dict) -> Path | None:+ """Return a producer-owned runtime venv identified by VIRTUAL_ENV.++ A user may carry an unrelated VIRTUAL_ENV, so the variable alone is not+ provenance. The legacy Windows base-Python gateway producer uses the exact+ ``<Hermes repo>/venv`` layout and a real venv marker; require both before+ accepting its separate runtime venv.+ """+ value = env.get("VIRTUAL_ENV")+ if not value:+ return None++ candidate = Path(value)+ if not any(_same_path(candidate, repo_root / "venv") for repo_root in _hermes_repo_root_aliases):+ return None++ try:+ if not (candidate / "pyvenv.cfg").is_file():+ return None+ except OSError:+ return None++ return candidate+++def _get_hermes_site_packages(env: dict) -> list[Path]:+ """Return exact site-packages dirs owned by the Hermes runtime.Uses ``site.getsitepackages()`` when available for robustness (it respects``.pth`` rewrites and platform conventions), with a manual fallback thatconstructs the canonical path from ``sys.prefix`` for POSIX and Windows.+ A validated Windows base-interpreter launch contributes its separate+ ``VIRTUAL_ENV/Lib/site-packages`` directory as an additional exact entry."""global _hermes_site_packagesif _hermes_site_packages is not None:- return _hermes_site_packages-- result: list[Path] = []- try:- import site- for sp in site.getsitepackages():- result.append(Path(sp))- except Exception:- pass+ result = list(_hermes_site_packages)+ else:+ result = []+ if _in_venv:+ try:+ import site+ for sp in site.getsitepackages():+ result.append(Path(sp))+ except Exception:+ pass- # Fallback: construct manually. On POSIX:- # sys.prefix / lib / python{X.Y} / site-packages- # On Windows:- # sys.prefix / Lib / site-packages- if not result:- if _IS_WINDOWS:- result.append(Path(sys.prefix) / "Lib" / "site-packages")- else:- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"- result.append(Path(sys.prefix) / "lib" / pyver / "site-packages")+ # Fallback: construct manually. On POSIX:+ # sys.prefix / lib / python{X.Y} / site-packages+ # On Windows:+ # sys.prefix / Lib / site-packages+ if not result:+ if _IS_WINDOWS:+ result.append(Path(sys.prefix) / "Lib" / "site-packages")+ else:+ pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"+ result.append(Path(sys.prefix) / "lib" / pyver / "site-packages")++ _hermes_site_packages = list(result)++ runtime_venv = _validated_runtime_venv(env)+ if runtime_venv is not None:+ runtime_site_packages = runtime_venv / "Lib" / "site-packages"+ if not any(_same_path(runtime_site_packages, existing) for existing in result):+ result.append(runtime_site_packages)- _hermes_site_packages = resultreturn result-# Regex to detect ``site-packages`` as a path component (not a substring of-# a longer directory name). Same cross-platform separator handling.-_SITE_PACKAGES_RE = re.compile(r"(?:^|[\\/])site-packages(?:[\\/]|$)")--def _strip_hermes_owned_pythonpath(env: dict) -> None:"""Remove Hermes-owned PYTHONPATH entries from subprocess environments.@@ -1471,11 +1524,12 @@ def _strip_hermes_owned_pythonpath(env: dict) -> None:stripped; direct children (``<repo>/tools`` etc.) are never injectedby any launcher and are treated as user paths.- 2. **Hermes venv site-packages** - entries under the running- interpreter's own venv site-packages directory. Redundant for+ 2. **Hermes venv site-packages** - the exact directories owned by the+ running interpreter's venv, or by a separately validated Windows+ base-Python gateway runtime venv. Redundant forsubprocesses (they get their packages via ``sys.path``, not an- inherited env var) and a common leak vector. Only checked when- running inside a venv.+ inherited env var) and a common leak vector. Descendants are not+ producer-owned entries and are preserved.User ``PYTHONPATH`` entries (``/opt/my-lib``, Nix plugin paths, a``/custom/lib/python3.13/site-packages`` intended for a child Python 3.13)@@ -1490,30 +1544,29 @@ def _strip_hermes_owned_pythonpath(env: dict) -> None:if not pp:return- hermes_site_packages = _get_hermes_site_packages() if _in_venv else []+ hermes_site_packages = _get_hermes_site_packages(env)kept: list[str] = []stripped: list[str] = []for entry in pp.split(os.pathsep):- entry = entry.strip()- if not entry:+ # Empty and non-normalized components are user-owned semantics. In+ # particular, an empty component means the current working directory.+ # Preserve raw spelling unless the exact component is Hermes-owned.+ if entry == "":+ kept.append(entry)continueentry_path = Path(entry)should_strip = False# --- Check 1: Hermes venv site-packages ---- # The entry lives under the running interpreter's own venv- # site-packages. Redundant for subprocesses (they get their packages- # via sys.path, not PYTHONPATH) and a common leak vector.- # Use the regex (not ``entry_path.parts``) for cross-platform detection- # so Windows backslash paths are caught on a POSIX host.- if _SITE_PACKAGES_RE.search(entry):- for sp in hermes_site_packages:- if _is_path_under(entry_path, sp):- should_strip = True- break+ # Producers inject the exact directory, never a descendant. Exact+ # matching avoids deleting a user path nested below site-packages.+ for sp in hermes_site_packages:+ if _same_path(entry_path, sp):+ should_strip = True+ breakif should_strip:stripped.append(entry)continue@@ -1528,13 +1581,10 @@ def _strip_hermes_owned_pythonpath(env: dict) -> None:# resolved and unresolved (HERMES_HOME/junction) spellings count as# Hermes-owned.if not should_strip:- for repo_root in _hermes_repo_root_aliases:- if _is_path_under(entry_path, repo_root):- # Exact root only (same path), not children.- rel = entry_path.relative_to(repo_root)- if len(rel.parts) == 0:- should_strip = True- break+ should_strip = any(+ _same_path(entry_path, repo_root)+ for repo_root in _hermes_repo_root_aliases+ )if should_strip:stripped.append(entry)