The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(pm): route Python tool installs through PM
ethernet80273b450700
diff --git a/agent/lsp/install.py b/agent/lsp/install.pyindex bc5046db940..ddea5266c02 100644--- a/agent/lsp/install.py+++ b/agent/lsp/install.py@@ -101,6 +101,16 @@ def _existing_binary(name: str) -> Optional[str]:for staged in _native_binary_candidates(hermes_lsp_bin_dir() / name):if staged.exists() and os.access(staged, os.X_OK):return str(staged)+ if any(r.get("strategy") == "pip" and r.get("bin") == name for r in INSTALL_RECIPES.values()):+ import pm++ try:+ binary = pm.python_tool(f"lsp-{name}", name)+ except RuntimeError as exc:+ logger.warning("[install] cannot read Python server %s: %s", name, exc)+ else:+ if binary is not None:+ return str(binary)suffixes = ("", *_WINDOWS_WRAPPER_SUFFIXES) if _is_windows() else ("",)return next((p for s in suffixes if (p := shutil.which(f"{name}{s}"))), None)@@ -211,24 +221,14 @@ def _install_go(pkg: str, bin_name: str) -> Optional[str]:def _install_pip(pkg: str, bin_name: str) -> Optional[str]:- """``pip install --target <staging>/python-packages`` then link the console script into ``lsp/bin/``."""- pip_target = hermes_lsp_bin_dir().parent / "python-packages"- pip_target.mkdir(parents=True, exist_ok=True)+ """Provision a Python server in its own PM-managed environment."""try:- logger.info("[install] pip install --target %s %s", pip_target, pkg)- from hermes_cli.tools_config import _pip_install+ import pm- proc = _pip_install(["--target", str(pip_target), "--quiet", pkg], timeout=300)- if proc.returncode != 0:- logger.warning("[install] pip install failed for %s: %s", pkg, (proc.stderr or "").strip()[:500])- return None- except (subprocess.TimeoutExpired, OSError) as e:- logger.warning("[install] pip install errored for %s: %s", pkg, e)+ return str(pm.ensure_python_tool(f"lsp-{bin_name}", [pkg], bin_name, timeout=300))+ except Exception as exc:+ logger.warning("[install] Python server install failed for %s: %s", pkg, exc)return None- # POSIX wheels write console scripts to bin/, native Windows to Scripts/.- script_dirs = [pip_target / "bin"] + ([pip_target / "Scripts"] if _is_windows() else [])- found = _first_existing(*(d / bin_name for d in script_dirs))- return _link_into_bin(found) if found is not None else None# strategy → installer(recipe, bin_name). ``manual`` is handled before dispatch.diff --git a/plugins/memory/hindsight/embedded_runtime.py b/plugins/memory/hindsight/embedded_runtime.pyindex 0d7c162bce9..68e23ed5997 100644--- a/plugins/memory/hindsight/embedded_runtime.py+++ b/plugins/memory/hindsight/embedded_runtime.py@@ -5,9 +5,7 @@ from __future__ import annotationsimport jsonimport loggingimport os-import shutilimport subprocess-import uuidfrom pathlib import Pathfrom typing import Any@@ -17,17 +15,11 @@ logger = logging.getLogger(__name__)_EMBED_VERSION = "0.9.2"_API_SLIM_VERSION = "0.9.2"-# Marker file written inside each generation recording what it was built from;-# a generation whose marker no longer matches is replaced (new generation) on-# the next ensure — never mutated in place.-_EXPECTED = {"hindsight-embed": _EMBED_VERSION, "hindsight-api-slim": _API_SLIM_VERSION}-_STATE_FILE = ".hermes-sideenv.json"-_ACTIVE_RECORD = "active.json"+_REQUIREMENTS = (f"hindsight-embed=={_EMBED_VERSION}", f"hindsight-api-slim[all]=={_API_SLIM_VERSION}")# First successful daemon start downloads/loads ML models — minutes, not seconds._DEFAULT_DAEMON_START_TIMEOUT = 900.0-_UV_LOCK_TIMEOUT = 900.0-_UV_SYNC_TIMEOUT = 3600.0+_INSTALL_TIMEOUT = 3600_PROBE_TIMEOUT = 300.0_PORT_HEALTH_GRACE_ENV = "HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT"@@ -66,122 +58,20 @@ def sideenv_root() -> Path:return get_hermes_home() / "profiles" / "Hindsight" / "env"-def _active_generation(root: Path) -> Path | None:- """The published generation directory, or None when nothing is active."""- try:- record = json.loads((root / _ACTIVE_RECORD).read_text(encoding="utf-8-sig"))- gen = root / str(record.get("generation", ""))- except Exception:- return None- return gen if gen.resolve().is_relative_to(root.resolve()) and gen != root and gen.is_dir() else None---def _publish_generation(root: Path, generation: Path) -> None:- """Point the selection record at *generation* atomically (file replace —- never a directory rename: venv launchers embed absolute paths)."""- from utils import atomic_json_write-- atomic_json_write(root / _ACTIVE_RECORD, {"generation": generation.name, "pins": _EXPECTED})--def sideenv_python(root: Path | None = None) -> Path | None:- """The active generation's interpreter, or None when the side env is not- installed. Resolved through the selection record — the generation dir is- created at its final path and never renamed."""- root = Path(root) if root is not None else sideenv_root()- gen = _active_generation(root)- if gen is None:- return None- exe = "python.exe" if os.name == "nt" else "python"- for scripts in ("Scripts", "bin"):- candidate = gen / ".venv" / scripts / exe- if candidate.is_file():- return candidate- return None---def sideenv_pyproject() -> str:- """Exact pinned requirements of the isolated runtime (public PyPI versions,- frozen into uv.lock at install time; never resolved against the main env)."""- return (- '[project]\n'- 'name = "hermes-hindsight-embedded"\n'- 'version = "0.9.2"\n'- 'requires-python = ">=3.11"\n'- 'dependencies = [\n'- f' "hindsight-embed=={_EMBED_VERSION}",\n'- f' "hindsight-api-slim[all]=={_API_SLIM_VERSION}",\n'- ']\n'- )---def _generation_current(generation: Path) -> bool:- """Installed and matching the pinned versions (marker written at build)."""- if generation is None:- return False- try:- state = json.loads((generation / _STATE_FILE).read_text(encoding="utf-8-sig"))- except Exception:- return False- return state.get("pins") == _EXPECTED+ """Read PM's selected side interpreter without creating an environment."""+ import pm--def _uv_bridge(venv: Path) -> tuple[str, dict[str, str]]:- """The sanctioned pm bridge: pinned uv binary + sanitized env for *venv*."""- from pm.client import uv as pm_uv-- uv_bin, env = pm_uv(venv=venv)- if not uv_bin:- raise RuntimeError(- "pm could not realize the pinned uv binary; run 'hermes pm install' "- "before installing the isolated Hindsight runtime"- )- return str(uv_bin), env---def _run_uv(uv_bin: str, env: dict[str, str], args: list[str], timeout: float) -> None:- result = subprocess.run( # noqa: S603 — fixed argv, no shell- [uv_bin, *args], env=env, capture_output=True, text=True,- encoding="utf-8", errors="replace", timeout=timeout,- )- if result.returncode != 0:- detail = (result.stderr or result.stdout or "").strip()[-2000:]- raise RuntimeError(f"uv {' '.join(args)} failed (exit {result.returncode}): {detail}")+ return pm.environment_python("hindsight", root=root if root is not None else sideenv_root())def ensure_sideenv() -> Path:- """Install/update the isolated runtime; returns the active generation dir.+ """Provision the isolated embedded runtime; PM owns generation publication."""+ import pm- Each install is an immutable generation built at its final path and- published via the ``active.json`` selection record. A failed build removes- only its own unpublished generation; the previous generation (and any- daemon running from it) stays untouched."""- root = sideenv_root()- active = _active_generation(root)- if _generation_current(active) and sideenv_python(root) is not None:- return active-- generation = root / f"gen-{uuid.uuid4().hex}"- generation.parent.mkdir(parents=True, exist_ok=True)- logger.info("Hindsight embedded runtime: building generation %s (pins=%s)",- generation, _EXPECTED)- try:- generation.mkdir(parents=True)- (generation / "pyproject.toml").write_text(sideenv_pyproject(), encoding="utf-8")- uv_bin, env = _uv_bridge(generation / ".venv")- _run_uv(uv_bin, env, ["lock", "--project", str(generation)], _UV_LOCK_TIMEOUT)- _run_uv(uv_bin, env, ["sync", "--project", str(generation), "--frozen"], _UV_SYNC_TIMEOUT)- (generation / _STATE_FILE).write_text(- json.dumps({"pins": _EXPECTED}, sort_keys=True) + "\n", encoding="utf-8")- except BaseException:- # The failed generation was never published; nothing can be running- # from it, so removing it leaks nothing. Previous generations stay.- shutil.rmtree(generation, ignore_errors=True)- raise- _publish_generation(root, generation)- logger.info("Hindsight embedded runtime: generation %s published (side env %s)",- generation.name, root)- return generation+ return pm.ensure_environment(+ "hindsight", _REQUIREMENTS, root=sideenv_root(), explicit=True, timeout=_INSTALL_TIMEOUT,+ )def _probe_interpreter(python: Path, timeout: float = _PROBE_TIMEOUT) -> tuple[bool, str | None]:diff --git a/plugins/memory/hindsight/setup.py b/plugins/memory/hindsight/setup.pyindex cbeaeb8b91e..f1b74aee442 100644--- a/plugins/memory/hindsight/setup.py+++ b/plugins/memory/hindsight/setup.py@@ -94,13 +94,13 @@ def _sync_client_dependency() -> bool:def _install_embedded_runtime() -> bool:"""local_embedded: install the isolated side env (hindsight-embed + the heavy- hindsight-api-slim[all], pinned 0.9.2) via the pm.ensure.uv bridge — never the+ hindsight-api-slim[all]) via PM's isolated environment operation — never theshared main venv (the protobuf floors conflict). The daemon later runs from theside env's own interpreter/binary; Hermes talks HTTP with hindsight-client."""from .embedded_runtime import _local_runtime_hint, ensure_sideenv, sideenv_roottry:- root = ensure_sideenv()+ ensure_sideenv()except Exception as e:print(f" ⚠ Isolated runtime install failed: {e}")print(f" {_local_runtime_hint(str(e)).strip()}")diff --git a/plugins/platforms/google_chat/oauth.py b/plugins/platforms/google_chat/oauth.pyindex 720c2e111b0..d28813b90f6 100644--- a/plugins/platforms/google_chat/oauth.py+++ b/plugins/platforms/google_chat/oauth.py@@ -19,12 +19,9 @@ import osimport reimport statimport sys-from importlib.metadata import version as _distribution_versionfrom pathlib import Pathfrom typing import Any, List, NoReturn, Optional, Tuple-from packaging.requirements import Requirement-from hermes_constants import display_hermes_home, get_hermes_homefrom utils import atomic_write_text@@ -39,16 +36,7 @@ _EMAIL_FS_RE = re.compile(r"[^a-z0-9._@-]+")# subsequent messages.create; no drive.file or other scopes.SCOPES: List[str] = ["https://www.googleapis.com/auth/chat.messages.create"]-# Pip packages required by the Google Chat adapter and its OAuth flow.-_REQUIRED_PACKAGES = [- "google-cloud-pubsub==2.39.0",- "google-api-python-client==2.194.0",- "google-auth==2.55.1",- "google-auth-oauthlib==1.3.1",- "google-auth-httplib2==0.3.1",- "httplib2==0.32.0",- "pyasn1==0.6.4",-]+_DEPENDENCY_EXTRAS = ["google", "google-chat"]# Google deprecated the ``oob`` flow: use a localhost redirect that is expected# to FAIL; the user pastes the code from the failed browser URL back into chat.@@ -210,47 +198,29 @@ def _fail(*lines: str) -> NoReturn:def _ensure_deps() -> None:- """Check exact dependency versions; install if stale; exit on failure."""- if _missing_required_packages() and not install_deps():- sys.exit(1)-+ """Auth must stop if new dependencies need a fresh process to activate."""+ try:+ import pm-def _missing_required_packages() -> List[str]:- """Return exact requirements absent or stale in this interpreter."""- missing = []- for spec in _REQUIRED_PACKAGES:- requirement = Requirement(spec)- try:- installed = _distribution_version(requirement.name)- satisfied = requirement.specifier.contains(installed, prereleases=True)- except Exception:- satisfied = False- if not satisfied:- missing.append(spec)- return missing+ for extra in _DEPENDENCY_EXTRAS:+ pm.ensure_import(extra)+ except Exception as exc:+ _fail(f"ERROR: Google Chat dependencies unavailable: {exc}")def install_deps() -> bool:- missing = _missing_required_packages()- if not missing:- print("Dependencies already installed.")- return True+ """Install the declared dependency graph without mutating the booted environment."""print("Installing Google Chat dependencies...")try:- from hermes_cli.tools_config import _pip_install-- result = _pip_install(["--quiet"] + missing)- if result.returncode != 0:- raise RuntimeError((result.stderr or "install failed").strip()[:300])- remaining = _missing_required_packages()- if remaining:- raise RuntimeError("dependencies remain stale after install: " + " ".join(remaining))- print("Dependencies installed.")- return True+ import pm++ pm.sync_venv(_DEPENDENCY_EXTRAS, explicit=True)except Exception as exc:print(f"ERROR: Failed to install dependencies: {exc}")print("Run `hermes setup` to repair the managed installation, then retry.")return False+ print("Dependencies installed. Restart Hermes to activate any new dependency environment.")+ return Truedef check_auth(email: Optional[str] = None) -> bool:diff --git a/tests/agent/lsp/test_install_and_lint_fixes.py b/tests/agent/lsp/test_install_and_lint_fixes.pyindex ae8c04d0638..aba4d631f1b 100644--- a/tests/agent/lsp/test_install_and_lint_fixes.py+++ b/tests/agent/lsp/test_install_and_lint_fixes.py@@ -68,34 +68,30 @@ def test_install_npm_works_without_extras(tmp_path, monkeypatch):[email protected]("windows")-def test_install_pip_finds_windows_scripts_launcher(tmp_path, monkeypatch):- """pip console scripts can land in Scripts/ on native Windows.-- ``platforms("windows")``: the ``Scripts/`` layout and the ``.exe`` launcher are- what pip actually produces on Windows. Faking ``_is_windows()`` on Linux- made the test assert against a directory tree the test itself created, on- a host where pip would never lay it out that way.- """- monkeypatch.setenv("HERMES_HOME", str(tmp_path))-+def test_install_python_server_uses_pm_tool_environment(tmp_path, monkeypatch):+ import pmfrom agent.lsp import install as install_mod- def fake_pip_install(args, **kwargs):- scripts_dir = install_mod.hermes_lsp_bin_dir().parent / "python-packages" / "Scripts"- scripts_dir.mkdir(parents=True, exist_ok=True)- launcher = scripts_dir / "fake-language-server.exe"- launcher.write_text("launcher\n", encoding="utf-8")- launcher.chmod(0o755)- return MagicMock(returncode=0, stderr="")+ binary = tmp_path / "environment" / "fake-language-server"+ calls = []+ selected = []- monkeypatch.setattr("hermes_cli.tools_config._pip_install", fake_pip_install)+ def ensure(name, requirements, executable, **kwargs):+ calls.append((name, requirements, executable, kwargs))+ selected.append(binary)+ return binary- resolved = install_mod._install_pip("fake-lsp", "fake-language-server")-- assert resolved is not None- assert resolved.endswith("fake-language-server.exe")- assert (install_mod.hermes_lsp_bin_dir() / "fake-language-server.exe").exists()+ monkeypatch.setattr(pm, "ensure_python_tool", ensure)+ monkeypatch.setattr(pm, "python_tool", lambda *a, **kw: selected[0] if selected else None)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.setattr(install_mod, "INSTALL_RECIPES", {+ "fake-lsp": {"strategy": "pip", "pkg": "fake-lsp==1.0", "bin": "fake-language-server"},+ })+ monkeypatch.setattr(install_mod, "_install_results", {})+ monkeypatch.setattr(install_mod.shutil, "which", lambda *a, **kw: None)+ assert install_mod.try_install("fake-lsp") == str(binary)+ assert calls == [("lsp-fake-language-server", ["fake-lsp==1.0"], "fake-language-server", {"timeout": 300})]+ assert install_mod.detect_status("fake-lsp") == "installed"# ---------------------------------------------------------------------------@@ -158,8 +154,12 @@ def test_status_output_includes_backend_warnings_section(tmp_path, monkeypatch):-def test_check_lint_returns_error_for_real_ts_type_errors(tmp_path):+def test_check_lint_returns_error_for_real_ts_type_errors(tmp_path, monkeypatch):"""Sanity: real TypeScript errors still go through the error path."""+ from pathlib import Path++ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)from tools.environments.local import LocalEnvironmentfrom tools.file_operations import ShellFileOperationsdiff --git a/tests/gateway/test_google_chat.py b/tests/gateway/test_google_chat.pyindex db425ec33dc..56a20d3126b 100644--- a/tests/gateway/test_google_chat.py+++ b/tests/gateway/test_google_chat.py@@ -1656,12 +1656,16 @@ class TestAuthorizationEmailMatch:back without a test failing."""- def test_allowlist_matches_when_user_id_is_email(self, monkeypatch):+ def test_allowlist_matches_when_user_id_is_email(self, monkeypatch, tmp_path):"""Email allowlist match — the canonical case.The adapter assigns ``user_id = sender_email`` so the genericcheck_ids path picks it up. No platform-specific bridge needed."""+ from pathlib import Path++ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)from gateway.config import GatewayConfigfrom gateway.run import GatewayRunnerfrom gateway.session import SessionSourcediff --git a/tests/gateway/test_google_chat_oauth_dependencies.py b/tests/gateway/test_google_chat_oauth_dependencies.pyindex 43b4227b2c4..d153950b0d3 100644--- a/tests/gateway/test_google_chat_oauth_dependencies.py+++ b/tests/gateway/test_google_chat_oauth_dependencies.py@@ -1,63 +1,26 @@-"""Security-floor tests for the Google Chat runtime installer."""+"""Google Chat dependency installation crosses PM's declared-feature interface."""-from __future__ import annotations+import pm-from importlib.metadata import PackageNotFoundError-from types import SimpleNamespace+import pytestfrom plugins.platforms.google_chat import oauth-def test_stale_google_transitives_are_reported_missing(monkeypatch):- installed = {- "google-cloud-pubsub": "2.39.0",- "google-api-python-client": "2.194.0",- "google-auth": "2.55.0",- "google-auth-oauthlib": "1.3.1",- "google-auth-httplib2": "0.3.1",- "httplib2": "0.31.2",- "pyasn1": "0.6.3",- }-- def fake_version(name):- try:- return installed[name]- except KeyError:- raise PackageNotFoundError(name) from None-- monkeypatch.setattr(oauth, "_distribution_version", fake_version)-- assert oauth._missing_required_packages() == [- "google-auth==2.55.1",- "httplib2==0.32.0",- "pyasn1==0.6.4",- ]---def test_installer_repairs_stale_transitives(monkeypatch):- states = iter(- [- [- "google-auth==2.55.1",- "httplib2==0.32.0",- "pyasn1==0.6.4",- ],- [],- ]- )- monkeypatch.setattr(oauth, "_missing_required_packages", lambda: next(states))+def test_installer_syncs_declared_features_without_rechecking_old_interpreter(monkeypatch, capsys):calls = []- monkeypatch.setattr(- "hermes_cli.tools_config._pip_install",- lambda argv: calls.append(argv) or SimpleNamespace(returncode=0, stderr=""),- )-+ monkeypatch.setattr(pm, "sync_venv", lambda extras, **kwargs: calls.append((extras, kwargs)))assert oauth.install_deps() is True- assert calls == [- [- "--quiet",- "google-auth==2.55.1",- "httplib2==0.32.0",- "pyasn1==0.6.4",- ]- ]+ assert calls == [(["google", "google-chat"], {"explicit": True})]+ assert "restart" in capsys.readouterr().out.lower()+++def test_auth_stops_when_pm_requires_a_restart(monkeypatch, capsys):+ def unavailable(extra):+ raise RuntimeError(f"{extra} installed; restart Hermes to activate")++ monkeypatch.setattr(pm, "ensure_import", unavailable)+ with pytest.raises(SystemExit) as failure:+ oauth._ensure_deps()+ assert failure.value.code == 1+ assert "restart Hermes" in capsys.readouterr().outdiff --git a/tests/plugins/memory/test_hindsight_embedded_runtime.py b/tests/plugins/memory/test_hindsight_embedded_runtime.pyindex e58115347cf..1a1e5f998d3 100644--- a/tests/plugins/memory/test_hindsight_embedded_runtime.py+++ b/tests/plugins/memory/test_hindsight_embedded_runtime.py@@ -1,7 +1,7 @@"""The isolated local_embedded Hindsight runtime (embedded_runtime).-Real imports of the plugin modules; the only fakes sit at the subprocess-boundary (the uv bridge invocations and the side-python bridge) — the URL the+Real plugin imports with fakes at PM's operation interface and the side-python+bridge. Generation ownership is tested in tests/pm; here the URL thedaemon reports is proven against a real loopback HTTP /health server, never aconstant port. The boot-selected main environment is never touched."""@@ -16,8 +16,6 @@ import pytestimport plugins.memory.hindsight.embedded_runtime as rt-_STATE = rt._STATE_FILE-@pytest.fixture()def side_root(tmp_path, monkeypatch):@@ -30,88 +28,44 @@ def _fake_completed(returncode=0, stdout="", stderr=""):return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)-# -- pinned pyproject ------------------------------------------------------------def test_sideenv_pyproject_pins_exact_pair():- text = rt.sideenv_pyproject()- assert 'hindsight-embed==0.9.2' in text- assert 'hindsight-api-slim[all]==0.9.2' in text # [all]: full feature parity- assert 'requires-python = ">=3.11"' in text---# -- ensure_sideenv: candidate build -> atomic commit via the pm uv bridge -----+def test_ensure_sideenv_uses_pm_selected_python(side_root, monkeypatch):+ import pm+ from hermes_constants import venv_python_path-def test_ensure_sideenv_builds_and_publishes_generation(side_root, monkeypatch):- calls = []+ python = venv_python_path(side_root / "selected")+ seen = {}- def fake_bridge(venv):- calls.append(("bridge", venv))- return "uv-bin", {"VIRTUAL_ENV": str(venv), "UV_PYTHON": "pm-python"}+ def ensure(name, requirements, **kwargs):+ seen.update(name=name, requirements=requirements, **kwargs)+ return python- def fake_run(cmd, **kwargs):- calls.append(("run", cmd, kwargs["env"]))- return _fake_completed()+ monkeypatch.setattr(pm, "ensure_environment", ensure)+ assert rt.ensure_sideenv() == python+ assert seen == dict(+ name="hindsight", requirements=(f"hindsight-embed=={rt._EMBED_VERSION}",+ f"hindsight-api-slim[all]=={rt._API_SLIM_VERSION}"),+ root=side_root, explicit=True, timeout=3600,+ )- monkeypatch.setattr(rt, "_uv_bridge", fake_bridge)- monkeypatch.setattr(rt.subprocess, "run", fake_run)- gen = rt.ensure_sideenv()-- # The generation was built at its FINAL path (no rename), published by the- # selection record, and no candidate/prev leftovers exist.- assert gen.is_dir() and gen.name.startswith("gen-")- assert rt.sideenv_pyproject() in (gen / "pyproject.toml").read_text(encoding="utf-8")- assert json.loads((gen / _STATE).read_text(encoding="utf-8"))["pins"] == rt._EXPECTED- assert json.loads((side_root / "active.json").read_text(encoding="utf-8"))["generation"] == gen.name- assert [p for p in side_root.iterdir() if p.is_dir()] == [gen]- # uv invoked for lock+sync against the generation's own venv.- runs = [c for c in calls if c[0] == "run"]- assert [c[1][1] for c in runs] == ["lock", "sync"]- assert all(c[2]["VIRTUAL_ENV"].endswith(".venv") for c in runs)- assert all(c[2]["UV_PYTHON"] == "pm-python" for c in runs)- assert calls[0][1] == gen / ".venv"---def test_ensure_sideenv_short_circuits_when_current(side_root, monkeypatch):- gen = side_root / "gen-1"- gen.mkdir(parents=True)- (side_root / "active.json").write_text(json.dumps({"generation": "gen-1", "pins": rt._EXPECTED}), encoding="utf-8")- (gen / _STATE).write_text(json.dumps({"pins": rt._EXPECTED}), encoding="utf-8")+def test_sideenv_python_is_pm_passive_selection(side_root, monkeypatch):+ import pmfrom hermes_constants import venv_python_path- py = venv_python_path(gen / ".venv")- py.parent.mkdir(parents=True, exist_ok=True)- py.write_bytes(b"")- monkeypatch.setattr(rt, "_uv_bridge", lambda venv: pytest.fail("bridge used for an up-to-date env"))- assert rt.ensure_sideenv() == gen---def test_ensure_sideenv_failure_preserves_previous_generation(side_root, monkeypatch):- old = side_root / "gen-old"- old.mkdir(parents=True)- (old / "keep.txt").write_text("old", encoding="utf-8")- (side_root / "active.json").write_text(json.dumps({"generation": "gen-old"}), encoding="utf-8")-- def boom(*a, **kw):- raise RuntimeError("uv sync failed: disk full")-- monkeypatch.setattr(rt, "_uv_bridge", boom)- with pytest.raises(RuntimeError, match="disk full"):- rt.ensure_sideenv()- # Previous generation untouched and still the published one; the failed- # unpublished generation is gone.- assert (old / "keep.txt").read_text(encoding="utf-8") == "old"- assert json.loads((side_root / "active.json").read_text(encoding="utf-8"))["generation"] == "gen-old"- assert [p for p in side_root.iterdir() if p.is_dir()] == [old]+ python = venv_python_path(side_root / "selected")+ seen = []+ monkeypatch.setattr(pm, "environment_python",+ lambda name, **kw: seen.append((name, kw)) or python)+ assert rt.sideenv_python() == python+ assert seen == [("hindsight", {"root": side_root})]+ assert not side_root.exists()# -- runtime probe: side interpreter, never the boot env ----------------------def test_check_local_runtime_probes_the_side_python(side_root, monkeypatch):- py = _install_side_python(side_root)+ py = _install_side_python(side_root, monkeypatch)seen = {}def fake_run(cmd, **kw):@@ -128,7 +82,7 @@ def test_check_local_runtime_probes_the_side_python(side_root, monkeypatch):def test_check_local_runtime_reports_probe_failure(side_root, monkeypatch):- _install_side_python(side_root)+ _install_side_python(side_root, monkeypatch)monkeypatch.setattr(rt.subprocess, "run",lambda cmd, **kw: _fake_completed(returncode=1, stderr="Illegal instruction (core dumped)"),@@ -168,24 +122,19 @@ def loopback_health():server.server_close()-def _install_side_python(side_root, name="gen-1"):- """A minimal 'installed' generation: selection record + interpreter file- (laid out by the canonical venv_python_path, so the test matches the- platform layout the runtime itself resolves)."""+def _install_side_python(side_root, monkeypatch):+ """A daemon/probe test needs a selected interpreter, not PM's record format."""from hermes_constants import venv_python_path- gen = side_root / name- py = venv_python_path(gen / ".venv")- py.parent.mkdir(parents=True, exist_ok=True)- (side_root / "active.json").write_text(json.dumps({"generation": name}), encoding="utf-8")- py.write_bytes(b"")- return py+ python = venv_python_path(side_root / "selected")+ monkeypatch.setattr(rt, "sideenv_python", lambda root=None: python)+ return pythondef test_ensure_daemon_url_from_sideenv_output_is_reachable(side_root, monkeypatch, loopback_health):"""The bridge subprocess reports the URL the side env resolved (here: a realloopback /health server) — the plugin never invents a port."""- py = _install_side_python(side_root)+ py = _install_side_python(side_root, monkeypatch)seen = {}def fake_run(cmd, *, env=None, **kw):@@ -209,7 +158,7 @@ def test_ensure_daemon_url_from_sideenv_output_is_reachable(side_root, monkeypatdef test_ensure_daemon_env_carries_grace_and_version_pin(side_root, monkeypatch, loopback_health):- _install_side_python(side_root)+ _install_side_python(side_root, monkeypatch)captured = {}def fake_run(cmd, *, env=None, **kw):@@ -238,7 +187,7 @@ def test_ensure_daemon_missing_runtime_raises_with_hint(side_root, monkeypatch):def test_ensure_daemon_bridge_failure_surfaces(side_root, monkeypatch):- _install_side_python(side_root)+ _install_side_python(side_root, monkeypatch)monkeypatch.setattr(rt.subprocess, "run",lambda cmd, **kw: _fake_completed(returncode=1, stderr="boom inside side env"),@@ -248,7 +197,7 @@ def test_ensure_daemon_bridge_failure_surfaces(side_root, monkeypatch):def test_ensure_daemon_not_ok_surfaces_bridge_error(side_root, monkeypatch):- _install_side_python(side_root)+ _install_side_python(side_root, monkeypatch)monkeypatch.setattr(rt.subprocess, "run",lambda cmd, **kw: _fake_completed(@@ -275,7 +224,7 @@ def test_local_runtime_hint_points_at_isolated_install(side_root):def test_trace_logs_on_daemon_start_and_ready(side_root, monkeypatch, caplog, loopback_health):- _install_side_python(side_root)+ _install_side_python(side_root, monkeypatch)monkeypatch.setattr(rt.subprocess, "run",lambda cmd, **kw: _fake_completed(stdout=f"{rt._BRIDGE_MARKER}" + json.dumps({"ok": True, "url": loopback_health})),@@ -288,7 +237,7 @@ def test_trace_logs_on_daemon_start_and_ready(side_root, monkeypatch, caplog, lodef test_trace_logs_on_startup_failure(side_root, monkeypatch, caplog):- _install_side_python(side_root)+ _install_side_python(side_root, monkeypatch)monkeypatch.setattr(rt.subprocess, "run",lambda cmd, **kw: _fake_completed(returncode=1, stderr="no dice"),diff --git a/tests/tools/conftest.py b/tests/tools/conftest.pyindex f5c2c431fd2..f975abaee2d 100644--- a/tests/tools/conftest.py+++ b/tests/tools/conftest.py@@ -15,10 +15,10 @@ import pytest@pytest.fixture(autouse=True)def _no_host_browser_use_cli():- """Keep the host's browser-use/uvx install out of tests.+ """Keep the host's PM-managed browser-use install out of tests.Browser Use mode is default-on when the CLI is runnable, so a developer- machine with uvx on PATH would silently flip every built-in-browser test+ machine with the CLI installed would silently flip every built-in-browser testinto CLI mode. Pin discovery to "not installed"; tests that exercise theCLI path monkeypatch ``bu_cli._find_cli`` themselves."""@@ -28,7 +28,7 @@ def _no_host_browser_use_cli():yieldreturn# Keep a handle to the real discovery function so TestFindCli (and any- # test that wants genuine PATH probing) can restore it explicitly.+ # test that wants genuine PM discovery) can restore it explicitly.if not hasattr(bu_cli, "_find_cli_unpatched"):bu_cli._find_cli_unpatched = bu_cli._find_cliwith patch.object(bu_cli, "_find_cli", lambda: None):diff --git a/tests/tools/test_browser_use_cli.py b/tests/tools/test_browser_use_cli.pyindex 54214e19c1c..17d5f8dfeca 100644--- a/tests/tools/test_browser_use_cli.py+++ b/tests/tools/test_browser_use_cli.py@@ -288,58 +288,17 @@ class TestVaultSupervisorAttach:class TestFindCli:- """The tests/tools conftest pins _find_cli to None (host isolation);- exercise the real function via the preserved _find_cli_unpatched."""-- def test_prefers_installed_binary(self, monkeypatch):- monkeypatch.setattr(- bu_cli.shutil, "which",- lambda name, path=None: "/usr/local/bin/browser-use" if name == "browser-use" and path is None else ("/usr/local/bin/uvx" if path is None else None),- )- assert bu_cli._find_cli_unpatched() == ["/usr/local/bin/browser-use"]-- def test_falls_back_to_uvx(self, monkeypatch, tmp_path):- """PM owns the executable spelling and the interpreter environment."""+ def test_uses_only_pm_selected_tool(self, monkeypatch, tmp_path):import pm- import subprocess-- executable = str(tmp_path / "chosen-by-pm.bin")- calls = []- def managed(command="uv", *, realize=True, base_env=None):- calls.append((command, realize))- return executable, {**(base_env or {}), "UV_PYTHON": "pm-python"}- monkeypatch.setattr(pm, "uv", managed)- monkeypatch.setattr(bu_cli.shutil, "which", lambda name, path=None: None)- assert bu_cli._find_cli_unpatched() == [executable, "browser-use"]- assert calls == [("uvx", False)]- monkeypatch.setattr(bu_cli, "_find_cli", bu_cli._find_cli_unpatched)- monkeypatch.setattr(bu_cli, "_base_subprocess_env", lambda: {"BROWSER_SETTING": "preserved"})- monkeypatch.setattr(bu_cli, "_route_backend", lambda *args: None)- seen = {}- def run(cmd, code, env, timeout):- seen.update(cmd=cmd, env=env, input=code)- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")- monkeypatch.setattr(bu_cli, "_run_cli_killing_process_group", run)- result = json.loads(bu_cli.browser_exec("print(1)"))- assert result["success"] is True- assert calls[-1] == ("uvx", True)- assert seen["cmd"] == [executable, "browser-use"]- assert seen["env"]["UV_PYTHON"] == "pm-python"- assert seen["env"]["BROWSER_SETTING"] == "preserved"- assert seen["input"] == "print(1)"-- def test_bare_path_uvx_not_consulted(self, monkeypatch):- """Kill the PATH probe: a uvx reachable only via bare PATH is not- used — without the pinned pm uvx there is no zero-install rung."""- monkeypatch.setattr(bu_cli, "_pinned_uvx", lambda: None)- monkeypatch.setattr(- bu_cli.shutil, "which",- lambda name, path=None: "/usr/local/bin/uvx" if name == "uvx" and path is None else None,- )- assert bu_cli._find_cli_unpatched() is None+ selected = tmp_path / "pm-generation" / "browser-use"+ monkeypatch.setattr(pm, "python_tool", lambda name, executable: selected)+ monkeypatch.setattr(shutil, "which", lambda *a, **kw: "/unmanaged/browser-use")+ assert bu_cli._find_cli_unpatched() == [str(selected)]- def test_none_when_neither_available(self, monkeypatch):- monkeypatch.setattr(bu_cli.shutil, "which", lambda name, path=None: None)+ def test_missing_managed_tool_does_not_use_path(self, monkeypatch):+ import pm+ monkeypatch.setattr(pm, "python_tool", lambda *a, **kw: None)+ monkeypatch.setattr(shutil, "which", lambda *a, **kw: "/unmanaged/browser-use")assert bu_cli._find_cli_unpatched() is None@@ -952,14 +911,14 @@ class TestSkillTextDescription:def test_static_fallback_carries_digest_and_install_hint(self):desc = bu_cli.BROWSER_EXEC_SCHEMA["description"]assert bu_cli._HELPERS_DIGEST in desc- assert "uv tool install browser-use" in desc+ assert "hermes tools" in descclass TestBrowserExec:def test_missing_cli_returns_install_hint(self, monkeypatch):monkeypatch.setattr(bu_cli, "_find_cli", lambda: None)result = json.loads(bu_cli.browser_exec("print(page_info())"))- assert "uv tool install browser-use" in result["error"]+ assert "hermes tools" in result["error"]def test_empty_code_rejected(self):result = json.loads(bu_cli.browser_exec(" "))@@ -1008,180 +967,36 @@ class TestBrowserExec:assert "timed out" in result["error"]-class TestFindCliManagedBin:- """MANAGED-FIRST: _find_cli probes $HERMES_HOME/bin before PATH and- ~/.local/bin, so the Hermes-installed copy always wins."""-- @pytest.fixture(autouse=True)- def _hermetic_home(self, tmp_path, monkeypatch):- """Pin HOME so the ~/.local/bin probe can't leak the host's real- user-level installs into these real-PATH-probing tests."""- monkeypatch.setenv("HOME", str(tmp_path / "userhome"))- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))- monkeypatch.setenv("PATH", str(tmp_path / "empty"))-- @pytest.mark.platforms("linux")- def test_managed_bin_browser_use_found(self, tmp_path, monkeypatch):- bin_dir = tmp_path / "home" / "bin"- bin_dir.mkdir(parents=True)- bu = bin_dir / "browser-use"- bu.write_text("#!/bin/sh\n", encoding="utf-8")- bu.chmod(bu.stat().st_mode | stat.S_IXUSR)- assert bu_cli._find_cli_unpatched() == [str(bu)]-- @pytest.mark.platforms("linux")- def test_managed_bin_uvx_fallback(self, tmp_path, monkeypatch):- bin_dir = tmp_path / "home" / "bin"- bin_dir.mkdir(parents=True)- uvx = bin_dir / "uvx"- uvx.write_text("#!/bin/sh\n", encoding="utf-8")- uvx.chmod(uvx.stat().st_mode | stat.S_IXUSR)- assert bu_cli._find_cli_unpatched() == [str(uvx), "browser-use"]-- def test_nothing_found(self, tmp_path, monkeypatch):- assert bu_cli._find_cli_unpatched() is None-- @pytest.mark.platforms("linux")- def test_user_local_bin_browser_use_found(self, tmp_path, monkeypatch):- """#83788: Desktop/TUI workers spawn with a minimal PATH that omits- ~/.local/bin, where `uv tool install browser-use` links the binary- by default — _find_cli must probe it explicitly."""- cli_dir = tmp_path / "userhome" / ".local" / "bin"- cli_dir.mkdir(parents=True)- cli = cli_dir / "browser-use"- cli.write_text("#!/bin/sh\n", encoding="utf-8")- cli.chmod(cli.stat().st_mode | stat.S_IXUSR)- assert bu_cli._find_cli_unpatched() == [str(cli)]-- @pytest.mark.platforms("linux")- def test_managed_bin_precedes_user_local_bin(self, tmp_path, monkeypatch):- """MANAGED-FIRST: Hermes' managed copy wins over a user-level side- install — every backend selection provisions/updates the managed- copy, so resolution must land on the binary we control (no version- drift from stray `uv tool install` runs)."""- user_dir = tmp_path / "userhome" / ".local" / "bin"- user_dir.mkdir(parents=True)- user_cli = user_dir / "browser-use"- user_cli.write_text("#!/bin/sh\n", encoding="utf-8")- user_cli.chmod(user_cli.stat().st_mode | stat.S_IXUSR)- managed_dir = tmp_path / "home" / "bin"- managed_dir.mkdir(parents=True)- managed_cli = managed_dir / "browser-use"- managed_cli.write_text("#!/bin/sh\n", encoding="utf-8")- managed_cli.chmod(managed_cli.stat().st_mode | stat.S_IXUSR)- assert bu_cli._find_cli_unpatched() == [str(managed_cli)]-- @pytest.mark.platforms("linux")- def test_managed_bin_precedes_path(self, tmp_path, monkeypatch):- """MANAGED-FIRST: the managed copy also wins over one on PATH."""- path_dir = tmp_path / "onpath"- path_dir.mkdir()- path_cli = path_dir / "browser-use"- path_cli.write_text("#!/bin/sh\n", encoding="utf-8")- path_cli.chmod(path_cli.stat().st_mode | stat.S_IXUSR)- monkeypatch.setenv("PATH", str(path_dir))- managed_dir = tmp_path / "home" / "bin"- managed_dir.mkdir(parents=True)- managed_cli = managed_dir / "browser-use"- managed_cli.write_text("#!/bin/sh\n", encoding="utf-8")- managed_cli.chmod(managed_cli.stat().st_mode | stat.S_IXUSR)- assert bu_cli._find_cli_unpatched() == [str(managed_cli)]-- @pytest.mark.platforms("linux")- def test_user_local_bin_uvx_fallback(self, tmp_path, monkeypatch):- cli_dir = tmp_path / "userhome" / ".local" / "bin"- cli_dir.mkdir(parents=True)- uvx = cli_dir / "uvx"- uvx.write_text("#!/bin/sh\n", encoding="utf-8")- uvx.chmod(uvx.stat().st_mode | stat.S_IXUSR)- assert bu_cli._find_cli_unpatched() == [str(uvx), "browser-use"]--class TestInstallCli:- def test_path_install_does_not_short_circuit(self, tmp_path, monkeypatch):- """MANAGED-FIRST: a browser-use on PATH is a user-level side install- and must NOT satisfy install_cli() — only the managed copy does,- otherwise resolution stays pinned to a binary Hermes can't update."""- cli = _fake_cli(tmp_path, "")- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))- monkeypatch.setattr(bu_cli.shutil, "which", lambda name, path=None: cli if name == "browser-use" and path is None else None)- import sys as _sys- import types as _types+ def test_installs_through_pm_even_with_an_unmanaged_binary(self, tmp_path, monkeypatch):import pm- monkeypatch.setattr(pm, "uv", lambda **kw: (None, {}))- ok, msg = bu_cli.install_cli()- # No uv available in this fixture, so the attempted managed install- # fails — the point is that the PATH copy did not short-circuit.- assert ok is False- assert "already installed" not in msg+ selected = tmp_path / "pm-generation" / "browser-use"+ seen = {}- @pytest.mark.platforms("linux")- def test_already_installed_in_managed_bin(self, tmp_path, monkeypatch):- bin_dir = tmp_path / "home" / "bin"- bin_dir.mkdir(parents=True)- cli = bin_dir / "browser-use"- cli.write_text("#!/bin/sh\n", encoding="utf-8")- cli.chmod(cli.stat().st_mode | stat.S_IXUSR)- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))- monkeypatch.setenv("PATH", str(tmp_path / "empty"))- ok, msg = bu_cli.install_cli()- assert ok is True- assert "already installed" in msg+ def install(name, requirements, executable, **kwargs):+ seen.update(name=name, requirements=requirements, executable=executable, **kwargs)+ return selected- def test_no_uv_anywhere_fails_with_guidance(self, tmp_path, monkeypatch):- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))- monkeypatch.setenv("PATH", str(tmp_path / "empty"))- import sys as _sys- import types as _types- import pm- monkeypatch.setattr(pm, "uv", lambda **kw: (None, {}))- ok, msg = bu_cli.install_cli()- assert ok is False- assert "uv" in msg+ monkeypatch.setattr(pm, "ensure_python_tool", install)+ monkeypatch.setattr(shutil, "which", lambda *a, **kw: "/unmanaged/browser-use")+ ok, message = bu_cli.install_cli(timeout_s=321)+ assert ok, message+ assert str(selected) in message+ assert seen == dict(name="browser-use", requirements=bu_cli._CLI_REQUIREMENTS,+ executable="browser-use", explicit=True, timeout=321)- @pytest.mark.platforms("linux")- def test_successful_install_via_fake_uv(self, tmp_path, monkeypatch):- home = tmp_path / "home"- bin_dir = home / "bin"- bin_dir.mkdir(parents=True)- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setenv("PATH", str(tmp_path / "empty"))- # install_cli verifies via _find_cli(), which the tests/tools conftest- # pins to None — restore the real resolver for this test.- monkeypatch.setattr(bu_cli, "_find_cli", bu_cli._find_cli_unpatched)- # fake uv: `uv tool install browser-use` drops a binary into UV_TOOL_BIN_DIR.- # Absolute /bin/chmod: PATH is emptied above, so bare chmod won't resolve.- uv = tmp_path / "uv"- uv.write_text(- "#!/bin/sh\n"- 'target="$UV_TOOL_BIN_DIR/browser-use"\n'- 'echo "#!/bin/sh" > "$target"\n'- '/bin/chmod +x "$target"\n'- , encoding="utf-8")- uv.chmod(uv.stat().st_mode | stat.S_IXUSR)- import sys as _sys- import types as _types+ def test_pm_install_failure_is_actionable(self, monkeypatch):import pm- monkeypatch.setattr(pm, "uv", lambda **kw: (str(uv), dict(os.environ)))- ok, msg = bu_cli.install_cli()- assert ok is True, msg- assert (bin_dir / "browser-use").exists()- @pytest.mark.platforms("linux")- def test_failed_install_surfaces_stderr_tail(self, tmp_path, monkeypatch):- home = tmp_path / "home"- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setenv("PATH", str(tmp_path / "empty"))- uv = tmp_path / "uv"- uv.write_text('#!/bin/sh\necho "no network" >&2\nexit 1\n', encoding="utf-8")- uv.chmod(uv.stat().st_mode | stat.S_IXUSR)- import sys as _sys- import types as _types- import pm- monkeypatch.setattr(pm, "uv", lambda **kw: (str(uv), dict(os.environ)))- ok, msg = bu_cli.install_cli()- assert ok is False- assert "no network" in msg+ def fail(*args, **kwargs):+ raise RuntimeError("network unavailable; retry hermes tools")++ monkeypatch.setattr(pm, "ensure_python_tool", fail)+ monkeypatch.setattr(shutil, "which", lambda *a, **kw: None)+ ok, message = bu_cli.install_cli()+ assert not ok+ assert "network unavailable" in message+ assert "hermes tools" in messageclass TestDefaultDowngradeNotice:diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex 874d04850f3..265a0b824d0 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -10,7 +10,6 @@ import jsonimport loggingimport osimport re-import shutilimport signalimport subprocessimport time@@ -139,7 +138,7 @@ def _blocked_url_in_code(code: str) -> Optional[str]:def _base_subprocess_env() -> dict:from tools.browser_tool import _build_browser_envenv = _build_browser_env()- # The CLI runs under its own Python (uv tool / uvx); an inherited PYTHONPATH/PYTHONHOME+ # The CLI runs under its own PM-managed Python; an inherited PYTHONPATH/PYTHONHOME# (Hermes's venv) wins over its site-packages → wrong-ABI C-extensions and a crash.# PYTHONPATH/PYTHONHOME inherited from the agent process point at Hermes's venv site-packages, and a# child interpreter honors them ahead of its own site-packages — so the CLI imports compiled@@ -154,10 +153,11 @@ def _base_subprocess_env() -> dict:def _floor_subprocess_path(path: str) -> str:- """Guarantee core system dirs on the CLI subprocess PATH: profile workers (kanban bots, cron) can inherit- a PATH of only version-manager dirs, and the uv binary's POSIX sh trampoline resolves ``dirname``/``realpath``- via PATH (exit 127 without /usr/bin). Reuses browser_tool's ``_merge_browser_path`` floor, else appends- FHS bin dirs. Windows .cmd shims don't trampoline: no-op there."""+ """Keep system commands reachable from profile workers with a minimal PATH.++ Browser subprocesses may launch shell helpers; version-manager-only paths+ omit /usr/bin. Reuse the shared browser PATH floor on POSIX.+ """if os.name == "nt":return pathwith contextlib.suppress(Exception):@@ -203,7 +203,7 @@ def is_legacy_browser_use_cloud_config(browser_cfg: dict) -> bool:def is_browser_use_cli_mode() -> bool:"""True when the Browser Use CLI replaces the built-in browser stack. Browser Use mode is the DEFAULT:- unset ``browser.backend`` ("") enables it whenever the CLI is runnable (installed binary or uvx);+ unset ``browser.backend`` ("") enables it whenever the PM-managed CLI is installed;``browser.backend: off`` keeps the built-in browser_* tools. Camofox always falls back to the built-intools (Firefox, custom HTTP API, no CDP surface for the harness)."""if _camofox_active():@@ -234,112 +234,28 @@ def default_downgrade_notice() -> Optional[str]:return None-def _managed_bin_dir() -> str:- """$HERMES_HOME/bin — where install.sh puts uv/uvx and install_cli() links browser-use."""- return str(Path(get_hermes_home()) / "bin")---def _pinned_uvx() -> Optional[str]:- """Read-only lookup of PM's uvx executable."""- try:- import pm-- uvx, _env = pm.uv("uvx", realize=False)- return uvx- except Exception as e: # pragma: no cover — defensive- logger.debug("Could not resolve pinned uvx: %s", e)- return None+_CLI_REQUIREMENTS = ("browser-use==0.13.10",)def _find_cli() -> Optional[List[str]]:- """Locate the browser-use CLI, or None when it can't be run.-- MANAGED-FIRST resolution: Hermes' own ``$HERMES_HOME/bin`` copy — the- one every browser backend selection installs and updates via- ``install_cli()`` — always wins, so all sessions drive one canonical,- Hermes-controlled binary. PATH and the user-level tool dir- (~/.local/bin / %APPDATA%\\uv\\bin, where a manual ``uv tool install``- links binaries) are fallbacks for setups that never ran our install,- and cover Desktop/TUI workers that spawn with a minimal PATH. The uvx- zero-install path is the final fallback — the pinned uvx from pm's- store first, then the Hermes-owned bin dir and the user-level tool- dir. A bare PATH uvx probe is deliberately absent: pm names the- pinned binary, and a PATH uvx is an unknown version.- """- if os.name == "nt":- appdata = os.environ.get("APPDATA")- user_bin = str(Path(appdata) / "uv" / "bin") if appdata else None- else:- user_bin = str(Path(os.path.expanduser("~")) / ".local" / "bin")- probe_paths = (_managed_bin_dir(), None, user_bin)- for probe_path in probe_paths:- if probe_path is None or probe_path:- direct = shutil.which("browser-use", path=probe_path)- if direct:- return [direct]- uvx = _pinned_uvx()- if uvx is not None:- return [uvx, "browser-use"]- for probe_path in (_managed_bin_dir(), user_bin):- if probe_path:- uvx = shutil.which("uvx", path=probe_path)- if uvx:- return [uvx, "browser-use"]- return None---def install_cli(timeout_s: int = 600) -> Tuple[bool, str]:- """Install the browser-use CLI persistently via ``uv tool install``.+ """Read PM's selected CLI without installing anything during discovery."""+ import pm- PM supplies both uv and its base Python. The binary is linked- into ``$HERMES_HOME/bin`` (``UV_TOOL_BIN_DIR``) so ``_find_cli()``- resolves it for every profile without touching the user's PATH.+ binary = pm.python_tool("browser-use", "browser-use")+ return [str(binary)] if binary is not None else None- Returns ``(ok, message)`` — never raises.- """- # MANAGED-FIRST: only the managed copy short-circuits the install. A- # browser-use found on PATH is a user-level side install — it must NOT- # prevent provisioning the canonical Hermes-managed copy, or resolution- # stays pinned to a binary we don't control (version drift, no updates- # through hermes tools).- bin_dir = _managed_bin_dir()- managed = shutil.which("browser-use", path=bin_dir)- if managed:- return True, f"browser-use CLI already installed ({managed})"+def install_cli(timeout_s: int = 600) -> Tuple[bool, str]:+ """Provision the pinned CLI in PM's isolated environment; never raises."""try:import pm- uv_bin, env = pm.uv()- except Exception as e:- return False, f"PM's uv/Python toolchain is unavailable: {e}"- if not uv_bin:- return False, "PM's uv/Python toolchain is unavailable; run `hermes pm install`."-- env["UV_NO_CONFIG"] = "1"- if bin_dir:- try:- Path(bin_dir).mkdir(parents=True, exist_ok=True)- env["UV_TOOL_BIN_DIR"] = bin_dir- except OSError as e:- logger.debug("Could not prepare %s: %s", bin_dir, e)-- try:- result = subprocess.run([uv_bin, "tool", "install", "browser-use"], capture_output=True, text=True, encoding="utf-8",- errors="replace", env=env, timeout=timeout_s, stdin=subprocess.DEVNULL)- except subprocess.TimeoutExpired:- return False, f"`uv tool install browser-use` timed out after {timeout_s}s"- except Exception as e:- return False, f"Failed to run `uv tool install browser-use`: {e}"-- if result.returncode != 0:- tail = "\n".join((result.stderr or result.stdout or "").strip().splitlines()[-3:])- return False, f"`uv tool install browser-use` failed:\n{tail}"- found = _find_cli()- if not found or len(found) != 1:- return False, ("install reported success but the browser-use binary is still not resolvable — "- "run `uv tool install browser-use` manually")- return True, f"browser-use CLI installed ({found[0]})"+ binary = pm.ensure_python_tool(+ "browser-use", _CLI_REQUIREMENTS, "browser-use", explicit=True, timeout=timeout_s,+ )+ except Exception as exc:+ return False, f"Could not install browser-use CLI: {exc}"+ return True, f"browser-use CLI installed ({binary})"def _workspace_dir(task_id: Optional[str]) -> Optional[str]:@@ -635,21 +551,10 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUTcmd = _find_cli()if not cmd:- return tool_error("browser-use CLI not found on PATH, and uvx is unavailable for a zero-install run. "- "Install it with `uv tool install browser-use` (or `pipx install browser-use`), "- "then run `browser-use --doctor` to verify the setup.")+ return tool_error("The PM-managed browser-use CLI is not installed. "+ "Run `hermes tools` (Browser Automation → Browser Use) to install it.")env = _base_subprocess_env()- if len(cmd) > 1:- try:- import pm-- uvx, env = pm.uv("uvx", base_env=env)- if not uvx:- return tool_error("PM's uv/Python toolchain is unavailable; run `hermes pm install`.")- cmd = [uvx, *cmd[1:]]- except Exception as e:- return tool_error(f"PM's uv/Python toolchain is unavailable: {e}")if session:if not _SESSION_RE.match(session):return tool_error(f"Invalid session name {session!r}: use 1-64 letters, digits, "@@ -788,9 +693,9 @@ def _dynamic_schema_overrides() -> dict:BROWSER_EXEC_SCHEMA = {"name": "browser_exec",- # Static fallback description, used only when the CLI (and uvx) is unavailable+ # Static fallback description, used only when the managed CLI is unavailable"description": (_HEADER_BASE + _HELPERS_DIGEST- + "\n\n(The browser-use CLI is not installed yet. Install it with `uv tool install browser-use`.)"),+ + "\n\n(The browser-use CLI is not installed yet. Install it with `hermes tools` (Browser Automation → Browser Use).)"),"parameters": {"type": "object","properties": {