doctor.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. """`hermes computer-use doctor` — thin client for cua-driver's `health_report` MCP tool. cua-driver owns the health
  2. model; we drive the stdio JSON-RPC handshake, call `health_report` and render the stable ``schema_version="1"``
  3. payload. cua-driver 0.10.x marks `health_report` risk-unclassified (isError=true, structuredContent
  4. ``{"exit_code": 1}``) — we detect that and synthesize a composite report from working probes (check_permissions,
  5. list_apps, CLI --version). Exit codes: 0 overall=="ok"; 1 degraded/failed; 2 binary missing / protocol error."""
  6. from __future__ import annotations
  7. import json
  8. import os
  9. import platform as _platform_mod
  10. import re
  11. import subprocess
  12. import sys
  13. from contextlib import contextmanager, suppress
  14. from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Tuple, Union
  15. from hermes_cli._subprocess_compat import windows_hide_flags
  16. from tools.computer_use.permissions import _child_env as _sanitized_cua_env
  17. from tools.computer_use.permissions import stale_tcc_grant_hint
  18. # Match the ALLOWED_STATUS_VALUES + ALLOWED_OVERALL_VALUES the cua-driver integration test pins.
  19. _STATUS_GLYPH = {"pass": "✅", "fail": "❌", "skip": "⏭️"}
  20. _OVERALL_GLYPH = {"ok": "✅", "degraded": "⚠️", "failed": "❌"}
  21. _SUPPORTED_PLATFORMS = ("darwin", "linux", "windows")
  22. _TCC_HINT = "Grant {} to CuaDriver in System Settings → Privacy & Security."
  23. _ZERO_DISPLAY_MSG = "ScreenCaptureKit reachable but 0 shareable display(s) — every capture will return 0x0."
  24. _ZERO_DISPLAY_HINT = ("Wake the built-in display, connect a monitor or HDMI dummy dongle (e.g. Headless Ghost), or enable "
  25. "a virtual display (Screen Sharing/VNC, BetterDisplay). Verify with `system_profiler SPDisplaysDataType`.")
  26. _IO_EXC = (OSError, subprocess.TimeoutExpired)
  27. _PRUNED_UNIT_MSG = "Exec targets {target} which no longer exists — a cua-driver upgrade pruned that release directory"
  28. _PRUNED_UNIT_HINT = ("Point the {kind} at ~/.cua-driver/packages/current/cua-driver — `current` survives upgrades; "
  29. "versioned packages/releases/<version>/ dirs are pruned (only the last 5 are kept)")
  30. _DEAD_DAEMON_MSG = ("{unit} is configured to run `cua-driver serve` but no daemon is listening on {socket} — "
  31. "the unit is not running (crash loop, stopped, or never started)")
  32. _DEAD_DAEMON_HINT = ("Check `systemctl --user status {unit}` / `journalctl --user -u {unit}`; a driver reinstall does not "
  33. "start the daemon and cannot fix a broken unit")
  34. Report = dict[str, Any]
  35. _Row = tuple[str, str, Report] # (status, message, extra {hint?, data?}) for one check
  36. class HealthReportUnavailable(RuntimeError):
  37. """health_report denied or non-schema payload — ``run_doctor`` falls back to probes."""
  38. def _run_cli(binary: str, *args: str, timeout: float) -> subprocess.CompletedProcess:
  39. """Run ``<binary> args`` with UTF-8 capture + sanitized env (raises on failure)."""
  40. return subprocess.run([binary, *args], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout,
  41. env=_sanitized_cua_env(), stdin=subprocess.DEVNULL, check=False)
  42. def _cli_text(binary: str, *args: str, timeout: float, exc_types: tuple[type, ...] = _IO_EXC) -> subprocess.CompletedProcess | BaseException:
  43. """``_run_cli`` that returns (not raises) any exception in *exc_types*."""
  44. try:
  45. return _run_cli(binary, *args, timeout=timeout)
  46. except exc_types as e:
  47. return e
  48. def _combined_output(completed: subprocess.CompletedProcess) -> str:
  49. return ((completed.stdout or "") + (completed.stderr or "")).strip()
  50. def _first_line(text: str) -> Optional[str]:
  51. return text.strip().splitlines()[0].strip() if text.strip() else None
  52. def _read_cli_version(binary: str, *, timeout: float = 5.0) -> Optional[str]:
  53. """First line of ``--version`` or None; health_report's ``driver_version`` can disagree (seen on Windows)."""
  54. cp = _cli_text(binary, "--version", timeout=timeout, exc_types=_IO_EXC + (ValueError, TypeError))
  55. return None if isinstance(cp, BaseException) else _first_line(cp.stdout or cp.stderr or "")
  56. def _cli_driver_version(binary: str, timeout: float = 5.0) -> tuple[str, Optional[str]]:
  57. """(status, version_or_message) from ``cua-driver --version``."""
  58. cp = _cli_text(binary, "--version", timeout=timeout)
  59. if isinstance(cp, BaseException):
  60. return "fail", f"--version failed: {cp}"
  61. text, failed = _combined_output(cp), cp.returncode != 0
  62. if failed and not text:
  63. return "fail", f"--version exited {cp.returncode}"
  64. m = re.search(r"(\d+\.\d+\.\d+(?:[-+][\w.]+)?)", text) # typical: "cua-driver 0.10.0"
  65. return ("fail" if failed else "pass"), m.group(1) if m else (_first_line(text) or "unknown")
  66. def _cli_doctor_snippet(binary: str, timeout: float = 8.0) -> Optional[str]:
  67. """Optional one-shot ``cua-driver doctor`` text (best-effort, never fatal)."""
  68. cp = _cli_text(binary, "doctor", timeout=timeout)
  69. return None if isinstance(cp, BaseException) else (_combined_output(cp) or None)
  70. def _build_identity(binary: str, report: Report) -> Report:
  71. """Hermes-side identity block comparing resolved binary vs health_report."""
  72. def token(text: str) -> str: # dotted version-ish token out of a free-form string
  73. m = text and re.search(r"(\d+\.\d+(?:\.\d+)?(?:[-+][\w.]+)?)", text)
  74. return m.group(1) if m else text.strip().lower()
  75. cli, report_v = _read_cli_version(binary) or "", str(report.get("driver_version") or "")
  76. return {"resolved_binary": binary, "cli_version": cli or None, "health_report_driver_version": report_v or None,
  77. "version_mismatch": bool(token(cli) and token(report_v) and token(cli) != token(report_v))}
  78. def _is_valid_health_report(payload: Any) -> bool: # looks like a schema_version=1 health_report
  79. return isinstance(payload, dict) and {"schema_version", "overall"} <= payload.keys() and isinstance(payload.get("checks"), list)
  80. def _text_items(result: Report) -> Iterator[str]: # text of every {"type": "text"} content item
  81. return (i.get("text") or "" for i in result.get("content") or [] if isinstance(i, dict) and i.get("type") == "text")
  82. def _first_text(result: Report, default: str) -> str:
  83. return next((t.strip() for t in _text_items(result) if t.strip()), default)
  84. def _extract_health_report_from_result(result: Report) -> Report:
  85. """Report from a tools/call result. ``HealthReportUnavailable`` when the tool denied the call (isError) or the
  86. payload is not a real report (0.10's ``{"exit_code": 1}``); ``RuntimeError`` when it carries no content."""
  87. if result.get("isError") is True:
  88. raise HealthReportUnavailable(_first_text(result, "health_report returned isError=true"))
  89. sc = result.get("structuredContent")
  90. if _is_valid_health_report(sc):
  91. return sc # type: ignore[return-value]
  92. for text in _text_items(result): # older builds: JSON text block with schema_version
  93. with suppress(ValueError, TypeError):
  94. if _is_valid_health_report(parsed := json.loads(text)):
  95. return parsed
  96. if isinstance(sc, dict): # present but not a real report — unavailable, not fatal
  97. raise HealthReportUnavailable(f"health_report structuredContent lacks schema_version/overall/checks (keys={sorted(sc.keys())})")
  98. raise RuntimeError(f"health_report response carried neither structuredContent nor a parseable JSON text block. Result keys: {list(result.keys())}")
  99. def _open_mcp(binary: str) -> subprocess.Popen:
  100. """Spawn ``<binary> mcp``; pin UTF-8 — cua-driver emits emoji/arbitrary paths and Windows' cp1252 would raise."""
  101. return subprocess.Popen([binary, "mcp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  102. text=True, encoding="utf-8", errors="replace", bufsize=1, creationflags=windows_hide_flags(),
  103. env=_sanitized_cua_env())
  104. def _mcp_rpc(proc: subprocess.Popen, msg_id: int, method: str, params: Any = None) -> Report:
  105. """Write one JSON-RPC request and read one response line."""
  106. payload: Report = {"jsonrpc": "2.0", "id": msg_id, "method": method, **({"params": params} if params is not None else {})}
  107. proc.stdin.write(json.dumps(payload) + "\n")
  108. proc.stdin.flush()
  109. line = proc.stdout.readline()
  110. if not line:
  111. tail: list[str] = []
  112. with suppress(Exception): # last 3 stderr lines, best-effort
  113. tail = [str(x) for x in (proc.stderr.read() or "").strip().splitlines()[-3:]]
  114. raise RuntimeError(f"cua-driver mcp produced no response for {method!r}. stderr tail: {tail or '(empty)'}")
  115. try:
  116. resp = json.loads(line)
  117. except (ValueError, TypeError) as e:
  118. raise RuntimeError(f"{method} response was not valid JSON: {e}\nraw: {line[:200]}")
  119. if "error" in resp:
  120. raise RuntimeError(f"{method} JSON-RPC error: {resp['error']}")
  121. return resp
  122. def _call_tool(proc: subprocess.Popen, msg_id: int, name: str, arguments: Any = None) -> Any:
  123. """tools/call *name* → raw ``result`` value (``{}`` when absent)."""
  124. return _mcp_rpc(proc, msg_id, "tools/call", {"name": name, "arguments": arguments or {}}).get("result") or {}
  125. @contextmanager
  126. def _mcp_session(binary: str, timeout: float) -> Iterator[subprocess.Popen]:
  127. """Spawn ``<binary> mcp`` and always close stdin / wait / kill it on exit."""
  128. proc = _open_mcp(binary)
  129. try:
  130. yield proc
  131. finally:
  132. with suppress(Exception):
  133. proc.stdin.close()
  134. try:
  135. proc.wait(timeout=timeout)
  136. except subprocess.TimeoutExpired:
  137. proc.kill()
  138. proc.wait()
  139. def _drive_health_report(binary: str, *, include: Sequence[str] = (), skip: Sequence[str] = (), timeout: float = 12.0) -> Report:
  140. """Handshake + `health_report` → report; HealthReportUnavailable (caller falls back) or RuntimeError."""
  141. args = {k: list(v) for k, v in (("include", include), ("skip", skip)) if v}
  142. with _mcp_session(binary, timeout) as proc:
  143. _mcp_rpc(proc, 1, "initialize", {})
  144. result = _call_tool(proc, 2, "health_report", args)
  145. if not isinstance(result, dict):
  146. raise RuntimeError(f"health_report result was not an object: {type(result).__name__}")
  147. return _extract_health_report_from_result(result)
  148. def _structured(result: Report) -> Report:
  149. return result["structuredContent"] if isinstance(result.get("structuredContent"), dict) else {}
  150. def _probe_tool(proc: subprocess.Popen, msg_id: int, name: str) -> tuple[Optional[Report], Optional[str]]:
  151. """``(result, None)`` on success; ``(None, error_text)`` on isError or RPC failure."""
  152. try:
  153. result = _call_tool(proc, msg_id, name)
  154. except RuntimeError as e:
  155. return None, str(e)
  156. return (None, _first_text(result, f"{name} isError")) if result.get("isError") is True else (result, None)
  157. def _drive_fallback_probes(binary: str, *, timeout: float = 12.0) -> Report:
  158. """One MCP session: initialize serverInfo version + check_permissions + list_apps probe results."""
  159. out: Report = dict.fromkeys(("init_version", "permissions", "permissions_error", "list_apps_ok", "list_apps_error", "list_apps_count"))
  160. with _mcp_session(binary, timeout) as proc:
  161. server_info = (_mcp_rpc(proc, 1, "initialize", {}).get("result") or {}).get("serverInfo") or {}
  162. out["init_version"] = server_info.get("version") if isinstance(server_info, dict) else None
  163. perms, out["permissions_error"] = _probe_tool(proc, 2, "check_permissions") # primary TCC signal on 0.10
  164. out["permissions"] = _structured(perms) if perms is not None else None
  165. # list_apps — light AX capability probe; text-only success still counts as AX working
  166. apps, out["list_apps_error"] = _probe_tool(proc, 3, "list_apps")
  167. out["list_apps_ok"] = apps is not None
  168. app_list = _structured(apps).get("apps") if apps is not None else None
  169. out["list_apps_count"] = len(app_list) if isinstance(app_list, list) else None
  170. return out
  171. def _platform_name() -> str:
  172. return (_platform_mod.system() or "").lower() or "unknown"
  173. def _tcc_row(field: str, label: str, platform_bound: bool, ctx: Report) -> _Row:
  174. """tcc_* row for one check_permissions boolean *field* (Accessibility / Screen Recording)."""
  175. perms, err = ctx["perms"], ctx["perm_err"]
  176. if perms is None:
  177. return ("fail" if err else "skip"), err or "check_permissions unavailable", {}
  178. granted = perms.get(field)
  179. if not isinstance(granted, bool): # only real booleans select a branch; anything else is "absent"
  180. off_platform = platform_bound and ctx["plat"] != "darwin"
  181. return "skip", f"not applicable on {ctx['plat']}" if off_platform else f"{field} field absent from check_permissions", {}
  182. if not granted:
  183. return "fail", f"{label} is not granted.", {"hint": _TCC_HINT.format(label), "data": {field: False}}
  184. data = {field: True, **({"screen_recording_capturable": perms.get("screen_recording_capturable")} if field == "screen_recording" else {})}
  185. if data.get("screen_recording_capturable") is False: # the granted-but-not-capturable row wins over plain pass
  186. return "fail", "Screen Recording granted but not capturable.", {"hint": (
  187. "Screen Recording permission may need a restart of CuaDriver or a re-grant in System Settings."), "data": data}
  188. return "pass", f"{label} is granted.", {"data": data}
  189. def _ax_capability_row(ctx: Report) -> _Row:
  190. """ax_capability — inferred from list_apps success or the accessibility grant."""
  191. probes, ax_granted = ctx["probes"], ctx["ax_granted"]
  192. list_ok, list_count = probes.get("list_apps_ok"), probes.get("list_apps_count")
  193. if list_ok is True:
  194. return "pass", "list_apps succeeded" + (f" ({list_count} apps)" if isinstance(list_count, int) else ""), {}
  195. if list_ok is False:
  196. return "fail", probes.get("list_apps_error") or ("list_apps failed" + (" despite accessibility grant" if ax_granted else "")), {}
  197. return ("pass", "inferred from accessibility grant (list_apps not probed)", {}) if ax_granted else ("skip", "not probed", {})
  198. def _cli_doctor_row(txt: Optional[str]) -> Optional[_Row]:
  199. return None if not txt else (("pass" if "[ok" in txt.lower() or "ok ]" in txt else "skip"), txt.splitlines()[0].strip(),
  200. {"data": {"snippet": txt[:2000]}})
  201. # Fallback composite probe table, in emitted order: (check name, row builder(ctx) -> _Row | None to omit).
  202. _FALLBACK_PROBES: tuple[tuple[str, Callable[[Report], Optional[_Row]]], ...] = (
  203. ("binary_version", lambda c: (c["ver_status"], c["ver_msg"], {})),
  204. ("platform_supported", lambda c: ("pass", f"platform={c['plat']}", {}) if c["plat"] in _SUPPORTED_PLATFORMS else ("fail", f"platform={c['plat']} (unsupported)", {})),
  205. # doctor does not start a session, so session_active is never probed
  206. ("session_active", lambda c: ("skip", "not probed (doctor does not open a cua session)", {})),
  207. ("tcc_accessibility", lambda c: _tcc_row("accessibility", "Accessibility", False, c)),
  208. ("tcc_screen_recording", lambda c: _tcc_row("screen_recording", "Screen Recording", True, c)),
  209. ("ax_capability", _ax_capability_row),
  210. ("health_report_path", lambda c: ("skip", "fallback composite (cua-driver 0.10 unclassified health_report); "
  211. f"cause: {c['reason_short']}", {})),
  212. ("cli_doctor", lambda c: _cli_doctor_row(c["doctor_txt"])),
  213. )
  214. def _overall_from(checks: list[Report]) -> str:
  215. """failed if binary missing/bad; ok if accessibility fine and nothing failed; else degraded."""
  216. by_name = {c.get("name"): c.get("status") for c in checks}
  217. if by_name.get("binary_version") != "pass":
  218. return "failed"
  219. ok = by_name.get("tcc_accessibility") in ("pass", "skip", None) and not any(c.get("status") == "fail" for c in checks)
  220. return "ok" if ok else "degraded"
  221. def _compose_fallback_report(binary: str, *, reason: str = "", timeout: float = 12.0) -> Report:
  222. """schema_version=1 report from CLI + MCP probes (``_FALLBACK_PROBES``) when health_report is denied (0.10)."""
  223. plat = _platform_name()
  224. ver_status, ver_value = _cli_driver_version(binary)
  225. probes = _drive_fallback_probes(binary, timeout=timeout)
  226. if probes.get("init_version"): # MCP initialize version beats a messy CLI parse
  227. ver_status, ver_value = "pass", str(probes["init_version"])
  228. perms = probes.get("permissions") if isinstance(probes.get("permissions"), dict) else None
  229. reason_short = (reason or "health_report unavailable").strip()
  230. reason_short = reason_short if len(reason_short) <= 160 else reason_short[:157] + "..."
  231. ctx: Report = {"plat": plat, "ver_status": ver_status, "probes": probes, "perms": perms,
  232. "perm_err": probes.get("permissions_error"), "reason_short": reason_short,
  233. "ver_msg": f"cua-driver {ver_value}" if ver_status == "pass" else (ver_value or "version unknown"),
  234. "ax_granted": bool(perms and perms.get("accessibility") is True),
  235. "doctor_txt": _cli_doctor_snippet(binary)} # optional CLI doctor text (best-effort)
  236. checks = [{"name": name, "status": row[0], "message": row[1], **row[2]} # hint/data only when present
  237. for name, build in _FALLBACK_PROBES if (row := build(ctx)) is not None]
  238. return {"schema_version": "1", "platform": plat,
  239. "driver_version": str(ver_value if ver_status == "pass" else (ver_value or "?")),
  240. "overall": _overall_from(checks), "checks": checks,
  241. "fallback": True, "fallback_reason": reason or "health_report unavailable"}
  242. _TCC_CHECK_FIELDS = {"tcc_accessibility": "accessibility", "tcc_screen_recording": "screen_recording"}
  243. def _apply_stale_tcc_guard(report: Report) -> Report:
  244. """Append the stale-row recovery to every failed ``tcc_*`` check. Applied at the report seam so the driver's
  245. own health_report rows (0.22+) get it too, not only the 0.10 fallback probes — the users hit by a stale row
  246. are on current drivers (trycua/cua#3170)."""
  247. checks = report.get("checks")
  248. for check in (c for c in (checks if isinstance(checks, list) else ()) if isinstance(c, dict)):
  249. field = _TCC_CHECK_FIELDS.get(check.get("name"))
  250. if field and check.get("status") == "fail":
  251. check["hint"] = f"{check.get('hint') or ''} {stale_tcc_grant_hint(field)}".strip()
  252. return report
  253. def _apply_display_count_guard(report: Report) -> Report:
  254. """Fail an 'ok' screen_capture_capability with ``display_count=0``: macOS ScreenCaptureKit reports 0 on headless
  255. / asleep panels — TCC fine, health_report ok, yet every capture is 0x0. Turns a silent failure actionable; applied
  256. at the report seam so the real and the fallback path both get it.
  257. Composed from PR #52949 (sujeet111) and PR #67259 (webtecnica).
  258. """
  259. checks = report.get("checks")
  260. for check in (c for c in (checks if isinstance(checks, list) else ()) if isinstance(c, dict) and c.get("name") == "screen_capture_capability"):
  261. data = check.get("data")
  262. if (data.get("display_count") if isinstance(data, dict) else None) == 0 and check.get("status") == "pass":
  263. check.update(status="fail", message=_ZERO_DISPLAY_MSG, hint=_ZERO_DISPLAY_HINT)
  264. if report.get("overall") == "ok":
  265. report["overall"] = "degraded"
  266. return report
  267. def cua_daemon_units(config_dir: Optional[str] = None) -> list[tuple[str, str, str, bool, Optional[str]]]:
  268. """(kind, unit, exec_target, runs_serve, --socket path or None) for every systemd user unit / XDG autostart
  269. entry whose Exec runs cua-driver — the hand-written daemon units Linux relies on (there is no managed
  270. autostart). ``%h`` is expanded in the socket path so it can be probed; the exec target is left as written."""
  271. home = os.path.expanduser("~")
  272. # systemd --user and XDG autostart both honour $XDG_CONFIG_HOME; a host that sets it keeps its units there.
  273. base = config_dir or os.environ.get("XDG_CONFIG_HOME") or os.path.join(home, ".config")
  274. units: list[tuple[str, str, str, bool, Optional[str]]] = []
  275. sources = (("systemd user unit", os.path.join(base, "systemd", "user"), ".service", "ExecStart"),
  276. ("XDG autostart entry", os.path.join(base, "autostart"), ".desktop", "Exec"))
  277. for kind, directory, suffix, key in sources:
  278. try:
  279. names = sorted(e.name for e in os.scandir(directory) if e.name.endswith(suffix) and e.is_file())
  280. except OSError:
  281. continue
  282. for name in names:
  283. try:
  284. with open(os.path.join(directory, name), encoding="utf-8-sig", errors="replace") as fh:
  285. text = fh.read()
  286. except OSError:
  287. continue
  288. for line in text.splitlines():
  289. stripped = line.strip()
  290. tokens = stripped.split("=", 1)[1].split() if stripped.startswith(key + "=") else []
  291. # first token = executable; systemd's prefix modifiers (-, +, !, :) never start a path
  292. if not tokens or "cua-driver" not in tokens[0]:
  293. continue
  294. socket = next((tokens[i + 1] for i, t in enumerate(tokens[:-1]) if t == "--socket"), None)
  295. units.append((kind, name, tokens[0].lstrip("-+:!"), "serve" in tokens[1:],
  296. os.path.expanduser(socket.replace("%h", home)) if socket else None))
  297. return units
  298. def _stale_cua_exec_references(config_dir: Optional[str] = None) -> list[tuple[str, str, str]]:
  299. """(kind, unit, target) for daemon units whose cua-driver Exec points at a pruned ``packages/releases/<version>/``
  300. directory. The installer prunes all but the last five, so a versioned reference crash-loops with 203/EXEC after
  301. every upgrade while every binary-level check stays green (#114748). ``packages/current`` and still-present
  302. release dirs are healthy by construction and never reported."""
  303. home = os.path.expanduser("~")
  304. findings: list[tuple[str, str, str]] = []
  305. for kind, unit, target, _serve, _socket in cua_daemon_units(config_dir):
  306. resolved = os.path.expanduser(target.replace("%h", home))
  307. if "/packages/releases/" in resolved and not os.path.exists(resolved):
  308. findings.append((kind, unit, target))
  309. return findings
  310. def _apply_daemon_liveness_guard(report: Report, binary: str) -> Report:
  311. """Append one check per configured daemon unit whose ``cua-driver serve`` is not answering on its socket
  312. (pass when it is). Only configured daemons are probed: on Linux the MCP runtime needs no daemon, so an
  313. unconfigured, silent socket is not a finding. Unknown probe results add nothing (#114748)."""
  314. from tools.computer_use.cua_backend import cua_daemon_listening
  315. checks = report.get("checks")
  316. if sys.platform != "linux" or not isinstance(checks, list):
  317. return report
  318. for _kind, unit, _target, serve, socket in cua_daemon_units():
  319. listening = cua_daemon_listening(binary, socket) if serve else None
  320. if listening is None:
  321. continue
  322. shown = socket or "the default socket"
  323. if listening:
  324. checks.append({"name": f"daemon ({unit})", "status": "pass", "message": f"cua-driver serve is listening on {shown}"})
  325. continue
  326. checks.append({"name": f"daemon ({unit})", "status": "fail", "message": _DEAD_DAEMON_MSG.format(unit=unit, socket=shown),
  327. "hint": _DEAD_DAEMON_HINT.format(unit=unit)})
  328. if report.get("overall") == "ok":
  329. report["overall"] = "degraded"
  330. return report
  331. def _apply_stale_unit_guard(report: Report) -> Report:
  332. """Append a fail check per hand-written unit/autostart entry whose cua-driver Exec target was pruned — the
  333. daemon can crash-loop (203/EXEC) for days while every binary-level check stays green (#114748). Binary-level
  334. repair (`install`) cannot fix a stale unit reference, so doctor is the only surface that can name it."""
  335. for kind, unit, target in _stale_cua_exec_references() if sys.platform == "linux" else ():
  336. checks = report.get("checks")
  337. if isinstance(checks, list):
  338. checks.append({"name": f"daemon unit ({unit})", "status": "fail",
  339. "message": _PRUNED_UNIT_MSG.format(target=target),
  340. "hint": _PRUNED_UNIT_HINT.format(kind=kind)})
  341. if report.get("overall") == "ok": # fail-worse overalls are never softened
  342. report["overall"] = "degraded"
  343. return report
  344. def _wayland_environment_context(report: Report) -> Optional[Report]:
  345. """Linux+Wayland only: doctor probes the CLI process's environment, not the gateway's."""
  346. if report.get("platform") != "linux" or not os.environ.get("WAYLAND_DISPLAY"):
  347. return None
  348. return {"scope": "cli_process", "gateway_environment_checked": False}
  349. def _print_text_report(report: Report, color: bool, *, identity: Optional[Report] = None,
  350. environment: Optional[Report] = None) -> None:
  351. """Render like `cua-driver call health_report`: header (CLI --version preferred over health_report's stale
  352. ``driver_version``), identity block, environment note, one line per check + indented hint/``data`` rows
  353. (support staff need them)."""
  354. platform, report_v, overall = (report.get(k, "?") for k in ("platform", "driver_version", "overall"))
  355. identity = identity or {}
  356. cli_v = identity.get("cli_version") or ""
  357. header_v = cli_v or report_v # binary's own --version wins when health_report is stale
  358. # No external color library — inline ANSI keeps doctor self-contained; colors only for known overall values.
  359. red, yellow, green, reset, dim = ("\033[31m", "\033[33m", "\033[32m", "\033[0m", "\033[2m") if color and overall in _OVERALL_GLYPH else ("",) * 5
  360. col_for = {"failed": red, "degraded": yellow, "ok": green}.get(overall, "")
  361. status_cols = {"pass": green, "fail": red, "skip": dim}
  362. lines = [f"{_OVERALL_GLYPH.get(overall, '•')} cua-driver {header_v} on {platform} — {col_for}{overall}{reset}"]
  363. if identity.get("resolved_binary"):
  364. lines.append(f" {dim}binary: {identity['resolved_binary']}{reset}")
  365. if cli_v and report_v and str(report_v) not in str(cli_v) and str(cli_v) not in str(report_v): # clearly differ
  366. lines += [f" {dim}--version: {cli_v}{reset}", f" {dim}health_report.driver_version: {report_v}{reset}"]
  367. if environment:
  368. lines += [f" {dim}environment: current CLI process{reset}",
  369. f" {dim}gateway environment was not checked; active gateway computer_use sessions use that process environment{reset}"]
  370. if identity.get("version_mismatch"):
  371. lines += [f" {yellow}⚠️ version mismatch: health_report says {report_v!r} but binary --version is {cli_v!r}{reset}",
  372. f" {dim}→ trust --version / packages/current for debugging; health_report's binary_version check can lag on Windows{reset}"]
  373. for check in report.get("checks", []):
  374. status = check.get("status", "?")
  375. lines.append(f" {_STATUS_GLYPH.get(status, '•')} {status_cols.get(status, '')}{check.get('name', '?')}{reset}: {check.get('message') or ''}")
  376. if check.get("hint"):
  377. lines.append(f" → {dim}{check['hint']}{reset}")
  378. data = check.get("data")
  379. for key, value in (data.items() if isinstance(data, dict) else ()):
  380. lines.append(f" {dim}{key}={json.dumps(value) if isinstance(value, (dict, list)) else value}{reset}")
  381. print("\n".join(lines))
  382. def run_doctor(driver_cmd: Optional[str] = None, *, include: Sequence[str] = (), skip: Sequence[str] = (), json_output: bool = False,
  383. color: Optional[bool] = None) -> int:
  384. """Resolve the binary via the shared runtime resolver (diagnose what `computer_use` actually invokes), call
  385. `health_report`, render; on 0.10.x (denied) a report is synthesized from probes."""
  386. # Windows' locale codec (cp1252, cp936, ...) cannot encode the ✅ ❌ ⚠️ ⏭️ glyphs — force UTF-8.
  387. for stream in (sys.stdout, sys.stderr):
  388. with suppress(AttributeError, OSError):
  389. stream.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]
  390. from tools.computer_use.cua_backend_driver import resolve_cua_driver_cmd
  391. binary = resolve_cua_driver_cmd(driver_cmd)
  392. if not binary:
  393. print(f"cua-driver: not installed (looked for {driver_cmd or 'cua-driver (PATH and canonical install paths)'!r}).\n Run: hermes computer-use install")
  394. return 2
  395. try: # prefer real health_report; on denial/non-schema, synthesize via probes
  396. try:
  397. report = _drive_health_report(binary, include=include, skip=skip, timeout=12.0)
  398. except HealthReportUnavailable as e:
  399. report = _compose_fallback_report(binary, reason=str(e), timeout=12.0)
  400. except OSError as e:
  401. # The spawn itself failed (Windows: a venv interpreter denied `CreateProcess` on a binary under
  402. # `C:\Program Files\WindowsApps`, WinError 5). A traceback here hides the one fact the user needs.
  403. print(f"cua-driver could not be started from {binary!r}: {e}\n"
  404. " The Hermes runtime interpreter cannot execute this binary; the tool may still work because the\n"
  405. " shell resolves a different copy on PATH. Fix: install cua-driver outside the protected directory\n"
  406. " (e.g. the upstream installer's default under your user profile) or point HERMES_CUA_DRIVER_CMD at\n"
  407. " a copy the runtime can execute, then re-run `hermes computer-use doctor`.", file=sys.stderr)
  408. return 2
  409. except RuntimeError as e:
  410. print(f"cua-driver health_report failed: {e}", file=sys.stderr)
  411. return 2
  412. report = _apply_display_count_guard(report)
  413. report = _apply_stale_tcc_guard(report)
  414. report = _apply_stale_unit_guard(report)
  415. report = _apply_daemon_liveness_guard(report, binary)
  416. identity = _build_identity(binary, report)
  417. environment = _wayland_environment_context(report)
  418. if json_output:
  419. # Additive envelope: upstream keys preserved, identity under hermes_identity (and environment under
  420. # hermes_environment when present) so overall/checks parsers keep working.
  421. payload = {**report, "hermes_identity": identity}
  422. if environment:
  423. payload["hermes_environment"] = environment
  424. json.dump(payload, sys.stdout, indent=2, sort_keys=True)
  425. sys.stdout.write("\n")
  426. else:
  427. _print_text_report(report, color=sys.stdout.isatty() if color is None else bool(color), identity=identity,
  428. environment=environment)
  429. return 0 if report.get("overall") == "ok" else 1 # unknown/missing overall must not look like success