The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): the user's own tools come before Hermes's in the terminal
ethernet162b457c8e2a
diff --git a/pm/user_facing.py b/pm/user_facing.pynew file mode 100644index 00000000000..6053b071ac0--- /dev/null+++ b/pm/user_facing.py@@ -0,0 +1,54 @@+"""The terminal's PATH: the user's own tools first, Hermes's after them.++Hermes's process puts its store's tool dirs first (``pm.install.activate``), so Hermes's own+code resolves the pinned binaries. Terminal commands belong to the user and the agent, so they+run the tools the user installed, and Hermes's tools are the fallback for a machine without+them. Hermes's own operations must not depend on this PATH: they resolve pinned tools+through PM (``pm.env_for``, ``pm.installed_package``).+"""+from __future__ import annotations++import os+from pathlib import Path+++def _python_stub_dir(directory: str) -> bool:+ """True for the Windows app-alias dir when its ``python.exe`` is only the Store stub.++ The stub opens the Microsoft Store instead of running Python. A real Store Python puts its+ aliases in the same dir, and it also ships a ``python3.N.exe``, which the stub does not.+ """+ parts = [os.path.normcase(part) for part in Path(directory).parts[-2:]]+ if parts != [os.path.normcase("Microsoft"), os.path.normcase("WindowsApps")]:+ return False+ try:+ return not any(Path(directory).glob("python3.*.exe"))+ except OSError:+ return True+++def _python_dirs() -> set[str]:+ from pm.install import env_for++ path = env_for("python", base_env={"PATH": ""}).get("PATH", "")+ return {os.path.normcase(d) for d in path.split(os.pathsep) if d}+++def user_facing_path(path: str) -> str:+ """*path* with Hermes's store tool dirs moved behind the user's own entries.++ Hermes's Python stops just before the app-alias dir that holds the Store stub, so a+ machine without Python still runs a real one.+ """+ from pm.install import _store_path_dirs++ ours = _store_path_dirs()+ if not ours:+ return path+ keys = {os.path.normcase(d) for d in ours}+ kept = [p for p in path.split(os.pathsep) if p and os.path.normcase(p) not in keys]+ python = _python_dirs()+ cut = next((i for i, p in enumerate(kept) if _python_stub_dir(p)), len(kept))+ early = [d for d in ours if os.path.normcase(d) in python]+ late = [d for d in ours if os.path.normcase(d) not in python]+ return os.pathsep.join(dict.fromkeys([*kept[:cut], *early, *kept[cut:], *late]))diff --git a/tests/pm/test_user_facing.py b/tests/pm/test_user_facing.pynew file mode 100644index 00000000000..50d0e8ea581--- /dev/null+++ b/tests/pm/test_user_facing.py@@ -0,0 +1,29 @@+"""The terminal runs the user's own tools first and Hermes's after them (pm.user_facing)."""+from __future__ import annotations++import os++import pm.install+import pm.user_facing+from pm.user_facing import user_facing_path+++def test_user_tools_come_before_hermes_and_python_stops_at_the_store_stub(tmp_path, monkeypatch):+ npm, node, python, rg = (str(tmp_path / "store" / name) for name in ("npm", "node", "python", "rg"))+ stub = tmp_path / "AppData" / "Local" / "Microsoft" / "WindowsApps"+ stub.mkdir(parents=True)+ monkeypatch.setattr(pm.install, "_store_path_dirs", lambda: [npm, node, python, rg])+ monkeypatch.setattr(pm.user_facing, "_python_dirs", lambda: {os.path.normcase(python)})+ path = os.pathsep.join([npm, node, python, rg, "/usr/bin", str(stub), "/home/u/bin"])++ # The stub alias would open the Store, so a machine without Python still runs ours.+ assert user_facing_path(path).split(os.pathsep) == [+ "/usr/bin", python, str(stub), "/home/u/bin", npm, node, rg]++ # A real Store Python ships python3.N.exe beside its alias: then the user's Python wins.+ (stub / "python3.13.exe").write_bytes(b"")+ assert user_facing_path(path).split(os.pathsep) == [+ "/usr/bin", str(stub), "/home/u/bin", python, npm, node, rg]++ monkeypatch.setattr(pm.install, "_store_path_dirs", list)+ assert user_facing_path(path) == pathdiff --git a/tests/tools/test_local_env_windows_msys.py b/tests/tools/test_local_env_windows_msys.pyindex 853d47e4d16..2be366a8aa5 100644--- a/tests/tools/test_local_env_windows_msys.py+++ b/tests/tools/test_local_env_windows_msys.py@@ -42,7 +42,6 @@ from tools.environments.local import (_git_bash_bin_dirs,_make_run_env,_msys_to_windows_path,- _prepend_git_bash_dirs,_quote_bash_path,_resolve_safe_cwd,_sanitize_subprocess_env,@@ -332,3 +331,15 @@ class TestWrapCommandWindowsNativeCwd:script = captured["script"]assert "/c/Users/Alexander/AppData/Local/Temp/hermes-snap-deadbeef.sh" in scriptassert r"C:\Users\Alexander\AppData" not in script+++def test_git_bash_dirs_stay_first_when_hermes_tools_move_behind_the_users(monkeypatch):+ """Git Bash's coreutils are store dirs too, but bash must find them before System32's."""+ import pm.install+ from tools.environments import local as local_mod++ bash_dir, node_dir, system32 = "/store/git/usr/bin", "/store/node", "/windows/system32"+ monkeypatch.setattr(pm.install, "_store_path_dirs", lambda: [bash_dir, node_dir])+ monkeypatch.setattr(local_mod, "_git_bash_bin_dirs", lambda: [bash_dir])+ path = os.pathsep.join([bash_dir, node_dir, system32])+ assert local_mod._user_tools_first(path).split(os.pathsep) == [bash_dir, system32, node_dir]diff --git a/tools/environments/local.py b/tools/environments/local.pyindex 5a9d39af73b..c2baf9daa10 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -314,6 +314,14 @@ def _sanitize_subprocess_env(base_env: dict | None, extra_env: dict | None = Non_plugin_terminal_env_strip_keys(), lambda p: p)+def _terminal_env(env: dict) -> dict:+ """*env* with the user's tools first on PATH (``_user_tools_first``), for background commands."""+ path_key = _path_env_key(env)+ if path_key is not None:+ env[path_key] = _user_tools_first(env[path_key])+ return env++def hermes_subprocess_env(*, inherit_credentials: bool = False, base_env: dict[str, str] | None = None) -> dict[str, str]:@@ -561,10 +569,18 @@ def _prepend_missing_path_entries(existing_path: str, dirs: list[str]) -> str:return os.pathsep.join([*missing, *entries]) if missing else existing_path-def _prepend_git_bash_dirs(existing_path: str) -> str:- """Prepend Git Bash's binary dirs if missing (no-op off Windows), so the- non-login ``bash -c`` fallback can find coreutils."""- return _prepend_missing_path_entries(existing_path, _git_bash_bin_dirs())+def _user_tools_first(existing_path: str) -> str:+ """*existing_path* with the user's tools before Hermes's (``pm.user_facing``) and, on+ Windows, Git Bash's dirs first. They go first even when already listed: they are store+ dirs that now sit behind the user's entries, and a non-login ``bash -c`` needs its+ coreutils ahead of System32's lookalikes."""+ from pm.user_facing import user_facing_path++ path = user_facing_path(existing_path)+ bash_dirs = _git_bash_bin_dirs()+ keys = {os.path.normcase(d) for d in bash_dirs}+ rest = [p for p in path.split(os.pathsep) if p and os.path.normcase(p) not in keys]+ return os.pathsep.join([*bash_dirs, *rest]) if bash_dirs else path# POSIX-sh-family shells that understand spawn_local's ``[shell, "-lic", "set +m; …"]``@@ -738,7 +754,7 @@ def _make_run_env(env: dict) -> dict:run_env = _scrubbed_env([(dict(strip_launch_profile_env(os.environ.copy()) | env), True)],frozenset(),- lambda p: _prepend_git_bash_dirs(_append_missing_sane_path_entries(p)),+ lambda p: _user_tools_first(_append_missing_sane_path_entries(p)),)# While this profile's Bot Desktop is running, its DISPLAY/XAUTHORITY/DBUS ride along so GUI# apps the agent launches from the terminal open on the Bot Screen the user is watching, notdiff --git a/tools/process_registry.py b/tools/process_registry.pyindex 017df6a9504..25bdc43394e 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -25,7 +25,7 @@ _IS_WINDOWS = platform.system() == "Windows"# (not merely "not Windows") so macOS and other POSIX platforms never touch systemd.# See #70716._IS_LINUX = platform.system() == "Linux"-from tools.environments.local import _find_shell, _resolve_safe_cwd, _sanitize_subprocess_env+from tools.environments.local import _find_shell, _resolve_safe_cwd, _sanitize_subprocess_env, _terminal_envfrom hermes_cli._subprocess_compat import windows_hide_flagsfrom dataclasses import dataclass, fieldfrom typing import Any, Dict, List, Literal, NamedTuple, Optional@@ -1152,7 +1152,7 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):def _spawn_env(env_vars: dict) -> dict:"""Sanitized child env; PYTHONUNBUFFERED so tqdm/datasets-style bufferingdoesn't hide progress from process(action="poll")."""- env = _sanitize_subprocess_env(os.environ, env_vars)+ env = _terminal_env(_sanitize_subprocess_env(os.environ, env_vars))env["PYTHONUNBUFFERED"] = "1"return env