From ea7e75f65a7c89cc0db3e6509b9ea09edf3dad9d Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 20:25:17 -0700 Subject: [PATCH 1/4] refactor(computer_use): unify cua quiet-subprocess probes via _run_quiet; table-drive discovery reasons; trim re-imports, contract gate, daemon teardown --- tools/computer_use/cua_backend.py | 199 +++++++++-------------- tools/computer_use/cua_backend_daemon.py | 71 ++++---- tools/computer_use/cua_backend_driver.py | 162 ++++++++---------- 3 files changed, 181 insertions(+), 251 deletions(-) diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.py index 135f70cc3b..9ce43e4115 100644 --- a/tools/computer_use/cua_backend.py +++ b/tools/computer_use/cua_backend.py @@ -16,6 +16,8 @@ keeps working; siblings look policy helpers up lazily through this module. from __future__ import annotations +import contextlib +import importlib import logging import os import shutil # noqa: F401 (tests patch cua_backend.shutil / .subprocess / .threading) @@ -27,9 +29,7 @@ from typing import Any, Dict, List, Optional from hermes_cli._subprocess_compat import windows_hide_flags from tools.computer_use.backend import ActionResult, ComputerUseBackend -from tools.computer_use.cua_backend_capture import ( # noqa: F401 - _CaptureMixin, _linux_x11_active_window_id, _select_capture_target, -) +from tools.computer_use.cua_backend_capture import _CaptureMixin, _select_capture_target # noqa: F401 from tools.computer_use.cua_backend_daemon import ( # noqa: F401 _EmbeddedCuaDaemon, _embedded_daemon_spawn_command, _resolve_cua_driver_app_path, _validate_cua_driver_app_signature, @@ -44,7 +44,7 @@ from tools.computer_use.cua_backend_input import _InputMixin from tools.computer_use.cua_backend_parse import ( # noqa: F401 _action_result_from, _extract_tool_result, _image_dimensions_from_bytes, _ingest_windows, _is_placeholder_id, _parse_elements_from_structured, _parse_elements_from_tree, - _parse_key_combo, _parse_xprop_net_active_window, _windows_from_tool_result, + _parse_xprop_net_active_window, _windows_from_tool_result, ) from tools.computer_use.cua_backend_session import _AsyncBridge, _CuaDriverSession # noqa: F401 @@ -77,10 +77,8 @@ def _cua_no_overlay() -> bool: val = _computer_use_cfg().get("no_overlay") if val is not None: return bool(val) - if sys.platform == "darwin": - return True if sys.platform != "linux": - return False + return sys.platform == "darwin" if not os.environ.get("DISPLAY"): return True try: @@ -104,12 +102,6 @@ def _cua_configured_permission_mode() -> str: raw = str(_computer_use_cfg().get("permission_mode", "standard") or "").strip().lower() return raw if raw in {"standard", "bounded"} else "standard" -def _cua_capability_manifest() -> Optional[str]: - """``computer_use.capability_manifest`` path, or None. Existence is - validated by ``_EmbeddedCuaDaemon`` so a missing file fails loudly.""" - raw = _computer_use_cfg().get("capability_manifest") - return raw.strip() if isinstance(raw, str) and raw.strip() else None - def _manifest_is_mode_independent(path: str) -> bool: """True when this manifest may accompany any permission mode: v1/v2 declare ``mode: bounded`` and abort startup under an unrestricted runtime; v3 has no @@ -157,17 +149,24 @@ def sanitized_cua_driver_env() -> Dict[str, str]: except Exception: return env -def _run_driver(driver_cmd: str, *args: str, timeout: float) -> subprocess.CompletedProcess: - """Run a short cua-driver verb with the sanitized env, hidden window and - stdin=DEVNULL (older drivers fall into a stdin-reading mode on unknown - verbs; EOF makes them exit fast instead of blocking until the timeout).""" - return subprocess.run( - [driver_cmd, *args], - capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, - stdin=subprocess.DEVNULL, - creationflags=windows_hide_flags(), - env=sanitized_cua_driver_env(), - ) +def _run_quiet(argv: List[str], *, timeout: float, swallow: Any = (), + **kw: Any) -> Any: + """``subprocess.run`` for short probe verbs: text mode, stdin=DEVNULL (older + drivers fall into a stdin-reading mode on unknown verbs; EOF makes them exit + fast instead of blocking until the timeout), output captured unless the + caller redirects it. Exceptions in ``swallow`` return None; others raise.""" + if "stdout" not in kw: + kw["capture_output"] = True + try: + return subprocess.run(argv, text=True, timeout=timeout, stdin=subprocess.DEVNULL, **kw) + except swallow: + return None + +def _run_driver(driver_cmd: str, *args: str, timeout: float, + swallow: Any = ()) -> Any: + """Run a short cua-driver verb with the sanitized env and hidden window.""" + return _run_quiet([driver_cmd, *args], timeout=timeout, swallow=swallow, encoding="utf-8", + errors="replace", creationflags=windows_hide_flags(), env=sanitized_cua_driver_env()) # --------------------------------------------------------------------------- @@ -182,13 +181,8 @@ def _linux_session_locked() -> Optional[bool]: systemd-logind, probe failure).""" if sys.platform != "linux": return None - - def _loginctl(*args: str) -> subprocess.CompletedProcess: - return subprocess.run(["loginctl", *args], capture_output=True, text=True, - timeout=2.0, stdin=subprocess.DEVNULL) - try: - proc = _loginctl("list-sessions", "--no-legend") + proc = _run_quiet(["loginctl", "list-sessions", "--no-legend"], timeout=2.0) if proc.returncode != 0: return None any_seat = False @@ -197,35 +191,32 @@ def _linux_session_locked() -> Optional[bool]: if len(parts) < 2 or "seat" not in line: continue any_seat = True - if "LockedHint=no" in _loginctl("show-session", parts[0], "-p", "LockedHint").stdout: + hint = _run_quiet(["loginctl", "show-session", parts[0], "-p", "LockedHint"], timeout=2.0) + if "LockedHint=no" in hint.stdout: return False return True if any_seat else None except Exception: return None +# (predicate, reason) in priority order; the default applies when none match. +_EMPTY_DISCOVERY_REASONS = ( + (lambda: _linux_session_locked() is True, + "the desktop session is LOCKED (loginctl LockedHint=yes) — unlock the screen; " + "a locked compositor hides windows and freezes app renderers"), + (lambda: sys.platform == "linux" and not os.environ.get("DISPLAY"), + "no DISPLAY is set — X11/XWayland is not reachable from this process"), + # Headless Mac / asleep panel: ScreenCaptureKit has 0 shareable displays while TCC grants look fine. + (lambda: sys.platform == "darwin", + "window discovery returned no windows; on macOS this usually means no shareable display " + "(headless Mac or panel asleep) — wake the display or attach a monitor/HDMI dummy, then run " + "`hermes computer-use doctor`"), +) + def _empty_discovery_reason() -> str: """One-line diagnosis for 'window discovery found nothing'.""" - if _linux_session_locked() is True: - return ( - "the desktop session is LOCKED (loginctl LockedHint=yes) — " - "unlock the screen; a locked compositor hides windows and " - "freezes app renderers" - ) - if sys.platform == "linux" and not os.environ.get("DISPLAY"): - return "no DISPLAY is set — X11/XWayland is not reachable from this process" - if sys.platform == "darwin": - # Headless Mac / asleep panel: ScreenCaptureKit has 0 shareable - # displays while TCC grants look fine. - return ( - "window discovery returned no windows; on macOS this usually " - "means no shareable display (headless Mac or panel asleep) — " - "wake the display or attach a monitor/HDMI dummy, then run " - "`hermes computer-use doctor`" - ) - return ( - "window discovery returned no windows; run `hermes computer-use " - "doctor` (display reachability, AX capability)" - ) + return next((reason for applies, reason in _EMPTY_DISCOVERY_REASONS if applies()), + "window discovery returned no windows; run `hermes computer-use doctor` " + "(display reachability, AX capability)") # --------------------------------------------------------------------------- @@ -245,19 +236,12 @@ def _maybe_repair_runtime_contract(contract: Dict[str, Any]) -> Dict[str, Any]: explicit ``HERMES_CUA_DRIVER_CMD`` override is authoritative even when broken, and a missing binary means installation was never requested.""" global _contract_repair_attempted - if ( - contract.get("ready") - or _contract_repair_attempted - or os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() - or not contract.get("binary") - ): + if (contract.get("ready") or _contract_repair_attempted + or os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() or not contract.get("binary")): return contract _contract_repair_attempted = True - logger.info( - "computer_use: installed cua-driver is not usable (%s); " - "attempting automatic repair", - contract.get("reason") or "runtime contract is incomplete", - ) + logger.info("computer_use: installed cua-driver is not usable (%s); attempting automatic repair", + contract.get("reason") or "runtime contract is incomplete") try: from hermes_cli.tools_config import install_cua_driver @@ -306,11 +290,10 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): # The manifest is mandatory for bounded (the daemon validates it) # and optional for unrestricted, where it still caps what an # approval-bypassed run may touch. + raw = _computer_use_cfg().get("capability_manifest") self._embedded_daemon = _EmbeddedCuaDaemon( - resolve_cua_driver_cmd() or "", - permission_mode, - capability_manifest=_cua_capability_manifest(), - ) + resolve_cua_driver_cmd() or "", permission_mode, + capability_manifest=raw.strip() if isinstance(raw, str) and raw.strip() else None) self._bridge = _AsyncBridge() self._session = _CuaDriverSession(self._bridge, self._embedded_daemon) # Sticky target — set by capture()/focus_app(), used by actions. @@ -339,35 +322,31 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): if not contract.get("ready"): contract = _maybe_repair_runtime_contract(contract) if not contract.get("ready"): - reason = contract.get("reason") or "runtime contract is incomplete" - repair = ( - "Update the binary selected by HERMES_CUA_DRIVER_CMD or remove that override." - if os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() - else "Run `hermes computer-use install` to repair it." - ) - raise RuntimeError(f"cua-driver is not ready: {reason}. {repair}") + repair = ("Update the binary selected by HERMES_CUA_DRIVER_CMD or remove that override." + if os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() + else "Run `hermes computer-use install` to repair it.") + raise RuntimeError(f"cua-driver is not ready: " + f"{contract.get('reason') or 'runtime contract is incomplete'}. {repair}") _maybe_nudge_update() # `mcp` is an optional extra: lazy-install on first use (gated by # `security.allow_lazy_installs`); failure raises FeatureUnavailable # with the exact `uv pip install` hint. from tools.lazy_deps import ensure as _lazy_ensure _lazy_ensure("tool.computer_use", prompt=False) - import importlib importlib.invalidate_caches() # a just-installed package may not be importable yet + daemon = self._embedded_daemon try: - if self._embedded_daemon is not None: - self._embedded_daemon.start() + if daemon is not None: + daemon.start() self._session.start() except Exception: - if self._embedded_daemon is not None: - self._embedded_daemon.stop() + if daemon is not None: + daemon.stop() raise - # Declare this run's identity. Non-fatal: cua-driver accepts anonymous # calls (the cursor just won't render), so degrade rather than abort. self._best_effort("start_session failed (continuing anonymous)", self._session.call_tool, "start_session", {"session": self._session_id}) - # Post-handshake tuning guards on `_started`: before the handshake flips # it, call_tool would re-enter session.start() (stubbed start() recurses). if self._session._started: @@ -388,14 +367,13 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): if self._session._started: self._best_effort("end_session failed (continuing teardown)", self._session.call_tool, "end_session", {"session": self._session_id}) - try: - self._session.stop() - finally: - try: - self._bridge.stop() - finally: - if self._embedded_daemon is not None: - self._embedded_daemon.stop() + # Every teardown step runs even if an earlier one raised (LIFO callbacks: + # session, then bridge, then the private daemon). + with contextlib.ExitStack() as teardown: + if self._embedded_daemon is not None: + teardown.callback(self._embedded_daemon.stop) + teardown.callback(self._bridge.stop) + teardown.callback(self._session.stop) @staticmethod def _best_effort(what: str, fn, *args: Any, **kwargs: Any) -> None: @@ -412,10 +390,7 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): # ── Target state ─────────────────────────────────────────────── def _clear_active_target(self) -> None: """Forget a capture/focus target so a failed lookup cannot misroute input.""" - self._active_pid = None - self._active_window_id = None - self._last_app = None - self._last_target = None + self._active_pid = self._active_window_id = self._last_app = self._last_target = None self._snapshot_tokens = {} def _set_active_target(self, target: Dict[str, Any]) -> None: @@ -427,15 +402,9 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): self._last_target = {"pid": self._active_pid, "window_id": self._active_window_id} # ── App lifecycle / focus ───────────────────────────────────────── - def launch_app( - self, - *, - bundle_id: Optional[str] = None, - name: Optional[str] = None, - urls: Optional[List[str]] = None, - additional_arguments: Optional[List[str]] = None, - creates_new_application_instance: bool = False, - ) -> Dict[str, Any]: + def launch_app(self, *, bundle_id: Optional[str] = None, name: Optional[str] = None, + urls: Optional[List[str]] = None, additional_arguments: Optional[List[str]] = None, + creates_new_application_instance: bool = False) -> Dict[str, Any]: """Idempotent launch returning ``{pid, bundle_id, name, windows[]}``. ``creates_new_application_instance=True`` forces a fresh instance so concurrent runs touching the same app get isolated windows.""" @@ -460,8 +429,7 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): return self._action("bring_to_front", args, inject_session=False) # ── Agent cursor / config ──────────────────────────────────────── - def set_agent_cursor_enabled(self, enabled: bool, *, - cursor_id: Optional[str] = None) -> ActionResult: + def set_agent_cursor_enabled(self, enabled: bool, *, cursor_id: Optional[str] = None) -> ActionResult: """Toggle the agent cursor overlay's visibility for this run.""" args: Dict[str, Any] = {"enabled": bool(enabled)} if cursor_id: @@ -484,20 +452,16 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): return self._session.call_tool(name, payload, timeout=timeout) # ── Internal ─────────────────────────────────────────────────── - def _maybe_attach_element_token(self, tool: str, args: Dict[str, Any]) -> None: - """Attach the snapshot's ``element_token`` to an ``element_index`` call so - a superseded snapshot yields an explicit 'stale' error. Gated on the - per-tool capability: older drivers (``additionalProperties: false``) - must never see the field.""" + def _action(self, name: str, args: Dict[str, Any], *, inject_session: bool = True) -> ActionResult: + # Attach the snapshot's `element_token` to an `element_index` call so a + # superseded snapshot yields an explicit 'stale' error. Gated on the + # per-tool capability: older drivers (`additionalProperties: false`) + # must never see the field. idx = args.get("element_index") token = self._snapshot_tokens.get(idx) if isinstance(idx, int) else None - if token and self._session.supports_capability("accessibility.element_tokens", tool=tool): + if token and self._session.supports_capability("accessibility.element_tokens", tool=name): args["element_token"] = token - - def _action(self, name: str, args: Dict[str, Any], *, inject_session: bool = True) -> ActionResult: - self._maybe_attach_element_token(name, args) - # setdefault preserves any explicit session a caller already supplied. - if inject_session: + if inject_session: # setdefault preserves any explicit session a caller already supplied args.setdefault("session", self._session_id) try: out = self._session.call_tool(name, args) @@ -511,9 +475,6 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): message = str(structured.get("message", "")) # Merge data + structuredContent into meta, structured winning on # overlap (it is the canonical verdict surface). - meta: Dict[str, Any] = {} - for part in (data, structured): - if isinstance(part, dict): - meta.update(part) + meta = {k: v for part in (data, structured) if isinstance(part, dict) for k, v in part.items()} return _action_result_from(name, not out["isError"], message, meta, structured, requested_delivery=args.get("delivery_mode")) diff --git a/tools/computer_use/cua_backend_daemon.py b/tools/computer_use/cua_backend_daemon.py index b42980e371..c45f3e3a62 100644 --- a/tools/computer_use/cua_backend_daemon.py +++ b/tools/computer_use/cua_backend_daemon.py @@ -24,6 +24,13 @@ logger = logging.getLogger("tools.computer_use.cua_backend") # official releases. Exact matches only: a suffixed identifier or other team is an impostor. _CUA_DRIVER_BUNDLE_ID = "com.trycua.driver" _CUA_DRIVER_TEAM_IDS = ("4YEC26S9KF", "YCK386LBJ7") +_QUIET_ERRORS = (OSError, subprocess.SubprocessError) + +def _cb(): + """Origin module, looked up lazily so ``patch("tools.computer_use.cua_backend.X")`` applies.""" + from tools.computer_use import cua_backend + + return cua_backend def _resolve_cua_driver_app_path(driver_cmd: str) -> Optional[str]: """Return the CuaDriver.app bundle that CARRIES *driver_cmd*, if any. Derived from the @@ -43,13 +50,11 @@ def _validate_cua_driver_app_signature(app_path: str) -> None: ``Identifier=com.trycua.driver`` and an expected TeamIdentifier. ``TeamIdentifier=not set`` (ad-hoc dev builds) is allowed only with ``computer_use.allow_unsigned_driver: true``. Raises RuntimeError on any mismatch or when codesign is unavailable/fails.""" - from tools.computer_use import cua_backend as _cb - codesign = shutil.which("codesign") if not codesign: raise RuntimeError("codesign is required to verify CuaDriver.app before launching it.") try: - proc = subprocess.run([codesign, "-dv", app_path], capture_output=True, text=True, timeout=15) + proc = _cb()._run_quiet([codesign, "-dv", app_path], timeout=15) except (OSError, subprocess.TimeoutExpired) as exc: raise RuntimeError(f"could not verify CuaDriver.app signature: {exc}") from exc if proc.returncode != 0: @@ -64,7 +69,7 @@ def _validate_cua_driver_app_signature(app_path: str) -> None: raise RuntimeError(f"CuaDriver.app at {app_path} has identifier {identifier!r}, " f"expected {_CUA_DRIVER_BUNDLE_ID!r}; refusing to launch it.") if team in _CUA_DRIVER_TEAM_IDS or ( - team in ("", "not set") and _cb._computer_use_cfg().get("allow_unsigned_driver") is True): + team in ("", "not set") and _cb()._computer_use_cfg().get("allow_unsigned_driver") is True): return raise RuntimeError( f"CuaDriver.app at {app_path} is signed by team {team!r}, expected one of " @@ -116,11 +121,8 @@ class _EmbeddedCuaDaemon: _START_TIMEOUT_SECONDS = 15.0 def __init__(self, driver_cmd: str, permission_mode: str, capability_manifest: Optional[str] = None) -> None: - from tools.computer_use import cua_backend as _cb - if permission_mode not in {"unrestricted", "bounded"}: raise ValueError("embedded permission override supports unrestricted or bounded only") - self.capability_manifest: Optional[str] = None manifest = str(capability_manifest or "").strip() if not manifest and permission_mode == "bounded": raise ValueError("bounded permission mode requires computer_use.capability_manifest") @@ -128,19 +130,19 @@ class _EmbeddedCuaDaemon: manifest = os.path.abspath(os.path.expanduser(manifest)) if not os.path.isfile(manifest): raise ValueError(f"capability manifest not found: {manifest}") - self.capability_manifest = manifest + self.capability_manifest: Optional[str] = manifest or None # bounded always forwards (the driver validates it); other modes accept only a v3 # manifest — a legacy one would abort startup instead. - self.manifest_applies = bool(self.capability_manifest) and ( - permission_mode == "bounded" or _cb._manifest_is_mode_independent(str(self.capability_manifest))) - if self.capability_manifest and not self.manifest_applies: + self.manifest_applies = bool(manifest) and ( + permission_mode == "bounded" or _cb()._manifest_is_mode_independent(manifest)) + if manifest and not self.manifest_applies: logger.warning("computer_use.capability_manifest is a legacy (v1/v2) manifest, " "which cua-driver only accepts in bounded mode — it will NOT " "bound this %s session. Migrate the manifest to version 3 to " "keep a ceiling on approval-bypassed runs.", permission_mode) self.permission_mode = permission_mode self._driver_cmd = self._command = driver_cmd - self._mcp_args: List[str] = list(_cb._CUA_DRIVER_ARGS) + self._mcp_args: List[str] = list(_cb()._CUA_DRIVER_ARGS) self._process: Any = None self._owns_runtime = self._running = self._launch_via_app = False self._stderr_tail: deque[str] = deque(maxlen=20) @@ -150,14 +152,17 @@ class _EmbeddedCuaDaemon: else os.path.join(tempfile.gettempdir(), f"hc-{token}.sock")) def child_env(self) -> Dict[str, str]: - from tools.computer_use import cua_backend as _cb - - env = _cb.cua_driver_child_env() + env = _cb().cua_driver_child_env() env["CUA_DRIVER_PERMISSION_MODE"] = self.permission_mode if self.permission_mode == "unrestricted": env["CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS"] = "1" return env + def _sanitized_env(self) -> Dict[str, str]: + from tools.environments.local import _sanitize_subprocess_env + + return _sanitize_subprocess_env(self.child_env()) + def _drain_stderr(self, process: Any) -> None: try: for line in getattr(process, "stderr", None) or (): @@ -169,8 +174,6 @@ class _EmbeddedCuaDaemon: pass def _serve_args(self) -> List[str]: - from tools.computer_use import cua_backend as _cb - serve_args = ["serve", "--embedded", "--socket", self.socket_path, "--no-permissions-gate", "--permission-mode", self.permission_mode] if self.permission_mode == "unrestricted": @@ -180,19 +183,16 @@ class _EmbeddedCuaDaemon: # The private daemon owns the cursor overlay, so the overlay policy must apply to this # long-lived serve process, not only its MCP proxy. Appended BEFORE the macOS app-launch # wrapping so the flag travels inside `open ... --args` with the rest of the serve args. - return _cb._mcp_args_with_overlay_flag(serve_args, driver_cmd=self._command) + return _cb()._mcp_args_with_overlay_flag(serve_args, driver_cmd=self._command) def start(self) -> None: if self._running: return - from tools.computer_use import cua_backend as _cb - from tools.environments.local import _sanitize_subprocess_env - - self._driver_cmd = self._driver_cmd or _cb.resolve_cua_driver_cmd() or "" + self._driver_cmd = self._driver_cmd or _cb().resolve_cua_driver_cmd() or "" if not self._driver_cmd: - raise RuntimeError(_cb.cua_driver_install_hint()) - self._command, self._mcp_args = _cb._resolve_mcp_invocation(self._driver_cmd) - env = _sanitize_subprocess_env(self.child_env()) + raise RuntimeError(_cb().cua_driver_install_hint()) + self._command, self._mcp_args = _cb()._resolve_mcp_invocation(self._driver_cmd) + env = self._sanitized_env() self._launch_via_app = sys.platform == "darwin" command = _embedded_daemon_spawn_command(self._command, self._serve_args(), platform=sys.platform) self._process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, @@ -219,13 +219,9 @@ class _EmbeddedCuaDaemon: def _socket_ready(self, env: Dict[str, str]) -> bool: """``cua-driver status --socket`` exits 0 once the private daemon accepts connections.""" - try: - probe = subprocess.run([self._command, "status", "--socket", self.socket_path], - stdin=subprocess.DEVNULL, capture_output=True, text=True, - timeout=2.0, env=env) - except (OSError, subprocess.SubprocessError): - return False - return probe.returncode == 0 + probe = _cb()._run_quiet([self._command, "status", "--socket", self.socket_path], + timeout=2.0, env=env, swallow=_QUIET_ERRORS) + return probe is not None and probe.returncode == 0 def proxy_invocation(self) -> Tuple[str, List[str]]: if not self._running: @@ -237,14 +233,9 @@ class _EmbeddedCuaDaemon: owns_runtime, self._owns_runtime = self._owns_runtime, False self._running = False if owns_runtime: - from tools.environments.local import _sanitize_subprocess_env - try: - subprocess.run([self._command, "stop", "--socket", self.socket_path], - stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, timeout=3.0, - env=_sanitize_subprocess_env(self.child_env())) - except (OSError, subprocess.SubprocessError): - pass + _cb()._run_quiet([self._command, "stop", "--socket", self.socket_path], timeout=3.0, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=self._sanitized_env(), swallow=_QUIET_ERRORS) if process is not None: _wait_or_kill(process) if sys.platform != "win32" and os.path.exists(self.socket_path): diff --git a/tools/computer_use/cua_backend_driver.py b/tools/computer_use/cua_backend_driver.py index 6ae4908799..81a4b656c4 100644 --- a/tools/computer_use/cua_backend_driver.py +++ b/tools/computer_use/cua_backend_driver.py @@ -36,6 +36,7 @@ _CUA_DRIVER_RUNTIME_CONTRACT_ARGS = { "stop": {"--socket"}, } _SEMVER_RE = re.compile(r"v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?") +_UPSTREAM_SCRIPTS = "https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts" def _cb(): """Origin module, looked up lazily so ``patch("tools.computer_use.cua_backend.X")`` applies.""" @@ -47,11 +48,8 @@ def _driver_json(driver_cmd: str, *args: str, timeout: float, require_ok: bool) """Run a driver verb and parse its stdout as a JSON object; None on spawn failure, empty stdout (older drivers print usage to stderr), unparseable or non-object output — and, with ``require_ok``, on a non-zero exit.""" - try: - proc = _cb()._run_driver(driver_cmd, *args, timeout=timeout) - except Exception: - return None - out = (proc.stdout or "").strip() + proc = _cb()._run_driver(driver_cmd, *args, timeout=timeout, swallow=Exception) + out = (proc.stdout or "").strip() if proc is not None else "" if not out or (require_ok and proc.returncode != 0): return None try: @@ -60,6 +58,11 @@ def _driver_json(driver_cmd: str, *args: str, timeout: float, require_ok: bool) return None return data if isinstance(data, dict) else None +def _valid_mcp_args(invocation: Any) -> Optional[List[str]]: + """``mcp_invocation.args`` when it is a list of strings (possibly empty), else None.""" + args = invocation.get("args") if isinstance(invocation, dict) else None + return args if isinstance(args, list) and all(isinstance(a, str) for a in args) else None + # --------------------------------------------------------------------------- # Binary resolution @@ -100,18 +103,12 @@ def _candidate_cua_driver_commands(override: Optional[str] = None) -> List[str]: home = os.path.expanduser("~") if sys.platform == "win32": local_app_data = os.environ.get("LOCALAPPDATA") or os.path.join(home, "AppData", "Local") - installed = [ - os.path.join(local_app_data, "Programs", "Cua", "cua-driver", "bin", "cua-driver.exe"), - os.path.join(home, ".local", "bin", "cua-driver.exe"), - os.path.join(home, ".local", "bin", "cua-driver"), - ] + installed = [os.path.join(local_app_data, "Programs", "Cua", "cua-driver", "bin", "cua-driver.exe"), + os.path.join(home, ".local", "bin", "cua-driver.exe"), + os.path.join(home, ".local", "bin", "cua-driver")] else: - installed = [ - os.path.join(home, ".local", "bin", "cua-driver"), - os.path.join(home, ".cargo", "bin", "cua-driver"), - "/opt/homebrew/bin/cua-driver", - "/usr/local/bin/cua-driver", - ] + installed = [os.path.join(home, ".local", "bin", "cua-driver"), os.path.join(home, ".cargo", "bin", "cua-driver"), + "/opt/homebrew/bin/cua-driver", "/usr/local/bin/cua-driver"] return [_CUA_DRIVER_DEFAULT_CMD, *installed] def resolve_cua_driver_cmd(override: Optional[str] = None) -> Optional[str]: @@ -129,28 +126,20 @@ def cua_driver_binary_available() -> bool: return _cb().resolve_cua_driver_cmd() is not None def cua_driver_install_hint() -> str: - scripts = "https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts" - if sys.platform == "win32": - installer = f" irm {scripts}/install.ps1 | iex" - else: - installer = f' /bin/bash -c "$(curl -fsSL {scripts}/install.sh)"' - return ( - "cua-driver is not installed. Install with one of:\n" - " hermes computer-use install\n" - "Or run the upstream installer directly:\n" - f"{installer}\n" - "Or run `hermes tools` and enable the Computer Use toolset to install it automatically." - ) + installer = (f" irm {_UPSTREAM_SCRIPTS}/install.ps1 | iex" if sys.platform == "win32" + else f' /bin/bash -c "$(curl -fsSL {_UPSTREAM_SCRIPTS}/install.sh)"') + return ("cua-driver is not installed. Install with one of:\n" + " hermes computer-use install\n" + "Or run the upstream installer directly:\n" + f"{installer}\n" + "Or run `hermes tools` and enable the Computer Use toolset to install it automatically.") # --------------------------------------------------------------------------- # MCP invocation # --------------------------------------------------------------------------- -def _mcp_args_with_overlay_flag( - args: List[str], - driver_cmd: str = _CUA_DRIVER_DEFAULT_CMD, -) -> List[str]: +def _mcp_args_with_overlay_flag(args: List[str], driver_cmd: str = _CUA_DRIVER_DEFAULT_CMD) -> List[str]: """Return *args* with ``--no-overlay`` appended when configured and supported.""" if _cb()._cua_no_overlay() and _cb()._cua_driver_supports_no_overlay(driver_cmd): return [*args, "--no-overlay"] @@ -174,12 +163,9 @@ def _resolve_mcp_invocation(driver_cmd: str, *, timeout: float = 6.0) -> Tuple[s start over a failed discovery hop. ``--no-overlay`` appended when allowed.""" manifest = _driver_json(driver_cmd, "manifest", timeout=timeout, require_ok=True) or {} invocation = manifest.get("mcp_invocation") - invocation = invocation if isinstance(invocation, dict) else {} - args = invocation.get("args") - valid_args = isinstance(args, list) and all(isinstance(a, str) for a in args) - if not valid_args: - args = list(_CUA_DRIVER_ARGS) - command = invocation.get("command") if valid_args else None + args = _valid_mcp_args(invocation) + command = invocation.get("command") if args is not None and isinstance(invocation, dict) else None + args = list(_CUA_DRIVER_ARGS) if args is None else args if isinstance(command, str) and command: # Translate a Windows ``C:\...`` command for WSL BEFORE the separator # check (backslash is not a separator on POSIX). A generic ``cua-driver`` @@ -199,58 +185,53 @@ def _resolve_mcp_invocation(driver_cmd: str, *, timeout: float = 6.0) -> Tuple[s # cua-driver's native `check-update` verb compares the installed binary against # the latest GitHub release (cached ~20h); we prefer it over a hardcoded floor. -def cua_driver_runtime_contract_status(binary: Optional[str] = None) -> Dict[str, Any]: - """Report whether a local driver can host Hermes' 0.20 integration.""" - resolved = binary or _cb().resolve_cua_driver_cmd() - - def _not_ready(reason: str, version: Optional[str] = None) -> Dict[str, Any]: - return {"ready": False, "binary": resolved, "version": version, "reason": reason} - - if not resolved: - return _not_ready("cua-driver is not installed") - try: - result = _cb()._run_driver(resolved, "manifest", timeout=15.0 if sys.platform == "win32" else 5.0) - except (OSError, subprocess.SubprocessError) as exc: - return _not_ready(f"manifest check failed: {exc}") - if result.returncode != 0: - detail = (result.stderr or result.stdout or "manifest command failed").strip() - return _not_ready(detail.splitlines()[-1][:200]) - try: - manifest = json.loads(result.stdout or "") - except (TypeError, ValueError): - manifest = None - if not isinstance(manifest, dict): - return _not_ready("driver manifest is missing or invalid") - - raw_version = str(manifest.get("binary_version") or "").strip() - match = _SEMVER_RE.fullmatch(raw_version) - if not match: - return _not_ready("driver manifest does not report a semantic version", raw_version or None) - if tuple(int(part) for part in match.groups()) < _CUA_DRIVER_RUNTIME_CONTRACT_MIN: - return _not_ready("Hermes computer use requires cua-driver 0.20.0 or newer", raw_version) - - invocation = manifest.get("mcp_invocation") - invocation_args = invocation.get("args") if isinstance(invocation, dict) else None - if not (invocation_args and isinstance(invocation_args, list) - and all(isinstance(arg, str) for arg in invocation_args)): - return _not_ready("driver manifest does not provide an MCP launch command", raw_version) - +def _manifest_contract_gaps(manifest: Dict[str, Any]) -> List[str]: + """``" "`` entries the driver's advertised subcommands lack.""" advertised: Dict[str, set[str]] = { - command["name"]: { - arg["name"] for arg in command.get("args") or [] - if isinstance(arg, dict) and isinstance(arg.get("name"), str) - } + command["name"]: {arg["name"] for arg in command.get("args") or [] + if isinstance(arg, dict) and isinstance(arg.get("name"), str)} for command in manifest.get("subcommands") or [] if isinstance(command, dict) and isinstance(command.get("name"), str) } - missing = [ - f"{command} {arg}" - for command, required_args in _CUA_DRIVER_RUNTIME_CONTRACT_ARGS.items() - for arg in sorted(required_args - advertised.get(command, set())) - ] - if missing: - return _not_ready("driver manifest is missing: " + ", ".join(missing), raw_version) - return {"ready": True, "binary": resolved, "version": raw_version, "reason": ""} + return [f"{command} {arg}" for command, required in _CUA_DRIVER_RUNTIME_CONTRACT_ARGS.items() + for arg in sorted(required - advertised.get(command, set()))] + +def cua_driver_runtime_contract_status(binary: Optional[str] = None) -> Dict[str, Any]: + """Report whether a local driver can host Hermes' 0.20 integration.""" + resolved = binary or _cb().resolve_cua_driver_cmd() + version: Optional[str] = None + reason = "cua-driver is not installed" + if resolved: + try: + result = _cb()._run_driver(resolved, "manifest", timeout=15.0 if sys.platform == "win32" else 5.0) + except (OSError, subprocess.SubprocessError) as exc: + result, reason = None, f"manifest check failed: {exc}" + if result is not None and result.returncode != 0: + detail = (result.stderr or result.stdout or "manifest command failed").strip() + result, reason = None, detail.splitlines()[-1][:200] + if result is not None: + try: + manifest = json.loads(result.stdout or "") + except (TypeError, ValueError): + manifest = None + reason = _manifest_contract_reason(manifest if isinstance(manifest, dict) else None) + if isinstance(manifest, dict): + version = str(manifest.get("binary_version") or "").strip() or None + return {"ready": not reason, "binary": resolved, "version": version, "reason": reason} + +def _manifest_contract_reason(manifest: Optional[Dict[str, Any]]) -> str: + """Why a parsed manifest fails the 0.20 contract, or ``""`` when it passes.""" + if manifest is None: + return "driver manifest is missing or invalid" + match = _SEMVER_RE.fullmatch(str(manifest.get("binary_version") or "").strip()) + if not match: + return "driver manifest does not report a semantic version" + if tuple(int(part) for part in match.groups()) < _CUA_DRIVER_RUNTIME_CONTRACT_MIN: + return "Hermes computer use requires cua-driver 0.20.0 or newer" + if not _valid_mcp_args(manifest.get("mcp_invocation")): + return "driver manifest does not provide an MCP launch command" + missing = _manifest_contract_gaps(manifest) + return "driver manifest is missing: " + ", ".join(missing) if missing else "" def cua_driver_update_check(*, timeout: Optional[float] = None) -> Optional[Dict[str, Any]]: """``cua-driver check-update --json`` payload (``{current_version, @@ -274,9 +255,6 @@ def cua_driver_update_nudge() -> Optional[str]: state = _cb().cua_driver_update_check() if not state or not state.get("update_available"): return None - latest = state.get("latest_version") or "?" - current = state.get("current_version") or "?" - return ( - f"cua-driver {latest} is available (you have {current}); " - f"update with `hermes computer-use install --upgrade`." - ) + return (f"cua-driver {state.get('latest_version') or '?'} is available " + f"(you have {state.get('current_version') or '?'}); " + f"update with `hermes computer-use install --upgrade`.") From 95b0ae9121cd4457cedfc0b4ec47055d92f25391 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 20:37:04 -0700 Subject: [PATCH 2/4] refactor(computer_use): compact cua_backend/driver/daemon docstrings, banners and imports; fold contract-reason logic --- tools/computer_use/cua_backend.py | 240 +++++++++-------------- tools/computer_use/cua_backend_daemon.py | 61 +++--- tools/computer_use/cua_backend_driver.py | 148 ++++++-------- 3 files changed, 187 insertions(+), 262 deletions(-) diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.py index 9ce43e4115..7d1718e463 100644 --- a/tools/computer_use/cua_backend.py +++ b/tools/computer_use/cua_backend.py @@ -1,17 +1,16 @@ """Cua-driver backend (macOS, Windows, Linux): MCP over stdio to `cua-driver`. -The async `mcp` SDK runs on a background loop (``cua_backend_session``); the -same tool surface works on all three platforms, and per-host gaps (no DISPLAY, -missing AT-SPI, TCC) surface via `hermes computer-use doctor` instead of -failing silently. Install with `hermes computer-use install`. The macOS path -uses private SkyLight SPIs that can break on OS updates. +The async `mcp` SDK runs on a background loop (``cua_backend_session``); the same tool surface +works on all three platforms, and per-host gaps (no DISPLAY, missing AT-SPI, TCC) surface via +`hermes computer-use doctor` instead of failing silently. Install with `hermes computer-use +install`. The macOS path uses private SkyLight SPIs that can break on OS updates. -Siblings: ``cua_backend_driver`` (binary resolution, runtime contract, update -check), ``cua_backend_capture`` / ``cua_backend_input`` (backend mixins), -``cua_backend_parse`` (pure parsing), ``cua_backend_session`` (bridge + session -+ CLI fallback), ``cua_backend_daemon`` (private daemon + macOS app identity). -Moved names are re-imported here so ``patch("tools.computer_use.cua_backend.X")`` -keeps working; siblings look policy helpers up lazily through this module. +Siblings: ``cua_backend_driver`` (binary resolution, runtime contract, update check), +``cua_backend_capture`` / ``cua_backend_input`` (backend mixins), ``cua_backend_parse`` (pure +parsing), ``cua_backend_session`` (bridge + session + CLI fallback), ``cua_backend_daemon`` +(private daemon + macOS app identity). Moved names are re-imported here so +``patch("tools.computer_use.cua_backend.X")`` keeps working; siblings look policy helpers up +lazily through this module. """ from __future__ import annotations @@ -31,49 +30,40 @@ from hermes_cli._subprocess_compat import windows_hide_flags from tools.computer_use.backend import ActionResult, ComputerUseBackend from tools.computer_use.cua_backend_capture import _CaptureMixin, _select_capture_target # noqa: F401 from tools.computer_use.cua_backend_daemon import ( # noqa: F401 - _EmbeddedCuaDaemon, _embedded_daemon_spawn_command, _resolve_cua_driver_app_path, - _validate_cua_driver_app_signature, + _EmbeddedCuaDaemon, _embedded_daemon_spawn_command, _resolve_cua_driver_app_path, _validate_cua_driver_app_signature, ) from tools.computer_use.cua_backend_driver import ( # noqa: F401 - _CUA_DRIVER_ARGS, _CUA_DRIVER_CMD_ENV, _cua_driver_supports_no_overlay, - _mcp_args_with_overlay_flag, _resolve_mcp_invocation, _wsl_windows_path_to_posix, - cua_driver_binary_available, cua_driver_install_hint, cua_driver_runtime_contract_status, - cua_driver_update_check, cua_driver_update_nudge, resolve_cua_driver_cmd, + _CUA_DRIVER_ARGS, _CUA_DRIVER_CMD_ENV, _cua_driver_supports_no_overlay, _mcp_args_with_overlay_flag, + _resolve_mcp_invocation, _wsl_windows_path_to_posix, cua_driver_binary_available, cua_driver_install_hint, + cua_driver_runtime_contract_status, cua_driver_update_check, cua_driver_update_nudge, resolve_cua_driver_cmd, ) from tools.computer_use.cua_backend_input import _InputMixin from tools.computer_use.cua_backend_parse import ( # noqa: F401 - _action_result_from, _extract_tool_result, _image_dimensions_from_bytes, _ingest_windows, - _is_placeholder_id, _parse_elements_from_structured, _parse_elements_from_tree, - _parse_xprop_net_active_window, _windows_from_tool_result, + _action_result_from, _extract_tool_result, _image_dimensions_from_bytes, _ingest_windows, _is_placeholder_id, + _parse_elements_from_structured, _parse_elements_from_tree, _parse_xprop_net_active_window, _windows_from_tool_result, ) from tools.computer_use.cua_backend_session import _AsyncBridge, _CuaDriverSession # noqa: F401 logger = logging.getLogger(__name__) - # cua-driver's anonymous PostHog telemetry gate ("0" disables; absent => ON upstream). _CUA_TELEMETRY_ENV_VAR = "CUA_DRIVER_RS_TELEMETRY_ENABLED" -# --------------------------------------------------------------------------- -# Config-derived policy -# --------------------------------------------------------------------------- - +# ── Config-derived policy ───────────────────────────────────────────────── def _computer_use_cfg() -> Dict[str, Any]: """The ``computer_use`` config block, or ``{}`` when config is unreadable.""" try: from hermes_cli.config import load_config - return (load_config() or {}).get("computer_use") or {} except Exception: return {} def _cua_no_overlay() -> bool: - """Pass ``--no-overlay``? ``computer_use.no_overlay`` overrides; else off on - macOS (cursor-overlay redraw loop can peg a core after a session), headless - Linux / WSL2 / containers, and Linux X11 (the overlay is a fullscreen - always-on-top all-workspaces window with no compositor-owned lifecycle, so - an unclean session end can leave it wedged over every app); on for Windows - and Linux Wayland (compositor owns the surface).""" + """Pass ``--no-overlay``? ``computer_use.no_overlay`` overrides; else off on macOS (cursor-overlay + redraw loop can peg a core after a session), headless Linux / WSL2 / containers, and Linux X11 (the + overlay is a fullscreen always-on-top all-workspaces window with no compositor-owned lifecycle, so an + unclean session end can leave it wedged over every app); on for Windows and Linux Wayland + (compositor owns the surface).""" val = _computer_use_cfg().get("no_overlay") if val is not None: return bool(val) @@ -90,27 +80,23 @@ def _cua_no_overlay() -> bool: return os.environ.get("XDG_SESSION_TYPE") != "wayland" and not os.environ.get("WAYLAND_DISPLAY") def _cua_telemetry_disabled() -> bool: - """True unless ``computer_use.cua_telemetry`` opts in (unreadable config - fails SAFE toward disabling telemetry).""" + """True unless ``computer_use.cua_telemetry`` opts in (unreadable config fails SAFE toward disabling).""" return not bool(_computer_use_cfg().get("cua_telemetry", False)) def _cua_configured_permission_mode() -> str: - """``computer_use.permission_mode``: ``standard`` (default) or ``bounded``; - unknown values fall closed to ``standard``. ``unrestricted`` is deliberately - NOT a config value — it stays tied to the per-session YOLO toggle so a stale - config line can never silently bypass approvals.""" + """``computer_use.permission_mode``: ``standard`` (default) or ``bounded``; unknown values fall closed + to ``standard``. ``unrestricted`` is deliberately NOT a config value — it stays tied to the per-session + YOLO toggle so a stale config line can never silently bypass approvals.""" raw = str(_computer_use_cfg().get("permission_mode", "standard") or "").strip().lower() return raw if raw in {"standard", "bounded"} else "standard" def _manifest_is_mode_independent(path: str) -> bool: - """True when this manifest may accompany any permission mode: v1/v2 declare - ``mode: bounded`` and abort startup under an unrestricted runtime; v3 has no - mode and is the ceiling the driver accepts alongside any mode. Unreadable / - unparseable -> False (forwarding one would turn a working session into a hard - startup failure; bounded forwards unconditionally anyway).""" + """True when this manifest may accompany any permission mode: v1/v2 declare ``mode: bounded`` and abort + startup under an unrestricted runtime; v3 has no mode and is the ceiling the driver accepts alongside any + mode. Unreadable / unparseable -> False (forwarding one would turn a working session into a hard startup + failure; bounded forwards unconditionally anyway).""" try: import yaml - with open(path, "r", encoding="utf-8") as handle: parsed = yaml.safe_load(handle) except Exception: @@ -120,8 +106,8 @@ def _manifest_is_mode_independent(path: str) -> bool: return isinstance(version, int) and not isinstance(version, bool) and version >= 3 def _computer_use_max_image_dimension() -> Optional[int]: - """``computer_use.max_image_dimension`` longest-edge cap (default 1456, - matching the aux-vision downscale); ``0``/negative -> None (unset).""" + """``computer_use.max_image_dimension`` longest-edge cap (default 1456, matching the aux-vision + downscale); ``0``/negative -> None (unset).""" try: dim = int(_computer_use_cfg().get("max_image_dimension", 1456)) except (TypeError, ValueError): @@ -130,31 +116,27 @@ def _computer_use_max_image_dimension() -> Optional[int]: def cua_driver_child_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str, str]: """Env for spawning cua-driver: ``base_env`` (default ``os.environ``) plus - ``CUA_DRIVER_RS_TELEMETRY_ENABLED=0`` unless the user opted in. Used by - every spawn site (MCP, status, doctor, install) so the policy is uniform.""" + ``CUA_DRIVER_RS_TELEMETRY_ENABLED=0`` unless the user opted in. Used by every spawn site (MCP, + status, doctor, install) so the policy is uniform.""" env = dict(base_env if base_env is not None else os.environ) if _cua_telemetry_disabled(): env[_CUA_TELEMETRY_ENV_VAR] = "0" return env def sanitized_cua_driver_env() -> Dict[str, str]: - """``cua_driver_child_env()`` with Hermes provider secrets stripped — - cua-driver is a third-party binary and must never inherit API keys. - Falls back to the unsanitized telemetry env if the sanitizer can't import.""" + """``cua_driver_child_env()`` with Hermes provider secrets stripped — cua-driver is a third-party binary + and must never inherit API keys. Falls back to the unsanitized telemetry env if the sanitizer can't import.""" env = cua_driver_child_env() try: from tools.environments.local import _sanitize_subprocess_env - return _sanitize_subprocess_env(env) except Exception: return env -def _run_quiet(argv: List[str], *, timeout: float, swallow: Any = (), - **kw: Any) -> Any: - """``subprocess.run`` for short probe verbs: text mode, stdin=DEVNULL (older - drivers fall into a stdin-reading mode on unknown verbs; EOF makes them exit - fast instead of blocking until the timeout), output captured unless the - caller redirects it. Exceptions in ``swallow`` return None; others raise.""" +def _run_quiet(argv: List[str], *, timeout: float, swallow: Any = (), **kw: Any) -> Any: + """``subprocess.run`` for short probe verbs: text mode, stdin=DEVNULL (older drivers fall into a + stdin-reading mode on unknown verbs; EOF makes them exit fast instead of blocking until the timeout), + output captured unless the caller redirects it. Exceptions in ``swallow`` return None; others raise.""" if "stdout" not in kw: kw["capture_output"] = True try: @@ -162,23 +144,18 @@ def _run_quiet(argv: List[str], *, timeout: float, swallow: Any = (), except swallow: return None -def _run_driver(driver_cmd: str, *args: str, timeout: float, - swallow: Any = ()) -> Any: +def _run_driver(driver_cmd: str, *args: str, timeout: float, swallow: Any = ()) -> Any: """Run a short cua-driver verb with the sanitized env and hidden window.""" return _run_quiet([driver_cmd, *args], timeout=timeout, swallow=swallow, encoding="utf-8", errors="replace", creationflags=windows_hide_flags(), env=sanitized_cua_driver_env()) -# --------------------------------------------------------------------------- -# Linux display diagnostics -# --------------------------------------------------------------------------- - +# ── Linux display diagnostics ───────────────────────────────────────────── def _linux_session_locked() -> Optional[bool]: - """Is the graphical session locked? (Linux; best-effort.) A locked KDE/GNOME - session freezes renderers and half-disables the AX tree, so discovery - legitimately returns nothing — which otherwise reads as a driver bug. - True/False when loginctl answers, None when unavailable (non-Linux, no - systemd-logind, probe failure).""" + """Is the graphical session locked? (Linux; best-effort.) A locked KDE/GNOME session freezes renderers + and half-disables the AX tree, so discovery legitimately returns nothing — which otherwise reads as a + driver bug. True/False when loginctl answers, None when unavailable (non-Linux, no systemd-logind, + probe failure).""" if sys.platform != "linux": return None try: @@ -198,18 +175,17 @@ def _linux_session_locked() -> Optional[bool]: except Exception: return None -# (predicate, reason) in priority order; the default applies when none match. +# (predicate, reason) in priority order; the default applies when none match. The macOS entry covers a +# headless Mac / asleep panel: ScreenCaptureKit has 0 shareable displays while TCC grants look fine. _EMPTY_DISCOVERY_REASONS = ( (lambda: _linux_session_locked() is True, "the desktop session is LOCKED (loginctl LockedHint=yes) — unlock the screen; " "a locked compositor hides windows and freezes app renderers"), (lambda: sys.platform == "linux" and not os.environ.get("DISPLAY"), "no DISPLAY is set — X11/XWayland is not reachable from this process"), - # Headless Mac / asleep panel: ScreenCaptureKit has 0 shareable displays while TCC grants look fine. (lambda: sys.platform == "darwin", - "window discovery returned no windows; on macOS this usually means no shareable display " - "(headless Mac or panel asleep) — wake the display or attach a monitor/HDMI dummy, then run " - "`hermes computer-use doctor`"), + "window discovery returned no windows; on macOS this usually means no shareable display (headless Mac or " + "panel asleep) — wake the display or attach a monitor/HDMI dummy, then run `hermes computer-use doctor`"), ) def _empty_discovery_reason() -> str: @@ -219,22 +195,17 @@ def _empty_discovery_reason() -> str: "(display reachability, AX capability)") -# --------------------------------------------------------------------------- -# One-shot start() helpers: auto-repair + update nudge -# --------------------------------------------------------------------------- - +# ── One-shot start() helpers: auto-repair + update nudge ────────────────── _update_checked = False -# One auto-repair attempt per process: when the runtime-contract gate fails -# for something a reinstall fixes (old version, missing manifest verbs) run -# the standard install path once instead of telling the user to. Guarded so a -# failing installer can't loop — the second start() goes straight to the error. +# One auto-repair attempt per process: when the runtime-contract gate fails for something a reinstall +# fixes (old version, missing manifest verbs) run the standard install path once instead of telling the +# user to. Guarded so a failing installer can't loop — the second start() goes straight to the error. _contract_repair_attempted = False def _maybe_repair_runtime_contract(contract: Dict[str, Any]) -> Dict[str, Any]: - """Try one automatic driver repair; return the post-repair contract (or the - original when no repair was attempted / it failed). Never raises. An - explicit ``HERMES_CUA_DRIVER_CMD`` override is authoritative even when - broken, and a missing binary means installation was never requested.""" + """Try one automatic driver repair; return the post-repair contract (or the original when no repair was + attempted / it failed). Never raises. An explicit ``HERMES_CUA_DRIVER_CMD`` override is authoritative + even when broken, and a missing binary means installation was never requested.""" global _contract_repair_attempted if (contract.get("ready") or _contract_repair_attempted or os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() or not contract.get("binary")): @@ -244,20 +215,18 @@ def _maybe_repair_runtime_contract(contract: Dict[str, Any]) -> Dict[str, Any]: contract.get("reason") or "runtime contract is incomplete") try: from hermes_cli.tools_config import install_cua_driver - - if not install_cua_driver(upgrade=False, show_installer_progress=False): - return contract + repaired = install_cua_driver(upgrade=False, show_installer_progress=False) except Exception as exc: logger.warning("computer_use: automatic cua-driver repair failed: %s", exc) - return contract + repaired = False try: - return cua_driver_runtime_contract_status() + return cua_driver_runtime_contract_status() if repaired else contract except Exception: return contract def _maybe_nudge_update() -> None: - """Emit an update nudge at most once per process, off-thread so the - (cached, ~20h) GitHub poll never blocks the first computer_use action.""" + """Emit an update nudge at most once per process, off-thread so the (cached, ~20h) GitHub poll never + blocks the first computer_use action.""" global _update_checked if _update_checked: return @@ -274,10 +243,6 @@ def _maybe_nudge_update() -> None: threading.Thread(target=_run, name="cua-driver-update-check", daemon=True).start() -# --------------------------------------------------------------------------- -# The backend itself -# --------------------------------------------------------------------------- - class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): """Default computer-use backend. Cross-platform via cua-driver MCP.""" @@ -287,28 +252,26 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): self.permission_mode = permission_mode self._embedded_daemon: Optional[_EmbeddedCuaDaemon] = None if permission_mode != "standard": - # The manifest is mandatory for bounded (the daemon validates it) - # and optional for unrestricted, where it still caps what an - # approval-bypassed run may touch. + # The manifest is mandatory for bounded (the daemon validates it) and optional for + # unrestricted, where it still caps what an approval-bypassed run may touch. raw = _computer_use_cfg().get("capability_manifest") self._embedded_daemon = _EmbeddedCuaDaemon( resolve_cua_driver_cmd() or "", permission_mode, capability_manifest=raw.strip() if isinstance(raw, str) and raw.strip() else None) self._bridge = _AsyncBridge() self._session = _CuaDriverSession(self._bridge, self._embedded_daemon) - # Sticky target — set by capture()/focus_app(), used by actions. + # Sticky target — set by capture()/focus_app(), used by actions. `_last_target` is the exact + # identity for capture_after: Linux app names may be generic (several unrelated Qt windows can + # all say Qt6Application). `_snapshot_tokens` is the per-snapshot `element_index -> + # element_token`; actions attach it so cua-driver reports "stale" instead of silently re-resolving. self._active_pid: Optional[int] = None self._active_window_id: Optional[int] = None self._last_app: Optional[str] = None - # Exact identity for capture_after: Linux app names may be generic - # (several unrelated Qt windows can all say Qt6Application). self._last_target: Optional[Dict[str, Optional[int]]] = None - # Per-snapshot `element_index -> element_token`; actions attach it so - # cua-driver reports "stale" instead of silently re-resolving. self._snapshot_tokens: Dict[int, str] = {} - # Public session label (one per Hermes run) sent as `session` on every - # call: owns the cursor color and gives config/recording state a stable - # owner across transport restarts. Part of the 0.20 runtime contract. + # Public session label (one per Hermes run) sent as `session` on every call: owns the cursor + # color and gives config/recording state a stable owner across transport restarts. Part of + # the 0.20 runtime contract. self._session_id: str = f"hermes-{uuid.uuid4().hex[:12]}" self._session.set_transport_reset_callback(self._handle_transport_reset) @@ -328,9 +291,8 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): raise RuntimeError(f"cua-driver is not ready: " f"{contract.get('reason') or 'runtime contract is incomplete'}. {repair}") _maybe_nudge_update() - # `mcp` is an optional extra: lazy-install on first use (gated by - # `security.allow_lazy_installs`); failure raises FeatureUnavailable - # with the exact `uv pip install` hint. + # `mcp` is an optional extra: lazy-install on first use (gated by `security.allow_lazy_installs`); + # failure raises FeatureUnavailable with the exact `uv pip install` hint. from tools.lazy_deps import ensure as _lazy_ensure _lazy_ensure("tool.computer_use", prompt=False) importlib.invalidate_caches() # a just-installed package may not be importable yet @@ -343,32 +305,28 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): if daemon is not None: daemon.stop() raise - # Declare this run's identity. Non-fatal: cua-driver accepts anonymous - # calls (the cursor just won't render), so degrade rather than abort. + # Declare this run's identity. Non-fatal: cua-driver accepts anonymous calls (the cursor just + # won't render), so degrade rather than abort. self._best_effort("start_session failed (continuing anonymous)", self._session.call_tool, "start_session", {"session": self._session_id}) - # Post-handshake tuning guards on `_started`: before the handshake flips - # it, call_tool would re-enter session.start() (stubbed start() recurses). + # Post-handshake tuning guards on `_started`: before the handshake flips it, call_tool would + # re-enter session.start() (stubbed start() recurses). if self._session._started: - # Smaller screenshots cost less over the daemon socket and per turn. max_dim = _computer_use_max_image_dimension() - if max_dim: + if max_dim: # smaller screenshots cost less over the daemon socket and per turn self._best_effort("set_config(max_image_dimension) failed", self.set_config, max_image_dimension=max_dim) - # Belt-and-suspenders when --no-overlay is unsupported or ignored. - if _cua_no_overlay(): + if _cua_no_overlay(): # belt-and-suspenders when --no-overlay is unsupported or ignored self._best_effort("set_agent_cursor_enabled failed", self.set_agent_cursor_enabled, False, cursor_id=self._session_id) def stop(self) -> None: - # Best-effort end_session so the driver cleans per-session state (cursor - # overlay, recording ownership, config overrides); the connection drop - # below releases daemon-side state regardless. + # Best-effort end_session so the driver cleans per-session state (cursor overlay, recording + # ownership, config overrides); the connection drop below releases daemon-side state regardless. if self._session._started: self._best_effort("end_session failed (continuing teardown)", self._session.call_tool, "end_session", {"session": self._session_id}) - # Every teardown step runs even if an earlier one raised (LIFO callbacks: - # session, then bridge, then the private daemon). + # Every teardown step runs even if an earlier one raised (LIFO: session, bridge, private daemon). with contextlib.ExitStack() as teardown: if self._embedded_daemon is not None: teardown.callback(self._embedded_daemon.stop) @@ -396,8 +354,8 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): def _set_active_target(self, target: Dict[str, Any]) -> None: self._active_pid = target["pid"] self._active_window_id = target["window_id"] - # Tokens belong to the prior snapshot; disarm before any capture call - # so an exception cannot pair old tokens with this target. + # Tokens belong to the prior snapshot; disarm before any capture call so an exception cannot + # pair old tokens with this target. self._snapshot_tokens = {} self._last_target = {"pid": self._active_pid, "window_id": self._active_window_id} @@ -406,8 +364,8 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): urls: Optional[List[str]] = None, additional_arguments: Optional[List[str]] = None, creates_new_application_instance: bool = False) -> Dict[str, Any]: """Idempotent launch returning ``{pid, bundle_id, name, windows[]}``. - ``creates_new_application_instance=True`` forces a fresh instance so - concurrent runs touching the same app get isolated windows.""" + ``creates_new_application_instance=True`` forces a fresh instance so concurrent runs touching + the same app get isolated windows.""" if not bundle_id and not name: raise ValueError("launch_app requires either bundle_id or name") args: Dict[str, Any] = {"session": self._session_id} @@ -424,8 +382,8 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): args: Dict[str, Any] = {"pid": int(pid)} if window_id is not None: args["window_id"] = int(window_id) - # The live schema is strict and has no session property: this is a - # standalone native focus operation, not a session-scoped input action. + # The live schema is strict and has no session property: this is a standalone native focus + # operation, not a session-scoped input action. return self._action("bring_to_front", args, inject_session=False) # ── Agent cursor / config ──────────────────────────────────────── @@ -437,15 +395,13 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): return self._action("set_agent_cursor_enabled", args) def set_config(self, **config) -> ActionResult: - """Set cua-driver config keys (e.g. ``max_image_dimension``). Unknown - keys pass through verbatim — cua-driver validates its own schema.""" + """Set cua-driver config keys (e.g. ``max_image_dimension``). Unknown keys pass through verbatim — + cua-driver validates its own schema.""" return self._action("set_config", dict(config)) - def call_tool(self, name: str, args: Optional[Dict[str, Any]] = None, - *, timeout: float = 30.0) -> Dict[str, Any]: - """Generic escape hatch: call any cua-driver MCP tool by name. - ``session`` is injected via setdefault, so this is the supported path - for tools the wrapper does not type-wrap (preferred over + def call_tool(self, name: str, args: Optional[Dict[str, Any]] = None, *, timeout: float = 30.0) -> Dict[str, Any]: + """Generic escape hatch: call any cua-driver MCP tool by name. ``session`` is injected via + setdefault, so this is the supported path for tools the wrapper does not type-wrap (preferred over ``self._session.call_tool``).""" payload = dict(args) if args else {} payload.setdefault("session", self._session_id) @@ -453,10 +409,9 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): # ── Internal ─────────────────────────────────────────────────── def _action(self, name: str, args: Dict[str, Any], *, inject_session: bool = True) -> ActionResult: - # Attach the snapshot's `element_token` to an `element_index` call so a - # superseded snapshot yields an explicit 'stale' error. Gated on the - # per-tool capability: older drivers (`additionalProperties: false`) - # must never see the field. + # Attach the snapshot's `element_token` to an `element_index` call so a superseded snapshot + # yields an explicit 'stale' error. Gated on the per-tool capability: older drivers + # (`additionalProperties: false`) must never see the field. idx = args.get("element_index") token = self._snapshot_tokens.get(idx) if isinstance(idx, int) else None if token and self._session.supports_capability("accessibility.element_tokens", tool=name): @@ -473,8 +428,7 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): message = str(data.get("message", "")) if isinstance(data, dict) else data if isinstance(data, str) else "" if not message and isinstance(structured, dict): message = str(structured.get("message", "")) - # Merge data + structuredContent into meta, structured winning on - # overlap (it is the canonical verdict surface). + # Merge data + structuredContent into meta, structured winning on overlap (canonical verdict surface). meta = {k: v for part in (data, structured) if isinstance(part, dict) for k, v in part.items()} return _action_result_from(name, not out["isError"], message, meta, structured, requested_delivery=args.get("delivery_mode")) diff --git a/tools/computer_use/cua_backend_daemon.py b/tools/computer_use/cua_backend_daemon.py index c45f3e3a62..92dd744f58 100644 --- a/tools/computer_use/cua_backend_daemon.py +++ b/tools/computer_use/cua_backend_daemon.py @@ -1,7 +1,6 @@ -"""Private embedded cua-driver daemon for non-standard permission modes, plus the macOS -CuaDriver.app identity checks its launch path depends on. Driver resolution / policy helpers -are looked up lazily through ``tools.computer_use.cua_backend`` so tests that patch them there -keep working. +"""Private embedded cua-driver daemon for non-standard permission modes, plus the macOS CuaDriver.app +identity checks its launch path depends on. Driver resolution / policy helpers are looked up lazily +through ``tools.computer_use.cua_backend`` so tests that patch them there keep working. """ from __future__ import annotations @@ -20,8 +19,8 @@ from typing import Any, Dict, List, Optional, Tuple logger = logging.getLogger("tools.computer_use.cua_backend") -# The only bundle identity the private daemon may launch through, and the teams that sign -# official releases. Exact matches only: a suffixed identifier or other team is an impostor. +# The only bundle identity the private daemon may launch through, and the teams that sign official +# releases. Exact matches only: a suffixed identifier or other team is an impostor. _CUA_DRIVER_BUNDLE_ID = "com.trycua.driver" _CUA_DRIVER_TEAM_IDS = ("4YEC26S9KF", "YCK386LBJ7") _QUIET_ERRORS = (OSError, subprocess.SubprocessError) @@ -29,13 +28,12 @@ _QUIET_ERRORS = (OSError, subprocess.SubprocessError) def _cb(): """Origin module, looked up lazily so ``patch("tools.computer_use.cua_backend.X")`` applies.""" from tools.computer_use import cua_backend - return cua_backend def _resolve_cua_driver_app_path(driver_cmd: str) -> Optional[str]: - """Return the CuaDriver.app bundle that CARRIES *driver_cmd*, if any. Derived from the - resolved binary path only — no /Applications fallback, which could be a DIFFERENT install - than the one the manifest resolved, running code the resolution chain never validated.""" + """Return the CuaDriver.app bundle that CARRIES *driver_cmd*, if any. Derived from the resolved binary + path only — no /Applications fallback, which could be a DIFFERENT install than the one the manifest + resolved, running code the resolution chain never validated.""" resolved = os.path.realpath(driver_cmd) marker_index = resolved.find(".app/Contents/MacOS/") if marker_index < 0: @@ -45,11 +43,11 @@ def _resolve_cua_driver_app_path(driver_cmd: str) -> Optional[str]: return candidate if os.path.isfile(executable) and os.access(executable, os.X_OK) else None def _validate_cua_driver_app_signature(app_path: str) -> None: - """Fail closed unless *app_path* is the genuinely-signed CuaDriver.app. ``/usr/bin/open`` - hands LaunchServices whatever bundle sits at the path, so ``codesign -dv`` must report EXACTLY - ``Identifier=com.trycua.driver`` and an expected TeamIdentifier. ``TeamIdentifier=not set`` - (ad-hoc dev builds) is allowed only with ``computer_use.allow_unsigned_driver: true``. - Raises RuntimeError on any mismatch or when codesign is unavailable/fails.""" + """Fail closed unless *app_path* is the genuinely-signed CuaDriver.app. ``/usr/bin/open`` hands + LaunchServices whatever bundle sits at the path, so ``codesign -dv`` must report EXACTLY + ``Identifier=com.trycua.driver`` and an expected TeamIdentifier. ``TeamIdentifier=not set`` (ad-hoc dev + builds) is allowed only with ``computer_use.allow_unsigned_driver: true``. Raises RuntimeError on any + mismatch or when codesign is unavailable/fails.""" codesign = shutil.which("codesign") if not codesign: raise RuntimeError("codesign is required to verify CuaDriver.app before launching it.") @@ -104,18 +102,18 @@ def _wait_or_kill(process: Any) -> None: class _EmbeddedCuaDaemon: """Private daemon for a non-standard permission mode. - cua-driver's permission mode is immutable after daemon startup, so reusing the - machine-wide daemon would let one Hermes session's YOLO choice affect another. A private - daemon gives the session its own socket, runtime and launch-time authorization; on macOS - it is launched through CuaDriver.app so TCC stays attached to ``com.trycua.driver``. + cua-driver's permission mode is immutable after daemon startup, so reusing the machine-wide daemon + would let one Hermes session's YOLO choice affect another. A private daemon gives the session its own + socket, runtime and launch-time authorization; on macOS it is launched through CuaDriver.app so TCC + stays attached to ``com.trycua.driver``. * ``unrestricted`` — explicit Hermes YOLO (``--dangerously-bypass-approvals``). - * ``bounded`` — a user-reviewed capability manifest approved at launch is the - authorization boundary, not a runtime prompt. + * ``bounded`` — a user-reviewed capability manifest approved at launch is the authorization + boundary, not a runtime prompt. - The manifest is a ceiling, not a mode: it "can narrow a profile but never widen it", so a - configured v3 manifest is forwarded even for ``unrestricted`` (bounding an approval-bypassed - run). Mandatory for ``bounded``, optional everywhere else. + The manifest is a ceiling, not a mode: it "can narrow a profile but never widen it", so a configured + v3 manifest is forwarded even for ``unrestricted`` (bounding an approval-bypassed run). Mandatory for + ``bounded``, optional everywhere else. """ _START_TIMEOUT_SECONDS = 15.0 @@ -131,8 +129,8 @@ class _EmbeddedCuaDaemon: if not os.path.isfile(manifest): raise ValueError(f"capability manifest not found: {manifest}") self.capability_manifest: Optional[str] = manifest or None - # bounded always forwards (the driver validates it); other modes accept only a v3 - # manifest — a legacy one would abort startup instead. + # bounded always forwards (the driver validates it); other modes accept only a v3 manifest — a + # legacy one would abort startup instead. self.manifest_applies = bool(manifest) and ( permission_mode == "bounded" or _cb()._manifest_is_mode_independent(manifest)) if manifest and not self.manifest_applies: @@ -160,7 +158,6 @@ class _EmbeddedCuaDaemon: def _sanitized_env(self) -> Dict[str, str]: from tools.environments.local import _sanitize_subprocess_env - return _sanitize_subprocess_env(self.child_env()) def _drain_stderr(self, process: Any) -> None: @@ -180,9 +177,9 @@ class _EmbeddedCuaDaemon: serve_args.append("--dangerously-bypass-approvals") if self.manifest_applies: serve_args += ["--capability-manifest", str(self.capability_manifest), "--approve-capability-manifest"] - # The private daemon owns the cursor overlay, so the overlay policy must apply to this - # long-lived serve process, not only its MCP proxy. Appended BEFORE the macOS app-launch - # wrapping so the flag travels inside `open ... --args` with the rest of the serve args. + # The private daemon owns the cursor overlay, so the overlay policy must apply to this long-lived + # serve process, not only its MCP proxy. Appended BEFORE the macOS app-launch wrapping so the flag + # travels inside `open ... --args` with the rest of the serve args. return _cb()._mcp_args_with_overlay_flag(serve_args, driver_cmd=self._command) def start(self) -> None: @@ -204,8 +201,8 @@ class _EmbeddedCuaDaemon: deadline = time.monotonic() + self._START_TIMEOUT_SECONDS while time.monotonic() < deadline: return_code = self._process.poll() - # `open` exits 0 once LaunchServices took the request, so on macOS only a - # non-zero exit means the daemon itself died. + # `open` exits 0 once LaunchServices took the request, so on macOS only a non-zero exit means + # the daemon itself died. if return_code is not None and (not self._launch_via_app or return_code != 0): detail = "; ".join(self._stderr_tail) or "no diagnostic output" raise RuntimeError(f"embedded cua-driver exited during startup: {detail}") diff --git a/tools/computer_use/cua_backend_driver.py b/tools/computer_use/cua_backend_driver.py index 81a4b656c4..a6476f0a20 100644 --- a/tools/computer_use/cua_backend_driver.py +++ b/tools/computer_use/cua_backend_driver.py @@ -1,9 +1,7 @@ -"""cua-driver binary resolution, MCP-invocation discovery, the 0.20 runtime -contract gate, and the update check. - -Config-derived policy (``_cua_no_overlay``, ``_run_driver`` ...) is looked up -lazily through ``tools.computer_use.cua_backend`` so tests that patch it there -keep working; logger name parity is kept for the same reason. +"""cua-driver binary resolution, MCP-invocation discovery, the 0.20 runtime contract gate, and the +update check. Config-derived policy (``_cua_no_overlay``, ``_run_driver`` ...) is looked up lazily +through ``tools.computer_use.cua_backend`` so tests that patch it there keep working; logger name +parity is kept for the same reason. """ from __future__ import annotations @@ -21,18 +19,15 @@ from typing import Any, Dict, List, Optional, Tuple logger = logging.getLogger("tools.computer_use.cua_backend") -# No version *pin* knob on purpose: the upstream installer always fetches the -# latest release, so a pin var would only LOOK like it pinned. Point -# HERMES_CUA_DRIVER_CMD at a specific binary instead. +# No version *pin* knob on purpose: the upstream installer always fetches the latest release, so a pin +# var would only LOOK like it pinned. Point HERMES_CUA_DRIVER_CMD at a specific binary instead. _CUA_DRIVER_CMD_ENV = "HERMES_CUA_DRIVER_CMD" _CUA_DRIVER_DEFAULT_CMD = "cua-driver" _CUA_DRIVER_ARGS = ["mcp"] # stdio MCP; fallback when the driver has no `manifest` verb - _CUA_DRIVER_RUNTIME_CONTRACT_MIN = (0, 20, 0) -_CUA_DRIVER_RUNTIME_CONTRACT_ARGS = { +_CUA_DRIVER_RUNTIME_CONTRACT_ARGS = { # key order feeds the "manifest is missing" text "mcp": {"--socket", "--grant"}, - "serve": {"--socket", "--permission-mode", "--capability-manifest", - "--approve-capability-manifest", "--embedded"}, + "serve": {"--socket", "--permission-mode", "--capability-manifest", "--approve-capability-manifest", "--embedded"}, "stop": {"--socket"}, } _SEMVER_RE = re.compile(r"v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?") @@ -41,13 +36,12 @@ _UPSTREAM_SCRIPTS = "https://raw.githubusercontent.com/trycua/cua/main/libs/cua- def _cb(): """Origin module, looked up lazily so ``patch("tools.computer_use.cua_backend.X")`` applies.""" from tools.computer_use import cua_backend - return cua_backend def _driver_json(driver_cmd: str, *args: str, timeout: float, require_ok: bool) -> Optional[Dict[str, Any]]: - """Run a driver verb and parse its stdout as a JSON object; None on spawn - failure, empty stdout (older drivers print usage to stderr), unparseable or - non-object output — and, with ``require_ok``, on a non-zero exit.""" + """Run a driver verb and parse its stdout as a JSON object; None on spawn failure, empty stdout (older + drivers print usage to stderr), unparseable or non-object output — and, with ``require_ok``, on a + non-zero exit.""" proc = _cb()._run_driver(driver_cmd, *args, timeout=timeout, swallow=Exception) out = (proc.stdout or "").strip() if proc is not None else "" if not out or (require_ok and proc.returncode != 0): @@ -64,23 +58,18 @@ def _valid_mcp_args(invocation: Any) -> Optional[List[str]]: return args if isinstance(args, list) and all(isinstance(a, str) for a in args) else None -# --------------------------------------------------------------------------- -# Binary resolution -# --------------------------------------------------------------------------- - +# ── Binary resolution ───────────────────────────────────────────────────── def _has_path_separator(value: str) -> bool: return os.sep in value or (os.altsep is not None and os.altsep in value) def _wsl_windows_path_to_posix(path: str) -> str: - """Translate a Windows absolute manifest command to its DrvFS - ``/mnt//...`` form when Hermes runs in WSL (a Windows cua-driver - manifest can report ``C:\\...`` while Hermes spawns via POSIX). Non-Windows + """Translate a Windows absolute manifest command to its DrvFS ``/mnt//...`` form when Hermes runs + in WSL (a Windows cua-driver manifest can report ``C:\\...`` while Hermes spawns via POSIX). Non-Windows paths and non-WSL hosts are returned unchanged.""" if not re.match(r"^[A-Za-z]:[\\/]", path): return path try: from hermes_constants import is_wsl - if not is_wsl(): return path except Exception: @@ -92,11 +81,10 @@ def _wsl_windows_path_to_posix(path: str) -> str: return os.path.join("/mnt", drive, *(str(part) for part in win.parts[1:])) def _candidate_cua_driver_commands(override: Optional[str] = None) -> List[str]: - """Candidate commands in resolution order. ``override`` / a non-empty - ``HERMES_CUA_DRIVER_CMD`` is authoritative (if wrong, report the driver - missing rather than silently picking another binary). Otherwise PATH, then - canonical installer locations — Finder/Dock-launched apps inherit a narrow - PATH without ``~/.local/bin``; fresh Windows sessions inherit a stale one.""" + """Candidate commands in resolution order. ``override`` / a non-empty ``HERMES_CUA_DRIVER_CMD`` is + authoritative (if wrong, report the driver missing rather than silently picking another binary). + Otherwise PATH, then canonical installer locations — Finder/Dock-launched apps inherit a narrow PATH + without ``~/.local/bin``; fresh Windows sessions inherit a stale one.""" configured = (override if override is not None else os.environ.get(_CUA_DRIVER_CMD_ENV, "")).strip() if configured: return [configured] @@ -104,16 +92,15 @@ def _candidate_cua_driver_commands(override: Optional[str] = None) -> List[str]: if sys.platform == "win32": local_app_data = os.environ.get("LOCALAPPDATA") or os.path.join(home, "AppData", "Local") installed = [os.path.join(local_app_data, "Programs", "Cua", "cua-driver", "bin", "cua-driver.exe"), - os.path.join(home, ".local", "bin", "cua-driver.exe"), - os.path.join(home, ".local", "bin", "cua-driver")] + os.path.join(home, ".local", "bin", "cua-driver.exe"), os.path.join(home, ".local", "bin", "cua-driver")] else: installed = [os.path.join(home, ".local", "bin", "cua-driver"), os.path.join(home, ".cargo", "bin", "cua-driver"), "/opt/homebrew/bin/cua-driver", "/usr/local/bin/cua-driver"] return [_CUA_DRIVER_DEFAULT_CMD, *installed] def resolve_cua_driver_cmd(override: Optional[str] = None) -> Optional[str]: - """Resolve the cua-driver executable for every runtime/status surface. - An override is never silently replaced by another binary.""" + """Resolve the cua-driver executable for every runtime/status surface. An override is never silently + replaced by another binary.""" for candidate in _candidate_cua_driver_commands(override): expanded = os.path.expanduser(candidate) resolved = shutil.which(expanded) @@ -128,17 +115,12 @@ def cua_driver_binary_available() -> bool: def cua_driver_install_hint() -> str: installer = (f" irm {_UPSTREAM_SCRIPTS}/install.ps1 | iex" if sys.platform == "win32" else f' /bin/bash -c "$(curl -fsSL {_UPSTREAM_SCRIPTS}/install.sh)"') - return ("cua-driver is not installed. Install with one of:\n" - " hermes computer-use install\n" - "Or run the upstream installer directly:\n" - f"{installer}\n" + return ("cua-driver is not installed. Install with one of:\n hermes computer-use install\n" + f"Or run the upstream installer directly:\n{installer}\n" "Or run `hermes tools` and enable the Computer Use toolset to install it automatically.") -# --------------------------------------------------------------------------- -# MCP invocation -# --------------------------------------------------------------------------- - +# ── MCP invocation ──────────────────────────────────────────────────────── def _mcp_args_with_overlay_flag(args: List[str], driver_cmd: str = _CUA_DRIVER_DEFAULT_CMD) -> List[str]: """Return *args* with ``--no-overlay`` appended when configured and supported.""" if _cb()._cua_no_overlay() and _cb()._cua_driver_supports_no_overlay(driver_cmd): @@ -147,8 +129,8 @@ def _mcp_args_with_overlay_flag(args: List[str], driver_cmd: str = _CUA_DRIVER_D @functools.lru_cache(maxsize=1) def _cua_driver_supports_no_overlay(driver_cmd: str) -> bool: - """True if `` --help`` mentions ``--no-overlay`` (probed once). - Older drivers reject unknown flags, which would crash the MCP spawn.""" + """True if `` --help`` mentions ``--no-overlay`` (probed once). Older drivers reject unknown + flags, which would crash the MCP spawn.""" try: proc = _cb()._run_driver(driver_cmd, "--help", timeout=3.0) return "--no-overlay" in (proc.stdout or "") + (proc.stderr or "") @@ -156,10 +138,9 @@ def _cua_driver_supports_no_overlay(driver_cmd: str) -> bool: return False def _resolve_mcp_invocation(driver_cmd: str, *, timeout: float = 6.0) -> Tuple[str, List[str]]: - """``(command, args)`` that spawn cua-driver's stdio MCP server, asked of - the driver itself via ``cua-driver manifest`` (``mcp_invocation``) so a - subcommand rename keeps working. Falls back to ``(driver_cmd, ["mcp"])`` on - older drivers or any discovery failure — the wrapper must not refuse to + """``(command, args)`` that spawn cua-driver's stdio MCP server, asked of the driver itself via + ``cua-driver manifest`` (``mcp_invocation``) so a subcommand rename keeps working. Falls back to + ``(driver_cmd, ["mcp"])`` on older drivers or any discovery failure — the wrapper must not refuse to start over a failed discovery hop. ``--no-overlay`` appended when allowed.""" manifest = _driver_json(driver_cmd, "manifest", timeout=timeout, require_ok=True) or {} invocation = manifest.get("mcp_invocation") @@ -167,24 +148,19 @@ def _resolve_mcp_invocation(driver_cmd: str, *, timeout: float = 6.0) -> Tuple[s command = invocation.get("command") if args is not None and isinstance(invocation, dict) else None args = list(_CUA_DRIVER_ARGS) if args is None else args if isinstance(command, str) and command: - # Translate a Windows ``C:\...`` command for WSL BEFORE the separator - # check (backslash is not a separator on POSIX). A generic ``cua-driver`` - # name would lose the resolved user-local path under a GUI's thin PATH, - # so only a concrete (path-bearing) command replaces the one we verified - # — and THAT binary is probed for `--no-overlay`, not the system one. + # Translate a Windows ``C:\...`` command for WSL BEFORE the separator check (backslash is not a + # separator on POSIX). A generic ``cua-driver`` name would lose the resolved user-local path under + # a GUI's thin PATH, so only a concrete (path-bearing) command replaces the one we verified — and + # THAT binary is probed for `--no-overlay`, not the system one. command = _wsl_windows_path_to_posix(command) if _has_path_separator(command): return command, _mcp_args_with_overlay_flag(args, driver_cmd=command) return driver_cmd, _mcp_args_with_overlay_flag(args, driver_cmd=driver_cmd) -# --------------------------------------------------------------------------- -# Runtime contract + update checking -# --------------------------------------------------------------------------- -# -# cua-driver's native `check-update` verb compares the installed binary against -# the latest GitHub release (cached ~20h); we prefer it over a hardcoded floor. - +# ── Runtime contract + update checking ──────────────────────────────────── +# cua-driver's native `check-update` verb compares the installed binary against the latest GitHub +# release (cached ~20h); we prefer it over a hardcoded floor. def _manifest_contract_gaps(manifest: Dict[str, Any]) -> List[str]: """``" "`` entries the driver's advertised subcommands lack.""" advertised: Dict[str, set[str]] = { @@ -196,6 +172,20 @@ def _manifest_contract_gaps(manifest: Dict[str, Any]) -> List[str]: return [f"{command} {arg}" for command, required in _CUA_DRIVER_RUNTIME_CONTRACT_ARGS.items() for arg in sorted(required - advertised.get(command, set()))] +def _manifest_contract_reason(manifest: Optional[Dict[str, Any]]) -> str: + """Why a parsed manifest fails the 0.20 contract, or ``""`` when it passes.""" + if manifest is None: + return "driver manifest is missing or invalid" + match = _SEMVER_RE.fullmatch(str(manifest.get("binary_version") or "").strip()) + if not match: + return "driver manifest does not report a semantic version" + if tuple(int(part) for part in match.groups()) < _CUA_DRIVER_RUNTIME_CONTRACT_MIN: + return "Hermes computer use requires cua-driver 0.20.0 or newer" + if not _valid_mcp_args(manifest.get("mcp_invocation")): + return "driver manifest does not provide an MCP launch command" + missing = _manifest_contract_gaps(manifest) + return "driver manifest is missing: " + ", ".join(missing) if missing else "" + def cua_driver_runtime_contract_status(binary: Optional[str] = None) -> Dict[str, Any]: """Report whether a local driver can host Hermes' 0.20 integration.""" resolved = binary or _cb().resolve_cua_driver_cmd() @@ -214,33 +204,18 @@ def cua_driver_runtime_contract_status(binary: Optional[str] = None) -> Dict[str manifest = json.loads(result.stdout or "") except (TypeError, ValueError): manifest = None - reason = _manifest_contract_reason(manifest if isinstance(manifest, dict) else None) - if isinstance(manifest, dict): + manifest = manifest if isinstance(manifest, dict) else None + reason = _manifest_contract_reason(manifest) + if manifest is not None: version = str(manifest.get("binary_version") or "").strip() or None return {"ready": not reason, "binary": resolved, "version": version, "reason": reason} -def _manifest_contract_reason(manifest: Optional[Dict[str, Any]]) -> str: - """Why a parsed manifest fails the 0.20 contract, or ``""`` when it passes.""" - if manifest is None: - return "driver manifest is missing or invalid" - match = _SEMVER_RE.fullmatch(str(manifest.get("binary_version") or "").strip()) - if not match: - return "driver manifest does not report a semantic version" - if tuple(int(part) for part in match.groups()) < _CUA_DRIVER_RUNTIME_CONTRACT_MIN: - return "Hermes computer use requires cua-driver 0.20.0 or newer" - if not _valid_mcp_args(manifest.get("mcp_invocation")): - return "driver manifest does not provide an MCP launch command" - missing = _manifest_contract_gaps(manifest) - return "driver manifest is missing: " + ", ".join(missing) if missing else "" - def cua_driver_update_check(*, timeout: Optional[float] = None) -> Optional[Dict[str, Any]]: - """``cua-driver check-update --json`` payload (``{current_version, - latest_version, update_available, ...}``), or ``None`` when the binary is - missing, the driver predates the verb, the GitHub check failed (``error`` - set) or the output didn't parse. Never raises. ``timeout`` defaults to 8s - on POSIX / 25s on Windows: first spawn of the exe routinely eats seconds in - Defender scanning, and callers treat ``None`` as indeterminate (the upgrade - path used to fall through to a full reinstall on a false timeout).""" + """``cua-driver check-update --json`` payload (``{current_version, latest_version, update_available, + ...}``), or ``None`` when the binary is missing, the driver predates the verb, the GitHub check failed + (``error`` set) or the output didn't parse. Never raises. ``timeout`` defaults to 8s on POSIX / 25s on + Windows: first spawn of the exe routinely eats seconds in Defender scanning, and callers treat ``None`` + as indeterminate (the upgrade path used to fall through to a full reinstall on a false timeout).""" if timeout is None: timeout = 25.0 if sys.platform == "win32" else 8.0 driver_cmd = _cb().resolve_cua_driver_cmd() @@ -250,11 +225,10 @@ def cua_driver_update_check(*, timeout: Optional[float] = None) -> Optional[Dict return None if data is None or data.get("error") else data def cua_driver_update_nudge() -> Optional[str]: - """One-line "an update is available" message, or ``None`` when up to date, - indeterminate, or the driver is too old to report.""" + """One-line "an update is available" message, or ``None`` when up to date, indeterminate, or the driver + is too old to report.""" state = _cb().cua_driver_update_check() if not state or not state.get("update_available"): return None return (f"cua-driver {state.get('latest_version') or '?'} is available " - f"(you have {state.get('current_version') or '?'}); " - f"update with `hermes computer-use install --upgrade`.") + f"(you have {state.get('current_version') or '?'}); update with `hermes computer-use install --upgrade`.") From 22def3f4a90b924f0534022c83ba6eec8715d7e1 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 21:02:05 -0700 Subject: [PATCH 3/4] refactor(computer_use): contextlib rollback/suppress in cua backend + daemon; _json_object helper; daemon startup-failure helper; tighten prose --- tools/computer_use/cua_backend.py | 180 ++++++++++------------- tools/computer_use/cua_backend_daemon.py | 89 +++++------ tools/computer_use/cua_backend_driver.py | 74 +++++----- 3 files changed, 148 insertions(+), 195 deletions(-) diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.py index 7d1718e463..d9da879f41 100644 --- a/tools/computer_use/cua_backend.py +++ b/tools/computer_use/cua_backend.py @@ -1,17 +1,11 @@ -"""Cua-driver backend (macOS, Windows, Linux): MCP over stdio to `cua-driver`. - -The async `mcp` SDK runs on a background loop (``cua_backend_session``); the same tool surface -works on all three platforms, and per-host gaps (no DISPLAY, missing AT-SPI, TCC) surface via -`hermes computer-use doctor` instead of failing silently. Install with `hermes computer-use -install`. The macOS path uses private SkyLight SPIs that can break on OS updates. - -Siblings: ``cua_backend_driver`` (binary resolution, runtime contract, update check), -``cua_backend_capture`` / ``cua_backend_input`` (backend mixins), ``cua_backend_parse`` (pure -parsing), ``cua_backend_session`` (bridge + session + CLI fallback), ``cua_backend_daemon`` -(private daemon + macOS app identity). Moved names are re-imported here so -``patch("tools.computer_use.cua_backend.X")`` keeps working; siblings look policy helpers up -lazily through this module. -""" +"""Cua-driver backend (macOS, Windows, Linux): MCP over stdio to `cua-driver`. The async `mcp` SDK runs on a +background loop (``cua_backend_session``); the same tool surface works on all three platforms, and per-host gaps +(no DISPLAY, missing AT-SPI, TCC) surface via `hermes computer-use doctor` instead of failing silently. Install +with `hermes computer-use install`. The macOS path uses private SkyLight SPIs that can break on OS updates. +Siblings: ``cua_backend_driver`` (binary/contract/update), ``cua_backend_capture`` + ``cua_backend_input`` +(mixins), ``cua_backend_parse``, ``cua_backend_session`` (bridge + session + CLI fallback), ``cua_backend_daemon`` +(private daemon + macOS app identity). Moved names are re-imported here so ``patch("tools.computer_use.cua_backend.X")`` +keeps working; siblings look policy helpers up lazily through this module.""" from __future__ import annotations @@ -59,11 +53,10 @@ def _computer_use_cfg() -> Dict[str, Any]: return {} def _cua_no_overlay() -> bool: - """Pass ``--no-overlay``? ``computer_use.no_overlay`` overrides; else off on macOS (cursor-overlay - redraw loop can peg a core after a session), headless Linux / WSL2 / containers, and Linux X11 (the - overlay is a fullscreen always-on-top all-workspaces window with no compositor-owned lifecycle, so an - unclean session end can leave it wedged over every app); on for Windows and Linux Wayland - (compositor owns the surface).""" + """Pass ``--no-overlay``? ``computer_use.no_overlay`` overrides; else off on macOS (cursor-overlay redraw + loop can peg a core after a session), headless Linux / WSL2 / containers, and Linux X11 (the overlay is a + fullscreen always-on-top all-workspaces window with no compositor-owned lifecycle, so an unclean session + end can leave it wedged over every app); on for Windows and Linux Wayland (compositor owns the surface).""" val = _computer_use_cfg().get("no_overlay") if val is not None: return bool(val) @@ -71,12 +64,9 @@ def _cua_no_overlay() -> bool: return sys.platform == "darwin" if not os.environ.get("DISPLAY"): return True - try: - with open("/proc/version", encoding="utf-8") as f: - if "microsoft" in f.read().lower(): - return True - except Exception: - pass + with contextlib.suppress(Exception), open("/proc/version", encoding="utf-8") as f: + if "microsoft" in f.read().lower(): + return True return os.environ.get("XDG_SESSION_TYPE") != "wayland" and not os.environ.get("WAYLAND_DISPLAY") def _cua_telemetry_disabled() -> bool: @@ -84,9 +74,9 @@ def _cua_telemetry_disabled() -> bool: return not bool(_computer_use_cfg().get("cua_telemetry", False)) def _cua_configured_permission_mode() -> str: - """``computer_use.permission_mode``: ``standard`` (default) or ``bounded``; unknown values fall closed - to ``standard``. ``unrestricted`` is deliberately NOT a config value — it stays tied to the per-session - YOLO toggle so a stale config line can never silently bypass approvals.""" + """``computer_use.permission_mode``: ``standard`` (default) or ``bounded``; unknown values fall closed to + ``standard``. ``unrestricted`` is deliberately NOT a config value — it stays tied to the per-session YOLO + toggle so a stale config line can never silently bypass approvals.""" raw = str(_computer_use_cfg().get("permission_mode", "standard") or "").strip().lower() return raw if raw in {"standard", "bounded"} else "standard" @@ -115,9 +105,8 @@ def _computer_use_max_image_dimension() -> Optional[int]: return dim if dim > 0 else None def cua_driver_child_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str, str]: - """Env for spawning cua-driver: ``base_env`` (default ``os.environ``) plus - ``CUA_DRIVER_RS_TELEMETRY_ENABLED=0`` unless the user opted in. Used by every spawn site (MCP, - status, doctor, install) so the policy is uniform.""" + """Env for spawning cua-driver: ``base_env`` (default ``os.environ``) plus ``CUA_DRIVER_RS_TELEMETRY_ENABLED=0`` + unless the user opted in. Used by every spawn site (MCP, status, doctor, install) so the policy is uniform.""" env = dict(base_env if base_env is not None else os.environ) if _cua_telemetry_disabled(): env[_CUA_TELEMETRY_ENV_VAR] = "0" @@ -134,9 +123,9 @@ def sanitized_cua_driver_env() -> Dict[str, str]: return env def _run_quiet(argv: List[str], *, timeout: float, swallow: Any = (), **kw: Any) -> Any: - """``subprocess.run`` for short probe verbs: text mode, stdin=DEVNULL (older drivers fall into a - stdin-reading mode on unknown verbs; EOF makes them exit fast instead of blocking until the timeout), - output captured unless the caller redirects it. Exceptions in ``swallow`` return None; others raise.""" + """``subprocess.run`` for short probe verbs: text mode, stdin=DEVNULL (older drivers fall into a stdin-reading + mode on unknown verbs; EOF makes them exit fast instead of blocking until the timeout), output captured unless + the caller redirects it. Exceptions in ``swallow`` return None; others raise.""" if "stdout" not in kw: kw["capture_output"] = True try: @@ -152,26 +141,20 @@ def _run_driver(driver_cmd: str, *args: str, timeout: float, swallow: Any = ()) # ── Linux display diagnostics ───────────────────────────────────────────── def _linux_session_locked() -> Optional[bool]: - """Is the graphical session locked? (Linux; best-effort.) A locked KDE/GNOME session freezes renderers - and half-disables the AX tree, so discovery legitimately returns nothing — which otherwise reads as a - driver bug. True/False when loginctl answers, None when unavailable (non-Linux, no systemd-logind, - probe failure).""" + """Is the graphical session locked? (Linux; best-effort.) A locked KDE/GNOME session freezes renderers and + half-disables the AX tree, so discovery legitimately returns nothing — which otherwise reads as a driver bug. + True/False when loginctl answers, None when unavailable (non-Linux, no systemd-logind, probe failure).""" if sys.platform != "linux": return None try: proc = _run_quiet(["loginctl", "list-sessions", "--no-legend"], timeout=2.0) if proc.returncode != 0: return None - any_seat = False - for line in proc.stdout.splitlines(): - parts = line.split() - if len(parts) < 2 or "seat" not in line: - continue - any_seat = True - hint = _run_quiet(["loginctl", "show-session", parts[0], "-p", "LockedHint"], timeout=2.0) - if "LockedHint=no" in hint.stdout: + seats = [line.split()[0] for line in proc.stdout.splitlines() if len(line.split()) >= 2 and "seat" in line] + for session_id in seats: + if "LockedHint=no" in _run_quiet(["loginctl", "show-session", session_id, "-p", "LockedHint"], timeout=2.0).stdout: return False - return True if any_seat else None + return True if seats else None except Exception: return None @@ -197,15 +180,15 @@ def _empty_discovery_reason() -> str: # ── One-shot start() helpers: auto-repair + update nudge ────────────────── _update_checked = False -# One auto-repair attempt per process: when the runtime-contract gate fails for something a reinstall -# fixes (old version, missing manifest verbs) run the standard install path once instead of telling the -# user to. Guarded so a failing installer can't loop — the second start() goes straight to the error. +# One auto-repair attempt per process: when the runtime-contract gate fails for something a reinstall fixes +# (old version, missing manifest verbs) run the standard install path once instead of telling the user to. +# Guarded so a failing installer can't loop — the second start() goes straight to the error. _contract_repair_attempted = False def _maybe_repair_runtime_contract(contract: Dict[str, Any]) -> Dict[str, Any]: """Try one automatic driver repair; return the post-repair contract (or the original when no repair was - attempted / it failed). Never raises. An explicit ``HERMES_CUA_DRIVER_CMD`` override is authoritative - even when broken, and a missing binary means installation was never requested.""" + attempted / it failed). Never raises. An explicit ``HERMES_CUA_DRIVER_CMD`` override is authoritative even + when broken, and a missing binary means installation was never requested.""" global _contract_repair_attempted if (contract.get("ready") or _contract_repair_attempted or os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() or not contract.get("binary")): @@ -225,20 +208,18 @@ def _maybe_repair_runtime_contract(contract: Dict[str, Any]) -> Dict[str, Any]: return contract def _maybe_nudge_update() -> None: - """Emit an update nudge at most once per process, off-thread so the (cached, ~20h) GitHub poll never - blocks the first computer_use action.""" + """Emit an update nudge at most once per process, off-thread so the (cached, ~20h) GitHub poll never blocks + the first computer_use action.""" global _update_checked if _update_checked: return _update_checked = True def _run() -> None: - try: + with contextlib.suppress(Exception): msg = cua_driver_update_nudge() - except Exception: - return - if msg: - logger.info("computer_use: %s", msg) + if msg: + logger.info("computer_use: %s", msg) threading.Thread(target=_run, name="cua-driver-update-check", daemon=True).start() @@ -260,18 +241,13 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): capability_manifest=raw.strip() if isinstance(raw, str) and raw.strip() else None) self._bridge = _AsyncBridge() self._session = _CuaDriverSession(self._bridge, self._embedded_daemon) - # Sticky target — set by capture()/focus_app(), used by actions. `_last_target` is the exact - # identity for capture_after: Linux app names may be generic (several unrelated Qt windows can - # all say Qt6Application). `_snapshot_tokens` is the per-snapshot `element_index -> - # element_token`; actions attach it so cua-driver reports "stale" instead of silently re-resolving. - self._active_pid: Optional[int] = None - self._active_window_id: Optional[int] = None - self._last_app: Optional[str] = None - self._last_target: Optional[Dict[str, Optional[int]]] = None - self._snapshot_tokens: Dict[int, str] = {} - # Public session label (one per Hermes run) sent as `session` on every call: owns the cursor - # color and gives config/recording state a stable owner across transport restarts. Part of - # the 0.20 runtime contract. + # Sticky target — set by capture()/focus_app(), used by actions: `_active_pid`, `_active_window_id`, + # `_last_app`, `_last_target` (exact identity for capture_after: Linux app names may be generic — several + # unrelated Qt windows can all say Qt6Application) and `_snapshot_tokens` (per-snapshot `element_index -> + # element_token`; actions attach it so cua-driver reports "stale" instead of silently re-resolving). + self._clear_active_target() + # Public session label (one per Hermes run) sent as `session` on every call: owns the cursor color and + # gives config/recording state a stable owner across transport restarts. Part of the 0.20 runtime contract. self._session_id: str = f"hermes-{uuid.uuid4().hex[:12]}" self._session.set_transport_reset_callback(self._handle_transport_reset) @@ -286,31 +262,26 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): contract = _maybe_repair_runtime_contract(contract) if not contract.get("ready"): repair = ("Update the binary selected by HERMES_CUA_DRIVER_CMD or remove that override." - if os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() - else "Run `hermes computer-use install` to repair it.") - raise RuntimeError(f"cua-driver is not ready: " - f"{contract.get('reason') or 'runtime contract is incomplete'}. {repair}") + if os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() else "Run `hermes computer-use install` to repair it.") + raise RuntimeError(f"cua-driver is not ready: {contract.get('reason') or 'runtime contract is incomplete'}. {repair}") _maybe_nudge_update() # `mcp` is an optional extra: lazy-install on first use (gated by `security.allow_lazy_installs`); # failure raises FeatureUnavailable with the exact `uv pip install` hint. from tools.lazy_deps import ensure as _lazy_ensure _lazy_ensure("tool.computer_use", prompt=False) importlib.invalidate_caches() # a just-installed package may not be importable yet - daemon = self._embedded_daemon - try: - if daemon is not None: - daemon.start() + with contextlib.ExitStack() as rollback: # a failed start stops the private daemon, then re-raises + if self._embedded_daemon is not None: + rollback.callback(self._embedded_daemon.stop) + self._embedded_daemon.start() self._session.start() - except Exception: - if daemon is not None: - daemon.stop() - raise - # Declare this run's identity. Non-fatal: cua-driver accepts anonymous calls (the cursor just - # won't render), so degrade rather than abort. + rollback.pop_all() + # Declare this run's identity. Non-fatal: cua-driver accepts anonymous calls (the cursor just won't + # render), so degrade rather than abort. self._best_effort("start_session failed (continuing anonymous)", self._session.call_tool, "start_session", {"session": self._session_id}) - # Post-handshake tuning guards on `_started`: before the handshake flips it, call_tool would - # re-enter session.start() (stubbed start() recurses). + # Post-handshake tuning guards on `_started`: before the handshake flips it, call_tool would re-enter + # session.start() (stubbed start() recurses). if self._session._started: max_dim = _computer_use_max_image_dimension() if max_dim: # smaller screenshots cost less over the daemon socket and per turn @@ -321,8 +292,8 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): self.set_agent_cursor_enabled, False, cursor_id=self._session_id) def stop(self) -> None: - # Best-effort end_session so the driver cleans per-session state (cursor overlay, recording - # ownership, config overrides); the connection drop below releases daemon-side state regardless. + # Best-effort end_session so the driver cleans per-session state (cursor overlay, recording ownership, + # config overrides); the connection drop below releases daemon-side state regardless. if self._session._started: self._best_effort("end_session failed (continuing teardown)", self._session.call_tool, "end_session", {"session": self._session_id}) @@ -348,14 +319,17 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): # ── Target state ─────────────────────────────────────────────── def _clear_active_target(self) -> None: """Forget a capture/focus target so a failed lookup cannot misroute input.""" - self._active_pid = self._active_window_id = self._last_app = self._last_target = None - self._snapshot_tokens = {} + self._active_pid: Optional[int] = None + self._active_window_id: Optional[int] = None + self._last_app: Optional[str] = None + self._last_target: Optional[Dict[str, Optional[int]]] = None + self._snapshot_tokens: Dict[int, str] = {} def _set_active_target(self, target: Dict[str, Any]) -> None: self._active_pid = target["pid"] self._active_window_id = target["window_id"] - # Tokens belong to the prior snapshot; disarm before any capture call so an exception cannot - # pair old tokens with this target. + # Tokens belong to the prior snapshot; disarm before any capture call so an exception cannot pair old + # tokens with this target. self._snapshot_tokens = {} self._last_target = {"pid": self._active_pid, "window_id": self._active_window_id} @@ -363,9 +337,8 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): def launch_app(self, *, bundle_id: Optional[str] = None, name: Optional[str] = None, urls: Optional[List[str]] = None, additional_arguments: Optional[List[str]] = None, creates_new_application_instance: bool = False) -> Dict[str, Any]: - """Idempotent launch returning ``{pid, bundle_id, name, windows[]}``. - ``creates_new_application_instance=True`` forces a fresh instance so concurrent runs touching - the same app get isolated windows.""" + """Idempotent launch returning ``{pid, bundle_id, name, windows[]}``. ``creates_new_application_instance=True`` + forces a fresh instance so concurrent runs touching the same app get isolated windows.""" if not bundle_id and not name: raise ValueError("launch_app requires either bundle_id or name") args: Dict[str, Any] = {"session": self._session_id} @@ -382,8 +355,8 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): args: Dict[str, Any] = {"pid": int(pid)} if window_id is not None: args["window_id"] = int(window_id) - # The live schema is strict and has no session property: this is a standalone native focus - # operation, not a session-scoped input action. + # The live schema is strict and has no session property: this is a standalone native focus operation, + # not a session-scoped input action. return self._action("bring_to_front", args, inject_session=False) # ── Agent cursor / config ──────────────────────────────────────── @@ -400,18 +373,17 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): return self._action("set_config", dict(config)) def call_tool(self, name: str, args: Optional[Dict[str, Any]] = None, *, timeout: float = 30.0) -> Dict[str, Any]: - """Generic escape hatch: call any cua-driver MCP tool by name. ``session`` is injected via - setdefault, so this is the supported path for tools the wrapper does not type-wrap (preferred over - ``self._session.call_tool``).""" + """Generic escape hatch: call any cua-driver MCP tool by name. ``session`` is injected via setdefault, so + this is the supported path for tools the wrapper does not type-wrap (preferred over ``self._session.call_tool``).""" payload = dict(args) if args else {} payload.setdefault("session", self._session_id) return self._session.call_tool(name, payload, timeout=timeout) # ── Internal ─────────────────────────────────────────────────── def _action(self, name: str, args: Dict[str, Any], *, inject_session: bool = True) -> ActionResult: - # Attach the snapshot's `element_token` to an `element_index` call so a superseded snapshot - # yields an explicit 'stale' error. Gated on the per-tool capability: older drivers - # (`additionalProperties: false`) must never see the field. + # Attach the snapshot's `element_token` to an `element_index` call so a superseded snapshot yields an + # explicit 'stale' error. Gated on the per-tool capability: older drivers (`additionalProperties: false`) + # must never see the field. idx = args.get("element_index") token = self._snapshot_tokens.get(idx) if isinstance(idx, int) else None if token and self._session.supports_capability("accessibility.element_tokens", tool=name): diff --git a/tools/computer_use/cua_backend_daemon.py b/tools/computer_use/cua_backend_daemon.py index 92dd744f58..75f715b353 100644 --- a/tools/computer_use/cua_backend_daemon.py +++ b/tools/computer_use/cua_backend_daemon.py @@ -1,10 +1,10 @@ -"""Private embedded cua-driver daemon for non-standard permission modes, plus the macOS CuaDriver.app -identity checks its launch path depends on. Driver resolution / policy helpers are looked up lazily -through ``tools.computer_use.cua_backend`` so tests that patch them there keep working. -""" +"""Private embedded cua-driver daemon for non-standard permission modes, plus the macOS CuaDriver.app identity +checks its launch path depends on. Driver resolution / policy helpers are looked up lazily through +``tools.computer_use.cua_backend`` so tests that patch them there keep working.""" from __future__ import annotations +import contextlib import logging import os import shutil @@ -31,9 +31,9 @@ def _cb(): return cua_backend def _resolve_cua_driver_app_path(driver_cmd: str) -> Optional[str]: - """Return the CuaDriver.app bundle that CARRIES *driver_cmd*, if any. Derived from the resolved binary - path only — no /Applications fallback, which could be a DIFFERENT install than the one the manifest - resolved, running code the resolution chain never validated.""" + """Return the CuaDriver.app bundle that CARRIES *driver_cmd*, if any. Derived from the resolved binary path + only — no /Applications fallback, which could be a DIFFERENT install than the one the manifest resolved, + running code the resolution chain never validated.""" resolved = os.path.realpath(driver_cmd) marker_index = resolved.find(".app/Contents/MacOS/") if marker_index < 0: @@ -43,11 +43,11 @@ def _resolve_cua_driver_app_path(driver_cmd: str) -> Optional[str]: return candidate if os.path.isfile(executable) and os.access(executable, os.X_OK) else None def _validate_cua_driver_app_signature(app_path: str) -> None: - """Fail closed unless *app_path* is the genuinely-signed CuaDriver.app. ``/usr/bin/open`` hands - LaunchServices whatever bundle sits at the path, so ``codesign -dv`` must report EXACTLY - ``Identifier=com.trycua.driver`` and an expected TeamIdentifier. ``TeamIdentifier=not set`` (ad-hoc dev - builds) is allowed only with ``computer_use.allow_unsigned_driver: true``. Raises RuntimeError on any - mismatch or when codesign is unavailable/fails.""" + """Fail closed unless *app_path* is the genuinely-signed CuaDriver.app. ``/usr/bin/open`` hands LaunchServices + whatever bundle sits at the path, so ``codesign -dv`` must report EXACTLY ``Identifier=com.trycua.driver`` and + an expected TeamIdentifier. ``TeamIdentifier=not set`` (ad-hoc dev builds) is allowed only with + ``computer_use.allow_unsigned_driver: true``. Raises RuntimeError on any mismatch or when codesign is + unavailable/fails.""" codesign = shutil.which("codesign") if not codesign: raise RuntimeError("codesign is required to verify CuaDriver.app before launching it.") @@ -100,21 +100,14 @@ def _wait_or_kill(process: Any) -> None: class _EmbeddedCuaDaemon: - """Private daemon for a non-standard permission mode. - - cua-driver's permission mode is immutable after daemon startup, so reusing the machine-wide daemon - would let one Hermes session's YOLO choice affect another. A private daemon gives the session its own - socket, runtime and launch-time authorization; on macOS it is launched through CuaDriver.app so TCC - stays attached to ``com.trycua.driver``. - - * ``unrestricted`` — explicit Hermes YOLO (``--dangerously-bypass-approvals``). - * ``bounded`` — a user-reviewed capability manifest approved at launch is the authorization - boundary, not a runtime prompt. - - The manifest is a ceiling, not a mode: it "can narrow a profile but never widen it", so a configured - v3 manifest is forwarded even for ``unrestricted`` (bounding an approval-bypassed run). Mandatory for - ``bounded``, optional everywhere else. - """ + """Private daemon for a non-standard permission mode. cua-driver's permission mode is immutable after daemon + startup, so reusing the machine-wide daemon would let one Hermes session's YOLO choice affect another. A + private daemon gives the session its own socket, runtime and launch-time authorization; on macOS it is + launched through CuaDriver.app so TCC stays attached to ``com.trycua.driver``. ``unrestricted`` = explicit + Hermes YOLO (``--dangerously-bypass-approvals``); ``bounded`` = a user-reviewed capability manifest approved + at launch is the authorization boundary, not a runtime prompt. The manifest is a ceiling, not a mode: it "can + narrow a profile but never widen it", so a configured v3 manifest is forwarded even for ``unrestricted`` + (bounding an approval-bypassed run). Mandatory for ``bounded``, optional everywhere else.""" _START_TIMEOUT_SECONDS = 15.0 @@ -129,8 +122,8 @@ class _EmbeddedCuaDaemon: if not os.path.isfile(manifest): raise ValueError(f"capability manifest not found: {manifest}") self.capability_manifest: Optional[str] = manifest or None - # bounded always forwards (the driver validates it); other modes accept only a v3 manifest — a - # legacy one would abort startup instead. + # bounded always forwards (the driver validates it); other modes accept only a v3 manifest — a legacy one + # would abort startup instead. self.manifest_applies = bool(manifest) and ( permission_mode == "bounded" or _cb()._manifest_is_mode_independent(manifest)) if manifest and not self.manifest_applies: @@ -142,9 +135,8 @@ class _EmbeddedCuaDaemon: self._driver_cmd = self._command = driver_cmd self._mcp_args: List[str] = list(_cb()._CUA_DRIVER_ARGS) self._process: Any = None - self._owns_runtime = self._running = self._launch_via_app = False + self._owns_runtime = self._running = False self._stderr_tail: deque[str] = deque(maxlen=20) - self._stderr_thread: Optional[threading.Thread] = None token = uuid.uuid4().hex[:12] self.socket_path = (rf"\\.\pipe\hermes-cua-{token}" if sys.platform == "win32" else os.path.join(tempfile.gettempdir(), f"hc-{token}.sock")) @@ -161,14 +153,12 @@ class _EmbeddedCuaDaemon: return _sanitize_subprocess_env(self.child_env()) def _drain_stderr(self, process: Any) -> None: - try: + with contextlib.suppress(Exception): for line in getattr(process, "stderr", None) or (): text = str(line).strip() if text: self._stderr_tail.append(text) logger.debug("embedded cua-driver: %s", text) - except Exception: - pass def _serve_args(self) -> List[str]: serve_args = ["serve", "--embedded", "--socket", self.socket_path, @@ -177,9 +167,9 @@ class _EmbeddedCuaDaemon: serve_args.append("--dangerously-bypass-approvals") if self.manifest_applies: serve_args += ["--capability-manifest", str(self.capability_manifest), "--approve-capability-manifest"] - # The private daemon owns the cursor overlay, so the overlay policy must apply to this long-lived - # serve process, not only its MCP proxy. Appended BEFORE the macOS app-launch wrapping so the flag - # travels inside `open ... --args` with the rest of the serve args. + # The private daemon owns the cursor overlay, so the overlay policy must apply to this long-lived serve + # process, not only its MCP proxy. Appended BEFORE the macOS app-launch wrapping so the flag travels inside + # `open ... --args` with the rest of the serve args. return _cb()._mcp_args_with_overlay_flag(serve_args, driver_cmd=self._command) def start(self) -> None: @@ -190,29 +180,28 @@ class _EmbeddedCuaDaemon: raise RuntimeError(_cb().cua_driver_install_hint()) self._command, self._mcp_args = _cb()._resolve_mcp_invocation(self._driver_cmd) env = self._sanitized_env() - self._launch_via_app = sys.platform == "darwin" command = _embedded_daemon_spawn_command(self._command, self._serve_args(), platform=sys.platform) self._process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, env=env) self._owns_runtime = True - self._stderr_thread = threading.Thread(target=self._drain_stderr, args=(self._process,), - name="hermes-cua-daemon-stderr", daemon=True) - self._stderr_thread.start() + threading.Thread(target=self._drain_stderr, args=(self._process,), + name="hermes-cua-daemon-stderr", daemon=True).start() deadline = time.monotonic() + self._START_TIMEOUT_SECONDS while time.monotonic() < deadline: return_code = self._process.poll() - # `open` exits 0 once LaunchServices took the request, so on macOS only a non-zero exit means - # the daemon itself died. - if return_code is not None and (not self._launch_via_app or return_code != 0): - detail = "; ".join(self._stderr_tail) or "no diagnostic output" - raise RuntimeError(f"embedded cua-driver exited during startup: {detail}") + # `open` exits 0 once LaunchServices took the request, so on macOS only a non-zero exit means the + # daemon itself died. + if return_code is not None and (sys.platform != "darwin" or return_code != 0): + self._startup_failure("embedded cua-driver exited during startup", "no diagnostic output") if self._socket_ready(env): self._running = True return time.sleep(0.1) self.stop() - detail = "; ".join(self._stderr_tail) or "daemon did not become ready" - raise RuntimeError(f"embedded cua-driver startup timed out: {detail}") + self._startup_failure("embedded cua-driver startup timed out", "daemon did not become ready") + + def _startup_failure(self, what: str, fallback: str) -> None: + raise RuntimeError(f"{what}: {'; '.join(self._stderr_tail) or fallback}") def _socket_ready(self, env: Dict[str, str]) -> bool: """``cua-driver status --socket`` exits 0 once the private daemon accepts connections.""" @@ -236,7 +225,5 @@ class _EmbeddedCuaDaemon: if process is not None: _wait_or_kill(process) if sys.platform != "win32" and os.path.exists(self.socket_path): - try: + with contextlib.suppress(OSError): os.remove(self.socket_path) - except OSError: - pass diff --git a/tools/computer_use/cua_backend_driver.py b/tools/computer_use/cua_backend_driver.py index a6476f0a20..68e8c693e8 100644 --- a/tools/computer_use/cua_backend_driver.py +++ b/tools/computer_use/cua_backend_driver.py @@ -1,8 +1,6 @@ -"""cua-driver binary resolution, MCP-invocation discovery, the 0.20 runtime contract gate, and the -update check. Config-derived policy (``_cua_no_overlay``, ``_run_driver`` ...) is looked up lazily -through ``tools.computer_use.cua_backend`` so tests that patch it there keep working; logger name -parity is kept for the same reason. -""" +"""cua-driver binary resolution, MCP-invocation discovery, the 0.20 runtime contract gate, and the update check. +Config-derived policy (``_cua_no_overlay``, ``_run_driver`` ...) is looked up lazily through +``tools.computer_use.cua_backend`` so tests that patch it there keep working; logger name parity likewise.""" from __future__ import annotations @@ -39,15 +37,16 @@ def _cb(): return cua_backend def _driver_json(driver_cmd: str, *args: str, timeout: float, require_ok: bool) -> Optional[Dict[str, Any]]: - """Run a driver verb and parse its stdout as a JSON object; None on spawn failure, empty stdout (older - drivers print usage to stderr), unparseable or non-object output — and, with ``require_ok``, on a - non-zero exit.""" + """Run a driver verb and parse its stdout as a JSON object; None on spawn failure, empty stdout (older drivers + print usage to stderr), unparseable or non-object output — and, with ``require_ok``, on a non-zero exit.""" proc = _cb()._run_driver(driver_cmd, *args, timeout=timeout, swallow=Exception) out = (proc.stdout or "").strip() if proc is not None else "" - if not out or (require_ok and proc.returncode != 0): - return None + return None if not out or (require_ok and proc.returncode != 0) else _json_object(out) + +def _json_object(text: str) -> Optional[Dict[str, Any]]: + """``json.loads`` that yields a dict or None (unparseable / non-object).""" try: - data = json.loads(out) + data = json.loads(text) except (ValueError, TypeError): return None return data if isinstance(data, dict) else None @@ -63,9 +62,9 @@ def _has_path_separator(value: str) -> bool: return os.sep in value or (os.altsep is not None and os.altsep in value) def _wsl_windows_path_to_posix(path: str) -> str: - """Translate a Windows absolute manifest command to its DrvFS ``/mnt//...`` form when Hermes runs - in WSL (a Windows cua-driver manifest can report ``C:\\...`` while Hermes spawns via POSIX). Non-Windows - paths and non-WSL hosts are returned unchanged.""" + """Translate a Windows absolute manifest command to its DrvFS ``/mnt//...`` form when Hermes runs in WSL + (a Windows cua-driver manifest can report ``C:\\...`` while Hermes spawns via POSIX). Non-Windows paths and + non-WSL hosts are returned unchanged.""" if not re.match(r"^[A-Za-z]:[\\/]", path): return path try: @@ -81,10 +80,10 @@ def _wsl_windows_path_to_posix(path: str) -> str: return os.path.join("/mnt", drive, *(str(part) for part in win.parts[1:])) def _candidate_cua_driver_commands(override: Optional[str] = None) -> List[str]: - """Candidate commands in resolution order. ``override`` / a non-empty ``HERMES_CUA_DRIVER_CMD`` is - authoritative (if wrong, report the driver missing rather than silently picking another binary). - Otherwise PATH, then canonical installer locations — Finder/Dock-launched apps inherit a narrow PATH - without ``~/.local/bin``; fresh Windows sessions inherit a stale one.""" + """Candidate commands in resolution order. ``override`` / a non-empty ``HERMES_CUA_DRIVER_CMD`` is authoritative + (if wrong, report the driver missing rather than silently picking another binary). Otherwise PATH, then + canonical installer locations — Finder/Dock-launched apps inherit a narrow PATH without ``~/.local/bin``; + fresh Windows sessions inherit a stale one.""" configured = (override if override is not None else os.environ.get(_CUA_DRIVER_CMD_ENV, "")).strip() if configured: return [configured] @@ -138,20 +137,20 @@ def _cua_driver_supports_no_overlay(driver_cmd: str) -> bool: return False def _resolve_mcp_invocation(driver_cmd: str, *, timeout: float = 6.0) -> Tuple[str, List[str]]: - """``(command, args)`` that spawn cua-driver's stdio MCP server, asked of the driver itself via - ``cua-driver manifest`` (``mcp_invocation``) so a subcommand rename keeps working. Falls back to - ``(driver_cmd, ["mcp"])`` on older drivers or any discovery failure — the wrapper must not refuse to - start over a failed discovery hop. ``--no-overlay`` appended when allowed.""" + """``(command, args)`` that spawn cua-driver's stdio MCP server, asked of the driver itself via ``cua-driver + manifest`` (``mcp_invocation``) so a subcommand rename keeps working. Falls back to ``(driver_cmd, ["mcp"])`` + on older drivers or any discovery failure — the wrapper must not refuse to start over a failed discovery hop. + ``--no-overlay`` appended when allowed.""" manifest = _driver_json(driver_cmd, "manifest", timeout=timeout, require_ok=True) or {} invocation = manifest.get("mcp_invocation") args = _valid_mcp_args(invocation) command = invocation.get("command") if args is not None and isinstance(invocation, dict) else None args = list(_CUA_DRIVER_ARGS) if args is None else args if isinstance(command, str) and command: - # Translate a Windows ``C:\...`` command for WSL BEFORE the separator check (backslash is not a - # separator on POSIX). A generic ``cua-driver`` name would lose the resolved user-local path under - # a GUI's thin PATH, so only a concrete (path-bearing) command replaces the one we verified — and - # THAT binary is probed for `--no-overlay`, not the system one. + # Translate a Windows ``C:\...`` command for WSL BEFORE the separator check (backslash is not a separator + # on POSIX). A generic ``cua-driver`` name would lose the resolved user-local path under a GUI's thin PATH, + # so only a concrete (path-bearing) command replaces the one we verified — and THAT binary is probed for + # `--no-overlay`, not the system one. command = _wsl_windows_path_to_posix(command) if _has_path_separator(command): return command, _mcp_args_with_overlay_flag(args, driver_cmd=command) @@ -200,24 +199,19 @@ def cua_driver_runtime_contract_status(binary: Optional[str] = None) -> Dict[str detail = (result.stderr or result.stdout or "manifest command failed").strip() result, reason = None, detail.splitlines()[-1][:200] if result is not None: - try: - manifest = json.loads(result.stdout or "") - except (TypeError, ValueError): - manifest = None - manifest = manifest if isinstance(manifest, dict) else None + manifest = _json_object(result.stdout or "") reason = _manifest_contract_reason(manifest) if manifest is not None: version = str(manifest.get("binary_version") or "").strip() or None return {"ready": not reason, "binary": resolved, "version": version, "reason": reason} def cua_driver_update_check(*, timeout: Optional[float] = None) -> Optional[Dict[str, Any]]: - """``cua-driver check-update --json`` payload (``{current_version, latest_version, update_available, - ...}``), or ``None`` when the binary is missing, the driver predates the verb, the GitHub check failed - (``error`` set) or the output didn't parse. Never raises. ``timeout`` defaults to 8s on POSIX / 25s on - Windows: first spawn of the exe routinely eats seconds in Defender scanning, and callers treat ``None`` - as indeterminate (the upgrade path used to fall through to a full reinstall on a false timeout).""" - if timeout is None: - timeout = 25.0 if sys.platform == "win32" else 8.0 + """``cua-driver check-update --json`` payload (``{current_version, latest_version, update_available, ...}``), + or ``None`` when the binary is missing, the driver predates the verb, the GitHub check failed (``error`` set) + or the output didn't parse. Never raises. ``timeout`` defaults to 8s on POSIX / 25s on Windows: first spawn of + the exe routinely eats seconds in Defender scanning, and callers treat ``None`` as indeterminate (the upgrade + path used to fall through to a full reinstall on a false timeout).""" + timeout = (25.0 if sys.platform == "win32" else 8.0) if timeout is None else timeout driver_cmd = _cb().resolve_cua_driver_cmd() if not driver_cmd: return None @@ -225,8 +219,8 @@ def cua_driver_update_check(*, timeout: Optional[float] = None) -> Optional[Dict return None if data is None or data.get("error") else data def cua_driver_update_nudge() -> Optional[str]: - """One-line "an update is available" message, or ``None`` when up to date, indeterminate, or the driver - is too old to report.""" + """One-line "an update is available" message, or ``None`` when up to date, indeterminate, or the driver is too + old to report.""" state = _cb().cua_driver_update_check() if not state or not state.get("update_available"): return None From fa0ff156146289b8127f832dce73d201f5516978 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 21:47:13 -0700 Subject: [PATCH 4/4] =?UTF-8?q?refactor(computer=5Fuse):=20final=20cua=20b?= =?UTF-8?q?ackend/driver/daemon=20folds=20=E2=80=94=20inline=20discovery?= =?UTF-8?q?=20reasons,=20contextlib=20suppress,=20one-line=20probes;=20str?= =?UTF-8?q?ings=20frozen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/computer_use/cua_backend.py | 202 +++++++++-------------- tools/computer_use/cua_backend_daemon.py | 84 ++++------ tools/computer_use/cua_backend_driver.py | 97 ++++------- 3 files changed, 141 insertions(+), 242 deletions(-) diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.py index d9da879f41..32b5127a29 100644 --- a/tools/computer_use/cua_backend.py +++ b/tools/computer_use/cua_backend.py @@ -24,18 +24,15 @@ from hermes_cli._subprocess_compat import windows_hide_flags from tools.computer_use.backend import ActionResult, ComputerUseBackend from tools.computer_use.cua_backend_capture import _CaptureMixin, _select_capture_target # noqa: F401 from tools.computer_use.cua_backend_daemon import ( # noqa: F401 - _EmbeddedCuaDaemon, _embedded_daemon_spawn_command, _resolve_cua_driver_app_path, _validate_cua_driver_app_signature, -) + _EmbeddedCuaDaemon, _embedded_daemon_spawn_command, _resolve_cua_driver_app_path, _validate_cua_driver_app_signature) from tools.computer_use.cua_backend_driver import ( # noqa: F401 _CUA_DRIVER_ARGS, _CUA_DRIVER_CMD_ENV, _cua_driver_supports_no_overlay, _mcp_args_with_overlay_flag, _resolve_mcp_invocation, _wsl_windows_path_to_posix, cua_driver_binary_available, cua_driver_install_hint, - cua_driver_runtime_contract_status, cua_driver_update_check, cua_driver_update_nudge, resolve_cua_driver_cmd, -) + cua_driver_runtime_contract_status, cua_driver_update_check, cua_driver_update_nudge, resolve_cua_driver_cmd) from tools.computer_use.cua_backend_input import _InputMixin from tools.computer_use.cua_backend_parse import ( # noqa: F401 _action_result_from, _extract_tool_result, _image_dimensions_from_bytes, _ingest_windows, _is_placeholder_id, - _parse_elements_from_structured, _parse_elements_from_tree, _parse_xprop_net_active_window, _windows_from_tool_result, -) + _parse_elements_from_structured, _parse_elements_from_tree, _parse_xprop_net_active_window, _windows_from_tool_result) from tools.computer_use.cua_backend_session import _AsyncBridge, _CuaDriverSession # noqa: F401 logger = logging.getLogger(__name__) @@ -43,14 +40,12 @@ logger = logging.getLogger(__name__) _CUA_TELEMETRY_ENV_VAR = "CUA_DRIVER_RS_TELEMETRY_ENABLED" -# ── Config-derived policy ───────────────────────────────────────────────── def _computer_use_cfg() -> Dict[str, Any]: """The ``computer_use`` config block, or ``{}`` when config is unreadable.""" - try: + with contextlib.suppress(Exception): from hermes_cli.config import load_config return (load_config() or {}).get("computer_use") or {} - except Exception: - return {} + return {} def _cua_no_overlay() -> bool: """Pass ``--no-overlay``? ``computer_use.no_overlay`` overrides; else off on macOS (cursor-overlay redraw @@ -58,16 +53,13 @@ def _cua_no_overlay() -> bool: fullscreen always-on-top all-workspaces window with no compositor-owned lifecycle, so an unclean session end can leave it wedged over every app); on for Windows and Linux Wayland (compositor owns the surface).""" val = _computer_use_cfg().get("no_overlay") - if val is not None: - return bool(val) - if sys.platform != "linux": - return sys.platform == "darwin" - if not os.environ.get("DISPLAY"): - return True + if val is not None or sys.platform != "linux": + return bool(val) if val is not None else sys.platform == "darwin" + wsl = False with contextlib.suppress(Exception), open("/proc/version", encoding="utf-8") as f: - if "microsoft" in f.read().lower(): - return True - return os.environ.get("XDG_SESSION_TYPE") != "wayland" and not os.environ.get("WAYLAND_DISPLAY") + wsl = "microsoft" in f.read().lower() + return wsl or not os.environ.get("DISPLAY") or ( + os.environ.get("XDG_SESSION_TYPE") != "wayland" and not os.environ.get("WAYLAND_DISPLAY")) def _cua_telemetry_disabled() -> bool: """True unless ``computer_use.cua_telemetry`` opts in (unreadable config fails SAFE toward disabling).""" @@ -78,7 +70,7 @@ def _cua_configured_permission_mode() -> str: ``standard``. ``unrestricted`` is deliberately NOT a config value — it stays tied to the per-session YOLO toggle so a stale config line can never silently bypass approvals.""" raw = str(_computer_use_cfg().get("permission_mode", "standard") or "").strip().lower() - return raw if raw in {"standard", "bounded"} else "standard" + return "bounded" if raw == "bounded" else "standard" def _manifest_is_mode_independent(path: str) -> bool: """True when this manifest may accompany any permission mode: v1/v2 declare ``mode: bounded`` and abort @@ -96,40 +88,35 @@ def _manifest_is_mode_independent(path: str) -> bool: return isinstance(version, int) and not isinstance(version, bool) and version >= 3 def _computer_use_max_image_dimension() -> Optional[int]: - """``computer_use.max_image_dimension`` longest-edge cap (default 1456, matching the aux-vision - downscale); ``0``/negative -> None (unset).""" + """``computer_use.max_image_dimension`` longest-edge cap (default 1456 = aux-vision downscale); ``0``/negative -> None.""" try: dim = int(_computer_use_cfg().get("max_image_dimension", 1456)) except (TypeError, ValueError): - return 1456 + dim = 1456 return dim if dim > 0 else None def cua_driver_child_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str, str]: """Env for spawning cua-driver: ``base_env`` (default ``os.environ``) plus ``CUA_DRIVER_RS_TELEMETRY_ENABLED=0`` unless the user opted in. Used by every spawn site (MCP, status, doctor, install) so the policy is uniform.""" - env = dict(base_env if base_env is not None else os.environ) - if _cua_telemetry_disabled(): - env[_CUA_TELEMETRY_ENV_VAR] = "0" - return env + return {**(os.environ if base_env is None else base_env), **({_CUA_TELEMETRY_ENV_VAR: "0"} if _cua_telemetry_disabled() else {})} def sanitized_cua_driver_env() -> Dict[str, str]: - """``cua_driver_child_env()`` with Hermes provider secrets stripped — cua-driver is a third-party binary - and must never inherit API keys. Falls back to the unsanitized telemetry env if the sanitizer can't import.""" + """``cua_driver_child_env()`` with Hermes provider secrets stripped — cua-driver is a third-party binary and must + never inherit API keys. Falls back to the unsanitized telemetry env if the sanitizer can't import.""" env = cua_driver_child_env() - try: + with contextlib.suppress(Exception): from tools.environments.local import _sanitize_subprocess_env return _sanitize_subprocess_env(env) - except Exception: - return env + return env def _run_quiet(argv: List[str], *, timeout: float, swallow: Any = (), **kw: Any) -> Any: - """``subprocess.run`` for short probe verbs: text mode, stdin=DEVNULL (older drivers fall into a stdin-reading - mode on unknown verbs; EOF makes them exit fast instead of blocking until the timeout), output captured unless - the caller redirects it. Exceptions in ``swallow`` return None; others raise.""" - if "stdout" not in kw: - kw["capture_output"] = True + """``subprocess.run`` for short probe verbs: text mode, stdin=DEVNULL unless overridden (older drivers fall into a + stdin-reading mode on unknown verbs; EOF makes them exit fast instead of blocking until the timeout), output + captured unless the caller redirects it. Exceptions in ``swallow`` return None; others raise.""" + kw.setdefault("stdin", subprocess.DEVNULL) + "stdout" in kw or kw.setdefault("capture_output", True) try: - return subprocess.run(argv, text=True, timeout=timeout, stdin=subprocess.DEVNULL, **kw) + return subprocess.run(argv, text=True, timeout=timeout, **kw) except swallow: return None @@ -138,8 +125,6 @@ def _run_driver(driver_cmd: str, *args: str, timeout: float, swallow: Any = ()) return _run_quiet([driver_cmd, *args], timeout=timeout, swallow=swallow, encoding="utf-8", errors="replace", creationflags=windows_hide_flags(), env=sanitized_cua_driver_env()) - -# ── Linux display diagnostics ───────────────────────────────────────────── def _linux_session_locked() -> Optional[bool]: """Is the graphical session locked? (Linux; best-effort.) A locked KDE/GNOME session freezes renderers and half-disables the AX tree, so discovery legitimately returns nothing — which otherwise reads as a driver bug. @@ -148,37 +133,26 @@ def _linux_session_locked() -> Optional[bool]: return None try: proc = _run_quiet(["loginctl", "list-sessions", "--no-legend"], timeout=2.0) - if proc.returncode != 0: - return None seats = [line.split()[0] for line in proc.stdout.splitlines() if len(line.split()) >= 2 and "seat" in line] - for session_id in seats: - if "LockedHint=no" in _run_quiet(["loginctl", "show-session", session_id, "-p", "LockedHint"], timeout=2.0).stdout: - return False - return True if seats else None + if proc.returncode != 0 or not seats: + return None + return not any("LockedHint=no" in _run_quiet(["loginctl", "show-session", s, "-p", "LockedHint"], timeout=2.0).stdout + for s in seats) except Exception: return None -# (predicate, reason) in priority order; the default applies when none match. The macOS entry covers a -# headless Mac / asleep panel: ScreenCaptureKit has 0 shareable displays while TCC grants look fine. -_EMPTY_DISCOVERY_REASONS = ( - (lambda: _linux_session_locked() is True, - "the desktop session is LOCKED (loginctl LockedHint=yes) — unlock the screen; " - "a locked compositor hides windows and freezes app renderers"), - (lambda: sys.platform == "linux" and not os.environ.get("DISPLAY"), - "no DISPLAY is set — X11/XWayland is not reachable from this process"), - (lambda: sys.platform == "darwin", - "window discovery returned no windows; on macOS this usually means no shareable display (headless Mac or " - "panel asleep) — wake the display or attach a monitor/HDMI dummy, then run `hermes computer-use doctor`"), -) - def _empty_discovery_reason() -> str: """One-line diagnosis for 'window discovery found nothing'.""" - return next((reason for applies, reason in _EMPTY_DISCOVERY_REASONS if applies()), - "window discovery returned no windows; run `hermes computer-use doctor` " - "(display reachability, AX capability)") + if _linux_session_locked() is True: + return ("the desktop session is LOCKED (loginctl LockedHint=yes) — unlock the screen; " + "a locked compositor hides windows and freezes app renderers") + if sys.platform == "linux" and not os.environ.get("DISPLAY"): + return "no DISPLAY is set — X11/XWayland is not reachable from this process" + if sys.platform == "darwin": # headless Mac / asleep panel: ScreenCaptureKit has 0 shareable displays while TCC looks fine + return ("window discovery returned no windows; on macOS this usually means no shareable display (headless Mac or " + "panel asleep) — wake the display or attach a monitor/HDMI dummy, then run `hermes computer-use doctor`") + return "window discovery returned no windows; run `hermes computer-use doctor` (display reachability, AX capability)" - -# ── One-shot start() helpers: auto-repair + update nudge ────────────────── _update_checked = False # One auto-repair attempt per process: when the runtime-contract gate fails for something a reinstall fixes # (old version, missing manifest verbs) run the standard install path once instead of telling the user to. @@ -190,8 +164,7 @@ def _maybe_repair_runtime_contract(contract: Dict[str, Any]) -> Dict[str, Any]: attempted / it failed). Never raises. An explicit ``HERMES_CUA_DRIVER_CMD`` override is authoritative even when broken, and a missing binary means installation was never requested.""" global _contract_repair_attempted - if (contract.get("ready") or _contract_repair_attempted - or os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() or not contract.get("binary")): + if contract.get("ready") or _contract_repair_attempted or os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() or not contract.get("binary"): return contract _contract_repair_attempted = True logger.info("computer_use: installed cua-driver is not usable (%s); attempting automatic repair", @@ -201,11 +174,10 @@ def _maybe_repair_runtime_contract(contract: Dict[str, Any]) -> Dict[str, Any]: repaired = install_cua_driver(upgrade=False, show_installer_progress=False) except Exception as exc: logger.warning("computer_use: automatic cua-driver repair failed: %s", exc) - repaired = False - try: - return cua_driver_runtime_contract_status() if repaired else contract - except Exception: return contract + with contextlib.suppress(Exception): + return cua_driver_runtime_contract_status() if repaired else contract + return contract def _maybe_nudge_update() -> None: """Emit an update nudge at most once per process, off-thread so the (cached, ~20h) GitHub poll never blocks @@ -218,8 +190,7 @@ def _maybe_nudge_update() -> None: def _run() -> None: with contextlib.suppress(Exception): msg = cua_driver_update_nudge() - if msg: - logger.info("computer_use: %s", msg) + msg and logger.info("computer_use: %s", msg) threading.Thread(target=_run, name="cua-driver-update-check", daemon=True).start() @@ -233,18 +204,18 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): self.permission_mode = permission_mode self._embedded_daemon: Optional[_EmbeddedCuaDaemon] = None if permission_mode != "standard": - # The manifest is mandatory for bounded (the daemon validates it) and optional for - # unrestricted, where it still caps what an approval-bypassed run may touch. + # Manifest: mandatory for bounded (the daemon validates it), optional for unrestricted where it still + # caps what an approval-bypassed run may touch. raw = _computer_use_cfg().get("capability_manifest") self._embedded_daemon = _EmbeddedCuaDaemon( resolve_cua_driver_cmd() or "", permission_mode, capability_manifest=raw.strip() if isinstance(raw, str) and raw.strip() else None) self._bridge = _AsyncBridge() self._session = _CuaDriverSession(self._bridge, self._embedded_daemon) - # Sticky target — set by capture()/focus_app(), used by actions: `_active_pid`, `_active_window_id`, - # `_last_app`, `_last_target` (exact identity for capture_after: Linux app names may be generic — several - # unrelated Qt windows can all say Qt6Application) and `_snapshot_tokens` (per-snapshot `element_index -> - # element_token`; actions attach it so cua-driver reports "stale" instead of silently re-resolving). + # Sticky target (set by capture()/focus_app(), used by actions): `_active_pid`, `_active_window_id`, `_last_app`, + # `_last_target` (exact identity for capture_after — Linux app names may be generic, e.g. several unrelated Qt + # windows all say Qt6Application), `_snapshot_tokens` (element_index -> element_token, attached to actions so + # cua-driver reports "stale" instead of silently re-resolving). self._clear_active_target() # Public session label (one per Hermes run) sent as `session` on every call: owns the cursor color and # gives config/recording state a stable owner across transport restarts. Part of the 0.20 runtime contract. @@ -255,29 +226,26 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): """Invalidate every capability minted by the replaced transport.""" self._clear_active_target() - # ── Lifecycle ────────────────────────────────────────────────── def start(self) -> None: contract = cua_driver_runtime_contract_status() if not contract.get("ready"): contract = _maybe_repair_runtime_contract(contract) if not contract.get("ready"): - repair = ("Update the binary selected by HERMES_CUA_DRIVER_CMD or remove that override." - if os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() else "Run `hermes computer-use install` to repair it.") - raise RuntimeError(f"cua-driver is not ready: {contract.get('reason') or 'runtime contract is incomplete'}. {repair}") + raise RuntimeError(f"cua-driver is not ready: {contract.get('reason') or 'runtime contract is incomplete'}. " + + ("Update the binary selected by HERMES_CUA_DRIVER_CMD or remove that override." + if os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() else "Run `hermes computer-use install` to repair it.")) _maybe_nudge_update() - # `mcp` is an optional extra: lazy-install on first use (gated by `security.allow_lazy_installs`); - # failure raises FeatureUnavailable with the exact `uv pip install` hint. + # `mcp` is an optional extra: lazy-install on first use (gated by `security.allow_lazy_installs`); failure + # raises FeatureUnavailable with the exact `uv pip install` hint. from tools.lazy_deps import ensure as _lazy_ensure _lazy_ensure("tool.computer_use", prompt=False) importlib.invalidate_caches() # a just-installed package may not be importable yet with contextlib.ExitStack() as rollback: # a failed start stops the private daemon, then re-raises if self._embedded_daemon is not None: - rollback.callback(self._embedded_daemon.stop) - self._embedded_daemon.start() + rollback.callback(self._embedded_daemon.stop) and self._embedded_daemon.start() self._session.start() rollback.pop_all() - # Declare this run's identity. Non-fatal: cua-driver accepts anonymous calls (the cursor just won't - # render), so degrade rather than abort. + # Declare this run's identity. Non-fatal: cua-driver accepts anonymous calls (cursor won't render), so degrade. self._best_effort("start_session failed (continuing anonymous)", self._session.call_tool, "start_session", {"session": self._session_id}) # Post-handshake tuning guards on `_started`: before the handshake flips it, call_tool would re-enter @@ -297,10 +265,8 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): if self._session._started: self._best_effort("end_session failed (continuing teardown)", self._session.call_tool, "end_session", {"session": self._session_id}) - # Every teardown step runs even if an earlier one raised (LIFO: session, bridge, private daemon). - with contextlib.ExitStack() as teardown: - if self._embedded_daemon is not None: - teardown.callback(self._embedded_daemon.stop) + with contextlib.ExitStack() as teardown: # every step runs even if one raised (LIFO: session, bridge, daemon) + self._embedded_daemon is None or teardown.callback(self._embedded_daemon.stop) teardown.callback(self._bridge.stop) teardown.callback(self._session.stop) @@ -313,27 +279,19 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): logger.debug("cua-driver %s: %s", what, e) def is_available(self) -> bool: - # Other Unix-likes haven't been exercised end-to-end. - return sys.platform in ("darwin", "win32", "linux") and cua_driver_binary_available() + return sys.platform in ("darwin", "win32", "linux") and cua_driver_binary_available() # other Unix-likes untested E2E - # ── Target state ─────────────────────────────────────────────── def _clear_active_target(self) -> None: """Forget a capture/focus target so a failed lookup cannot misroute input.""" - self._active_pid: Optional[int] = None - self._active_window_id: Optional[int] = None - self._last_app: Optional[str] = None - self._last_target: Optional[Dict[str, Optional[int]]] = None + self._active_pid = self._active_window_id = self._last_app = self._last_target = None self._snapshot_tokens: Dict[int, str] = {} def _set_active_target(self, target: Dict[str, Any]) -> None: self._active_pid = target["pid"] self._active_window_id = target["window_id"] - # Tokens belong to the prior snapshot; disarm before any capture call so an exception cannot pair old - # tokens with this target. - self._snapshot_tokens = {} + self._snapshot_tokens = {} # prior snapshot's tokens: disarm before any capture so an exception can't pair them self._last_target = {"pid": self._active_pid, "window_id": self._active_window_id} - # ── App lifecycle / focus ───────────────────────────────────────── def launch_app(self, *, bundle_id: Optional[str] = None, name: Optional[str] = None, urls: Optional[List[str]] = None, additional_arguments: Optional[List[str]] = None, creates_new_application_instance: bool = False) -> Dict[str, Any]: @@ -341,35 +299,26 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): forces a fresh instance so concurrent runs touching the same app get isolated windows.""" if not bundle_id and not name: raise ValueError("launch_app requires either bundle_id or name") - args: Dict[str, Any] = {"session": self._session_id} - for key, value in (("bundle_id", bundle_id), ("name", name), ("urls", urls and list(urls)), - ("additional_arguments", additional_arguments and list(additional_arguments)), - ("creates_new_application_instance", creates_new_application_instance or None)): - if value: - args[key] = value + args: Dict[str, Any] = {"session": self._session_id, **{k: v for k, v in ( + ("bundle_id", bundle_id), ("name", name), ("urls", urls and list(urls)), + ("additional_arguments", additional_arguments and list(additional_arguments)), + ("creates_new_application_instance", creates_new_application_instance or None)) if v}} out = self._session.call_tool("launch_app", args) return out["structuredContent"] or {"data": out["data"]} def bring_to_front(self, *, pid: int, window_id: Optional[int] = None) -> ActionResult: """Activate a window so subsequent foreground-dispatched input lands on it.""" - args: Dict[str, Any] = {"pid": int(pid)} - if window_id is not None: - args["window_id"] = int(window_id) - # The live schema is strict and has no session property: this is a standalone native focus operation, - # not a session-scoped input action. + args: Dict[str, Any] = {"pid": int(pid), **({} if window_id is None else {"window_id": int(window_id)})} + # Strict live schema with no session property: a standalone native focus op, not a session-scoped input action. return self._action("bring_to_front", args, inject_session=False) - # ── Agent cursor / config ──────────────────────────────────────── def set_agent_cursor_enabled(self, enabled: bool, *, cursor_id: Optional[str] = None) -> ActionResult: """Toggle the agent cursor overlay's visibility for this run.""" - args: Dict[str, Any] = {"enabled": bool(enabled)} - if cursor_id: - args["cursor_id"] = cursor_id - return self._action("set_agent_cursor_enabled", args) + return self._action("set_agent_cursor_enabled", + {"enabled": bool(enabled), **({"cursor_id": cursor_id} if cursor_id else {})}) def set_config(self, **config) -> ActionResult: - """Set cua-driver config keys (e.g. ``max_image_dimension``). Unknown keys pass through verbatim — - cua-driver validates its own schema.""" + """Set cua-driver config keys (e.g. ``max_image_dimension``); unknown keys pass through — cua-driver validates.""" return self._action("set_config", dict(config)) def call_tool(self, name: str, args: Optional[Dict[str, Any]] = None, *, timeout: float = 30.0) -> Dict[str, Any]: @@ -379,11 +328,9 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): payload.setdefault("session", self._session_id) return self._session.call_tool(name, payload, timeout=timeout) - # ── Internal ─────────────────────────────────────────────────── def _action(self, name: str, args: Dict[str, Any], *, inject_session: bool = True) -> ActionResult: - # Attach the snapshot's `element_token` to an `element_index` call so a superseded snapshot yields an - # explicit 'stale' error. Gated on the per-tool capability: older drivers (`additionalProperties: false`) - # must never see the field. + # Attach the snapshot's `element_token` to an `element_index` call so a superseded snapshot yields an explicit + # 'stale' error. Gated on the per-tool capability: older drivers (`additionalProperties: false`) must never see it. idx = args.get("element_index") token = self._snapshot_tokens.get(idx) if isinstance(idx, int) else None if token and self._session.supports_capability("accessibility.element_tokens", tool=name): @@ -397,9 +344,8 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend): return ActionResult(ok=False, action=name, message=f"cua-driver error: {e}") data = out["data"] structured = out.get("structuredContent") or {} - message = str(data.get("message", "")) if isinstance(data, dict) else data if isinstance(data, str) else "" - if not message and isinstance(structured, dict): - message = str(structured.get("message", "")) + message = (str(data.get("message", "")) if isinstance(data, dict) else data if isinstance(data, str) else "") \ + or (str(structured.get("message", "")) if isinstance(structured, dict) else "") # Merge data + structuredContent into meta, structured winning on overlap (canonical verdict surface). meta = {k: v for part in (data, structured) if isinstance(part, dict) for k, v in part.items()} return _action_result_from(name, not out["isError"], message, meta, structured, diff --git a/tools/computer_use/cua_backend_daemon.py b/tools/computer_use/cua_backend_daemon.py index 75f715b353..52b69f6b7d 100644 --- a/tools/computer_use/cua_backend_daemon.py +++ b/tools/computer_use/cua_backend_daemon.py @@ -34,13 +34,9 @@ def _resolve_cua_driver_app_path(driver_cmd: str) -> Optional[str]: """Return the CuaDriver.app bundle that CARRIES *driver_cmd*, if any. Derived from the resolved binary path only — no /Applications fallback, which could be a DIFFERENT install than the one the manifest resolved, running code the resolution chain never validated.""" - resolved = os.path.realpath(driver_cmd) - marker_index = resolved.find(".app/Contents/MacOS/") - if marker_index < 0: - return None - candidate = resolved[: marker_index + len(".app")] - executable = os.path.join(candidate, "Contents", "MacOS", "cua-driver") - return candidate if os.path.isfile(executable) and os.access(executable, os.X_OK) else None + head, marker, _ = os.path.realpath(driver_cmd).partition(".app/Contents/MacOS/") + executable = os.path.join(head + ".app", "Contents", "MacOS", "cua-driver") + return head + ".app" if marker and os.path.isfile(executable) and os.access(executable, os.X_OK) else None def _validate_cua_driver_app_signature(app_path: str) -> None: """Fail closed unless *app_path* is the genuinely-signed CuaDriver.app. ``/usr/bin/open`` hands LaunchServices @@ -52,27 +48,22 @@ def _validate_cua_driver_app_signature(app_path: str) -> None: if not codesign: raise RuntimeError("codesign is required to verify CuaDriver.app before launching it.") try: - proc = _cb()._run_quiet([codesign, "-dv", app_path], timeout=15) + proc = _cb()._run_quiet([codesign, "-dv", app_path], timeout=15, stdin=None) except (OSError, subprocess.TimeoutExpired) as exc: raise RuntimeError(f"could not verify CuaDriver.app signature: {exc}") from exc if proc.returncode != 0: - raise RuntimeError(f"CuaDriver.app at {app_path} is not code-signed; refusing to launch it " - f"({(proc.stderr or '').strip()})") - fields: Dict[str, str] = {} - for key, sep, value in (line.partition("=") for line in (proc.stderr or "").splitlines()): - if sep: # codesign -dv reports on stderr - fields.setdefault(key.strip(), value.strip()) + raise RuntimeError(f"CuaDriver.app at {app_path} is not code-signed; refusing to launch it ({(proc.stderr or '').strip()})") + parts = [line.partition("=") for line in (proc.stderr or "").splitlines()] # codesign -dv reports on stderr + fields = {k.strip(): v.strip() for k, sep, v in reversed(parts) if sep} # first occurrence of a key wins identifier, team = fields.get("Identifier", ""), fields.get("TeamIdentifier", "") if identifier != _CUA_DRIVER_BUNDLE_ID: - raise RuntimeError(f"CuaDriver.app at {app_path} has identifier {identifier!r}, " - f"expected {_CUA_DRIVER_BUNDLE_ID!r}; refusing to launch it.") - if team in _CUA_DRIVER_TEAM_IDS or ( - team in ("", "not set") and _cb()._computer_use_cfg().get("allow_unsigned_driver") is True): + raise RuntimeError(f"CuaDriver.app at {app_path} has identifier {identifier!r}, expected {_CUA_DRIVER_BUNDLE_ID!r}; " + "refusing to launch it.") + if team in _CUA_DRIVER_TEAM_IDS or (team in ("", "not set") and _cb()._computer_use_cfg().get("allow_unsigned_driver") is True): return - raise RuntimeError( - f"CuaDriver.app at {app_path} is signed by team {team!r}, expected one of " - f"{_CUA_DRIVER_TEAM_IDS!r}; refusing to launch it. (Set computer_use.allow_unsigned_driver: " - "true in config.yaml only for local unsigned driver builds.)") + raise RuntimeError(f"CuaDriver.app at {app_path} is signed by team {team!r}, expected one of {_CUA_DRIVER_TEAM_IDS!r}; " + "refusing to launch it. (Set computer_use.allow_unsigned_driver: true in config.yaml only for " + "local unsigned driver builds.)") def _embedded_daemon_spawn_command(driver_cmd: str, serve_args: List[str], *, platform: str, app_path: Optional[str] = None) -> List[str]: @@ -81,8 +72,7 @@ def _embedded_daemon_spawn_command(driver_cmd: str, serve_args: List[str], *, pl return [driver_cmd, *serve_args] resolved_app = app_path or _resolve_cua_driver_app_path(driver_cmd) if not resolved_app: - raise RuntimeError("CuaDriver.app is required for private computer-use sessions on macOS. " - "Run `hermes computer-use install` to restore it.") + raise RuntimeError("CuaDriver.app is required for private computer-use sessions on macOS. Run `hermes computer-use install` to restore it.") _validate_cua_driver_app_signature(resolved_app) return ["/usr/bin/open", "-n", "-g", "-a", resolved_app, "--args", *serve_args] @@ -117,22 +107,18 @@ class _EmbeddedCuaDaemon: manifest = str(capability_manifest or "").strip() if not manifest and permission_mode == "bounded": raise ValueError("bounded permission mode requires computer_use.capability_manifest") - if manifest: - manifest = os.path.abspath(os.path.expanduser(manifest)) - if not os.path.isfile(manifest): - raise ValueError(f"capability manifest not found: {manifest}") + manifest = os.path.abspath(os.path.expanduser(manifest)) if manifest else "" + if manifest and not os.path.isfile(manifest): + raise ValueError(f"capability manifest not found: {manifest}") self.capability_manifest: Optional[str] = manifest or None - # bounded always forwards (the driver validates it); other modes accept only a v3 manifest — a legacy one - # would abort startup instead. + # bounded always forwards (driver validates it); other modes accept only v3 — a legacy manifest aborts startup. self.manifest_applies = bool(manifest) and ( permission_mode == "bounded" or _cb()._manifest_is_mode_independent(manifest)) if manifest and not self.manifest_applies: - logger.warning("computer_use.capability_manifest is a legacy (v1/v2) manifest, " - "which cua-driver only accepts in bounded mode — it will NOT " - "bound this %s session. Migrate the manifest to version 3 to " - "keep a ceiling on approval-bypassed runs.", permission_mode) - self.permission_mode = permission_mode - self._driver_cmd = self._command = driver_cmd + logger.warning("computer_use.capability_manifest is a legacy (v1/v2) manifest, which cua-driver only accepts in " + "bounded mode — it will NOT bound this %s session. Migrate the manifest to version 3 to keep a " + "ceiling on approval-bypassed runs.", permission_mode) + self.permission_mode, self._driver_cmd, self._command = permission_mode, driver_cmd, driver_cmd self._mcp_args: List[str] = list(_cb()._CUA_DRIVER_ARGS) self._process: Any = None self._owns_runtime = self._running = False @@ -142,8 +128,7 @@ class _EmbeddedCuaDaemon: else os.path.join(tempfile.gettempdir(), f"hc-{token}.sock")) def child_env(self) -> Dict[str, str]: - env = _cb().cua_driver_child_env() - env["CUA_DRIVER_PERMISSION_MODE"] = self.permission_mode + env = {**_cb().cua_driver_child_env(), "CUA_DRIVER_PERMISSION_MODE": self.permission_mode} if self.permission_mode == "unrestricted": env["CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS"] = "1" return env @@ -161,10 +146,8 @@ class _EmbeddedCuaDaemon: logger.debug("embedded cua-driver: %s", text) def _serve_args(self) -> List[str]: - serve_args = ["serve", "--embedded", "--socket", self.socket_path, - "--no-permissions-gate", "--permission-mode", self.permission_mode] - if self.permission_mode == "unrestricted": - serve_args.append("--dangerously-bypass-approvals") + serve_args = ["serve", "--embedded", "--socket", self.socket_path, "--no-permissions-gate", "--permission-mode", + self.permission_mode, *(["--dangerously-bypass-approvals"] if self.permission_mode == "unrestricted" else [])] if self.manifest_applies: serve_args += ["--capability-manifest", str(self.capability_manifest), "--approve-capability-manifest"] # The private daemon owns the cursor overlay, so the overlay policy must apply to this long-lived serve @@ -184,13 +167,11 @@ class _EmbeddedCuaDaemon: self._process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, env=env) self._owns_runtime = True - threading.Thread(target=self._drain_stderr, args=(self._process,), - name="hermes-cua-daemon-stderr", daemon=True).start() + threading.Thread(target=self._drain_stderr, args=(self._process,), name="hermes-cua-daemon-stderr", daemon=True).start() deadline = time.monotonic() + self._START_TIMEOUT_SECONDS while time.monotonic() < deadline: return_code = self._process.poll() - # `open` exits 0 once LaunchServices took the request, so on macOS only a non-zero exit means the - # daemon itself died. + # `open` exits 0 once LaunchServices took the request: on macOS only a non-zero exit means the daemon died. if return_code is not None and (sys.platform != "darwin" or return_code != 0): self._startup_failure("embedded cua-driver exited during startup", "no diagnostic output") if self._socket_ready(env): @@ -205,8 +186,7 @@ class _EmbeddedCuaDaemon: def _socket_ready(self, env: Dict[str, str]) -> bool: """``cua-driver status --socket`` exits 0 once the private daemon accepts connections.""" - probe = _cb()._run_quiet([self._command, "status", "--socket", self.socket_path], - timeout=2.0, env=env, swallow=_QUIET_ERRORS) + probe = _cb()._run_quiet([self._command, "status", "--socket", self.socket_path], timeout=2.0, env=env, swallow=_QUIET_ERRORS) return probe is not None and probe.returncode == 0 def proxy_invocation(self) -> Tuple[str, List[str]]: @@ -216,12 +196,10 @@ class _EmbeddedCuaDaemon: def stop(self) -> None: process, self._process = self._process, None - owns_runtime, self._owns_runtime = self._owns_runtime, False - self._running = False + owns_runtime, self._owns_runtime, self._running = self._owns_runtime, False, False if owns_runtime: - _cb()._run_quiet([self._command, "stop", "--socket", self.socket_path], timeout=3.0, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, - env=self._sanitized_env(), swallow=_QUIET_ERRORS) + _cb()._run_quiet([self._command, "stop", "--socket", self.socket_path], timeout=3.0, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, env=self._sanitized_env(), swallow=_QUIET_ERRORS) if process is not None: _wait_or_kill(process) if sys.platform != "win32" and os.path.exists(self.socket_path): diff --git a/tools/computer_use/cua_backend_driver.py b/tools/computer_use/cua_backend_driver.py index 68e8c693e8..9e0442c6aa 100644 --- a/tools/computer_use/cua_backend_driver.py +++ b/tools/computer_use/cua_backend_driver.py @@ -56,8 +56,6 @@ def _valid_mcp_args(invocation: Any) -> Optional[List[str]]: args = invocation.get("args") if isinstance(invocation, dict) else None return args if isinstance(args, list) and all(isinstance(a, str) for a in args) else None - -# ── Binary resolution ───────────────────────────────────────────────────── def _has_path_separator(value: str) -> bool: return os.sep in value or (os.altsep is not None and os.altsep in value) @@ -69,15 +67,12 @@ def _wsl_windows_path_to_posix(path: str) -> str: return path try: from hermes_constants import is_wsl - if not is_wsl(): - return path + wsl = is_wsl() except Exception: - return path + wsl = False win = PureWindowsPath(path) drive = (win.drive or "").rstrip(":").lower() - if not drive: - return path - return os.path.join("/mnt", drive, *(str(part) for part in win.parts[1:])) + return os.path.join("/mnt", drive, *(str(part) for part in win.parts[1:])) if wsl and drive else path def _candidate_cua_driver_commands(override: Optional[str] = None) -> List[str]: """Candidate commands in resolution order. ``override`` / a non-empty ``HERMES_CUA_DRIVER_CMD`` is authoritative @@ -90,18 +85,14 @@ def _candidate_cua_driver_commands(override: Optional[str] = None) -> List[str]: home = os.path.expanduser("~") if sys.platform == "win32": local_app_data = os.environ.get("LOCALAPPDATA") or os.path.join(home, "AppData", "Local") - installed = [os.path.join(local_app_data, "Programs", "Cua", "cua-driver", "bin", "cua-driver.exe"), - os.path.join(home, ".local", "bin", "cua-driver.exe"), os.path.join(home, ".local", "bin", "cua-driver")] - else: - installed = [os.path.join(home, ".local", "bin", "cua-driver"), os.path.join(home, ".cargo", "bin", "cua-driver"), - "/opt/homebrew/bin/cua-driver", "/usr/local/bin/cua-driver"] - return [_CUA_DRIVER_DEFAULT_CMD, *installed] + return [_CUA_DRIVER_DEFAULT_CMD, os.path.join(local_app_data, "Programs", "Cua", "cua-driver", "bin", "cua-driver.exe"), + os.path.join(home, ".local", "bin", "cua-driver.exe"), os.path.join(home, ".local", "bin", "cua-driver")] + return [_CUA_DRIVER_DEFAULT_CMD, os.path.join(home, ".local", "bin", "cua-driver"), + os.path.join(home, ".cargo", "bin", "cua-driver"), "/opt/homebrew/bin/cua-driver", "/usr/local/bin/cua-driver"] def resolve_cua_driver_cmd(override: Optional[str] = None) -> Optional[str]: - """Resolve the cua-driver executable for every runtime/status surface. An override is never silently - replaced by another binary.""" - for candidate in _candidate_cua_driver_commands(override): - expanded = os.path.expanduser(candidate) + """Resolve the cua-driver executable for every runtime/status surface; an override is never silently replaced.""" + for expanded in map(os.path.expanduser, _candidate_cua_driver_commands(override)): resolved = shutil.which(expanded) if resolved: return expanded if _has_path_separator(expanded) else resolved @@ -118,18 +109,15 @@ def cua_driver_install_hint() -> str: f"Or run the upstream installer directly:\n{installer}\n" "Or run `hermes tools` and enable the Computer Use toolset to install it automatically.") - -# ── MCP invocation ──────────────────────────────────────────────────────── def _mcp_args_with_overlay_flag(args: List[str], driver_cmd: str = _CUA_DRIVER_DEFAULT_CMD) -> List[str]: """Return *args* with ``--no-overlay`` appended when configured and supported.""" - if _cb()._cua_no_overlay() and _cb()._cua_driver_supports_no_overlay(driver_cmd): - return [*args, "--no-overlay"] - return list(args) + on = _cb()._cua_no_overlay() and _cb()._cua_driver_supports_no_overlay(driver_cmd) + return [*args, "--no-overlay"] if on else list(args) @functools.lru_cache(maxsize=1) def _cua_driver_supports_no_overlay(driver_cmd: str) -> bool: - """True if `` --help`` mentions ``--no-overlay`` (probed once). Older drivers reject unknown - flags, which would crash the MCP spawn.""" + """True if `` --help`` mentions ``--no-overlay`` (probed once); older drivers reject unknown flags, which + would crash the MCP spawn.""" try: proc = _cb()._run_driver(driver_cmd, "--help", timeout=3.0) return "--no-overlay" in (proc.stdout or "") + (proc.stderr or "") @@ -146,33 +134,17 @@ def _resolve_mcp_invocation(driver_cmd: str, *, timeout: float = 6.0) -> Tuple[s args = _valid_mcp_args(invocation) command = invocation.get("command") if args is not None and isinstance(invocation, dict) else None args = list(_CUA_DRIVER_ARGS) if args is None else args - if isinstance(command, str) and command: - # Translate a Windows ``C:\...`` command for WSL BEFORE the separator check (backslash is not a separator - # on POSIX). A generic ``cua-driver`` name would lose the resolved user-local path under a GUI's thin PATH, - # so only a concrete (path-bearing) command replaces the one we verified — and THAT binary is probed for - # `--no-overlay`, not the system one. - command = _wsl_windows_path_to_posix(command) - if _has_path_separator(command): - return command, _mcp_args_with_overlay_flag(args, driver_cmd=command) - return driver_cmd, _mcp_args_with_overlay_flag(args, driver_cmd=driver_cmd) - - -# ── Runtime contract + update checking ──────────────────────────────────── -# cua-driver's native `check-update` verb compares the installed binary against the latest GitHub -# release (cached ~20h); we prefer it over a hardcoded floor. -def _manifest_contract_gaps(manifest: Dict[str, Any]) -> List[str]: - """``" "`` entries the driver's advertised subcommands lack.""" - advertised: Dict[str, set[str]] = { - command["name"]: {arg["name"] for arg in command.get("args") or [] - if isinstance(arg, dict) and isinstance(arg.get("name"), str)} - for command in manifest.get("subcommands") or [] - if isinstance(command, dict) and isinstance(command.get("name"), str) - } - return [f"{command} {arg}" for command, required in _CUA_DRIVER_RUNTIME_CONTRACT_ARGS.items() - for arg in sorted(required - advertised.get(command, set()))] + # Translate a Windows ``C:\...`` command for WSL BEFORE the separator check (backslash is not a separator on + # POSIX). A generic ``cua-driver`` name would lose the resolved user-local path under a GUI's thin PATH, so only + # a concrete (path-bearing) command replaces the one we verified — and THAT binary is probed for `--no-overlay`, + # not the system one. + command = _wsl_windows_path_to_posix(command) if isinstance(command, str) and command else "" + command = command if command and _has_path_separator(command) else driver_cmd + return command, _mcp_args_with_overlay_flag(args, driver_cmd=command) def _manifest_contract_reason(manifest: Optional[Dict[str, Any]]) -> str: - """Why a parsed manifest fails the 0.20 contract, or ``""`` when it passes.""" + """Why a parsed manifest fails the 0.20 contract, or ``""`` when it passes (version floor, MCP launch + command, then the ``" "`` entries the advertised subcommands lack).""" if manifest is None: return "driver manifest is missing or invalid" match = _SEMVER_RE.fullmatch(str(manifest.get("binary_version") or "").strip()) @@ -182,7 +154,14 @@ def _manifest_contract_reason(manifest: Optional[Dict[str, Any]]) -> str: return "Hermes computer use requires cua-driver 0.20.0 or newer" if not _valid_mcp_args(manifest.get("mcp_invocation")): return "driver manifest does not provide an MCP launch command" - missing = _manifest_contract_gaps(manifest) + advertised: Dict[str, set[str]] = { + command["name"]: {arg["name"] for arg in command.get("args") or [] + if isinstance(arg, dict) and isinstance(arg.get("name"), str)} + for command in manifest.get("subcommands") or [] + if isinstance(command, dict) and isinstance(command.get("name"), str) + } + missing = [f"{command} {arg}" for command, required in _CUA_DRIVER_RUNTIME_CONTRACT_ARGS.items() + for arg in sorted(required - advertised.get(command, set()))] return "driver manifest is missing: " + ", ".join(missing) if missing else "" def cua_driver_runtime_contract_status(binary: Optional[str] = None) -> Dict[str, Any]: @@ -196,31 +175,27 @@ def cua_driver_runtime_contract_status(binary: Optional[str] = None) -> Dict[str except (OSError, subprocess.SubprocessError) as exc: result, reason = None, f"manifest check failed: {exc}" if result is not None and result.returncode != 0: - detail = (result.stderr or result.stdout or "manifest command failed").strip() - result, reason = None, detail.splitlines()[-1][:200] + result, reason = None, (result.stderr or result.stdout or "manifest command failed").strip().splitlines()[-1][:200] if result is not None: manifest = _json_object(result.stdout or "") reason = _manifest_contract_reason(manifest) - if manifest is not None: - version = str(manifest.get("binary_version") or "").strip() or None + version = str(manifest.get("binary_version") or "").strip() or None if manifest is not None else None return {"ready": not reason, "binary": resolved, "version": version, "reason": reason} def cua_driver_update_check(*, timeout: Optional[float] = None) -> Optional[Dict[str, Any]]: - """``cua-driver check-update --json`` payload (``{current_version, latest_version, update_available, ...}``), + """cua-driver's native ``check-update`` verb compares the installed binary against the latest GitHub release + (cached ~20h); we prefer it over a hardcoded floor. Returns the ``check-update --json`` payload (``{current_version, latest_version, update_available, ...}``), or ``None`` when the binary is missing, the driver predates the verb, the GitHub check failed (``error`` set) or the output didn't parse. Never raises. ``timeout`` defaults to 8s on POSIX / 25s on Windows: first spawn of the exe routinely eats seconds in Defender scanning, and callers treat ``None`` as indeterminate (the upgrade path used to fall through to a full reinstall on a false timeout).""" timeout = (25.0 if sys.platform == "win32" else 8.0) if timeout is None else timeout driver_cmd = _cb().resolve_cua_driver_cmd() - if not driver_cmd: - return None - data = _driver_json(driver_cmd, "check-update", "--json", timeout=timeout, require_ok=False) + data = _driver_json(driver_cmd, "check-update", "--json", timeout=timeout, require_ok=False) if driver_cmd else None return None if data is None or data.get("error") else data def cua_driver_update_nudge() -> Optional[str]: - """One-line "an update is available" message, or ``None`` when up to date, indeterminate, or the driver is too - old to report.""" + """One-line "an update is available" message, or ``None`` when up to date, indeterminate, or driver too old.""" state = _cb().cua_driver_update_check() if not state or not state.get("update_available"): return None