lease.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. """Who may drive a profile's Bot Desktop screen: the agent (default) or exactly one human viewer.
  2. The lease is the single truth shared by the RFB bridge (drops human input from non-holders), the
  3. ``computer_use`` tool (refuses to act while a human holds control — the person may be typing a
  4. credential, so even screenshots are refused; fail closed rather than trusting the agent to pause
  5. itself) and the Desktop UI (Watch / Take over / Hand back).
  6. Scope: the lease is a TOOL-LEVEL fence, not a property of the X server. ``computer_use`` and the browser
  7. tools consult it; a process the agent starts by hand against the published ``DISPLAY``/``XAUTHORITY``
  8. (the ``terminal`` tool, a script) is inside the documented same-user boundary and is not stopped by it
  9. (bot-screen.md, "Threat model"; #110040).
  10. Authority lives ON DISK, ``<HERMES_HOME>/bot-desktop/lease.json`` under an fcntl lock, because the
  11. processes that must agree do not share memory: ``hermes serve`` (viewer bridge), the messaging
  12. gateway, a CLI turn and isolated workers all drive the same display. Every read goes to the file;
  13. the in-process Condition only wakes local waiters early. ``epoch`` increments on every transition so
  14. an action admitted under one lease can tell that control changed underneath it.
  15. """
  16. from __future__ import annotations
  17. import json
  18. import logging
  19. import os
  20. import threading
  21. import time
  22. from dataclasses import asdict, dataclass, field
  23. from pathlib import Path
  24. from typing import Callable, Dict, List, Optional
  25. from hermes_constants import get_hermes_home, hermes_home_key, secure_parent_dir
  26. try:
  27. import fcntl
  28. except ImportError: # Windows/macOS without fcntl: computer_use imports this module on every call, and no
  29. fcntl = None # multi-process Bot Desktop exists there, so the cross-process lock degrades to a no-op.
  30. logger = logging.getLogger(__name__)
  31. AGENT = "agent"
  32. HUMAN = "human"
  33. class HumanHasControl(RuntimeError):
  34. """Raised by screen-driving tools while a human holds the lease."""
  35. @dataclass
  36. class Lease:
  37. holder: str = AGENT
  38. viewer_id: Optional[str] = None
  39. since: float = field(default_factory=time.time)
  40. reason: str = ""
  41. epoch: int = 0
  42. def as_dict(self) -> dict[str, object]:
  43. return asdict(self)
  44. def public_view(lease: Lease) -> dict[str, object]:
  45. """The lease as anything outside the gateway may see it (RPC results, the ``display.lease`` broadcast,
  46. the CLI): the holder's viewer id is a capability — whoever presents it co-drives or releases the lease —
  47. so it is replaced by a short hash the holder can match against its own id to know it is in control."""
  48. import hashlib
  49. d = lease.as_dict()
  50. d["viewer_id"] = None
  51. d["viewer_hash"] = hashlib.sha256(lease.viewer_id.encode()).hexdigest()[:12] if lease.viewer_id else None
  52. return d
  53. _lock = threading.Condition()
  54. _listeners: list[Callable[[str, Lease], None]] = []
  55. def _path(profile_key: Optional[str]) -> Path:
  56. """``profile_key`` is the HERMES_HOME path of the profile whose lease is meant (the RFB bridge
  57. serves several profiles from one process); ``None`` means the current profile."""
  58. home = Path(profile_key) if profile_key else get_hermes_home()
  59. return home / "bot-desktop" / "lease.json"
  60. def _read(path: Path) -> Lease:
  61. """No file = fresh profile, agent holds. A file that exists but cannot be parsed is a torn write
  62. or tampering: fail CLOSED (human holds) — an unreadable lease must never let the agent act on a
  63. screen a human may be using; the next successful write repairs it."""
  64. try:
  65. raw = path.read_text(encoding="utf-8-sig")
  66. except FileNotFoundError:
  67. return Lease()
  68. except OSError:
  69. return Lease(holder=HUMAN, viewer_id="unreadable-lease", reason="lease file unreadable")
  70. try:
  71. data = json.loads(raw)
  72. except ValueError:
  73. data = None
  74. if not isinstance(data, dict) or data.get("holder") not in (AGENT, HUMAN):
  75. return Lease(holder=HUMAN, viewer_id="unreadable-lease", reason="lease file corrupt")
  76. try:
  77. return Lease(**{k: v for k, v in data.items() if k in Lease.__dataclass_fields__})
  78. except TypeError:
  79. return Lease(holder=HUMAN, viewer_id="unreadable-lease", reason="lease file corrupt")
  80. def _private_dir(path: Path) -> None:
  81. """``bot-desktop/`` owner-only even when the lease is the first thing written there (a takeover can be
  82. recorded before start() ever ran, and the umask would otherwise leave it 0755)."""
  83. path.parent.mkdir(parents=True, exist_ok=True)
  84. secure_parent_dir(path)
  85. def _open_private(path: str | bytes | os.PathLike, flags: int) -> int:
  86. """``open(..., opener=_open_private)``: the file is created 0600 regardless of the umask."""
  87. return os.open(path, flags, 0o600)
  88. def _write(path: Path, lease: Lease) -> None:
  89. _private_dir(path)
  90. tmp = path.with_suffix(".json.tmp")
  91. with open(tmp, "w", encoding="utf-8", opener=_open_private) as fh:
  92. fh.write(json.dumps(lease.as_dict()))
  93. os.replace(tmp, path)
  94. class _locked:
  95. """Cross-process critical section over the lease file (fcntl on a sibling lock file)."""
  96. def __init__(self, path: Path):
  97. self._lockfile = path.with_suffix(".lock")
  98. self._fh = None
  99. def __enter__(self):
  100. if fcntl is None:
  101. return self
  102. _private_dir(self._lockfile)
  103. self._fh = open(self._lockfile, "a+", encoding="utf-8", opener=_open_private)
  104. fcntl.flock(self._fh.fileno(), fcntl.LOCK_EX)
  105. return self
  106. def __exit__(self, *exc):
  107. if self._fh is None:
  108. return
  109. fcntl.flock(self._fh.fileno(), fcntl.LOCK_UN)
  110. self._fh.close()
  111. def get(profile_key: Optional[str] = None) -> Lease:
  112. return _read(_path(profile_key))
  113. def on_change(listener: Callable[[str, Lease], None]) -> Callable[[], None]:
  114. """Subscribe to lease transitions made IN THIS PROCESS (the gateway broadcasts them to Desktop
  115. clients). Transitions made by another process are observed by reading, not by callback."""
  116. with _lock:
  117. _listeners.append(listener)
  118. def _off() -> None:
  119. with _lock:
  120. if listener in _listeners:
  121. _listeners.remove(listener)
  122. return _off
  123. def _notify(key: str, lease: Lease) -> None:
  124. # Snapshot under the lock: a viewer disconnecting on another thread runs unsubscribe()
  125. # concurrently with this loop; removing an entry from the live list mid-iteration skips
  126. # the next listener, and a still-connected viewer misses the lease transition.
  127. with _lock:
  128. listeners = list(_listeners)
  129. for cb in listeners:
  130. try:
  131. cb(key, lease)
  132. except Exception: # a broken subscriber must not wedge the handoff
  133. pass
  134. def _transition(profile_key: Optional[str], mutate: Callable[[Lease], bool]) -> Lease:
  135. key, path = hermes_home_key(profile_key) if profile_key else hermes_home_key(), _path(profile_key)
  136. with _locked(path):
  137. lease = _read(path)
  138. if not mutate(lease):
  139. return lease
  140. lease.epoch += 1
  141. _write(path, lease)
  142. with _lock:
  143. _lock.notify_all()
  144. _notify(key, lease)
  145. return lease
  146. def acquire(viewer_id: str, *, profile_key: Optional[str] = None, reason: str = "") -> Lease:
  147. """Human ``viewer_id`` takes control. Last writer wins: a second viewer evicts the first, and the
  148. RFB bridge closes the evicted socket so its UI drops to view-only."""
  149. def _m(lease: Lease) -> bool:
  150. if lease.holder == HUMAN and lease.viewer_id == viewer_id:
  151. return False # already theirs: no epoch bump, `since` and the reason on screen stay put
  152. # The agent's ask ("please log in to X") stays as the takeover reason: the human needs it
  153. # on screen WHILE they act, not only before they clicked Take over.
  154. lease.holder, lease.viewer_id, lease.since = HUMAN, viewer_id, time.time()
  155. lease.reason = reason or ""
  156. return True
  157. return _transition(profile_key, _m)
  158. def release(viewer_id: Optional[str] = None, *, profile_key: Optional[str] = None,
  159. unless_human: bool = False, epoch: Optional[int] = None) -> Lease:
  160. """Return control to the agent. With ``viewer_id`` only that holder may release (a stale viewer
  161. closing its window must not yank control from the one who took over after it). ``unless_human``
  162. makes a bare release a no-op while any human holds: the decision is taken under the file lock,
  163. so a takeover racing a check-then-release cannot be silently revoked. ``epoch`` releases only the
  164. lease generation the caller judged: any transition since (a takeover, a hand-back and re-take by the
  165. same viewer) keeps the lease. Callers read the returned lease's holder to learn whether anything
  166. happened."""
  167. def _m(lease: Lease) -> bool:
  168. if epoch is not None and lease.epoch != epoch:
  169. logger.info("bot-desktop lease: release of epoch %d ignored, the lease changed since", epoch)
  170. return False
  171. if unless_human and lease.holder == HUMAN:
  172. logger.info("bot-desktop lease: bare release ignored, a human holds")
  173. return False
  174. if viewer_id is not None and lease.holder == HUMAN and lease.viewer_id != viewer_id:
  175. # Ignored, not an error: the returned lease still shows the real holder. Logged so a
  176. # caller that never inspects the return value leaves a trace.
  177. logger.info("bot-desktop lease: release by %r ignored, another viewer holds", viewer_id)
  178. return False
  179. if lease.holder == AGENT:
  180. # Already the agent's. Bumping the epoch here would make a legitimately admitted in-flight
  181. # agent action (a double-clicked Hand back, a stray CLI stop) look overtaken and get voided.
  182. return False
  183. lease.holder, lease.viewer_id, lease.since, lease.reason = AGENT, None, time.time(), ""
  184. return True
  185. return _transition(profile_key, _m)
  186. def human_holds(profile_key: Optional[str] = None) -> bool:
  187. return get(profile_key).holder == HUMAN
  188. def viewer_may_send_input(viewer_id: str, *, profile_key: Optional[str] = None) -> bool:
  189. lease = get(profile_key)
  190. return lease.holder == HUMAN and lease.viewer_id == viewer_id
  191. def assert_agent_may_act(profile_key: Optional[str] = None) -> Lease:
  192. """The lease as of now, or ``HumanHasControl``. Callers keep the returned ``epoch`` and compare it
  193. with ``get().epoch`` after an admitted action: a change means a human took over mid-flight."""
  194. lease = get(profile_key)
  195. if lease.holder == HUMAN:
  196. raise HumanHasControl(
  197. "A human has taken over this desktop (they may be entering a credential). Screen actions and "
  198. "captures are refused until they hand control back. Tell the user what you need in your reply.")
  199. return lease
  200. def _reset_for_tests() -> None:
  201. with _lock:
  202. _listeners.clear()
  203. p = get_hermes_home() / "bot-desktop" / "lease.json"
  204. for f in (p, p.with_suffix(".lock"), p.with_suffix(".json.tmp")):
  205. try:
  206. f.unlink()
  207. except OSError:
  208. pass