Skip to content

The agent that grows with you

refactor(tools/computer_use): split cua_backend into daemon/actions/... siblings; dispatch tables; compact doctor/tool

Teknium33ae442e9407
diff --git a/tools/computer_use/__init__.py b/tools/computer_use/__init__.py
index 03bdbbe893b..6d18e7af16c 100644
--- a/tools/computer_use/__init__.py
+++ b/tools/computer_use/__init__.py
@@ -1,37 +1,20 @@
-"""Computer use toolset — universal (any-model) macOS desktop control.
+"""Computer use toolset — universal (any-model) desktop control via cua-driver.
-Architecture
-------------
-This toolset drives macOS apps through cua-driver's background computer-use
-primitive (SkyLight private SPIs for focus-without-raise + pid-scoped event
-posting). Unlike #4562's pyautogui backend, it does NOT steal the user's
-cursor, keyboard focus, or Space — the agent and the user can co-work on the
-same machine.
+Drives apps through cua-driver's background computer-use primitive (focus-
+without-raise + pid-scoped event posting): it does NOT steal the user's cursor,
+keyboard focus, or Space. The schema is plain OpenAI function-calling so every
+tool-capable model can drive it; vision models get SOM captures (numbered
+overlays + AX tree) and click by element index, non-vision models use the AX
+tree alone.
-Unlike #4562's Anthropic-native `computer_20251124` tool, the schema here is
-a plain OpenAI function-calling schema that every tool-capable model can
-drive. Vision models get SOM (set-of-mark) captures — a screenshot with
-numbered overlays on every interactable element plus the AX tree — so they
-click by element index instead of pixel coordinates. Non-vision models can
-drive via the AX tree alone.
+* `tool.py` — `computer_use` handler, approval gate, response shaping.
+* `backend.py` — abstract `ComputerUseBackend` + result dataclasses.
+* `cua_backend.py` — default backend (MCP over stdio to `cua-driver`), with
+ `cua_backend_parse` / `_session` / `_daemon` siblings.
+* `schema.py` — the model-facing schema (byte-frozen).
-Wiring
-------
-* `tool.py` — registers the `computer_use` tool via tools.registry.
-* `backend.py` — abstract `ComputerUseBackend`; swappable implementation.
-* `cua_backend.py`— default backend; speaks MCP over stdio to `cua-driver`.
-* `schema.py` — shared schema + docstring for the generic `computer_use`
- tool. Model-agnostic.
-* `capture.py` — screenshot post-processing (PNG coercion, sizing, SOM
- overlay if the backend did not).
-
-The outer integration points (multimodal tool-result plumbing, screenshot
-eviction in the Anthropic adapter, image-aware token estimation, approval
-hook, and the skill) live alongside this package. See
-agent/anthropic_adapter.py for the salvaged hunks from PR #4562. Model-facing
-guidance (workflow, background-first, the escalate ladder, safety) lives in
-the tool's schema description and each action result's `verdict`, not a
-separate system-prompt block.
+Model-facing guidance (workflow, background-first, escalate ladder, safety)
+lives in the schema description and each action result's `verdict`.
"""
from __future__ import annotations
@@ -43,5 +26,4 @@ from tools.computer_use.tool import ( # noqa: F401
set_approval_callback,
check_computer_use_requirements,
get_computer_use_schema,
- release_computer_use_session,
)
diff --git a/tools/computer_use/backend.py b/tools/computer_use/backend.py
index aa4507e3623..adf067efe33 100644
--- a/tools/computer_use/backend.py
+++ b/tools/computer_use/backend.py
@@ -7,10 +7,56 @@ handled inside the backend implementation if needed.
from __future__ import annotations
+import struct
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple
+_JPEG_SOF_MARKERS = frozenset({
+ 0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,
+ 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF,
+})
+
+
+def image_dimensions_from_bytes(raw: bytes) -> Optional[Tuple[int, int]]:
+ """Return (width, height) for PNG / JPEG bytes, or None when unreadable.
+
+ PNG: IHDR. JPEG: walk segments (skipping 0xFF fill bytes) to the first SOF
+ marker; stop at SOS. Used by the tool layer's provider min-size guard.
+ """
+ if raw.startswith(b"\x89PNG\r\n\x1a\n") and len(raw) >= 24:
+ try:
+ width, height = struct.unpack(">II", raw[16:24])
+ return int(width), int(height)
+ except Exception:
+ return None
+ if raw.startswith(b"\xff\xd8") and len(raw) > 4:
+ i = 2
+ while i + 9 < len(raw):
+ if raw[i] != 0xFF:
+ i += 1
+ continue
+ marker = raw[i + 1]
+ i += 2
+ while marker == 0xFF and i < len(raw):
+ marker = raw[i]
+ i += 1
+ if marker in {0xD8, 0xD9}:
+ continue
+ if marker == 0xDA:
+ break
+ if i + 2 > len(raw):
+ break
+ segment_len = int.from_bytes(raw[i:i + 2], "big")
+ if segment_len < 2 or i + segment_len > len(raw):
+ break
+ if marker in _JPEG_SOF_MARKERS and segment_len >= 7:
+ height = int.from_bytes(raw[i + 3:i + 5], "big")
+ width = int.from_bytes(raw[i + 5:i + 7], "big")
+ return int(width), int(height)
+ i += segment_len
+ return None
+
@dataclass
class UIElement:
diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.py
index 2d3937787d2..6f12b36c2d9 100644
--- a/tools/computer_use/cua_backend.py
+++ b/tools/computer_use/cua_backend.py
@@ -1,44 +1,20 @@
-"""Cua-driver backend (macOS, Windows, Linux).
-
-Speaks MCP over stdio to `cua-driver`. The Python `mcp` SDK is async, so we
-run a dedicated asyncio event loop on a background thread and marshal sync
-calls through it.
-
-The same `cua-driver call <tool>` surface (click, type_text, hotkey, drag,
-scroll, screenshot, launch_app, list_apps, list_windows, get_window_state,
-move_cursor, wait) works identically across macOS, Windows, and Linux —
-cua-driver's PARITY matrix marks the action tools VERIFIED on macOS and
-Windows in the cross-platform Rust port (`cua-driver-rs`).
-
-Linux is the most recent runtime (X11 today, Wayland via XWayland; pure-
-Wayland progress tracked upstream). It is enabled in
-`check_computer_use_requirements` alongside macOS and Windows. The plumbing
-in this file is OS-agnostic; per-host gaps (no DISPLAY, missing AT-SPI,
-etc.) surface as specific blocked checks via `hermes computer-use doctor`
-rather than failing silently.
-
-Install:
- - **macOS**:
- /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/install.sh)"
- - **Windows** (PowerShell):
- irm https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/install.ps1 | iex
-
-After install, `cua-driver` is on $PATH and supports `cua-driver mcp` (stdio
-transport) which is what we invoke.
-
-The macOS path uses private SkyLight SPIs (SLEventPostToPid,
-SLPSPostEventRecordTo, _AXObserverAddNotificationAndCheckRemote) that aren't
-Apple-public and can break on OS updates. The Windows path in cua-driver-rs
-uses stable Win32 APIs (SendInput + UI Automation) — not subject to the
-same SPI breakage class.
+"""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_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.
"""
from __future__ import annotations
-import asyncio
import base64
-from collections import deque
-import concurrent.futures
import functools
import json
import logging
@@ -47,178 +23,86 @@ import re
import shutil
import subprocess
import sys
-import tempfile
import threading
-import time
import uuid
from pathlib import PureWindowsPath
from typing import Any, Dict, List, Optional, Tuple
from hermes_cli._subprocess_compat import windows_hide_flags
-from tools.computer_use.backend import (
- ActionResult,
- CaptureResult,
- ComputerUseBackend,
- UIElement,
+from tools.computer_use.backend import ActionResult, CaptureResult, ComputerUseBackend, UIElement
+from tools.computer_use.cua_backend_daemon import ( # noqa: F401
+ _CUA_DRIVER_BUNDLE_ID,
+ _CUA_DRIVER_TEAM_IDS,
+ _EmbeddedCuaDaemon,
+ _embedded_daemon_spawn_command,
+ _resolve_cua_driver_app_path,
+ _validate_cua_driver_app_signature,
)
+from tools.computer_use.cua_backend_parse import ( # noqa: F401
+ _ELEMENT_LINE_RE,
+ _MISSING,
+ _NON_APP_WINDOW_TITLE_PREFIXES,
+ _action_result_from,
+ _apps_from_windows,
+ _extract_tool_result,
+ _image_dimensions_from_bytes,
+ _image_from_tool_result,
+ _ingest_windows,
+ _is_placeholder_id,
+ _is_real_app_window,
+ _mcp_field,
+ _parse_elements_from_structured,
+ _parse_elements_from_tree,
+ _parse_key_combo,
+ _parse_xprop_net_active_window,
+ _positive_int,
+ _split_tree_text,
+ _windows_from_tool_result,
+ _z_index_uninformative,
+)
+from tools.computer_use.cua_backend_session import _AsyncBridge, _CuaDriverSession # noqa: F401
logger = logging.getLogger(__name__)
-_MISSING = object()
-
-
-def _mcp_field(obj, snake: str, camel: str, default=None):
- """Read an MCP model field across the 1.x -> 2.x field rename.
-
- mcp 2.0 renamed model fields to snake_case, keeping camelCase only as a
- serialization alias that pydantic does not expose to attribute access. A
- plain ``getattr(result, "isError", False)`` therefore reads False for
- *every* result on 2.x — a denied or failed cua-driver call would be
- treated as a success. Reading both spellings keeps this correct on either
- SDK generation.
-
- Deliberately duplicated from ``tools.mcp_tool.mcp_field`` rather than
- imported: computer_use talks to cua-driver over its own stdio client and
- does not otherwise load the (much larger) config-driven MCP client module.
- """
- value = getattr(obj, snake, _MISSING)
- if value is not _MISSING:
- return value
- value = getattr(obj, camel, _MISSING)
- return default if value is _MISSING else value
-
-
-def _action_result_from(
- name: str,
- ok: bool,
- message: str,
- meta: Dict[str, Any],
- structured: Dict[str, Any],
- *,
- requested_delivery: Optional[str] = None,
-) -> ActionResult:
- """Build an ActionResult, lifting cua-driver's structured verdict.
-
- All structured fields are additive: a driver that omits
- ``structuredContent`` (or any individual field) leaves the corresponding
- ActionResult attribute ``None``, so callers and tests see unchanged
- behavior on old drivers. See the action response shape in
- cua-driver's mcp-tool-notes and NousResearch/hermes-agent#67052.
- """
- sc = structured if isinstance(structured, dict) else {}
-
- def _pick(key: str) -> Any:
- # structuredContent is canonical; fall back to a flattened meta copy.
- if key in sc:
- return sc.get(key)
- return meta.get(key)
-
- verified = _pick("verified")
- if not isinstance(verified, bool):
- verified = None
- effect = _pick("effect")
- if not isinstance(effect, str):
- effect = None
- escalation = _pick("escalation")
- if not isinstance(escalation, dict):
- escalation = None
- path = _pick("path")
- if not isinstance(path, str):
- path = None
- degraded = _pick("degraded")
- if not isinstance(degraded, bool):
- degraded = None
- # Refusal/limitation code — drivers spell it "code" or "reason_code".
- code = _pick("code") or _pick("reason_code")
- if not isinstance(code, str):
- code = None
- # Echo the delivery mode the caller actually requested (the driver's
- # `path` records the rung that ran; this records what we asked for).
- delivery_mode = requested_delivery if isinstance(requested_delivery, str) else None
-
- return ActionResult(
- ok=ok,
- action=name,
- message=message,
- meta=meta,
- verified=verified,
- effect=effect,
- escalation=escalation,
- path=path,
- degraded=degraded,
- delivery_mode=delivery_mode,
- code=code,
- )
-
-
-
-# ---------------------------------------------------------------------------
-# Update checking
-# ---------------------------------------------------------------------------
-#
-# cua-driver ships a native `check-update` verb (and a `check_for_update` MCP
-# tool) that compares the installed binary against the latest GitHub release —
-# the source of truth — and caches the result (~20h). We prefer that over a
-# hardcoded version floor, which would rot and can't know what "latest" is.
-#
-# There is intentionally no version *pin* knob: the upstream installer always
-# fetches the latest release, so a `HERMES_CUA_DRIVER_VERSION` env var would
-# only have *looked* like it pinned. For a reproducible version, 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 transport (fallback when the
- # driver doesn't expose `manifest` — see
- # `_resolve_mcp_invocation` below)
-
-# Whole-screen / desktop capture. cua-driver is a window-oriented driver —
-# its `get_window_state` / `screenshot` tools capture a single window (by
-# pid + window_id), and there is no MCP tool that captures the entire virtual
-# desktop or an arbitrary monitor as one image. But the OS shell surfaces
-# themselves (the desktop backdrop and the taskbar/menu-bar) are real windows
-# that show up in `list_windows`, so "click the taskbar" is reachable by
-# targeting those windows.
-#
-# Two distinct whole-screen intents, two lanes:
-# * app="screen" (or "fullscreen"/"full screen"/"all") → a real composited
-# capture of everything currently displayed, via cua-driver's
-# `get_desktop_state`. Pixels only — no element tree.
-# * app="desktop" → the OS shell/desktop window (wallpaper + icons) resolved
-# through list_windows, WITH interactable elements (desktop icons).
+_CUA_DRIVER_ARGS = ["mcp"] # stdio MCP; fallback when the driver has no `manifest` verb
+
+# Whole-screen intents: app="screen"/... -> composited `get_desktop_state`
+# (pixels only); app="desktop" -> the OS shell window via list_windows, WITH
+# interactable elements (desktop icons, taskbar).
_FULL_SCREEN_SENTINELS = {"screen", "fullscreen", "full screen", "all"}
_DESKTOP_SHELL_SENTINELS = {"desktop"}
-# Backwards-compatible union — membership means "some whole-screen intent".
-_SCREEN_CAPTURE_SENTINELS = _FULL_SCREEN_SENTINELS | _DESKTOP_SHELL_SENTINELS
-
-# Known shell/desktop window identifiers across platforms. Matched
-# case-insensitively as a substring against both the window's app_name and
-# its title (cua-driver surfaces the Win32 class name / app name here).
-# Windows: Progman / WorkerW back the desktop; Shell_TrayWnd is the taskbar.
-# macOS: Finder owns the desktop; the menu bar / Dock are the shell.
+# Shell window identifiers (substring of app_name + title, case-insensitive).
+# Windows: Progman/WorkerW = desktop, Shell_TrayWnd = taskbar; macOS: Finder/Dock.
_DESKTOP_WINDOW_NAMES = (
- "progman", "workerw", "program manager", # Windows desktop
- "shell_traywnd", "taskbar", # Windows taskbar
- "finder", "desktop", "dock", # macOS desktop / shell
+ "progman", "workerw", "program manager", "shell_traywnd", "taskbar",
+ "finder", "desktop", "dock",
)
+# Backdrop subset preferred over the taskbar when both are present.
+_DESKTOP_BACKDROP_NAMES = ("progman", "workerw", "program manager", "finder", "desktop")
-# Linux/X11 can surface GNOME Shell / desktop backdrop windows before real app
-# windows and cua-driver 0.6.x currently does not assign a useful z-order for
-# them. These windows are targetable X11 windows but do not produce screenshots
-# through get_window_state, so default app capture must skip them.
-_NON_APP_WINDOW_TITLE_PREFIXES = (
- "@!", # GNOME Shell background/monitor helper windows
- "Desktop",
- "gnome-shell",
- "GNOME Shell",
-)
+# cua-driver's anonymous PostHog telemetry gate ("0" disables; absent => ON upstream).
+_CUA_TELEMETRY_ENV_VAR = "CUA_DRIVER_RS_TELEMETRY_ENABLED"
+
+_CUA_DRIVER_RUNTIME_CONTRACT_MIN = (0, 20, 0)
+_CUA_DRIVER_RUNTIME_CONTRACT_ARGS = {
+ "mcp": {"--socket", "--grant"},
+ "serve": {"--socket", "--permission-mode", "--capability-manifest",
+ "--approve-capability-manifest", "--embedded"},
+ "stop": {"--socket"},
+}
+_WINDOW_TITLE_RE = re.compile(r'AXWindow\s+"([^"]+)"')
-# Env var cua-driver reads to gate its anonymous usage telemetry (PostHog).
-# Setting it to "0" disables telemetry; absence => the binary's own default
-# (telemetry 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."""
@@ -233,20 +117,16 @@ def _computer_use_cfg() -> Dict[str, Any]:
def _cua_no_overlay() -> bool:
"""True when Hermes should pass ``--no-overlay`` to cua-driver.
- Reads ``computer_use.no_overlay``. Default ``None`` (auto-detect):
- disable the overlay where idle CPU burn or an X11 desktop wedge is a
- known failure mode — macOS (cursor-overlay vImage redraw loop,
- #28152/#47032), headless Linux / WSL2 / containers, and Linux X11
- (fullscreen always-on-top overlay window that can get stuck over every
- workspace after an unclean session end) — and keep it on Windows and
- Linux Wayland. Explicit ``True`` / ``False`` overrides auto-detection.
+ ``computer_use.no_overlay`` overrides when set. Auto-detect otherwise:
+ 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)
- # Auto-detect: macOS overlay can peg a core indefinitely after a
- # computer_use session (#47032). Prefer off until the driver teardown
- # is solid; set computer_use.no_overlay: false to keep the cursor.
if sys.platform == "darwin":
return True
if sys.platform != "linux":
@@ -259,50 +139,30 @@ def _cua_no_overlay() -> bool:
return True
except Exception:
pass
- # Linux/X11: the cursor overlay is a fullscreen, always-on-top,
- # all-workspaces X11 window (save-unders path). An unclean session end
- # (agent interrupted mid-capture, stale target window) can leave it stuck
- # above every app on every workspace, wedging desktop input until the app
- # restarts — the same failure class as the HUD window on Mutter/X11
- # (#83473). There is no compositor-owned surface to tear down with the
- # client connection, so default the overlay off on X11 too; set
- # computer_use.no_overlay: false to keep the cursor. Wayland keeps it: the
- # compositor owns the overlay surface lifecycle there.
- if os.environ.get("XDG_SESSION_TYPE") != "wayland" and not os.environ.get("WAYLAND_DISPLAY"):
- return True
- return False
+ return os.environ.get("XDG_SESSION_TYPE") != "wayland" and not os.environ.get("WAYLAND_DISPLAY")
def _cua_telemetry_disabled() -> bool:
- """True when Hermes should disable cua-driver telemetry for this user.
-
- Reads ``computer_use.cua_telemetry`` (default False → telemetry off).
- Unreadable config falls SAFE toward disabling telemetry.
- """
- # opt-in flag: True => user wants telemetry => do NOT disable.
+ """True unless ``computer_use.cua_telemetry`` opts in (unreadable config
+ fails SAFE toward disabling telemetry)."""
return not bool(_computer_use_cfg().get("cua_telemetry", False))
def _cua_configured_permission_mode() -> str:
- """The user-configured cua-driver permission mode.
+ """``computer_use.permission_mode`` (default ``standard``).
- Reads ``computer_use.permission_mode`` (default ``standard``). Only
- ``standard`` and ``bounded`` are honored here — ``unrestricted`` is
- deliberately NOT a config value: it stays tied to the explicit
- per-session Hermes YOLO toggle so a stale config line can never
- silently bypass approvals. Unknown values fall closed to ``standard``.
+ Only ``standard`` / ``bounded`` are honored: ``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.
+ Unknown values fall closed to ``standard``.
"""
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]:
- """Path of the reviewed capability manifest for bounded mode, or None.
-
- Reads ``computer_use.capability_manifest``. Existence is validated by
- ``_EmbeddedCuaDaemon`` so a missing file fails loudly at session start
- instead of silently degrading the authorization story.
- """
+ """``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")
if not isinstance(raw, str) or not raw.strip():
return None
@@ -312,19 +172,11 @@ def _cua_capability_manifest() -> Optional[str]:
def _manifest_is_mode_independent(path: str) -> bool:
"""True when this capability manifest may accompany any permission mode.
- cua-driver splits manifests by schema version (session_manifest.rs):
-
- * v1/v2 are "legacy" — they must declare ``mode: bounded`` (or
- ``autonomous``), so handing one to an unrestricted runtime aborts
- startup with "legacy capability manifest mode must be bounded".
- * v3 must NOT declare a mode. It is the mode-independent ceiling that
- "can narrow a profile but never widen it", and the driver accepts it
- alongside ``--permission-mode unrestricted``.
-
- Unreadable or unparseable manifests return False: forwarding one to a
- non-bounded runtime would turn a working session into a hard startup
- failure, and bounded forwards unconditionally anyway so the driver stays
- the authority on validity there.
+ v1/v2 manifests must declare ``mode: bounded`` and abort startup under an
+ unrestricted runtime; v3 must NOT declare a mode and is the mode-
+ independent 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
@@ -341,11 +193,8 @@ def _manifest_is_mode_independent(path: str) -> bool:
def _computer_use_max_image_dimension() -> Optional[int]:
- """Longest-edge cap for cua-driver screenshots, or None to leave unset.
-
- Reads ``computer_use.max_image_dimension`` (default 1456, matching the
- aux-vision downscale). ``0`` / negative / non-numeric → None.
- """
+ """``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):
@@ -354,36 +203,58 @@ def _computer_use_max_image_dimension() -> Optional[int]:
def cua_driver_child_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str, str]:
- """Return the environment dict for spawning cua-driver.
-
- Starts from ``base_env`` (defaults to ``os.environ``) and, when telemetry
- is disabled (the default), injects ``CUA_DRIVER_RS_TELEMETRY_ENABLED=0``.
- When the user has opted in, the var is left untouched so cua-driver uses
- its own default. Used by every cua-driver spawn site (MCP backend, status,
- doctor, install) so the policy is applied consistently.
- """
+ """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
+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."""
+ 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_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 / capture-target selection
+# ---------------------------------------------------------------------------
+
def _linux_session_locked() -> Optional[bool]:
"""Best-effort: is the graphical session locked? (Linux only.)
- A locked KDE/GNOME session freezes app renderers and half-disables the
- AX tree, so window discovery legitimately returns nothing — but a bare
- empty result reads as a driver bug (live QA, Aug 2026: every capture
- came back 0x0 with no hint). True/False when loginctl answers, None
- when unavailable (non-Linux, no systemd-logind, probe failure).
+ A locked KDE/GNOME session freezes renderers and half-disables the AX
+ tree, so window 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 = subprocess.run(
- ["loginctl", "list-sessions", "--no-legend"],
- capture_output=True, text=True, timeout=2.0,
- )
+ proc = subprocess.run(["loginctl", "list-sessions", "--no-legend"],
+ capture_output=True, text=True, timeout=2.0)
if proc.returncode != 0:
return None
any_seat = False
@@ -392,10 +263,8 @@ def _linux_session_locked() -> Optional[bool]:
if len(parts) < 2 or "seat" not in line:
continue
any_seat = True
- probe = subprocess.run(
- ["loginctl", "show-session", parts[0], "-p", "LockedHint"],
- capture_output=True, text=True, timeout=2.0,
- )
+ probe = subprocess.run(["loginctl", "show-session", parts[0], "-p", "LockedHint"],
+ capture_output=True, text=True, timeout=2.0)
if "LockedHint=no" in probe.stdout:
return False
return True if any_seat else None
@@ -405,8 +274,7 @@ def _linux_session_locked() -> Optional[bool]:
def _empty_discovery_reason() -> str:
"""One-line diagnosis for 'window discovery found nothing'."""
- locked = _linux_session_locked()
- if locked is True:
+ if _linux_session_locked() is True:
return (
"the desktop session is LOCKED (loginctl LockedHint=yes) — "
"unlock the screen; a locked compositor hides windows and "
@@ -416,7 +284,7 @@ def _empty_discovery_reason() -> str:
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 (#67165, #52925 lineage).
+ # 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) — "
@@ -429,57 +297,16 @@ def _empty_discovery_reason() -> str:
)
-def _z_index_uninformative(windows: List[Dict[str, Any]]) -> bool:
- """True when every window shares the same z_index (common on Linux/X11)."""
- if not windows:
- return True
- return len({w.get("z_index", 0) for w in windows}) <= 1
-
-
-def _parse_xprop_net_active_window(stdout: str) -> Optional[int]:
- """Parse ``xprop -root _NET_ACTIVE_WINDOW`` stdout into a window id.
-
- Accepts the common ``window id # 0x...`` form and falls back to the first
- hex token. Returns None for empty/unparseable output.
- """
- text = stdout or ""
- match = re.search(r"window id # (0x[0-9a-fA-F]+)", text)
- if not match:
- match = re.search(r"(0x[0-9a-fA-F]+)", text)
- if not match:
- return None
- try:
- return int(match.group(1), 16)
- except ValueError:
- return None
-
-
def _linux_x11_active_window_id() -> Optional[int]:
"""Best-effort read of ``_NET_ACTIVE_WINDOW`` via xprop. Never raises."""
if sys.platform != "linux" or not os.environ.get("DISPLAY"):
return None
try:
- proc = subprocess.run(
- ["xprop", "-root", "_NET_ACTIVE_WINDOW"],
- capture_output=True,
- text=True, encoding="utf-8", errors="replace",
- timeout=2,
- check=False,
- )
+ proc = subprocess.run(["xprop", "-root", "_NET_ACTIVE_WINDOW"], capture_output=True,
+ text=True, encoding="utf-8", errors="replace", timeout=2, check=False)
except Exception:
return None
- if proc.returncode != 0:
- return None
- return _parse_xprop_net_active_window(proc.stdout or "")
-
-
-def _is_real_app_window(w: Dict[str, Any]) -> bool:
- """Return False for desktop/shell helper windows that capture as empty."""
- title = w.get("title", "")
- return not any(
- title.startswith(p) or title.lower().startswith(p.lower())
- for p in _NON_APP_WINDOW_TITLE_PREFIXES
- )
+ return _parse_xprop_net_active_window(proc.stdout or "") if proc.returncode == 0 else None
def _select_capture_target(
@@ -488,17 +315,14 @@ def _select_capture_target(
app_requested: bool,
exact_target: bool = False,
) -> Dict[str, Any]:
- """Select the best window for capture from normalized list_windows output.
-
- Callers pass windows already sorted by ``z_index`` descending (higher =
- frontmost). When ordering is informative, keep that frontmost contract.
- For unqualified default captures (no app filter and no exact
- pid/window_id) on Linux, desktop/shell helper windows (GNOME ``ding``
- "Desktop Icons", ``@!x,y;BDHF`` backdrop helpers) are skipped first —
- they are targetable X11 windows but capture as empty. Then, when every
- remaining candidate shares the same ``z_index`` (tied or unknown, the
- common Linux/X11 case), prefer ``_NET_ACTIVE_WINDOW`` over list order
- (#58026). Exact-target captures must not pay for an ``xprop`` probe.
+ """Select the best window for capture from z-sorted list_windows output.
+
+ Windows arrive sorted by ``z_index`` descending (frontmost first). For
+ unqualified default captures on Linux (no app filter, no exact target),
+ desktop/shell helper windows are skipped first — they are targetable but
+ capture as empty — and when every remaining candidate shares the same
+ ``z_index`` (the common X11 case) ``_NET_ACTIVE_WINDOW`` beats list order.
+ Exact-target captures never pay for the ``xprop`` probe.
"""
candidates = [w for w in windows if not w["off_screen"]]
pool = candidates
@@ -512,19 +336,22 @@ def _select_capture_target(
for w in pool:
if w.get("window_id") == active_id:
return w
- if pool:
- return pool[0]
- return windows[0]
+ return pool[0] if pool else windows[0]
-def _wsl_windows_path_to_posix(path: str) -> str:
- """Translate a Windows absolute manifest command when Hermes runs in WSL.
+# ---------------------------------------------------------------------------
+# Driver resolution + MCP invocation
+# ---------------------------------------------------------------------------
- Windows cua-driver manifests can report ``C:\\Users\\...\\cua-driver.exe``
- even though the Hermes process uses POSIX subprocess spawning inside WSL.
- The same file is reachable through DrvFS as ``/mnt/c/Users/...``.
- Non-Windows paths and non-WSL hosts are returned unchanged.
- """
+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."""
if not re.match(r"^[A-Za-z]:[\\/]", path):
return path
try:
@@ -541,552 +368,25 @@ def _wsl_windows_path_to_posix(path: str) -> str:
return os.path.join("/mnt", drive, *(str(part) for part in win.parts[1:]))
-def _resolve_cua_driver_app_path(driver_cmd: str) -> Optional[str]:
- """Return the CuaDriver.app bundle that CARRIES *driver_cmd*, if any.
-
- Deliberately derived from the resolved driver binary path only — no
- /Applications or ~/Applications fallback. A fallback candidate can be a
- DIFFERENT install than the driver the manifest resolved (stale copy,
- side-by-side version), and launching it would run code the resolution
- chain never validated. If the resolved driver does not live inside an
- app bundle, the caller fails closed with install guidance.
- """
- resolved_driver_cmd = os.path.realpath(driver_cmd)
- marker = ".app/Contents/MacOS/"
- marker_index = resolved_driver_cmd.find(marker)
- if marker_index < 0:
- return None
- candidate = resolved_driver_cmd[: marker_index + len(".app")]
- executable = os.path.join(candidate, "Contents", "MacOS", "cua-driver")
- if os.path.isfile(executable) and os.access(executable, os.X_OK):
- return candidate
- return None
-
-
-# The only bundle identity the private daemon may launch through, and the
-# teams that sign official cua-driver releases. Exact matches only: a
-# suffixed identifier ("com.trycua.driver.evil") or a different non-empty
-# team is an impostor bundle, not a variant.
-_CUA_DRIVER_BUNDLE_ID = "com.trycua.driver"
-_CUA_DRIVER_TEAM_IDS = ("4YEC26S9KF", "YCK386LBJ7")
-
-
-def _validate_cua_driver_app_signature(app_path: str) -> None:
- """Fail closed unless *app_path* is the genuinely-signed CuaDriver.app.
-
- Launching via ``/usr/bin/open`` hands LaunchServices whatever bundle sits
- at the path, so the TCC-identity fix must not become a launcher for
- arbitrary apps: require ``codesign -dv`` to report EXACTLY
- ``Identifier=com.trycua.driver`` and an expected TeamIdentifier.
- ``TeamIdentifier=not set`` (unsigned/ad-hoc dev builds) is allowed only
- when ``computer_use.allow_unsigned_driver: true`` is set in config.yaml —
- the escape hatch for local driver development, never the default. 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,
- )
- 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()})"
- )
- # codesign -dv reports on stderr.
- fields = {}
- for line in (proc.stderr or "").splitlines():
- key, sep, value = line.partition("=")
- if sep:
- fields.setdefault(key.strip(), value.strip())
- identifier = fields.get("Identifier", "")
- team = 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:
- return
- if team in ("", "not set") and _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.)"
- )
-
-
-def _embedded_daemon_spawn_command(
- driver_cmd: str,
- serve_args: List[str],
- *,
- platform: str,
- app_path: Optional[str] = None,
-) -> List[str]:
- """Build the private-daemon launch while preserving macOS TCC identity."""
- if platform != "darwin":
- 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."
- )
- _validate_cua_driver_app_signature(resolved_app)
- return [
- "/usr/bin/open",
- "-n",
- "-g",
- "-a",
- resolved_app,
- "--args",
- *serve_args,
- ]
-
-
-class _EmbeddedCuaDaemon:
- """Private daemon for a non-standard permission mode.
-
- Cua Driver permission mode is immutable after daemon startup. Reusing the
- machine-wide daemon would therefore let one Hermes session's YOLO choice
- affect another session. A private embedded daemon gives the requesting
- session its own socket, runtime, and launch-time authorization. On macOS
- the runtime is launched through CuaDriver.app so TCC remains attached to
- ``com.trycua.driver`` instead of the embedding host's ad-hoc signature:
-
- * ``unrestricted`` — explicit Hermes YOLO; launch-time risk
- acknowledgement via ``--dangerously-bypass-approvals``.
- * ``bounded`` — a user-reviewed capability manifest
- (``computer_use.capability_manifest`` in config.yaml) approved at
- launch via ``--approve-capability-manifest``. The manifest, not a
- runtime prompt, is the authorization boundary; calls outside it fail
- closed inside cua-driver.
-
- The manifest is a ceiling, not a mode. cua-driver accepts it alongside
- any permission mode and it "can narrow a profile but never widen it", so
- a configured manifest is forwarded here even when YOLO selected
- ``unrestricted`` — that pairing is what bounds an approval-bypassed run
- to declared scope. It stays mandatory for ``bounded`` and optional
- everywhere else.
- """
-
- _START_TIMEOUT_SECONDS = 15.0
-
- def __init__(
- self,
- driver_cmd: str,
- permission_mode: str,
- capability_manifest: Optional[str] = None,
- ) -> None:
- 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 there. Any other
- # mode only accepts a v3 (mode-independent) manifest; forwarding a
- # legacy one would abort startup instead of bounding the run.
- self.manifest_applies = bool(self.capability_manifest) and (
- permission_mode == "bounded"
- or _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 = driver_cmd
- self._command = driver_cmd
- self._mcp_args: List[str] = list(_CUA_DRIVER_ARGS)
- self._process: Any = None
- self._owns_runtime = False
- self._running = False
- self._launch_via_app = False
- self._stderr_tail: deque[str] = deque(maxlen=20)
- self._stderr_thread: Optional[threading.Thread] = None
- token = uuid.uuid4().hex[:12]
- if sys.platform == "win32":
- self.socket_path = rf"\\.\pipe\hermes-cua-{token}"
- else:
- self.socket_path = os.path.join(
- tempfile.gettempdir(), f"hc-{token}.sock"
- )
-
- def child_env(self) -> Dict[str, str]:
- env = 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 _drain_stderr(self, process: Any) -> None:
- stream = getattr(process, "stderr", None)
- if stream is None:
- return
- try:
- for line in stream:
- text = str(line).strip()
- if text:
- self._stderr_tail.append(text)
- logger.debug("embedded cua-driver: %s", text)
- except Exception:
- pass
-
- def start(self) -> None:
- if self._running:
- return
- from tools.environments.local import _sanitize_subprocess_env
-
- if not self._driver_cmd:
- self._driver_cmd = resolve_cua_driver_cmd() or ""
- if not self._driver_cmd:
- raise RuntimeError(cua_driver_install_hint())
- self._command, self._mcp_args = _resolve_mcp_invocation(self._driver_cmd)
- env = _sanitize_subprocess_env(self.child_env())
- 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")
- # A v3 manifest is a ceiling, not a mode: cua-driver accepts it
- # alongside any permission mode and it "can narrow a profile but never
- # widen it". Attaching it to unrestricted is what bounds an
- # approval-bypassed run to declared scope, so pass it whenever it
- # applies — not only for bounded, which used to drop it for every
- # other mode.
- if self.manifest_applies:
- serve_args.extend(
- [
- "--capability-manifest",
- str(self.capability_manifest),
- "--approve-capability-manifest",
- ]
- )
- # The private daemon owns the platform cursor overlay. Applying the
- # policy only to its MCP proxy leaves this long-lived serve process
- # free to create a full-screen overlay before session tuning runs.
- # Must be appended BEFORE the macOS app-launch wrapping so the flag
- # travels inside `open ... --args` with the rest of the serve args.
- serve_args = _mcp_args_with_overlay_flag(serve_args, driver_cmd=self._command)
- self._launch_via_app = sys.platform == "darwin"
- command = _embedded_daemon_spawn_command(
- self._command,
- 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()
-
- deadline = time.monotonic() + self._START_TIMEOUT_SECONDS
- while time.monotonic() < deadline:
- return_code = self._process.poll()
- 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}"
- )
- 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):
- probe = None
- if probe is not None and probe.returncode == 0:
- 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}")
-
- def proxy_invocation(self) -> Tuple[str, List[str]]:
- if not self._running:
- raise RuntimeError("embedded cua-driver daemon is not running")
- return self._command, [
- *self._mcp_args,
- "--embedded",
- "--socket",
- self.socket_path,
- ]
-
- def stop(self) -> None:
- process = self._process
- self._process = None
- 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
- if process is not None:
- try:
- process.wait(timeout=5.0)
- except subprocess.TimeoutExpired:
- process.terminate()
- try:
- process.wait(timeout=2.0)
- except subprocess.TimeoutExpired:
- process.kill()
- process.wait(timeout=2.0)
- if sys.platform != "win32" and os.path.exists(self.socket_path):
- try:
- os.remove(self.socket_path)
- except OSError:
- pass
-
-
-def _resolve_mcp_invocation(
- driver_cmd: str,
- *,
- timeout: float = 6.0,
-) -> Tuple[str, List[str]]:
- """Return ``(command, args)`` that spawn cua-driver's stdio MCP server.
-
- Surface 8 of NousResearch/hermes-agent#47072: instead of hardcoding
- ``["mcp"]`` we ask the driver itself via ``cua-driver manifest``
- (trycua/cua#1961). The manifest carries a stable ``mcp_invocation``
- pointer with both ``command`` and ``args``, so a future cua-driver
- that renames or relocates the subcommand keeps working without a
- Hermes patch.
-
- Falls back to ``(driver_cmd, ["mcp"])`` for older drivers that don't
- expose ``manifest``, or any indeterminate failure — the wrapper must
- not refuse to start just because the discovery hop failed.
-
- When ``computer_use.no_overlay`` is enabled (or auto-detected — macOS,
- headless/WSL2/X11 Linux), ``--no-overlay`` is appended to suppress the
- cursor overlay rendering loop that can consume CPU indefinitely when idle
- (#28152, #47032). Older drivers that don't recognise the flag will
- reject it; callers should fall back to the no-overlay invocation on
- spawn failure.
- """
- try:
- from tools.environments.local import _sanitize_subprocess_env
- proc = subprocess.run(
- [driver_cmd, "manifest"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout,
- stdin=subprocess.DEVNULL,
- creationflags=windows_hide_flags(),
- # cua-driver is a third-party binary — never hand it provider
- # API keys via inherited env (same policy as the MCP and CLI
- # fallback spawns below; #53503/#55709/#58889 lineage).
- env=_sanitize_subprocess_env(cua_driver_child_env()),
- )
- except Exception:
- return driver_cmd, _mcp_args_with_overlay_flag(list(_CUA_DRIVER_ARGS), driver_cmd=driver_cmd)
- out = (proc.stdout or "").strip()
- if proc.returncode != 0 or not out:
- return driver_cmd, _mcp_args_with_overlay_flag(list(_CUA_DRIVER_ARGS), driver_cmd=driver_cmd)
- try:
- manifest = json.loads(out)
- except (ValueError, TypeError):
- return driver_cmd, _mcp_args_with_overlay_flag(list(_CUA_DRIVER_ARGS), driver_cmd=driver_cmd)
- if not isinstance(manifest, dict):
- return driver_cmd, _mcp_args_with_overlay_flag(list(_CUA_DRIVER_ARGS), driver_cmd=driver_cmd)
- invocation = manifest.get("mcp_invocation")
- if not isinstance(invocation, dict):
- return driver_cmd, _mcp_args_with_overlay_flag(list(_CUA_DRIVER_ARGS), driver_cmd=driver_cmd)
- args = invocation.get("args")
- command = invocation.get("command")
- if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
- return driver_cmd, _mcp_args_with_overlay_flag(list(_CUA_DRIVER_ARGS), driver_cmd=driver_cmd)
- if not isinstance(command, str) or not command:
- # The driver knows the subcommand but didn't surface its own path.
- # Keep our resolved driver_cmd; the args are still authoritative.
- return driver_cmd, _mcp_args_with_overlay_flag(args, driver_cmd=driver_cmd)
- # A Windows-installed cua-driver can hand a WSL-hosted Hermes an absolute
- # ``C:\...`` command; translate it to its DrvFS ``/mnt/<drive>/...`` form
- # BEFORE the path-separator check (backslash is not a separator on POSIX,
- # so the raw Windows string would otherwise be discarded here).
- command = _wsl_windows_path_to_posix(command)
- if not _has_path_separator(command):
- # A manifest may legitimately retain the generic ``cua-driver`` name.
- # Under a GUI's thin PATH that would lose the resolved user-local path
- # and fail at MCP spawn, so preserve the concrete command we verified.
- return driver_cmd, _mcp_args_with_overlay_flag(args, driver_cmd=driver_cmd)
- # Manifest surfaced a relocated executable — probe THAT binary for
- # `--no-overlay` support rather than the system-resolved one, so a
- # wrapper/relocation with a different feature set doesn't crash on
- # an unknown flag (or silently keep an unwanted overlay).
- return command, _mcp_args_with_overlay_flag(args, driver_cmd=command)
-
-
-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 _cua_no_overlay() and _cua_driver_supports_no_overlay(driver_cmd):
- return [*args, "--no-overlay"]
- return list(args)
-
-
[email protected]_cache(maxsize=1)
-def _cua_driver_supports_no_overlay(driver_cmd: str) -> bool:
- """True if the installed cua-driver recognises ``--no-overlay``.
-
- Probes ``<driver> --help`` once and caches the result. Older
- drivers (< 0.6.x) reject unknown flags, so passing ``--no-overlay``
- would crash the MCP spawn.
- """
- try:
- # cua-driver is a third-party binary — never hand it provider
- # API keys via inherited env (same policy as the manifest probe
- # and MCP spawn; #53503/#55709/#58889 lineage).
- from tools.environments.local import _sanitize_subprocess_env
- proc = subprocess.run(
- [driver_cmd, "--help"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=3.0,
- stdin=subprocess.DEVNULL,
- creationflags=windows_hide_flags(),
- env=_sanitize_subprocess_env(cua_driver_child_env()),
- )
- help_text = (proc.stdout or "") + (proc.stderr or "")
- return "--no-overlay" in help_text
- except Exception:
- return False
-
-# Regex to parse element lines from get_window_state AX tree markdown.
-#
-# cua-driver renders each actionable node as one of:
-# - [N] AXRole "label" (quoted label, classic)
-# - [N] AXRole = "value" (value form, e.g. AXStaticText/AXPopUpButton)
-# - [N] AXRole (label) (parenthesised label, e.g. AXButton (Dark))
-# - [N] AXRole (order) id=Label (order number + id= label, newer builds)
-# - [N] AXRole id=Label (id= label only)
-# - [N] AXRole (no label)
-# followed by trailing metadata like [help="..." actions=[...]].
-#
-# Earlier the regex only matched the quoted and id= forms, so the very common
-# `(label)` and `= "value"` forms (System Settings buttons, static text, popups)
-# came back with an empty label — which made label-driven clicking impossible.
-# A parenthesised group that is purely digits is an ORDER index, not a label, so
-# it is excluded and we fall through to the id= label.
-#
-# Group 1: element index Group 2: AX role
-# Groups 3-6: the label in value / quoted / paren / id= form (whichever matched)
-_ELEMENT_LINE_RE = re.compile(
- r'^\s*(?:-\s+)?\[(\d+)\]\s+(\w+)'
- r'(?:'
- r'\s*=\s*"([^"]*)"' # = "value"
- r'|\s+"([^"]*)"' # "value"
- r'|\s+\((?!\d+\))([^)]*)\)' # (value) but not a pure-digit (order) number
- r')?'
- r'(?:\s+(?:\(\d+\)\s+)?id=([^\s\[\]]+))?', # optional id=value (after an optional (order))
- re.MULTILINE,
-)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-def _is_macos() -> bool:
- return sys.platform == "darwin"
-
-
-def _has_path_separator(value: str) -> bool:
- return os.sep in value or (os.altsep is not None and os.altsep in value)
-
-
def _candidate_cua_driver_commands(override: Optional[str] = None) -> List[str]:
- """Return candidate cua-driver commands in resolution order.
-
- ``override`` is authoritative when supplied. Otherwise a non-empty
- ``HERMES_CUA_DRIVER_CMD`` is authoritative; only when neither is set do we
- use PATH and canonical install locations.
+ """Candidate cua-driver commands in resolution order.
- Desktop apps launched from Finder/Dock often inherit a narrow PATH that
- omits user-local install directories. The upstream cua-driver installer
- commonly places the binary under ``~/.local/bin`` on POSIX systems, so a
- Hermes Desktop/TUI session can otherwise filter out the `computer_use`
- tool even though `hermes computer-use doctor` succeeds from a login shell.
+ ``override`` / a non-empty ``HERMES_CUA_DRIVER_CMD`` is authoritative (if
+ it is wrong, report the driver missing rather than silently picking
+ another binary). Otherwise PATH, then canonical installer locations —
+ Desktop apps launched from Finder/Dock inherit a narrow PATH that omits
+ ``~/.local/bin``, and freshly installed Windows sessions inherit a stale one.
"""
configured = (override if override is not None else os.environ.get(_CUA_DRIVER_CMD_ENV, "")).strip()
if configured:
- # An explicit override is authoritative: if it is wrong, report the
- # driver missing instead of silently picking a different binary.
return [configured]
candidates = [_CUA_DRIVER_DEFAULT_CMD]
home = os.path.expanduser("~")
if sys.platform == "win32":
- local_app_data = os.environ.get("LOCALAPPDATA") or os.path.join(
- home, "AppData", "Local"
- )
+ local_app_data = os.environ.get("LOCALAPPDATA") or os.path.join(home, "AppData", "Local")
candidates.extend([
- # Official cua-driver installer location on Windows. Freshly
- # installed sessions inherit a stale PATH, so PATH lookup alone
- # misses it until every Hermes process is restarted.
- os.path.join(
- local_app_data, "Programs", "Cua", "cua-driver", "bin", "cua-driver.exe"
- ),
+ 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"),
])
@@ -1102,20 +402,12 @@ def _candidate_cua_driver_commands(override: Optional[str] = None) -> List[str]:
def resolve_cua_driver_cmd(override: Optional[str] = None) -> Optional[str]:
"""Resolve the cua-driver executable for every runtime/status surface.
-
- A supplied override (or ``HERMES_CUA_DRIVER_CMD``) is never silently
- replaced by another binary. Otherwise resolve PATH first, then canonical
- user-local installation locations used by the official installer.
- """
+ An override is never silently replaced by another binary."""
for candidate in _candidate_cua_driver_commands(override):
expanded = os.path.expanduser(candidate)
- if _has_path_separator(expanded):
- if shutil.which(expanded):
- return expanded
- else:
- resolved = shutil.which(expanded)
- if resolved:
- return resolved
+ resolved = shutil.which(expanded)
+ if resolved:
+ return expanded if _has_path_separator(expanded) else resolved
return None
@@ -1124,91 +416,109 @@ def cua_driver_binary_available() -> bool:
return resolve_cua_driver_cmd() is not None
-_CUA_DRIVER_RUNTIME_CONTRACT_MIN = (0, 20, 0)
-_CUA_DRIVER_RUNTIME_CONTRACT_ARGS = {
- "mcp": {"--socket", "--grant"},
- "serve": {
- "--socket",
- "--permission-mode",
- "--capability-manifest",
- "--approve-capability-manifest",
- "--embedded",
- },
- "stop": {"--socket"},
-}
+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 _cua_no_overlay() and _cua_driver_supports_no_overlay(driver_cmd):
+ return [*args, "--no-overlay"]
+ return list(args)
+
+
[email protected]_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."""
+ try:
+ proc = _run_driver(driver_cmd, "--help", timeout=3.0)
+ return "--no-overlay" in (proc.stdout or "") + (proc.stderr or "")
+ except Exception:
+ return False
+
+
+def _resolve_mcp_invocation(driver_cmd: str, *, timeout: float = 6.0) -> Tuple[str, List[str]]:
+ """Return ``(command, args)`` that spawn cua-driver's stdio MCP server.
+
+ Asks the driver itself via ``cua-driver manifest`` (``mcp_invocation``
+ carries ``command`` + ``args``) so a future rename of the subcommand keeps
+ working. Falls back to ``(driver_cmd, ["mcp"])`` for older drivers or any
+ discovery failure — the wrapper must not refuse to start over a failed
+ discovery hop. ``--no-overlay`` is appended when policy + driver allow.
+ """
+ def _with_driver(args: List[str]) -> Tuple[str, List[str]]:
+ return driver_cmd, _mcp_args_with_overlay_flag(args, driver_cmd=driver_cmd)
+
+ default = list(_CUA_DRIVER_ARGS)
+ try:
+ proc = _run_driver(driver_cmd, "manifest", timeout=timeout)
+ except Exception:
+ return _with_driver(default)
+ out = (proc.stdout or "").strip()
+ if proc.returncode != 0 or not out:
+ return _with_driver(default)
+ try:
+ manifest = json.loads(out)
+ except (ValueError, TypeError):
+ return _with_driver(default)
+ invocation = manifest.get("mcp_invocation") if isinstance(manifest, dict) else None
+ if not isinstance(invocation, dict):
+ return _with_driver(default)
+ args = invocation.get("args")
+ command = invocation.get("command")
+ if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
+ return _with_driver(default)
+ if not isinstance(command, str) or not command:
+ # Args are authoritative; keep our resolved driver_cmd as the binary.
+ return _with_driver(args)
+ # Translate a Windows ``C:\...`` command for WSL BEFORE the separator
+ # check (backslash is not a separator on POSIX).
+ command = _wsl_windows_path_to_posix(command)
+ if not _has_path_separator(command):
+ # A generic ``cua-driver`` name would lose the resolved user-local
+ # path under a GUI's thin PATH; keep the concrete command we verified.
+ return _with_driver(args)
+ # Manifest surfaced a relocated executable — probe THAT binary for
+ # `--no-overlay` support, not the system-resolved one.
+ 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 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 resolve_cua_driver_cmd()
- if not resolved:
- return {
- "ready": False,
- "binary": None,
- "version": None,
- "reason": "cua-driver is not installed",
- }
- try:
- from tools.environments.local import _sanitize_subprocess_env
+ def _not_ready(reason: str, version: Optional[str] = None) -> Dict[str, Any]:
+ return {"ready": False, "binary": resolved, "version": version, "reason": reason}
- result = subprocess.run(
- [resolved, "manifest"],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=15.0 if sys.platform == "win32" else 5.0,
- stdin=subprocess.DEVNULL,
- env=_sanitize_subprocess_env(cua_driver_child_env()),
- creationflags=windows_hide_flags(),
- )
+ if not resolved:
+ return _not_ready("cua-driver is not installed")
+ try:
+ result = _run_driver(resolved, "manifest", timeout=15.0 if sys.platform == "win32" else 5.0)
except (OSError, subprocess.SubprocessError) as exc:
- return {
- "ready": False,
- "binary": resolved,
- "version": None,
- "reason": f"manifest check failed: {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 {
- "ready": False,
- "binary": resolved,
- "version": None,
- "reason": detail.splitlines()[-1][:200],
- }
-
+ 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 {
- "ready": False,
- "binary": resolved,
- "version": None,
- "reason": "driver manifest is missing or invalid",
- }
+ return _not_ready("driver manifest is missing or invalid")
raw_version = str(manifest.get("binary_version") or "").strip()
match = re.fullmatch(r"v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?", raw_version)
if not match:
- return {
- "ready": False,
- "binary": resolved,
- "version": raw_version or None,
- "reason": "driver manifest does not report a semantic version",
- }
- version = tuple(int(part) for part in match.groups())
- if version < _CUA_DRIVER_RUNTIME_CONTRACT_MIN:
- return {
- "ready": False,
- "binary": resolved,
- "version": raw_version,
- "reason": "Hermes computer use requires cua-driver 0.20.0 or newer",
- }
+ 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
@@ -1217,12 +527,7 @@ def cua_driver_runtime_contract_status(binary: Optional[str] = None) -> Dict[str
and invocation_args
and all(isinstance(arg, str) for arg in invocation_args)
):
- return {
- "ready": False,
- "binary": resolved,
- "version": raw_version,
- "reason": "driver manifest does not provide an MCP launch command",
- }
+ return _not_ready("driver manifest does not provide an MCP launch command", raw_version)
advertised: Dict[str, set[str]] = {}
for command in manifest.get("subcommands") or []:
@@ -1233,44 +538,27 @@ def cua_driver_runtime_contract_status(binary: Optional[str] = None) -> Dict[str
for arg in command.get("args") or []
if isinstance(arg, dict) and isinstance(arg.get("name"), str)
}
-
- missing = []
- for command, required_args in _CUA_DRIVER_RUNTIME_CONTRACT_ARGS.items():
- for arg in sorted(required_args - advertised.get(command, set())):
- missing.append(f"{command} {arg}")
+ 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 {
- "ready": False,
- "binary": resolved,
- "version": raw_version,
- "reason": "driver manifest is missing: " + ", ".join(missing),
- }
-
- return {
- "ready": True,
- "binary": resolved,
- "version": raw_version,
- "reason": "",
- }
+ return _not_ready("driver manifest is missing: " + ", ".join(missing), raw_version)
+ return {"ready": True, "binary": resolved, "version": raw_version, "reason": ""}
def cua_driver_update_check(*, timeout: Optional[float] = None) -> Optional[Dict[str, Any]]:
- """Run ``cua-driver check-update --json`` and return its parsed state.
-
- The payload mirrors the ``check_for_update`` MCP tool:
- ``{current_version, latest_version, update_available, ...}``.
-
- ``timeout`` defaults to 8s on POSIX and 25s on Windows — first-spawn of
- the exe there routinely eats several seconds in Defender/SmartScreen
- scanning, and a false timeout is expensive: callers treat ``None`` as
- indeterminate, and the ``install_cua_driver(upgrade=True)`` path used to
- fall through to a full multi-minute reinstall on it.
-
- Returns ``None`` (callers should stay quiet) when the result is
- indeterminate: the binary is missing, the driver is too old to support
- the verb (it predates trycua/cua#1734), the GitHub check failed (an
- ``error`` field is set), or the output didn't parse. Best-effort; never
- raises.
+ """Run ``cua-driver check-update --json``; payload mirrors the
+ ``check_for_update`` MCP tool (``{current_version, latest_version,
+ update_available, ...}``).
+
+ ``timeout`` defaults to 8s on POSIX and 25s on Windows (first spawn of the
+ exe routinely eats seconds in Defender scanning, and a false timeout is
+ expensive: callers treat ``None`` as indeterminate and the upgrade path
+ used to fall through to a full reinstall on it). Returns ``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.
"""
if timeout is None:
timeout = 25.0 if sys.platform == "win32" else 8.0
@@ -1278,31 +566,17 @@ def cua_driver_update_check(*, timeout: Optional[float] = None) -> Optional[Dict
if not driver_cmd:
return None
try:
- from tools.environments.local import _sanitize_subprocess_env
- proc = subprocess.run(
- [driver_cmd, "check-update", "--json"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout,
- # Some older drivers don't have the verb and fall through to a
- # stdin-reading mode rather than erroring — DEVNULL gives them EOF
- # so they exit fast instead of blocking until the timeout.
- stdin=subprocess.DEVNULL,
- creationflags=windows_hide_flags(),
- # Sanitized like every other cua-driver spawn: third-party
- # binary, no inherited provider keys (#53503/#55709/#58889).
- env=_sanitize_subprocess_env(cua_driver_child_env()),
- )
+ proc = _run_driver(driver_cmd, "check-update", "--json", timeout=timeout)
except Exception:
return None
out = (proc.stdout or "").strip()
- if not out:
- # Older drivers don't have the verb: usage goes to stderr, stdout empty.
+ if not out: # older drivers: usage goes to stderr, stdout empty
return None
try:
data = json.loads(out)
except (ValueError, TypeError):
return None
if not isinstance(data, dict) or data.get("error"):
- # A failed check (exit 1) carries its reason in `error` — indeterminate.
return None
return data
@@ -1323,32 +597,25 @@ def cua_driver_update_nudge() -> Optional[str]:
_update_checked = False
-# One auto-repair attempt per process. The runtime-contract gate in
-# ``CuaDriverBackend.start()`` fails closed on an incompatible driver; when
-# the incompatibility is something a reinstall fixes (old version, missing
-# manifest verbs) we run the standard install/repair path once instead of
-# telling the user to do it by hand. Guarded so a failing installer can't
-# loop — the second start() in the same process 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 for a failed runtime contract.
-
- Returns the post-repair contract state (or the original state when no
- repair was attempted / the repair failed). Never raises. An explicit
- ``HERMES_CUA_DRIVER_CMD`` override is authoritative even when broken, and
- a missing binary means installation was never requested — both are left
- for the caller's error message.
- """
+ """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"):
- return contract
- if _contract_repair_attempted:
- return contract
- if os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip():
- return contract
- if 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(
@@ -1386,1252 +653,78 @@ def _maybe_nudge_update() -> None:
if msg:
logger.info("computer_use: %s", msg)
- threading.Thread(
- target=_run, name="cua-driver-update-check", daemon=True
- ).start()
+ threading.Thread(target=_run, name="cua-driver-update-check", daemon=True).start()
def cua_driver_install_hint() -> str:
+ scripts = "https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts"
if sys.platform == "win32":
- installer = (
- ' irm https://raw.githubusercontent.com/trycua/cua/main/'
- 'libs/cua-driver/scripts/install.ps1 | iex'
- )
+ installer = f" irm {scripts}/install.ps1 | iex"
else:
- installer = (
- ' /bin/bash -c "$(curl -fsSL '
- 'https://raw.githubusercontent.com/trycua/cua/main/'
- 'libs/cua-driver/scripts/install.sh)"'
- )
+ 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."
- )
-
-
-def _parse_elements_from_tree(markdown: str) -> List[UIElement]:
- """Parse UIElement list from get_window_state AX tree markdown.
-
- Last-resort fallback for cua-driver builds that don't carry the
- canonical ``structuredContent.elements`` array (see
- ``_parse_elements_from_structured`` — Surface 2 of #47072 prefers
- that path).
-
- Captures the label whichever form cua-driver used: ``= "value"``,
- ``"quoted"``, ``(parenthesised)``, or ``id=Label``. Bounds always
- come back ``(0, 0, 0, 0)`` because the markdown surface doesn't
- carry them — yet another reason to prefer the structured path;
- element-index clicks don't need them (the driver resolves the index
- to a frame internally).
- """
- elements = []
- for m in _ELEMENT_LINE_RE.finditer(markdown):
- # groups 3-6: value / quoted / paren / id= label (first non-None wins)
- label = m.group(3) or m.group(4) or m.group(5) or m.group(6) or ""
- elements.append(UIElement(
- index=int(m.group(1)),
- role=m.group(2),
- label=label,
- bounds=(0, 0, 0, 0),
- ))
- return elements
-
-
-def _parse_elements_from_structured(raw_elements: List[Dict[str, Any]]) -> List[UIElement]:
- """Surface 2 of NousResearch/hermes-agent#47072: read the canonical
- ``structuredContent.elements`` array cua-driver-rs emits on every
- ``get_window_state`` response (trycua/cua#1961).
-
- Each entry has at minimum ``element_index``, ``role``, ``label``;
- ``frame`` (``{x, y, w, h}``) is included whenever the AT-SPI /
- AXFrame call returned usable bounds. Older code parsed the same
- information out of the markdown tree via a regex (lossy: bounds
- were always ``(0, 0, 0, 0)``) — this path preserves the real
- frame so downstream consumers (e.g. ``UIElement.center()``) work
- against pixel coordinates instead of just the index lookup.
-
- Unknown / malformed entries are skipped rather than failing the
- whole walk — the wrapper degrades to "fewer elements" rather than
- "no elements" on a bad row.
- """
- elements: List[UIElement] = []
- for raw in raw_elements:
- if not isinstance(raw, dict):
- continue
- idx = raw.get("element_index")
- if not isinstance(idx, int):
- continue
- role = raw.get("role") if isinstance(raw.get("role"), str) else ""
- label = raw.get("label") if isinstance(raw.get("label"), str) else ""
- frame = raw.get("frame") if isinstance(raw.get("frame"), dict) else None
- bounds: Tuple[int, int, int, int] = (0, 0, 0, 0)
- if frame:
- try:
- bounds = (
- int(frame.get("x", 0)),
- int(frame.get("y", 0)),
- int(frame.get("w", 0)),
- int(frame.get("h", 0)),
- )
- except (TypeError, ValueError):
- bounds = (0, 0, 0, 0)
- # Surface 6: opaque element_token. cua-driver-rs format is
- # `s{snapshot_hex}:{index}`. We treat it as a black-box string —
- # the driver owns the parse + LRU semantics.
- raw_token = raw.get("element_token")
- token = raw_token if isinstance(raw_token, str) and raw_token else None
- elements.append(UIElement(
- index=idx,
- role=role,
- label=label,
- bounds=bounds,
- element_token=token,
- ))
- return elements
-
-
-def _image_dimensions_from_bytes(raw: bytes) -> Tuple[int, int]:
- """Best-effort PNG/JPEG dimension sniffing without extra dependencies."""
- if raw.startswith(b"\x89PNG\r\n\x1a\n") and len(raw) >= 24:
- width = int.from_bytes(raw[16:20], "big")
- height = int.from_bytes(raw[20:24], "big")
- if width > 0 and height > 0:
- return width, height
-
- if raw.startswith(b"\xff\xd8"):
- i = 2
- n = len(raw)
- while i + 9 < n:
- if raw[i] != 0xFF:
- i += 1
- continue
- marker = raw[i + 1]
- i += 2
- if marker in {0xD8, 0xD9} or 0xD0 <= marker <= 0xD7:
- continue
- if i + 2 > n:
- break
- segment_len = int.from_bytes(raw[i:i + 2], "big")
- if segment_len < 2 or i + segment_len > n:
- break
- if marker in {
- 0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,
- 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF,
- }:
- if segment_len >= 7:
- height = int.from_bytes(raw[i + 3:i + 5], "big")
- width = int.from_bytes(raw[i + 5:i + 7], "big")
- if width > 0 and height > 0:
- return width, height
- break
- i += segment_len
-
- return 0, 0
-
-
-def _split_tree_text(full_text: str) -> Tuple[str, str]:
- """Split get_window_state text into (summary_line, tree_markdown)."""
- lines = full_text.split("\n", 1)
- summary = lines[0]
- tree = lines[1] if len(lines) > 1 else ""
- return summary, tree
-
-
-def _parse_key_combo(keys: str) -> Tuple[Optional[str], List[str]]:
- """Parse a key string like 'cmd+s' into (key, modifiers).
-
- Returns (key, modifiers) where key is the non-modifier key and modifiers
- is a list of modifier names (cmd, shift, option, ctrl).
- """
- MODIFIER_NAMES = {"cmd", "command", "shift", "option", "alt", "ctrl", "control", "fn"}
- KEY_ALIASES = {"command": "cmd", "alt": "option", "control": "ctrl"}
-
- parts = [p.strip().lower() for p in re.split(r'[+\-]', keys) if p.strip()]
- modifiers = []
- key = None
- for part in parts:
- normalized = KEY_ALIASES.get(part, part)
- if normalized in MODIFIER_NAMES:
- modifiers.append(normalized)
- else:
- key = part # last non-modifier wins
- return key, modifiers
-
-
-# ---------------------------------------------------------------------------
-# Asyncio bridge — one long-lived loop on a background thread
-# ---------------------------------------------------------------------------
-
-class _AsyncBridge:
- """Runs one asyncio loop on a daemon thread; marshals coroutines from the caller."""
-
- def __init__(self) -> None:
- self._loop: Optional[asyncio.AbstractEventLoop] = None
- self._thread: Optional[threading.Thread] = None
- self._ready = threading.Event()
-
- def start(self) -> None:
- if self._thread and self._thread.is_alive():
- return
- self._ready.clear()
-
- def _run() -> None:
- self._loop = asyncio.new_event_loop()
- asyncio.set_event_loop(self._loop)
- self._ready.set()
- try:
- self._loop.run_forever()
- finally:
- try:
- self._loop.close()
- except Exception:
- pass
-
- self._thread = threading.Thread(target=_run, daemon=True, name="cua-driver-loop")
- self._thread.start()
- if not self._ready.wait(timeout=5.0):
- raise RuntimeError("cua-driver asyncio bridge failed to start")
-
- def run(self, coro, timeout: Optional[float] = 30.0) -> Any:
- from agent.async_utils import safe_schedule_threadsafe
- if not self._loop or not self._thread or not self._thread.is_alive():
- if asyncio.iscoroutine(coro):
- coro.close()
- raise RuntimeError("cua-driver bridge not started")
- fut = safe_schedule_threadsafe(coro, self._loop)
- if fut is None:
- raise RuntimeError("cua-driver bridge not started")
- return fut.result(timeout=timeout)
-
- def stop(self) -> None:
- if self._loop and self._loop.is_running():
- self._loop.call_soon_threadsafe(self._loop.stop)
- if self._thread:
- self._thread.join(timeout=2.0)
- self._thread = None
- self._loop = None
-
-
-# ---------------------------------------------------------------------------
-# MCP session (lazy, shared across tool calls)
-# ---------------------------------------------------------------------------
-
-class _CuaDriverSession:
- """Holds the mcp ClientSession. Spawned lazily; re-entered on drop.
-
- Lifecycle ownership: a single long-running coroutine
- (`_lifecycle_coro`) opens both the stdio_client and ClientSession
- contexts, populates capabilities, sets `_ready_event`, and then waits
- on `_shutdown_event`. When shutdown is signalled the same coroutine
- closes the contexts — keeping anyio's cancel-scope task-identity
- invariant intact (the bridge schedules each `bridge.run(coro)` as a
- NEW task, so opening contexts in one and closing them in another
- raises "Attempted to exit cancel scope in a different task").
- Tool calls run in their own short-lived tasks; they only touch the
- session object, never the surrounding contexts.
- """
-
- def __init__(
- self,
- bridge: _AsyncBridge,
- embedded_daemon: Optional[_EmbeddedCuaDaemon] = None,
- ) -> None:
- self._bridge = bridge
- self._embedded_daemon = embedded_daemon
- self._session = None
- self._lock = threading.Lock()
- self._started = False
- # Surface 4 of NousResearch/hermes-agent#47072: per-tool
- # capability-token sets, populated from `tools/list` at session
- # init. Keys are tool names (e.g. "click", "get_window_state");
- # values are sets of capability strings (e.g.
- # "accessibility.element_tokens", "input.keyboard.type.terminal_safe").
- # Empty until the session starts; consumers should call
- # `supports_capability` rather than reading directly.
- self._capabilities: Dict[str, set] = {}
- # Raw input schemas are the compatibility source of truth for action
- # properties. cua-driver 0.9-era builds advertise delivery_mode in
- # inputSchema while intentionally omitting the old, fabricated
- # ``input.delivery_mode`` capability token.
- self._tool_schemas: Dict[str, Dict[str, Any]] = {}
- self._capability_version: str = ""
- # Lifecycle plumbing — see class docstring above.
- self._ready_event = threading.Event()
- self._shutdown_event: Optional[asyncio.Event] = None # created on bridge loop
- self._lifecycle_future = None # concurrent.futures.Future
- self._setup_error: Optional[BaseException] = None
- # Stable driver-side identity declared through start_session.
- # Used to revive a logical ended-session rejection without
- # recursive call_tool re-entry or backend-owned state (#71166).
- self._declared_session_id: Optional[str] = None
- self._transport_generation = 0
- self._transport_reset_callback: Optional[Any] = None
-
- def _require_started(self) -> None:
- if not self._started:
- raise RuntimeError("cua-driver session not started")
-
- async def _lifecycle_coro(self) -> None:
- """Long-lived owner of the stdio MCP contexts. Opens, signals
- ready, blocks on shutdown, then cleans up. enter + exit happen
- in the SAME asyncio task, so anyio's cancel-scope invariant
- holds — fixing the "Attempted to exit cancel scope in a
- different task than it was entered in" warning emitted by the
- previous _aenter/_aexit split.
- """
- import time as _time
- from mcp import ClientSession, StdioServerParameters
- from mcp.client.stdio import stdio_client
- from tools.environments.local import _sanitize_subprocess_env
-
- # Build the shutdown event on the loop's thread so the asyncio
- # primitive belongs to the correct loop.
- self._shutdown_event = asyncio.Event()
- _t0 = _time.monotonic()
- # Phase marker surfaced by the ready-timeout error (issue #57025):
- # when startup wedges, the caller reports HOW FAR it got instead of
- # an opaque "never reached ready".
- self._startup_phase = "binary-check"
-
- try:
- driver_cmd = resolve_cua_driver_cmd()
- if not driver_cmd:
- raise RuntimeError(cua_driver_install_hint())
-
- # Surface 8: ask cua-driver itself which subcommand spawns
- # the MCP server, instead of hardcoding ["mcp"]. Falls back
- # transparently for older drivers / any discovery failure.
- self._startup_phase = "manifest-discovery"
- if self._embedded_daemon is not None:
- command, args = self._embedded_daemon.proxy_invocation()
- child_env = self._embedded_daemon.child_env()
- else:
- command, args = _resolve_mcp_invocation(driver_cmd)
- child_env = cua_driver_child_env()
- _t_manifest = _time.monotonic()
- params = StdioServerParameters(
- command=command,
- args=args,
- # Apply the telemetry policy first (default: disabled), then
- # sanitize Hermes-managed secrets out of the child env.
- env=_sanitize_subprocess_env(child_env),
- )
-
- async with stdio_client(params) as (read, write):
- self._startup_phase = "mcp-initialize"
- async with ClientSession(read, write) as session:
- await session.initialize()
- _t_init = _time.monotonic()
- # Populate capabilities + capability_version BEFORE
- # exposing the session to callers, so the first
- # tool call already sees them.
- self._startup_phase = "capability-discovery"
- await self._populate_capabilities(session)
- self._session = session
- self._startup_phase = "ready"
- self._ready_event.set()
- logger.info(
- "cua-driver session ready in %.1fs "
- "(manifest=%.1fs, mcp_init=%.1fs)",
- _time.monotonic() - _t0,
- _t_manifest - _t0,
- _t_init - _t_manifest,
- )
- # Hold the contexts open until stop() / restart asks
- # us to wind down. Tool calls run as their own tasks
- # on the same loop and touch self._session directly.
- await self._shutdown_event.wait()
- except BaseException as e:
- # Capture both ordinary errors and anyio CancelledError.
- # The caller (start()) inspects this to surface setup
- # failures to the synchronous world.
- self._setup_error = e
- self._ready_event.set()
- raise
- finally:
- # Clearing _session before the contexts unwind would let a
- # racing call_tool see None during teardown — but the
- # outer context-manager exits AFTER this block, so set to
- # None here is fine: stop() has already flipped _started.
- self._session = None
- # Reset _started so a session that dies for ANY reason (MCP
- # connection drop, driver crash, unexpected coro exit) is
- # re-enterable: the next start()/call sees _started False and
- # rebuilds the session instead of hanging forever on a dead one
- # via _require_started(). On the normal stop() path this is a
- # harmless idempotent no-op (stop() already set it False). A
- # plain bool write is atomic in CPython, so this is safe from
- # the bridge-loop thread without taking self._lock (which stop()
- # may hold while awaiting this coro's future). See #55048 Bug 1.
- self._started = False
-
- async def _populate_capabilities(self, session: Any) -> None:
- """Surface 4: cache per-tool capability sets + capability_version
- from tools/list. Soft prerequisite — discovery failure leaves
- the map empty and supports_capability degrades to False."""
- self._capabilities = {}
- self._tool_schemas = {}
- self._capability_version = ""
- try:
- tools_list = await session.list_tools()
- for tool in getattr(tools_list, "tools", []) or []:
- tool_name = getattr(tool, "name", None)
- if not isinstance(tool_name, str):
- continue
- caps = getattr(tool, "capabilities", None)
- if caps is None:
- # Some MCP SDKs forward custom fields via
- # `model_extra` (Pydantic v2) instead of attributes.
- extra = getattr(tool, "model_extra", None) or {}
- caps = extra.get("capabilities")
- if isinstance(caps, list):
- self._capabilities[tool_name] = {
- c for c in caps if isinstance(c, str)
- }
- else:
- self._capabilities[tool_name] = set()
- schema = _mcp_field(tool, "input_schema", "inputSchema")
- if schema is None:
- schema = (getattr(tool, "model_extra", None) or {}).get(
- "inputSchema"
- )
- self._tool_schemas[tool_name] = (
- dict(schema) if isinstance(schema, dict) else {}
- )
- # capability_version is a top-level sibling of `tools` on the
- # tools/list response. cua-driver-core/src/tool.rs:354 emits
- # it; cua-driver-core/src/protocol.rs:150 leaves it OUT of
- # initialize — so we discover here, not there.
- cv = getattr(tools_list, "capability_version", None)
- if cv is None:
- extra = getattr(tools_list, "model_extra", None) or {}
- cv = extra.get("capability_version")
- if isinstance(cv, str):
- self._capability_version = cv
- except Exception as e:
- logger.debug("cua-driver tools/list capability discovery failed: %s", e)
-
- def start(self) -> None:
- with self._lock:
- if self._started:
- return
- self._bridge.start()
- self._start_lifecycle_locked()
- self._started = True
-
- def _start_lifecycle_locked(self) -> None:
- """Spawn the lifecycle owner and wait for it to reach ready.
- Caller must hold self._lock."""
- # Reset per-session state.
- self._ready_event = threading.Event()
- self._setup_error = None
- self._shutdown_event = None
- # Fire-and-forget schedule on the bridge loop. The future tracks
- # completion of the WHOLE lifecycle (open → wait → close), not
- # just the open step — start() waits on _ready_event separately.
- loop = self._bridge._loop
- if loop is None:
- raise RuntimeError("cua-driver bridge not started")
- self._lifecycle_future = asyncio.run_coroutine_threadsafe(
- self._lifecycle_coro(), loop
- )
- if not self._ready_event.wait(timeout=30.0):
- # Best-effort: signal shutdown if the future is still alive.
- self._signal_shutdown_locked()
- # Surface which startup phase wedged (issue #57025) — "doctor
- # passes but the wrapper times out" reports are undiagnosable
- # from a bare "never reached ready".
- phase = getattr(self, "_startup_phase", "unknown")
- from hermes_constants import display_hermes_home
- raise RuntimeError(
- "cua-driver session never reached ready (timeout 30s; "
- f"stuck in phase: {phase}). "
- "Run `hermes computer-use doctor` and check "
- f"{display_hermes_home()}/logs/agent.log for the phase timings."
- )
- # If setup failed, the lifecycle coroutine set _setup_error
- # before setting _ready_event. Re-raise it on the caller's thread.
- if self._setup_error is not None:
- raise RuntimeError(
- f"cua-driver session setup failed: {self._setup_error}"
- ) from self._setup_error
- self._transport_generation += 1
- if self._transport_generation > 1:
- self._notify_transport_reset()
-
- def stop(self) -> None:
- with self._lock:
- if not self._started:
- return
- self._started = False
- self._stop_lifecycle_locked()
-
- def set_transport_reset_callback(self, callback: Any) -> None:
- """Register a synchronous cache invalidation hook for transport swaps."""
- self._transport_reset_callback = callback
-
- def _notify_transport_reset(self) -> None:
- callback = getattr(self, "_transport_reset_callback", None)
- if callback is None:
- return
- try:
- callback()
- except Exception as exc:
- logger.debug("cua-driver transport reset callback failed: %s", exc)
-
- def _stop_lifecycle_locked(self) -> None:
- """Signal shutdown + wait for the lifecycle coroutine to unwind.
- Caller must hold self._lock."""
- self._signal_shutdown_locked()
- fut = self._lifecycle_future
- if fut is None:
- return
- try:
- # 5s budget for context unwind (stdio_client teardown).
- fut.result(timeout=5.0)
- except concurrent.futures.TimeoutError:
- logger.warning("cua-driver session shutdown timed out (5s)")
- except Exception as e:
- # Real shutdown errors (not the previous cancel-scope race
- # which is now structurally impossible) still get surfaced.
- logger.warning("cua-driver shutdown error: %s", e)
- finally:
- self._lifecycle_future = None
-
- def _signal_shutdown_locked(self) -> None:
- """Set the asyncio shutdown event from the caller's thread."""
- loop = self._bridge._loop
- event = self._shutdown_event
- if loop is not None and event is not None and loop.is_running():
- try:
- loop.call_soon_threadsafe(event.set)
- except RuntimeError:
- # Loop closed — nothing to signal.
- pass
-
- async def _call_tool_async(self, name: str, args: Dict[str, Any]) -> Dict[str, Any]:
- result = await self._session.call_tool(name, args)
- return _extract_tool_result(result)
-
- # ── Capability detection (Surface 4 of #47072) ────────────────────
- def supports_capability(self, capability: str, tool: Optional[str] = None) -> bool:
- """Return True when the connected cua-driver advertises the given
- capability token (trycua/cua#1961 capability vocabulary).
-
- When ``tool`` is given, scope the check to that specific tool's
- advertised capability set. When omitted, return True if ANY tool
- advertises the capability — useful for "is this feature available
- anywhere on the driver" probes.
-
- Always returns False before the session is started (so consumers
- on a dead/uninitialised wrapper degrade rather than crash).
- """
- if tool is not None:
- return capability in self._capabilities.get(tool, set())
- return any(capability in caps for caps in self._capabilities.values())
-
- def _has_tool(self, name: str) -> bool:
- """Return True when ``tools/list`` advertised a tool by this name.
-
- Used to route capture(): cua-driver dropped the standalone
- ``screenshot`` tool and folded full-window PNG capture into
- ``get_window_state`` (whose own description notes it "Also captures
- a PNG screenshot of the specified window"). Older drivers that still
- expose ``screenshot`` keep using it; newer ones fall through to
- ``get_window_state``.
-
- Returns False when discovery hasn't populated the map yet — callers
- treat that as "unknown" and probe defensively rather than trusting it.
- """
- return name in self._capabilities
-
- def supports_input_property(self, tool: str, property_name: str) -> bool:
- """Return whether a live action schema accepts ``property_name``.
-
- This deliberately inspects tools/list rather than guessing from the
- package version or requiring a capability token the driver never
- shipped. A missing/invalid schema fails closed.
- """
- schema = getattr(self, "_tool_schemas", {}).get(tool, {})
- properties = schema.get("properties") if isinstance(schema, dict) else None
- return isinstance(properties, dict) and property_name in properties
-
- @property
- def capabilities_discovered(self) -> bool:
- """True once ``tools/list`` populated the per-tool map. When False,
- ``_has_tool`` answers are not trustworthy (discovery failed or the
- session hasn't started) and capture() should probe defensively."""
- return bool(self._capabilities)
-
- @property
- def capability_version(self) -> str:
- """Driver-advertised capability vocabulary version (empty string
- when the driver predates the field — older builds had no version)."""
- return self._capability_version
-
- @staticmethod
- def _logical_error_text(result: Dict[str, Any]) -> str:
- """Flatten a logical MCP error into text for narrow classification."""
- chunks: List[str] = []
- for value in (result.get("data"), result.get("structuredContent")):
- if isinstance(value, str):
- chunks.append(value)
- elif value is not None:
- try:
- chunks.append(json.dumps(value, sort_keys=True))
- except (TypeError, ValueError):
- chunks.append(str(value))
- return "\n".join(chunks)
-
- @classmethod
- def _is_ended_session_result(cls, result: Any) -> bool:
- """Recognise cua-driver's explicit recoverable ended-session result."""
- if not isinstance(result, dict) or result.get("isError") is not True:
- return False
- message = cls._logical_error_text(result).lower()
- return (
- "session" in message
- and ("has ended" in message or "session ended" in message)
- and "start_session" in message
- )
-
- def _revive_declared_session_once(
- self,
- name: str,
- args: Dict[str, Any],
- first_result: Dict[str, Any],
- timeout: float,
- ) -> Dict[str, Any]:
- """Revive the stable session and replay one rejected tool call once."""
- session_id = self._declared_session_id
- if not session_id or name in self._LIFECYCLE_CALLS:
- return first_result
-
- logger.warning(
- "cua-driver session %s ended during %s; reviving and retrying once",
- session_id,
- name,
- )
- revive_result = self._bridge.run(
- self._call_tool_async("start_session", {"session": session_id}),
- timeout=timeout,
- )
- if revive_result.get("isError") is True:
- logger.warning(
- "cua-driver session %s could not be revived: %s",
- session_id,
- self._logical_error_text(revive_result),
- )
- return first_result
-
- # Return the second result as-is. A second rejection is surfaced; no loop.
- return self._bridge.run(
- self._call_tool_async(name, args),
- timeout=timeout,
- )
-
- def _restore_declared_session_after_transport_reset(self, timeout: float) -> None:
- """Re-attach the public label inside a replacement private lifecycle."""
- session_id = getattr(self, "_declared_session_id", None)
- if not session_id:
- return
- result = self._bridge.run(
- self._call_tool_async("start_session", {"session": session_id}),
- timeout=timeout,
- )
- if result.get("isError") is True:
- logger.warning(
- "cua-driver public session label %s could not be restored: %s",
- session_id,
- self._logical_error_text(result),
- )
-
- @staticmethod
- def _is_closed_session_error(exc: Exception) -> bool:
- """Return True for MCP/stdio failures that are recoverable by reconnecting."""
- name = exc.__class__.__name__
- module = getattr(exc.__class__, "__module__", "")
- return (
- name in {"ClosedResourceError", "BrokenResourceError", "EndOfStream"}
- or (module.startswith("anyio") and "Resource" in name)
- or isinstance(exc, (BrokenPipeError, EOFError))
- )
-
- @staticmethod
- def _is_transient_daemon_error(exc: Exception) -> bool:
- """Return True for the cua-driver daemon-proxy EAGAIN congestion error.
-
- On macOS the ``cua-driver mcp`` bridge forwards calls to the CuaDriver
- daemon over a non-blocking unix socket. Heavier ops (notably
- ``get_window_state``, which walks the AX tree and captures a PNG) can
- come back as an ``MCPError`` carrying ``Resource temporarily
- unavailable (os error 35)`` — POSIX EAGAIN — when the socket buffer is
- momentarily full. This is transient by definition: the same call
- succeeds when retried after a short pause (which is why spaced-out
- single calls work while rapid/large ones intermittently fail). Detect
- it by message so we can retry with backoff rather than surfacing an
- empty 0x0 capture to the model. See the EAGAIN diagnosis in
- references/catalog-add-troubleshooting (apple-music skill) and the
- cua-driver daemon-proxy note.
- """
- msg = str(exc)
- return (
- "Resource temporarily unavailable" in msg
- or "os error 35" in msg
- or "daemon transport error" in msg
- or "daemon proxy" in msg
- )
-
- def _restart_session_locked(self) -> None:
- """Recreate the MCP session after the daemon/stdin transport was closed.
- Caller must hold self._lock (the reconnect-once retry path holds it)."""
- if self._started:
- try:
- self._stop_lifecycle_locked()
- except Exception as e:
- logger.debug("cua-driver session cleanup before reconnect failed: %s", e)
- self._started = False
- # Clear stale capability state; the next start populates from scratch.
- self._capabilities = {}
- self._tool_schemas = {}
- self._capability_version = ""
- self._start_lifecycle_locked()
- self._started = True
-
- def _call_tool_via_cli(self, name: str, args: Dict[str, Any], timeout: float) -> Dict[str, Any]:
- """Fallback transport: invoke ``cua-driver call <tool> <json>`` as a
- subprocess instead of going through the stdio MCP bridge.
-
- The ``cua-driver mcp`` stdio bridge can persistently fail to forward
- heavier calls (notably ``get_window_state``) to the daemon with POSIX
- EAGAIN, while the plain ``cua-driver call`` path — which talks to the
- daemon over its own socket — keeps working. When the MCP path gives up,
- we retry over the CLI and remap the JSON into the same dict shape that
- ``_extract_tool_result`` produces, so callers (capture(), _action(),
- list_windows parsing) are transport-agnostic.
-
- For ``get_window_state`` we route the screenshot to a temp file via
- ``screenshot_out_file`` so the daemon returns a tiny JSON body (a path)
- instead of a multi-megabyte base64 blob — the large payload is what
- congests the daemon socket and triggers EAGAIN in the first place. We
- read the PNG back from disk and base64-encode it ourselves. The CLI
- call is itself retried a few times with backoff, since the underlying
- daemon socket can still be momentarily busy.
- """
- import subprocess as _subprocess
- import tempfile as _tempfile
- import time as _time
- from tools.environments.local import _sanitize_subprocess_env
-
- call_args = dict(args)
- shot_file: Optional[str] = None
- if name == "get_window_state" and "screenshot_out_file" not in call_args:
- fd, shot_file = _tempfile.mkstemp(prefix="cua_shot_", suffix=".png")
- os.close(fd)
- call_args["screenshot_out_file"] = shot_file
-
- driver_command = resolve_cua_driver_cmd()
- if not driver_command:
- raise RuntimeError(cua_driver_install_hint())
- child_env = cua_driver_child_env()
- socket_args: List[str] = []
- embedded_daemon = getattr(self, "_embedded_daemon", None)
- if embedded_daemon is not None:
- driver_command = embedded_daemon.proxy_invocation()[0]
- child_env = embedded_daemon.child_env()
- socket_args = ["--socket", embedded_daemon.socket_path]
- cmd = [
- driver_command,
- "call",
- name,
- json.dumps(call_args),
- *socket_args,
- ]
- attempts = 4
- backoff = 0.5
- parsed: Any = None
- last_err = ""
- try:
- for attempt in range(attempts):
- try:
- proc = _subprocess.run(
- cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=max(15.0, timeout),
- creationflags=windows_hide_flags(),
- env=_sanitize_subprocess_env(child_env),
- )
- except Exception as e: # pragma: no cover - subprocess spawn failure
- raise RuntimeError(f"cua-driver CLI fallback for {name} failed to spawn: {e}") from e
-
- out = (proc.stdout or "").strip()
- last_err = out[:200] or (proc.stderr or "")[:200]
- # "daemon is not running" is a PERMANENT condition for this
- # invocation (`cua-driver call` requires the machine-wide
- # daemon socket, which Linux installs typically never start —
- # Hermes talks to the direct `cua-driver mcp` runtime
- # instead). Retrying with backoff burns ~3.5s of sleeps per
- # fallback for an outcome that cannot change; fail fast so
- # callers surface a diagnosable error immediately.
- if "daemon is not running" in out or "daemon is not running" in (proc.stderr or ""):
- raise RuntimeError(
- f"cua-driver CLI fallback for {name} unavailable: the "
- "machine-wide cua-driver daemon is not running (the "
- "CLI transport requires it; the MCP runtime does not)."
- )
- start = min(
- (i for i in (out.find("{"), out.find("[")) if i != -1),
- default=-1,
- )
- if start != -1:
- try:
- candidate = json.loads(out[start:])
- except json.JSONDecodeError:
- candidate = None
- if candidate is not None:
- parsed = candidate
- break
- # No JSON (EAGAIN warning / empty) — retry with backoff.
- if attempt < attempts - 1:
- logger.warning(
- "cua-driver CLI fallback for %s got no JSON "
- "(attempt %d/%d); retrying in %.1fs",
- name, attempt + 1, attempts, backoff,
- )
- _time.sleep(backoff)
- backoff *= 2
-
- if parsed is None:
- raise RuntimeError(
- f"cua-driver CLI fallback for {name} returned no JSON after "
- f"{attempts} attempts: {last_err}"
- )
-
- # Remap structured JSON into {data, images, structuredContent, isError}.
- images: List[str] = []
- data: Any = None
- structured: Optional[Dict] = parsed if isinstance(parsed, dict) else None
- is_error = False
- if isinstance(parsed, dict):
- # Current cua-driver CLI responses may report logical failures
- # in-band even when the subprocess itself exits successfully.
- # Preserve that bit so stateful callers can fail closed.
- is_error = parsed.get("isError") is True or parsed.get("is_error") is True
- shot = parsed.get("screenshot_png_b64")
- if not shot:
- # Screenshot was routed to a file (ours or the daemon's choice).
- fpath = parsed.get("screenshot_file_path") or shot_file
- if fpath and os.path.exists(fpath):
- try:
- with open(fpath, "rb") as fh:
- shot = base64.b64encode(fh.read()).decode("ascii")
- except Exception as e:
- logger.debug("cua-driver CLI fallback: failed reading %s: %s", fpath, e)
- if shot:
- images.append(shot)
- tree = parsed.get("tree_markdown")
- if tree is not None:
- ec = parsed.get("element_count")
- summary = f"{ec} elements" if ec is not None else ""
- data = f"{summary}\n{tree}" if summary else tree
- return {
- "data": data,
- "images": images,
- "structuredContent": structured,
- "isError": is_error,
- }
- finally:
- if shot_file and os.path.exists(shot_file):
- try:
- os.remove(shot_file)
- except OSError:
- pass
-
- # Lifecycle handshake calls issued BY start()/stop() themselves — these
- # must not trigger the auto-restart guard below, or start() would recurse
- # into start() when the session-start hasn't flipped _started yet.
- _LIFECYCLE_CALLS = frozenset({"start_session", "end_session"})
-
- # Retrying these calls after a broken transport is safe. The first call
- # either had no side effect or is explicitly idempotent. Mutations stay
- # out of this set because a lost response does not prove they failed.
- _TRANSPORT_REPLAY_SAFE_TOOLS = frozenset({
- "get_cursor_position",
- "get_displays",
- "get_screen_size",
- "get_window_state",
- "list_apps",
- "list_windows",
- })
-
- # Set when an MCP call timed out (#74799): a timed-out session is
- # wedged for all later calls, so it is torn down and recreated before
- # the next non-lifecycle call_tool. Class-level default so tests that
- # bypass __init__ see a healthy (non-suspect) session.
- _timeout_suspect = False
-
- @classmethod
- def _transport_replay_is_safe(cls, name: str) -> bool:
- return name in cls._TRANSPORT_REPLAY_SAFE_TOOLS
-
- @staticmethod
- def _unknown_transport_outcome(name: str, exc: Exception) -> Dict[str, Any]:
- message = (
- f"cua-driver transport failed during {name}; the action outcome is "
- "unknown, so Hermes did not replay it. Take fresh state before "
- "deciding whether to act again."
- )
- return {
- "data": message,
- "images": [],
- "image_mime_types": [],
- "structuredContent": {
- "ok": False,
- "code": "transport_outcome_unknown",
- "message": message,
- "operation": name,
- "next_step": "fresh_state",
- "detail": str(exc),
- },
- "isError": True,
- }
-
- @staticmethod
- def _timeout_outcome(name: str, exc: Exception) -> Dict[str, Any]:
- """Fail-closed result for an MCP call that hit its deadline (#74799).
-
- The action MAY have taken effect on the remote screen before the
- response was lost — the same effect_disposition=unknown principle as
- ``_unknown_transport_outcome`` — so the timed-out call is never
- silently replayed here; the caller decides after taking fresh state.
- """
- message = (
- f"cua-driver MCP call {name} timed out; the action outcome is "
- "unknown and may still have taken effect on the remote screen. "
- "The session has been marked suspect and will be recreated before "
- "the next computer-use call. Take fresh state before deciding "
- "whether to act again."
- )
- return {
- "data": message,
- "images": [],
- "image_mime_types": [],
- "structuredContent": {
- "ok": False,
- "code": "timeout_outcome_unknown",
- "message": message,
- "operation": name,
- "next_step": "fresh_state",
- "detail": str(exc),
- },
- "isError": True,
- }
-
- def call_tool(self, name: str, args: Dict[str, Any], timeout: float = 30.0) -> Dict[str, Any]:
- # A prior MCP timeout (#74799) marks the session suspect: it may be
- # wedged for every later call. Recreate it before this call so a
- # single timeout never poisons the rest of the computer-use session.
- # Healthy sessions (flag clear) are never restarted here.
- if self._timeout_suspect and name not in self._LIFECYCLE_CALLS:
- logger.warning(
- "cua-driver session suspect after earlier MCP timeout; "
- "recreating before %s",
- name,
- )
- with self._lock:
- self._restart_session_locked()
- self._timeout_suspect = False
- self._restore_declared_session_after_transport_reset(timeout)
-
- # A prior session may have died (MCP drop / driver crash): its
- # lifecycle coro reset _started to False in its finally (#55048).
- if not self._started and name not in self._LIFECYCLE_CALLS:
- logger.warning(
- "cua-driver session not active on %s; (re)starting before call", name
- )
- self.start()
- self._restore_declared_session_after_transport_reset(timeout)
- self._require_started()
-
- try:
- result = self._bridge.run(
- self._call_tool_async(name, args),
- timeout=timeout,
- )
- except Exception as e:
- if isinstance(e, concurrent.futures.TimeoutError):
- # MCP deadline hit (#74799): the session is suspect and must
- # be recreated before the next call. Fail closed — the action
- # may have taken effect on the remote screen, so never replay
- # it here; surface the uncertainty instead (#74799).
- self._timeout_suspect = True
- logger.warning(
- "cua-driver MCP timed out on %s; marking session suspect "
- "for recreation before the next call",
- name,
- )
- return self._timeout_outcome(name, e)
- if self._is_transient_daemon_error(e):
- if not self._transport_replay_is_safe(name):
- self._notify_transport_reset()
- return self._unknown_transport_outcome(name, e)
- logger.warning(
- "cua-driver MCP transport failed on %s (%s); "
- "falling back to CLI transport", name, e,
- )
- return self._call_tool_via_cli(name, args, timeout)
- if not self._is_closed_session_error(e):
- raise
- logger.warning("cua-driver MCP session closed during %s; reconnecting once", name)
- with self._lock:
- self._restart_session_locked()
- self._restore_declared_session_after_transport_reset(timeout)
- if not self._transport_replay_is_safe(name):
- return self._unknown_transport_outcome(name, e)
- result = self._bridge.run(
- self._call_tool_async(name, args),
- timeout=timeout,
- )
-
- # Remember only a successfully declared stable identity. Failed
- # start_session calls must not leave stale recovery state behind.
- if name == "start_session" and result.get("isError") is not True:
- declared_id = args.get("session")
- if isinstance(declared_id, str) and declared_id:
- self._declared_session_id = declared_id
-
- if self._is_ended_session_result(result):
- result = self._revive_declared_session_once(name, args, result, timeout)
-
- if (
- name == "end_session"
- and result.get("isError") is not True
- and args.get("session") == self._declared_session_id
- ):
- self._declared_session_id = None
- return result
-
-
-def _extract_tool_result(mcp_result: Any) -> Dict[str, Any]:
- """Convert an mcp CallToolResult into a plain dict.
-
- cua-driver returns a mix of text parts, image parts, and structuredContent.
- We flatten into:
- {
- "data": <text or parsed json>,
- "images": [b64, ...],
- "image_mime_types": [mime, ...], # parallel to `images`, "" when absent
- "structuredContent": <dict|None>,
- "isError": bool,
- }
- structuredContent is populated from the MCP result's structuredContent field
- (MCP spec §2024-11-05+) and takes precedence for structured data like
- list_windows window arrays.
-
- `image_mime_types` is the explicit `mimeType` cua-driver emits on every
- image part as of trycua/cua#1961 (Surface 7 of
- NousResearch/hermes-agent#47072). Each entry corresponds index-for-index
- with `images`; an empty string entry signals the part carried no
- mimeType (older cua-driver build), and the caller should fall back to
- base64-prefix sniffing.
- """
- data: Any = None
- images: List[str] = []
- image_mime_types: List[str] = []
- # Use identity, not truthiness: unittest mocks and proxy objects commonly
- # synthesize truthy attributes that were never present in the real result.
- is_error = _mcp_field(mcp_result, "is_error", "isError", False) is True
- structured: Optional[Dict] = (
- _mcp_field(mcp_result, "structured_content", "structuredContent") or None
- )
- text_chunks: List[str] = []
- for part in getattr(mcp_result, "content", []) or []:
- ptype = getattr(part, "type", None)
- if ptype == "text":
- text_chunks.append(getattr(part, "text", "") or "")
- elif ptype == "image":
- b64 = getattr(part, "data", None)
- if b64:
- images.append(b64)
- mime = _mcp_field(part, "mime_type", "mimeType") or ""
- image_mime_types.append(mime)
- if text_chunks:
- joined = "\n".join(t for t in text_chunks if t)
- try:
- data = json.loads(joined) if joined.strip().startswith(("{", "[")) else joined
- except json.JSONDecodeError:
- data = joined
- return {
- "data": data,
- "images": images,
- "image_mime_types": image_mime_types,
- "structuredContent": structured,
- "isError": is_error,
- }
-
-
-def _image_from_tool_result(out: Dict[str, Any]) -> tuple[Optional[str], Optional[str]]:
- """Pull a (png_b64, mime_type) pair out of a flattened tool result.
-
- cua-driver delivers window screenshots in two shapes depending on tool +
- transport:
-
- * As an MCP ``image`` content part — surfaced by ``_extract_tool_result``
- in ``out["images"]`` with a parallel ``image_mime_types`` entry. This
- is what ``get_window_state`` emits over the stdio MCP transport.
- * As a base64 field inside ``structuredContent`` —
- ``screenshot_png_b64`` (+ ``screenshot_mime_type``). This is what
- ``get_window_state`` returns when its structured payload carries the
- image instead of a content part (newer driver builds; also the shape
- seen via the ``cua-driver call`` CLI surface).
-
- Checking both makes capture() robust to either delivery shape, so the
- image never silently drops just because the driver moved it between the
- content list and structuredContent. Returns ``(None, None)`` when neither
- location carries an image.
- """
- images = out.get("images") or []
- if images and images[0]:
- mimes = out.get("image_mime_types") or []
- mime = mimes[0] if mimes and mimes[0] else None
- return images[0], mime
-
- structured = out.get("structuredContent") or {}
- b64 = structured.get("screenshot_png_b64") or structured.get("png_b64")
- if b64:
- mime = (
- structured.get("screenshot_mime_type")
- or structured.get("mime_type")
- or None
- )
- return b64, mime
-
- return None, None
-
-
-def _positive_int(value: Any) -> Optional[int]:
- """Return a positive integer, rejecting booleans and malformed values."""
- if isinstance(value, bool) or not isinstance(value, (int, str)):
- return None
- try:
- parsed = int(value)
- except ValueError:
- return None
- return parsed if parsed > 0 else None
+ )
-def _is_placeholder_id(value: Any) -> bool:
- """True when *value* is a schema-filler id rather than a real target.
+# ---------------------------------------------------------------------------
+# Capture helpers
+# ---------------------------------------------------------------------------
- Several providers emit every declared schema property on every tool call,
- filling unused optional integers with ``0``. A non-positive id cannot name
- a window, so treating it as a targeting request drops the caller's ``app=``
- and fails the capture. Malformed non-numeric values are deliberately NOT
- placeholders: those still reach the existing validation error rather than
- being silently ignored.
- """
- if isinstance(value, bool) or not isinstance(value, (int, str)):
+def _gws_is_empty(out: Dict[str, Any]) -> bool:
+ """True when a get_window_state result carries neither a screenshot nor a
+ parseable tree. Modern drivers put the payload in structuredContent with
+ no markdown tree — that is NOT empty."""
+ if out.get("images"):
return False
- try:
- return int(value) <= 0
- except ValueError:
+ sc_ = out.get("structuredContent") or {}
+ if sc_.get("elements") or sc_.get("screenshot_png_b64"):
return False
+ txt = out.get("data") if isinstance(out.get("data"), str) else ""
+ _, tr = _split_tree_text(txt or "")
+ return not (tr and tr.strip())
-def _ingest_windows(raw_windows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """Normalise cua-driver ``list_windows`` entries, dropping unusable ones.
+def _tree_text(out: Dict[str, Any]) -> str:
+ return out["data"] if isinstance(out["data"], str) else ""
- Every downstream operation needs both an integer ``pid`` (for
- get_window_state / action tools) and ``window_id`` (for screenshot /
- element clicks), so a window missing either is uncapturable.
- Crucially, on X11 a window's PID comes from the *optional*
- ``_NET_WM_PID`` property — the desktop root, panels, and
- override-redirect popups routinely omit it, so the driver reports
- ``pid: null`` for them. Coercing every entry unconditionally
- (``int(w["pid"])``) let one such window abort enumeration of the real,
- targetable windows. We skip the unusable entries instead so capture()
- and focus_app() still find the windows that matter.
+def _window_title_from_tree(tree: str) -> str:
+ wt = _WINDOW_TITLE_RE.search(tree)
+ return wt.group(1) if wt else ""
- ``z_index`` follows CUA Driver semantics: higher = closer to front.
- Wayland may return ``z_index: null`` (undefined stacking order); we
- treat null as the lowest priority so real windows still sort above
- desktop/root windows, and the backmost never ends up selected as the
- capture target.
- """
- windows: List[Dict[str, Any]] = []
- for w in raw_windows:
- # Compatibility envelopes are untrusted input: skip non-dict members
- # instead of raising AttributeError on one malformed record.
- if not isinstance(w, dict):
- continue
- pid_int = _positive_int(w.get("pid"))
- window_id_int = _positive_int(w.get("window_id"))
- if pid_int is None or window_id_int is None:
- continue
- z_raw = w.get("z_index")
- z_index = z_raw if isinstance(z_raw, (int, float)) and not isinstance(z_raw, bool) else 0
- app_name = w.get("app_name", "")
- title = w.get("title", "")
- windows.append({
- "app_name": app_name if isinstance(app_name, str) else "",
- "pid": pid_int,
- "window_id": window_id_int,
- # cua-driver 0.6.x on Linux may return JSON null here.
- # Only explicit False means off-screen; null means unknown.
- "off_screen": w.get("is_on_screen") is False,
- "title": title if isinstance(title, str) else "",
- "z_index": z_index,
- })
- return windows
-
-
-def _windows_from_tool_result(out: Dict[str, Any]) -> List[Dict[str, Any]]:
- """Return list_windows payloads across cua-driver result shapes."""
- structured = out.get("structuredContent")
- if isinstance(structured, dict):
- windows = structured.get("windows")
- if isinstance(windows, list) and windows:
- return windows
- data = out.get("data")
- if isinstance(data, dict):
- windows = data.get("windows")
- if isinstance(windows, list) and windows:
- return windows
- legacy_windows = data.get("_legacy_windows")
- if isinstance(legacy_windows, list) and legacy_windows:
- return legacy_windows
+def _png_metrics(png_b64: str, width: int, height: int) -> Tuple[int, int, int]:
+ """Return ``(png_bytes_len, width, height)``, replacing the given size with
+ the sniffed one when the bytes decode to a readable PNG/JPEG header."""
+ try:
+ raw = base64.b64decode(png_b64, validate=False)
+ png_bytes_len = len(raw)
+ detected_width, detected_height = _image_dimensions_from_bytes(raw)
+ if detected_width and detected_height:
+ width, height = detected_width, detected_height
+ except Exception:
+ png_bytes_len = len(png_b64) * 3 // 4
+ return png_bytes_len, width, height
- windows = out.get("windows")
- if isinstance(windows, list) and windows:
- return windows
- legacy_windows = out.get("_legacy_windows")
- if isinstance(legacy_windows, list) and legacy_windows:
- return legacy_windows
- return []
-
-
-def _apps_from_windows(windows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- apps: List[Dict[str, Any]] = []
- seen: set[tuple[str, int]] = set()
- for summary in _ingest_windows(windows):
- name = summary["app_name"]
- if not name:
- continue
- key = (name, summary["pid"])
- if key in seen:
- continue
- seen.add(key)
- apps.append({"name": name, "pid": summary["pid"]})
- return apps
+
+def _is_desktop_window(w: Dict[str, Any], names: Tuple[str, ...] = _DESKTOP_WINDOW_NAMES) -> bool:
+ haystack = f"{w.get('app_name', '')} {w.get('title', '')}".lower()
+ return any(name in haystack for name in names)
# ---------------------------------------------------------------------------
# The backend itself
# ---------------------------------------------------------------------------
+_NO_TARGET_MSG = "No active window — call capture() first."
+_BTF_UNSUPPORTED_MSG = "The connected cua-driver does not advertise the standalone bring_to_front tool."
+
+
class CuaDriverBackend(ComputerUseBackend):
"""Default computer-use backend. Cross-platform via cua-driver MCP."""
@@ -2639,56 +732,33 @@ class CuaDriverBackend(ComputerUseBackend):
if permission_mode not in {"standard", "bounded", "unrestricted"}:
raise ValueError(f"unsupported cua-driver permission mode: {permission_mode}")
self.permission_mode = permission_mode
- if permission_mode == "unrestricted":
- # Carry the manifest into unrestricted too. It is optional here
- # (unlike bounded), but when the user declared one it still caps
- # what an approval-bypassed run may touch.
- self._embedded_daemon: Optional[_EmbeddedCuaDaemon] = _EmbeddedCuaDaemon(
- resolve_cua_driver_cmd() or "",
- permission_mode,
- capability_manifest=_cua_capability_manifest(),
- )
- elif permission_mode == "bounded":
- # Manifest path comes from config.yaml; _EmbeddedCuaDaemon
- # validates existence and raises a clear error otherwise.
+ 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.
self._embedded_daemon = _EmbeddedCuaDaemon(
resolve_cua_driver_cmd() or "",
permission_mode,
capability_manifest=_cua_capability_manifest(),
)
- else:
- self._embedded_daemon = None
self._bridge = _AsyncBridge()
self._session = _CuaDriverSession(self._bridge, self._embedded_daemon)
- # Sticky context — updated by capture(), used by action tools.
+ # Sticky context — updated 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 # last app name targeted via capture/focus_app
- # Exact identity for capture_after. App names may be generic on Linux
- # (for example, multiple unrelated Qt windows can say Qt6Application).
+ self._last_app: Optional[str] = None
+ # Exact identity for capture_after: app names may be generic on Linux
+ # (several unrelated Qt windows can all say Qt6Application).
self._last_target: Optional[Dict[str, Optional[int]]] = None
- # Surface 6 of NousResearch/hermes-agent#47072: per-snapshot
- # `element_index -> element_token` map populated on capture().
- # Action tools (click/scroll/set_value/...) attach the matching
- # token alongside `element_index` so cua-driver detects "stale"
- # explicitly instead of silently re-resolving to a different
- # element. Cleared whenever a fresh capture overwrites the
- # snapshot context.
+ # Per-snapshot `element_index -> element_token` map from capture().
+ # Actions attach the token so cua-driver detects "stale" explicitly
+ # instead of silently re-resolving to a different element.
self._snapshot_tokens: Dict[int, str] = {}
- # Per-instance public cua-driver session label. The MCP transport owns
- # the private lifecycle and releases it when the connection closes.
- # start_session/end_session attach this stable label to cursor,
- # recording, and config state within that lifecycle. Doing so:
- # - Gets a distinct agent-cursor color per Hermes run, with
- # overlay rendering visualising where actions land
- # (without moving the real OS cursor).
- # - Gives config and recording state a stable owner label inside the
- # transport-private lifecycle.
- # We mint a UUID4-based id once per CuaDriverBackend instance —
- # one Hermes run = one backend = one label — and pass it as
- # `session` on every cua-driver tool call. Labels are an
- # part of the required Cua Driver 0.20 runtime contract checked at
- # backend startup.
+ # Public session label (one per backend = one per Hermes run) passed as
+ # `session` on every call: owns the agent cursor color and gives config
+ # / recording state a stable owner inside the transport-private
+ # lifecycle. Part of the 0.20 runtime contract checked at start().
self._session_id: str = f"hermes-{uuid.uuid4().hex[:12]}"
self._session.set_transport_reset_callback(self._handle_transport_reset)
@@ -2700,35 +770,23 @@ class CuaDriverBackend(ComputerUseBackend):
def start(self) -> None:
contract = cua_driver_runtime_contract_status()
if not contract.get("ready"):
- # An installed-but-incompatible driver (e.g. predating a Hermes
- # version-floor bump) is a state we created — repair it once
- # automatically instead of failing every computer_use call.
contract = _maybe_repair_runtime_contract(contract)
if not contract.get("ready"):
reason = contract.get("reason") or "runtime contract is incomplete"
- if os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip():
- repair = (
- "Update the binary selected by HERMES_CUA_DRIVER_CMD or "
- "remove that override."
- )
- else:
- repair = "Run `hermes computer-use install` to repair it."
+ 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}")
_maybe_nudge_update()
- # The MCP client SDK (`mcp`) is an optional dependency (the
- # `computer-use` / `mcp` extras), not part of Hermes' minimal core.
- # Lazy-install it on first use — the same pattern every other optional
- # backend uses — so users never hit an opaque `No module named 'mcp'`
- # at invoke time. Auto-install is gated by `security.allow_lazy_installs`
- # (default on); when it's disabled or fails, ensure() raises
- # FeatureUnavailable carrying an actionable `uv pip install mcp==…`
- # hint, which surfaces via the backend-unavailable path in tool.py.
+ # `mcp` is an optional extra: lazy-install on first use (gated by
+ # `security.allow_lazy_installs`); on failure ensure() 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)
- # A just-installed package may not be importable until the import
- # machinery's caches are refreshed within this process.
import importlib
- importlib.invalidate_caches()
+ importlib.invalidate_caches() # a just-installed package may not be importable yet
try:
if self._embedded_daemon is not None:
self._embedded_daemon.start()
@@ -2738,35 +796,26 @@ class CuaDriverBackend(ComputerUseBackend):
self._embedded_daemon.stop()
raise
- # Declare the run's session identity to cua-driver. From the
- # cua-driver server instructions: "start_session(session) once
- # at the start of a run → declares THIS run's identity (a
- # stable id you choose). Pass that same `session` on every
- # action below. It owns your agent cursor (a distinct color
- # per id) and follows the run across apps/windows." Failure
- # to start the session is non-fatal — cua-driver's tools
- # accept anonymous calls (the cursor just won't render),
- # so we 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.
try:
self._session.call_tool("start_session", {"session": self._session_id})
except Exception as e:
logger.debug("cua-driver start_session failed (continuing anonymous): %s", e)
- # Post-handshake session tuning. Both guard on `_started`: before the
- # handshake flips it, call_tool would re-enter session.start() (see
- # _LIFECYCLE_CALLS) and tests that stub start() would recurse.
+ # Post-handshake tuning guards on `_started`: before the handshake
+ # flips it, call_tool would re-enter session.start() and tests that
+ # stub start() would recurse.
if self._session._started:
- # Cap screenshot size so every later get_window_state / SOM
- # capture pays less over the daemon socket and in the model turn.
+ # Cap screenshot size so every later capture pays less over the
+ # daemon socket and in the model turn.
max_dim = _computer_use_max_image_dimension()
if max_dim:
try:
self.set_config(max_image_dimension=max_dim)
except Exception as e:
logger.debug("cua-driver set_config(max_image_dimension) failed: %s", e)
- # Belt-and-suspenders when --no-overlay is unsupported or ignored:
- # hide the agent cursor overlay via the session API so macOS idle
- # redraw loops cannot keep burning CPU after the first action.
+ # Belt-and-suspenders when --no-overlay is unsupported or ignored.
if _cua_no_overlay():
try:
self.set_agent_cursor_enabled(False, cursor_id=self._session_id)
@@ -2774,11 +823,9 @@ class CuaDriverBackend(ComputerUseBackend):
logger.debug("cua-driver set_agent_cursor_enabled failed: %s", e)
def stop(self) -> None:
- # Tear the cua-driver session down before disconnecting so the
- # driver can clean up per-session state (cursor overlay, recording
- # ownership, config overrides). Best-effort — even if it fails,
- # the connection drop below releases the daemon-side state via
- # the session_end hook cua-driver registers internally.
+ # Best-effort end_session first 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:
try:
self._session.call_tool("end_session", {"session": self._session_id})
@@ -2794,14 +841,12 @@ class CuaDriverBackend(ComputerUseBackend):
self._embedded_daemon.stop()
def is_available(self) -> bool:
- # cua-driver runs on macOS, Windows, and Linux. The Linux path is
- # the most recent addition (X11 + Wayland both supported upstream
- # as of mid-2026). Override the platform check at your own risk:
- # other Unix-likes haven't been exercised end-to-end.
+ # Other Unix-likes haven't been exercised end-to-end.
if sys.platform not in ("darwin", "win32", "linux"):
return False
return cua_driver_binary_available()
+ # ── Target state ───────────────────────────────────────────────
def _clear_active_target(self) -> None:
"""Forget a capture/focus target so a failed lookup cannot misroute input."""
self._active_pid = None
@@ -2810,19 +855,24 @@ class CuaDriverBackend(ComputerUseBackend):
self._last_target = None
self._snapshot_tokens = {}
+ 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._last_target = {"pid": self._active_pid, "window_id": self._active_window_id}
+
+ def _no_target(self, action: str, *, need_window: bool = False) -> Optional[ActionResult]:
+ if self._active_pid is None or (need_window and self._active_window_id is None):
+ return ActionResult(ok=False, action=action, message=_NO_TARGET_MSG)
+ return None
+
def _failed_capture(self, mode: str, message: str = "") -> CaptureResult:
"""Return an empty capture after disarming any prior target context."""
self._clear_active_target()
- return CaptureResult(
- mode=mode,
- width=0,
- height=0,
- png_b64=None,
- elements=[],
- app="",
- window_title=message,
- png_bytes_len=0,
- )
+ return CaptureResult(mode=mode, width=0, height=0, png_b64=None, elements=[],
+ app="", window_title=message, png_bytes_len=0)
def _call_capture_tool(self, name: str, args: Dict[str, Any]) -> Dict[str, Any]:
"""Call a capture-stage tool and disarm state on transport or logical failure."""
@@ -2840,20 +890,15 @@ class CuaDriverBackend(ComputerUseBackend):
)
return out
+ # ── Window discovery ───────────────────────────────────────────
+ def _list_windows_args(self) -> Dict[str, Any]:
+ return {"on_screen_only": True, "session": self._session_id}
+
def _load_windows(self) -> List[Dict[str, Any]]:
- """Load normalized visible windows, with the shared CLI recovery path.
-
- Windows are sorted by ``z_index`` **descending**: CUA Driver
- defines higher values as closer to the front, so the frontmost
- window ends up at index 0 — which is what ``capture()`` and
- ``focus_app()`` pick as the default target. ``_ingest_windows``
- already normalised null ``z_index`` (Wayland) to 0, so those
- windows sort to the back.
- """
- out = self._call_capture_tool(
- "list_windows",
- {"on_screen_only": True, "session": self._session_id},
- )
+ """Load normalized visible windows sorted by ``z_index`` DESCENDING
+ (frontmost at index 0 — the default target for capture()/focus_app()),
+ re-fetching over the CLI transport when MCP returns nothing."""
+ out = self._call_capture_tool("list_windows", self._list_windows_args())
windows = _ingest_windows(_windows_from_tool_result(out))
windows.sort(key=lambda w: w["z_index"], reverse=True)
if windows:
@@ -2864,11 +909,7 @@ class CuaDriverBackend(ComputerUseBackend):
"re-fetching via CLI transport",
)
try:
- cli_out = self._session._call_tool_via_cli(
- "list_windows",
- {"on_screen_only": True, "session": self._session_id},
- 20.0,
- )
+ cli_out = self._session._call_tool_via_cli("list_windows", self._list_windows_args(), 20.0)
except Exception as exc:
logger.error("cua-driver CLI re-fetch for list_windows failed: %s", exc)
return []
@@ -2885,19 +926,21 @@ class CuaDriverBackend(ComputerUseBackend):
) -> List[Dict[str, Any]]:
"""Resolve ``app=`` through exact names before convenience substrings.
- Linux ``list_windows`` can omit an app name while ``list_apps`` retains
+ Linux ``list_windows`` can omit an app name while ``list_apps`` keeps
name/bundle-ID metadata. Exact direct names and exact metadata aliases
- must win over substring matches: querying ``Code`` must not silently
- select ``Visual Studio Code`` merely because it is frontmost.
+ win over substring matches: querying ``Code`` must not silently select
+ ``Visual Studio Code`` because it is frontmost.
"""
app_lower = app.strip().lower()
if not app_lower:
return []
- direct_exact = [
- w for w in windows
- if app_lower == str(w.get("app_name", "")).strip().lower()
- ]
+ def _by_name(exact: bool) -> List[Dict[str, Any]]:
+ if exact:
+ return [w for w in windows if app_lower == str(w.get("app_name", "")).strip().lower()]
+ return [w for w in windows if app_lower in str(w.get("app_name", "")).lower()]
+
+ direct_exact = _by_name(exact=True)
if direct_exact:
return direct_exact
@@ -2905,8 +948,7 @@ class CuaDriverBackend(ComputerUseBackend):
running_apps = self.list_apps()
except Exception as exc:
# A title can still be the only usable identity on X11 when app
- # enumeration is unavailable, so retain the constrained title
- # fallback below instead of treating this as a hard no-match.
+ # enumeration is unavailable, so keep the title fallback below.
logger.debug("computer_use list_apps fallback failed for %r: %s", app, exc)
running_apps = []
@@ -2915,16 +957,9 @@ class CuaDriverBackend(ComputerUseBackend):
for raw_app in running_apps:
if not isinstance(raw_app, dict) or raw_app.get("running") is False:
continue
- raw_pid = raw_app.get("pid")
- if isinstance(raw_pid, bool) or not isinstance(raw_pid, (int, str)):
+ pid = _positive_int(raw_app.get("pid"))
+ if pid is None:
continue
- try:
- pid = int(raw_pid)
- except ValueError:
- continue
- if pid <= 0:
- continue
-
aliases = {
value.strip().lower()
for key in ("bundle_id", "bundleId", "name", "app_name", "display_name")
@@ -2935,20 +970,13 @@ class CuaDriverBackend(ComputerUseBackend):
elif any(app_lower in alias for alias in aliases):
partial_pids.add(pid)
- metadata_exact = [w for w in windows if w.get("pid") in exact_pids]
- if metadata_exact:
- return metadata_exact
-
- direct_partial = [
- w for w in windows
- if app_lower in str(w.get("app_name", "")).lower()
- ]
- if direct_partial:
- return direct_partial
-
- metadata_partial = [w for w in windows if w.get("pid") in partial_pids]
- if metadata_partial:
- return metadata_partial
+ for matched in (
+ [w for w in windows if w.get("pid") in exact_pids],
+ _by_name(exact=False),
+ [w for w in windows if w.get("pid") in partial_pids],
+ ):
+ if matched:
+ return matched
# Some X11 backends expose a title but no app name. Restrict this final
# fallback to nameless rows so a localized app name is not overridden
@@ -2959,104 +987,164 @@ class CuaDriverBackend(ComputerUseBackend):
and app_lower in str(w.get("title", "")).lower()
]
- def _capture_full_screen(self, mode: str) -> CaptureResult:
- """Capture the whole displayed screen via cua-driver's desktop lane.
-
- Uses `get_desktop_state` — a composited grab of everything currently
- on screen (like PrtScn) — instead of resolving a single window through
- `list_windows`. This is what "screenshot my screen" means: previously
- the `screen` sentinel resolved to the OS shell window (Progman /
- WorkerW on Windows), which is the wallpaper + icons layer and never
- shows the windows stacked above it.
-
- Bonus resilience (2ndNatureAI, #60081): this lane works even when
- Windows UIA enumeration (`list_windows` / `list_apps`) hangs
- (trycua/cua#2110/#2113), because it never enumerates.
-
- Returns pixels only — a composited image has no single accessibility
- tree, so `elements` is always empty regardless of requested mode. The
- result carries a `note` telling the model how to reach the
- interactive lanes.
- """
- self._clear_active_target()
- previous_scope: Optional[str] = None
+ def _resolve_capture_windows(
+ self,
+ mode: str,
+ app: Optional[str],
+ pid: Optional[int],
+ window_id: Optional[int],
+ ) -> "List[Dict[str, Any]] | CaptureResult":
+ """Candidate windows for capture(), or a failed CaptureResult."""
+ if pid is not None or window_id is not None:
+ # An exact pid/window pair is both the stable capture_after target
+ # and the escape hatch when discovery is unavailable on X11.
+ if pid is None or window_id is None:
+ return self._failed_capture(
+ mode, "<capture targeting requires both pid and window_id>",
+ )
+ target_pid = _positive_int(pid)
+ target_window_id = _positive_int(window_id)
+ if target_pid is None or target_window_id is None:
+ return self._failed_capture(
+ mode, "<capture targeting requires positive integer pid and window_id>",
+ )
+ return [{"app_name": app or "", "pid": target_pid, "window_id": target_window_id,
+ "off_screen": False, "title": "", "z_index": 0}]
+
try:
- cfg = self._session.call_tool(
- "get_config", {"session": self._session_id}, timeout=10.0,
+ windows = self._load_windows()
+ except Exception:
+ self._clear_active_target()
+ raise
+ if not windows:
+ # Diagnose instead of a bare 0x0: the dominant real-world cause on
+ # Linux is a locked desktop session.
+ return self._failed_capture(mode, _empty_discovery_reason())
+ if not app:
+ return windows
+
+ if app.strip().lower() in _DESKTOP_SHELL_SENTINELS:
+ # Desktop-shell request: the OS shell window WITH its interactable
+ # elements (desktop icons), so "click the taskbar" works.
+ desktop = [w for w in windows if _is_desktop_window(w)]
+ if not desktop:
+ return self._failed_capture(mode, (
+ f"<no desktop/shell window found for app={app!r}; "
+ f"cua-driver captures one window at a time and exposes "
+ f"no whole-virtual-desktop or per-monitor capture. "
+ f"Call list_apps / capture(app='<AppName>') to target a "
+ f"specific window instead. On Windows the taskbar is "
+ f"'Shell_TrayWnd' and the desktop is 'Progman'.>"
+ ))
+ # Prefer the backdrop (Progman/WorkerW/Finder) over the taskbar so
+ # the capture shows the full desktop rather than the task strip.
+ return sorted(
+ desktop,
+ key=lambda w: 0 if _is_desktop_window(w, _DESKTOP_BACKDROP_NAMES) else 1,
)
- sc = cfg.get("structuredContent") or {}
- if isinstance(sc, dict):
- val = sc.get("capture_scope")
- if isinstance(val, str):
- previous_scope = val
- except Exception as e:
- logger.debug("cua-driver get_config before full-screen capture failed: %s", e)
+ # When the filter matches nothing, say so instead of silently capturing
+ # the frontmost window — on macOS list_windows returns the localized
+ # app name (e.g. "計算機"), so `app="Calculator"` legitimately misses.
+ filtered = self._match_windows_for_app(windows, app)
+ if not filtered:
+ return self._failed_capture(mode, (
+ f"<no on-screen window matched app={app!r}; "
+ f"call list_apps to see available app names or bundle IDs "
+ f"(macOS reports localized names, e.g. '計算機' "
+ f"instead of 'Calculator'; some Linux/Qt apps only "
+ f"resolve via list_apps metadata)>"
+ ))
+ return filtered
+
+ # ── Capture ────────────────────────────────────────────────────
+ def _gws_args(self) -> Dict[str, Any]:
+ return {
+ "pid": self._active_pid,
+ "window_id": self._active_window_id,
+ "session": self._session_id,
+ }
+
+ def _cli_refetch_window_state(self, what: str) -> Optional[Dict[str, Any]]:
+ """One-shot get_window_state over the CLI transport (different daemon
+ socket) after MCP came back imageless/empty without raising."""
try:
- if previous_scope != "desktop":
- self._session.call_tool(
- "set_config",
- {"key": "capture_scope", "value": "desktop",
- "session": self._session_id},
- timeout=10.0,
- )
- out = self._call_capture_tool(
- "get_desktop_state", {"session": self._session_id},
- )
- finally:
- if previous_scope and previous_scope != "desktop":
- try:
- self._session.call_tool(
- "set_config",
- {"key": "capture_scope", "value": previous_scope,
- "session": self._session_id},
- timeout=10.0,
- )
- except Exception as e:
- logger.debug("cua-driver restore capture_scope failed: %s", e)
+ cli_out = self._session._call_tool_via_cli("get_window_state", self._gws_args(), 30.0)
+ except Exception as cli_exc:
+ logger.error("cua-driver CLI re-fetch for %s failed: %s", what, cli_exc)
+ return None
+ if cli_out.get("isError") is True:
+ self._clear_active_target()
+ return None
+ return cli_out
- png_b64, image_mime_type = _image_from_tool_result(out)
+ def _capture_vision(self) -> Tuple[Optional[str], Optional[str], str]:
+ """Pixels only, no elements. Returns ``(png_b64, mime, window_title)``.
+
+ Drivers that advertise the (cheaper) standalone ``screenshot`` tool use
+ it; current drivers folded PNG capture into ``get_window_state``, whose
+ tree is DISCARDED here. When discovery hasn't run we still try
+ ``screenshot`` first and fall back, so the path self-heals on any
+ driver version.
+ """
+ png_b64: Optional[str] = None
+ image_mime_type: Optional[str] = None
+ window_title = ""
+ if self._session._has_tool("screenshot") or not self._session.capabilities_discovered:
+ sc_out = self._call_capture_tool("screenshot", {
+ "window_id": self._active_window_id, "format": "jpeg", "quality": 85,
+ "session": self._session_id,
+ })
+ png_b64, image_mime_type = _image_from_tool_result(sc_out)
if not png_b64:
- return self._failed_capture(
- mode,
- "<get_desktop_state returned no image; the driver may "
- "predate the desktop capture lane — try "
- "capture(app='<AppName>') for a specific window>",
+ # "Unknown tool: screenshot" or an empty image part -> get_window_state.
+ gws_out = self._call_capture_tool("get_window_state", self._gws_args())
+ png_b64, image_mime_type = _image_from_tool_result(gws_out)
+ # The title is cheap and useful; `elements` stays empty by contract.
+ _, tree = _split_tree_text(_tree_text(gws_out))
+ window_title = _window_title_from_tree(tree)
+ if not png_b64:
+ logger.warning(
+ "cua-driver vision capture returned no image over MCP "
+ "(window_id=%s); re-fetching via CLI transport",
+ self._active_window_id,
)
- structured = out.get("structuredContent") or {}
- width = int(structured.get("screenshot_width")
- or structured.get("screen_width") or 0)
- height = int(structured.get("screenshot_height")
- or structured.get("screen_height") or 0)
- png_bytes_len = 0
- try:
- raw = base64.b64decode(png_b64, validate=False)
- png_bytes_len = len(raw)
- detected_width, detected_height = _image_dimensions_from_bytes(raw)
- if detected_width and detected_height:
- width = detected_width
- height = detected_height
- except Exception:
- png_bytes_len = len(png_b64) * 3 // 4
- return CaptureResult(
- mode="vision",
- width=width,
- height=height,
- png_b64=png_b64,
- elements=[],
- app="screen",
- window_title="Full screen (composited)",
- png_bytes_len=png_bytes_len,
- image_mime_type=image_mime_type,
- note=(
- "full-screen capture has no interactable elements; to act on "
- "what you see, call capture(app='<AppName>') for that app's "
- "clickable element list, or capture(app='desktop') for the "
- "desktop shell (wallpaper icons / taskbar) with elements"
- ),
- )
+ cli_out = self._cli_refetch_window_state("vision screenshot")
+ if cli_out is not None and cli_out.get("images"):
+ png_b64 = cli_out["images"][0]
+ image_mime_type = "image/png"
+ return png_b64, image_mime_type, window_title
+
+ def _capture_window_state(self) -> Tuple[Optional[str], Optional[str], List[UIElement], str]:
+ """AX tree + screenshot. Returns ``(png_b64, mime, elements, window_title)``."""
+ gws_out = self._call_capture_tool("get_window_state", self._gws_args())
+ # A flaky bridge can return a degenerate result (no screenshot AND no
+ # parseable tree) WITHOUT raising — a silent 0x0 to the model. Distinct
+ # from the EAGAIN path handled in call_tool: here MCP "succeeded".
+ if _gws_is_empty(gws_out):
+ logger.warning(
+ "cua-driver get_window_state returned an empty result over MCP "
+ "(pid=%s window_id=%s); re-fetching via CLI transport",
+ self._active_pid, self._active_window_id,
+ )
+ cli_out = self._cli_refetch_window_state("get_window_state")
+ if cli_out is not None and not _gws_is_empty(cli_out):
+ gws_out = cli_out
+
+ _, tree = _split_tree_text(_tree_text(gws_out))
+ # Prefer the canonical structuredContent.elements (real frames); the
+ # markdown regex fallback yields (0,0,0,0) bounds.
+ sc_elements = (gws_out.get("structuredContent") or {}).get("elements")
+ if isinstance(sc_elements, list) and sc_elements:
+ elements = _parse_elements_from_structured(sc_elements)
+ else:
+ elements = _parse_elements_from_tree(tree) if tree else []
+ # Tokens are tied to this snapshot: overwrite the whole map (and clear
+ # it when the new capture carries none).
+ self._snapshot_tokens = {e.index: e.element_token for e in elements if e.element_token}
+ png_b64, image_mime_type = _image_from_tool_result(gws_out)
+ return png_b64, image_mime_type, elements, _window_title_from_tree(tree)
- # ── Capture ────────────────────────────────────────────────────
def capture(
self,
mode: str = "som",
@@ -3066,354 +1154,107 @@ class CuaDriverBackend(ComputerUseBackend):
) -> CaptureResult:
"""Capture the frontmost on-screen window or an exact known target.
- Maps hermes `capture(mode, app)` → cua-driver `list_windows` +
- `get_window_state` (ax/som) or `screenshot` (vision).
+ Maps hermes `capture(mode, app)` -> cua-driver `list_windows` +
+ `get_window_state` (ax/som) or `screenshot` (vision). Only the
+ structured ``structuredContent.windows`` shape is supported.
"""
- # Step 1: enumerate on-screen windows to find target pid/window_id.
- # Surface 3 of NousResearch/hermes-agent#47072: read the canonical
- # `structuredContent.windows` array directly. Pre-fix the wrapper
- # also kept a text-line regex (`_WINDOW_LINE_RE`) as a fallback for
- # cua-driver builds that predated structuredContent; the supersede
- # PR's effective minimum (trycua/cua#1961 + #1908) is well past
- # that, so the fallback is gone — the wrapper now treats the
- # structured shape as the only contract.
- # Drop schema-filler ids before they can be read as a targeting
- # request, so `capture(app=...)` and frontmost capture still work for
- # models that emit every optional property zero-filled.
+ # Drop schema-filler ids (models that zero-fill every optional
+ # property) before they read as a targeting request.
if _is_placeholder_id(pid):
pid = None
if _is_placeholder_id(window_id):
window_id = None
- # Step 0: explicit full-screen capture — a composited grab of
- # everything displayed, via get_desktop_state. Bypasses window
- # enumeration entirely (also keeps screenshots working when Windows
- # UIA enumeration hangs — trycua/cua#2110/#2113, #60081).
- # app='desktop' intentionally does NOT take this lane: it resolves to
- # the shell/desktop window below so desktop icons stay clickable.
- if (
- pid is None
- and window_id is None
- and app
- and app.strip().lower() in _FULL_SCREEN_SENTINELS
- ):
+ exact_target = pid is not None or window_id is not None
+ # Full-screen lane bypasses enumeration entirely (also keeps
+ # screenshots working when Windows UIA enumeration hangs).
+ # app='desktop' deliberately does NOT take it: desktop icons stay clickable.
+ if not exact_target and app and app.strip().lower() in _FULL_SCREEN_SENTINELS:
return self._capture_full_screen(mode)
- # An exact pid/window pair is both the stable capture_after target and
- # the escape hatch when app/window discovery is unavailable on X11.
- if pid is not None or window_id is not None:
- if pid is None or window_id is None:
- return self._failed_capture(
- mode, "<capture targeting requires both pid and window_id>",
- )
- target_pid = _positive_int(pid)
- target_window_id = _positive_int(window_id)
- if target_pid is None or target_window_id is None:
- return self._failed_capture(
- mode, "<capture targeting requires positive integer pid and window_id>",
- )
- windows = [{
- "app_name": app or "",
- "pid": target_pid,
- "window_id": target_window_id,
- "off_screen": False,
- "title": "",
- "z_index": 0,
- }]
- else:
- try:
- windows = self._load_windows()
- except Exception:
- self._clear_active_target()
- raise
- if not windows:
- # Diagnose instead of returning a bare 0x0: the dominant
- # real-world cause on Linux is a locked desktop session.
- return self._failed_capture(mode, _empty_discovery_reason())
-
- # Filter by app name (case-insensitive substring) if requested.
- # When the filter matches nothing, surface that explicitly instead of
- # silently capturing the frontmost window — on macOS the `app_name`
- # returned by list_windows is the localized name (e.g. "計算機"), so
- # `app="Calculator"` legitimately matches no windows on a non-English
- # system and the caller needs to retry with the localized name.
- if pid is None and window_id is None and app and app.strip().lower() in _DESKTOP_SHELL_SENTINELS:
- # Desktop-shell request (app='desktop'): resolve to the OS
- # shell/desktop window (the desktop backdrop or the
- # taskbar/menu-bar) via list_windows. Unlike the full-screen lane
- # above, this carries the shell's interactable elements (desktop
- # icons), so "click the taskbar" / "open the recycle bin" work.
- def _is_desktop_window(w: Dict[str, Any]) -> bool:
- haystack = f"{w.get('app_name', '')} {w.get('title', '')}".lower()
- return any(name in haystack for name in _DESKTOP_WINDOW_NAMES)
- desktop = [w for w in windows if _is_desktop_window(w)]
- if not desktop:
- return self._failed_capture(
- mode,
- (
- f"<no desktop/shell window found for app={app!r}; "
- f"cua-driver captures one window at a time and exposes "
- f"no whole-virtual-desktop or per-monitor capture. "
- f"Call list_apps / capture(app='<AppName>') to target a "
- f"specific window instead. On Windows the taskbar is "
- f"'Shell_TrayWnd' and the desktop is 'Progman'.>"
- ),
- )
- # Prefer the desktop backdrop (Progman/WorkerW/Finder) over the
- # taskbar when both are present, so a bare "screen" capture shows
- # the full desktop rather than just the task strip.
- windows = sorted(
- desktop,
- key=lambda w: 0 if any(
- n in f"{w.get('app_name', '')} {w.get('title', '')}".lower()
- for n in ("progman", "workerw", "program manager", "finder", "desktop")
- ) else 1,
- )
- elif pid is None and window_id is None and app:
- filtered = self._match_windows_for_app(windows, app)
- if not filtered:
- return self._failed_capture(
- mode,
- (
- f"<no on-screen window matched app={app!r}; "
- f"call list_apps to see available app names or bundle IDs "
- f"(macOS reports localized names, e.g. '計算機' "
- f"instead of 'Calculator'; some Linux/Qt apps only "
- f"resolve via list_apps metadata)>"
- ),
- )
- windows = filtered
-
- # Pick first on-screen window (sorted by z_index / z-order above).
- # On Linux, unqualified default captures skip desktop/shell helper
- # windows and, with tied/unknown z_index, may additionally consult
- # _NET_ACTIVE_WINDOW (#58026).
- target = _select_capture_target(
- windows,
- app_requested=bool(app),
- exact_target=pid is not None or window_id is not None,
- )
- self._active_pid = target["pid"]
- self._active_window_id = target["window_id"]
- # Tokens belong to the prior window snapshot. Disarm them before any
- # capture call so an exception cannot pair old tokens with this target.
- self._snapshot_tokens = {}
+ windows = self._resolve_capture_windows(mode, app, pid, window_id)
+ if isinstance(windows, CaptureResult):
+ return windows
+
+ target = _select_capture_target(windows, app_requested=bool(app), exact_target=exact_target)
+ self._set_active_target(target)
app_name = target["app_name"]
- # Record the resolved app name so capture_after= follow-ups can re-target
- # the same app rather than falling back to the frontmost window.
+ # Record the resolved app so capture_after= follow-ups re-target the
+ # same app rather than falling back to the frontmost window.
if app or not self._last_app:
self._last_app = app_name or app or ""
- self._last_target = {
- "pid": self._active_pid,
- "window_id": self._active_window_id,
- }
- # Step 2: capture.
- png_b64: Optional[str] = None
- image_mime_type: Optional[str] = None
elements: List[UIElement] = []
- width = height = 0
- window_title = ""
-
if mode == "vision":
- # Plain screenshot, no AX walk. cua-driver dropped the standalone
- # `screenshot` tool (≥0.5.x) and folded full-window PNG capture
- # into `get_window_state`. Route accordingly:
- # * Driver advertises `screenshot` (older builds) → use it; it's
- # the cheapest path (no AX tree walked server-side).
- # * Otherwise (current drivers) → call `get_window_state` but
- # DISCARD the AX tree/elements, returning only the PNG. Vision
- # mode's whole contract is "just the pixels, no element noise",
- # so we drop everything but the image.
- # When capability discovery hasn't run (empty map), we don't trust
- # a negative `_has_tool` answer — we still try `screenshot` first
- # and fall back if the driver rejects it, so the path self-heals on
- # any driver version.
- use_screenshot = (
- self._session._has_tool("screenshot")
- or not self._session.capabilities_discovered
- )
- sc_out: Optional[Dict[str, Any]] = None
- if use_screenshot:
- sc_out = self._call_capture_tool(
- "screenshot",
- {
- "window_id": self._active_window_id,
- "format": "jpeg",
- "quality": 85,
- "session": self._session_id,
- },
- )
- png_b64, image_mime_type = _image_from_tool_result(sc_out)
- if not png_b64:
- # Driver had no usable `screenshot` (e.g. "Unknown tool:
- # screenshot" on ≥0.5.x, or an empty image part). Fall
- # through to the get_window_state path below.
- sc_out = None
-
- if sc_out is None:
- gws_out = self._call_capture_tool(
- "get_window_state",
- {
- "pid": self._active_pid,
- "window_id": self._active_window_id,
- "session": self._session_id,
- },
- )
- png_b64, image_mime_type = _image_from_tool_result(gws_out)
- # Still grab the window title — it's cheap and useful in the
- # vision response — but deliberately leave `elements` empty so
- # vision stays free of AX-tree noise.
- text = gws_out["data"] if isinstance(gws_out["data"], str) else ""
- _, tree = _split_tree_text(text)
- wt = re.search(r'AXWindow\s+"([^"]+)"', tree)
- if wt:
- window_title = wt.group(1)
-
- if not png_b64:
- # Both MCP attempts came back imageless without raising (flaky
- # bridge dropping the heavy payload) — re-fetch the window
- # state over the CLI transport, which embeds a screenshot.
- logger.warning(
- "cua-driver vision capture returned no image over MCP "
- "(window_id=%s); re-fetching via CLI transport",
- self._active_window_id,
- )
- try:
- cli_out = self._session._call_tool_via_cli(
- "get_window_state",
- {
- "pid": self._active_pid,
- "window_id": self._active_window_id,
- "session": self._session_id,
- },
- 30.0,
- )
- if cli_out.get("isError") is True:
- self._clear_active_target()
- elif cli_out.get("images"):
- png_b64 = cli_out["images"][0]
- image_mime_type = "image/png"
- except Exception as cli_exc:
- logger.error(
- "cua-driver CLI re-fetch for vision screenshot failed: %s", cli_exc,
- )
+ png_b64, image_mime_type, window_title = self._capture_vision()
else:
- # get_window_state: AX tree + screenshot.
- gws_out = self._call_capture_tool(
- "get_window_state",
- {
- "pid": self._active_pid,
- "window_id": self._active_window_id,
- "session": self._session_id,
- },
- )
- # The persistent MCP session can return a degenerate result —
- # empty/partial data with NO exception — when the bridge is flaky
- # (e.g. it reconnected mid-call and dropped the heavy
- # get_window_state payload). That surfaces to the model as a silent
- # 0x0 capture. Detect "no screenshot AND no parseable tree" and
- # force a one-shot CLI-transport re-fetch, which talks to the daemon
- # over a different socket and returns the full result. This is
- # distinct from the EAGAIN MCPError path (handled in call_tool);
- # here the MCP call "succeeded" but gave us nothing usable.
- def _gws_is_empty(out: Dict[str, Any]) -> bool:
- if out.get("images"):
- return False
- sc_ = out.get("structuredContent") or {}
- # Modern drivers carry the payload in structuredContent
- # (elements array / embedded screenshot) with no markdown
- # tree — that is NOT an empty result.
- if sc_.get("elements") or sc_.get("screenshot_png_b64"):
- return False
- txt = out.get("data") if isinstance(out.get("data"), str) else ""
- _, tr = _split_tree_text(txt or "")
- return not (tr and tr.strip())
-
- if _gws_is_empty(gws_out):
- logger.warning(
- "cua-driver get_window_state returned an empty result over MCP "
- "(pid=%s window_id=%s); re-fetching via CLI transport",
- self._active_pid, self._active_window_id,
- )
- try:
- cli_out = self._session._call_tool_via_cli(
- "get_window_state",
- {
- "pid": self._active_pid,
- "window_id": self._active_window_id,
- "session": self._session_id,
- },
- 30.0,
- )
- if cli_out.get("isError") is True:
- self._clear_active_target()
- elif not _gws_is_empty(cli_out):
- gws_out = cli_out
- except Exception as cli_exc:
- logger.error(
- "cua-driver CLI re-fetch for get_window_state failed: %s", cli_exc,
- )
-
- text = gws_out["data"] if isinstance(gws_out["data"], str) else ""
- summary, tree = _split_tree_text(text)
-
- # Surface 2 of NousResearch/hermes-agent#47072: prefer the
- # canonical structuredContent.elements array (trycua/cua#1961).
- # Falls back to markdown regex parsing for cua-driver builds
- # that didn't carry the structured shape — those bounds come
- # back (0,0,0,0); the structured path preserves real frames.
- sc_elements = (gws_out.get("structuredContent") or {}).get("elements")
- if isinstance(sc_elements, list) and sc_elements:
- elements = _parse_elements_from_structured(sc_elements)
- else:
- elements = _parse_elements_from_tree(tree) if tree else []
-
- # Surface 6: refresh the snapshot-token cache from this
- # capture. Tokens are tied to a specific cua-driver snapshot
- # — when a fresh capture lands, the prior snapshot's tokens
- # are stale, so we overwrite the whole map (and clear it
- # entirely when the new capture carries none).
- self._snapshot_tokens = {
- e.index: e.element_token
- for e in elements
- if e.element_token
- }
+ png_b64, image_mime_type, elements, window_title = self._capture_window_state()
- # Image may arrive as an MCP image part or inside
- # structuredContent (screenshot_png_b64) depending on the driver
- # build — _image_from_tool_result handles both.
- png_b64, image_mime_type = _image_from_tool_result(gws_out)
+ png_bytes_len = width = height = 0
+ if png_b64:
+ png_bytes_len, width, height = _png_metrics(png_b64, 0, 0)
- # Extract window title from the AX tree first AXWindow line.
- wt = re.search(r'AXWindow\s+"([^"]+)"', tree)
- if wt:
- window_title = wt.group(1)
+ return CaptureResult(mode=mode, width=width, height=height, png_b64=png_b64,
+ elements=elements, app=app_name, window_title=window_title,
+ png_bytes_len=png_bytes_len, image_mime_type=image_mime_type)
- png_bytes_len = 0
- if png_b64:
- try:
- raw = base64.b64decode(png_b64, validate=False)
- png_bytes_len = len(raw)
- detected_width, detected_height = _image_dimensions_from_bytes(raw)
- if detected_width and detected_height:
- width = detected_width
- height = detected_height
- except Exception:
- png_bytes_len = len(png_b64) * 3 // 4
+ def _capture_full_screen(self, mode: str) -> CaptureResult:
+ """Composited grab of everything on screen via `get_desktop_state`
+ (like PrtScn) — the shell window would only show wallpaper + icons.
+ Never enumerates, so it also works when Windows UIA hangs. Pixels only:
+ `elements` is always empty; `note` tells the model how to reach the
+ interactive lanes. ``capture_scope`` is switched to desktop for the
+ call and restored afterwards.
+ """
+ self._clear_active_target()
+ previous_scope: Optional[str] = None
+ try:
+ cfg = self._session.call_tool("get_config", {"session": self._session_id}, timeout=10.0)
+ sc = cfg.get("structuredContent") or {}
+ if isinstance(sc, dict) and isinstance(sc.get("capture_scope"), str):
+ previous_scope = sc["capture_scope"]
+ except Exception as e:
+ logger.debug("cua-driver get_config before full-screen capture failed: %s", e)
+
+ def _set_scope(value: str) -> None:
+ self._session.call_tool(
+ "set_config",
+ {"key": "capture_scope", "value": value, "session": self._session_id},
+ timeout=10.0,
+ )
+
+ try:
+ if previous_scope != "desktop":
+ _set_scope("desktop")
+ out = self._call_capture_tool("get_desktop_state", {"session": self._session_id})
+ finally:
+ if previous_scope and previous_scope != "desktop":
+ try:
+ _set_scope(previous_scope)
+ except Exception as e:
+ logger.debug("cua-driver restore capture_scope failed: %s", e)
+ png_b64, image_mime_type = _image_from_tool_result(out)
+ if not png_b64:
+ return self._failed_capture(mode, "<get_desktop_state returned no image; the driver may "
+ "predate the desktop capture lane — try "
+ "capture(app='<AppName>') for a specific window>")
+ structured = out.get("structuredContent") or {}
+ png_bytes_len, width, height = _png_metrics(
+ png_b64,
+ int(structured.get("screenshot_width") or structured.get("screen_width") or 0),
+ int(structured.get("screenshot_height") or structured.get("screen_height") or 0),
+ )
return CaptureResult(
- mode=mode,
- width=width,
- height=height,
- png_b64=png_b64,
- elements=elements,
- app=app_name,
- window_title=window_title,
- png_bytes_len=png_bytes_len,
- image_mime_type=image_mime_type,
+ mode="vision", width=width, height=height, png_b64=png_b64, elements=[],
+ app="screen", window_title="Full screen (composited)",
+ png_bytes_len=png_bytes_len, image_mime_type=image_mime_type,
+ note=("full-screen capture has no interactable elements; to act on "
+ "what you see, call capture(app='<AppName>') for that app's "
+ "clickable element list, or capture(app='desktop') for the "
+ "desktop shell (wallpaper icons / taskbar) with elements"),
)
- # ── Pointer ────────────────────────────────────────────────────
+ # ── Input delivery ─────────────────────────────────────────────
def _apply_delivery(
self,
action: str,
@@ -3422,32 +1263,24 @@ class CuaDriverBackend(ComputerUseBackend):
) -> Optional[ActionResult]:
"""Attach delivery_mode to an input-action args dict.
- Background is the default and never needs a flag. Foreground is only
- sent when the live action schema accepts it; on an older driver that
- lacks the property we refuse with a structured
- ``foreground_unsupported`` result instead of silently downgrading to
- background (which would land the input somewhere the model didn't
- expect). Returns an ActionResult to short-circuit on refusal, or None
- to proceed. See NousResearch/hermes-agent#67052 phase B.
+ Background is the default and needs no flag. Foreground is only sent
+ when the live action schema accepts it; on an older driver we refuse
+ with ``foreground_unsupported`` instead of silently downgrading to
+ background (which would land input where the model didn't expect).
+ Returns an ActionResult to short-circuit on refusal, or None to proceed.
"""
if not delivery_mode or delivery_mode == "background":
return None
if delivery_mode != "foreground":
- return ActionResult(
- ok=False, action=action, code="bad_delivery_mode",
- message=f"unknown delivery_mode {delivery_mode!r} — use background|foreground.",
- )
- # Foreground requested. Only send it if the driver understands it.
+ return ActionResult(ok=False, action=action, code="bad_delivery_mode",
+ message=f"unknown delivery_mode {delivery_mode!r} — use background|foreground.")
if not self._session.supports_input_property(action, "delivery_mode"):
return ActionResult(
- ok=False, action=action, code="foreground_unsupported",
- delivery_mode="foreground",
- message=(
- "The connected cua-driver action schema does not accept "
- "delivery_mode, so foreground delivery is unavailable. "
- "Use another verified rung without assuming the reported "
- "package version describes the live schema."
- ),
+ ok=False, action=action, code="foreground_unsupported", delivery_mode="foreground",
+ message=("The connected cua-driver action schema does not accept "
+ "delivery_mode, so foreground delivery is unavailable. "
+ "Use another verified rung without assuming the reported "
+ "package version describes the live schema."),
)
args["delivery_mode"] = "foreground"
return None
@@ -3461,51 +1294,35 @@ class CuaDriverBackend(ComputerUseBackend):
) -> ActionResult:
"""Apply one delivery rung, optionally focusing via its own tool.
- ``bring_to_front`` is never an input-action property. When explicitly
- requested, the separately approved standalone focus action runs first,
- then the original foreground input runs unchanged.
+ ``bring_to_front`` is never an input-action property: when requested,
+ the separately approved standalone focus action runs first, then the
+ original foreground input runs unchanged.
"""
refusal = self._apply_delivery(action, args, delivery_mode)
if refusal is not None:
return refusal
if bring_to_front:
if delivery_mode != "foreground":
- return ActionResult(
- ok=False,
- action=action,
- code="bring_to_front_requires_foreground",
- message="bring_to_front requires delivery_mode='foreground'.",
- )
+ return ActionResult(ok=False, action=action, code="bring_to_front_requires_foreground",
+ message="bring_to_front requires delivery_mode='foreground'.")
if not self._session._has_tool("bring_to_front"):
- return ActionResult(
- ok=False,
- action=action,
- code="bring_to_front_unsupported",
- delivery_mode="foreground",
- message="The connected cua-driver does not advertise the standalone bring_to_front tool.",
- )
+ return ActionResult(ok=False, action=action, code="bring_to_front_unsupported",
+ delivery_mode="foreground", message=_BTF_UNSUPPORTED_MSG)
if self._active_pid is None or self._active_window_id is None:
return ActionResult(
- ok=False,
- action=action,
- code="bring_to_front_target_required",
+ ok=False, action=action, code="bring_to_front_target_required",
delivery_mode="foreground",
message="Capture an exact target before requesting persistent foreground focus.",
)
- focused = self.bring_to_front(
- pid=self._active_pid,
- window_id=self._active_window_id,
- )
+ focused = self.bring_to_front(pid=self._active_pid, window_id=self._active_window_id)
if not focused.ok:
return focused
result = self._action(action, args)
if bring_to_front:
- result.meta["foreground_focus"] = {
- "invoked": True,
- "tool": "bring_to_front",
- }
+ result.meta["foreground_focus"] = {"invoked": True, "tool": "bring_to_front"}
return result
+ # ── Pointer ────────────────────────────────────────────────────
def click(
self,
*,
@@ -3518,45 +1335,35 @@ class CuaDriverBackend(ComputerUseBackend):
delivery_mode: Optional[str] = None,
bring_to_front: bool = False,
) -> ActionResult:
- pid = self._active_pid
- if pid is None:
- return ActionResult(ok=False, action="click",
- message="No active window — call capture() first.")
-
- # Choose tool by click_count only — single-vs-double — and pass the
- # button through to `click`'s `button` enum (Surface 5 of
- # NousResearch/hermes-agent#47072). cua-driver-rs gained an explicit
- # `button: "left"|"right"|"middle"` arg on `click` in trycua/cua#1961
- # which rejects unknown buttons; before that, `middle` was silently
- # mapped to a left-click via name-routing through `right_click`.
- # `right_click`/`middle_click` MCP tools are deprecated aliases —
- # kept around but no longer invoked from here.
+ missing = self._no_target("click")
+ if missing is not None:
+ return missing
+ # Tool is chosen by click_count only; `button` goes through click's
+ # enum (the driver rejects unknown buttons). `right_click` /
+ # `middle_click` MCP tools are deprecated aliases and never invoked here.
button_norm = (button or "left").lower()
if button_norm not in {"left", "right", "middle"}:
return ActionResult(ok=False, action="click",
message=f"unknown button {button!r} — expected left, right, middle.")
tool = "double_click" if click_count == 2 else "click"
- args: Dict[str, Any] = {"pid": pid, "button": button_norm}
+ args: Dict[str, Any] = {"pid": self._active_pid, "button": button_norm}
if element is not None:
if self._active_window_id is None:
return ActionResult(ok=False, action=tool,
message="No active window_id for element_index click.")
args["element_index"] = element
- args["window_id"] = self._active_window_id
elif x is not None and y is not None:
if self._active_window_id is None:
return ActionResult(ok=False, action=tool,
message="No active window_id for coordinate click.")
args["x"] = x
args["y"] = y
- args["window_id"] = self._active_window_id
else:
- return ActionResult(ok=False, action=tool,
- message="click requires element= or x/y.")
+ return ActionResult(ok=False, action=tool, message="click requires element= or x/y.")
+ args["window_id"] = self._active_window_id
if modifiers:
args["modifier"] = modifiers
-
return self._run_input_action(tool, args, delivery_mode, bring_to_front)
def drag(
@@ -3571,28 +1378,26 @@ class CuaDriverBackend(ComputerUseBackend):
delivery_mode: Optional[str] = None,
bring_to_front: bool = False,
) -> ActionResult:
- pid = self._active_pid
- if pid is None:
- return ActionResult(ok=False, action="drag",
- message="No active window — call capture() first.")
- args: Dict[str, Any] = {"pid": pid}
+ missing = self._no_target("drag")
+ if missing is not None:
+ return missing
+ args: Dict[str, Any] = {"pid": self._active_pid}
if from_element is not None and to_element is not None:
if self._active_window_id is None:
return ActionResult(ok=False, action="drag",
message="No active window_id for element-based drag.")
args["from_element"] = from_element
args["to_element"] = to_element
- args["window_id"] = self._active_window_id
elif from_xy is not None and to_xy is not None:
if self._active_window_id is None:
return ActionResult(ok=False, action="drag",
message="No active window_id for coordinate drag.")
args["from_x"], args["from_y"] = int(from_xy[0]), int(from_xy[1])
args["to_x"], args["to_y"] = int(to_xy[0]), int(to_xy[1])
- args["window_id"] = self._active_window_id
else:
return ActionResult(ok=False, action="drag",
message="drag requires from_element/to_element or from_coordinate/to_coordinate.")
+ args["window_id"] = self._active_window_id
return self._run_input_action("drag", args, delivery_mode, bring_to_front)
def scroll(
@@ -3607,15 +1412,11 @@ class CuaDriverBackend(ComputerUseBackend):
delivery_mode: Optional[str] = None,
bring_to_front: bool = False,
) -> ActionResult:
- pid = self._active_pid
- if pid is None:
- return ActionResult(ok=False, action="scroll",
- message="No active window — call capture() first.")
- args: Dict[str, Any] = {
- "pid": pid,
- "direction": direction,
- "amount": max(1, min(50, amount)),
- }
+ missing = self._no_target("scroll")
+ if missing is not None:
+ return missing
+ args: Dict[str, Any] = {"pid": self._active_pid, "direction": direction,
+ "amount": max(1, min(50, amount))}
if element is not None and self._active_window_id is not None:
args["element_index"] = element
args["window_id"] = self._active_window_id
@@ -3623,15 +1424,10 @@ class CuaDriverBackend(ComputerUseBackend):
if self._active_window_id is None:
return ActionResult(ok=False, action="scroll",
message="No active window_id for coordinate scroll.")
- # CUA Driver 0.7.1 Linux schema rejects x/y on scroll. Only
- # include them when the driver explicitly advertises support
- # for coordinate scrolling; otherwise omit and let the driver
- # scroll the targeted window (window_id is still sent for
- # routing). This is the safe default when capabilities
- # haven't been discovered yet (older drivers).
- if self._session.supports_capability(
- "input.scroll.coordinates", tool="scroll"
- ):
+ # Some driver schemas reject x/y on scroll: only send coordinates
+ # when the driver advertises support; otherwise it scrolls the
+ # targeted window (window_id is still sent for routing).
+ if self._session.supports_capability("input.scroll.coordinates", tool="scroll"):
args["x"] = x
args["y"] = y
args["window_id"] = self._active_window_id
@@ -3640,54 +1436,39 @@ class CuaDriverBackend(ComputerUseBackend):
# ── Keyboard ───────────────────────────────────────────────────
def type_text(self, text: str, *, delivery_mode: Optional[str] = None,
bring_to_front: bool = False) -> ActionResult:
- pid = self._active_pid
- window_id = self._active_window_id
- if pid is None or window_id is None:
- return ActionResult(ok=False, action="type_text",
- message="No active window — call capture() first.")
- args: Dict[str, Any] = {"pid": pid, "window_id": window_id, "text": text}
+ missing = self._no_target("type_text", need_window=True)
+ if missing is not None:
+ return missing
+ args: Dict[str, Any] = {"pid": self._active_pid, "window_id": self._active_window_id, "text": text}
return self._run_input_action("type_text", args, delivery_mode, bring_to_front)
def key(self, keys: str, *, delivery_mode: Optional[str] = None,
bring_to_front: bool = False) -> ActionResult:
- pid = self._active_pid
- window_id = self._active_window_id
- if pid is None or window_id is None:
- return ActionResult(ok=False, action="key",
- message="No active window — call capture() first.")
-
+ missing = self._no_target("key", need_window=True)
+ if missing is not None:
+ return missing
key_name, modifiers = _parse_key_combo(keys)
if not key_name:
return ActionResult(ok=False, action="key",
message=f"Could not parse key from '{keys}'.")
-
- if modifiers:
- # hotkey requires at least one modifier + one key.
- args: Dict[str, Any] = {"pid": pid, "window_id": window_id,
- "keys": modifiers + [key_name]}
+ args: Dict[str, Any] = {"pid": self._active_pid, "window_id": self._active_window_id}
+ if modifiers: # hotkey requires at least one modifier + one key
+ args["keys"] = modifiers + [key_name]
return self._run_input_action("hotkey", args, delivery_mode, bring_to_front)
- else:
- args = {"pid": pid, "window_id": window_id, "key": key_name}
- return self._run_input_action("press_key", args, delivery_mode, bring_to_front)
+ args["key"] = key_name
+ return self._run_input_action("press_key", args, delivery_mode, bring_to_front)
# ── Value setter ────────────────────────────────────────────────
def set_value(self, value: str, element: Optional[int] = None) -> ActionResult:
"""Set a value on an element. Handles AXPopUpButton selects natively."""
- pid = self._active_pid
- window_id = self._active_window_id
- if pid is None or window_id is None:
- return ActionResult(ok=False, action="set_value",
- message="No active window — call capture() first.")
+ missing = self._no_target("set_value", need_window=True)
+ if missing is not None:
+ return missing
if element is None:
return ActionResult(ok=False, action="set_value",
message="set_value requires element= (element index).")
- args: Dict[str, Any] = {
- "pid": pid,
- "window_id": window_id,
- "element_index": element,
- "value": value,
- }
- return self._action("set_value", args)
+ return self._action("set_value", {"pid": self._active_pid, "window_id": self._active_window_id,
+ "element_index": element, "value": value})
# ── Introspection ──────────────────────────────────────────────
def list_apps(self) -> List[Dict[str, Any]]:
@@ -3695,22 +1476,20 @@ class CuaDriverBackend(ComputerUseBackend):
structured = out.get("structuredContent")
data = out.get("data")
- # structuredContent is the canonical MCP payload. Empty lists fall
- # through so a populated compatibility envelope can still recover.
+ # structuredContent is canonical; empty lists fall through so a
+ # populated compatibility envelope (older drivers, CLI fallback) can
+ # still recover.
if isinstance(structured, dict):
apps = structured.get("apps")
if isinstance(apps, list) and apps:
return apps
- # Older drivers and direct CLI fallbacks may put apps in data instead.
if isinstance(data, list) and data:
return data
- if isinstance(data, dict):
- apps = data.get("apps")
- if isinstance(apps, list) and apps:
- return apps
- apps = out.get("apps")
- if isinstance(apps, list) and apps:
- return apps
+ for container in (data, out):
+ if isinstance(container, dict):
+ apps = container.get("apps")
+ if isinstance(apps, list) and apps:
+ return apps
derived = _apps_from_windows(_windows_from_tool_result(out))
if derived:
@@ -3718,30 +1497,21 @@ class CuaDriverBackend(ComputerUseBackend):
# Old text-only drivers retain a small, name/PID-only fallback.
if isinstance(data, str):
- parsed_apps = []
- for line in data.splitlines():
- m = re.search(r'(.+?)\s+\(pid\s+(\d+)\)', line)
- if m:
- parsed_apps.append({"name": m.group(1).strip(), "pid": int(m.group(2))})
- return parsed_apps
+ return [
+ {"name": m.group(1).strip(), "pid": int(m.group(2))}
+ for m in (re.search(r'(.+?)\s+\(pid\s+(\d+)\)', line) for line in data.splitlines())
+ if m
+ ]
return []
def list_windows(self) -> List[Dict[str, Any]]:
return self._load_windows()
def focus_app(self, app: str, raise_window: bool = False) -> ActionResult:
- """Target an app, optionally invoking standalone foreground focus.
-
- cua-driver background-automation never needs to bring a window to the
- front: capture(app=...) already selects the right window via
- list_windows. We implement focus_app as a pure window-selector —
- enumerate on-screen windows, find the best match for *app*, and store
- its pid/window_id so that subsequent click/type calls hit the right
- process.
-
- The default remains non-disruptive. ``raise_window=True`` is explicit,
- separately approved by the Hermes adapter, and uses cua-driver's
- standalone ``bring_to_front`` tool rather than an action property.
+ """Target an app: a pure window-selector (store pid/window_id so later
+ input hits the right process) — background automation never needs to
+ raise a window. ``raise_window=True`` is explicit, separately approved,
+ and uses the standalone ``bring_to_front`` tool.
"""
try:
windows = self._load_windows()
@@ -3750,52 +1520,30 @@ class CuaDriverBackend(ComputerUseBackend):
raise
matched = self._match_windows_for_app(windows, app)
- # Don't silently fall back to the frontmost window when the filter
- # matches nothing — that hides the real failure (often a localized
- # macOS app name mismatch, e.g. caller passed "Calculator" but
- # list_windows returns "計算機").
- target = matched[0] if matched else None
- if target:
- self._active_pid = target["pid"]
- self._active_window_id = target["window_id"]
- self._snapshot_tokens = {}
- self._last_app = target["app_name"] or app # retained for back-compat diagnostics
- self._last_target = {
- "pid": self._active_pid,
- "window_id": self._active_window_id,
- }
- if raise_window:
- if not self._session._has_tool("bring_to_front"):
- return ActionResult(
- ok=False,
- action="focus_app",
- code="bring_to_front_unsupported",
- message="The connected cua-driver does not advertise the standalone bring_to_front tool.",
- )
- focused = self.bring_to_front(
- pid=self._active_pid,
- window_id=self._active_window_id,
- )
- if not focused.ok:
- return focused
- focused.action = "focus_app"
- focused.meta["target_selected"] = True
+ # No silent fallback to the frontmost window: that hides the real
+ # failure (often a localized macOS app-name mismatch).
+ if not matched:
+ self._clear_active_target()
+ return ActionResult(ok=False, action="focus_app",
+ message=f"No on-screen window found for app '{app}'.")
+ target = matched[0]
+ self._set_active_target(target)
+ self._last_app = target["app_name"] or app # retained for back-compat diagnostics
+ if raise_window:
+ if not self._session._has_tool("bring_to_front"):
+ return ActionResult(ok=False, action="focus_app", code="bring_to_front_unsupported",
+ message=_BTF_UNSUPPORTED_MSG)
+ focused = self.bring_to_front(pid=self._active_pid, window_id=self._active_window_id)
+ if not focused.ok:
return focused
- return ActionResult(
- ok=True, action="focus_app",
- message=f"Targeted {target['app_name']} (pid {self._active_pid}, "
- f"window {self._active_window_id}) without raising window.",
- )
- self._clear_active_target()
- return ActionResult(ok=False, action="focus_app",
- message=f"No on-screen window found for app '{app}'.")
+ focused.action = "focus_app"
+ focused.meta["target_selected"] = True
+ return focused
+ return ActionResult(ok=True, action="focus_app",
+ message=f"Targeted {target['app_name']} (pid {self._active_pid}, "
+ f"window {self._active_window_id}) without raising window.")
# ── App lifecycle ────────────────────────────────────────────────
- #
- # cua-driver exposes launch_app / kill_app / bring_to_front as a
- # complete set. focus_app() above is a *window-selector* (no
- # process state change); these methods drive the process layer.
-
def launch_app(
self,
*,
@@ -3805,98 +1553,30 @@ class CuaDriverBackend(ComputerUseBackend):
additional_arguments: Optional[List[str]] = None,
creates_new_application_instance: bool = False,
) -> Dict[str, Any]:
- """Idempotent launch. Returns ``{pid, bundle_id, name, windows[]}``
- so callers can skip an extra ``list_windows`` round-trip before
- ``get_window_state``.
-
- ``creates_new_application_instance=True`` forces a new instance
- even if the app is already running — use it when concurrent
- runs may touch the same app so each session gets its own
- isolated window."""
+ """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}
- if bundle_id:
- args["bundle_id"] = bundle_id
- if name:
- args["name"] = name
- if urls:
- args["urls"] = list(urls)
- if additional_arguments:
- args["additional_arguments"] = list(additional_arguments)
- if creates_new_application_instance:
- args["creates_new_application_instance"] = True
+ 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
out = self._session.call_tool("launch_app", args)
return out["structuredContent"] or {"data": out["data"]}
- def kill_app(self, *, pid: int) -> ActionResult:
- """Terminate by pid. Equivalent to ``kill -9`` on POSIX,
- ``taskkill /F`` on Windows."""
- return self._action("kill_app", {"pid": int(pid)})
-
- def bring_to_front(self, *, pid: int,
- window_id: Optional[int] = None) -> ActionResult:
- """Activate a window so subsequent foreground-dispatched input
- lands on it. cua-driver's docstring notes this is the cheaper
- path than per-call SetForegroundWindow flashes."""
+ 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 0.9-era schema is strict and deliberately has no session
- # property. It 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)
- # ── Pointer + display introspection ─────────────────────────────
-
- def move_cursor(self, x: int, y: int) -> ActionResult:
- """Move the agent-cursor *overlay* to a screen point. This is a
- visual hint — it does NOT move the real OS pointer (cua-driver
- explicitly avoids stealing pointer focus). The overlay glides
- smoothly to the target, so consumers use it before a click to
- give a visible "where the agent is going" cue."""
- return self._action("move_cursor", {"x": int(x), "y": int(y)})
-
- def get_cursor_position(self) -> Tuple[int, int]:
- """Return the *real* OS cursor position in screen points
- (origin top-left)."""
- out = self._session.call_tool(
- "get_cursor_position", {"session": self._session_id}
- )
- sc = out.get("structuredContent") or {}
- return int(sc.get("x", 0)), int(sc.get("y", 0))
-
- def get_screen_size(self) -> Dict[str, Any]:
- """Return the logical size of the main display in points plus
- its backing scale factor. Shape:
- ``{width, height, backing_scale_factor}``."""
- out = self._session.call_tool(
- "get_screen_size", {"session": self._session_id}
- )
- return out.get("structuredContent") or {}
-
- def zoom(self, *, window_id: int, x: float, y: float, w: float, h: float,
- factor: float = 1.0, format: str = "jpeg",
- quality: int = 85) -> Dict[str, Any]:
- """Return a JPEG / PNG of a sub-region of a window, optionally
- scaled. cua-driver supports zoom-to-rect for callers that need
- a higher-resolution view of a specific element."""
- return self._session.call_tool("zoom", {
- "window_id": int(window_id),
- "x": float(x), "y": float(y), "w": float(w), "h": float(h),
- "factor": float(factor),
- "format": format, "quality": int(quality),
- "session": self._session_id,
- })
-
- # ── Agent cursor (overlay) ──────────────────────────────────────
- #
- # Sessions (start_session/end_session, wired in start/stop) own the
- # cursor. These knobs tune its appearance + behavior per-session.
- # All accept an optional `cursor_id` to address a specific cursor
- # when the run drives multiple (rare); the default is this run's
- # session id.
-
+ # ── 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."""
@@ -3905,193 +1585,34 @@ class CuaDriverBackend(ComputerUseBackend):
args["cursor_id"] = cursor_id
return self._action("set_agent_cursor_enabled", args)
- def set_agent_cursor_motion(self, *,
- glide_ms: Optional[float] = None,
- dwell_ms: Optional[float] = None,
- idle_hide_ms: Optional[float] = None,
- cursor_id: Optional[str] = None) -> ActionResult:
- """Tune the overlay's motion timings — glide duration, post-click
- dwell, idle-hide delay. Each None means "leave at current value"."""
- args: Dict[str, Any] = {}
- if glide_ms is not None:
- args["glide_ms"] = float(glide_ms)
- if dwell_ms is not None:
- args["dwell_ms"] = float(dwell_ms)
- if idle_hide_ms is not None:
- args["idle_hide_ms"] = float(idle_hide_ms)
- if cursor_id:
- args["cursor_id"] = cursor_id
- return self._action("set_agent_cursor_motion", args)
-
- def set_agent_cursor_style(self, *,
- gradient_colors: Optional[List[str]] = None,
- bloom_color: Optional[str] = None,
- image_path: Optional[str] = None,
- cursor_id: Optional[str] = None) -> ActionResult:
- """Customise the cursor body. ``gradient_colors`` are CSS hex
- strings tip→tail; ``bloom_color`` is the radial halo; an
- ``image_path`` (.svg/.png/.ico) replaces the silhouette
- entirely. Empty values revert to the palette default."""
- args: Dict[str, Any] = {}
- if gradient_colors is not None:
- args["gradient_colors"] = list(gradient_colors)
- if bloom_color is not None:
- args["bloom_color"] = bloom_color
- if image_path is not None:
- args["image_path"] = image_path
- if cursor_id:
- args["cursor_id"] = cursor_id
- return self._action("set_agent_cursor_style", args)
-
- def get_agent_cursor_state(self, *,
- cursor_id: Optional[str] = None) -> Dict[str, Any]:
- """Return ``{x, y, config: {cursor_color, cursor_icon, ...},
- enabled}`` for this run's cursor (or the named ``cursor_id``)."""
- args: Dict[str, Any] = {"session": self._session_id}
- if cursor_id:
- args["cursor_id"] = cursor_id
- out = self._session.call_tool("get_agent_cursor_state", args)
- return out.get("structuredContent") or {}
-
- # ── Recording / replay ──────────────────────────────────────────
-
- def start_recording(self, *, output_dir: str,
- record_video: bool = False) -> Dict[str, Any]:
- """Enable trajectory recording (per-turn screenshots + action
- JSON) to ``output_dir``. ``record_video=True`` ALSO captures
- the main display to ``<output_dir>/recording.mp4`` (H.264).
- Recording ownership is keyed by this run's session id so
- concurrent runs don't fight over the recorder."""
- out = self._session.call_tool("start_recording", {
- "output_dir": output_dir,
- "record_video": bool(record_video),
- "session": self._session_id,
- })
- return out.get("structuredContent") or {}
-
- def stop_recording(self) -> Dict[str, Any]:
- """Disable recording and finalise the mp4 (if video was on).
- Returns the recorder's final state including ``last_video_path``."""
- out = self._session.call_tool("stop_recording", {
- "session": self._session_id,
- })
- return out.get("structuredContent") or {}
-
- def get_recording_state(self) -> Dict[str, Any]:
- """Return the current recorder state without changing it.
- Shape: ``{recording, enabled, output_dir, next_turn,
- last_video_path, last_error, owner, video_active}``."""
- out = self._session.call_tool(
- "get_recording_state", {"session": self._session_id}
- )
- return out.get("structuredContent") or {}
-
- def replay_trajectory(self, *, trajectory_dir: str,
- dry_run: bool = False,
- speed_factor: float = 1.0) -> Dict[str, Any]:
- """Replay a prior recording's turn stream by re-invoking each
- turn's tool call in lexical order. ``dry_run=True`` logs without
- actually firing the tools."""
- return self._session.call_tool("replay_trajectory", {
- "trajectory_dir": trajectory_dir,
- "dry_run": bool(dry_run),
- "speed_factor": float(speed_factor),
- "session": self._session_id,
- })
-
- def install_ffmpeg(self) -> Dict[str, Any]:
- """Bootstrap ffmpeg for ``start_recording(record_video=True)``
- on Linux / Windows. macOS records natively via ScreenCaptureKit
- and doesn't need ffmpeg."""
- return self._session.call_tool(
- "install_ffmpeg", {"session": self._session_id}
- )
-
- # ── Config ──────────────────────────────────────────────────────
-
- def get_config(self) -> Dict[str, Any]:
- """Return the current cua-driver runtime config."""
- out = self._session.call_tool(
- "get_config", {"session": self._session_id}
- )
- return out.get("structuredContent") or {}
-
def set_config(self, **config) -> ActionResult:
- """Set cua-driver config keys. Common keys include
- ``max_image_dimension`` (image-output resizing), recording
- flags, etc. Unknown keys are passed through verbatim — cua-driver
- validates against 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))
- # ── Lower-level introspection ───────────────────────────────────
-
- def get_accessibility_tree(self) -> Dict[str, Any]:
- """Return a lightweight snapshot of running regular apps +
- on-screen visible windows with bounds, z-order, owner pid.
- Roughly the data ``list_windows`` exposes, in one call. Most
- callers should prefer ``capture()`` / ``focus_app()`` which
- already use this shape internally."""
- out = self._session.call_tool(
- "get_accessibility_tree", {"session": self._session_id}
- )
- return out.get("structuredContent") or {"data": out["data"]}
-
- # ── Browser page tool ───────────────────────────────────────────
-
- def page(self, *, pid: int, action: str,
- **page_args: Any) -> Dict[str, Any]:
- """Interact with a browser page loaded in a running app (Chrome,
- Safari, Edge, ...). cua-driver routes through CDP / Apple Events
- / AX tree depending on the target. ``action`` + ``page_args``
- shape depends on the requested operation (e.g. ``action="eval"``
- takes ``js: str``); see cua-driver's ``page`` tool description
- for the full grammar."""
- args: Dict[str, Any] = {
- "pid": int(pid),
- "action": action,
- "session": self._session_id,
- }
- args.update(page_args)
- return self._session.call_tool("page", args)
-
# ── Generic escape hatch ────────────────────────────────────────
-
def call_tool(self, name: str, args: Optional[Dict[str, Any]] = None,
*, timeout: float = 30.0) -> Dict[str, Any]:
- """Call any cua-driver MCP tool by name with arbitrary args.
- ``session`` is injected (preserves the caller's explicit one
- via setdefault). For tools the wrapper doesn't already type-
- wrap, this is the supported escape hatch — preferred over
- reaching for ``self._session.call_tool`` directly because it
- keeps the session-id contract consistent with everything else."""
+ """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:
- """Surface 6: when the wrapper is about to call a token-capable
- tool with `element_index`, look up the matching `element_token`
- from the last snapshot and attach it. cua-driver-rs's contract
- for combined args is documented in trycua/cua#1961:
-
- "element_token takes precedence over element_index when both
- supplied. Returns an explicit 'stale' error if the snapshot
- has been superseded."
-
- Gated on the per-tool capability claim so we don't send the
- field to drivers that predate the surface (which would reject
- the schema with `additionalProperties: false`).
- """
+ """Attach the last snapshot's ``element_token`` for an ``element_index``
+ call. The token takes precedence and yields an explicit 'stale' error
+ when the snapshot was superseded. Gated on the per-tool capability so
+ older drivers (``additionalProperties: false``) never see the field."""
idx = args.get("element_index")
if not isinstance(idx, int):
return
token = self._snapshot_tokens.get(idx)
if not token:
return
- if not self._session.supports_capability(
- "accessibility.element_tokens", tool=tool
- ):
+ if not self._session.supports_capability("accessibility.element_tokens", tool=tool):
return
args["element_token"] = token
@@ -4102,13 +1623,8 @@ class CuaDriverBackend(ComputerUseBackend):
*,
inject_session: bool = True,
) -> ActionResult:
- # Attach the snapshot's element_token whenever the call carries
- # an element_index and the target tool advertises support.
self._maybe_attach_element_token(name, args)
- # Carry this run's session id so the cua-driver agent cursor
- # and per-session state (config overrides, recording ownership)
- # stay tied to this run. setdefault preserves any explicit
- # session a caller already supplied.
+ # setdefault preserves any explicit session a caller already supplied.
if inject_session:
args.setdefault("session", self._session_id)
try:
@@ -4126,8 +1642,8 @@ class CuaDriverBackend(ComputerUseBackend):
message = data
if not message and isinstance(structured, dict):
message = str(structured.get("message", ""))
- # Merge data + structuredContent into meta for debugging, structured
- # winning on key overlap (it is the canonical verdict surface).
+ # Merge data + structuredContent into meta, structured winning on
+ # overlap (it is the canonical verdict surface).
meta: Dict[str, Any] = {}
if isinstance(data, dict):
meta.update(data)
diff --git a/tools/computer_use/cua_backend_daemon.py b/tools/computer_use/cua_backend_daemon.py
new file mode 100644
index 00000000000..ba66e2a9430
--- /dev/null
+++ b/tools/computer_use/cua_backend_daemon.py
@@ -0,0 +1,306 @@
+"""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 logging
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import uuid
+from collections import deque
+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 cua-driver releases. Exact matches only: a suffixed
+# identifier or a different non-empty team is an impostor, not a variant.
+_CUA_DRIVER_BUNDLE_ID = "com.trycua.driver"
+_CUA_DRIVER_TEAM_IDS = ("4YEC26S9KF", "YCK386LBJ7")
+
+
+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:
+ a fallback candidate could be a DIFFERENT install than the one the
+ manifest resolved, running code the resolution chain never validated.
+ """
+ resolved_driver_cmd = os.path.realpath(driver_cmd)
+ marker = ".app/Contents/MacOS/"
+ marker_index = resolved_driver_cmd.find(marker)
+ if marker_index < 0:
+ return None
+ candidate = resolved_driver_cmd[: marker_index + len(".app")]
+ executable = os.path.join(candidate, "Contents", "MacOS", "cua-driver")
+ if os.path.isfile(executable) and os.access(executable, os.X_OK):
+ return candidate
+ return 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 require ``codesign -dv`` to 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
+
+ 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,
+ )
+ 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 = {}
+ for line in (proc.stderr or "").splitlines(): # codesign -dv reports on stderr
+ key, sep, value = line.partition("=")
+ if sep:
+ fields.setdefault(key.strip(), value.strip())
+ identifier = fields.get("Identifier", "")
+ team = 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:
+ return
+ if 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.)"
+ )
+
+
+def _embedded_daemon_spawn_command(
+ driver_cmd: str,
+ serve_args: List[str],
+ *,
+ platform: str,
+ app_path: Optional[str] = None,
+) -> List[str]:
+ """Build the private-daemon launch while preserving macOS TCC identity."""
+ if platform != "darwin":
+ 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.")
+ _validate_cua_driver_app_signature(resolved_app)
+ return ["/usr/bin/open", "-n", "-g", "-a", resolved_app, "--args", *serve_args]
+
+
+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;
+ the manifest, not a runtime prompt, is the authorization boundary.
+
+ 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`` — that pairing bounds an approval-bypassed run. It stays
+ mandatory for ``bounded`` and 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 only
+ # accept 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 = driver_cmd
+ self._command = driver_cmd
+ self._mcp_args: List[str] = list(_cb._CUA_DRIVER_ARGS)
+ self._process: Any = None
+ self._owns_runtime = False
+ self._running = False
+ self._launch_via_app = False
+ self._stderr_tail: deque[str] = deque(maxlen=20)
+ self._stderr_thread: Optional[threading.Thread] = None
+ token = uuid.uuid4().hex[:12]
+ if sys.platform == "win32":
+ self.socket_path = rf"\\.\pipe\hermes-cua-{token}"
+ else:
+ self.socket_path = 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
+ if self.permission_mode == "unrestricted":
+ env["CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS"] = "1"
+ return env
+
+ def _drain_stderr(self, process: Any) -> None:
+ stream = getattr(process, "stderr", None)
+ if stream is None:
+ return
+ try:
+ for line in stream:
+ 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")
+ if self.manifest_applies:
+ serve_args.extend([
+ "--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)
+
+ 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
+
+ if not self._driver_cmd:
+ self._driver_cmd = _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"
+ 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()
+
+ deadline = time.monotonic() + self._START_TIMEOUT_SECONDS
+ while time.monotonic() < deadline:
+ return_code = self._process.poll()
+ # `open` exits 0 as soon as 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}")
+ 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):
+ probe = None
+ if probe is not None and probe.returncode == 0:
+ 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}")
+
+ def proxy_invocation(self) -> Tuple[str, List[str]]:
+ if not self._running:
+ raise RuntimeError("embedded cua-driver daemon is not running")
+ return self._command, [*self._mcp_args, "--embedded", "--socket", self.socket_path]
+
+ def stop(self) -> None:
+ process = self._process
+ self._process = None
+ 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
+ if process is not None:
+ try:
+ process.wait(timeout=5.0)
+ except subprocess.TimeoutExpired:
+ process.terminate()
+ try:
+ process.wait(timeout=2.0)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=2.0)
+ if sys.platform != "win32" and os.path.exists(self.socket_path):
+ try:
+ os.remove(self.socket_path)
+ except OSError:
+ pass
diff --git a/tools/computer_use/cua_backend_parse.py b/tools/computer_use/cua_backend_parse.py
new file mode 100644
index 00000000000..ddf398c6742
--- /dev/null
+++ b/tools/computer_use/cua_backend_parse.py
@@ -0,0 +1,402 @@
+"""Pure parsing helpers for the cua-driver backend: MCP result flattening,
+``list_windows`` / ``get_window_state`` payload normalisation, key combos.
+
+No I/O, no module state — everything here is a function of its inputs, which
+is what makes it safe to share between the MCP and CLI transports.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Any, Dict, List, Optional, Tuple
+
+from tools.computer_use.backend import ActionResult, UIElement
+
+_MISSING = object()
+
+# Linux/X11 can surface GNOME Shell / desktop backdrop windows before real app
+# windows with no useful z-order. They are targetable X11 windows but capture
+# as empty through get_window_state, so default app capture must skip them.
+_NON_APP_WINDOW_TITLE_PREFIXES = (
+ "@!", # GNOME Shell background/monitor helper windows
+ "Desktop",
+ "gnome-shell",
+ "GNOME Shell",
+)
+
+_ELEMENT_LINE_RE = re.compile(
+ r'^\s*(?:-\s+)?\[(\d+)\]\s+(\w+)'
+ r'(?:'
+ r'\s*=\s*"([^"]*)"' # = "value"
+ r'|\s+"([^"]*)"' # "value"
+ r'|\s+\((?!\d+\))([^)]*)\)' # (value) but not a pure-digit (order) number
+ r')?'
+ r'(?:\s+(?:\(\d+\)\s+)?id=([^\s\[\]]+))?', # optional id=value (after an optional (order))
+ re.MULTILINE,
+)
+"""Element line of the get_window_state AX-tree markdown.
+
+cua-driver renders each actionable node as ``[N] AXRole`` followed by a label
+in one of four forms — ``= "value"``, ``"quoted"``, ``(paren)``, ``id=Label``
+(optionally after an ``(order)`` number). A parenthesised pure-digit group is
+an ORDER index, not a label, and is excluded so the id= label wins. Group 1 is
+the index, group 2 the role, groups 3-6 the label in whichever form matched.
+"""
+
+
+def _mcp_field(obj, snake: str, camel: str, default=None):
+ """Read an MCP model field across the 1.x -> 2.x rename.
+
+ mcp 2.0 exposes snake_case attributes and keeps camelCase only as a
+ serialization alias, so ``getattr(result, "isError", False)`` reads False
+ for every result on 2.x and a denied call would look like a success.
+ Deliberately duplicated from ``tools.mcp_tool.mcp_field`` so computer_use
+ never loads the much larger config-driven MCP client module.
+ """
+ value = getattr(obj, snake, _MISSING)
+ if value is not _MISSING:
+ return value
+ value = getattr(obj, camel, _MISSING)
+ return default if value is _MISSING else value
+
+
+def _action_result_from(
+ name: str,
+ ok: bool,
+ message: str,
+ meta: Dict[str, Any],
+ structured: Dict[str, Any],
+ *,
+ requested_delivery: Optional[str] = None,
+) -> ActionResult:
+ """Build an ActionResult, lifting cua-driver's structured verdict.
+
+ structuredContent is canonical, the flattened ``meta`` copy the fallback.
+ Every structured field is additive: a driver that omits one leaves the
+ attribute ``None`` so old drivers see unchanged behavior.
+ """
+ sc = structured if isinstance(structured, dict) else {}
+
+ def _pick(key: str) -> Any:
+ return sc.get(key) if key in sc else meta.get(key)
+
+ def _typed(value: Any, typ) -> Any:
+ return value if isinstance(value, typ) else None
+
+ return ActionResult(
+ ok=ok,
+ action=name,
+ message=message,
+ meta=meta,
+ verified=_typed(_pick("verified"), bool),
+ effect=_typed(_pick("effect"), str),
+ escalation=_typed(_pick("escalation"), dict),
+ path=_typed(_pick("path"), str),
+ degraded=_typed(_pick("degraded"), bool),
+ # What we asked for; the driver's `path` records the rung that ran.
+ delivery_mode=_typed(requested_delivery, str),
+ # Refusal/limitation code — drivers spell it "code" or "reason_code".
+ code=_typed(_pick("code") or _pick("reason_code"), str),
+ )
+
+
+def _z_index_uninformative(windows: List[Dict[str, Any]]) -> bool:
+ """True when every window shares the same z_index (common on Linux/X11)."""
+ if not windows:
+ return True
+ return len({w.get("z_index", 0) for w in windows}) <= 1
+
+
+def _parse_xprop_net_active_window(stdout: str) -> Optional[int]:
+ """Parse ``xprop -root _NET_ACTIVE_WINDOW`` stdout into a window id.
+
+ Accepts the ``window id # 0x...`` form, falling back to the first hex token.
+ """
+ text = stdout or ""
+ match = re.search(r"window id # (0x[0-9a-fA-F]+)", text) or re.search(r"(0x[0-9a-fA-F]+)", text)
+ if not match:
+ return None
+ try:
+ return int(match.group(1), 16)
+ except ValueError:
+ return None
+
+
+def _is_real_app_window(w: Dict[str, Any]) -> bool:
+ """Return False for desktop/shell helper windows that capture as empty."""
+ title = w.get("title", "")
+ return not any(
+ title.startswith(p) or title.lower().startswith(p.lower())
+ for p in _NON_APP_WINDOW_TITLE_PREFIXES
+ )
+
+
+def _parse_elements_from_tree(markdown: str) -> List[UIElement]:
+ """Parse UIElements from get_window_state AX-tree markdown.
+
+ Last-resort fallback for drivers without ``structuredContent.elements``.
+ Bounds always come back ``(0, 0, 0, 0)`` — the markdown carries none —
+ which is fine for element-index clicks (the driver resolves the frame).
+ """
+ return [
+ UIElement(
+ index=int(m.group(1)),
+ role=m.group(2),
+ # groups 3-6: value / quoted / paren / id= label (first non-None wins)
+ label=m.group(3) or m.group(4) or m.group(5) or m.group(6) or "",
+ bounds=(0, 0, 0, 0),
+ )
+ for m in _ELEMENT_LINE_RE.finditer(markdown)
+ ]
+
+
+def _parse_elements_from_structured(raw_elements: List[Dict[str, Any]]) -> List[UIElement]:
+ """Read the canonical ``structuredContent.elements`` array.
+
+ Each entry has ``element_index``, ``role``, ``label`` and, when the AT-SPI /
+ AXFrame call returned usable bounds, ``frame`` ``{x, y, w, h}`` — so real
+ pixel bounds survive (the markdown path loses them). Malformed entries are
+ skipped rather than failing the whole walk.
+ """
+ elements: List[UIElement] = []
+ for raw in raw_elements:
+ if not isinstance(raw, dict):
+ continue
+ idx = raw.get("element_index")
+ if not isinstance(idx, int):
+ continue
+ role = raw.get("role") if isinstance(raw.get("role"), str) else ""
+ label = raw.get("label") if isinstance(raw.get("label"), str) else ""
+ frame = raw.get("frame") if isinstance(raw.get("frame"), dict) else None
+ bounds: Tuple[int, int, int, int] = (0, 0, 0, 0)
+ if frame:
+ try:
+ bounds = tuple(int(frame.get(k, 0)) for k in ("x", "y", "w", "h")) # type: ignore[assignment]
+ except (TypeError, ValueError):
+ bounds = (0, 0, 0, 0)
+ # Opaque element_token (`s{snapshot_hex}:{index}`) — the driver owns
+ # the parse + LRU semantics; we treat it as a black-box string.
+ raw_token = raw.get("element_token")
+ elements.append(UIElement(
+ index=idx,
+ role=role,
+ label=label,
+ bounds=bounds,
+ element_token=raw_token if isinstance(raw_token, str) and raw_token else None,
+ ))
+ return elements
+
+
+def _image_dimensions_from_bytes(raw: bytes) -> Tuple[int, int]:
+ """Best-effort PNG/JPEG dimension sniffing without extra dependencies."""
+ if raw.startswith(b"\x89PNG\r\n\x1a\n") and len(raw) >= 24:
+ width = int.from_bytes(raw[16:20], "big")
+ height = int.from_bytes(raw[20:24], "big")
+ if width > 0 and height > 0:
+ return width, height
+
+ if raw.startswith(b"\xff\xd8"):
+ i = 2
+ n = len(raw)
+ while i + 9 < n:
+ if raw[i] != 0xFF:
+ i += 1
+ continue
+ marker = raw[i + 1]
+ i += 2
+ if marker in {0xD8, 0xD9} or 0xD0 <= marker <= 0xD7:
+ continue
+ if i + 2 > n:
+ break
+ segment_len = int.from_bytes(raw[i:i + 2], "big")
+ if segment_len < 2 or i + segment_len > n:
+ break
+ if marker in {
+ 0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,
+ 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF,
+ }:
+ if segment_len >= 7:
+ height = int.from_bytes(raw[i + 3:i + 5], "big")
+ width = int.from_bytes(raw[i + 5:i + 7], "big")
+ if width > 0 and height > 0:
+ return width, height
+ break
+ i += segment_len
+
+ return 0, 0
+
+
+def _split_tree_text(full_text: str) -> Tuple[str, str]:
+ """Split get_window_state text into (summary_line, tree_markdown)."""
+ summary, _, tree = full_text.partition("\n")
+ return summary, tree
+
+
+_MODIFIER_NAMES = frozenset({"cmd", "command", "shift", "option", "alt", "ctrl", "control", "fn"})
+_KEY_ALIASES = {"command": "cmd", "alt": "option", "control": "ctrl"}
+
+
+def _parse_key_combo(keys: str) -> Tuple[Optional[str], List[str]]:
+ """Parse 'cmd+s' / 'ctrl-alt-t' into (key, modifiers); last non-modifier wins."""
+ modifiers: List[str] = []
+ key = None
+ for part in (p.strip().lower() for p in re.split(r'[+\-]', keys) if p.strip()):
+ normalized = _KEY_ALIASES.get(part, part)
+ if normalized in _MODIFIER_NAMES:
+ modifiers.append(normalized)
+ else:
+ key = part
+ return key, modifiers
+
+
+def _extract_tool_result(mcp_result: Any) -> Dict[str, Any]:
+ """Flatten an mcp CallToolResult into
+ ``{data, images, image_mime_types, structuredContent, isError}``.
+
+ ``data`` is the joined text parts (parsed as JSON when it looks like JSON);
+ ``image_mime_types`` is parallel to ``images`` with ``""`` where the part
+ carried no mimeType (older drivers — callers then sniff the base64 prefix).
+ """
+ data: Any = None
+ images: List[str] = []
+ image_mime_types: List[str] = []
+ # Identity, not truthiness: mocks/proxies synthesize truthy attributes.
+ is_error = _mcp_field(mcp_result, "is_error", "isError", False) is True
+ structured: Optional[Dict] = (
+ _mcp_field(mcp_result, "structured_content", "structuredContent") or None
+ )
+ text_chunks: List[str] = []
+ for part in getattr(mcp_result, "content", []) or []:
+ ptype = getattr(part, "type", None)
+ if ptype == "text":
+ text_chunks.append(getattr(part, "text", "") or "")
+ elif ptype == "image":
+ b64 = getattr(part, "data", None)
+ if b64:
+ images.append(b64)
+ image_mime_types.append(_mcp_field(part, "mime_type", "mimeType") or "")
+ if text_chunks:
+ joined = "\n".join(t for t in text_chunks if t)
+ try:
+ data = json.loads(joined) if joined.strip().startswith(("{", "[")) else joined
+ except json.JSONDecodeError:
+ data = joined
+ return {
+ "data": data,
+ "images": images,
+ "image_mime_types": image_mime_types,
+ "structuredContent": structured,
+ "isError": is_error,
+ }
+
+
+def _image_from_tool_result(out: Dict[str, Any]) -> tuple[Optional[str], Optional[str]]:
+ """Pull ``(b64, mime_type)`` out of a flattened tool result.
+
+ cua-driver delivers screenshots either as an MCP ``image`` part
+ (``out["images"]``) or as ``screenshot_png_b64`` inside structuredContent
+ (newer builds, and the CLI transport); checking both keeps capture()
+ robust when the driver moves the image between the two.
+ """
+ images = out.get("images") or []
+ if images and images[0]:
+ mimes = out.get("image_mime_types") or []
+ return images[0], (mimes[0] if mimes and mimes[0] else None)
+ structured = out.get("structuredContent") or {}
+ b64 = structured.get("screenshot_png_b64") or structured.get("png_b64")
+ if b64:
+ return b64, (structured.get("screenshot_mime_type") or structured.get("mime_type") or None)
+ return None, None
+
+
+def _positive_int(value: Any) -> Optional[int]:
+ """Return a positive integer, rejecting booleans and malformed values."""
+ if isinstance(value, bool) or not isinstance(value, (int, str)):
+ return None
+ try:
+ parsed = int(value)
+ except ValueError:
+ return None
+ return parsed if parsed > 0 else None
+
+
+def _is_placeholder_id(value: Any) -> bool:
+ """True when *value* is a schema-filler id (``0`` / negative) rather than a target.
+
+ Some providers emit every optional integer zero-filled; treating that as a
+ targeting request would drop the caller's ``app=``. Non-numeric values are
+ NOT placeholders — they still reach the validation error.
+ """
+ if isinstance(value, bool) or not isinstance(value, (int, str)):
+ return False
+ try:
+ return int(value) <= 0
+ except ValueError:
+ return False
+
+
+def _ingest_windows(raw_windows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ """Normalise cua-driver ``list_windows`` entries, dropping unusable ones.
+
+ Every downstream call needs an integer ``pid`` and ``window_id``. On X11
+ the PID comes from the optional ``_NET_WM_PID`` property, so root/panel/
+ popup windows report ``pid: null`` — skip those instead of aborting the
+ whole enumeration. ``z_index``: higher = closer to front; Wayland's null
+ (undefined stacking) sorts lowest so real windows stay above the desktop.
+ """
+ windows: List[Dict[str, Any]] = []
+ for w in raw_windows:
+ if not isinstance(w, dict): # untrusted compatibility envelopes
+ continue
+ pid_int = _positive_int(w.get("pid"))
+ window_id_int = _positive_int(w.get("window_id"))
+ if pid_int is None or window_id_int is None:
+ continue
+ z_raw = w.get("z_index")
+ app_name = w.get("app_name", "")
+ title = w.get("title", "")
+ windows.append({
+ "app_name": app_name if isinstance(app_name, str) else "",
+ "pid": pid_int,
+ "window_id": window_id_int,
+ # Only explicit False means off-screen; null (Linux 0.6.x) means unknown.
+ "off_screen": w.get("is_on_screen") is False,
+ "title": title if isinstance(title, str) else "",
+ "z_index": z_raw if isinstance(z_raw, (int, float)) and not isinstance(z_raw, bool) else 0,
+ })
+ return windows
+
+
+def _first_nonempty_list(*containers: Any, keys: Tuple[str, ...]) -> List[Any]:
+ for container in containers:
+ if not isinstance(container, dict):
+ continue
+ for key in keys:
+ value = container.get(key)
+ if isinstance(value, list) and value:
+ return value
+ return []
+
+
+def _windows_from_tool_result(out: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Return list_windows payloads across cua-driver result shapes."""
+ structured = out.get("structuredContent")
+ if isinstance(structured, dict):
+ windows = structured.get("windows")
+ if isinstance(windows, list) and windows:
+ return windows
+ return _first_nonempty_list(out.get("data"), out, keys=("windows", "_legacy_windows"))
+
+
+def _apps_from_windows(windows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ apps: List[Dict[str, Any]] = []
+ seen: set[tuple[str, int]] = set()
+ for summary in _ingest_windows(windows):
+ name = summary["app_name"]
+ key = (name, summary["pid"])
+ if not name or key in seen:
+ continue
+ seen.add(key)
+ apps.append({"name": name, "pid": summary["pid"]})
+ return apps
diff --git a/tools/computer_use/cua_backend_session.py b/tools/computer_use/cua_backend_session.py
new file mode 100644
index 00000000000..a84023bfbca
--- /dev/null
+++ b/tools/computer_use/cua_backend_session.py
@@ -0,0 +1,691 @@
+"""cua-driver MCP session plumbing: the asyncio bridge thread and the
+lazily-started, self-healing ``_CuaDriverSession`` (MCP transport with a
+``cua-driver call`` CLI fallback).
+
+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 asyncio
+import base64
+import concurrent.futures
+import json
+import logging
+import os
+import threading
+from typing import Any, Dict, List, Optional
+
+from tools.computer_use.cua_backend_parse import _extract_tool_result, _mcp_field
+
+logger = logging.getLogger("tools.computer_use.cua_backend")
+
+
+class _AsyncBridge:
+ """Runs one asyncio loop on a daemon thread; marshals coroutines from the caller."""
+
+ def __init__(self) -> None:
+ self._loop: Optional[asyncio.AbstractEventLoop] = None
+ self._thread: Optional[threading.Thread] = None
+ self._ready = threading.Event()
+
+ def start(self) -> None:
+ if self._thread and self._thread.is_alive():
+ return
+ self._ready.clear()
+
+ def _run() -> None:
+ self._loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(self._loop)
+ self._ready.set()
+ try:
+ self._loop.run_forever()
+ finally:
+ try:
+ self._loop.close()
+ except Exception:
+ pass
+
+ self._thread = threading.Thread(target=_run, daemon=True, name="cua-driver-loop")
+ self._thread.start()
+ if not self._ready.wait(timeout=5.0):
+ raise RuntimeError("cua-driver asyncio bridge failed to start")
+
+ def run(self, coro, timeout: Optional[float] = 30.0) -> Any:
+ from agent.async_utils import safe_schedule_threadsafe
+ if not self._loop or not self._thread or not self._thread.is_alive():
+ if asyncio.iscoroutine(coro):
+ coro.close()
+ raise RuntimeError("cua-driver bridge not started")
+ fut = safe_schedule_threadsafe(coro, self._loop)
+ if fut is None:
+ raise RuntimeError("cua-driver bridge not started")
+ return fut.result(timeout=timeout)
+
+ def stop(self) -> None:
+ if self._loop and self._loop.is_running():
+ self._loop.call_soon_threadsafe(self._loop.stop)
+ if self._thread:
+ self._thread.join(timeout=2.0)
+ self._thread = None
+ self._loop = None
+
+
+def _outcome_unknown(name: str, exc: Exception, code: str, message: str) -> Dict[str, Any]:
+ """Fail-closed result for a call whose effect on the remote screen is unknown."""
+ return {
+ "data": message,
+ "images": [],
+ "image_mime_types": [],
+ "structuredContent": {
+ "ok": False,
+ "code": code,
+ "message": message,
+ "operation": name,
+ "next_step": "fresh_state",
+ "detail": str(exc),
+ },
+ "isError": True,
+ }
+
+
+class _CuaDriverSession:
+ """Holds the mcp ClientSession. Spawned lazily; re-entered on drop.
+
+ Lifecycle ownership: one long-running coroutine (`_lifecycle_coro`) opens
+ the stdio_client and ClientSession contexts, populates capabilities, sets
+ `_ready_event`, then waits on `_shutdown_event` and closes the contexts —
+ enter and exit in the SAME task, which anyio's cancel-scope invariant
+ requires (the bridge schedules each `bridge.run(coro)` as a NEW task).
+ Tool calls run in their own short-lived tasks and only touch the session
+ object, never the surrounding contexts.
+ """
+
+ # Handshake calls issued BY start()/stop() themselves — must not trigger
+ # the auto-restart guard in call_tool, or start() would recurse.
+ _LIFECYCLE_CALLS = frozenset({"start_session", "end_session"})
+
+ # Safe to replay after a broken transport: no side effect or idempotent.
+ # Mutations stay out — a lost response does not prove they failed.
+ _TRANSPORT_REPLAY_SAFE_TOOLS = frozenset({
+ "get_cursor_position",
+ "get_displays",
+ "get_screen_size",
+ "get_window_state",
+ "list_apps",
+ "list_windows",
+ })
+
+ # Set when an MCP call timed out: a timed-out session is wedged for later
+ # calls, so it is recreated before the next non-lifecycle call_tool.
+ # Class-level default so tests that bypass __init__ see a healthy session.
+ _timeout_suspect = False
+
+ def __init__(self, bridge: _AsyncBridge, embedded_daemon: Optional[Any] = None) -> None:
+ self._bridge = bridge
+ self._embedded_daemon = embedded_daemon
+ self._session = None
+ self._lock = threading.Lock()
+ self._started = False
+ # Per-tool capability-token sets from `tools/list` (e.g. "click" ->
+ # {"accessibility.element_tokens", ...}). Empty until the session
+ # starts; consumers call `supports_capability` rather than reading it.
+ self._capabilities: Dict[str, set] = {}
+ # Raw input schemas are the source of truth for action properties:
+ # 0.9-era drivers advertise delivery_mode in inputSchema while
+ # omitting the old fabricated ``input.delivery_mode`` capability token.
+ self._tool_schemas: Dict[str, Dict[str, Any]] = {}
+ self._capability_version: str = ""
+ self._ready_event = threading.Event()
+ self._shutdown_event: Optional[asyncio.Event] = None # created on bridge loop
+ self._lifecycle_future = None # concurrent.futures.Future
+ self._setup_error: Optional[BaseException] = None
+ # Stable driver-side identity declared through start_session; used to
+ # revive a logical ended-session rejection without re-entrant call_tool.
+ self._declared_session_id: Optional[str] = None
+ self._transport_generation = 0
+ self._transport_reset_callback: Optional[Any] = None
+
+ def _require_started(self) -> None:
+ if not self._started:
+ raise RuntimeError("cua-driver session not started")
+
+ async def _lifecycle_coro(self) -> None:
+ """Long-lived owner of the stdio MCP contexts: open, signal ready,
+ block on shutdown, clean up — all in one task (see class docstring)."""
+ import time as _time
+ from mcp import ClientSession, StdioServerParameters
+ from mcp.client.stdio import stdio_client
+ from tools.computer_use import cua_backend as _cb
+ from tools.environments.local import _sanitize_subprocess_env
+
+ # Built on the loop's thread so the primitive belongs to this loop.
+ self._shutdown_event = asyncio.Event()
+ _t0 = _time.monotonic()
+ # Phase marker surfaced by the ready-timeout error so a wedged startup
+ # reports HOW FAR it got instead of an opaque "never reached ready".
+ self._startup_phase = "binary-check"
+
+ try:
+ driver_cmd = _cb.resolve_cua_driver_cmd()
+ if not driver_cmd:
+ raise RuntimeError(_cb.cua_driver_install_hint())
+
+ self._startup_phase = "manifest-discovery"
+ if self._embedded_daemon is not None:
+ command, args = self._embedded_daemon.proxy_invocation()
+ child_env = self._embedded_daemon.child_env()
+ else:
+ command, args = _cb._resolve_mcp_invocation(driver_cmd)
+ child_env = _cb.cua_driver_child_env()
+ _t_manifest = _time.monotonic()
+ # Telemetry policy first (default: disabled), then strip Hermes secrets.
+ params = StdioServerParameters(command=command, args=args,
+ env=_sanitize_subprocess_env(child_env))
+
+ async with stdio_client(params) as (read, write):
+ self._startup_phase = "mcp-initialize"
+ async with ClientSession(read, write) as session:
+ await session.initialize()
+ _t_init = _time.monotonic()
+ # Populate capabilities BEFORE exposing the session so
+ # the first tool call already sees them.
+ self._startup_phase = "capability-discovery"
+ await self._populate_capabilities(session)
+ self._session = session
+ self._startup_phase = "ready"
+ self._ready_event.set()
+ logger.info("cua-driver session ready in %.1fs (manifest=%.1fs, mcp_init=%.1fs)",
+ _time.monotonic() - _t0, _t_manifest - _t0, _t_init - _t_manifest)
+ await self._shutdown_event.wait()
+ except BaseException as e:
+ # Ordinary errors and anyio CancelledError alike: start()
+ # inspects this to surface setup failures synchronously.
+ self._setup_error = e
+ self._ready_event.set()
+ raise
+ finally:
+ self._session = None
+ # A session that dies for ANY reason (MCP drop, driver crash,
+ # unexpected exit) must be re-enterable: the next call sees
+ # _started False and rebuilds instead of hanging on a dead one.
+ # Plain bool write is atomic, so no lock needed here (stop() may
+ # hold self._lock while awaiting this coro's future).
+ self._started = False
+
+ async def _populate_capabilities(self, session: Any) -> None:
+ """Cache per-tool capability sets, input schemas and capability_version
+ from tools/list. Soft prerequisite — on failure the map stays empty and
+ supports_capability degrades to False."""
+ self._capabilities = {}
+ self._tool_schemas = {}
+ self._capability_version = ""
+
+ def _field(obj: Any, name: str) -> Any:
+ # Some MCP SDKs forward custom fields via `model_extra` (Pydantic v2).
+ value = getattr(obj, name, None)
+ if value is None:
+ value = (getattr(obj, "model_extra", None) or {}).get(name)
+ return value
+
+ try:
+ tools_list = await session.list_tools()
+ for tool in getattr(tools_list, "tools", []) or []:
+ tool_name = getattr(tool, "name", None)
+ if not isinstance(tool_name, str):
+ continue
+ caps = _field(tool, "capabilities")
+ self._capabilities[tool_name] = (
+ {c for c in caps if isinstance(c, str)} if isinstance(caps, list) else set()
+ )
+ schema = _mcp_field(tool, "input_schema", "inputSchema")
+ if schema is None:
+ schema = (getattr(tool, "model_extra", None) or {}).get("inputSchema")
+ self._tool_schemas[tool_name] = dict(schema) if isinstance(schema, dict) else {}
+ # capability_version is a top-level sibling of `tools` on the
+ # tools/list response (cua-driver leaves it OUT of initialize).
+ cv = _field(tools_list, "capability_version")
+ if isinstance(cv, str):
+ self._capability_version = cv
+ except Exception as e:
+ logger.debug("cua-driver tools/list capability discovery failed: %s", e)
+
+ def start(self) -> None:
+ with self._lock:
+ if self._started:
+ return
+ self._bridge.start()
+ self._start_lifecycle_locked()
+ self._started = True
+
+ def _start_lifecycle_locked(self) -> None:
+ """Spawn the lifecycle owner and wait for ready. Caller holds self._lock."""
+ self._ready_event = threading.Event()
+ self._setup_error = None
+ self._shutdown_event = None
+ # The future tracks the WHOLE lifecycle (open -> wait -> close);
+ # readiness is signalled separately via _ready_event.
+ loop = self._bridge._loop
+ if loop is None:
+ raise RuntimeError("cua-driver bridge not started")
+ self._lifecycle_future = asyncio.run_coroutine_threadsafe(self._lifecycle_coro(), loop)
+ if not self._ready_event.wait(timeout=30.0):
+ self._signal_shutdown_locked()
+ phase = getattr(self, "_startup_phase", "unknown")
+ from hermes_constants import display_hermes_home
+ raise RuntimeError(
+ "cua-driver session never reached ready (timeout 30s; "
+ f"stuck in phase: {phase}). "
+ "Run `hermes computer-use doctor` and check "
+ f"{display_hermes_home()}/logs/agent.log for the phase timings."
+ )
+ if self._setup_error is not None:
+ raise RuntimeError(f"cua-driver session setup failed: {self._setup_error}") from self._setup_error
+ self._transport_generation += 1
+ if self._transport_generation > 1:
+ self._notify_transport_reset()
+
+ def stop(self) -> None:
+ with self._lock:
+ if not self._started:
+ return
+ self._started = False
+ self._stop_lifecycle_locked()
+
+ def set_transport_reset_callback(self, callback: Any) -> None:
+ """Register a synchronous cache invalidation hook for transport swaps."""
+ self._transport_reset_callback = callback
+
+ def _notify_transport_reset(self) -> None:
+ callback = getattr(self, "_transport_reset_callback", None)
+ if callback is None:
+ return
+ try:
+ callback()
+ except Exception as exc:
+ logger.debug("cua-driver transport reset callback failed: %s", exc)
+
+ def _stop_lifecycle_locked(self) -> None:
+ """Signal shutdown and wait (5s) for the lifecycle coroutine to unwind."""
+ self._signal_shutdown_locked()
+ fut = self._lifecycle_future
+ if fut is None:
+ return
+ try:
+ fut.result(timeout=5.0)
+ except concurrent.futures.TimeoutError:
+ logger.warning("cua-driver session shutdown timed out (5s)")
+ except Exception as e:
+ logger.warning("cua-driver shutdown error: %s", e)
+ finally:
+ self._lifecycle_future = None
+
+ def _signal_shutdown_locked(self) -> None:
+ """Set the asyncio shutdown event from the caller's thread."""
+ loop = self._bridge._loop
+ event = self._shutdown_event
+ if loop is not None and event is not None and loop.is_running():
+ try:
+ loop.call_soon_threadsafe(event.set)
+ except RuntimeError: # loop closed — nothing to signal
+ pass
+
+ async def _call_tool_async(self, name: str, args: Dict[str, Any]) -> Dict[str, Any]:
+ result = await self._session.call_tool(name, args)
+ return _extract_tool_result(result)
+
+ def _run_call(self, name: str, args: Dict[str, Any], timeout: float) -> Dict[str, Any]:
+ return self._bridge.run(self._call_tool_async(name, args), timeout=timeout)
+
+ # ── Capability detection ─────────────────────────────────────────
+ def supports_capability(self, capability: str, tool: Optional[str] = None) -> bool:
+ """True when the driver advertises *capability* — for *tool* when given,
+ otherwise on ANY tool. Always False before the session started."""
+ if tool is not None:
+ return capability in self._capabilities.get(tool, set())
+ return any(capability in caps for caps in self._capabilities.values())
+
+ def _has_tool(self, name: str) -> bool:
+ """True when ``tools/list`` advertised *name*.
+
+ Routes capture(): cua-driver dropped the standalone ``screenshot``
+ tool and folded PNG capture into ``get_window_state``. False before
+ discovery populated the map — callers treat that as "unknown".
+ """
+ return name in self._capabilities
+
+ def supports_input_property(self, tool: str, property_name: str) -> bool:
+ """Whether the live action schema accepts *property_name* (fails closed).
+ Inspects tools/list rather than guessing from the package version."""
+ schema = getattr(self, "_tool_schemas", {}).get(tool, {})
+ properties = schema.get("properties") if isinstance(schema, dict) else None
+ return isinstance(properties, dict) and property_name in properties
+
+ @property
+ def capabilities_discovered(self) -> bool:
+ """True once tools/list populated the map; when False, ``_has_tool``
+ answers are untrustworthy and capture() should probe defensively."""
+ return bool(self._capabilities)
+
+ @property
+ def capability_version(self) -> str:
+ """Driver-advertised capability vocabulary version ("" on old builds)."""
+ return self._capability_version
+
+ # ── Error classification ─────────────────────────────────────────
+ @staticmethod
+ def _logical_error_text(result: Dict[str, Any]) -> str:
+ """Flatten a logical MCP error into text for narrow classification."""
+ chunks: List[str] = []
+ for value in (result.get("data"), result.get("structuredContent")):
+ if isinstance(value, str):
+ chunks.append(value)
+ elif value is not None:
+ try:
+ chunks.append(json.dumps(value, sort_keys=True))
+ except (TypeError, ValueError):
+ chunks.append(str(value))
+ return "\n".join(chunks)
+
+ @classmethod
+ def _is_ended_session_result(cls, result: Any) -> bool:
+ """Recognise cua-driver's explicit recoverable ended-session result."""
+ if not isinstance(result, dict) or result.get("isError") is not True:
+ return False
+ message = cls._logical_error_text(result).lower()
+ return (
+ "session" in message
+ and ("has ended" in message or "session ended" in message)
+ and "start_session" in message
+ )
+
+ @staticmethod
+ def _is_closed_session_error(exc: Exception) -> bool:
+ """True for MCP/stdio failures that are recoverable by reconnecting."""
+ name = exc.__class__.__name__
+ module = getattr(exc.__class__, "__module__", "")
+ return (
+ name in {"ClosedResourceError", "BrokenResourceError", "EndOfStream"}
+ or (module.startswith("anyio") and "Resource" in name)
+ or isinstance(exc, (BrokenPipeError, EOFError))
+ )
+
+ @staticmethod
+ def _is_transient_daemon_error(exc: Exception) -> bool:
+ """True for the daemon-proxy EAGAIN congestion error.
+
+ On macOS the ``cua-driver mcp`` bridge forwards calls to the daemon
+ over a non-blocking unix socket; heavy ops (``get_window_state``)
+ can fail with ``Resource temporarily unavailable (os error 35)`` when
+ the buffer is momentarily full. The same call succeeds on retry, so
+ we back off / fall back instead of surfacing an empty 0x0 capture.
+ """
+ msg = str(exc)
+ return (
+ "Resource temporarily unavailable" in msg
+ or "os error 35" in msg
+ or "daemon transport error" in msg
+ or "daemon proxy" in msg
+ )
+
+ @classmethod
+ def _transport_replay_is_safe(cls, name: str) -> bool:
+ return name in cls._TRANSPORT_REPLAY_SAFE_TOOLS
+
+ @staticmethod
+ def _unknown_transport_outcome(name: str, exc: Exception) -> Dict[str, Any]:
+ return _outcome_unknown(
+ name, exc, "transport_outcome_unknown",
+ f"cua-driver transport failed during {name}; the action outcome is "
+ "unknown, so Hermes did not replay it. Take fresh state before "
+ "deciding whether to act again.",
+ )
+
+ @staticmethod
+ def _timeout_outcome(name: str, exc: Exception) -> Dict[str, Any]:
+ """Fail-closed result for an MCP call that hit its deadline. The action
+ MAY have landed, so it is never replayed here; the caller decides after
+ taking fresh state."""
+ return _outcome_unknown(
+ name, exc, "timeout_outcome_unknown",
+ f"cua-driver MCP call {name} timed out; the action outcome is "
+ "unknown and may still have taken effect on the remote screen. "
+ "The session has been marked suspect and will be recreated before "
+ "the next computer-use call. Take fresh state before deciding "
+ "whether to act again.",
+ )
+
+ # ── Recovery ─────────────────────────────────────────────────────
+ def _revive_declared_session_once(
+ self,
+ name: str,
+ args: Dict[str, Any],
+ first_result: Dict[str, Any],
+ timeout: float,
+ ) -> Dict[str, Any]:
+ """Revive the stable session and replay one rejected tool call once.
+ A second rejection is surfaced as-is; no loop."""
+ session_id = self._declared_session_id
+ if not session_id or name in self._LIFECYCLE_CALLS:
+ return first_result
+ logger.warning("cua-driver session %s ended during %s; reviving and retrying once",
+ session_id, name)
+ revive_result = self._run_call("start_session", {"session": session_id}, timeout)
+ if revive_result.get("isError") is True:
+ logger.warning("cua-driver session %s could not be revived: %s",
+ session_id, self._logical_error_text(revive_result))
+ return first_result
+ return self._run_call(name, args, timeout)
+
+ def _restore_declared_session_after_transport_reset(self, timeout: float) -> None:
+ """Re-attach the public label inside a replacement private lifecycle."""
+ session_id = getattr(self, "_declared_session_id", None)
+ if not session_id:
+ return
+ result = self._run_call("start_session", {"session": session_id}, timeout)
+ if result.get("isError") is True:
+ logger.warning("cua-driver public session label %s could not be restored: %s",
+ session_id, self._logical_error_text(result))
+
+ def _restart_session_locked(self) -> None:
+ """Recreate the MCP session after the transport closed. Caller holds self._lock."""
+ if self._started:
+ try:
+ self._stop_lifecycle_locked()
+ except Exception as e:
+ logger.debug("cua-driver session cleanup before reconnect failed: %s", e)
+ self._started = False
+ # Stale capability state is repopulated from scratch by the next start.
+ self._capabilities = {}
+ self._tool_schemas = {}
+ self._capability_version = ""
+ self._start_lifecycle_locked()
+ self._started = True
+
+ def _restart_and_restore(self, timeout: float) -> None:
+ with self._lock:
+ self._restart_session_locked()
+ self._restore_declared_session_after_transport_reset(timeout)
+
+ def _call_tool_via_cli(self, name: str, args: Dict[str, Any], timeout: float) -> Dict[str, Any]:
+ """Fallback transport: ``cua-driver call <tool> <json>`` as a subprocess.
+
+ The ``cua-driver mcp`` stdio bridge can persistently fail heavy calls
+ (notably ``get_window_state``) with EAGAIN while the plain CLI — which
+ talks to the daemon over its own socket — keeps working. The JSON is
+ remapped into the ``_extract_tool_result`` dict shape so callers stay
+ transport-agnostic.
+
+ For ``get_window_state`` the screenshot is routed to a temp file via
+ ``screenshot_out_file`` so the daemon returns a tiny JSON body instead
+ of a multi-megabyte base64 blob (the large payload is what congests
+ the socket in the first place); we read the PNG back ourselves. The
+ CLI call is retried with backoff since the socket may still be busy.
+ """
+ import subprocess as _subprocess
+ import tempfile as _tempfile
+ import time as _time
+ from tools.computer_use import cua_backend as _cb
+ from tools.environments.local import _sanitize_subprocess_env
+
+ call_args = dict(args)
+ shot_file: Optional[str] = None
+ if name == "get_window_state" and "screenshot_out_file" not in call_args:
+ fd, shot_file = _tempfile.mkstemp(prefix="cua_shot_", suffix=".png")
+ os.close(fd)
+ call_args["screenshot_out_file"] = shot_file
+
+ driver_command = _cb.resolve_cua_driver_cmd()
+ if not driver_command:
+ raise RuntimeError(_cb.cua_driver_install_hint())
+ child_env = _cb.cua_driver_child_env()
+ socket_args: List[str] = []
+ embedded_daemon = getattr(self, "_embedded_daemon", None)
+ if embedded_daemon is not None:
+ driver_command = embedded_daemon.proxy_invocation()[0]
+ child_env = embedded_daemon.child_env()
+ socket_args = ["--socket", embedded_daemon.socket_path]
+ cmd = [driver_command, "call", name, json.dumps(call_args), *socket_args]
+ attempts = 4
+ backoff = 0.5
+ parsed: Any = None
+ last_err = ""
+ try:
+ for attempt in range(attempts):
+ try:
+ proc = _subprocess.run(
+ cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
+ timeout=max(15.0, timeout), creationflags=_cb.windows_hide_flags(),
+ env=_sanitize_subprocess_env(child_env))
+ except Exception as e: # pragma: no cover - subprocess spawn failure
+ raise RuntimeError(f"cua-driver CLI fallback for {name} failed to spawn: {e}") from e
+
+ out = (proc.stdout or "").strip()
+ last_err = out[:200] or (proc.stderr or "")[:200]
+ # PERMANENT for this invocation: `cua-driver call` needs the
+ # machine-wide daemon socket, which Linux installs typically
+ # never start. Fail fast instead of burning ~3.5s of backoff.
+ if "daemon is not running" in out or "daemon is not running" in (proc.stderr or ""):
+ raise RuntimeError(
+ f"cua-driver CLI fallback for {name} unavailable: the "
+ "machine-wide cua-driver daemon is not running (the "
+ "CLI transport requires it; the MCP runtime does not)."
+ )
+ start = min((i for i in (out.find("{"), out.find("[")) if i != -1), default=-1)
+ if start != -1:
+ try:
+ candidate = json.loads(out[start:])
+ except json.JSONDecodeError:
+ candidate = None
+ if candidate is not None:
+ parsed = candidate
+ break
+ # No JSON (EAGAIN warning / empty) — retry with backoff.
+ if attempt < attempts - 1:
+ logger.warning(
+ "cua-driver CLI fallback for %s got no JSON "
+ "(attempt %d/%d); retrying in %.1fs",
+ name, attempt + 1, attempts, backoff,
+ )
+ _time.sleep(backoff)
+ backoff *= 2
+
+ if parsed is None:
+ raise RuntimeError(f"cua-driver CLI fallback for {name} returned no JSON after "
+ f"{attempts} attempts: {last_err}")
+
+ images: List[str] = []
+ data: Any = None
+ structured: Optional[Dict] = parsed if isinstance(parsed, dict) else None
+ is_error = False
+ if isinstance(parsed, dict):
+ # CLI responses may report logical failures in-band even when
+ # the subprocess exits 0 — preserve the bit so callers fail closed.
+ is_error = parsed.get("isError") is True or parsed.get("is_error") is True
+ shot = parsed.get("screenshot_png_b64")
+ if not shot:
+ # Screenshot was routed to a file (ours or the daemon's choice).
+ fpath = parsed.get("screenshot_file_path") or shot_file
+ if fpath and os.path.exists(fpath):
+ try:
+ with open(fpath, "rb") as fh:
+ shot = base64.b64encode(fh.read()).decode("ascii")
+ except Exception as e:
+ logger.debug("cua-driver CLI fallback: failed reading %s: %s", fpath, e)
+ if shot:
+ images.append(shot)
+ tree = parsed.get("tree_markdown")
+ if tree is not None:
+ ec = parsed.get("element_count")
+ summary = f"{ec} elements" if ec is not None else ""
+ data = f"{summary}\n{tree}" if summary else tree
+ return {"data": data, "images": images, "structuredContent": structured, "isError": is_error}
+ finally:
+ if shot_file and os.path.exists(shot_file):
+ try:
+ os.remove(shot_file)
+ except OSError:
+ pass
+
+ def call_tool(self, name: str, args: Dict[str, Any], timeout: float = 30.0) -> Dict[str, Any]:
+ # A prior MCP timeout marks the session suspect (possibly wedged for
+ # every later call): recreate it first so one timeout never poisons
+ # the rest of the run. Healthy sessions are never restarted here.
+ if self._timeout_suspect and name not in self._LIFECYCLE_CALLS:
+ logger.warning("cua-driver session suspect after earlier MCP timeout; "
+ "recreating before %s", name)
+ with self._lock:
+ self._restart_session_locked()
+ self._timeout_suspect = False
+ self._restore_declared_session_after_transport_reset(timeout)
+
+ # A prior session may have died (MCP drop / driver crash) and reset
+ # _started in its lifecycle finally.
+ if not self._started and name not in self._LIFECYCLE_CALLS:
+ logger.warning("cua-driver session not active on %s; (re)starting before call", name)
+ self.start()
+ self._restore_declared_session_after_transport_reset(timeout)
+ self._require_started()
+
+ try:
+ result = self._run_call(name, args, timeout)
+ except Exception as e:
+ if isinstance(e, concurrent.futures.TimeoutError):
+ # Fail closed: the action may have landed, so never replay it.
+ self._timeout_suspect = True
+ logger.warning("cua-driver MCP timed out on %s; marking session suspect "
+ "for recreation before the next call", name)
+ return self._timeout_outcome(name, e)
+ if self._is_transient_daemon_error(e):
+ if not self._transport_replay_is_safe(name):
+ self._notify_transport_reset()
+ return self._unknown_transport_outcome(name, e)
+ logger.warning("cua-driver MCP transport failed on %s (%s); "
+ "falling back to CLI transport", name, e)
+ return self._call_tool_via_cli(name, args, timeout)
+ if not self._is_closed_session_error(e):
+ raise
+ logger.warning("cua-driver MCP session closed during %s; reconnecting once", name)
+ self._restart_and_restore(timeout)
+ if not self._transport_replay_is_safe(name):
+ return self._unknown_transport_outcome(name, e)
+ result = self._run_call(name, args, timeout)
+
+ # Remember only a successfully declared stable identity, so a failed
+ # start_session cannot leave stale recovery state behind.
+ if name == "start_session" and result.get("isError") is not True:
+ declared_id = args.get("session")
+ if isinstance(declared_id, str) and declared_id:
+ self._declared_session_id = declared_id
+
+ if self._is_ended_session_result(result):
+ result = self._revive_declared_session_once(name, args, result, timeout)
+
+ if (
+ name == "end_session"
+ and result.get("isError") is not True
+ and args.get("session") == self._declared_session_id
+ ):
+ self._declared_session_id = None
+ return result
diff --git a/tools/computer_use/doctor.py b/tools/computer_use/doctor.py
index 1379c8d95c8..ee220b24ccd 100644
--- a/tools/computer_use/doctor.py
+++ b/tools/computer_use/doctor.py
@@ -1,22 +1,13 @@
-"""
-`hermes computer-use doctor` — thin client for cua-driver's `health_report` MCP tool.
-
-cua-driver owns the health model (#1908 / be761fac on `main`). This module
-just drives the stdio JSON-RPC handshake, calls `health_report`, and
-renders the structured response. When the driver gets new checks, they
-flow through here without code changes on the Hermes side — the only
-contract is the stable `schema_version="1"` payload shape.
-
-cua-driver 0.10.x marks `health_report` with risk.class='unclassified', so
-MCP tools/call returns isError=true ("Permission denied: ... no reviewed
-risk classification") with structuredContent ``{"exit_code": 1}``. That is
-NOT a schema_version=1 report — we detect it and synthesize a composite
-report via working probes (check_permissions, list_apps, CLI --version).
-
-Exit code conventions:
-- 0: overall == "ok"
-- 1: overall in ("degraded", "failed")
-- 2: driver binary missing / unreachable / protocol error
+"""`hermes computer-use doctor` — thin client for cua-driver's `health_report` MCP tool.
+
+cua-driver owns the health model; this module drives the stdio JSON-RPC handshake,
+calls `health_report`, and renders the response. The only contract is the stable
+`schema_version="1"` payload shape. cua-driver 0.10.x marks `health_report`
+risk-unclassified (isError=true, structuredContent ``{"exit_code": 1}``) — we detect
+that and synthesize a composite report from working probes (check_permissions,
+list_apps, CLI --version).
+
+Exit codes: 0 overall=="ok"; 1 degraded/failed; 2 binary missing / protocol error.
"""
from __future__ import annotations
@@ -27,104 +18,75 @@ import platform as _platform_mod
import re
import subprocess
import sys
-from typing import Any, Dict, List, Optional, Sequence, Tuple
+from contextlib import contextmanager
+from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple
from hermes_cli._subprocess_compat import windows_hide_flags
# Match the ALLOWED_STATUS_VALUES + ALLOWED_OVERALL_VALUES the cua-driver
# integration test pins. If health_report widens its vocabulary, add here.
-_STATUS_GLYPH = {
- "pass": "✅",
- "fail": "❌",
- "skip": "⏭️",
-}
-_OVERALL_GLYPH = {
- "ok": "✅",
- "degraded": "⚠️",
- "failed": "❌",
-}
+_STATUS_GLYPH = {"pass": "✅", "fail": "❌", "skip": "⏭️"}
+_OVERALL_GLYPH = {"ok": "✅", "degraded": "⚠️", "failed": "❌"}
+_SUPPORTED_PLATFORMS = ("darwin", "linux", "windows")
+_TCC_HINT = "Grant {} to CuaDriver in System Settings → Privacy & Security."
class HealthReportUnavailable(RuntimeError):
- """health_report MCP tool denied or returned a non-schema payload.
-
- Raised so ``run_doctor`` can fall back to composite probes that work on
- cua-driver builds where ``health_report`` is risk-unclassified (0.10.x).
- """
-
+ """health_report denied or non-schema payload — ``run_doctor`` falls back to probes."""
-def _cua_child_env() -> Dict[str, str]:
- """cua-driver child env with the Hermes telemetry policy applied.
- Delegates to ``cua_backend.cua_driver_child_env`` (telemetry disabled by
- default unless the user opts in). Falls back to the current environment
- if that import fails, so doctor never breaks on a telemetry-helper error.
- """
+def _sanitized_cua_env() -> Dict[str, str]:
+ """cua-driver child env (telemetry policy + provider secrets stripped);
+ degrades to ``os.environ`` on import error so doctor keeps working."""
try:
- from tools.computer_use.cua_backend import cua_driver_child_env
+ from tools.computer_use.cua_backend import sanitized_cua_driver_env
- return cua_driver_child_env()
+ return sanitized_cua_driver_env()
except Exception:
return dict(os.environ)
-def _sanitized_cua_env() -> Dict[str, str]:
- """Telemetry-policy env with Hermes provider secrets stripped.
+def _is_valid_health_report(payload: Any) -> bool:
+ """True when *payload* looks like a schema_version=1 health_report."""
+ return (
+ isinstance(payload, dict)
+ and "schema_version" in payload
+ and "overall" in payload
+ and isinstance(payload.get("checks"), list)
+ )
- cua-driver is a third-party binary — it must never inherit provider
- API keys (#53503/#55709/#58889 lineage). Falls back to the unsanitized
- telemetry env if the sanitizer can't be imported, so doctor keeps
- working in stripped-down environments.
- """
- env = _cua_child_env()
- try:
- from tools.environments.local import _sanitize_subprocess_env
- return _sanitize_subprocess_env(env)
- except Exception:
- return env
+def _run_cli(binary: str, *args: str, timeout: float) -> subprocess.CompletedProcess:
+ """Run ``<binary> args`` with UTF-8 capture + sanitized env (raises on failure)."""
+ return subprocess.run(
+ [binary, *args], capture_output=True, text=True, encoding="utf-8",
+ errors="replace", timeout=timeout, env=_sanitized_cua_env(),
+ )
-def _is_valid_health_report(payload: Any) -> bool:
- """True when *payload* looks like a schema_version=1 health_report."""
- if not isinstance(payload, dict):
- return False
- if "schema_version" not in payload:
- return False
- if "overall" not in payload:
- return False
- if not isinstance(payload.get("checks"), list):
- return False
- return True
+def _first_text(result: Dict[str, Any], default: str) -> str:
+ """First non-empty text content item of an MCP tools/call result, else *default*."""
+ for item in result.get("content") or []:
+ if isinstance(item, dict) and item.get("type") == "text":
+ text = (item.get("text") or "").strip()
+ if text:
+ return text
+ return default
def _read_cli_version(binary: str, *, timeout: float = 5.0) -> Optional[str]:
- """Return ``cua-driver --version`` stdout (stripped), or None on failure.
+ """Return ``cua-driver --version`` first line (stripped), or None on failure.
- health_report's ``driver_version`` / binary_version check can disagree
- with the actual binary (observed on Windows: health_report claims
- 0.8.3 while ``--version`` and the on-disk release are 0.12.6). Doctor
- surfaces both so operators are not misled when debugging session
- issues against a "wrong" version string.
+ health_report's ``driver_version`` can disagree with the actual binary
+ (observed on Windows); doctor surfaces both so operators are not misled.
"""
try:
- completed = subprocess.run(
- [binary, "--version"],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=timeout,
- env=_sanitized_cua_env(),
- )
+ completed = _run_cli(binary, "--version", timeout=timeout)
except (OSError, subprocess.TimeoutExpired, ValueError, TypeError):
return None
text = (completed.stdout or completed.stderr or "").strip()
- if not text:
- return None
- # First non-empty line only — keep the banner compact.
- return text.splitlines()[0].strip()
+ return text.splitlines()[0].strip() if text else None
def _normalize_version_token(text: str) -> str:
@@ -141,34 +103,23 @@ def _build_identity(binary: str, report: Dict[str, Any]) -> Dict[str, Any]:
report_v = str(report.get("driver_version") or "")
cli_tok = _normalize_version_token(cli)
report_tok = _normalize_version_token(report_v)
- mismatch = bool(cli_tok and report_tok and cli_tok != report_tok)
return {
"resolved_binary": binary,
"cli_version": cli or None,
"health_report_driver_version": report_v or None,
- "version_mismatch": mismatch,
+ "version_mismatch": bool(cli_tok and report_tok and cli_tok != report_tok),
}
def _extract_health_report_from_result(result: Dict[str, Any]) -> Dict[str, Any]:
"""Pull a schema_version=1 report out of an MCP tools/call result.
- Raises ``HealthReportUnavailable`` when the tool denied the call
- (isError) or the payload is not a real health report (e.g. 0.10's
- ``{"exit_code": 1}`` structuredContent on unclassified denial).
- Raises ``RuntimeError`` when the response shape is unusable for other
- reasons (no content at all).
+ Raises ``HealthReportUnavailable`` when the tool denied the call (isError)
+ or the payload is not a real health report (0.10's ``{"exit_code": 1}``);
+ ``RuntimeError`` when the response carries no content at all.
"""
if result.get("isError") is True:
- # Prefer the human text; fall back to a generic denial message.
- denial = "health_report returned isError=true"
- for item in result.get("content") or []:
- if isinstance(item, dict) and item.get("type") == "text":
- text = (item.get("text") or "").strip()
- if text:
- denial = text
- break
- raise HealthReportUnavailable(denial)
+ raise HealthReportUnavailable(_first_text(result, "health_report returned isError=true"))
sc = result.get("structuredContent")
if _is_valid_health_report(sc):
@@ -178,22 +129,19 @@ def _extract_health_report_from_result(result: Dict[str, Any]) -> Dict[str, Any]
for item in result.get("content") or []:
if not isinstance(item, dict) or item.get("type") != "text":
continue
- text = item.get("text", "")
try:
- parsed = json.loads(text)
+ parsed = json.loads(item.get("text", ""))
except (ValueError, TypeError):
continue
if _is_valid_health_report(parsed):
return parsed
- # structuredContent present but not a real report (the 0.10 unclassified
- # path ships {"exit_code": 1}) — treat as unavailable, not fatal protocol.
+ # structuredContent present but not a real report — unavailable, not fatal protocol.
if isinstance(sc, dict):
raise HealthReportUnavailable(
"health_report structuredContent lacks schema_version/overall/checks "
f"(keys={sorted(sc.keys())})"
)
-
raise RuntimeError(
"health_report response carried neither structuredContent nor a parseable "
f"JSON text block. Result keys: {list(result.keys())}"
@@ -201,23 +149,15 @@ def _extract_health_report_from_result(result: Dict[str, Any]) -> Dict[str, Any]
def _open_mcp(binary: str) -> subprocess.Popen:
- """Spawn ``<binary> mcp`` with UTF-8 + sanitized env."""
- # cua-driver emits UTF-8 (containing emoji in check messages on macOS
- # and arbitrary file paths on Windows). The Python default
- # text-mode encoding follows the system locale — `cp1252` on a
- # default Windows install — which raises UnicodeDecodeError on the
- # first non-ASCII byte. Pin the codec.
+ """Spawn ``<binary> mcp`` with UTF-8 + sanitized env.
+
+ cua-driver emits UTF-8 (emoji, arbitrary paths); the locale default
+ (`cp1252` on Windows) would raise UnicodeDecodeError, so pin the codec.
+ """
return subprocess.Popen(
- [binary, "mcp"],
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- text=True,
- encoding="utf-8",
- errors="replace",
- bufsize=1,
- creationflags=windows_hide_flags(),
- env=_sanitized_cua_env(),
+ [binary, "mcp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ text=True, encoding="utf-8", errors="replace", bufsize=1,
+ creationflags=windows_hide_flags(), env=_sanitized_cua_env(),
)
@@ -251,58 +191,42 @@ def _mcp_rpc(proc: subprocess.Popen, msg_id: int, method: str, params: Any = Non
return resp
-def _close_mcp(proc: subprocess.Popen, timeout: float) -> None:
- try:
- if proc.stdin is not None:
- proc.stdin.close()
- except Exception:
- pass
- try:
- proc.wait(timeout=timeout)
- except subprocess.TimeoutExpired:
- proc.kill()
- proc.wait()
-
-
-def _drive_health_report(
- binary: str,
- *,
- include: Sequence[str] = (),
- skip: Sequence[str] = (),
- timeout: float = 12.0,
-) -> Dict[str, Any]:
- """Spawn `<binary> mcp`, perform the JSON-RPC handshake, call
- `health_report`, and return the parsed schema_version=1 report.
-
- Raises:
- HealthReportUnavailable: tool denied (isError) or non-schema payload
- (cua-driver 0.10 unclassified). Caller should fall back.
- RuntimeError: protocol-level failure (binary crash, malformed JSON,
- JSON-RPC error, empty content).
- """
- args: Dict[str, Any] = {}
- if include:
- args["include"] = list(include)
- if skip:
- args["skip"] = list(skip)
+def _call_tool(proc: subprocess.Popen, msg_id: int, name: str, arguments: Any = None) -> Any:
+ """tools/call *name* and return the raw ``result`` value (``{}`` when absent)."""
+ resp = _mcp_rpc(proc, msg_id, "tools/call", {"name": name, "arguments": arguments or {}})
+ return resp.get("result") or {}
+
+@contextmanager
+def _mcp_session(binary: str, timeout: float) -> Iterator[subprocess.Popen]:
+ """Spawn ``<binary> mcp`` and always close stdin / wait / kill it on exit."""
proc = _open_mcp(binary)
try:
- # 1. initialize
- init_resp = _mcp_rpc(proc, 1, "initialize", {})
- _ = init_resp # handshake only
-
- # 2. tools/call health_report
- call_resp = _mcp_rpc(
- proc,
- 2,
- "tools/call",
- {"name": "health_report", "arguments": args},
- )
+ yield proc
finally:
- _close_mcp(proc, timeout)
+ try:
+ if proc.stdin is not None:
+ proc.stdin.close()
+ except Exception:
+ pass
+ try:
+ proc.wait(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait()
+
+
+def _drive_health_report(binary: str, *, include: Sequence[str] = (), skip: Sequence[str] = (),
+ timeout: float = 12.0) -> Dict[str, Any]:
+ """Spawn `<binary> mcp`, handshake, call `health_report`, return the parsed report.
- result = call_resp.get("result") or {}
+ Raises HealthReportUnavailable (denied / non-schema — caller falls back) or
+ RuntimeError (protocol-level failure).
+ """
+ args = {k: list(v) for k, v in (("include", include), ("skip", skip)) if v}
+ with _mcp_session(binary, timeout) as proc:
+ _mcp_rpc(proc, 1, "initialize", {})
+ result = _call_tool(proc, 2, "health_report", args)
if not isinstance(result, dict):
raise RuntimeError(f"health_report result was not an object: {type(result).__name__}")
return _extract_health_report_from_result(result)
@@ -311,15 +235,7 @@ def _drive_health_report(
def _cli_driver_version(binary: str, timeout: float = 5.0) -> Tuple[str, Optional[str]]:
"""Return (status, version_or_message) from ``cua-driver --version``."""
try:
- completed = subprocess.run(
- [binary, "--version"],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=timeout,
- env=_sanitized_cua_env(),
- )
+ completed = _run_cli(binary, "--version", timeout=timeout)
except (OSError, subprocess.TimeoutExpired) as e:
return "fail", f"--version failed: {e}"
@@ -330,54 +246,29 @@ def _cli_driver_version(binary: str, timeout: float = 5.0) -> Tuple[str, Optiona
# Typical: "cua-driver 0.10.0"
m = re.search(r"(\d+\.\d+\.\d+(?:[-+][\w.]+)?)", text)
version = m.group(1) if m else (text.splitlines()[0] if text else "unknown")
- if completed.returncode != 0:
- return "fail", version
- return "pass", version
+ return ("fail" if completed.returncode != 0 else "pass"), version
def _cli_doctor_snippet(binary: str, timeout: float = 8.0) -> Optional[str]:
"""Optional one-shot ``cua-driver doctor`` text (best-effort, never fatal)."""
try:
- completed = subprocess.run(
- [binary, "doctor"],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=timeout,
- env=_sanitized_cua_env(),
- )
+ completed = _run_cli(binary, "doctor", timeout=timeout)
except (OSError, subprocess.TimeoutExpired):
return None
- out = ((completed.stdout or "") + (completed.stderr or "")).strip()
- return out or None
+ return ((completed.stdout or "") + (completed.stderr or "")).strip() or None
-def _drive_fallback_probes(
- binary: str,
- *,
- timeout: float = 12.0,
-) -> Dict[str, Any]:
+def _drive_fallback_probes(binary: str, *, timeout: float = 12.0) -> Dict[str, Any]:
"""Call working MCP tools (check_permissions, list_apps) in one session.
- Returns a dict with keys:
- - init_version: str | None (from initialize serverInfo)
- - permissions: structuredContent dict | None
- - permissions_error: str | None
- - list_apps_ok: bool | None
- - list_apps_error: str | None
- - list_apps_count: int | None
+ Returns init_version (initialize serverInfo), permissions (structuredContent
+ dict | None), permissions_error, list_apps_ok, list_apps_error, list_apps_count.
"""
- out: Dict[str, Any] = {
- "init_version": None,
- "permissions": None,
- "permissions_error": None,
- "list_apps_ok": None,
- "list_apps_error": None,
- "list_apps_count": None,
- }
- proc = _open_mcp(binary)
- try:
+ out: Dict[str, Any] = dict.fromkeys((
+ "init_version", "permissions", "permissions_error",
+ "list_apps_ok", "list_apps_error", "list_apps_count",
+ ))
+ with _mcp_session(binary, timeout) as proc:
init_resp = _mcp_rpc(proc, 1, "initialize", {})
server_info = ((init_resp.get("result") or {}).get("serverInfo") or {})
if isinstance(server_info, dict):
@@ -385,84 +276,103 @@ def _drive_fallback_probes(
# check_permissions — primary TCC signal on 0.10
try:
- perm_resp = _mcp_rpc(
- proc, 2, "tools/call", {"name": "check_permissions", "arguments": {}}
- )
- perm_result = perm_resp.get("result") or {}
+ perm_result = _call_tool(proc, 2, "check_permissions")
if perm_result.get("isError") is True:
- msg = "check_permissions isError"
- for item in perm_result.get("content") or []:
- if isinstance(item, dict) and item.get("type") == "text":
- t = (item.get("text") or "").strip()
- if t:
- msg = t
- break
- out["permissions_error"] = msg
+ out["permissions_error"] = _first_text(perm_result, "check_permissions isError")
else:
sc = perm_result.get("structuredContent")
out["permissions"] = sc if isinstance(sc, dict) else {}
except RuntimeError as e:
out["permissions_error"] = str(e)
- # list_apps — light AX capability probe
+ # list_apps — light AX capability probe; text-only success still counts as AX working
try:
- apps_resp = _mcp_rpc(
- proc, 3, "tools/call", {"name": "list_apps", "arguments": {}}
- )
- apps_result = apps_resp.get("result") or {}
+ apps_result = _call_tool(proc, 3, "list_apps")
if apps_result.get("isError") is True:
- msg = "list_apps isError"
- for item in apps_result.get("content") or []:
- if isinstance(item, dict) and item.get("type") == "text":
- t = (item.get("text") or "").strip()
- if t:
- msg = t
- break
out["list_apps_ok"] = False
- out["list_apps_error"] = msg
+ out["list_apps_error"] = _first_text(apps_result, "list_apps isError")
else:
sc = apps_result.get("structuredContent") or {}
apps = sc.get("apps") if isinstance(sc, dict) else None
- if isinstance(apps, list):
- out["list_apps_ok"] = True
- out["list_apps_count"] = len(apps)
- else:
- # text-only success still counts as AX working
- out["list_apps_ok"] = True
- out["list_apps_count"] = None
+ out["list_apps_ok"] = True
+ out["list_apps_count"] = len(apps) if isinstance(apps, list) else None
except RuntimeError as e:
out["list_apps_ok"] = False
out["list_apps_error"] = str(e)
- finally:
- _close_mcp(proc, timeout)
-
return out
def _platform_name() -> str:
sysname = (_platform_mod.system() or "").lower()
- if sysname == "darwin":
- return "darwin"
- if sysname == "windows":
- return "windows"
- if sysname == "linux":
- return "linux"
- return sysname or "unknown"
-
-
-def _compose_fallback_report(
- binary: str,
- *,
- reason: str = "",
- timeout: float = 12.0,
-) -> Dict[str, Any]:
+ return sysname if sysname in _SUPPORTED_PLATFORMS else (sysname or "unknown")
+
+
+def _check(name: str, status: str, message: str, **extra: Any) -> Dict[str, Any]:
+ """Build one health check dict (``hint`` / ``data`` only when given)."""
+ return {"name": name, "status": status, "message": message, **extra}
+
+
+def _tcc_checks(perms: Optional[Dict[str, Any]], perm_err: Optional[str], plat: str) -> List[Dict[str, Any]]:
+ """tcc_accessibility + tcc_screen_recording checks from check_permissions output."""
+ if perms is None:
+ status = "fail" if perm_err else "skip"
+ msg = perm_err or "check_permissions unavailable"
+ return [_check("tcc_accessibility", status, msg), _check("tcc_screen_recording", status, msg)]
+
+ # Only real booleans select a branch; anything else (missing/odd) is the "absent" row.
+ ax, scr, capturable = (perms.get(k) for k in ("accessibility", "screen_recording", "screen_recording_capturable"))
+ ax = ax if isinstance(ax, bool) else None
+ scr = scr if isinstance(scr, bool) else None
+
+ ax_rows = {
+ True: ("pass", "Accessibility is granted.", {"data": {"accessibility": True}}),
+ False: ("fail", "Accessibility is not granted.",
+ {"hint": _TCC_HINT.format("Accessibility"), "data": {"accessibility": False}}),
+ None: ("skip", "accessibility field absent from check_permissions", {}),
+ }
+ scr_rows = {
+ # (scr, capturable is False) — the granted-but-not-capturable row wins first.
+ (True, True): ("fail", "Screen Recording granted but not capturable.",
+ {"hint": "Screen Recording permission may need a restart of CuaDriver "
+ "or a re-grant in System Settings.",
+ "data": {"screen_recording": True, "screen_recording_capturable": False}}),
+ (True, False): ("pass", "Screen Recording is granted.",
+ {"data": {"screen_recording": True, "screen_recording_capturable": capturable}}),
+ (False, False): ("fail", "Screen Recording is not granted.",
+ {"hint": _TCC_HINT.format("Screen Recording"), "data": {"screen_recording": False}}),
+ (None, False): ("skip", "screen_recording field absent from check_permissions" if plat == "darwin"
+ else f"not applicable on {plat}", {}),
+ }
+ ax_status, ax_msg, ax_extra = ax_rows[ax]
+ scr_status, scr_msg, scr_extra = scr_rows[(scr, capturable is False and scr is True)]
+ return [
+ _check("tcc_accessibility", ax_status, ax_msg, **ax_extra),
+ _check("tcc_screen_recording", scr_status, scr_msg, **scr_extra),
+ ]
+
+
+def _ax_capability_check(probes: Dict[str, Any], ax_granted: bool) -> Dict[str, Any]:
+ """ax_capability — inferred from list_apps success or the accessibility grant."""
+ list_ok = probes.get("list_apps_ok")
+ list_count = probes.get("list_apps_count")
+ if list_ok is True:
+ count_msg = f" ({list_count} apps)" if isinstance(list_count, int) else ""
+ return _check("ax_capability", "pass", f"list_apps succeeded{count_msg}")
+ if list_ok is False:
+ default = "list_apps failed despite accessibility grant" if ax_granted else "list_apps failed"
+ return _check("ax_capability", "fail", probes.get("list_apps_error") or default)
+ if ax_granted:
+ return _check("ax_capability", "pass", "inferred from accessibility grant (list_apps not probed)")
+ return _check("ax_capability", "skip", "not probed")
+
+
+def _compose_fallback_report(binary: str, *, reason: str = "", timeout: float = 12.0) -> Dict[str, Any]:
"""Build a schema_version=1 report from CLI + working MCP probes.
Used when ``health_report`` is denied (unclassified risk on 0.10) or
returns a non-schema payload. Compatible with ``_print_text_report``.
"""
plat = _platform_name()
- checks: List[Dict[str, Any]] = []
ver_status, ver_value = _cli_driver_version(binary)
driver_version = ver_value if ver_status == "pass" else (ver_value or "?")
@@ -473,204 +383,51 @@ def _compose_fallback_report(
ver_status = "pass"
ver_msg = f"cua-driver {driver_version}"
else:
- ver_msg = (
- f"cua-driver {ver_value}" if ver_status == "pass" else (ver_value or "version unknown")
- )
+ ver_msg = f"cua-driver {ver_value}" if ver_status == "pass" else (ver_value or "version unknown")
- checks.append({
- "name": "binary_version",
- "status": ver_status,
- "message": ver_msg,
- })
-
- # platform_supported — doctor runs wherever the binary runs
- supported = plat in ("darwin", "linux", "windows")
- checks.append({
- "name": "platform_supported",
- "status": "pass" if supported else "fail",
- "message": f"platform={plat}" + ("" if supported else " (unsupported)"),
- })
-
- # session_active — we don't start a session in doctor; mark skip
- checks.append({
- "name": "session_active",
- "status": "skip",
- "message": "not probed (doctor does not open a cua session)",
- })
+ supported = plat in _SUPPORTED_PLATFORMS
+ checks: List[Dict[str, Any]] = [
+ _check("binary_version", ver_status, ver_msg),
+ _check("platform_supported", "pass" if supported else "fail",
+ f"platform={plat}" + ("" if supported else " (unsupported)")),
+ # doctor does not start a session, so session_active is never probed
+ _check("session_active", "skip", "not probed (doctor does not open a cua session)"),
+ ]
perms = probes.get("permissions") if isinstance(probes.get("permissions"), dict) else None
- perm_err = probes.get("permissions_error")
-
- if perms is not None:
- ax = perms.get("accessibility")
- scr = perms.get("screen_recording")
- capturable = perms.get("screen_recording_capturable")
-
- if ax is True:
- checks.append({
- "name": "tcc_accessibility",
- "status": "pass",
- "message": "Accessibility is granted.",
- "data": {"accessibility": True},
- })
- elif ax is False:
- checks.append({
- "name": "tcc_accessibility",
- "status": "fail",
- "message": "Accessibility is not granted.",
- "hint": "Grant Accessibility to CuaDriver in System Settings → Privacy & Security.",
- "data": {"accessibility": False},
- })
- else:
- checks.append({
- "name": "tcc_accessibility",
- "status": "skip",
- "message": "accessibility field absent from check_permissions",
- })
-
- if scr is True and capturable is False:
- checks.append({
- "name": "tcc_screen_recording",
- "status": "fail",
- "message": "Screen Recording granted but not capturable.",
- "hint": (
- "Screen Recording permission may need a restart of CuaDriver "
- "or a re-grant in System Settings."
- ),
- "data": {
- "screen_recording": True,
- "screen_recording_capturable": False,
- },
- })
- elif scr is True:
- checks.append({
- "name": "tcc_screen_recording",
- "status": "pass",
- "message": "Screen Recording is granted.",
- "data": {
- "screen_recording": True,
- "screen_recording_capturable": capturable,
- },
- })
- elif scr is False:
- checks.append({
- "name": "tcc_screen_recording",
- "status": "fail",
- "message": "Screen Recording is not granted.",
- "hint": "Grant Screen Recording to CuaDriver in System Settings → Privacy & Security.",
- "data": {"screen_recording": False},
- })
- else:
- # Non-macOS or field absent
- if plat == "darwin":
- checks.append({
- "name": "tcc_screen_recording",
- "status": "skip",
- "message": "screen_recording field absent from check_permissions",
- })
- else:
- checks.append({
- "name": "tcc_screen_recording",
- "status": "skip",
- "message": f"not applicable on {plat}",
- })
- else:
- checks.append({
- "name": "tcc_accessibility",
- "status": "fail" if perm_err else "skip",
- "message": perm_err or "check_permissions unavailable",
- })
- checks.append({
- "name": "tcc_screen_recording",
- "status": "fail" if perm_err else "skip",
- "message": perm_err or "check_permissions unavailable",
- })
-
- # ax_capability — infer from list_apps success or accessibility grant
- list_ok = probes.get("list_apps_ok")
- list_err = probes.get("list_apps_error")
- list_count = probes.get("list_apps_count")
- ax_granted = bool(perms and perms.get("accessibility") is True)
- if list_ok is True:
- count_msg = f" ({list_count} apps)" if isinstance(list_count, int) else ""
- checks.append({
- "name": "ax_capability",
- "status": "pass",
- "message": f"list_apps succeeded{count_msg}",
- })
- elif list_ok is False:
- checks.append({
- "name": "ax_capability",
- "status": "fail",
- "message": (
- list_err
- or (
- "list_apps failed despite accessibility grant"
- if ax_granted
- else "list_apps failed"
- )
- ),
- })
- elif ax_granted:
- checks.append({
- "name": "ax_capability",
- "status": "pass",
- "message": "inferred from accessibility grant (list_apps not probed)",
- })
- else:
- checks.append({
- "name": "ax_capability",
- "status": "skip",
- "message": "not probed",
- })
+ checks += _tcc_checks(perms, probes.get("permissions_error"), plat)
+ checks.append(_ax_capability_check(probes, bool(perms and perms.get("accessibility") is True)))
# Annotate that we used the fallback path
reason_short = (reason or "health_report unavailable").strip()
if len(reason_short) > 160:
reason_short = reason_short[:157] + "..."
- checks.append({
- "name": "health_report_path",
- "status": "skip",
- "message": (
- "fallback composite (cua-driver 0.10 unclassified health_report); "
- f"cause: {reason_short}"
- ),
- })
+ checks.append(_check(
+ "health_report_path", "skip",
+ f"fallback composite (cua-driver 0.10 unclassified health_report); cause: {reason_short}",
+ ))
# Optional CLI doctor text (best-effort)
doctor_txt = _cli_doctor_snippet(binary)
if doctor_txt:
- first = doctor_txt.splitlines()[0].strip()
cli_ok = "[ok" in doctor_txt.lower() or "ok ]" in doctor_txt
- checks.append({
- "name": "cli_doctor",
- "status": "pass" if cli_ok else "skip",
- "message": first,
- "data": {"snippet": doctor_txt[:2000]},
- })
+ checks.append(_check("cli_doctor", "pass" if cli_ok else "skip",
+ doctor_txt.splitlines()[0].strip(), data={"snippet": doctor_txt[:2000]}))
# Normalize any accidental non-vocab status values
for c in checks:
if c.get("status") not in ("pass", "fail", "skip"):
c["status"] = "fail"
- # overall: ok if TCC+binary ok; degraded if partial; failed if binary missing/bad
+ # overall: failed if binary missing/bad; ok if accessibility fine and nothing
+ # failed; otherwise degraded (screen recording or accessibility problems).
status_by_name = {c.get("name"): c.get("status") for c in checks}
- binary_ok = status_by_name.get("binary_version") == "pass"
- tcc_ax_status = status_by_name.get("tcc_accessibility")
- tcc_ok = tcc_ax_status in ("pass", "skip", None)
fail_count = sum(1 for c in checks if c.get("status") == "fail")
-
- if not binary_ok:
+ if status_by_name.get("binary_version") != "pass":
overall = "failed"
- elif tcc_ok and fail_count == 0:
+ elif status_by_name.get("tcc_accessibility") in ("pass", "skip", None) and fail_count == 0:
overall = "ok"
- elif tcc_ok and fail_count > 0:
- # Binary + accessibility fine, but something else failed (e.g. screen
- # recording) → degraded rather than failed.
- overall = "degraded"
else:
- # Accessibility denied or broken — computer-use is partially/fully blocked.
overall = "degraded"
return {
@@ -684,22 +441,13 @@ def _compose_fallback_report(
}
-def _drive_health_report_or_fallback(
- binary: str,
- *,
- include: Sequence[str] = (),
- skip: Sequence[str] = (),
- timeout: float = 12.0,
-) -> Dict[str, Any]:
+def _drive_health_report_or_fallback(binary: str, *, include: Sequence[str] = (), skip: Sequence[str] = (),
+ timeout: float = 12.0) -> Dict[str, Any]:
"""Prefer real health_report; on denial/non-schema, synthesize via probes."""
try:
- report = _drive_health_report(
- binary, include=include, skip=skip, timeout=timeout,
- )
+ report = _drive_health_report(binary, include=include, skip=skip, timeout=timeout)
except HealthReportUnavailable as e:
- report = _compose_fallback_report(
- binary, reason=str(e), timeout=timeout,
- )
+ report = _compose_fallback_report(binary, reason=str(e), timeout=timeout)
return _apply_display_count_guard(report)
@@ -708,156 +456,90 @@ def _apply_display_count_guard(report: Dict[str, Any]) -> Dict[str, Any]:
macOS ScreenCaptureKit reports ``display_count=0`` on headless Macs and
when the built-in panel is asleep — TCC grants are fine, health_report
- can still say pass/ok, but every capture will come back 0x0. Marking
- the check failed (with the recovery actions) turns an undiagnosable
- silent failure into an actionable one. Applied at the report seam so
- the real health_report path and the composed fallback both get it.
-
- Composed from PR #52949 (sujeet111) and PR #67259 (webtecnica).
+ can still say pass/ok, but every capture will come back 0x0. Marking the
+ check failed turns a silent failure into an actionable one. Applied at
+ the report seam so both the real and the composed fallback path get it.
"""
checks = report.get("checks")
if not isinstance(checks, list):
return report
for check in checks:
- if not isinstance(check, dict):
- continue
- if check.get("name") != "screen_capture_capability":
+ if not isinstance(check, dict) or check.get("name") != "screen_capture_capability":
continue
data = check.get("data")
count = data.get("display_count") if isinstance(data, dict) else None
if count == 0 and check.get("status") == "pass":
check["status"] = "fail"
- check["message"] = (
- "ScreenCaptureKit reachable but 0 shareable display(s) — "
- "every capture will return 0x0."
- )
+ check["message"] = "ScreenCaptureKit reachable but 0 shareable display(s) — every capture will return 0x0."
check["hint"] = (
- "Wake the built-in display, connect a monitor or HDMI dummy "
- "dongle (e.g. Headless Ghost), or enable a virtual display "
- "(Screen Sharing/VNC, BetterDisplay). Verify with "
- "`system_profiler SPDisplaysDataType`."
+ "Wake the built-in display, connect a monitor or HDMI dummy dongle (e.g. Headless Ghost), "
+ "or enable a virtual display (Screen Sharing/VNC, BetterDisplay). "
+ "Verify with `system_profiler SPDisplaysDataType`."
)
if report.get("overall") == "ok":
report["overall"] = "degraded"
return report
-def _print_text_report(
- report: Dict[str, Any],
- color: bool,
- *,
- identity: Optional[Dict[str, Any]] = None,
-) -> None:
- """Render the report in the same style as `cua-driver call health_report`
- would (one line per check + a summary footer).
+def _print_text_report(report: Dict[str, Any], color: bool, *, identity: Optional[Dict[str, Any]] = None) -> None:
+ """Render the report like `cua-driver call health_report` (one line per check).
- When *identity* is provided (resolved binary + ``--version``), the header
- prefers the CLI version if health_report's ``driver_version`` disagrees,
- and a short identity block is printed under the header.
+ With *identity* (resolved binary + ``--version``) the header prefers the CLI
+ version over health_report's ``driver_version`` and prints an identity block.
"""
- schema = report.get("schema_version", "?")
platform = report.get("platform", "?")
report_v = report.get("driver_version", "?")
overall = report.get("overall", "?")
identity = identity or {}
cli_v = identity.get("cli_version") or ""
mismatch = bool(identity.get("version_mismatch"))
- # Prefer the binary's own --version when health_report is wrong/stale.
- header_v = cli_v or report_v
-
- header_glyph = _OVERALL_GLYPH.get(overall, "•")
-
- if color and overall in _OVERALL_GLYPH:
- # No external color library — keep ANSI inline so the doctor
- # command stays a single self-contained module.
- col_red = "\033[31m"
- col_yellow = "\033[33m"
- col_green = "\033[32m"
- col_reset = "\033[0m"
- col_dim = "\033[2m"
- col_for = {"failed": col_red, "degraded": col_yellow, "ok": col_green}.get(overall, "")
- else:
- col_red = col_yellow = col_green = col_reset = col_dim = ""
- col_for = ""
+ header_v = cli_v or report_v # binary's own --version wins when health_report is stale
- print(
- f"{header_glyph} cua-driver {header_v} on {platform} — "
- f"{col_for}{overall}{col_reset}"
- )
+ # No external color library — keep ANSI inline so doctor stays self-contained.
+ # Colors only apply when overall is a known vocabulary value.
+ ansi = ("\033[31m", "\033[33m", "\033[32m", "\033[0m", "\033[2m")
+ red, yellow, green, reset, dim = ansi if color and overall in _OVERALL_GLYPH else ("",) * 5
+ col_for = {"failed": red, "degraded": yellow, "ok": green}.get(overall, "")
+ status_cols = {"pass": green, "fail": red, "skip": dim}
+
+ print(f"{_OVERALL_GLYPH.get(overall, '•')} cua-driver {header_v} on {platform} — {col_for}{overall}{reset}")
if identity.get("resolved_binary"):
- print(f" {col_dim}binary: {identity['resolved_binary']}{col_reset}")
+ print(f" {dim}binary: {identity['resolved_binary']}{reset}")
if cli_v and report_v and str(report_v) not in str(cli_v) and str(cli_v) not in str(report_v):
# Only annotate when the free-form strings clearly differ.
- print(
- f" {col_dim}--version: {cli_v}{col_reset}"
- )
- print(
- f" {col_dim}health_report.driver_version: {report_v}{col_reset}"
- )
- elif cli_v and not mismatch:
- # Still show the resolved path; version already matches header.
- pass
+ print(f" {dim}--version: {cli_v}{reset}")
+ print(f" {dim}health_report.driver_version: {report_v}{reset}")
if mismatch:
- warn = col_yellow if color else ""
- print(
- f" {warn}⚠️ version mismatch: health_report says {report_v!r} "
- f"but binary --version is {cli_v!r}{col_reset}"
- )
- print(
- f" {col_dim}→ trust --version / packages/current for debugging; "
- f"health_report's binary_version check can lag on Windows{col_reset}"
- )
+ print(f" {yellow}⚠️ version mismatch: health_report says {report_v!r} but binary --version is {cli_v!r}{reset}")
+ print(f" {dim}→ trust --version / packages/current for debugging; health_report's binary_version check can lag on Windows{reset}")
for check in report.get("checks", []):
name = check.get("name", "?")
status = check.get("status", "?")
glyph = _STATUS_GLYPH.get(status, "•")
message = check.get("message") or ""
- if color:
- status_col = {
- "pass": col_green, "fail": col_red, "skip": col_dim,
- }.get(status, "")
- print(f" {glyph} {status_col}{name}{col_reset}: {message}")
- else:
- print(f" {glyph} {name}: {message}")
+ print(f" {glyph} {status_cols.get(status, '')}{name}{reset}: {message}")
hint = check.get("hint")
if hint:
- print(f" → {col_dim}{hint}{col_reset}")
- # `data` is the structured payload some checks attach (bundle id,
- # AX permission state, version triple, etc.). Surface when present
- # because users / support staff frequently need it.
+ print(f" → {dim}{hint}{reset}")
+ # `data` is the structured payload some checks attach (bundle id, AX
+ # state, version triple) — users / support staff frequently need it.
data = check.get("data")
if isinstance(data, dict) and data:
for key, value in data.items():
- rendered = value if not isinstance(value, (dict, list)) else json.dumps(value)
- print(f" {col_dim}{key}={rendered}{col_reset}")
- _ = schema # acknowledge field for forward-compat readers
-
-
-def run_doctor(
- driver_cmd: Optional[str] = None,
- *,
- include: Sequence[str] = (),
- skip: Sequence[str] = (),
- json_output: bool = False,
- color: Optional[bool] = None,
-) -> int:
- """Resolve the cua-driver binary, call `health_report`, render the result.
+ rendered = json.dumps(value) if isinstance(value, (dict, list)) else value
+ print(f" {dim}{key}={rendered}{reset}")
- Honors `HERMES_CUA_DRIVER_CMD` via the shared runtime resolver, so the
- doctor diagnoses what your `computer_use` toolset will actually invoke.
- On cua-driver 0.10.x, ``health_report`` may be risk-unclassified and
- denied; doctor then synthesizes a schema_version=1 report from
- check_permissions / list_apps / CLI probes instead of printing
- ``• cua-driver ? on ? — ?``.
+def run_doctor(driver_cmd: Optional[str] = None, *, include: Sequence[str] = (), skip: Sequence[str] = (),
+ json_output: bool = False, color: Optional[bool] = None) -> int:
+ """Resolve the cua-driver binary, call `health_report`, render the result.
+
+ Honors `HERMES_CUA_DRIVER_CMD` via the shared runtime resolver, so doctor
+ diagnoses what `computer_use` will actually invoke. On 0.10.x (health_report
+ denied) it synthesizes a report from check_permissions / list_apps / CLI probes.
"""
- # Windows ships stdout/stderr wrapped with the system ANSI codec
- # (`cp1252` on a US locale, `cp936` on zh-CN, etc.). The check-matrix
- # output below contains ✅ ❌ ⚠️ ⏭️ glyphs — none of them encodable
- # in those codepages. Switch stdout to UTF-8 once, idempotently: every
- # supported TextIOWrapper (Py3.7+) has `.reconfigure`, and a no-op
- # re-encode is cheap if we were already UTF-8.
+ # Windows' locale codec (cp1252, cp936, ...) cannot encode the ✅ ❌ ⚠️ ⏭️ glyphs — force UTF-8.
for stream in (sys.stdout, sys.stderr):
try:
stream.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]
@@ -873,9 +555,7 @@ def run_doctor(
return 2
try:
- report = _drive_health_report_or_fallback(
- binary, include=include, skip=skip,
- )
+ report = _drive_health_report_or_fallback(binary, include=include, skip=skip)
except RuntimeError as e:
print(f"cua-driver health_report failed: {e}", file=sys.stderr)
return 2
@@ -883,9 +563,8 @@ def run_doctor(
identity = _build_identity(binary, report)
if json_output:
- # Additive envelope: preserve the upstream health_report keys and
- # attach Hermes identity under hermes_identity so existing parsers
- # that only read overall/checks keep working.
+ # Additive envelope: upstream health_report keys preserved, Hermes identity
+ # under hermes_identity so parsers that only read overall/checks keep working.
payload = dict(report)
payload["hermes_identity"] = identity
json.dump(payload, sys.stdout, indent=2, sort_keys=True)
@@ -895,10 +574,5 @@ def run_doctor(
color = sys.stdout.isatty()
_print_text_report(report, color=bool(color), identity=identity)
- overall = report.get("overall")
- if overall in ("degraded", "failed"):
- return 1
- if overall != "ok":
- # Unknown / missing overall after fallback should not look like success.
- return 1
- return 0
+ # Unknown / missing overall after fallback must not look like success.
+ return 0 if report.get("overall") == "ok" else 1
diff --git a/tools/computer_use/permissions.py b/tools/computer_use/permissions.py
index 65eac7877c1..11bb56d785f 100644
--- a/tools/computer_use/permissions.py
+++ b/tools/computer_use/permissions.py
@@ -1,24 +1,18 @@
"""
Cross-platform Computer Use readiness + macOS permission helpers.
-cua-driver runs on macOS, Windows, and Linux, but "ready to drive" means
-something different on each:
-
- * macOS — explicit TCC grants (Accessibility + Screen Recording). cua-driver
- reports/requests them via ``permissions status`` / ``permissions grant``.
- The grants attach to cua-driver's OWN identity (``com.trycua.driver`` /
- the installed ``CuaDriver.app``), NOT Hermes — so no Hermes entitlement is
- involved, and ``grant`` launches CuaDriver via LaunchServices so the macOS
- dialog is attributed correctly.
- * Windows — no TCC toggles; the UIAccess worker (``cua-driver-uia.exe``) may
- trip a SmartScreen prompt on first run. Readiness == driver health.
- * Linux — assistive control via the X11/XWayland stack. Readiness == driver
- health.
-
-The universal signal on every platform is ``cua-driver doctor --json`` (binary
-integrity + platform support). ``computer_use_status`` folds that together with
-the macOS permission detail into one payload for the desktop card, the
-``hermes computer-use permissions`` CLI, and ``/api/tools/computer-use/status``.
+"Ready to drive" differs per platform:
+ * macOS — explicit TCC grants (Accessibility + Screen Recording), reported /
+ requested via cua-driver ``permissions status`` / ``permissions grant``. The
+ grants attach to cua-driver's OWN identity (``com.trycua.driver``), not
+ Hermes, so ``grant`` launches CuaDriver via LaunchServices for correct
+ dialog attribution.
+ * Windows / Linux — no TCC toggles; readiness == driver health.
+
+``cua-driver doctor --json`` is the universal signal; ``computer_use_status``
+folds it with the macOS permission detail into one payload for the desktop
+card, the ``hermes computer-use permissions`` CLI, and
+``/api/tools/computer-use/status``.
"""
from __future__ import annotations
@@ -44,24 +38,14 @@ def _resolve_driver_cmd(override: Optional[str]) -> Optional[str]:
def _child_env() -> Dict[str, str]:
- """cua-driver child env: telemetry opt-in policy + secret sanitization.
-
- cua-driver is a third-party binary — it must never inherit provider
- API keys (#53503/#55709/#58889 lineage). Each layer degrades
- gracefully so permission probes never break on a helper import error.
- """
- try:
- from tools.computer_use.cua_backend import cua_driver_child_env
-
- env = cua_driver_child_env()
- except Exception:
- env = dict(os.environ)
+ """cua-driver child env (telemetry policy + provider secrets stripped);
+ degrades to ``os.environ`` on import error so probes never break."""
try:
- from tools.environments.local import _sanitize_subprocess_env
+ from tools.computer_use.cua_backend import sanitized_cua_driver_env
- return _sanitize_subprocess_env(env)
+ return sanitized_cua_driver_env()
except Exception:
- return env
+ return dict(os.environ)
def _run(binary: str, *args: str, timeout: float) -> subprocess.CompletedProcess:
@@ -77,7 +61,7 @@ def _run(binary: str, *args: str, timeout: float) -> subprocess.CompletedProcess
def _json_out(binary: str, *args: str, timeout: float) -> Any:
- """Run ``binary args`` and parse stdout as JSON, or ``None`` on any failure."""
+ """Run ``binary args`` and parse stdout as JSON (``None`` on empty output)."""
raw = (_run(binary, *args, timeout=timeout).stdout or "").strip()
return json.loads(raw) if raw else None
@@ -91,11 +75,7 @@ def _doctor(binary: str) -> Optional[Dict[str, Any]]:
if not isinstance(data, dict):
return None
checks: List[Dict[str, str]] = [
- {
- "label": str(p.get("label", "")),
- "status": str(p.get("status", "")),
- "message": str(p.get("message", "")),
- }
+ {k: str(p.get(k, "")) for k in ("label", "status", "message")}
for p in data.get("probes", [])
if isinstance(p, dict)
]
@@ -128,15 +108,9 @@ def computer_use_status(driver_cmd: Optional[str] = None) -> Dict[str, Any]:
plat = sys.platform
binary = _resolve_driver_cmd(driver_cmd)
out: Dict[str, Any] = {
- "platform": plat,
- "platform_supported": plat in _RUNTIME_PLATFORMS,
- "installed": bool(binary),
- "version": None,
- "ready": None,
- "can_grant": plat == "darwin",
- "checks": [],
- "source": None,
- "error": None,
+ "platform": plat, "platform_supported": plat in _RUNTIME_PLATFORMS,
+ "installed": bool(binary), "version": None, "ready": None,
+ "can_grant": plat == "darwin", "checks": [], "source": None, "error": None,
**{k: None for k in _BOOLS},
}
if not binary:
@@ -156,18 +130,15 @@ def computer_use_status(driver_cmd: Optional[str] = None) -> Dict[str, Any]:
if out["error"] is None:
out["ready"] = out["accessibility"] is True and out["screen_recording"] is True
elif doctor is not None:
- # No TCC model off macOS — readiness is driver health.
- out["ready"] = doctor["ok"]
+ out["ready"] = doctor["ok"] # no TCC model off macOS
return out
def request_permissions_grant(driver_cmd: Optional[str] = None) -> int:
"""Run ``cua-driver permissions grant`` (macOS); stream its output.
- Launches CuaDriver via LaunchServices so the TCC dialog is attributed to
- ``com.trycua.driver``, then waits for the grant. Returns the driver's exit
- code (0 ok), 2 if the binary is missing, 64 on a non-macOS platform (which
- has no TCC permission model to grant).
+ Returns the driver's exit code (0 ok), 2 if the binary is missing, 64 on a
+ non-macOS platform (no TCC model to grant).
"""
if sys.platform != "darwin":
print("Computer Use permissions are a macOS concept; nothing to grant here.")
@@ -184,13 +155,8 @@ def request_permissions_grant(driver_cmd: Optional[str] = None) -> int:
"approve it, then return here."
)
try:
- return int(
- subprocess.run(
- [binary, "permissions", "grant"],
- env=_child_env(),
- stdin=subprocess.DEVNULL,
- ).returncode
- )
+ return int(subprocess.run([binary, "permissions", "grant"], env=_child_env(),
+ stdin=subprocess.DEVNULL).returncode)
except KeyboardInterrupt: # pragma: no cover - interactive
return 130
except Exception as exc: # pragma: no cover - defensive
diff --git a/tools/computer_use/tool.py b/tools/computer_use/tool.py
index 0b3801b5157..118bbe2aabf 100644
--- a/tools/computer_use/tool.py
+++ b/tools/computer_use/tool.py
@@ -1,67 +1,38 @@
"""Entry point for the `computer_use` tool.
-Universal (any-model) desktop control across macOS, Windows, and Linux via
-cua-driver's background computer-use primitive. Replaces #4562's
-Anthropic-native `computer_20251124` approach — the schema here is standard
-OpenAI function-calling so every tool-capable model can drive it.
-
-Linux is the most recent runtime (X11 + Wayland, via cua-driver-rs's
-AT-SPI tree path); it is enabled here alongside macOS and Windows. When a
-host's display server or accessibility stack isn't reachable, cua-driver's
-`health_report` (surfaced by `hermes computer-use doctor`) reports the
-exact blocked check rather than the toolset silently failing.
-
-Return contract
----------------
-For text-only results (wait, key, list_apps, focus_app, failures, etc.):
- JSON string.
-
-For captures / actions with `capture_after=True`:
- A dict wrapped as the OpenAI-style multi-part tool-message content:
-
- {
- "_multimodal": True,
- "content": [
- {"type": "text", "text": "<human-readable summary + SOM index>"},
- {"type": "image_url",
- "image_url": {"url": "data:image/png;base64,<b64>"}},
- ],
- "text_summary": "<text used for fallback string content>",
- }
-
- run_agent.py's tool-message builder inspects `_multimodal` and emits a
- list-shaped `content` for OpenAI-compatible providers. The Anthropic
- adapter splices the base64 image into a `tool_result` block (see
- `agent/anthropic_adapter.py`). Every provider that supports multi-part
- tool content gets the image; text-only providers see the summary only.
+Any-model desktop control (macOS/Windows/Linux) via cua-driver; standard OpenAI
+function-calling schema. Return contract: text-only results are a JSON string;
+captures / `capture_after=True` return ``{"_multimodal": True, "content":
+[text part, image_url part], "text_summary": <fallback>}`` which run_agent.py /
+the Anthropic adapter turn into provider-specific image tool content.
"""
from __future__ import annotations
import atexit
import base64
+import contextlib
import json
import logging
import os
import re
-import struct
import sys
import threading
-from typing import Any, Dict, List, Optional, Tuple
+import uuid
+from typing import Any, Callable, Dict, List, Optional, Tuple
from tools.computer_use.backend import (
ActionResult,
CaptureResult,
ComputerUseBackend,
UIElement,
+ image_dimensions_from_bytes,
)
logger = logging.getLogger(__name__)
-# ---------------------------------------------------------------------------
-# Approval & safety
-# ---------------------------------------------------------------------------
+# ── Approval & safety ───────────────────────────────────────────────────────
_approval_callback = None
@@ -69,36 +40,31 @@ _approval_callback = None
def set_approval_callback(cb) -> None:
"""Register a callback for computer_use approval prompts (used by CLI).
- Matches the terminal_tool._approval_callback pattern. The callback
- receives (action, args, summary) and returns one of:
- "approve_once" | "approve_session" | "always_approve" | "deny".
+ Matches the terminal_tool._approval_callback pattern. The callback receives
+ (action, args, summary) and returns one of
+ "approve_once" | "approve_session" | "always_approve" | "deny".
"""
global _approval_callback
_approval_callback = cb
# Actions that read, not mutate. Always allowed.
-_SAFE_ACTIONS = frozenset({
- "capture", "wait", "list_apps", "list_windows",
-})
+_SAFE_ACTIONS = frozenset({"capture", "wait", "list_apps", "list_windows"})
# Actions that mutate user-visible state. Go through approval.
-_DESTRUCTIVE_ACTIONS = frozenset({
- "click", "double_click", "right_click", "middle_click",
- "drag", "scroll", "type", "key", "set_value", "focus_app",
-})
+_DESTRUCTIVE_ACTIONS = frozenset({"click", "double_click", "right_click", "middle_click",
+ "drag", "scroll", "type", "key", "set_value", "focus_app"})
-# Hard-blocked key combinations. Mirrored from #4562 — these are destructive
-# regardless of approval level (e.g. logout kills the session Hermes runs in).
+# Hard-blocked key combinations: destructive regardless of approval level
+# (e.g. logout kills the session Hermes runs in).
_BLOCKED_KEY_COMBOS = {
frozenset({"cmd", "shift", "backspace"}), # empty trash
frozenset({"cmd", "option", "backspace"}), # force delete
frozenset({"cmd", "ctrl", "q"}), # lock screen
frozenset({"cmd", "shift", "q"}), # log out
frozenset({"cmd", "option", "shift", "q"}), # force log out
- # Windows secure/session shortcuts. The Windows driver accepts Win-key
- # combos, and Alt is canonicalized to option below, so block the
- # destructive variants before any backend sees them.
+ # Windows secure/session shortcuts. Alt is canonicalized to option below,
+ # so block the destructive variants before any backend sees them.
frozenset({"win", "l"}),
frozenset({"ctrl", "option", "delete"}),
frozenset({"ctrl", "option", "del"}),
@@ -112,146 +78,99 @@ _KEY_ALIASES = {
def _canon_key_combo(keys: str) -> frozenset:
- # Split on both "+" and "-": the cua-driver backend's _parse_key_combo
- # accepts hyphen-separated combos too, so "ctrl-alt-delete" executes as
- # the real destructive shortcut. Mirror its separators here, otherwise the
- # _BLOCKED_KEY_COMBOS gate is trivially bypassed with hyphen notation.
+ # Split on both "+" and "-": the cua-driver backend accepts hyphen-separated
+ # combos too, so "ctrl-alt-delete" would bypass the gate otherwise.
parts = [p.strip().lower() for p in re.split(r"\s*[+\-]\s*", keys) if p.strip()]
- parts = [_KEY_ALIASES.get(p, p) for p in parts]
- return frozenset(parts)
-
-
-# Native input actions that deliver to the backend's sticky target. `app=`
-# on these calls is NOT a targeting parameter — see the mismatch guard in
-# _dispatch. Kept in sync with the dispatch branches below.
-_INPUT_ACTIONS = frozenset({
- "click", "double_click", "right_click", "middle_click",
- "drag", "scroll", "type", "key", "set_value",
-})
+ return frozenset(_KEY_ALIASES.get(p, p) for p in parts)
def _input_target_mismatch(backend, requested_app: str) -> Optional[str]:
- """Current sticky-target app when it clearly differs from *requested_app*.
-
- Returns the CURRENT target's app name only for a provable mismatch:
- both names known and neither a substring of the other (list_windows
- app names are localized/variant — 'Google-chrome' vs 'chrome'). An
- unknown current target returns None (fail open: legacy flows that
- never pass app= on input keep working; wrong-window delivery there is
- caught by the verify ladder instead).
+ """Current sticky-target app when it provably differs from *requested_app*.
+
+ Both names must be known and neither a substring of the other (app names
+ are localized/variant — 'Google-chrome' vs 'chrome'). Unknown current target
+ -> None (fail open; wrong-window delivery is caught by the verify ladder).
"""
current = (getattr(backend, "_last_app", None) or "").strip().lower()
wanted = requested_app.strip().lower()
- if not current or not wanted:
- return None
- if wanted in current or current in wanted:
+ if not current or not wanted or wanted in current or current in wanted:
return None
return getattr(backend, "_last_app", None)
-# Dangerous text patterns for the `type` action. Same list as #4562.
-_BLOCKED_TYPE_PATTERNS = [
- re.compile(r"curl\s+[^|]*\|\s*bash", re.IGNORECASE),
- re.compile(r"curl\s+[^|]*\|\s*sh", re.IGNORECASE),
- re.compile(r"wget\s+[^|]*\|\s*bash", re.IGNORECASE),
- re.compile(r"\bsudo\s+rm\s+-[rf]", re.IGNORECASE),
- re.compile(r"\brm\s+-rf\s+/\s*$", re.IGNORECASE),
- re.compile(r":\s*\(\)\s*\{\s*:\|:\s*&\s*\}", re.IGNORECASE), # fork bomb
-]
+# Dangerous text patterns for the `type` action.
+_BLOCKED_TYPE_PATTERNS = [re.compile(p, re.IGNORECASE) for p in (
+ r"curl\s+[^|]*\|\s*bash", r"curl\s+[^|]*\|\s*sh", r"wget\s+[^|]*\|\s*bash",
+ r"\bsudo\s+rm\s+-[rf]", r"\brm\s+-rf\s+/\s*$",
+ r":\s*\(\)\s*\{\s*:\|:\s*&\s*\}", # fork bomb
+)]
def _is_blocked_type(text: str) -> Optional[str]:
- for pat in _BLOCKED_TYPE_PATTERNS:
- if pat.search(text):
- return pat.pattern
- return None
+ return next((pat.pattern for pat in _BLOCKED_TYPE_PATTERNS if pat.search(text)), None)
-# ---------------------------------------------------------------------------
-# Backend selection — env-swappable for tests
-# ---------------------------------------------------------------------------
+# ── Backend selection — env-swappable for tests ─────────────────────────────
-# Per-Hermes-session cached backends. Each backend owns its own cua-driver
-# session, native target, typed-browser binding, refs, and grant namespace.
+# Per-Hermes-session cached backends; each owns its own cua-driver session,
+# native target, refs, and grant namespace.
_backend_lock = threading.Lock()
-# Backward-compatible empty-session injection hook used by older tests.
# Process-scoped aux-vision routing cache: (provider, model) → bool.
_AUX_VISION_ROUTE_CACHE: Dict[Tuple[str, str], bool] = {}
+# `_backend` is the backward-compatible empty-session injection hook (older tests).
_backend: Optional[ComputerUseBackend] = None
_backends: Dict[str, ComputerUseBackend] = {}
_backend_call_locks: Dict[str, threading.RLock] = {}
_backend_permission_modes: Dict[str, str] = {}
-# Approval state, scoped per conversation/run (keyed by session_id) so a
-# gateway serving concurrent sessions can't leak one run's "always approve"
-# unlock into another. Falls back to a shared "" bucket for callers that
-# don't pass a session_id (e.g. the classic single-run CLI). Values:
+# Approval state, scoped per conversation/run (keyed by session_id) so a gateway
+# serving concurrent sessions can't leak one run's "always approve" unlock into
+# another. Callers without a session_id share the "" bucket.
# _session_auto_approve[sid] -> bool ("always_approve everything")
# _always_allow[sid] -> set of (action, delivery_mode) scope keys
-# See NousResearch/hermes-agent#67052 gap 4.
_approval_lock = threading.Lock()
_session_auto_approve: Dict[str, bool] = {}
_always_allow: Dict[str, set] = {}
-
-# Sessions already told that their approval bypass widened the driver mode.
-# The resolver runs per dispatch, so without this the warning would repeat on
-# every single tool call.
+# Sessions already warned that a bypass widened the driver mode (resolver runs per dispatch).
_escalation_warned: set = set()
def _warn_bypass_escalation(session_id: str) -> None:
- """Say out loud that an approval bypass just widened the driver's mode.
-
- ``-z`` / ``--yolo`` read as "don't prompt me", but they also swap the
- driver onto a private ``unrestricted`` daemon, dropping the ceiling the
- configured mode would have applied. That is deliberate (see
- ``_cua_permission_mode``) and ``unrestricted`` is reachable no other way
- — it is intentionally not a config value, so a stale config line cannot
- silently bypass approvals. But it is easy to trigger without meaning to:
- a script gets ``-z`` for quiet output and loses its limits as a side
- effect. So the widening is at least stated, once per session.
- """
+ """Warn once per session that ``-z``/``--yolo`` swapped the driver onto a private
+ ``unrestricted`` daemon, dropping the configured ceiling. Deliberate (``unrestricted``
+ is intentionally not a config value), but easy to trigger by accident."""
key = str(session_id or "")
with _approval_lock:
if key in _escalation_warned:
return
_escalation_warned.add(key)
- try:
- from tools.computer_use.cua_backend import _cua_configured_permission_mode
-
- configured = _cua_configured_permission_mode()
- except Exception:
- configured = "standard"
+ configured = _configured_permission_mode()
logger.warning(
"computer_use: approval bypass (--yolo / -z) escalated the cua-driver "
"permission mode from the configured '%s' to 'unrestricted' for this "
"session. Runtime approval prompts are disabled and the driver's "
"residual ceilings no longer apply. Drop the bypass flag to keep '%s', "
"or declare a version-3 computer_use.capability_manifest to keep a "
- "ceiling on bypassed runs.",
- configured,
- configured,
- )
+ "ceiling on bypassed runs.", configured, configured)
+
+
+def _configured_permission_mode() -> str:
+ """Configured cua mode (standard | bounded); "standard" if unresolvable. bounded
+ needs computer_use.capability_manifest; the backend fails loudly without it."""
+ try:
+ from tools.computer_use.cua_backend import _cua_configured_permission_mode
+
+ return _cua_configured_permission_mode()
+ except Exception:
+ return "standard"
def _cua_permission_mode(session_id: str) -> str:
- """Map Hermes's explicit approval bypass onto Cua's immutable mode.
-
- Hermes has TWO session-identity namespaces: the tool-dispatch path passes
- the DB ``session_id`` (``agent.session_id``), while gateway ``/yolo``
- keys approval state off the gateway ``session_key`` (set per turn via the
- ``set_current_session_key`` contextvar in tools/approval.py). CLI and TUI
- use the DB id for both. Checking ONLY ``session_id`` here would make a
- gateway ``/yolo`` toggle silently invisible to computer_use (works in
- CLI, dead on messaging platforms), so we consult both namespaces —
- bypass in either means the user explicitly opted out of approvals for
- this run. Fails closed on any resolution error.
- """
+ """Map Hermes's approval bypass onto Cua's immutable mode. Both identity
+ namespaces are consulted — DB ``session_id`` and gateway ``session_key``
+ contextvar — or a gateway ``/yolo`` would be invisible here. Fails closed."""
try:
- from tools.approval import (
- get_current_session_key,
- is_approval_bypass_active_for_session,
- )
+ from tools.approval import get_current_session_key, is_approval_bypass_active_for_session
if is_approval_bypass_active_for_session(session_id):
_warn_bypass_escalation(session_id)
@@ -261,98 +180,83 @@ def _cua_permission_mode(session_id: str) -> str:
_warn_bypass_escalation(session_id)
return "unrestricted"
except Exception:
- # Approval state must fail closed if it cannot be resolved.
pass
- try:
- # Without YOLO, honor the configured mode (standard | bounded).
- # bounded requires computer_use.capability_manifest; the backend
- # fails loudly at session start when the manifest is missing.
- from tools.computer_use.cua_backend import _cua_configured_permission_mode
+ return _configured_permission_mode()
- return _cua_configured_permission_mode()
- except Exception:
- return "standard"
+
+def _new_backend(permission_mode: str) -> ComputerUseBackend:
+ backend_name = os.environ.get("HERMES_COMPUTER_USE_BACKEND", "cua").lower()
+ if backend_name in {"cua", "cua-driver", ""}:
+ from tools.computer_use.cua_backend import CuaDriverBackend
+
+ return CuaDriverBackend(permission_mode=permission_mode)
+ if backend_name == "noop": # pragma: no cover
+ return _NoopBackend()
+ raise RuntimeError(f"Unknown HERMES_COMPUTER_USE_BACKEND={backend_name!r}")
+
+
+def _install_backend(sid: str, backend: ComputerUseBackend, permission_mode: str) -> None:
+ """Record a backend in the session caches. Caller holds ``_backend_lock``."""
+ _backends[sid] = backend
+ _backend_call_locks[sid] = threading.RLock()
+ _backend_permission_modes[sid] = permission_mode
+
+
+def _stop_backend(backend: ComputerUseBackend, call_lock: Optional[threading.RLock]) -> None:
+ """Stop under the session call lock (if any) so an in-flight action finishes first.
+ Never called under ``_backend_lock``: unrelated sessions stay free meanwhile. Raises."""
+ if call_lock is not None:
+ with call_lock:
+ backend.stop()
+ else:
+ backend.stop()
def _get_backend(session_id: str = "") -> ComputerUseBackend:
global _backend
sid = str(session_id or "")
while True:
- stale_backend: Optional[ComputerUseBackend] = None
- stale_lock: Optional[threading.RLock] = None
with _backend_lock:
- # Resolve the mode while holding the cache lock. Session YOLO
- # mutation never holds the approval lock while releasing this
- # cache, so the lock order cannot cycle.
+ # Resolve the mode under the cache lock; YOLO mutation never holds
+ # the approval lock while releasing this cache, so no lock cycle.
permission_mode = _cua_permission_mode(sid)
if sid == "" and _backend is not None and sid not in _backends:
- # Preserve the long-standing empty-session injection hook used
- # by integrations and tests while normalizing it into the
- # session-owned cache/lifecycle path.
- _backends[sid] = _backend
- _backend_call_locks[sid] = threading.RLock()
- _backend_permission_modes[sid] = permission_mode
+ # Fold the empty-session injection hook into the session cache.
+ _install_backend(sid, _backend, permission_mode)
cached = _backends.get(sid)
- if cached is not None:
- if _backend_permission_modes.get(sid, "standard") == permission_mode:
- return cached
- # Cua's permission mode cannot change after daemon startup. A
- # /yolo toggle replaces only this session's backend.
- stale_backend = _backends.pop(sid)
- stale_lock = _backend_call_locks.pop(sid, None)
- _backend_permission_modes.pop(sid, None)
- if sid == "":
- _backend = None
- else:
- backend_name = os.environ.get(
- "HERMES_COMPUTER_USE_BACKEND", "cua"
- ).lower()
- if backend_name in {"cua", "cua-driver", ""}:
- from tools.computer_use.cua_backend import CuaDriverBackend
-
- backend = CuaDriverBackend(permission_mode=permission_mode)
- elif backend_name == "noop": # pragma: no cover
- backend = _NoopBackend()
- else:
- raise RuntimeError(
- f"Unknown HERMES_COMPUTER_USE_BACKEND={backend_name!r}"
- )
- # Starting under the cache lock preserves the existing
- # one-backend-per-session invariant. A concurrent mode toggle
- # releases this backend before returning to its caller.
+ if cached is None:
+ backend = _new_backend(permission_mode)
+ # Starting under the cache lock preserves one-backend-per-session.
+ # A concurrent mode toggle releases this backend before returning.
backend.start()
- _backends[sid] = backend
- _backend_call_locks[sid] = threading.RLock()
- _backend_permission_modes[sid] = permission_mode
+ _install_backend(sid, backend, permission_mode)
if sid == "":
_backend = backend
return backend
-
- # Stop a mismatched backend outside the global cache lock. Another
- # session can continue creating or releasing its own backend, and the
- # loop re-reads the authoritative mode before installing a replacement.
+ if _backend_permission_modes.get(sid, "standard") == permission_mode:
+ return cached
+ # Cua's permission mode cannot change after daemon startup. A /yolo
+ # toggle replaces only this session's backend.
+ stale_backend = _backends.pop(sid)
+ stale_lock = _backend_call_locks.pop(sid, None)
+ _backend_permission_modes.pop(sid, None)
+ if sid == "":
+ _backend = None
+
+ # Stop outside the cache lock; the loop re-reads the authoritative mode
+ # before installing a replacement.
try:
- if stale_lock is not None:
- with stale_lock:
- stale_backend.stop()
- elif stale_backend is not None:
- stale_backend.stop()
+ _stop_backend(stale_backend, stale_lock)
except Exception:
pass
def release_computer_use_session(session_id: str) -> bool:
- """Release one session-owned computer-use backend.
+ """Release one session-owned backend (lifecycle seam for hosts/plugins).
- This is the production lifecycle seam for hosts and policy plugins. It
- removes the exact session backend, its call lock, and its recorded
- permission mode before stopping the backend, so new lookups cannot retain
- the stale target/ref namespace — and stops a private embedded daemon when
- Hermes YOLO selected unrestricted mode. Approval state is cleared even
- when no backend was started.
-
- Returns ``True`` when a backend was found and released, ``False`` when the
- session was already absent. Safe to call repeatedly.
+ Cache entries are removed BEFORE stopping so new lookups cannot retain the
+ stale target/ref namespace; approval state is cleared even without a backend.
+ Returns True when a backend was released, False if already absent; idempotent.
"""
global _backend
sid = str(session_id or "")
@@ -360,8 +264,7 @@ def release_computer_use_session(session_id: str) -> bool:
backend = _backends.pop(sid, None)
call_lock = _backend_call_locks.pop(sid, None)
_backend_permission_modes.pop(sid, None)
- # Preserve the backward-compatible empty-session injection hook:
- # older callers/tests may populate only `_backend`.
+ # Older callers/tests may populate only the `_backend` injection hook.
if sid == "" and backend is None:
backend = _backend
if sid == "" and _backend is backend:
@@ -370,71 +273,36 @@ def release_computer_use_session(session_id: str) -> bool:
with _approval_lock:
_session_auto_approve.pop(sid, None)
_always_allow.pop(sid, None)
-
if backend is None:
return False
try:
- # Let an in-flight action finish before ending the driver session and
- # dropping its target/ref state. Do not hold the global cache lock
- # while waiting: unrelated Hermes sessions remain independent.
- if call_lock is not None:
- with call_lock:
- backend.stop()
- else:
- backend.stop()
+ _stop_backend(backend, call_lock)
except Exception:
- logger.debug(
- "computer_use backend release failed for session %s",
- sid,
- exc_info=True,
- )
+ logger.debug("computer_use backend release failed for session %s", sid, exc_info=True)
return True
def _shutdown_backend_atexit() -> None:
- """Stop all cached backends so cua-driver children don't outlive us.
-
- Each session backend holds a long-lived ``cua-driver`` subprocess, so
- without this a driver can survive the Hermes process that spawned it
- (#28152 item 3). #69903 kept the orphan from burning a core by disabling
- the cursor overlay; the process itself still lingered.
-
- Mirrors ``browser_tool``'s ``atexit.register(_emergency_cleanup_all_sessions)``
- — same spawn-and-drive-a-subprocess shape. atexit only, no signal handlers:
- a ``SystemExit`` raised from a prompt_toolkit key binding corrupts its
- coroutine state and makes the process unkillable. Never raises, since an
- exception escaping atexit prints a traceback on every exit.
- """
+ """Stop all cached backends so cua-driver subprocesses don't outlive us.
+ atexit only, no signal handlers: a ``SystemExit`` from a prompt_toolkit key
+ binding corrupts its coroutine state and makes the process unkillable. Never raises."""
global _backend
# Drop the global lock before stop() — teardown budgets 5s and shouldn't
# block an unrelated caller waiting to spawn.
with _backend_lock:
- unique = {
- id(backend): (backend, _backend_call_locks.get(sid))
- for sid, backend in _backends.items()
- }
+ unique = {id(b): (b, _backend_call_locks.get(sid)) for sid, b in _backends.items()}
if _backend is not None:
- unique.setdefault(
- id(_backend),
- (_backend, _backend_call_locks.get("")),
- )
+ unique.setdefault(id(_backend), (_backend, _backend_call_locks.get("")))
_backend = None
- _backends.clear()
- _backend_call_locks.clear()
- _backend_permission_modes.clear()
-
+ for cache in (_backends, _backend_call_locks, _backend_permission_modes):
+ cache.clear()
with _approval_lock:
- _session_auto_approve.clear()
- _always_allow.clear()
- _escalation_warned.clear()
+ for cache in (_session_auto_approve, _always_allow, _escalation_warned):
+ cache.clear()
for backend, call_lock in unique.values():
try:
- if call_lock is not None:
- with call_lock:
- backend.stop()
- else:
- backend.stop()
+ _stop_backend(backend, call_lock)
except Exception as e:
logger.debug("cua-driver atexit teardown failed: %s", e)
@@ -459,124 +327,81 @@ class _NoopBackend(ComputerUseBackend): # pragma: no cover
def stop(self) -> None: self._started = False
def is_available(self) -> bool: return True
- def capture(
- self,
- mode: str = "som",
- app: Optional[str] = None,
- pid: Optional[int] = None,
- window_id: Optional[int] = None,
- ) -> CaptureResult:
- self.calls.append((
- "capture",
- {"mode": mode, "app": app, "pid": pid, "window_id": window_id},
- ))
- return CaptureResult(mode=mode, width=1024, height=768, png_b64=None,
- elements=[], app=app or "", window_title="")
-
- def click(self, **kw) -> ActionResult:
- self.calls.append(("click", kw))
- return ActionResult(ok=True, action="click")
-
- def drag(self, **kw) -> ActionResult:
- self.calls.append(("drag", kw))
- return ActionResult(ok=True, action="drag")
-
- def scroll(self, **kw) -> ActionResult:
- self.calls.append(("scroll", kw))
- return ActionResult(ok=True, action="scroll")
+ def _record(self, name: str, kw: Dict[str, Any]) -> ActionResult:
+ self.calls.append((name, kw))
+ return ActionResult(ok=True, action=name)
- def type_text(self, text: str, **kw) -> ActionResult:
- self.calls.append(("type", {"text": text, **kw}))
- return ActionResult(ok=True, action="type")
+ def _record_list(self, name: str) -> List[Dict[str, Any]]:
+ self.calls.append((name, {}))
+ return []
- def key(self, keys: str, **kw) -> ActionResult:
- self.calls.append(("key", {"keys": keys, **kw}))
- return ActionResult(ok=True, action="key")
+ def capture(self, mode: str = "som", app: Optional[str] = None,
+ pid: Optional[int] = None, window_id: Optional[int] = None) -> CaptureResult:
+ self.calls.append(("capture", {"mode": mode, "app": app, "pid": pid, "window_id": window_id}))
+ return CaptureResult(mode=mode, width=1024, height=768, png_b64=None,
+ elements=[], app=app or "", window_title="")
- def list_apps(self) -> List[Dict[str, Any]]:
- self.calls.append(("list_apps", {}))
- return []
+ def click(self, **kw) -> ActionResult: return self._record("click", kw)
+ def drag(self, **kw) -> ActionResult: return self._record("drag", kw)
+ def scroll(self, **kw) -> ActionResult: return self._record("scroll", kw)
+ def type_text(self, text: str, **kw) -> ActionResult: return self._record("type", {"text": text, **kw})
+ def key(self, keys: str, **kw) -> ActionResult: return self._record("key", {"keys": keys, **kw})
- def list_windows(self) -> List[Dict[str, Any]]:
- self.calls.append(("list_windows", {}))
- return []
+ def list_apps(self) -> List[Dict[str, Any]]: return self._record_list("list_apps")
+ def list_windows(self) -> List[Dict[str, Any]]: return self._record_list("list_windows")
def focus_app(self, app: str, raise_window: bool = False) -> ActionResult:
- self.calls.append(("focus_app", {"app": app, "raise": raise_window}))
- return ActionResult(ok=True, action="focus_app")
+ return self._record("focus_app", {"app": app, "raise": raise_window})
def set_value(self, value: str, element: Optional[int] = None) -> ActionResult:
- self.calls.append(("set_value", {"value": value, "element": element}))
- return ActionResult(ok=True, action="set_value")
+ return self._record("set_value", {"value": value, "element": element})
-# ---------------------------------------------------------------------------
-# Dispatch
-# ---------------------------------------------------------------------------
+# ── Dispatch ────────────────────────────────────────────────────────────────
def handle_computer_use(args: Dict[str, Any], **kwargs) -> Any:
- """Main entry point — dispatched by tools.registry.
-
- Returns either a JSON string (text-only) or a dict marked `_multimodal`
- (image + summary) which run_agent.py wraps into the tool message.
- """
+ """Main entry point — dispatched by tools.registry. Returns a JSON string
+ (text-only) or a dict marked `_multimodal` (image + summary)."""
action = (args.get("action") or "").strip().lower()
if not action:
return json.dumps({"error": "missing `action`"})
- # Per-run key for approval-state and daemon-mode isolation across
- # concurrent sessions.
+ # Per-run key for approval-state and daemon-mode isolation across sessions.
session_id = str(kwargs.get("session_id") or "")
# Safety: validate actions before approval prompt.
if action == "type":
- text = args.get("text", "")
- pat = _is_blocked_type(text)
+ pat = _is_blocked_type(args.get("text", ""))
if pat:
- return json.dumps({
- "error": f"blocked pattern in type text: {pat!r}",
- "hint": "Dangerous shell patterns cannot be typed via computer_use.",
- })
-
+ return json.dumps({"error": f"blocked pattern in type text: {pat!r}",
+ "hint": "Dangerous shell patterns cannot be typed via computer_use."})
if action == "key":
- keys = args.get("keys", "")
- combo = _canon_key_combo(keys)
+ combo = _canon_key_combo(args.get("keys", ""))
for blocked in _BLOCKED_KEY_COMBOS:
if blocked.issubset(combo) and len(blocked) <= len(combo):
- return json.dumps({
- "error": f"blocked key combo: {sorted(blocked)}",
- "hint": "Destructive system shortcuts are hard-blocked.",
- })
+ return json.dumps({"error": f"blocked key combo: {sorted(blocked)}",
+ "hint": "Destructive system shortcuts are hard-blocked."})
if args.get("bring_to_front") and args.get("delivery_mode") != "foreground":
- return json.dumps({
- "error": "bring_to_front requires delivery_mode='foreground'",
- "code": "bring_to_front_requires_foreground",
- })
-
- # Approval gate (destructive actions only).
- if action in _DESTRUCTIVE_ACTIONS:
- err = _request_approval(action, args, session_id)
- if err is not None:
- return err
- # Persistent focus is a separate, visible side effect from the input
- # itself. Keep its approval scope distinct even when the input rung has
- # already been approved for this session.
- if args.get("bring_to_front") or (
- action == "focus_app" and args.get("raise_window")
- ):
- err = _request_approval("bring_to_front", args, session_id)
+ return json.dumps({"error": "bring_to_front requires delivery_mode='foreground'",
+ "code": "bring_to_front_requires_foreground"})
+
+ # Approval gate (destructive actions only). Persistent focus is a separate,
+ # visible side effect with its own scope even when the input rung is approved.
+ scopes = [action] if action in _DESTRUCTIVE_ACTIONS else []
+ if args.get("bring_to_front") or (action == "focus_app" and args.get("raise_window")):
+ scopes.append("bring_to_front")
+ for scope in scopes:
+ err = _request_approval(scope, args, session_id)
if err is not None:
return err
- # Dispatch to backend.
try:
backend = _get_backend(session_id=session_id)
except Exception as e:
return json.dumps({
"error": f"computer_use backend unavailable: {e}",
"hint": "If the cua-driver binary is missing, run `hermes computer-use install`. "
- "If a Python dependency is missing, the error above shows the exact install command.",
- })
+ "If a Python dependency is missing, the error above shows the exact install command."})
try:
with _backend_lock:
@@ -590,68 +415,49 @@ def handle_computer_use(args: Dict[str, Any], **kwargs) -> Any:
def _request_approval(action: str, args: Dict[str, Any],
session_id: str = "") -> Optional[str]:
- """Return None if approved, or a JSON error string if denied.
-
- Approval is scoped by (action, delivery_mode) AND by session_id.
- Foreground delivery is a visible focus change, so a prior background
- approval — even ``approve_session`` on the same action — must NOT
- silently authorize it (NousResearch/hermes-agent#67052).
- ``always_approve`` (the blanket "auto-approve everything" unlock) still
- covers foreground, since the user explicitly opted into unattended
- operation. State is keyed on session_id so concurrent runs don't leak
- unlocks into one another.
- """
- is_foreground = args.get("delivery_mode") == "foreground"
- scope_key = (action, "foreground" if is_foreground else "background")
+ """None if approved, else a JSON error string. Scoped by (action, delivery_mode)
+ AND session_id: foreground delivery is a visible focus change, so a background
+ ``approve_session`` must NOT cover it; the blanket ``always_approve`` does."""
+ scope_key = (action, "foreground" if args.get("delivery_mode") == "foreground" else "background")
with _approval_lock:
- if _session_auto_approve.get(session_id):
- return None
- if scope_key in _always_allow.get(session_id, set()):
+ if _session_auto_approve.get(session_id) or scope_key in _always_allow.get(session_id, set()):
return None
cb = _approval_callback
if cb is None:
# No CLI approval wired — default allow. Gateway approval is handled
# one layer out via the normal tool-approval infra.
return None
- summary = _summarize_action(action, args)
try:
- verdict = cb(action, args, summary)
+ verdict = cb(action, args, _summarize_action(action, args))
except Exception as e:
logger.warning("approval callback failed: %s", e)
verdict = "deny"
if verdict == "approve_once":
return None
- if verdict == "approve_session" or verdict == "always_approve":
+ if verdict in ("approve_session", "always_approve"):
with _approval_lock:
_always_allow.setdefault(session_id, set()).add(scope_key)
if verdict == "always_approve":
_session_auto_approve[session_id] = True
return None
if verdict == "timeout":
- return json.dumps({
- "error": (
- "approval prompt timed out — the user did not respond. "
- "Silence is not consent; do not retry without the user."
- ),
- "action": action,
- })
+ return json.dumps({"error": ("approval prompt timed out — the user did not respond. "
+ "Silence is not consent; do not retry without the user."),
+ "action": action})
return json.dumps({"error": "denied by user", "action": action})
def _summarize_action(action: str, args: Dict[str, Any]) -> str:
- fg = " [FOREGROUND — briefly raises the window / changes focus]" \
- if args.get("delivery_mode") == "foreground" else ""
- if action in {"click", "double_click", "right_click", "middle_click"}:
+ fg = (" [FOREGROUND — briefly raises the window / changes focus]"
+ if args.get("delivery_mode") == "foreground" else "")
+ if action in _CLICK_VARIANTS:
if args.get("element") is not None:
return f"{action} element #{args['element']}{fg}"
coord = args.get("coordinate")
- if coord:
- return f"{action} at {tuple(coord)}{fg}"
- return action + fg
+ return f"{action} at {tuple(coord)}{fg}" if coord else action + fg
if action == "drag":
- src = args.get("from_element") or args.get("from_coordinate")
- dst = args.get("to_element") or args.get("to_coordinate")
- return f"drag {src} → {dst}{fg}"
+ return (f"drag {args.get('from_element') or args.get('from_coordinate')} → "
+ f"{args.get('to_element') or args.get('to_coordinate')}{fg}")
if action == "scroll":
return f"scroll {args.get('direction', '?')} x{args.get('amount', 3)}{fg}"
if action == "type":
@@ -664,230 +470,193 @@ def _summarize_action(action: str, args: Dict[str, Any]) -> str:
return action + fg
-def _dispatch(backend: ComputerUseBackend, action: str, args: Dict[str, Any]) -> Any:
- capture_after = bool(args.get("capture_after"))
-
- if action == "capture":
- mode = str(args.get("mode", "som"))
- if mode not in {"som", "vision", "ax"}:
- return json.dumps({"error": f"bad mode {mode!r}; use som|vision|ax"})
- capture_kwargs: Dict[str, Any] = {"mode": mode, "app": args.get("app")}
- if args.get("pid") is not None or args.get("window_id") is not None:
- capture_kwargs.update({
- "pid": args.get("pid"),
- "window_id": args.get("window_id"),
- })
- cap = backend.capture(**capture_kwargs)
- return _capture_response(cap)
+# --- read-only / focus actions: (backend, args) -> final tool result ---------
- if action == "wait":
- seconds = float(args.get("seconds", 1.0))
- res = backend.wait(seconds)
- return _text_response(res)
+def _do_capture(backend: ComputerUseBackend, args: Dict[str, Any]) -> Any:
+ mode = str(args.get("mode", "som"))
+ if mode not in {"som", "vision", "ax"}:
+ return json.dumps({"error": f"bad mode {mode!r}; use som|vision|ax"})
+ capture_kwargs: Dict[str, Any] = {"mode": mode, "app": args.get("app")}
+ # pid/window_id forwarded only when given so older backends keep their defaults.
+ if args.get("pid") is not None or args.get("window_id") is not None:
+ capture_kwargs.update({"pid": args.get("pid"), "window_id": args.get("window_id")})
+ return _capture_response(backend.capture(**capture_kwargs))
- if action == "list_apps":
- apps = backend.list_apps()
- return json.dumps({"apps": apps, "count": len(apps)})
- if action == "list_windows":
- windows = backend.list_windows()
- return json.dumps({"windows": windows, "count": len(windows)})
+def _do_focus_app(backend: ComputerUseBackend, args: Dict[str, Any]) -> Any:
+ app = args.get("app")
+ if not app:
+ return json.dumps({"error": "focus_app requires `app`"})
+ return _maybe_follow_capture(backend, backend.focus_app(app, raise_window=bool(args.get("raise_window"))),
+ bool(args.get("capture_after")))
- if action == "focus_app":
- app = args.get("app")
- if not app:
- return json.dumps({"error": "focus_app requires `app`"})
- res = backend.focus_app(app, raise_window=bool(args.get("raise_window")))
- return _maybe_follow_capture(backend, res, capture_after)
- # delivery_mode / bring_to_front thread through every input action so the
- # model can escalate background → foreground per cua-driver's ladder.
- delivery_mode = args.get("delivery_mode")
- bring_to_front = bool(args.get("bring_to_front"))
-
- # ── app= mismatch guard for input actions ──────────────────────────
- # Input goes to the backend's sticky target (set by the last capture/
- # focus_app). Models routinely pass app= on the input call itself —
- # live QA (Aug 2026) proved `type(text=..., app="kate")` typed into
- # kcalc while reporting ok:true, because the argument was silently
- # dropped. Refuse the clear mismatch instead of delivering input to
- # the wrong window; the fix instruction keeps the flow one call long.
- if action in _INPUT_ACTIONS:
- requested_app = args.get("app")
- if isinstance(requested_app, str) and requested_app.strip():
- mismatch = _input_target_mismatch(backend, requested_app)
- if mismatch is not None:
- return json.dumps({
- "ok": False,
- "action": action,
- "code": "input_target_mismatch",
- "error": (
- f"{action} would go to the current target "
- f"{mismatch!r}, not {requested_app.strip()!r} — input "
- "actions always hit the sticky target from the last "
- f"capture/focus_app. Call capture(app={requested_app.strip()!r}) "
- "or focus_app first, then retry."
- ),
- })
-
- if action in {"click", "double_click", "right_click", "middle_click"}:
- button = args.get("button")
- click_count = 1
- if action == "double_click":
- click_count = 2
- elif action == "right_click":
- button = "right"
- elif action == "middle_click":
- button = "middle"
- else:
- button = button or "left"
- element = args.get("element")
- coord = args.get("coordinate") or (None, None)
- x, y = (coord[0], coord[1]) if coord and coord[0] is not None else (None, None)
- res = backend.click(
- element=element if element is not None else None,
- x=x, y=y, button=button or "left", click_count=click_count,
- modifiers=args.get("modifiers"),
- delivery_mode=delivery_mode, bring_to_front=bring_to_front,
- )
- return _maybe_follow_capture(backend, res, capture_after)
+def _listing(key: str, items: List[Dict[str, Any]]) -> str:
+ return json.dumps({key: items, "count": len(items)})
- if action == "drag":
- has_elements = args.get("from_element") is not None and args.get("to_element") is not None
- has_coords = args.get("from_coordinate") and args.get("to_coordinate")
- if not has_elements and not has_coords:
- return json.dumps({
- "error": "drag requires from_coordinate/to_coordinate or from_element/to_element",
- })
- res = backend.drag(
- from_element=args.get("from_element"),
- to_element=args.get("to_element"),
- from_xy=tuple(args["from_coordinate"]) if args.get("from_coordinate") else None,
- to_xy=tuple(args["to_coordinate"]) if args.get("to_coordinate") else None,
- button=args.get("button", "left"),
- modifiers=args.get("modifiers"),
- delivery_mode=delivery_mode, bring_to_front=bring_to_front,
- )
- return _maybe_follow_capture(backend, res, capture_after)
- if action == "scroll":
- coord = args.get("coordinate") or (None, None)
- res = backend.scroll(
- direction=args.get("direction", "down"),
- amount=int(args.get("amount", 3)),
- element=args.get("element"),
- x=coord[0] if coord and coord[0] is not None else None,
- y=coord[1] if coord and coord[1] is not None else None,
- modifiers=args.get("modifiers"),
- delivery_mode=delivery_mode, bring_to_front=bring_to_front,
- )
- return _maybe_follow_capture(backend, res, capture_after)
+_SIMPLE_ACTIONS: Dict[str, Callable[[ComputerUseBackend, Dict[str, Any]], Any]] = {
+ "capture": _do_capture,
+ "wait": lambda backend, args: _text_response(backend.wait(float(args.get("seconds", 1.0)))),
+ "list_apps": lambda backend, args: _listing("apps", backend.list_apps()),
+ "list_windows": lambda backend, args: _listing("windows", backend.list_windows()),
+ "focus_app": _do_focus_app,
+}
- if action == "type":
- res = backend.type_text(args.get("text", ""),
- delivery_mode=delivery_mode, bring_to_front=bring_to_front)
- return _maybe_follow_capture(backend, res, capture_after)
+# --- input actions: (backend, action, args, delivery_mode, bring_to_front)
+# -> ActionResult, or a JSON error string for a rejected call -------------
- if action == "key":
- res = backend.key(args.get("keys", ""),
- delivery_mode=delivery_mode, bring_to_front=bring_to_front)
- return _maybe_follow_capture(backend, res, capture_after)
-
- if action == "set_value":
- value = args.get("value")
- if value is None:
- return json.dumps({"error": "set_value requires `value`"})
- res = backend.set_value(value=str(value), element=args.get("element"))
- return _maybe_follow_capture(backend, res, capture_after)
-
- # Do NOT alias unknown actions (we never repair bad model output), but
- # name the nearest real action: live QA showed a model emitting
- # "hotkey"/"press_key" and getting zero guidance from the bare error.
- _suggestions = {
- "hotkey": "key", "press_key": "key", "keypress": "key",
- "key_combo": "key", "shortcut": "key",
- "type_text": "type", "input_text": "type",
- "screenshot": "capture", "get_window_state": "capture",
- "left_click": "click", "mouse_click": "click",
- }
- hint = _suggestions.get(str(action))
- if hint:
- return json.dumps({
- "error": (
- f"unknown action {action!r} — did you mean {hint!r}? "
- "See the action enum in the tool schema."
- )
- })
- return json.dumps({"error": f"unknown action {action!r}"})
+# action -> (forced button or None, click_count)
+_CLICK_VARIANTS = {"click": (None, 1), "double_click": (None, 2),
+ "right_click": ("right", 1), "middle_click": ("middle", 1)}
-# ---------------------------------------------------------------------------
-# Response shaping
-# ---------------------------------------------------------------------------
+def _xy(args: Dict[str, Any]) -> Tuple[Any, Any]:
+ coord = args.get("coordinate") or (None, None)
+ return (coord[0], coord[1]) if coord and coord[0] is not None else (None, None)
-def _classify_action_result(res: ActionResult) -> Dict[str, Any]:
- """Choose the next ladder step from semantic evidence, in precedence order.
- An escalation recommendation is advisory. It never overrides a confirmed
- effect and it never turns an unverifiable action into permission to repeat
- input. The model must first obtain fresh evidence.
- """
+def _do_click(backend, action, args, delivery_mode, bring_to_front):
+ forced_button, click_count = _CLICK_VARIANTS[action]
+ x, y = _xy(args)
+ return backend.click(
+ element=args.get("element"), x=x, y=y,
+ button=forced_button or args.get("button") or "left", click_count=click_count,
+ modifiers=args.get("modifiers"), delivery_mode=delivery_mode, bring_to_front=bring_to_front,
+ )
+
+
+def _do_drag(backend, action, args, delivery_mode, bring_to_front):
+ has_elements = args.get("from_element") is not None and args.get("to_element") is not None
+ has_coords = args.get("from_coordinate") and args.get("to_coordinate")
+ if not has_elements and not has_coords:
+ return json.dumps({"error": "drag requires from_coordinate/to_coordinate or from_element/to_element"})
+ return backend.drag(
+ from_element=args.get("from_element"), to_element=args.get("to_element"),
+ from_xy=tuple(args["from_coordinate"]) if args.get("from_coordinate") else None,
+ to_xy=tuple(args["to_coordinate"]) if args.get("to_coordinate") else None,
+ button=args.get("button", "left"), modifiers=args.get("modifiers"),
+ delivery_mode=delivery_mode, bring_to_front=bring_to_front,
+ )
+
+
+def _do_scroll(backend, action, args, delivery_mode, bring_to_front):
+ coord = args.get("coordinate") or (None, None)
+ return backend.scroll(
+ direction=args.get("direction", "down"), amount=int(args.get("amount", 3)),
+ element=args.get("element"),
+ x=coord[0] if coord and coord[0] is not None else None,
+ y=coord[1] if coord and coord[1] is not None else None,
+ modifiers=args.get("modifiers"), delivery_mode=delivery_mode, bring_to_front=bring_to_front,
+ )
+
+
+def _do_set_value(backend, action, args, delivery_mode, bring_to_front):
+ value = args.get("value")
+ if value is None:
+ return json.dumps({"error": "set_value requires `value`"})
+ return backend.set_value(value=str(value), element=args.get("element"))
+
+
+_INPUT_HANDLERS = {
+ "click": _do_click, "double_click": _do_click,
+ "right_click": _do_click, "middle_click": _do_click,
+ "drag": _do_drag, "scroll": _do_scroll, "set_value": _do_set_value,
+ "type": lambda backend, action, args, dm, btf: backend.type_text(
+ args.get("text", ""), delivery_mode=dm, bring_to_front=btf),
+ "key": lambda backend, action, args, dm, btf: backend.key(
+ args.get("keys", ""), delivery_mode=dm, bring_to_front=btf),
+}
+# Native input actions deliver to the backend's sticky target; `app=` on these
+# calls is NOT a targeting parameter — see the mismatch guard in _dispatch.
+_INPUT_ACTIONS = frozenset(_INPUT_HANDLERS)
+
+# Unknown actions are never aliased (no repairing bad model output), but the
+# nearest real action is named so a bare error isn't the only guidance.
+_ACTION_SUGGESTIONS = {
+ "hotkey": "key", "press_key": "key", "keypress": "key",
+ "key_combo": "key", "shortcut": "key",
+ "type_text": "type", "input_text": "type",
+ "screenshot": "capture", "get_window_state": "capture",
+ "left_click": "click", "mouse_click": "click",
+}
+
+
+def _dispatch(backend: ComputerUseBackend, action: str, args: Dict[str, Any]) -> Any:
+ simple = _SIMPLE_ACTIONS.get(action)
+ if simple is not None:
+ return simple(backend, args)
+
+ handler = _INPUT_HANDLERS.get(action)
+ if handler is None:
+ hint = _ACTION_SUGGESTIONS.get(str(action))
+ if hint:
+ return json.dumps({"error": (f"unknown action {action!r} — did you mean {hint!r}? "
+ "See the action enum in the tool schema.")})
+ return json.dumps({"error": f"unknown action {action!r}"})
+
+ # app= guard: input goes to the sticky target from the last capture/focus_app
+ # and the backend drops app= silently — refuse a clear mismatch rather than
+ # type into the wrong window while reporting ok:true.
+ requested_app = args.get("app")
+ if isinstance(requested_app, str) and requested_app.strip():
+ mismatch = _input_target_mismatch(backend, requested_app)
+ if mismatch is not None:
+ return json.dumps({
+ "ok": False, "action": action, "code": "input_target_mismatch",
+ "error": (f"{action} would go to the current target "
+ f"{mismatch!r}, not {requested_app.strip()!r} — input "
+ "actions always hit the sticky target from the last "
+ f"capture/focus_app. Call capture(app={requested_app.strip()!r}) "
+ "or focus_app first, then retry."),
+ })
+
+ # delivery_mode / bring_to_front thread through every input action so the
+ # model can escalate background → foreground per cua-driver's ladder.
+ res = handler(backend, action, args, args.get("delivery_mode"), bool(args.get("bring_to_front")))
+ if isinstance(res, str):
+ return res
+ return _maybe_follow_capture(backend, res, bool(args.get("capture_after")))
+
+
+# ── Response shaping ────────────────────────────────────────────────────────
+
+def _classify_action_result(res: ActionResult) -> Dict[str, Any]:
+ """Next ladder step from semantic evidence, in precedence order. Escalation is
+ advisory: it never overrides a confirmed effect nor licenses repeating input."""
if res.effect == "confirmed" or res.verified is True:
return {"decision": "done"}
if res.effect == "unverifiable":
- return {
- "decision": "verify_fresh_state",
- "hint": (
- "Input was delivered but not confirmed. Re-capture and check "
- "the result BEFORE any retry — do not repeat the input on an "
- "escalation recommendation alone."
- ),
- }
+ return {"decision": "verify_fresh_state",
+ "hint": ("Input was delivered but not confirmed. Re-capture and check "
+ "the result BEFORE any retry — do not repeat the input on an "
+ "escalation recommendation alone.")}
if res.effect == "suspected_noop" or not res.ok or res.code is not None:
decision: Dict[str, Any] = {"decision": "escalate"}
if isinstance(res.escalation, dict):
decision["recommended"] = res.escalation.get("recommended")
- decision["hint"] = (
- "The input likely did not land. Climb one rung following "
- "`recommended`: 'px' → re-issue by coordinate; 'foreground' (or a "
- "failed pixel click) → re-issue with delivery_mode='foreground' "
- "(separate approval). Do not predict the rung from the app being "
- "Electron/Chromium — react to this signal."
- )
+ decision["hint"] = ("The input likely did not land. Climb one rung following "
+ "`recommended`: 'px' → re-issue by coordinate; 'foreground' (or a "
+ "failed pixel click) → re-issue with delivery_mode='foreground' "
+ "(separate approval). Do not predict the rung from the app being "
+ "Electron/Chromium — react to this signal.")
return decision
# Transport success without semantic proof is not proof of effect.
- return {
- "decision": "verify_fresh_state",
- "hint": (
- "Transport succeeded but the effect is unproven. Re-capture and "
- "confirm before continuing."
- ),
- }
+ return {"decision": "verify_fresh_state",
+ "hint": ("Transport succeeded but the effect is unproven. Re-capture and "
+ "confirm before continuing.")}
def _action_payload(res: ActionResult) -> Dict[str, Any]:
payload: Dict[str, Any] = {"ok": res.ok, "action": res.action}
if res.message:
payload["message"] = res.message
- # Surface cua-driver's structured verdict additively so the model can
- # follow the verify → escalate ladder. Only include fields the driver
- # actually returned (None = old driver / not carried). ok is transport
- # success; effect/escalation are the semantic verdict.
- if res.verified is not None:
- payload["verified"] = res.verified
- if res.effect is not None:
- payload["effect"] = res.effect
- escalation = _enrich_escalation(res)
- if escalation is not None:
- payload["escalation"] = escalation
- if res.path is not None:
- payload["path"] = res.path
- if res.degraded is not None:
- payload["degraded"] = res.degraded
- if res.delivery_mode is not None:
- payload["delivery_mode"] = res.delivery_mode
- if res.code is not None:
- payload["code"] = res.code
+ # cua-driver's structured verdict, only for fields it returned (None = old
+ # driver). ok is transport success; effect/escalation are the semantic verdict.
+ for key in ("verified", "effect", "escalation", "path", "degraded", "delivery_mode", "code"):
+ value = getattr(res, key)
+ if value is not None:
+ payload[key] = value
if res.meta:
payload["meta"] = res.meta
payload["verdict"] = _classify_action_result(res)
@@ -898,73 +667,62 @@ def _text_response(res: ActionResult) -> str:
return json.dumps(_action_payload(res))
-def _enrich_escalation(res: ActionResult) -> Optional[Dict[str, Any]]:
- """Return the driver's escalation dict unchanged."""
- return res.escalation
-
-
-# Fixed cap for the AX `elements` array surfaced in a capture response. Dense
-# UIs (Electron apps, Obsidian, JetBrains IDEs) can publish 500+ AX nodes,
-# which would exhaust session context after a single capture. The full,
-# untruncated tree is always written to an `elements_file` spill (see
-# _capture_lost_detail) so nothing is lost — read_file/search_files it when the
-# target isn't in the surfaced window.
+# Cap for the AX `elements` array: dense UIs publish 500+ AX nodes, which would
+# exhaust context after one capture. The full tree spills to `elements_file`.
_DEFAULT_MAX_ELEMENTS = 100
+# Some providers reject images below 8x8 before the model sees the tool result;
+# such captures fall back to the AX/SOM text payload.
_MIN_PROVIDER_IMAGE_DIMENSION = 8
def _image_dimensions_from_b64(image_b64: str) -> Optional[Tuple[int, int]]:
- """Return (width, height) for common inline screenshot formats.
-
- Some providers reject images below 8x8 before the model sees the tool
- result. Inspecting the encoded bytes here lets computer_use fall back to
- its AX/SOM text payload instead of sending an unusable placeholder.
- """
+ """(width, height) of an inline PNG/JPEG screenshot, or None."""
if not image_b64:
return None
try:
raw = base64.b64decode(image_b64, validate=False)
except Exception:
return None
+ return image_dimensions_from_bytes(raw)
+
+
+def _capture_mime(cap: CaptureResult) -> str:
+ """Prefer cua-driver's explicit MIME type; sniff the base64 prefix for older
+ builds (JPEG base64 starts with /9j/, PNG with iVBOR)."""
+ if cap.image_mime_type:
+ return cap.image_mime_type
+ return "image/jpeg" if (cap.png_b64 or "")[:8].startswith("/9j/") else "image/png"
- # PNG: signature + IHDR width/height.
- if raw.startswith(b"\x89PNG\r\n\x1a\n") and len(raw) >= 24:
- try:
- width, height = struct.unpack(">II", raw[16:24])
- return int(width), int(height)
- except Exception:
- return None
- # JPEG: scan for SOF markers that carry dimensions.
- if raw.startswith(b"\xff\xd8") and len(raw) > 4:
- i = 2
- while i + 9 < len(raw):
- if raw[i] != 0xFF:
- i += 1
- continue
- marker = raw[i + 1]
- i += 2
- while marker == 0xFF and i < len(raw):
- marker = raw[i]
- i += 1
- if marker in {0xD8, 0xD9}:
- continue
- if marker == 0xDA:
- break
- if i + 2 > len(raw):
- break
- segment_len = int.from_bytes(raw[i:i + 2], "big")
- if segment_len < 2 or i + segment_len > len(raw):
- break
- if marker in {
- 0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,
- 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF,
- } and segment_len >= 7:
- height = int.from_bytes(raw[i + 3:i + 5], "big")
- width = int.from_bytes(raw[i + 5:i + 7], "big")
- return int(width), int(height)
- i += segment_len
- return None
+def _capture_image_ext(cap: CaptureResult) -> str:
+ """File extension matching the on-disk bytes so MIME sniffing agrees."""
+ return ".jpg" if _capture_mime(cap).lower() == "image/jpeg" else ".png"
+
+
+def _present(**fields: Any) -> Dict[str, Any]:
+ """Only the truthy optional fields, in the given order."""
+ return {k: v for k, v in fields.items() if v}
+
+
+def _text_capture_payload(
+ cap: CaptureResult, elements: List[UIElement], total_elements: int,
+ width: int, height: int, summary: str, *,
+ extra: Optional[Dict[str, Any]] = None, truncated_elements: int = 0,
+ elements_file: Optional[str] = None, screenshot_path: Optional[str] = None,
+ bounds_scale: Optional[float] = None,
+) -> str:
+ """JSON text payload shared by the AX, vision-unavailable and aux-vision branches.
+ Key order is contract: fixed fields, ``extra`` branch markers, then set optionals."""
+ payload: Dict[str, Any] = {
+ "mode": cap.mode, "width": width, "height": height,
+ "app": cap.app, "window_title": cap.window_title,
+ "elements": [_element_to_dict(e) for e in elements],
+ "total_elements": total_elements, "summary": summary,
+ **(extra or {}),
+ }
+ payload.update(_present(truncated_elements=truncated_elements, elements_file=elements_file,
+ screenshot_path=screenshot_path, bounds_scale=bounds_scale))
+ return json.dumps(payload)
def _capture_response(cap: CaptureResult, max_elements: int = _DEFAULT_MAX_ELEMENTS) -> Any:
@@ -977,183 +735,86 @@ def _capture_response(cap: CaptureResult, max_elements: int = _DEFAULT_MAX_ELEME
bounds_note = _bounds_space_note(visible_elements, response_width, response_height)
bounds_scale = _bounds_scale(visible_elements, response_width, response_height)
if bounds_note and bounds_scale:
- bounds_note += (
- f"; estimated scale ~{bounds_scale}x (screenshot position x "
- f"{bounds_scale} ≈ native coordinate)"
- )
- # When the in-context response drops detail (capped labels / capped element
- # array), spill the complete tree to a cache file so the model can read or
- # grep the full text on demand instead of losing it entirely.
- elements_file = (
- _spill_elements_to_file(cap)
- if _capture_lost_detail(cap, visible_elements, truncated_elements)
- else None
- )
- image_too_small = bool(
- image_dimensions
- and (
- image_dimensions[0] < _MIN_PROVIDER_IMAGE_DIMENSION
- or image_dimensions[1] < _MIN_PROVIDER_IMAGE_DIMENSION
- )
- )
- screenshot_path = (
- _persist_capture_image(cap)
- if cap.png_b64 and cap.mode != "ax" and not image_too_small
- else None
- )
-
- # Index only what's actually surfaced in the response — otherwise the
- # human-readable summary references element indices the model cannot
- # find in the JSON `elements` array (the surfaced window is capped at
- # _DEFAULT_MAX_ELEMENTS; the full tree spills to elements_file).
- element_index = _format_elements(visible_elements)
+ bounds_note += (f"; estimated scale ~{bounds_scale}x (screenshot position x "
+ f"{bounds_scale} ≈ native coordinate)")
+ # Capped labels / capped element array: spill the complete tree for on-demand reads.
+ elements_file = None
+ if _capture_lost_detail(cap, visible_elements, truncated_elements):
+ elements_file = _spill_elements_to_file(cap)
+ image_too_small = bool(image_dimensions) and min(image_dimensions) < _MIN_PROVIDER_IMAGE_DIMENSION
+ has_image = bool(cap.png_b64) and cap.mode != "ax" and not image_too_small
+ screenshot_path = _persist_capture_image(cap) if has_image else None
+
+ # Index only what's surfaced in the response — otherwise the summary
+ # references element indices the model cannot find in `elements`.
summary_lines = [
f"capture mode={cap.mode} {response_width}x{response_height}"
- + (f" app={cap.app}" if cap.app else "")
- + (f" window={cap.window_title!r}" if cap.window_title else ""),
+ + (f" app={cap.app}" if cap.app else "") + (f" window={cap.window_title!r}" if cap.window_title else ""),
f"{total_elements} interactable element(s):",
]
if bounds_note:
summary_lines.append(f" ({bounds_note})")
if screenshot_path:
- summary_lines.append(
- f" (shareable screenshot saved to {screenshot_path})"
- )
+ summary_lines.append(f" (shareable screenshot saved to {screenshot_path})")
if cap.note:
summary_lines.append(f" ({cap.note})")
if elements_file:
- summary_lines.append(
- f" (full element tree with untruncated labels saved to "
- f"{elements_file} — read_file/search_files it if you need "
- "dropped label text or elements beyond the cap)"
- )
- if element_index:
- summary_lines.extend(element_index)
- # Multimodal and AX paths both reference `summary`; build it once up-front
- # so the aux-vision routing branch (which fires before either path is
- # selected) has a valid value to hand to _route_capture_through_aux_vision.
- # The AX path appends the "truncated to N of M" note to summary_lines
- # below and rebuilds; the multimodal path keeps this version untouched.
+ summary_lines.append(f" (full element tree with untruncated labels saved to "
+ f"{elements_file} — read_file/search_files it if you need "
+ "dropped label text or elements beyond the cap)")
+ summary_lines.extend(_format_elements(visible_elements))
if image_too_small:
- summary_lines.append(
- f" (screenshot omitted: {image_dimensions[0]}x{image_dimensions[1]} "
- f"is below the {_MIN_PROVIDER_IMAGE_DIMENSION}x{_MIN_PROVIDER_IMAGE_DIMENSION} "
- "provider minimum)"
- )
+ summary_lines.append(f" (screenshot omitted: {image_dimensions[0]}x{image_dimensions[1]} "
+ f"is below the {_MIN_PROVIDER_IMAGE_DIMENSION}x{_MIN_PROVIDER_IMAGE_DIMENSION} "
+ "provider minimum)")
+ # Multimodal/aux paths use this summary; text paths append notes and rebuild.
summary = "\n".join(summary_lines)
- if cap.png_b64 and cap.mode != "ax" and not image_too_small:
- # Decide whether to hand the screenshot to the auxiliary.vision
- # pipeline (text-only result) or keep the multimodal envelope (main
- # model handles vision natively). Issue #24015: previously the
- # multimodal envelope was returned unconditionally, so non-vision
- # main models tripped HTTP 404 / 400 at the provider boundary even
- # when auxiliary.vision was explicitly configured to handle this.
- if _should_route_through_aux_vision():
- routed = _route_capture_through_aux_vision(
- cap, summary,
- visible_elements=visible_elements,
- truncated_elements=truncated_elements,
- elements_file=elements_file,
- screenshot_path=screenshot_path,
- )
- if routed is not None:
- return routed
- # Aux routing was requested but failed (vision node down, aux call
- # raised, empty analysis, etc.). Routing being requested means the
- # main model may not be able to consume images; falling through to
- # the multimodal envelope can break the capture with a provider
- # error. Degrade to the AX/SOM text payload instead so element
- # indices remain usable while vision is unavailable.
- summary_lines.append(
- " (vision unavailable: the auxiliary vision model could not "
- "be reached; screenshot omitted. Element-index actions still "
- "work — drive via the element list above.)"
- )
- if truncated_elements:
- summary_lines.append(
- f" (response truncated to {len(visible_elements)} of "
- f"{total_elements} elements; the full tree is in "
- "elements_file — read_file/search_files it, or pass app= "
- "to narrow scope)"
- )
- payload = {
- "mode": cap.mode,
- "width": response_width,
- "height": response_height,
- "app": cap.app,
- "window_title": cap.window_title,
- "elements": [_element_to_dict(e) for e in visible_elements],
- "total_elements": total_elements,
- "summary": "\n".join(summary_lines),
- "vision_unavailable": True,
+ extra = None
+ if has_image:
+ # Hand the screenshot to auxiliary.vision (text-only result) when the main
+ # model may not consume images natively; returning the multimodal envelope
+ # unconditionally tripped HTTP 404/400 at the provider boundary.
+ if not _should_route_through_aux_vision():
+ # The multimodal response carries the screenshot, not the elements
+ # array, so the "truncated to N of M" note would be inaccurate here.
+ return {
+ "_multimodal": True,
+ "content": [{"type": "text", "text": summary},
+ {"type": "image_url",
+ "image_url": {"url": f"data:{_capture_mime(cap)};base64,{cap.png_b64}"}}],
+ "text_summary": summary,
+ "meta": {"mode": cap.mode, "width": response_width, "height": response_height,
+ "elements": total_elements, "png_bytes": cap.png_bytes_len,
+ **_present(screenshot_path=screenshot_path, elements_file=elements_file,
+ bounds_scale=bounds_scale)},
}
- if truncated_elements:
- payload["truncated_elements"] = truncated_elements
- if elements_file:
- payload["elements_file"] = elements_file
- if screenshot_path:
- payload["screenshot_path"] = screenshot_path
- if bounds_scale:
- payload["bounds_scale"] = bounds_scale
- return json.dumps(payload)
-
- # Prefer the explicit MIME type cua-driver attaches to its image
- # parts (Surface 7 of NousResearch/hermes-agent#47072 — trycua/cua#1961
- # made `mimeType` part of every MCP image-part response). Fall back
- # to base64-prefix sniffing for older cua-driver builds that didn't
- # carry the field. JPEG base64 starts with /9j/; PNG with iVBOR.
- _mime = cap.image_mime_type
- if not _mime:
- _b64_prefix = cap.png_b64[:8]
- _mime = "image/jpeg" if _b64_prefix.startswith("/9j/") else "image/png"
- # The multimodal response carries the screenshot, not the AX
- # elements array, so a "response truncated to N of M elements"
- # note would be inaccurate — skip it on this branch.
- return {
- "_multimodal": True,
- "content": [
- {"type": "text", "text": summary},
- {"type": "image_url",
- "image_url": {"url": f"data:{_mime};base64,{cap.png_b64}"}},
- ],
- "text_summary": summary,
- "meta": {"mode": cap.mode, "width": response_width, "height": response_height,
- "elements": total_elements, "png_bytes": cap.png_bytes_len,
- **({"screenshot_path": screenshot_path} if screenshot_path else {}),
- **({"elements_file": elements_file} if elements_file else {}),
- **({"bounds_scale": bounds_scale} if bounds_scale else {})},
- }
- # AX-only (or image-missing fallback): text path actually carries the
- # `elements` array, so the truncation note applies here.
+ routed = _route_capture_through_aux_vision(
+ cap, summary, visible_elements=visible_elements, truncated_elements=truncated_elements,
+ elements_file=elements_file, screenshot_path=screenshot_path,
+ )
+ if routed is not None:
+ return routed
+ # Aux routing was requested but failed (vision node down, empty analysis,
+ # ...). Falling through to the multimodal envelope could break the capture
+ # with a provider error, so degrade to the AX/SOM text payload.
+ summary_lines.append(" (vision unavailable: the auxiliary vision model could not "
+ "be reached; screenshot omitted. Element-index actions still "
+ "work — drive via the element list above.)")
+ extra = {"vision_unavailable": True}
+ # Text paths carry the `elements` array, so the truncation note applies.
if truncated_elements:
summary_lines.append(
f" (response truncated to {len(visible_elements)} of {total_elements} elements; "
- "the full tree is in elements_file — read_file/search_files it, or pass app= to narrow scope)"
- )
- summary = "\n".join(summary_lines)
- payload: Dict[str, Any] = {
- "mode": cap.mode,
- "width": response_width,
- "height": response_height,
- "app": cap.app,
- "window_title": cap.window_title,
- "elements": [_element_to_dict(e) for e in visible_elements],
- "total_elements": total_elements,
- "summary": summary,
- }
- if truncated_elements:
- payload["truncated_elements"] = truncated_elements
- if elements_file:
- payload["elements_file"] = elements_file
- if bounds_scale:
- payload["bounds_scale"] = bounds_scale
- return json.dumps(payload)
+ "the full tree is in elements_file — read_file/search_files it, or pass app= to narrow scope)")
+ return _text_capture_payload(
+ cap, visible_elements, total_elements, response_width, response_height, "\n".join(summary_lines),
+ extra=extra, truncated_elements=truncated_elements, elements_file=elements_file,
+ screenshot_path=screenshot_path, bounds_scale=bounds_scale,
+ )
-# ---------------------------------------------------------------------------
-# auxiliary.vision routing for captured screenshots (#24015)
-# ---------------------------------------------------------------------------
+# ── auxiliary.vision routing for captured screenshots ───────────────────────
# Longest image side handed to the aux vision model. Full-resolution desktop
# captures tokenize heavily and can overflow small local-model context windows;
@@ -1165,13 +826,9 @@ def _shrink_capture_for_vision(raw: bytes, ext: str,
max_dim: int = _MAX_VISION_DIM,
) -> tuple[bytes, Optional[str]]:
"""Downscale encoded image bytes so the longest side is <= max_dim.
-
- Returns ``(bytes, scale_note)``. ``scale_note`` is ``None`` when the image
- was returned unchanged (already fits, or Pillow unavailable/failed — no
- worse than the pre-shrink behavior). When a downscale happened, the note
- tells the vision model the scale factor so any coordinates it reports can
- be mapped back to the real screen instead of being silently wrong.
- """
+ Returns ``(bytes, scale_note)``; note is None when unchanged (fits, or Pillow
+ unavailable/failed), else it tells the vision model the factor so reported
+ coordinates map back to the real screen instead of being silently wrong."""
try:
from io import BytesIO
from PIL import Image
@@ -1186,45 +843,30 @@ def _shrink_capture_for_vision(raw: bytes, ext: str,
fx = orig_w / new_w if new_w else 1.0
fy = orig_h / new_h if new_h else 1.0
if f"{fx:.2f}" == f"{fy:.2f}":
- factor_clause = (
- f"multiply any coordinates you report by {fx:.2f} "
- f"to map back to the real screen."
- )
+ factor_clause = f"multiply any coordinates you report by {fx:.2f} to map back to the real screen."
else:
- factor_clause = (
- f"multiply any x coordinates you report by {fx:.2f} and "
- f"any y coordinates by {fy:.2f} to map back to the real screen."
- )
- scale_note = (
- f"Screenshot downscaled from {orig_w}x{orig_h} to "
- f"{new_w}x{new_h} for vision; {factor_clause}"
- )
- return out.getvalue(), scale_note
+ factor_clause = (f"multiply any x coordinates you report by {fx:.2f} and "
+ f"any y coordinates by {fy:.2f} to map back to the real screen.")
+ return out.getvalue(), (f"Screenshot downscaled from {orig_w}x{orig_h} to "
+ f"{new_w}x{new_h} for vision; {factor_clause}")
except Exception as exc:
logger.debug("computer_use: vision downscale skipped: %s", exc)
return raw, None
-def _should_route_through_aux_vision() -> bool:
- """Return True when ``_capture_response`` should hand the PNG to aux vision.
- Reads the active main provider/model and the loaded config and asks the
- routing helper. Any failure (config import, runtime override missing,
- etc.) returns False so the existing multimodal envelope continues to be
- returned — fail open on the routing decision so a broken config can
- never silently drop the screenshot for vision-capable main models.
- """
+def _should_route_through_aux_vision() -> bool:
+ """True when ``_capture_response`` should hand the PNG to aux vision. Any failure
+ returns False (fail open) so a broken config never silently drops the screenshot
+ for vision-capable main models."""
try:
from agent.auxiliary_client import _read_main_model, _read_main_provider
from hermes_cli.config import load_config
- from tools.computer_use.vision_routing import (
- should_route_capture_to_aux_vision,
- )
+ from tools.computer_use.vision_routing import should_route_capture_to_aux_vision
except Exception as exc: # pragma: no cover - defensive
logger.debug("computer_use: aux-vision routing import failed: %s", exc)
return False
try:
- provider = _read_main_provider() or ""
- model = _read_main_model() or ""
+ provider, model = _read_main_provider() or "", _read_main_model() or ""
except Exception as exc: # pragma: no cover - defensive
logger.debug("computer_use: aux-vision routing config read failed: %s", exc)
return False
@@ -1233,8 +875,7 @@ def _should_route_through_aux_vision() -> bool:
if cached is not None:
return cached
try:
- cfg = load_config()
- decision = bool(should_route_capture_to_aux_vision(provider, model, cfg))
+ decision = bool(should_route_capture_to_aux_vision(provider, model, load_config()))
except Exception as exc: # pragma: no cover - defensive
logger.debug("computer_use: aux-vision routing decision failed: %s", exc)
return False
@@ -1247,9 +888,7 @@ def _capture_after_mode() -> str:
try:
from hermes_cli.config import load_config
- raw = ((load_config() or {}).get("computer_use") or {}).get(
- "capture_after_mode", "som"
- )
+ raw = ((load_config() or {}).get("computer_use") or {}).get("capture_after_mode", "som")
except Exception:
return "som"
mode = str(raw or "som").strip().lower()
@@ -1265,26 +904,12 @@ def _route_capture_through_aux_vision(
elements_file: Optional[str] = None,
screenshot_path: Optional[str] = None,
) -> Optional[str]:
- """Pre-analyse the captured PNG via ``vision_analyze`` and return a text result.
-
- The captured base64 PNG is materialised to ``$HERMES_HOME/cache/vision/``
- and handed to ``vision_analyze_tool`` with a generic describe prompt.
- The resulting text description is merged into the existing AX/SOM
- summary so the main model receives a single text payload that mentions
- every interactable element AND a description of what the screenshot
- looked like.
-
- Returns:
- A JSON-encoded text response on success.
- ``None`` on failure (caller falls back to the multimodal envelope).
- """
+ """Pre-analyse the capture via ``vision_analyze_tool`` (temp file under
+ ``$HERMES_HOME/cache/vision/``) and merge the description with the AX/SOM
+ summary into one text payload. Returns JSON, or None on any failure."""
if not cap.png_b64:
return None
try:
- import base64 as _base64
- import os as _os
- import uuid as _uuid
-
from hermes_constants import get_hermes_dir
from model_tools import _run_async
from tools.vision_tools import vision_analyze_tool
@@ -1292,56 +917,39 @@ def _route_capture_through_aux_vision(
logger.debug("computer_use: aux-vision import failed: %s", exc)
return None
- temp_image_path = None
try:
- try:
- raw = _base64.b64decode(cap.png_b64, validate=False)
- except Exception as exc:
- logger.debug("computer_use: failed to decode capture base64: %s", exc)
- return None
+ raw = base64.b64decode(cap.png_b64, validate=False)
+ except Exception as exc:
+ logger.debug("computer_use: failed to decode capture base64: %s", exc)
+ return None
- # Pick an extension that matches the on-disk bytes so vision_analyze's
- # MIME sniffing returns the right content-type.
- # Surface 7: prefer the explicit MIME type cua-driver supplied.
- _mime_for_ext = cap.image_mime_type or ""
- if _mime_for_ext == "image/jpeg" or (not _mime_for_ext and cap.png_b64[:8].startswith("/9j/")):
- ext = ".jpg"
- else:
- ext = ".png"
+ temp_image_path = None
+ try:
+ ext = _capture_image_ext(cap)
cache_dir = get_hermes_dir("cache/vision", "temp_vision_images")
cache_dir.mkdir(parents=True, exist_ok=True)
- temp_image_path = cache_dir / f"computer_use_{_uuid.uuid4().hex}{ext}"
+ temp_image_path = cache_dir / f"computer_use_{uuid.uuid4().hex}{ext}"
raw, scale_note = _shrink_capture_for_vision(raw, ext)
temp_image_path.write_bytes(raw)
- prompt = (
- "Describe what is visible in this desktop application screenshot in "
- "concise but specific terms. Mention the app name and window "
- "title if visible, the overall layout, any labelled buttons, "
- "menus or text fields, and any prominent text content the user "
- "would need to know about. Do not invent details that are not "
- "actually visible.\n\n"
- f"AX/SOM index for cross-reference:\n{summary}"
- )
+ prompt = ("Describe what is visible in this desktop application screenshot in "
+ "concise but specific terms. Mention the app name and window "
+ "title if visible, the overall layout, any labelled buttons, "
+ "menus or text fields, and any prominent text content the user "
+ "would need to know about. Do not invent details that are not "
+ f"actually visible.\n\nAX/SOM index for cross-reference:\n{summary}")
if scale_note:
prompt += f"\n\nNote: {scale_note}"
- result_json = _run_async(
- vision_analyze_tool(str(temp_image_path), prompt)
- )
+ result_json = _run_async(vision_analyze_tool(str(temp_image_path), prompt))
except Exception as exc:
- logger.warning(
- "computer_use: auxiliary.vision pre-analysis failed (%s); "
- "returning to caller without aux analysis",
- exc,
- )
+ logger.warning("computer_use: auxiliary.vision pre-analysis failed (%s); "
+ "returning to caller without aux analysis", exc)
return None
finally:
if temp_image_path is not None:
- try:
- _os.unlink(str(temp_image_path))
- except Exception:
- pass
+ with contextlib.suppress(Exception):
+ os.unlink(str(temp_image_path))
analysis_text = ""
if isinstance(result_json, str):
@@ -1351,54 +959,29 @@ def _route_capture_through_aux_vision(
analysis_text = str(parsed.get("analysis") or "").strip()
except (TypeError, json.JSONDecodeError):
analysis_text = result_json.strip()
-
if not analysis_text:
return None
-
- # Respect the same element cap as every other capture branch. Before this,
- # the aux-vision path dumped cap.elements in full — silently bypassing
- # max_elements exactly when a non-vision main model was configured, so a
- # dense Electron UI (Discord, Slack, IDEs) could blow the response budget
- # on this branch alone.
+ # Same element cap as every other capture branch; dumping cap.elements in
+ # full would bypass max_elements exactly for non-vision main models.
elements_out = cap.elements if visible_elements is None else visible_elements
- payload: Dict[str, Any] = {
- "mode": cap.mode,
- "width": cap.width,
- "height": cap.height,
- "app": cap.app,
- "window_title": cap.window_title,
- "elements": [_element_to_dict(e) for e in elements_out],
- "total_elements": len(cap.elements),
- "summary": summary,
- "vision_analysis": analysis_text,
- "vision_analysis_routed_via": "auxiliary.vision",
- }
- if truncated_elements:
- payload["truncated_elements"] = truncated_elements
- if elements_file:
- payload["elements_file"] = elements_file
- if screenshot_path:
- payload["screenshot_path"] = screenshot_path
- return json.dumps(payload)
+ return _text_capture_payload(
+ cap, elements_out, len(cap.elements), cap.width, cap.height, summary,
+ extra={"vision_analysis": analysis_text, "vision_analysis_routed_via": "auxiliary.vision"},
+ truncated_elements=truncated_elements, elements_file=elements_file,
+ screenshot_path=screenshot_path,
+ )
-def _maybe_follow_capture(
- backend: ComputerUseBackend, res: ActionResult, do_capture: bool,
-) -> Any:
- if not do_capture:
- return _text_response(res)
- # Skip the follow-up capture when the action itself failed: showing a
- # normal-looking screenshot after a failure misleads the model into thinking
- # the action succeeded. Return the error text instead.
- if not res.ok:
+def _maybe_follow_capture(backend: ComputerUseBackend, res: ActionResult, do_capture: bool) -> Any:
+ # No follow-up capture after a failed action: a normal-looking screenshot
+ # would suggest it succeeded.
+ if not do_capture or not res.ok:
return _text_response(res)
try:
- # Preserve the exact selected window when possible. Linux may expose a
- # generic app name for several unrelated windows, so app-only recapture
- # can silently switch targets after a successful action.
+ # Recapture the exact window when known: on Linux several unrelated
+ # windows may share an app name, so app-only recapture can switch targets.
target = getattr(backend, "_last_target", None) or {}
- pid = target.get("pid")
- window_id = target.get("window_id")
+ pid, window_id = target.get("pid"), target.get("window_id")
mode = _capture_after_mode()
if pid is not None and window_id is not None:
cap = backend.capture(mode=mode, pid=pid, window_id=window_id)
@@ -1407,19 +990,16 @@ def _maybe_follow_capture(
except Exception as e:
logger.warning("follow-up capture failed: %s", e)
return _text_response(res)
- # Combine action summary with the capture.
resp = _capture_response(cap)
if isinstance(resp, dict) and resp.get("_multimodal"):
- # Keep the complete evidence/verdict contract visible when an image is
- # attached; otherwise capture_after would accidentally discard the
- # very signal that governs whether repeating input is allowed.
+ # Keep the evidence/verdict contract visible alongside the image — it
+ # governs whether repeating input is allowed.
prefix = json.dumps(_action_payload(res))
resp["content"][0]["text"] = prefix + "\n\n" + resp["content"][0]["text"]
resp["text_summary"] = prefix + "\n\n" + resp["text_summary"]
resp["action_result"] = _action_payload(res)
return resp
- # Fallback: action + text capture merged.
- try:
+ try: # text capture: merge the action payload in
data = json.loads(resp)
except (TypeError, json.JSONDecodeError):
data = {"capture": resp}
@@ -1428,13 +1008,9 @@ def _maybe_follow_capture(
def _bounds_unknown(bounds) -> bool:
- """True when the AX tree reported no real geometry for an element.
-
- KDE/Qt apps commonly report ``[0, 0, 0, 0]`` for elements that are
- perfectly clickable by index (live QA, Aug 2026: all of kcalc's radio
- buttons). Serializing that as a plausible-looking rect invites a model
- to derive ``coordinate=[0, 0]`` from it and click the screen corner.
- """
+ """True when the AX tree reported no real geometry. KDE/Qt apps report
+ ``[0, 0, 0, 0]`` for elements clickable by index; serializing that as a rect
+ invites ``coordinate=[0, 0]`` clicks on the screen corner."""
try:
return all(int(v) == 0 for v in bounds)
except (TypeError, ValueError):
@@ -1446,69 +1022,45 @@ def _format_elements(elements: List[UIElement], max_lines: int = 40) -> List[str
for e in elements[:max_lines]:
label = e.label.replace("\n", " ")[:60]
where = "@ bounds-unknown (click by element index)" if _bounds_unknown(e.bounds) else f"@ {e.bounds}"
- out.append(f" #{e.index} {e.role} {label!r} {where}"
- + (f" [{e.app}]" if e.app else ""))
+ out.append(f" #{e.index} {e.role} {label!r} {where}" + (f" [{e.app}]" if e.app else ""))
if len(elements) > max_lines:
out.append(f" ... +{len(elements) - max_lines} more (call capture with app= to narrow)")
return out
-# Element labels come straight from the platform accessibility tree, which on
-# some apps (Discord/Slack via UIA, Electron chat clients generally) exposes
-# ENTIRE message bodies / document text as the accessible name of a node.
-# 100 elements x multi-KB labels made single capture responses exceed 170KB —
-# blowing the tool-result budget so the model never saw the elements it needed,
-# and leaking full private chat text into context. The summary line has always
-# truncated to 60 chars; this applies a (more generous) cap to the JSON
-# `elements` array too. Labels are for identifying a control, not for reading
-# page content — captures are not a text-extraction surface.
+# Some AX trees (Discord/Slack via UIA, Electron chat clients) expose ENTIRE
+# message bodies as labels; uncapped they blew the tool-result budget and leaked
+# private chat text. Labels identify a control; captures aren't text extraction.
_MAX_ELEMENT_LABEL_CHARS = 120
-
-# Keep at most this many spilled element-tree files in the cache dir. Each
-# capture of a dense UI can spill; without pruning the cache grows unbounded.
+# Bounded cache trails: every dense capture can spill, and CLI-only sessions
+# never run the gateway's periodic media-cache cleanup.
_MAX_SPILL_FILES = 20
-
-# Keep user-shareable capture files bounded independently from the gateway's
-# periodic media-cache cleanup. CLI-only sessions may never start the gateway,
-# and capture_after can otherwise leave an unbounded screenshot trail.
_MAX_CAPTURE_FILES = 20
-def _persist_capture_image(cap: CaptureResult) -> Optional[str]:
- """Save a capture in Hermes' media cache and return its absolute path.
+def _prune_cache_files(cache_dir, pattern: str, cap: int) -> None:
+ """Best-effort: unlink the oldest ``pattern`` files so at most ``cap - 1``
+ remain before the caller writes one more."""
+ with contextlib.suppress(Exception):
+ files = sorted(cache_dir.glob(pattern), key=lambda p: p.stat().st_mtime)
+ for stale in files[: max(0, len(files) - (cap - 1))]:
+ stale.unlink(missing_ok=True)
- Captures are normally embedded only in the model's tool context. Persisting
- a bounded copy gives attachment-capable surfaces a real file to deliver
- when the user explicitly asks for the screenshot. This is best-effort: an
- unwritable cache must never break computer control.
- """
+
+def _persist_capture_image(cap: CaptureResult) -> Optional[str]:
+ """Save a bounded copy of the capture in Hermes' media cache so attachment
+ surfaces can deliver it; returns the path. Best-effort: an unwritable cache
+ must never break computer control."""
if not cap.png_b64:
return None
try:
- import uuid as _uuid
-
from hermes_constants import get_hermes_dir
raw = base64.b64decode(cap.png_b64, validate=False)
- mime = str(cap.image_mime_type or "").lower()
- ext = ".jpg" if mime == "image/jpeg" or (
- not mime and cap.png_b64[:8].startswith("/9j/")
- ) else ".png"
-
cache_dir = get_hermes_dir("cache/images", "image_cache")
cache_dir.mkdir(parents=True, exist_ok=True)
- try:
- captures = sorted(
- cache_dir.glob("computer_use_*.*"),
- key=lambda path: path.stat().st_mtime,
- )
- keep_before_write = max(0, _MAX_CAPTURE_FILES - 1)
- for stale in captures[: max(0, len(captures) - keep_before_write)]:
- stale.unlink(missing_ok=True)
- except Exception:
- pass
-
- path = cache_dir / f"computer_use_{_uuid.uuid4().hex}{ext}"
+ _prune_cache_files(cache_dir, "computer_use_*.*", _MAX_CAPTURE_FILES)
+ path = cache_dir / f"computer_use_{uuid.uuid4().hex}{_capture_image_ext(cap)}"
path.write_bytes(raw)
return str(path)
except Exception as exc: # pragma: no cover - defensive
@@ -1517,89 +1069,50 @@ def _persist_capture_image(cap: CaptureResult) -> Optional[str]:
def _spill_elements_to_file(cap: CaptureResult) -> Optional[str]:
- """Write the FULL element tree (untruncated labels) to a cache file.
-
- The in-context response caps labels at ``_MAX_ELEMENT_LABEL_CHARS`` and
- the array at ``max_elements`` to protect the tool-result budget, but the
- dropped text is sometimes exactly what the task needs (reading a chat
- transcript or document text exposed through the AX tree). Spilling the
- complete tree to disk gives the model an escape hatch — read_file /
- search_files against the returned path — without paying the full tree
- into context on every capture.
-
- Returns the absolute path, or None on any failure (spilling is an
- enhancement; a capture must never fail because the cache dir is
- unwritable).
- """
+ """Write the FULL element tree (untruncated labels) to a cache file — the
+ read_file/search_files escape hatch for capped text. Returns the path, or None
+ on any failure (a capture must never fail on an unwritable cache)."""
try:
- import uuid as _uuid
-
from hermes_constants import get_hermes_dir
cache_dir = get_hermes_dir("cache/computer_use", "computer_use_cache")
cache_dir.mkdir(parents=True, exist_ok=True)
- # Prune oldest spills beyond the cap (best-effort).
- try:
- spills = sorted(
- cache_dir.glob("elements_*.json"),
- key=lambda p: p.stat().st_mtime,
- )
- for stale in spills[: max(0, len(spills) - (_MAX_SPILL_FILES - 1))]:
- stale.unlink(missing_ok=True)
- except Exception:
- pass
- path = cache_dir / f"elements_{_uuid.uuid4().hex}.json"
+ _prune_cache_files(cache_dir, "elements_*.json", _MAX_SPILL_FILES)
+ path = cache_dir / f"elements_{uuid.uuid4().hex}.json"
payload = {
"app": cap.app,
"window_title": cap.window_title,
"total_elements": len(cap.elements),
+ # Labels here are full and untruncated.
"elements": [
- {
- "index": e.index,
- "role": e.role,
- "label": e.label, # full, untruncated
- "bounds": list(e.bounds),
- "app": e.app,
- }
+ {"index": e.index, "role": e.role, "label": e.label,
+ "bounds": list(e.bounds), "app": e.app}
for e in cap.elements
],
}
- path.write_text(
- json.dumps(payload, ensure_ascii=False, indent=1),
- encoding="utf-8",
- )
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=1), encoding="utf-8")
return str(path)
except Exception as exc: # pragma: no cover - defensive
logger.debug("computer_use: element spill failed: %s", exc)
return None
-def _capture_lost_detail(
- cap: CaptureResult, visible_elements: List[UIElement], truncated_elements: int,
-) -> bool:
+def _capture_lost_detail(cap: CaptureResult, visible_elements: List[UIElement], truncated_elements: int) -> bool:
"""True when the in-context response drops information the full tree has."""
- if truncated_elements:
- return True
- return any(
+ return bool(truncated_elements) or any(
len(e.label) > _MAX_ELEMENT_LABEL_CHARS for e in visible_elements
)
-def _bounds_scale(
+def _bounds_divergence(
elements: List[UIElement], image_width: int, image_height: int,
-) -> Optional[float]:
- """Estimated native-bounds → screenshot-pixel scale factor, or None.
-
- Only meaningful when the two spaces diverge (same condition as
- ``_bounds_space_note``). Uses the larger of the two axis ratios so the
- estimate is driven by the axis with real extent data. Rounded to 2
- decimals — this is a heuristic for mapping screenshot positions to
- native coordinates, not display-metrics ground truth.
- """
+) -> Optional[Tuple[int, int]]:
+ """(max right edge, max bottom edge) of element bounds when they exceed the
+ screenshot, else None. 5% slack: window chrome can hang a few px past the
+ captured frame without implying a different coordinate space."""
if not elements or image_width <= 0 or image_height <= 0:
return None
- max_x = 0
- max_y = 0
+ max_x = max_y = 0
for e in elements:
try:
x, y, w, h = e.bounds
@@ -1609,82 +1122,55 @@ def _bounds_scale(
max_y = max(max_y, int(y) + int(h))
if max_x <= image_width * 1.05 and max_y <= image_height * 1.05:
return None
- return round(max(max_x / image_width, max_y / image_height), 2)
+ return max_x, max_y
+
+
+def _bounds_scale(
+ elements: List[UIElement], image_width: int, image_height: int,
+) -> Optional[float]:
+ """Estimated native-bounds → screenshot-pixel scale factor, or None when the
+ spaces don't diverge (same condition as ``_bounds_space_note``). Larger axis
+ ratio wins so real extent data drives it; rounded to 2 decimals (heuristic)."""
+ extent = _bounds_divergence(elements, image_width, image_height)
+ if extent is None:
+ return None
+ return round(max(extent[0] / image_width, extent[1] / image_height), 2)
def _bounds_space_note(
elements: List[UIElement], image_width: int, image_height: int,
) -> Optional[str]:
- """Warn when element bounds live in a different coordinate space.
-
- On HiDPI/scaled displays (common on Windows + macOS retina), cua-driver
- reports AX element bounds in native desktop coordinates while the
- screenshot is captured/downscaled to a smaller pixel grid. Nothing in the
- response related the two, so models reading a position off the screenshot
- and clicking by coordinate= missed by the scale factor (e.g. 2.6x on a
- 4K display with a 1455px-wide screenshot). Element bounds are what
- click(coordinate=...) expects; the note makes that explicit whenever the
- two spaces visibly diverge.
- """
- if not elements or image_width <= 0 or image_height <= 0:
- return None
- max_x = 0
- max_y = 0
- for e in elements:
- try:
- x, y, w, h = e.bounds
- except (TypeError, ValueError):
- continue
- max_x = max(max_x, int(x) + int(w))
- max_y = max(max_y, int(y) + int(h))
- if max_x <= 0 and max_y <= 0:
- return None
- # 5% slack: window chrome can hang a few px past the captured frame
- # without implying a different coordinate space.
- if max_x <= image_width * 1.05 and max_y <= image_height * 1.05:
+ """Warn when element bounds live in a different coordinate space: on HiDPI
+ displays AX bounds are native while the screenshot is downscaled, so coordinate=
+ clicks read off the screenshot missed by the scale factor."""
+ extent = _bounds_divergence(elements, image_width, image_height)
+ if extent is None:
return None
- return (
- f"element bounds are in native desktop coordinates (extend to "
- f"~{max_x}x{max_y}), NOT screenshot pixels ({image_width}x"
- f"{image_height}). coordinate= clicks expect the native space — "
- "derive click points from element bounds, or scale screenshot "
- "positions up accordingly"
- )
+ return (f"element bounds are in native desktop coordinates (extend to "
+ f"~{extent[0]}x{extent[1]}), NOT screenshot pixels ({image_width}x"
+ f"{image_height}). coordinate= clicks expect the native space — "
+ "derive click points from element bounds, or scale screenshot "
+ "positions up accordingly")
def _element_to_dict(e: UIElement) -> Dict[str, Any]:
- label = e.label
- truncated = len(label) > _MAX_ELEMENT_LABEL_CHARS
- if truncated:
- label = label[:_MAX_ELEMENT_LABEL_CHARS]
+ truncated = len(e.label) > _MAX_ELEMENT_LABEL_CHARS
+ # A zero rect is "geometry unknown", not a position — null it so no
+ # coordinate= is ever derived from it. The element index still works.
out: Dict[str, Any] = {
- "index": e.index,
- "role": e.role,
- "label": label,
- # A zero rect is "geometry unknown", not a position — null it so no
- # coordinate= is ever derived from it. The element index still works.
- "bounds": None if _bounds_unknown(e.bounds) else list(e.bounds),
- "app": e.app,
+ "index": e.index, "role": e.role, "label": e.label[:_MAX_ELEMENT_LABEL_CHARS],
+ "bounds": None if _bounds_unknown(e.bounds) else list(e.bounds), "app": e.app,
}
if truncated:
out["label_truncated"] = True
return out
-# ---------------------------------------------------------------------------
-# Availability check (used by the tool registry check_fn)
-# ---------------------------------------------------------------------------
+# ── Availability check (used by the tool registry check_fn) ─────────────────
def check_computer_use_requirements() -> bool:
- """Return True iff computer_use can run on this host.
-
- Conditions: macOS, Windows, or Linux + cua-driver binary installed (or
- override via env). cua-driver runs on all three; the Linux path is
- headed/X11 today (Wayland via XWayland), pure-Wayland progress tracked
- upstream. Linux users see specific blocked checks via
- `hermes computer-use doctor` if their session is incomplete (e.g. no
- DISPLAY set).
- """
+ """True iff computer_use can run here: macOS/Windows/Linux + cua-driver binary
+ (or env override). `hermes computer-use doctor` names blocked Linux checks."""
if sys.platform not in ("darwin", "win32", "linux"):
return False
from tools.computer_use.cua_backend import cua_driver_binary_available
diff --git a/tools/computer_use/vision_routing.py b/tools/computer_use/vision_routing.py
index 5cc9e2fb61c..9dd546641b9 100644
--- a/tools/computer_use/vision_routing.py
+++ b/tools/computer_use/vision_routing.py
@@ -1,48 +1,26 @@
"""Vision-routing decisions for ``computer_use`` capture results.
-Background
-----------
-``computer_use(action='capture', mode='som'|'vision')`` returns a
-``_multimodal`` envelope containing the captured screenshot. That envelope
-is delivered back to the **active session model** as the tool result. When
-the active main model has no vision capability (e.g. text-only or
-text+code-only models), or when the active provider rejects multimodal
-content inside tool-result messages, the screenshot trips a 404 / 400 at
-the provider boundary and the agent loop reports a hard tool failure.
-
-Issue #24015 reports this regression for the ``cua-driver`` backend:
-configuring ``auxiliary.vision`` (a dedicated vision-capable model) in
-``config.yaml`` was silently ignored — the screenshot was still routed at
-the *main* model and failed with HTTP 404 ``No endpoints found that
-support image input`` even though a perfectly good vision backend was
-sitting in config waiting to be used.
-
-This module centralises the small policy decision: should a captured
-screenshot be returned as multimodal content (main model handles vision
-natively) or pre-analysed via the auxiliary vision pipeline so the main
+``computer_use(action='capture', mode='som'|'vision')`` returns a ``_multimodal``
+envelope with the screenshot, delivered to the active session model as the tool
+result. A text-only main model, or a provider that rejects multimodal content in
+tool results, turns that into a hard 400/404 tool failure — even when a working
+``auxiliary.vision`` model sits in config. This module decides: return the
+screenshot as multimodal content, or pre-analyse it via aux vision so the main
model only ever sees text?
-Behaviour (mirrors ``vision_analyze`` for consistency)
-------------------------------------------------------
-* If the user explicitly configured ``auxiliary.vision`` (any of
- ``provider``, ``model``, or ``base_url`` non-empty / not ``"auto"``),
- the screenshot is routed through the aux vision pipeline. Users who
- pay for a dedicated vision model usually want it used.
-* Otherwise, if the user explicitly declared the active model vision-capable
- via ``model.supports_vision`` / provider model config, return ``False``.
- This is the escape hatch for custom/local OpenAI-compatible VLM routes that
- are absent from models.dev and provider allowlists.
-* Otherwise, if the active main model+provider can carry an image inside
- a tool-result message AND the model reports ``supports_vision=True``
- in models.dev metadata, return ``False`` (use the multimodal path).
-* In every other case (non-vision main model, provider that does not
- accept multimodal tool results, lookup failure), route through aux
- vision so the main model receives a text description it can act on.
-
-The decision intentionally fails *closed* (i.e. towards aux routing) when
-metadata is missing or ambiguous: returning a screenshot to a model that
-cannot read it is a hard tool failure, while routing it through aux costs
-one extra LLM call and yields a usable description.
+Decision order (mirrors ``vision_analyze``):
+1. ``auxiliary.vision`` explicitly configured (provider not ""/"auto", or model /
+ base_url set) → aux routing; users who pay for a vision model want it used.
+2. User declared ``supports_vision`` for the active route (config escape hatch
+ for custom/local VLMs absent from models.dev) → honour it (True → multimodal).
+3. Provider+model carries images inside tool-result messages AND models.dev says
+ ``supports_vision=True`` → multimodal.
+4. Everything else (non-vision model, provider rejecting multimodal tool results,
+ lookup failure) → aux routing.
+
+The decision fails *closed* toward aux routing when metadata is missing or
+ambiguous: a screenshot sent to a model that cannot read it is a hard failure,
+while aux routing costs one extra LLM call and yields a usable description.
"""
from __future__ import annotations
@@ -56,28 +34,20 @@ logger = logging.getLogger(__name__)
def _explicit_aux_vision_override(cfg: Optional[Dict[str, Any]]) -> bool:
"""True when ``auxiliary.vision`` carries a non-default user override.
- Mirrors ``agent.image_routing._explicit_aux_vision_override`` so the
- capture path and the user-attached-image path agree on what counts as
- an explicit user request for the aux vision pipeline. ``provider:
- "auto"``, blank values, or a missing block all count as *not*
- explicit.
+ Mirrors ``agent.image_routing._explicit_aux_vision_override`` so the capture
+ path and the user-attached-image path agree. ``provider: "auto"``, blank
+ values, or a missing block all count as *not* explicit.
"""
if not isinstance(cfg, dict):
return False
aux = cfg.get("auxiliary") or {}
- if not isinstance(aux, dict):
- return False
- vision = aux.get("vision") or {}
+ vision = aux.get("vision") if isinstance(aux, dict) else None
if not isinstance(vision, dict):
return False
-
provider = str(vision.get("provider") or "").strip().lower()
model = str(vision.get("model") or "").strip()
base_url = str(vision.get("base_url") or "").strip()
-
- if provider in ("", "auto") and not model and not base_url:
- return False
- return True
+ return not (provider in ("", "auto") and not model and not base_url)
def _lookup_user_declared_supports_vision(
@@ -85,22 +55,13 @@ def _lookup_user_declared_supports_vision(
model: str,
cfg: Optional[Dict[str, Any]],
) -> Optional[bool]:
- """Return config-declared ``supports_vision`` for the active route."""
+ """Return config-declared ``supports_vision`` for the active route (None on failure)."""
try:
from agent.image_routing import _supports_vision_override
- except Exception as exc: # pragma: no cover - defensive
- logger.debug(
- "computer_use vision_routing: config override lookup import failed: %s",
- exc,
- )
- return None
- try:
+
return _supports_vision_override(cfg, provider, model)
except Exception as exc: # pragma: no cover - defensive
- logger.debug(
- "computer_use vision_routing: config override lookup failed: %s",
- exc,
- )
+ logger.debug("computer_use vision_routing: config override lookup failed: %s", exc)
return None
@@ -109,25 +70,23 @@ def _lookup_supports_vision(
model: str,
cfg: Optional[Dict[str, Any]] = None,
) -> Optional[bool]:
- """Return config/models.dev ``supports_vision`` for *(provider, model)*."""
+ """Return config/models.dev ``supports_vision`` for *(provider, model)*.
+
+ Prefers ``agent.image_routing._lookup_supports_vision``; falls back to raw
+ models.dev capabilities only when that import is unavailable. Any lookup
+ error yields None (caller fails closed toward aux routing).
+ """
if not provider or not model:
return None
try:
from agent.image_routing import _lookup_supports_vision as _lookup_image_supports
except Exception:
_lookup_image_supports = None
- if _lookup_image_supports is not None:
- try:
- return _lookup_image_supports(provider, model, cfg)
- except Exception as exc: # pragma: no cover - defensive
- logger.debug(
- "computer_use vision_routing: image-routing caps lookup failed "
- "for %s:%s — %s",
- provider, model, exc,
- )
- return None
try:
+ if _lookup_image_supports is not None:
+ return _lookup_image_supports(provider, model, cfg)
from agent.models_dev import get_model_capabilities
+
caps = get_model_capabilities(provider, model)
except Exception as exc: # pragma: no cover - defensive
logger.debug(
@@ -135,28 +94,22 @@ def _lookup_supports_vision(
provider, model, exc,
)
return None
- if caps is None:
- return None
- return bool(getattr(caps, "supports_vision", False))
+ return None if caps is None else bool(getattr(caps, "supports_vision", False))
def _provider_accepts_multimodal_tool_result(provider: str, model: str) -> Optional[bool]:
- """Return whether *provider*+*model* carries images inside tool-result messages.
+ """Whether *provider*+*model* carries images inside tool-result messages.
- Reuses ``tools.vision_tools._supports_media_in_tool_results`` so the
- capture-routing decision stays in lockstep with the
- ``vision_analyze`` native fast path. Returns None on import failure
- so callers fall back to aux routing rather than guessing.
+ Reuses ``tools.vision_tools._supports_media_in_tool_results`` so this stays
+ in lockstep with the ``vision_analyze`` native fast path. Returns None on
+ import failure so callers fall back to aux routing rather than guessing.
"""
if not provider:
return None
try:
from tools.vision_tools import _supports_media_in_tool_results
except Exception as exc: # pragma: no cover - defensive
- logger.debug(
- "computer_use vision_routing: tool-result support lookup failed: %s",
- exc,
- )
+ logger.debug("computer_use vision_routing: tool-result support lookup failed: %s", exc)
return None
return bool(_supports_media_in_tool_results(provider, model))
@@ -166,19 +119,11 @@ def should_route_capture_to_aux_vision(
model: str,
cfg: Optional[Dict[str, Any]],
) -> bool:
- """Return True iff the captured screenshot should be pre-analysed via aux vision.
-
- Args:
- provider: active inference provider id (e.g. ``"openrouter"``,
- ``"anthropic"``, ``"openai-codex"``). Lower-case canonical id.
- model: active main model slug as it would be sent to the provider.
- cfg: loaded ``config.yaml`` dict (or None).
-
- Returns:
- ``True`` when the caller should hand the screenshot to the aux vision
- pipeline (and surface a text-only tool result). ``False`` when the
- caller should keep the existing multimodal envelope (main model
- handles vision natively).
+ """True iff the captured screenshot should be pre-analysed via aux vision.
+
+ *provider* is the lower-case canonical id, *model* the slug as sent to the
+ provider, *cfg* the loaded ``config.yaml`` dict (or None). False means keep
+ the multimodal envelope (main model handles vision natively).
"""
if _explicit_aux_vision_override(cfg):
return True
@@ -189,14 +134,10 @@ def should_route_capture_to_aux_vision(
if user_declared is False:
return True
- accepts_tool_image = _provider_accepts_multimodal_tool_result(provider, model)
- if accepts_tool_image is None or accepts_tool_image is False:
+ if not _provider_accepts_multimodal_tool_result(provider, model):
return True
- supports_vision = _lookup_supports_vision(provider, model, cfg)
- if supports_vision is True:
- return False
- return True
+ return _lookup_supports_vision(provider, model, cfg) is not True
__all__ = [
diff --git a/tools/computer_use_tool.py b/tools/computer_use_tool.py
index 9593795768e..3e14f7aedcf 100644
--- a/tools/computer_use_tool.py
+++ b/tools/computer_use_tool.py
@@ -38,5 +38,4 @@ __all__ = [
"release_computer_use_session",
"set_approval_callback",
"check_computer_use_requirements",
- "release_computer_use_session",
]