cua_backend_daemon.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. """Private embedded cua-driver daemon for non-standard permission modes, plus the macOS CuaDriver.app identity
  2. checks its launch path depends on. Config/policy helpers are looked up lazily through the facade."""
  3. from __future__ import annotations
  4. import contextlib
  5. import logging
  6. import os
  7. import shutil
  8. import subprocess
  9. import sys
  10. import tempfile
  11. import threading
  12. import time
  13. import uuid
  14. from collections import deque
  15. from typing import Any, Dict, List, Optional, Tuple
  16. from tools.computer_use import cua_backend_driver as _driver
  17. from tools.computer_use.permissions import CUA_DRIVER_BUNDLE_ID
  18. from hermes_cli.process_identity import release_process_group_once_empty, spawn_owned
  19. logger = logging.getLogger("tools.computer_use.cua_backend")
  20. # The only bundle identity the private daemon may launch through, and the teams that sign official
  21. # releases. Exact matches only: a suffixed identifier or other team is an impostor.
  22. _CUA_DRIVER_BUNDLE_ID = CUA_DRIVER_BUNDLE_ID
  23. _CUA_DRIVER_TEAM_IDS = ("4YEC26S9KF", "YCK386LBJ7")
  24. _QUIET_ERRORS = (OSError, subprocess.SubprocessError)
  25. def _cb():
  26. """Facade module (config/policy helpers), looked up lazily to avoid the import cycle."""
  27. from tools.computer_use import cua_backend
  28. return cua_backend
  29. def _resolve_cua_driver_app_path(driver_cmd: str) -> Optional[str]:
  30. """Return the CuaDriver.app bundle that CARRIES *driver_cmd*, if any. Derived from the resolved binary path
  31. only — no /Applications fallback, which could be a DIFFERENT install than the one the manifest resolved,
  32. running code the resolution chain never validated."""
  33. head, marker, _ = os.path.realpath(driver_cmd).partition(".app/Contents/MacOS/")
  34. executable = os.path.join(head + ".app", "Contents", "MacOS", "cua-driver")
  35. return head + ".app" if marker and os.path.isfile(executable) and os.access(executable, os.X_OK) else None
  36. def _validate_cua_driver_app_signature(app_path: str) -> None:
  37. """Fail closed unless *app_path* is the genuinely-signed CuaDriver.app. ``/usr/bin/open`` hands LaunchServices
  38. whatever bundle sits at the path, so ``codesign -dv`` must report EXACTLY ``Identifier=com.trycua.driver`` and
  39. an expected TeamIdentifier. ``TeamIdentifier=not set`` (ad-hoc dev builds) is allowed only with
  40. ``computer_use.allow_unsigned_driver: true``. Raises RuntimeError on any mismatch or when codesign is
  41. unavailable/fails."""
  42. codesign = shutil.which("codesign")
  43. if not codesign:
  44. raise RuntimeError("codesign is required to verify CuaDriver.app before launching it.")
  45. try:
  46. proc = _cb()._run_quiet([codesign, "-dv", app_path], timeout=15)
  47. except (OSError, subprocess.TimeoutExpired) as exc:
  48. raise RuntimeError(f"could not verify CuaDriver.app signature: {exc}") from exc
  49. if proc.returncode != 0:
  50. raise RuntimeError(f"CuaDriver.app at {app_path} is not code-signed; refusing to launch it ({(proc.stderr or '').strip()})")
  51. parts = [line.partition("=") for line in (proc.stderr or "").splitlines()] # codesign -dv reports on stderr
  52. fields = {k.strip(): v.strip() for k, sep, v in reversed(parts) if sep} # first occurrence of a key wins
  53. identifier, team = fields.get("Identifier", ""), fields.get("TeamIdentifier", "")
  54. if identifier != _CUA_DRIVER_BUNDLE_ID:
  55. raise RuntimeError(f"CuaDriver.app at {app_path} has identifier {identifier!r}, expected {_CUA_DRIVER_BUNDLE_ID!r}; "
  56. "refusing to launch it.")
  57. if team in _CUA_DRIVER_TEAM_IDS or (team in ("", "not set") and _cb()._computer_use_cfg().get("allow_unsigned_driver") is True):
  58. return
  59. raise RuntimeError(f"CuaDriver.app at {app_path} is signed by team {team!r}, expected one of {_CUA_DRIVER_TEAM_IDS!r}; "
  60. "refusing to launch it. (Set computer_use.allow_unsigned_driver: true in config.yaml only for "
  61. "local unsigned driver builds.)")
  62. def _embedded_daemon_spawn_command(driver_cmd: str, serve_args: list[str], *, platform: str,
  63. app_path: Optional[str] = None) -> list[str]:
  64. """Build the private-daemon launch while preserving macOS TCC identity."""
  65. if platform != "darwin":
  66. return [driver_cmd, *serve_args]
  67. resolved_app = app_path or _resolve_cua_driver_app_path(driver_cmd)
  68. if not resolved_app:
  69. raise RuntimeError("CuaDriver.app is required for private computer-use sessions on macOS. Run `hermes computer-use install` to restore it.")
  70. _validate_cua_driver_app_signature(resolved_app)
  71. return ["/usr/bin/open", "-n", "-g", "-a", resolved_app, "--args", *serve_args]
  72. def _wait_or_kill(process: Any) -> None:
  73. """Wait 5s for a graceful exit, then terminate (2s), then kill."""
  74. try:
  75. process.wait(timeout=5.0)
  76. except subprocess.TimeoutExpired:
  77. process.terminate()
  78. try:
  79. process.wait(timeout=2.0)
  80. except subprocess.TimeoutExpired:
  81. process.kill()
  82. process.wait(timeout=2.0)
  83. class _EmbeddedCuaDaemon:
  84. """Private daemon for a non-standard permission mode. cua-driver's permission mode is immutable after daemon
  85. startup, so reusing the machine-wide daemon would let one Hermes session's YOLO choice affect another. A
  86. private daemon gives the session its own socket, runtime and launch-time authorization; on macOS it is
  87. launched through CuaDriver.app so TCC stays attached to ``com.trycua.driver``. ``unrestricted`` = explicit
  88. Hermes YOLO (``--dangerously-bypass-approvals``); ``bounded`` = a user-reviewed capability manifest approved
  89. at launch is the authorization boundary, not a runtime prompt. The manifest is a ceiling, not a mode: it "can
  90. narrow a profile but never widen it", so a configured v3 manifest is forwarded even for ``unrestricted``
  91. (bounding an approval-bypassed run). Mandatory for ``bounded``, optional everywhere else."""
  92. _START_TIMEOUT_SECONDS = 15.0
  93. def __init__(self, driver_cmd: str, permission_mode: str, capability_manifest: Optional[str] = None) -> None:
  94. if permission_mode not in {"unrestricted", "bounded"}:
  95. raise ValueError("embedded permission override supports unrestricted or bounded only")
  96. manifest = str(capability_manifest or "").strip()
  97. if not manifest and permission_mode == "bounded":
  98. raise ValueError("bounded permission mode requires computer_use.capability_manifest")
  99. manifest = os.path.abspath(os.path.expanduser(manifest)) if manifest else ""
  100. if manifest and not os.path.isfile(manifest):
  101. raise ValueError(f"capability manifest not found: {manifest}")
  102. self.capability_manifest: Optional[str] = manifest or None
  103. # bounded always forwards (driver validates it); other modes accept only v3 — a legacy manifest aborts startup.
  104. self.manifest_applies = bool(manifest) and (
  105. permission_mode == "bounded" or _cb()._manifest_is_mode_independent(manifest))
  106. if manifest and not self.manifest_applies:
  107. logger.warning("computer_use.capability_manifest is a legacy (v1/v2) manifest, which cua-driver only accepts in "
  108. "bounded mode — it will NOT bound this %s session. Migrate the manifest to version 3 to keep a "
  109. "ceiling on approval-bypassed runs.", permission_mode)
  110. self.permission_mode, self._driver_cmd, self._command = permission_mode, driver_cmd, driver_cmd
  111. self._mcp_args: list[str] = list(_driver._CUA_DRIVER_ARGS)
  112. self._process: Any = None
  113. self._owns_runtime = self._running = False
  114. self._stderr_tail: deque[str] = deque(maxlen=20)
  115. token = uuid.uuid4().hex[:12]
  116. self.socket_path = (rf"\\.\pipe\hermes-cua-{token}" if sys.platform == "win32"
  117. else os.path.join(tempfile.gettempdir(), f"hc-{token}.sock"))
  118. def child_env(self) -> dict[str, str]:
  119. env = {**_cb().cua_driver_child_env(), "CUA_DRIVER_PERMISSION_MODE": self.permission_mode}
  120. if self.permission_mode == "unrestricted":
  121. env["CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS"] = "1"
  122. return env
  123. def _sanitized_env(self) -> dict[str, str]:
  124. from tools.environments.local import _sanitize_subprocess_env
  125. return _sanitize_subprocess_env(self.child_env())
  126. def _drain_stderr(self, process: Any) -> None:
  127. with contextlib.suppress(Exception):
  128. for line in getattr(process, "stderr", None) or ():
  129. text = str(line).strip()
  130. if text:
  131. self._stderr_tail.append(text)
  132. logger.debug("embedded cua-driver: %s", text)
  133. def _serve_args(self) -> list[str]:
  134. serve_args = ["serve", "--embedded", "--socket", self.socket_path, "--no-permissions-gate", "--permission-mode",
  135. self.permission_mode, *(["--dangerously-bypass-approvals"] if self.permission_mode == "unrestricted" else [])]
  136. if self.manifest_applies:
  137. serve_args += ["--capability-manifest", str(self.capability_manifest), "--approve-capability-manifest"]
  138. # The private daemon owns the cursor overlay, so the overlay policy must apply to this long-lived serve
  139. # process, not only its MCP proxy. Appended BEFORE the macOS app-launch wrapping so the flag travels inside
  140. # `open ... --args` with the rest of the serve args.
  141. return _driver._mcp_args_with_overlay_flag(serve_args, driver_cmd=self._command)
  142. def start(self) -> None:
  143. if self._running:
  144. return
  145. # Keep an explicit command fixed, but reselect managed drivers on every
  146. # launch: PM may have acquired a new pin since construction or last stop.
  147. driver_cmd = self._driver_cmd or _driver.resolve_cua_driver_cmd()
  148. if not driver_cmd:
  149. raise RuntimeError(_driver.cua_driver_install_hint())
  150. self._command, self._mcp_args = _driver._resolve_mcp_invocation(driver_cmd)
  151. env = self._sanitized_env()
  152. command = _embedded_daemon_spawn_command(self._command, self._serve_args(), platform=sys.platform)
  153. popen_kwargs: dict[str, Any] = dict(stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
  154. text=True, encoding="utf-8", errors="replace", env=env)
  155. if sys.platform == "darwin":
  156. # `open` hands the daemon to LaunchServices: it is launchd's child, never in our tree, so there is no
  157. # group of ours to own. The daemon's own --embedded lifetime is the only bound there.
  158. self._process = subprocess.Popen(command, **popen_kwargs)
  159. else:
  160. # Owned: the daemon dies with this process however it dies. It used to be stopped only by stop()
  161. # (session release / atexit), so a SIGKILLed or OOM-killed Hermes left a YOLO-mode daemon running.
  162. self._process = spawn_owned(command, purpose="cua-driver-embedded", **popen_kwargs)
  163. self._owns_runtime = True
  164. threading.Thread(target=self._drain_stderr, args=(self._process,), name="hermes-cua-daemon-stderr", daemon=True).start()
  165. deadline = time.monotonic() + self._START_TIMEOUT_SECONDS
  166. while time.monotonic() < deadline:
  167. return_code = self._process.poll()
  168. # `open` exits 0 once LaunchServices took the request: on macOS only a non-zero exit means the daemon died.
  169. if return_code is not None and (sys.platform != "darwin" or return_code != 0):
  170. self._startup_failure("embedded cua-driver exited during startup", "no diagnostic output")
  171. if self._socket_ready(env):
  172. self._running = True
  173. return
  174. time.sleep(0.1)
  175. self.stop()
  176. self._startup_failure("embedded cua-driver startup timed out", "daemon did not become ready")
  177. def _startup_failure(self, what: str, fallback: str) -> None:
  178. raise RuntimeError(f"{what}: {'; '.join(self._stderr_tail) or fallback}")
  179. def _socket_ready(self, env: dict[str, str]) -> bool:
  180. """``cua-driver status --socket`` exits 0 once the private daemon accepts connections."""
  181. probe = _cb()._run_quiet([self._command, "status", "--socket", self.socket_path], timeout=2.0, env=env, swallow=_QUIET_ERRORS)
  182. return probe is not None and probe.returncode == 0
  183. def proxy_invocation(self) -> tuple[str, list[str]]:
  184. if not self._running:
  185. raise RuntimeError("embedded cua-driver daemon is not running")
  186. return self._command, [*self._mcp_args, "--embedded", "--socket", self.socket_path]
  187. def stop(self) -> None:
  188. process, self._process = self._process, None
  189. owns_runtime, self._owns_runtime, self._running = self._owns_runtime, False, False
  190. if owns_runtime:
  191. _cb()._run_quiet([self._command, "stop", "--socket", self.socket_path], timeout=3.0, stdout=subprocess.DEVNULL,
  192. stderr=subprocess.DEVNULL, env=self._sanitized_env(), swallow=_QUIET_ERRORS)
  193. if process is not None:
  194. _wait_or_kill(process)
  195. release_process_group_once_empty(process.pid, proc=process) # stopped it ourselves (a no-op for the macOS `open` launcher)
  196. if sys.platform != "win32" and os.path.exists(self.socket_path):
  197. with contextlib.suppress(OSError):
  198. os.remove(self.socket_path)