The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(computer_use): contextlib rollback/suppress in cua backend + daemon; _json_object helper; daemon startup-failure helper; tighten prose
Teknium22def3f4a90b
diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.pyindex 7d1718e4637..d9da879f413 100644--- a/tools/computer_use/cua_backend.py+++ b/tools/computer_use/cua_backend.py@@ -1,17 +1,11 @@-"""Cua-driver backend (macOS, Windows, Linux): MCP over stdio to `cua-driver`.--The async `mcp` SDK runs on a background loop (``cua_backend_session``); the same tool surface-works on all three platforms, and per-host gaps (no DISPLAY, missing AT-SPI, TCC) surface via-`hermes computer-use doctor` instead of failing silently. Install with `hermes computer-use-install`. The macOS path uses private SkyLight SPIs that can break on OS updates.--Siblings: ``cua_backend_driver`` (binary resolution, runtime contract, update check),-``cua_backend_capture`` / ``cua_backend_input`` (backend mixins), ``cua_backend_parse`` (pure-parsing), ``cua_backend_session`` (bridge + session + CLI fallback), ``cua_backend_daemon``-(private daemon + macOS app identity). Moved names are re-imported here so-``patch("tools.computer_use.cua_backend.X")`` keeps working; siblings look policy helpers up-lazily through this module.-"""+"""Cua-driver backend (macOS, Windows, Linux): MCP over stdio to `cua-driver`. The async `mcp` SDK runs on a+background loop (``cua_backend_session``); the same tool surface works on all three platforms, and per-host gaps+(no DISPLAY, missing AT-SPI, TCC) surface via `hermes computer-use doctor` instead of failing silently. Install+with `hermes computer-use install`. The macOS path uses private SkyLight SPIs that can break on OS updates.+Siblings: ``cua_backend_driver`` (binary/contract/update), ``cua_backend_capture`` + ``cua_backend_input``+(mixins), ``cua_backend_parse``, ``cua_backend_session`` (bridge + session + CLI fallback), ``cua_backend_daemon``+(private daemon + macOS app identity). Moved names are re-imported here so ``patch("tools.computer_use.cua_backend.X")``+keeps working; siblings look policy helpers up lazily through this module."""from __future__ import annotations@@ -59,11 +53,10 @@ def _computer_use_cfg() -> Dict[str, Any]:return {}def _cua_no_overlay() -> bool:- """Pass ``--no-overlay``? ``computer_use.no_overlay`` overrides; else off on macOS (cursor-overlay- redraw loop can peg a core after a session), headless Linux / WSL2 / containers, and Linux X11 (the- overlay is a fullscreen always-on-top all-workspaces window with no compositor-owned lifecycle, so an- unclean session end can leave it wedged over every app); on for Windows and Linux Wayland- (compositor owns the surface)."""+ """Pass ``--no-overlay``? ``computer_use.no_overlay`` overrides; else off on macOS (cursor-overlay redraw+ loop can peg a core after a session), headless Linux / WSL2 / containers, and Linux X11 (the overlay is a+ fullscreen always-on-top all-workspaces window with no compositor-owned lifecycle, so an unclean session+ end can leave it wedged over every app); on for Windows and Linux Wayland (compositor owns the surface)."""val = _computer_use_cfg().get("no_overlay")if val is not None:return bool(val)@@ -71,12 +64,9 @@ def _cua_no_overlay() -> bool:return sys.platform == "darwin"if not os.environ.get("DISPLAY"):return True- try:- with open("/proc/version", encoding="utf-8") as f:- if "microsoft" in f.read().lower():- return True- except Exception:- pass+ with contextlib.suppress(Exception), open("/proc/version", encoding="utf-8") as f:+ if "microsoft" in f.read().lower():+ return Truereturn os.environ.get("XDG_SESSION_TYPE") != "wayland" and not os.environ.get("WAYLAND_DISPLAY")def _cua_telemetry_disabled() -> bool:@@ -84,9 +74,9 @@ def _cua_telemetry_disabled() -> bool:return not bool(_computer_use_cfg().get("cua_telemetry", False))def _cua_configured_permission_mode() -> str:- """``computer_use.permission_mode``: ``standard`` (default) or ``bounded``; unknown values fall closed- to ``standard``. ``unrestricted`` is deliberately NOT a config value — it stays tied to the per-session- YOLO toggle so a stale config line can never silently bypass approvals."""+ """``computer_use.permission_mode``: ``standard`` (default) or ``bounded``; unknown values fall closed to+ ``standard``. ``unrestricted`` is deliberately NOT a config value — it stays tied to the per-session YOLO+ toggle so a stale config line can never silently bypass approvals."""raw = str(_computer_use_cfg().get("permission_mode", "standard") or "").strip().lower()return raw if raw in {"standard", "bounded"} else "standard"@@ -115,9 +105,8 @@ def _computer_use_max_image_dimension() -> Optional[int]:return dim if dim > 0 else Nonedef cua_driver_child_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str, str]:- """Env for spawning cua-driver: ``base_env`` (default ``os.environ``) plus- ``CUA_DRIVER_RS_TELEMETRY_ENABLED=0`` unless the user opted in. Used by every spawn site (MCP,- status, doctor, install) so the policy is uniform."""+ """Env for spawning cua-driver: ``base_env`` (default ``os.environ``) plus ``CUA_DRIVER_RS_TELEMETRY_ENABLED=0``+ unless the user opted in. Used by every spawn site (MCP, status, doctor, install) so the policy is uniform."""env = dict(base_env if base_env is not None else os.environ)if _cua_telemetry_disabled():env[_CUA_TELEMETRY_ENV_VAR] = "0"@@ -134,9 +123,9 @@ def sanitized_cua_driver_env() -> Dict[str, str]:return envdef _run_quiet(argv: List[str], *, timeout: float, swallow: Any = (), **kw: Any) -> Any:- """``subprocess.run`` for short probe verbs: text mode, stdin=DEVNULL (older drivers fall into a- stdin-reading mode on unknown verbs; EOF makes them exit fast instead of blocking until the timeout),- output captured unless the caller redirects it. Exceptions in ``swallow`` return None; others raise."""+ """``subprocess.run`` for short probe verbs: text mode, stdin=DEVNULL (older drivers fall into a stdin-reading+ mode on unknown verbs; EOF makes them exit fast instead of blocking until the timeout), output captured unless+ the caller redirects it. Exceptions in ``swallow`` return None; others raise."""if "stdout" not in kw:kw["capture_output"] = Truetry:@@ -152,26 +141,20 @@ def _run_driver(driver_cmd: str, *args: str, timeout: float, swallow: Any = ())# ── Linux display diagnostics ─────────────────────────────────────────────def _linux_session_locked() -> Optional[bool]:- """Is the graphical session locked? (Linux; best-effort.) A locked KDE/GNOME session freezes renderers- and half-disables the AX tree, so discovery legitimately returns nothing — which otherwise reads as a- driver bug. True/False when loginctl answers, None when unavailable (non-Linux, no systemd-logind,- probe failure)."""+ """Is the graphical session locked? (Linux; best-effort.) A locked KDE/GNOME session freezes renderers and+ half-disables the AX tree, so discovery legitimately returns nothing — which otherwise reads as a driver bug.+ True/False when loginctl answers, None when unavailable (non-Linux, no systemd-logind, probe failure)."""if sys.platform != "linux":return Nonetry:proc = _run_quiet(["loginctl", "list-sessions", "--no-legend"], timeout=2.0)if proc.returncode != 0:return None- any_seat = False- for line in proc.stdout.splitlines():- parts = line.split()- if len(parts) < 2 or "seat" not in line:- continue- any_seat = True- hint = _run_quiet(["loginctl", "show-session", parts[0], "-p", "LockedHint"], timeout=2.0)- if "LockedHint=no" in hint.stdout:+ seats = [line.split()[0] for line in proc.stdout.splitlines() if len(line.split()) >= 2 and "seat" in line]+ for session_id in seats:+ if "LockedHint=no" in _run_quiet(["loginctl", "show-session", session_id, "-p", "LockedHint"], timeout=2.0).stdout:return False- return True if any_seat else None+ return True if seats else Noneexcept Exception:return None@@ -197,15 +180,15 @@ def _empty_discovery_reason() -> str:# ── One-shot start() helpers: auto-repair + update nudge ──────────────────_update_checked = False-# One auto-repair attempt per process: when the runtime-contract gate fails for something a reinstall-# fixes (old version, missing manifest verbs) run the standard install path once instead of telling the-# user to. Guarded so a failing installer can't loop — the second start() goes straight to the error.+# One auto-repair attempt per process: when the runtime-contract gate fails for something a reinstall fixes+# (old version, missing manifest verbs) run the standard install path once instead of telling the user to.+# Guarded so a failing installer can't loop — the second start() goes straight to the error._contract_repair_attempted = Falsedef _maybe_repair_runtime_contract(contract: Dict[str, Any]) -> Dict[str, Any]:"""Try one automatic driver repair; return the post-repair contract (or the original when no repair was- attempted / it failed). Never raises. An explicit ``HERMES_CUA_DRIVER_CMD`` override is authoritative- even when broken, and a missing binary means installation was never requested."""+ attempted / it failed). Never raises. An explicit ``HERMES_CUA_DRIVER_CMD`` override is authoritative even+ when broken, and a missing binary means installation was never requested."""global _contract_repair_attemptedif (contract.get("ready") or _contract_repair_attemptedor os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() or not contract.get("binary")):@@ -225,20 +208,18 @@ def _maybe_repair_runtime_contract(contract: Dict[str, Any]) -> Dict[str, Any]:return contractdef _maybe_nudge_update() -> None:- """Emit an update nudge at most once per process, off-thread so the (cached, ~20h) GitHub poll never- blocks the first computer_use action."""+ """Emit an update nudge at most once per process, off-thread so the (cached, ~20h) GitHub poll never blocks+ the first computer_use action."""global _update_checkedif _update_checked:return_update_checked = Truedef _run() -> None:- try:+ with contextlib.suppress(Exception):msg = cua_driver_update_nudge()- except Exception:- return- if msg:- logger.info("computer_use: %s", msg)+ if msg:+ logger.info("computer_use: %s", msg)threading.Thread(target=_run, name="cua-driver-update-check", daemon=True).start()@@ -260,18 +241,13 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend):capability_manifest=raw.strip() if isinstance(raw, str) and raw.strip() else None)self._bridge = _AsyncBridge()self._session = _CuaDriverSession(self._bridge, self._embedded_daemon)- # Sticky target — set by capture()/focus_app(), used by actions. `_last_target` is the exact- # identity for capture_after: Linux app names may be generic (several unrelated Qt windows can- # all say Qt6Application). `_snapshot_tokens` is the per-snapshot `element_index ->- # element_token`; actions attach it so cua-driver reports "stale" instead of silently re-resolving.- self._active_pid: Optional[int] = None- self._active_window_id: Optional[int] = None- self._last_app: Optional[str] = None- self._last_target: Optional[Dict[str, Optional[int]]] = None- self._snapshot_tokens: Dict[int, str] = {}- # Public session label (one per Hermes run) sent as `session` on every call: owns the cursor- # color and gives config/recording state a stable owner across transport restarts. Part of- # the 0.20 runtime contract.+ # Sticky target — set by capture()/focus_app(), used by actions: `_active_pid`, `_active_window_id`,+ # `_last_app`, `_last_target` (exact identity for capture_after: Linux app names may be generic — several+ # unrelated Qt windows can all say Qt6Application) and `_snapshot_tokens` (per-snapshot `element_index ->+ # element_token`; actions attach it so cua-driver reports "stale" instead of silently re-resolving).+ self._clear_active_target()+ # Public session label (one per Hermes run) sent as `session` on every call: owns the cursor color and+ # gives config/recording state a stable owner across transport restarts. Part of the 0.20 runtime contract.self._session_id: str = f"hermes-{uuid.uuid4().hex[:12]}"self._session.set_transport_reset_callback(self._handle_transport_reset)@@ -286,31 +262,26 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend):contract = _maybe_repair_runtime_contract(contract)if not contract.get("ready"):repair = ("Update the binary selected by HERMES_CUA_DRIVER_CMD or remove that override."- if os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip()- else "Run `hermes computer-use install` to repair it.")- raise RuntimeError(f"cua-driver is not ready: "- f"{contract.get('reason') or 'runtime contract is incomplete'}. {repair}")+ if os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip() else "Run `hermes computer-use install` to repair it.")+ raise RuntimeError(f"cua-driver is not ready: {contract.get('reason') or 'runtime contract is incomplete'}. {repair}")_maybe_nudge_update()# `mcp` is an optional extra: lazy-install on first use (gated by `security.allow_lazy_installs`);# failure raises FeatureUnavailable with the exact `uv pip install` hint.from tools.lazy_deps import ensure as _lazy_ensure_lazy_ensure("tool.computer_use", prompt=False)importlib.invalidate_caches() # a just-installed package may not be importable yet- daemon = self._embedded_daemon- try:- if daemon is not None:- daemon.start()+ with contextlib.ExitStack() as rollback: # a failed start stops the private daemon, then re-raises+ if self._embedded_daemon is not None:+ rollback.callback(self._embedded_daemon.stop)+ self._embedded_daemon.start()self._session.start()- except Exception:- if daemon is not None:- daemon.stop()- raise- # Declare this run's identity. Non-fatal: cua-driver accepts anonymous calls (the cursor just- # won't render), so degrade rather than abort.+ rollback.pop_all()+ # Declare this run's identity. Non-fatal: cua-driver accepts anonymous calls (the cursor just won't+ # render), so degrade rather than abort.self._best_effort("start_session failed (continuing anonymous)",self._session.call_tool, "start_session", {"session": self._session_id})- # Post-handshake tuning guards on `_started`: before the handshake flips it, call_tool would- # re-enter session.start() (stubbed start() recurses).+ # Post-handshake tuning guards on `_started`: before the handshake flips it, call_tool would re-enter+ # session.start() (stubbed start() recurses).if self._session._started:max_dim = _computer_use_max_image_dimension()if max_dim: # smaller screenshots cost less over the daemon socket and per turn@@ -321,8 +292,8 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend):self.set_agent_cursor_enabled, False, cursor_id=self._session_id)def stop(self) -> None:- # Best-effort end_session so the driver cleans per-session state (cursor overlay, recording- # ownership, config overrides); the connection drop below releases daemon-side state regardless.+ # Best-effort end_session so the driver cleans per-session state (cursor overlay, recording ownership,+ # config overrides); the connection drop below releases daemon-side state regardless.if self._session._started:self._best_effort("end_session failed (continuing teardown)",self._session.call_tool, "end_session", {"session": self._session_id})@@ -348,14 +319,17 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend):# ── Target state ───────────────────────────────────────────────def _clear_active_target(self) -> None:"""Forget a capture/focus target so a failed lookup cannot misroute input."""- self._active_pid = self._active_window_id = self._last_app = self._last_target = None- self._snapshot_tokens = {}+ self._active_pid: Optional[int] = None+ self._active_window_id: Optional[int] = None+ self._last_app: Optional[str] = None+ self._last_target: Optional[Dict[str, Optional[int]]] = None+ self._snapshot_tokens: Dict[int, str] = {}def _set_active_target(self, target: Dict[str, Any]) -> None:self._active_pid = target["pid"]self._active_window_id = target["window_id"]- # Tokens belong to the prior snapshot; disarm before any capture call so an exception cannot- # pair old tokens with this target.+ # Tokens belong to the prior snapshot; disarm before any capture call so an exception cannot pair old+ # tokens with this target.self._snapshot_tokens = {}self._last_target = {"pid": self._active_pid, "window_id": self._active_window_id}@@ -363,9 +337,8 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend):def launch_app(self, *, bundle_id: Optional[str] = None, name: Optional[str] = None,urls: Optional[List[str]] = None, additional_arguments: Optional[List[str]] = None,creates_new_application_instance: bool = False) -> Dict[str, Any]:- """Idempotent launch returning ``{pid, bundle_id, name, windows[]}``.- ``creates_new_application_instance=True`` forces a fresh instance so concurrent runs touching- the same app get isolated windows."""+ """Idempotent launch returning ``{pid, bundle_id, name, windows[]}``. ``creates_new_application_instance=True``+ forces a fresh instance so concurrent runs touching the same app get isolated windows."""if not bundle_id and not name:raise ValueError("launch_app requires either bundle_id or name")args: Dict[str, Any] = {"session": self._session_id}@@ -382,8 +355,8 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend):args: Dict[str, Any] = {"pid": int(pid)}if window_id is not None:args["window_id"] = int(window_id)- # The live schema is strict and has no session property: this is a standalone native focus- # operation, not a session-scoped input action.+ # The live schema is strict and has no session property: this is a standalone native focus operation,+ # not a session-scoped input action.return self._action("bring_to_front", args, inject_session=False)# ── Agent cursor / config ────────────────────────────────────────@@ -400,18 +373,17 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend):return self._action("set_config", dict(config))def call_tool(self, name: str, args: Optional[Dict[str, Any]] = None, *, timeout: float = 30.0) -> Dict[str, Any]:- """Generic escape hatch: call any cua-driver MCP tool by name. ``session`` is injected via- setdefault, so this is the supported path for tools the wrapper does not type-wrap (preferred over- ``self._session.call_tool``)."""+ """Generic escape hatch: call any cua-driver MCP tool by name. ``session`` is injected via setdefault, so+ this is the supported path for tools the wrapper does not type-wrap (preferred over ``self._session.call_tool``)."""payload = dict(args) if args else {}payload.setdefault("session", self._session_id)return self._session.call_tool(name, payload, timeout=timeout)# ── Internal ───────────────────────────────────────────────────def _action(self, name: str, args: Dict[str, Any], *, inject_session: bool = True) -> ActionResult:- # Attach the snapshot's `element_token` to an `element_index` call so a superseded snapshot- # yields an explicit 'stale' error. Gated on the per-tool capability: older drivers- # (`additionalProperties: false`) must never see the field.+ # Attach the snapshot's `element_token` to an `element_index` call so a superseded snapshot yields an+ # explicit 'stale' error. Gated on the per-tool capability: older drivers (`additionalProperties: false`)+ # must never see the field.idx = args.get("element_index")token = self._snapshot_tokens.get(idx) if isinstance(idx, int) else Noneif token and self._session.supports_capability("accessibility.element_tokens", tool=name):diff --git a/tools/computer_use/cua_backend_daemon.py b/tools/computer_use/cua_backend_daemon.pyindex 92dd744f584..75f715b3531 100644--- a/tools/computer_use/cua_backend_daemon.py+++ b/tools/computer_use/cua_backend_daemon.py@@ -1,10 +1,10 @@-"""Private embedded cua-driver daemon for non-standard permission modes, plus the macOS CuaDriver.app-identity checks its launch path depends on. Driver resolution / policy helpers are looked up lazily-through ``tools.computer_use.cua_backend`` so tests that patch them there keep working.-"""+"""Private embedded cua-driver daemon for non-standard permission modes, plus the macOS CuaDriver.app identity+checks its launch path depends on. Driver resolution / policy helpers are looked up lazily through+``tools.computer_use.cua_backend`` so tests that patch them there keep working."""from __future__ import annotations+import contextlibimport loggingimport osimport shutil@@ -31,9 +31,9 @@ def _cb():return cua_backenddef _resolve_cua_driver_app_path(driver_cmd: str) -> Optional[str]:- """Return the CuaDriver.app bundle that CARRIES *driver_cmd*, if any. Derived from the resolved binary- path only — no /Applications fallback, which could be a DIFFERENT install than the one the manifest- resolved, running code the resolution chain never validated."""+ """Return the CuaDriver.app bundle that CARRIES *driver_cmd*, if any. Derived from the resolved binary path+ only — no /Applications fallback, which could be a DIFFERENT install than the one the manifest resolved,+ running code the resolution chain never validated."""resolved = os.path.realpath(driver_cmd)marker_index = resolved.find(".app/Contents/MacOS/")if marker_index < 0:@@ -43,11 +43,11 @@ def _resolve_cua_driver_app_path(driver_cmd: str) -> Optional[str]:return candidate if os.path.isfile(executable) and os.access(executable, os.X_OK) else Nonedef _validate_cua_driver_app_signature(app_path: str) -> None:- """Fail closed unless *app_path* is the genuinely-signed CuaDriver.app. ``/usr/bin/open`` hands- LaunchServices whatever bundle sits at the path, so ``codesign -dv`` must report EXACTLY- ``Identifier=com.trycua.driver`` and an expected TeamIdentifier. ``TeamIdentifier=not set`` (ad-hoc dev- builds) is allowed only with ``computer_use.allow_unsigned_driver: true``. Raises RuntimeError on any- mismatch or when codesign is unavailable/fails."""+ """Fail closed unless *app_path* is the genuinely-signed CuaDriver.app. ``/usr/bin/open`` hands LaunchServices+ whatever bundle sits at the path, so ``codesign -dv`` must report EXACTLY ``Identifier=com.trycua.driver`` and+ an expected TeamIdentifier. ``TeamIdentifier=not set`` (ad-hoc dev builds) is allowed only with+ ``computer_use.allow_unsigned_driver: true``. Raises RuntimeError on any mismatch or when codesign is+ unavailable/fails."""codesign = shutil.which("codesign")if not codesign:raise RuntimeError("codesign is required to verify CuaDriver.app before launching it.")@@ -100,21 +100,14 @@ def _wait_or_kill(process: Any) -> None:class _EmbeddedCuaDaemon:- """Private daemon for a non-standard permission mode.-- cua-driver's permission mode is immutable after daemon startup, so reusing the machine-wide daemon- would let one Hermes session's YOLO choice affect another. A private daemon gives the session its own- socket, runtime and launch-time authorization; on macOS it is launched through CuaDriver.app so TCC- stays attached to ``com.trycua.driver``.-- * ``unrestricted`` — explicit Hermes YOLO (``--dangerously-bypass-approvals``).- * ``bounded`` — a user-reviewed capability manifest approved at launch is the authorization- boundary, not a runtime prompt.-- The manifest is a ceiling, not a mode: it "can narrow a profile but never widen it", so a configured- v3 manifest is forwarded even for ``unrestricted`` (bounding an approval-bypassed run). Mandatory for- ``bounded``, optional everywhere else.- """+ """Private daemon for a non-standard permission mode. cua-driver's permission mode is immutable after daemon+ startup, so reusing the machine-wide daemon would let one Hermes session's YOLO choice affect another. A+ private daemon gives the session its own socket, runtime and launch-time authorization; on macOS it is+ launched through CuaDriver.app so TCC stays attached to ``com.trycua.driver``. ``unrestricted`` = explicit+ Hermes YOLO (``--dangerously-bypass-approvals``); ``bounded`` = a user-reviewed capability manifest approved+ at launch is the authorization boundary, not a runtime prompt. The manifest is a ceiling, not a mode: it "can+ narrow a profile but never widen it", so a configured v3 manifest is forwarded even for ``unrestricted``+ (bounding an approval-bypassed run). Mandatory for ``bounded``, optional everywhere else."""_START_TIMEOUT_SECONDS = 15.0@@ -129,8 +122,8 @@ class _EmbeddedCuaDaemon:if not os.path.isfile(manifest):raise ValueError(f"capability manifest not found: {manifest}")self.capability_manifest: Optional[str] = manifest or None- # bounded always forwards (the driver validates it); other modes accept only a v3 manifest — a- # legacy one would abort startup instead.+ # bounded always forwards (the driver validates it); other modes accept only a v3 manifest — a legacy one+ # would abort startup instead.self.manifest_applies = bool(manifest) and (permission_mode == "bounded" or _cb()._manifest_is_mode_independent(manifest))if manifest and not self.manifest_applies:@@ -142,9 +135,8 @@ class _EmbeddedCuaDaemon:self._driver_cmd = self._command = driver_cmdself._mcp_args: List[str] = list(_cb()._CUA_DRIVER_ARGS)self._process: Any = None- self._owns_runtime = self._running = self._launch_via_app = False+ self._owns_runtime = self._running = Falseself._stderr_tail: deque[str] = deque(maxlen=20)- self._stderr_thread: Optional[threading.Thread] = Nonetoken = uuid.uuid4().hex[:12]self.socket_path = (rf"\\.\pipe\hermes-cua-{token}" if sys.platform == "win32"else os.path.join(tempfile.gettempdir(), f"hc-{token}.sock"))@@ -161,14 +153,12 @@ class _EmbeddedCuaDaemon:return _sanitize_subprocess_env(self.child_env())def _drain_stderr(self, process: Any) -> None:- try:+ with contextlib.suppress(Exception):for line in getattr(process, "stderr", None) or ():text = str(line).strip()if text:self._stderr_tail.append(text)logger.debug("embedded cua-driver: %s", text)- except Exception:- passdef _serve_args(self) -> List[str]:serve_args = ["serve", "--embedded", "--socket", self.socket_path,@@ -177,9 +167,9 @@ class _EmbeddedCuaDaemon:serve_args.append("--dangerously-bypass-approvals")if self.manifest_applies:serve_args += ["--capability-manifest", str(self.capability_manifest), "--approve-capability-manifest"]- # The private daemon owns the cursor overlay, so the overlay policy must apply to this long-lived- # serve process, not only its MCP proxy. Appended BEFORE the macOS app-launch wrapping so the flag- # travels inside `open ... --args` with the rest of the serve args.+ # The private daemon owns the cursor overlay, so the overlay policy must apply to this long-lived serve+ # process, not only its MCP proxy. Appended BEFORE the macOS app-launch wrapping so the flag travels inside+ # `open ... --args` with the rest of the serve args.return _cb()._mcp_args_with_overlay_flag(serve_args, driver_cmd=self._command)def start(self) -> None:@@ -190,29 +180,28 @@ class _EmbeddedCuaDaemon:raise RuntimeError(_cb().cua_driver_install_hint())self._command, self._mcp_args = _cb()._resolve_mcp_invocation(self._driver_cmd)env = self._sanitized_env()- self._launch_via_app = sys.platform == "darwin"command = _embedded_daemon_spawn_command(self._command, self._serve_args(), platform=sys.platform)self._process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,stderr=subprocess.PIPE, text=True, env=env)self._owns_runtime = True- self._stderr_thread = threading.Thread(target=self._drain_stderr, args=(self._process,),- name="hermes-cua-daemon-stderr", daemon=True)- self._stderr_thread.start()+ threading.Thread(target=self._drain_stderr, args=(self._process,),+ name="hermes-cua-daemon-stderr", daemon=True).start()deadline = time.monotonic() + self._START_TIMEOUT_SECONDSwhile time.monotonic() < deadline:return_code = self._process.poll()- # `open` exits 0 once LaunchServices took the request, so on macOS only a non-zero exit means- # the daemon itself died.- if return_code is not None and (not self._launch_via_app or return_code != 0):- detail = "; ".join(self._stderr_tail) or "no diagnostic output"- raise RuntimeError(f"embedded cua-driver exited during startup: {detail}")+ # `open` exits 0 once LaunchServices took the request, so on macOS only a non-zero exit means the+ # daemon itself died.+ if return_code is not None and (sys.platform != "darwin" or return_code != 0):+ self._startup_failure("embedded cua-driver exited during startup", "no diagnostic output")if self._socket_ready(env):self._running = Truereturntime.sleep(0.1)self.stop()- detail = "; ".join(self._stderr_tail) or "daemon did not become ready"- raise RuntimeError(f"embedded cua-driver startup timed out: {detail}")+ self._startup_failure("embedded cua-driver startup timed out", "daemon did not become ready")++ def _startup_failure(self, what: str, fallback: str) -> None:+ raise RuntimeError(f"{what}: {'; '.join(self._stderr_tail) or fallback}")def _socket_ready(self, env: Dict[str, str]) -> bool:"""``cua-driver status --socket`` exits 0 once the private daemon accepts connections."""@@ -236,7 +225,5 @@ class _EmbeddedCuaDaemon:if process is not None:_wait_or_kill(process)if sys.platform != "win32" and os.path.exists(self.socket_path):- try:+ with contextlib.suppress(OSError):os.remove(self.socket_path)- except OSError:- passdiff --git a/tools/computer_use/cua_backend_driver.py b/tools/computer_use/cua_backend_driver.pyindex a6476f0a205..68e8c693e80 100644--- a/tools/computer_use/cua_backend_driver.py+++ b/tools/computer_use/cua_backend_driver.py@@ -1,8 +1,6 @@-"""cua-driver binary resolution, MCP-invocation discovery, the 0.20 runtime contract gate, and the-update check. Config-derived policy (``_cua_no_overlay``, ``_run_driver`` ...) is looked up lazily-through ``tools.computer_use.cua_backend`` so tests that patch it there keep working; logger name-parity is kept for the same reason.-"""+"""cua-driver binary resolution, MCP-invocation discovery, the 0.20 runtime contract gate, and the update check.+Config-derived policy (``_cua_no_overlay``, ``_run_driver`` ...) is looked up lazily through+``tools.computer_use.cua_backend`` so tests that patch it there keep working; logger name parity likewise."""from __future__ import annotations@@ -39,15 +37,16 @@ def _cb():return cua_backenddef _driver_json(driver_cmd: str, *args: str, timeout: float, require_ok: bool) -> Optional[Dict[str, Any]]:- """Run a driver verb and parse its stdout as a JSON object; None on spawn failure, empty stdout (older- drivers print usage to stderr), unparseable or non-object output — and, with ``require_ok``, on a- non-zero exit."""+ """Run a driver verb and parse its stdout as a JSON object; None on spawn failure, empty stdout (older drivers+ print usage to stderr), unparseable or non-object output — and, with ``require_ok``, on a non-zero exit."""proc = _cb()._run_driver(driver_cmd, *args, timeout=timeout, swallow=Exception)out = (proc.stdout or "").strip() if proc is not None else ""- if not out or (require_ok and proc.returncode != 0):- return None+ return None if not out or (require_ok and proc.returncode != 0) else _json_object(out)++def _json_object(text: str) -> Optional[Dict[str, Any]]:+ """``json.loads`` that yields a dict or None (unparseable / non-object)."""try:- data = json.loads(out)+ data = json.loads(text)except (ValueError, TypeError):return Nonereturn data if isinstance(data, dict) else None@@ -63,9 +62,9 @@ def _has_path_separator(value: str) -> bool:return os.sep in value or (os.altsep is not None and os.altsep in value)def _wsl_windows_path_to_posix(path: str) -> str:- """Translate a Windows absolute manifest command to its DrvFS ``/mnt/<drive>/...`` form when Hermes runs- in WSL (a Windows cua-driver manifest can report ``C:\\...`` while Hermes spawns via POSIX). Non-Windows- paths and non-WSL hosts are returned unchanged."""+ """Translate a Windows absolute manifest command to its DrvFS ``/mnt/<drive>/...`` form when Hermes runs in WSL+ (a Windows cua-driver manifest can report ``C:\\...`` while Hermes spawns via POSIX). Non-Windows paths and+ non-WSL hosts are returned unchanged."""if not re.match(r"^[A-Za-z]:[\\/]", path):return pathtry:@@ -81,10 +80,10 @@ def _wsl_windows_path_to_posix(path: str) -> str:return os.path.join("/mnt", drive, *(str(part) for part in win.parts[1:]))def _candidate_cua_driver_commands(override: Optional[str] = None) -> List[str]:- """Candidate commands in resolution order. ``override`` / a non-empty ``HERMES_CUA_DRIVER_CMD`` is- authoritative (if wrong, report the driver missing rather than silently picking another binary).- Otherwise PATH, then canonical installer locations — Finder/Dock-launched apps inherit a narrow PATH- without ``~/.local/bin``; fresh Windows sessions inherit a stale one."""+ """Candidate commands in resolution order. ``override`` / a non-empty ``HERMES_CUA_DRIVER_CMD`` is authoritative+ (if wrong, report the driver missing rather than silently picking another binary). Otherwise PATH, then+ canonical installer locations — Finder/Dock-launched apps inherit a narrow PATH without ``~/.local/bin``;+ fresh Windows sessions inherit a stale one."""configured = (override if override is not None else os.environ.get(_CUA_DRIVER_CMD_ENV, "")).strip()if configured:return [configured]@@ -138,20 +137,20 @@ def _cua_driver_supports_no_overlay(driver_cmd: str) -> bool:return Falsedef _resolve_mcp_invocation(driver_cmd: str, *, timeout: float = 6.0) -> Tuple[str, List[str]]:- """``(command, args)`` that spawn cua-driver's stdio MCP server, asked of the driver itself via- ``cua-driver manifest`` (``mcp_invocation``) so a subcommand rename keeps working. Falls back to- ``(driver_cmd, ["mcp"])`` on older drivers or any discovery failure — the wrapper must not refuse to- start over a failed discovery hop. ``--no-overlay`` appended when allowed."""+ """``(command, args)`` that spawn cua-driver's stdio MCP server, asked of the driver itself via ``cua-driver+ manifest`` (``mcp_invocation``) so a subcommand rename keeps working. Falls back to ``(driver_cmd, ["mcp"])``+ on older drivers or any discovery failure — the wrapper must not refuse to start over a failed discovery hop.+ ``--no-overlay`` appended when allowed."""manifest = _driver_json(driver_cmd, "manifest", timeout=timeout, require_ok=True) or {}invocation = manifest.get("mcp_invocation")args = _valid_mcp_args(invocation)command = invocation.get("command") if args is not None and isinstance(invocation, dict) else Noneargs = list(_CUA_DRIVER_ARGS) if args is None else argsif isinstance(command, str) and command:- # Translate a Windows ``C:\...`` command for WSL BEFORE the separator check (backslash is not a- # separator on POSIX). A generic ``cua-driver`` name would lose the resolved user-local path under- # a GUI's thin PATH, so only a concrete (path-bearing) command replaces the one we verified — and- # THAT binary is probed for `--no-overlay`, not the system one.+ # Translate a Windows ``C:\...`` command for WSL BEFORE the separator check (backslash is not a separator+ # on POSIX). A generic ``cua-driver`` name would lose the resolved user-local path under a GUI's thin PATH,+ # so only a concrete (path-bearing) command replaces the one we verified — and THAT binary is probed for+ # `--no-overlay`, not the system one.command = _wsl_windows_path_to_posix(command)if _has_path_separator(command):return command, _mcp_args_with_overlay_flag(args, driver_cmd=command)@@ -200,24 +199,19 @@ def cua_driver_runtime_contract_status(binary: Optional[str] = None) -> Dict[strdetail = (result.stderr or result.stdout or "manifest command failed").strip()result, reason = None, detail.splitlines()[-1][:200]if result is not None:- try:- manifest = json.loads(result.stdout or "")- except (TypeError, ValueError):- manifest = None- manifest = manifest if isinstance(manifest, dict) else None+ manifest = _json_object(result.stdout or "")reason = _manifest_contract_reason(manifest)if manifest is not None:version = str(manifest.get("binary_version") or "").strip() or Nonereturn {"ready": not reason, "binary": resolved, "version": version, "reason": reason}def cua_driver_update_check(*, timeout: Optional[float] = None) -> Optional[Dict[str, Any]]:- """``cua-driver check-update --json`` payload (``{current_version, latest_version, update_available,- ...}``), or ``None`` when the binary is missing, the driver predates the verb, the GitHub check failed- (``error`` set) or the output didn't parse. Never raises. ``timeout`` defaults to 8s on POSIX / 25s on- Windows: first spawn of the exe routinely eats seconds in Defender scanning, and callers treat ``None``- as indeterminate (the upgrade path used to fall through to a full reinstall on a false timeout)."""- if timeout is None:- timeout = 25.0 if sys.platform == "win32" else 8.0+ """``cua-driver check-update --json`` payload (``{current_version, latest_version, update_available, ...}``),+ or ``None`` when the binary is missing, the driver predates the verb, the GitHub check failed (``error`` set)+ or the output didn't parse. Never raises. ``timeout`` defaults to 8s on POSIX / 25s on Windows: first spawn of+ the exe routinely eats seconds in Defender scanning, and callers treat ``None`` as indeterminate (the upgrade+ path used to fall through to a full reinstall on a false timeout)."""+ timeout = (25.0 if sys.platform == "win32" else 8.0) if timeout is None else timeoutdriver_cmd = _cb().resolve_cua_driver_cmd()if not driver_cmd:return None@@ -225,8 +219,8 @@ def cua_driver_update_check(*, timeout: Optional[float] = None) -> Optional[Dictreturn None if data is None or data.get("error") else datadef cua_driver_update_nudge() -> Optional[str]:- """One-line "an update is available" message, or ``None`` when up to date, indeterminate, or the driver- is too old to report."""+ """One-line "an update is available" message, or ``None`` when up to date, indeterminate, or the driver is too+ old to report."""state = _cb().cua_driver_update_check()if not state or not state.get("update_available"):return None