Merge branch 'simp/r2-tools-b-cua2-drv' into simp/r2-tools-b-cua2

This commit is contained in:
Teknium
2026-09-02 21:51:32 -07:00
3 changed files with 349 additions and 642 deletions
+157 -324
View File
@@ -1,21 +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.
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
import contextlib
import importlib
import logging
import os
import shutil # noqa: F401 (tests patch cua_backend.shutil / .subprocess / .threading)
@@ -27,98 +22,63 @@ 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,
)
_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_key_combo, _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
# ---------------------------------------------------------------------------
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 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)
if sys.platform == "darwin":
return True
if sys.platform != "linux":
return False
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
return os.environ.get("XDG_SESSION_TYPE") != "wayland" and not os.environ.get("WAYLAND_DISPLAY")
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:
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 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 _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
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 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:
@@ -128,172 +88,113 @@ 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
"""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."""
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_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(),
)
# ---------------------------------------------------------------------------
# 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)."""
if sys.platform != "linux":
def _run_quiet(argv: List[str], *, timeout: float, swallow: Any = (), **kw: Any) -> Any:
"""``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, **kw)
except swallow:
return None
def _loginctl(*args: str) -> subprocess.CompletedProcess:
return subprocess.run(["loginctl", *args], capture_output=True, text=True,
timeout=2.0, stdin=subprocess.DEVNULL)
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())
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)."""
if sys.platform != "linux":
return None
try:
proc = _loginctl("list-sessions", "--no-legend")
if proc.returncode != 0:
proc = _run_quiet(["loginctl", "list-sessions", "--no-legend"], timeout=2.0)
seats = [line.split()[0] for line in proc.stdout.splitlines() if len(line.split()) >= 2 and "seat" in line]
if proc.returncode != 0 or not seats:
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
if "LockedHint=no" in _loginctl("show-session", parts[0], "-p", "LockedHint").stdout:
return False
return True if any_seat else 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
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"
)
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)"
)
# ---------------------------------------------------------------------------
# One-shot start() helpers: auto-repair + update nudge
# ---------------------------------------------------------------------------
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)"
_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")
):
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
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
try:
return cua_driver_runtime_contract_status()
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 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)
msg and logger.info("computer_use: %s", msg)
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."""
@@ -303,29 +204,21 @@ 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=_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.
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.
# 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.
self._session_id: str = f"hermes-{uuid.uuid4().hex[:12]}"
self._session.set_transport_reset_callback(self._handle_transport_reset)
@@ -333,69 +226,49 @@ 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"):
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}")
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)
import importlib
importlib.invalidate_caches() # a just-installed package may not be importable yet
try:
with contextlib.ExitStack() as rollback: # a failed start stops the private daemon, then re-raises
if self._embedded_daemon is not None:
self._embedded_daemon.start()
rollback.callback(self._embedded_daemon.stop) and self._embedded_daemon.start()
self._session.start()
except Exception:
if self._embedded_daemon is not None:
self._embedded_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 (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 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})
try:
self._session.stop()
finally:
try:
self._bridge.stop()
finally:
if self._embedded_daemon is not None:
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)
@staticmethod
def _best_effort(what: str, fn, *args: Any, **kwargs: Any) -> None:
@@ -406,98 +279,63 @@ 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 = None
self._active_window_id = None
self._last_app = None
self._last_target = None
self._snapshot_tokens = {}
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]:
"""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."""
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."""
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:
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]:
"""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``)."""
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)
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 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=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)
@@ -506,14 +344,9 @@ 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", ""))
# 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)
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,
requested_delivery=args.get("delivery_mode"))
+86 -133
View File
@@ -1,11 +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
@@ -20,56 +19,51 @@ 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)
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."""
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
"""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."""
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 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."""
from tools.computer_use import cua_backend as _cb
"""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.")
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, 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]:
@@ -78,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]
@@ -97,135 +90,104 @@ 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
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")
if manifest:
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
# 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:
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)
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 (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, 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 = 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"))
def child_env(self) -> Dict[str, str]:
from tools.computer_use import cua_backend as _cb
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
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:
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]:
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":
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 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)
# 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:
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())
self._launch_via_app = sys.platform == "darwin"
raise RuntimeError(_cb().cua_driver_install_hint())
self._command, self._mcp_args = _cb()._resolve_mcp_invocation(self._driver_cmd)
env = self._sanitized_env()
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: 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):
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."""
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:
@@ -234,21 +196,12 @@ 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:
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):
try:
with contextlib.suppress(OSError):
os.remove(self.socket_path)
except OSError:
pass
+106 -185
View File
@@ -1,10 +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
@@ -21,104 +17,82 @@ 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+)(?:[-+].*)?")
_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."""
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 ""
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:
proc = _cb()._run_driver(driver_cmd, *args, timeout=timeout)
except Exception:
return None
out = (proc.stdout or "").strip()
if not out or (require_ok and proc.returncode != 0):
return None
try:
data = json.loads(out)
data = json.loads(text)
except (ValueError, TypeError):
return None
return data if isinstance(data, dict) else None
# ---------------------------------------------------------------------------
# Binary resolution
# ---------------------------------------------------------------------------
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
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/<drive>/...`` 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/<drive>/...`` 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
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 (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]
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
@@ -129,37 +103,21 @@ 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"
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]:
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 ``<driver> --help`` mentions ``--no-overlay`` (probed once).
Older drivers reject unknown flags, which would crash the MCP spawn."""
"""True if ``<driver> --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 "")
@@ -167,116 +125,79 @@ 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")
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
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)
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
# 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)
# ---------------------------------------------------------------------------
# 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_reason(manifest: Optional[Dict[str, Any]]) -> str:
"""Why a parsed manifest fails the 0.20 contract, or ``""`` when it passes (version floor, MCP launch
command, then the ``"<verb> <flag>"`` 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())
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"
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]:
"""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)
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_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": ""}
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:
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)
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, ...}``), 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
"""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)."""
if timeout is None:
timeout = 25.0 if sys.platform == "win32" else 8.0
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
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 '?'}); update with `hermes computer-use install --upgrade`.")