The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(computer-use): enforce existing-profile grant, unblock the opt-in
Francesco Bonacci9a96fdc5b8c0
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 4e4f3e9ae30..103109bac28 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -12696,6 +12696,7 @@ def main():install_cua_driver(upgrade=bool(getattr(args, "upgrade", False)))returnif action == "status":+ import os as _osimport subprocessfrom hermes_cli.tools_config import _cua_driver_contract_statusfrom tools.computer_use.cua_backend import (@@ -12705,6 +12706,7 @@ def main():# Must match the runtime resolver: Desktop/TUI processes can omit# ~/.local/bin even though the official installer put the driver there.path = resolve_cua_driver_cmd()+ override = _os.environ.get("HERMES_CUA_DRIVER_CMD", "").strip()if path:version = ""try:@@ -12716,17 +12718,30 @@ def main():).stdout.strip()except Exception:pass+ from hermes_cli.tools_config import _cua_version_summary+ version = _cua_version_summary(version)+ # Name the override here too. Without it the operator is told+ # to repair an install that `hermes computer-use install` will+ # (correctly) refuse to touch, with nothing pointing at the+ # env var that actually selected the binary.+ origin = " [custom binary from HERMES_CUA_DRIVER_CMD]" if override else ""if version:- print(f"cua-driver: installed at {path} ({version})")+ print(f"cua-driver: installed at {path}{origin} ({version})")else:- print(f"cua-driver: installed at {path}")+ print(f"cua-driver: installed at {path}{origin}")contract = _cua_driver_contract_status(path)if not contract.get("ready"):print(" ⚠ Repair required: "+ (contract.get("reason") or "runtime contract is incomplete"))- print(" Run: hermes computer-use install")+ if override:+ print(+ " Update the binary selected by HERMES_CUA_DRIVER_CMD, or unset "+ "the override and run: hermes computer-use install --upgrade"+ )+ else:+ print(" Run: hermes computer-use install")returntry:st = cua_driver_update_check()diff --git a/hermes_cli/tools_config.py b/hermes_cli/tools_config.pyindex 1a65dcc1bbc..846a6857c84 100644--- a/hermes_cli/tools_config.py+++ b/hermes_cli/tools_config.py@@ -770,6 +770,23 @@ def _cua_driver_cmd() -> str:return os.environ.get("HERMES_CUA_DRIVER_CMD", "").strip() or "cua-driver"+def _cua_version_summary(raw: str, *, limit: int = 120) -> str:+ """Reduce a driver's ``--version`` output to one short status line.++ A binary selected by ``HERMES_CUA_DRIVER_CMD`` is not obliged to answer+ ``--version`` the way cua-driver does. Pointing the override at, say,+ ``cmd.exe`` yields a multi-line banner plus a prompt, which used to be+ interpolated verbatim into ``cua-driver: installed at ... (<version>)``+ and shattered the one-line summary. Keep the first non-empty line and+ bound its length.+ """+ for line in (raw or "").splitlines():+ text = line.strip()+ if text:+ return text[:limit]+ return ""++def _resolved_cua_driver_cmd() -> Optional[str]:"""Resolve cua-driver exactly as the runtime and Desktop status do."""from tools.computer_use.cua_backend import resolve_cua_driver_cmddiff --git a/tests/hermes_cli/test_install_cua_driver.py b/tests/hermes_cli/test_install_cua_driver.pyindex bc9152e123a..03e7012fcee 100644--- a/tests/hermes_cli/test_install_cua_driver.py+++ b/tests/hermes_cli/test_install_cua_driver.py@@ -1244,3 +1244,42 @@ class TestWindowsAutostartRepair:assert "-ArgumentList @('autostart','enable')" in ps_commandassert f"$exe = '{driver}'" in ps_commandassert f"& {driver}" not in ps_command+++class TestCuaVersionSummary:+ """`hermes computer-use status` prints one line, whatever the binary says.++ A binary chosen by HERMES_CUA_DRIVER_CMD is under no obligation to answer+ `--version` the way cua-driver does, and its output used to be spliced+ verbatim into the status line.+ """++ @staticmethod+ def _summary(raw, **kw):+ from hermes_cli import tools_config++ return tools_config._cua_version_summary(raw, **kw)++ def test_plain_version_passes_through(self):+ assert self._summary("cua-driver 0.20.0") == "cua-driver 0.20.0"++ def test_multiline_banner_collapses_to_first_line(self):+ banner = (+ "Microsoft Windows [Version 10.0.26200.9168]\n"+ "(c) Microsoft Corporation. All rights reserved.\n"+ "\n"+ "C:\\Users\\demo>"+ )+ summary = self._summary(banner)+ assert summary == "Microsoft Windows [Version 10.0.26200.9168]"+ assert "\n" not in summary++ def test_leading_blank_lines_skipped(self):+ assert self._summary("\n\n cua-driver 0.20.0 ") == "cua-driver 0.20.0"++ def test_long_line_is_bounded(self):+ assert len(self._summary("x" * 500)) == 120++ def test_empty_output_stays_empty(self):+ assert self._summary("") == ""+ assert self._summary(" \n \n") == ""diff --git a/tests/tools/test_computer_use_browser_authorization.py b/tests/tools/test_computer_use_browser_authorization.pyindex 1d8cc5fd182..ed72f8a0402 100644--- a/tests/tools/test_computer_use_browser_authorization.py+++ b/tests/tools/test_computer_use_browser_authorization.py@@ -53,6 +53,7 @@ def test_existing_profile_prepare_delegates_authorization_to_driver():pid=101,window_id=202,profile_mode="existing_profile",+ grant_existing_profile=True,)assert result["status"] == "ok"@@ -69,6 +70,152 @@ def test_existing_profile_prepare_delegates_authorization_to_driver():]+def test_existing_profile_prepare_refused_without_config_grant():+ driver = _PrepareDriver()+ result = _route(driver).prepare(+ pid=101,+ window_id=202,+ profile_mode="existing_profile",+ )++ assert result["status"] == "refused"+ assert result["code"] == "browser_existing_profile_not_granted"+ assert "computer_use.grant_existing_profile" in result["message"]+ # Never reached the driver: the host refuses before the transport.+ assert driver.calls == []+++def test_existing_profile_prepare_refused_in_unrestricted_without_grant():+ """An approval bypass must not stand in for the config grant.++ ``--yolo`` / ``-z`` give the session a private unrestricted daemon that+ answers every prepare, so without this host-side floor the documented+ ``grant_existing_profile: false`` default silently stopped protecting the+ live profile's pages, cookies, and storage.+ """+ driver = _PrepareDriver()+ result = _route(driver).prepare(+ pid=101,+ window_id=202,+ profile_mode="existing_profile",+ grant_existing_profile=False,+ permission_mode="unrestricted",+ )++ assert result["code"] == "browser_existing_profile_not_granted"+ assert driver.calls == []+++def test_existing_profile_prepare_bounded_mode_exempt_from_grant():+ """bounded's reviewed capability manifest is the authorization boundary."""+ driver = _PrepareDriver()+ result = _route(driver).prepare(+ pid=101,+ window_id=202,+ profile_mode="existing_profile",+ grant_existing_profile=False,+ permission_mode="bounded",+ )++ assert result["status"] == "ok"+ assert [name for name, _ in driver.calls] == ["browser_prepare"]+++def test_isolated_prepare_unaffected_by_the_grant():+ """The floor is scoped to existing_profile; isolated launches still work."""+ driver = _PrepareDriver()+ result = _route(driver).prepare(+ pid=101,+ profile_mode="isolated_new",+ allow_launch=True,+ grant_existing_profile=False,+ )++ assert result["status"] == "ok"+ assert [name for name, _ in driver.calls] == ["browser_prepare"]+++def test_backend_resolves_authorization_and_ignores_model_supplied_values(monkeypatch):+ """pid/window_id come from the model; the grant never does."""+ captured: Dict[str, Any] = {}++ class _Route:+ def prepare(self, **kwargs: Any) -> Dict[str, Any]:+ captured.update(kwargs)+ return {"status": "ok"}++ backend = cb.CuaDriverBackend.__new__(cb.CuaDriverBackend)+ backend.permission_mode = "unrestricted"+ monkeypatch.setattr(cb, "_cua_grant_existing_profile", lambda: False)+ monkeypatch.setattr(+ cb.CuaDriverBackend, "_browser_route", lambda self: _Route()+ )++ backend.typed_browser_prepare(+ pid=101,+ window_id=202,+ profile_mode="existing_profile",+ # A model that tries to grant itself access must be ignored.+ grant_existing_profile=True,+ permission_mode="bounded",+ )++ assert captured["grant_existing_profile"] is False+ assert captured["permission_mode"] == "unrestricted"+++# ── config grant stands in for the approval prompt ──────────────────────+++def _preauth(**cfg: Any):+ from tools.computer_use import tool as cu_tool++ return cu_tool._config_preauthorized+++def test_config_grant_preauthorizes_existing_profile_prepare(monkeypatch):+ """The durable opt-in is the authorization; re-prompting is redundant.++ It also made the documented opt-in unusable on non-interactive runs,+ where the prompt has nobody to answer it and the call dies on approval+ timeout rather than attaching.+ """+ monkeypatch.setattr(+ cb, "_computer_use_cfg", lambda: {"grant_existing_profile": True}+ )+ assert _preauth()(+ "cua_browser_prepare", {"profile_mode": "existing_profile"}+ ) is True+++def test_no_preauthorization_without_the_grant(monkeypatch):+ monkeypatch.setattr(cb, "_computer_use_cfg", dict)+ assert _preauth()(+ "cua_browser_prepare", {"profile_mode": "existing_profile"}+ ) is False+++def test_preauthorization_scoped_to_existing_profile(monkeypatch):+ """Isolated launches keep prompting even when the grant is on."""+ monkeypatch.setattr(+ cb, "_computer_use_cfg", lambda: {"grant_existing_profile": True}+ )+ assert _preauth()(+ "cua_browser_prepare", {"profile_mode": "isolated_new"}+ ) is False+ assert _preauth()("click", {"profile_mode": "existing_profile"}) is False+++def test_preauthorization_fails_closed_on_config_error(monkeypatch):+ def _boom():+ raise RuntimeError("config unreadable")++ monkeypatch.setattr(cb, "_computer_use_cfg", _boom)+ assert _preauth()(+ "cua_browser_prepare", {"profile_mode": "existing_profile"}+ ) is False++def test_dispatch_does_not_forward_removed_approval_token():from unittest.mock import Mockdiff --git a/tools/computer_use/browser_route.py b/tools/computer_use/browser_route.pyindex 7d724095560..55ff095021e 100644--- a/tools/computer_use/browser_route.py+++ b/tools/computer_use/browser_route.py@@ -374,6 +374,8 @@ class CuaTypedBrowserRoute:profile_mode: str,profile_name: Optional[str] = None,allow_launch: bool = False,+ grant_existing_profile: bool = False,+ permission_mode: str = "standard",) -> Dict[str, Any]:"""Run explicit setup through the driver's authoritative mode gate."""missing = self._require_tool("browser_prepare")@@ -391,10 +393,25 @@ class CuaTypedBrowserRoute:"browser_exact_target_required","Existing-profile attachment requires an exact positive pid and window_id pair.",)- # The driver owns the immutable standard/bounded/unrestricted- # decision. Standard fails closed without a certified host;- # bounded mode uses its approved capability manifest and explicit- # Hermes YOLO owns a private unrestricted daemon.+ # Host-side floor for the config grant. The driver owns the+ # immutable standard/bounded/unrestricted decision, but an+ # unrestricted daemon answers every prepare — so relying on the+ # driver alone let an approval bypass (`--yolo`, `-z`) silently+ # nullify `computer_use.grant_existing_profile: false` and expose+ # the live profile's pages, cookies, and storage over CDP.+ # Approval bypass is consent to skip *prompts*, not consent to+ # read an existing browser profile, so this key is enforced here+ # regardless of permission mode. bounded is exempt: its reviewed+ # capability manifest is the authorization boundary.+ if permission_mode != "bounded" and not grant_existing_profile:+ return _refusal(+ "browser_existing_profile_not_granted",+ "Attaching to an existing browser profile requires the "+ "one-time opt-in `computer_use.grant_existing_profile: "+ "true` in config.yaml. Hermes cannot grant this at "+ "runtime, and an approval bypass does not substitute for "+ "it. Use profile_mode=isolated_new to browse without it.",+ )self.state.clear()args: Dict[str, Any] = {"pid": exact_pid,diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.pyindex f866e47aeb0..53cd1f1ce28 100644--- a/tools/computer_use/cua_backend.py+++ b/tools/computer_use/cua_backend.py@@ -274,8 +274,14 @@ def _cua_grant_existing_profile() -> bool:``--grant existing-profile`` when it launches the standard-mode runtime.On macOS it also selects a private socket so the newly configuredCuaDriver.app runtime cannot collide with an already-running default- daemon. The setting never applies to bounded mode, where the manifest owns- authorization, or unrestricted mode, which already bypasses approvals.+ daemon. The setting never applies to bounded mode, where the reviewed+ capability manifest owns authorization.++ It DOES apply to unrestricted mode. An approval bypass (``--yolo``,+ ``-z``) is consent to skip prompts, not consent to read an existing+ browser profile's live pages, cookies, and storage, so the host-side+ floor in ``CuaTypedBrowserRoute.prepare`` enforces this key even when the+ private unrestricted daemon would answer the prepare."""return bool(_computer_use_cfg().get("grant_existing_profile", False))@@ -3497,8 +3503,18 @@ class CuaDriverBackend(ComputerUseBackend):return self._browser_route().observe(**kwargs)def typed_browser_prepare(self, **kwargs: Any) -> Dict[str, Any]:- """Prepare an explicitly approved driver-owned browser profile."""- return self._browser_route().prepare(**kwargs)+ """Prepare an explicitly approved driver-owned browser profile.++ The authorization inputs are resolved here, from config and this+ backend's immutable mode — never from model-supplied kwargs.+ """+ kwargs.pop("grant_existing_profile", None)+ kwargs.pop("permission_mode", None)+ return self._browser_route().prepare(+ grant_existing_profile=_cua_grant_existing_profile(),+ permission_mode=self.permission_mode,+ **kwargs,+ )def typed_browser_action(self,diff --git a/tools/computer_use/tool.py b/tools/computer_use/tool.pyindex c6f89c66b34..99e36b82390 100644--- a/tools/computer_use/tool.py+++ b/tools/computer_use/tool.py@@ -234,6 +234,32 @@ def _cua_permission_mode(session_id: str) -> str:return "standard"+def _config_preauthorized(action: str, args: Dict[str, Any]) -> bool:+ """True when config already carries the authorization for this action.++ ``computer_use.grant_existing_profile`` is a durable, file-backed opt-in+ that the model can never set. When it is on, an extra runtime prompt for+ the existing-profile prepare asks the user to re-authorize what they+ already authorized — and it makes the documented opt-in unusable on any+ non-interactive run, where the prompt has nobody to answer it and the+ call dies on approval timeout instead of attaching.++ Scope is deliberately narrow: only the existing-profile prepare, only+ when the grant is present. Isolated-profile launches still prompt, and+ any resolution failure falls closed to prompting.+ """+ if action != "cua_browser_prepare":+ return False+ if args.get("profile_mode") != "existing_profile":+ return False+ try:+ from tools.computer_use.cua_backend import _cua_grant_existing_profile++ return _cua_grant_existing_profile() is True+ except Exception:+ return False++def _get_backend(session_id: str = "") -> ComputerUseBackend:global _backendsid = str(session_id or "")@@ -512,8 +538,9 @@ def handle_computer_use(args: Dict[str, Any], **kwargs) -> Any:"code": "bring_to_front_requires_foreground",})- # Approval gate (destructive actions only).- if action in _DESTRUCTIVE_ACTIONS:+ # Approval gate (destructive actions only). A durable config grant is+ # already the user's authorization, so it stands in for the prompt.+ if action in _DESTRUCTIVE_ACTIONS and not _config_preauthorized(action, args):err = _request_approval(action, args, session_id)if err is not None:return err