tools_config_cua.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. """PM-backed CUA setup and the host integration not supplied by its binary archive."""
  2. from __future__ import annotations
  3. import contextlib
  4. import os
  5. import shutil
  6. import subprocess
  7. import sys
  8. import time
  9. from typing import Optional
  10. from hermes_cli.cli_output import (
  11. print_info as _print_info, print_success as _print_success, print_warning as _print_warning)
  12. def _run_text(cmd: list, *, timeout, capture_output: bool = True,
  13. **kwargs) -> subprocess.CompletedProcess:
  14. """Run a text subprocess with consistent decoding."""
  15. return subprocess.run(cmd, capture_output=capture_output, text=True, encoding="utf-8", # noqa: PLW1510 -- forwarding wrapper: callers pass subprocess kwargs via **kwargs (check may arrive through it); an explicit check=False would raise TypeError
  16. errors="replace", timeout=timeout, **kwargs)
  17. def _fail(message: str, *hints: str) -> bool:
  18. _print_warning(message)
  19. for hint in hints:
  20. _print_info(hint)
  21. return False
  22. def _print_output_tail(result: subprocess.CompletedProcess, printer=None) -> None:
  23. for line in (result.stderr or result.stdout or "").strip().splitlines()[-3:]:
  24. (printer or _print_info)(f" {line[:200]}")
  25. def _post_setup_no_window_flags(*, streams_to_console: bool = False) -> int:
  26. """Hide Windows children unless their output is going to a real console."""
  27. from hermes_cli._subprocess_compat import windows_hide_flags
  28. flags = windows_hide_flags()
  29. try:
  30. if flags and streams_to_console and sys.stdout is not None and sys.stdout.isatty():
  31. return 0
  32. except Exception:
  33. pass
  34. return flags or 0
  35. def _cua_driver_cmd() -> str:
  36. return os.environ.get("HERMES_CUA_DRIVER_CMD", "").strip() or "cua-driver"
  37. def _cua_version_summary(raw: str, *, limit: int = 120) -> str:
  38. """Bound an external binary's potentially multiline version banner."""
  39. return next((line.strip()[:limit] for line in (raw or "").splitlines() if line.strip()), "")
  40. def _resolved_cua_driver_cmd() -> Optional[str]:
  41. from tools.computer_use.cua_backend_driver import resolve_cua_driver_cmd
  42. return resolve_cua_driver_cmd()
  43. def _cua_driver_env() -> dict:
  44. from tools.computer_use.cua_backend import sanitized_cua_driver_env
  45. return sanitized_cua_driver_env()
  46. _CUA_DRIVER_CONTRACT_CACHE: dict = {}
  47. def _cua_driver_contract_status(binary: Optional[str] = None) -> dict:
  48. """Cache the runtime manifest check by binary identity for UI polling."""
  49. from tools.computer_use.cua_backend_driver import cua_driver_runtime_contract_status
  50. resolved = binary or _resolved_cua_driver_cmd()
  51. if not resolved:
  52. return cua_driver_runtime_contract_status(None)
  53. try:
  54. stat = os.stat(resolved)
  55. fingerprint = (resolved, stat.st_mtime_ns, stat.st_size)
  56. except OSError:
  57. return cua_driver_runtime_contract_status(resolved)
  58. now = time.monotonic()
  59. cache = _CUA_DRIVER_CONTRACT_CACHE
  60. if cache.get("fingerprint") == fingerprint and now - cache.get("checked_at", 0.0) < 30.0:
  61. return dict(cache["state"])
  62. state = cua_driver_runtime_contract_status(resolved)
  63. cache.update(fingerprint=fingerprint, checked_at=now, state=dict(state))
  64. return state
  65. def _cua_driver_install_ready() -> bool:
  66. state = _cua_driver_contract_status()
  67. if not state.get("ready"):
  68. return False
  69. if sys.platform == "darwin":
  70. from tools.computer_use.cua_backend_daemon import _resolve_cua_driver_app_path
  71. return bool(_resolve_cua_driver_app_path(state["binary"]))
  72. # On-demand default (#97389): with computer_use.autostart off, a missing
  73. # cua-driver-serve logon task is intentional, not a repair condition —
  74. # requiring it here biased every enable flow toward registering it.
  75. return (sys.platform != "win32"
  76. or _cua_driver_autostart_registered_windows()
  77. or not _cua_autostart_opt_in())
  78. def install_cua_driver(upgrade: bool = False, show_installer_progress: bool = True) -> bool:
  79. """Prepare the PM pin and host setup for an explicit install/upgrade command.
  80. Both CLI modes reconcile the same pin; neither discovers a vendor release.
  81. A configured override is validated, never replaced or acquired by PM.
  82. Unattended callers should use PM ensure directly, without interactive host setup.
  83. """
  84. from pm import ensure
  85. override = os.environ.get("HERMES_CUA_DRIVER_CMD", "").strip()
  86. binary = _resolved_cua_driver_cmd()
  87. fresh_install = binary is None
  88. if override:
  89. if not binary:
  90. return _fail(f" HERMES_CUA_DRIVER_CMD does not resolve to an executable: {override}",
  91. " Fix or unset the override before running computer-use install.")
  92. else:
  93. if show_installer_progress:
  94. _print_info(" Preparing the pinned cua-driver with Hermes PM...")
  95. try:
  96. ensure("cua-driver", explicit=True)
  97. except Exception as exc:
  98. return _fail(f" cua-driver preparation failed: {exc}")
  99. binary = _resolved_cua_driver_cmd()
  100. if not binary:
  101. return _fail(" PM did not select a usable cua-driver executable.")
  102. _CUA_DRIVER_CONTRACT_CACHE.clear()
  103. contract = _cua_driver_contract_status(binary)
  104. if not contract.get("ready"):
  105. hint = (" Update the binary selected by HERMES_CUA_DRIVER_CMD, or unset the override."
  106. if override else " Run: hermes computer-use doctor")
  107. return _fail(" cua-driver runtime contract is unusable: "
  108. f"{contract.get('reason') or 'unknown error'}.", hint)
  109. if sys.platform == "win32" and not _repair_cua_driver_autostart_windows(
  110. binary, verbose=show_installer_progress):
  111. return _fail(" cua-driver is compatible, but Windows autostart setup failed.")
  112. if sys.platform == "darwin":
  113. from tools.computer_use.cua_backend_daemon import (
  114. _resolve_cua_driver_app_path, _validate_cua_driver_app_signature)
  115. app = _resolve_cua_driver_app_path(binary)
  116. if not app:
  117. return _fail(" macOS computer use requires the signed CuaDriver.app, not a bare binary.",
  118. " The PM cua-driver package must include its signed macOS app bundle.")
  119. try:
  120. _validate_cua_driver_app_signature(app)
  121. result = _run_text([
  122. "/System/Library/Frameworks/CoreServices.framework/Frameworks/"
  123. "LaunchServices.framework/Support/lsregister", "-f", app], timeout=15)
  124. except (RuntimeError, OSError, subprocess.SubprocessError) as exc:
  125. return _fail(f" cua-driver macOS app registration failed: {exc}")
  126. if result.returncode:
  127. _print_output_tail(result)
  128. return _fail(" cua-driver macOS app registration failed.")
  129. if show_installer_progress:
  130. _print_success(f" cua-driver ready: {contract.get('version') or 'unknown version'}.")
  131. _print_cua_platform_notes(sys.platform == "win32", sys.platform == "linux",
  132. fresh_install=fresh_install)
  133. return True
  134. def _ps_single_quote(value: str) -> str:
  135. return "'" + value.replace("'", "''") + "'"
  136. def _cua_driver_autostart_registered_windows(binary: Optional[str] = None) -> bool:
  137. """A task targeting a previous PM version is not a ready registration."""
  138. if sys.platform != "win32":
  139. return False
  140. from xml.etree import ElementTree
  141. binary = binary or _resolved_cua_driver_cmd()
  142. if not binary:
  143. return False
  144. try:
  145. result = subprocess.run(
  146. ["schtasks.exe", "/Query", "/TN", "cua-driver-serve", "/XML"],
  147. capture_output=True, timeout=10, creationflags=_post_setup_no_window_flags(), check=False)
  148. if result.returncode:
  149. return False
  150. # Parse bytes: schtasks' XML declaration carries the output encoding.
  151. task = ElementTree.fromstring(result.stdout)
  152. commands = task.findall(".//{*}Exec/{*}Command")
  153. return any(os.path.normcase((node.text or "").strip().strip('"')) == os.path.normcase(binary)
  154. for node in commands)
  155. except (OSError, subprocess.SubprocessError, ElementTree.ParseError):
  156. return False
  157. def _cua_autostart_opt_in() -> bool:
  158. """``computer_use.autostart`` — opt IN to the Windows per-boot ``cua-driver-serve`` logon
  159. task. The default (absent/False) is on-demand (#97389): Computer Use starts the driver per
  160. session exactly as macOS and Linux do, install/enable flows register no scheduled task, and
  161. a missing task is not a repair condition. True registers (or repairs) the logon task at
  162. install/enable time — needed when driving Windows over SSH (Session 0 has no interactive
  163. desktop). Unreadable config fails closed to the on-demand default."""
  164. with contextlib.suppress(Exception):
  165. from hermes_cli.config import load_config
  166. return bool(((load_config() or {}).get("computer_use") or {}).get("autostart", False))
  167. return False
  168. def _cua_autostart_registration_ps_command(binary: str) -> str:
  169. """PowerShell body for the elevated registration: Start-Process with a STRUCTURED
  170. ``-FilePath`` / ``-ArgumentList`` (older install.ps1 builds interpolated the binary path
  171. into a command string, which split at the first space) and ``-Verb RunAs -Wait -PassThru``
  172. so the exit code propagates."""
  173. return (f"$exe = {_ps_single_quote(binary)}; "
  174. "$proc = Start-Process -FilePath $exe -ArgumentList @('autostart','enable') "
  175. "-Verb RunAs -Wait -PassThru -ErrorAction Stop; exit $proc.ExitCode")
  176. def _repair_cua_driver_autostart_windows(driver_cmd: str, *, verbose: bool) -> bool:
  177. """Register autostart using structured arguments, including paths with spaces.
  178. Only registers when the user opted into the per-boot task via
  179. ``computer_use.autostart`` (#97389): the on-demand default registers
  180. nothing, silently — returning True (nothing to repair) keeps callers from
  181. printing "auto-start was not registered" warnings for an intentional
  182. absence."""
  183. if sys.platform != "win32":
  184. return True
  185. if not _cua_autostart_opt_in():
  186. # On-demand default (#97389): the per-boot cua-driver-serve task is opt-in
  187. # via computer_use.autostart. Registering here would recreate, on every
  188. # enable/install, exactly the silent boot-time task the issue reports.
  189. return True
  190. binary = shutil.which(driver_cmd)
  191. if not binary:
  192. return False
  193. if _cua_driver_autostart_registered_windows(binary):
  194. return True
  195. ps = shutil.which("powershell") or shutil.which("powershell.exe") or "powershell"
  196. ps_cmd = _cua_autostart_registration_ps_command(binary)
  197. _print_info(" Registering cua-driver auto-start..." if verbose
  198. else " Repairing cua-driver auto-start registration...")
  199. try:
  200. result = _run_text([ps, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
  201. "-Command", ps_cmd],
  202. timeout=300, env=_cua_driver_env(),
  203. creationflags=_post_setup_no_window_flags())
  204. except subprocess.TimeoutExpired:
  205. return _fail(" cua-driver autostart registration timed out.")
  206. except Exception as exc:
  207. return _fail(f" cua-driver autostart registration failed: {exc}")
  208. if result.returncode == 0:
  209. return _cua_driver_autostart_registered_windows(binary)
  210. _print_warning(" cua-driver autostart registration failed.")
  211. _print_output_tail(result)
  212. _print_info(f" From an elevated shell, run: & {_ps_single_quote(binary)} autostart enable")
  213. return False
  214. def _print_cua_platform_notes(is_windows: bool, is_linux: bool, *, fresh_install: bool) -> None:
  215. if is_windows:
  216. _print_info(" cua-driver may spawn a UIAccess worker (cua-driver-uia.exe);")
  217. _print_info(" Windows/SmartScreen may prompt the first time it runs.")
  218. elif is_linux:
  219. _print_warning(" Linux support is alpha.")
  220. else:
  221. _print_info(" IMPORTANT — grant macOS permissions now:" if fresh_install
  222. else " Grant macOS permissions if not done yet:")
  223. _print_info(" System Settings > Privacy & Security > Accessibility")
  224. _print_info(" System Settings > Privacy & Security > Screen Recording")
  225. _print_info(" Allow CuaDriver.app; run `hermes computer-use permissions grant` for guidance.")