permissions.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. """Cross-platform Computer Use readiness + macOS permission helpers. "Ready to drive" differs per platform: macOS
  2. needs explicit TCC grants (Accessibility + Screen Recording) via cua-driver ``permissions status`` / ``permissions
  3. grant``; Windows/Linux have no TCC toggles, so readiness == driver health. The grants attach to cua-driver's OWN
  4. identity (``com.trycua.driver``), not Hermes, so ``grant`` launches CuaDriver via LaunchServices for correct dialog
  5. attribution. ``cua-driver doctor --json`` is the universal signal; ``computer_use_status`` folds it with the macOS
  6. detail into one payload for the desktop card, the ``permissions`` CLI and ``/api/tools/computer-use/status``."""
  7. from __future__ import annotations
  8. import json
  9. import os
  10. import subprocess
  11. import sys
  12. from contextlib import suppress
  13. from typing import Any, Dict, Optional
  14. from hermes_cli._subprocess_compat import windows_hide_flags
  15. _RUNTIME_PLATFORMS = frozenset({"darwin", "win32", "linux"}) # mirrors the toolset platform_gate
  16. _BOOLS = ("accessibility", "screen_recording", "screen_recording_capturable")
  17. CUA_DRIVER_BUNDLE_ID = "com.trycua.driver" # the only identity TCC rows and the private daemon are keyed to
  18. _TCC_SERVICES = {"accessibility": "Accessibility", "screen_recording": "ScreenCapture"} # status field -> tccutil service
  19. TCC_FIELDS = tuple(_TCC_SERVICES)
  20. def stale_tcc_grant_hint(*missing: str) -> str:
  21. """Recovery text for grants the daemon reports missing while System Settings shows the CuaDriver toggle ON.
  22. TCC keys each row to the app's code-signing requirement, so a row written for an earlier CuaDriver build can
  23. stop matching after a driver update: the toggle stays ON, the daemon is denied, and flipping the toggle does
  24. not rewrite the requirement (trycua/cua#3170). Only a reset + re-grant recovers it, so the hint names the
  25. exact rows for the *missing* status fields.
  26. """
  27. resets = " && ".join(f"tccutil reset {_TCC_SERVICES[f]} {CUA_DRIVER_BUNDLE_ID}" for f in missing if f in _TCC_SERVICES)
  28. if not resets:
  29. return ""
  30. return ("If System Settings already shows CuaDriver ON, the stored grant is stale (it no longer matches the installed "
  31. f"driver's signature): run `{resets}`, then `hermes computer-use permissions grant`.")
  32. def _child_env() -> dict[str, str]:
  33. """cua-driver child env (telemetry policy + provider secrets stripped); ``os.environ`` on import error.
  34. cua-driver is a third-party binary — it must never inherit provider API keys (#53503/#55709/#58889
  35. lineage). Each layer degrades gracefully so permission probes never break on a helper import error.
  36. """
  37. try:
  38. from tools.computer_use.cua_backend import sanitized_cua_driver_env
  39. return sanitized_cua_driver_env()
  40. except Exception:
  41. return dict(os.environ)
  42. def _run(binary: str, *args: str, timeout: float) -> subprocess.CompletedProcess:
  43. return subprocess.run([binary, *args], capture_output=True, text=True, encoding='utf-8', errors='replace',
  44. timeout=timeout, env=_child_env(), stdin=subprocess.DEVNULL, creationflags=windows_hide_flags(), check=False)
  45. def _json_out(binary: str, *args: str, timeout: float) -> Any:
  46. """Run ``binary args`` and parse stdout as JSON (``None`` on empty output)."""
  47. raw = (_run(binary, *args, timeout=timeout).stdout or "").strip()
  48. return json.loads(raw) if raw else None
  49. def _doctor(binary: str) -> Optional[dict[str, Any]]:
  50. """``cua-driver doctor --json`` → ``{ok, checks:[{label,status,message}]}`` (None on any failure)."""
  51. try:
  52. data = _json_out(binary, "doctor", "--json", timeout=12)
  53. except Exception:
  54. data = None
  55. if not isinstance(data, dict):
  56. return None
  57. checks = [{k: str(p.get(k, "")) for k in ("label", "status", "message")} for p in data.get("probes", []) if isinstance(p, dict)]
  58. return {"ok": bool(data.get("ok")), "checks": checks}
  59. def _mac_permissions(binary: str, out: dict[str, Any]) -> None:
  60. """Fold ``cua-driver permissions status --json`` booleans (+ ``source``) into ``out``."""
  61. try:
  62. data = _json_out(binary, "permissions", "status", "--json", timeout=10)
  63. except subprocess.TimeoutExpired:
  64. out["error"] = "cua-driver permissions status timed out"
  65. except Exception as exc: # spawn failure or malformed JSON
  66. out["error"] = f"cua-driver permissions status failed: {exc}"
  67. else:
  68. if isinstance(data, dict):
  69. out.update({k: data[k] for k in _BOOLS if isinstance(data.get(k), bool)})
  70. if isinstance(data.get("source"), dict):
  71. out["source"] = data["source"]
  72. def computer_use_status(driver_cmd: Optional[str] = None) -> dict[str, Any]:
  73. """OS-aware readiness for the desktop card; key order is an API payload contract. ``ready`` is the single signal the
  74. UI keys off: macOS = both TCC grants, elsewhere = driver health (no TCC model); ``None`` = unknown (binary missing /
  75. probe failed). ``can_grant`` is macOS-only."""
  76. from plugins.computer_use import DEFAULT_BACKEND, configured_backend_name, get_active_provider
  77. from tools.computer_use.cua_backend_driver import resolve_cua_driver_cmd # same resolver as the tool itself
  78. plat, name = sys.platform, configured_backend_name()
  79. binary = resolve_cua_driver_cmd(driver_cmd) if name == DEFAULT_BACKEND else None
  80. out: dict[str, Any] = {"platform": plat, "platform_supported": plat in _RUNTIME_PLATFORMS,
  81. "installed": bool(binary), "version": None, "ready": None, "can_grant": plat == "darwin",
  82. "checks": [], "source": None, "error": None, **{k: None for k in _BOOLS}}
  83. if name != DEFAULT_BACKEND: # another driver is selected: cua-driver probes and TCC grants do not apply
  84. out.update(platform_supported=True, can_grant=False)
  85. try:
  86. provider = get_active_provider()
  87. except LookupError as e:
  88. out["error"] = str(e)
  89. return out
  90. out.update(installed=True, version=f"{provider.display_name} (computer_use.backend: {provider.name})",
  91. ready=provider.is_available())
  92. return out
  93. if not binary:
  94. return out
  95. with suppress(Exception):
  96. out["version"] = (_run(binary, "--version", timeout=5).stdout or "").strip() or None
  97. doctor = _doctor(binary)
  98. if doctor is not None:
  99. out["checks"] = doctor["checks"]
  100. if plat == "darwin":
  101. _mac_permissions(binary, out)
  102. if out["error"] is None:
  103. out["ready"] = out["accessibility"] is True and out["screen_recording"] is True
  104. elif doctor is not None:
  105. out["ready"] = doctor["ok"] # no TCC model off macOS
  106. return out
  107. def request_permissions_grant(driver_cmd: Optional[str] = None) -> int:
  108. """Run ``cua-driver permissions grant`` (macOS), streaming its output. Returns the driver's exit code (0 ok), 2 if
  109. the binary is missing, 64 on a non-macOS platform (no TCC model to grant)."""
  110. if sys.platform != "darwin":
  111. print("Computer Use permissions are a macOS concept; nothing to grant here.")
  112. return 64
  113. from tools.computer_use.cua_backend_driver import resolve_cua_driver_cmd
  114. binary = resolve_cua_driver_cmd(driver_cmd)
  115. if not binary:
  116. print("cua-driver: not installed. Run: hermes computer-use install")
  117. return 2
  118. print("Requesting Accessibility + Screen Recording for CuaDriver.\n"
  119. f"macOS will show a dialog attributed to CuaDriver ({CUA_DRIVER_BUNDLE_ID}) — approve it, then return here.")
  120. try:
  121. return int(subprocess.run([binary, "permissions", "grant"], env=_child_env(), stdin=subprocess.DEVNULL, check=False).returncode)
  122. except KeyboardInterrupt: # pragma: no cover - interactive
  123. return 130
  124. except Exception as exc: # pragma: no cover - defensive
  125. print(f"cua-driver permissions grant failed: {exc}", file=sys.stderr)
  126. return 2