browser_supervisor_capture.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. """Captured CDP connection handle for trusted in-process plugins.
  2. ``SUPERVISOR_REGISTRY.capture(task_id)`` pins one supervisor's current WebSocket and the
  3. default page session attached on it. ``call()`` sends only over that socket. Once the
  4. supervisor reconnects, stops, or is replaced in the registry, the handle is invalid and
  5. every call raises ``CapturedCDPInvalid``: it never retargets a newer connection.
  6. This grants no new capability. In-process plugin code can already reach the supervisor;
  7. the handle exists so plugins stop writing its private call table and socket (catalog
  8. review on #132272). It performs no origin, consent or target-ownership checks.
  9. """
  10. from __future__ import annotations
  11. import asyncio
  12. import concurrent.futures
  13. import inspect
  14. import math
  15. import threading
  16. import time
  17. from typing import TYPE_CHECKING, Any, Callable, Optional
  18. if TYPE_CHECKING:
  19. from tools.browser_supervisor import CDPSupervisor, _SupervisorRegistry
  20. class CapturedCDPInvalid(RuntimeError):
  21. """The captured connection is gone (reconnect, stop, or registry replacement)."""
  22. class CapturedCDP:
  23. """A CDP channel pinned to one supervisor connection. Build via ``SUPERVISOR_REGISTRY.capture``."""
  24. def __init__(self, supervisor: CDPSupervisor, registry: _SupervisorRegistry) -> None:
  25. # Runs on the supervisor loop (see ``capture``) so ws and session id are one snapshot.
  26. self._supervisor = supervisor
  27. self._registry = registry
  28. self._loop: asyncio.AbstractEventLoop = supervisor._loop # type: ignore[assignment]
  29. self._ws = supervisor._ws
  30. self.task_id: str = supervisor.task_id
  31. self.cdp_url: str = supervisor.cdp_url
  32. # The default page session at capture time. A later ``focus_page`` on the supervisor
  33. # does not change it: calls with this id keep reaching the page captured here.
  34. self.page_session_id: str = supervisor._page_session_id or ""
  35. def is_valid(self) -> bool:
  36. """True while the captured connection is still the supervisor's live one."""
  37. sup = self._supervisor
  38. return (self._registry.get(self.task_id) is sup and sup._active and not sup._stop_requested
  39. and sup._ws is self._ws and self._loop.is_running())
  40. def _invalid(self) -> CapturedCDPInvalid:
  41. return CapturedCDPInvalid(f"captured CDP connection for task {self.task_id!r} is gone "
  42. "(supervisor reconnected, stopped or was replaced); capture again")
  43. async def _send(self, method: str, params: Optional[dict[str, Any]],
  44. session_id: Optional[str], timeout: Optional[float],
  45. deadline: Optional[float], before_send: Optional[Callable[[], None]]) -> dict[str, Any]:
  46. # ``_cdp`` reaches its send without awaiting, so this check and the send run in one
  47. # loop step: a reconnect cannot swap the socket in between.
  48. if not self.is_valid():
  49. raise self._invalid()
  50. if deadline is not None and time.monotonic() >= deadline:
  51. raise TimeoutError("Captured CDP dispatch deadline expired")
  52. if before_send is not None:
  53. outcome = before_send()
  54. if outcome is not None:
  55. if inspect.iscoroutine(outcome):
  56. outcome.close()
  57. raise TypeError("before_send must return None synchronously")
  58. if deadline is not None and time.monotonic() >= deadline:
  59. raise TimeoutError("Captured CDP dispatch deadline expired")
  60. if not self.is_valid():
  61. raise self._invalid()
  62. try:
  63. return await self._supervisor._cdp(method, params, session_id=session_id, timeout=timeout)
  64. except Exception:
  65. # A reply lost to a dropped socket (timeout, ConnectionError, ConnectionClosed)
  66. # surfaces as invalidation; a CDP error on a live connection passes through.
  67. if not self.is_valid():
  68. raise self._invalid() from None
  69. raise
  70. def call(self, method: str, params: Optional[dict[str, Any]] = None, *,
  71. session_id: Optional[str] = None, timeout: Optional[float] = 10.0,
  72. before_send: Optional[Callable[[], None]] = None) -> dict[str, Any]:
  73. """Send ``method`` on the captured connection and return the raw CDP reply
  74. (``{"id", "result"}``). ``session_id=None`` targets the browser endpoint;
  75. pass ``page_session_id`` (or a session you attached) for page domains.
  76. Raises ``CapturedCDPInvalid`` when the connection is gone, ``TimeoutError`` when no
  77. reply arrives in ``timeout`` seconds, ``RuntimeError`` for a CDP error reply.
  78. Blocks the calling thread; never call it from the supervisor's own loop.
  79. A finite timeout also fences send admission while this call waits in the
  80. supervisor queue. ``timeout=None`` deliberately retains a reply until
  81. the connection closes: use it only in a consumer-owned worker when a
  82. late reply (for example an attachment session ID) must not be lost.
  83. Keep the consumer's own wait/issuance deadline finite and retain cleanup
  84. responsibility after it expires.
  85. ``before_send`` is a trusted synchronous nonblocking validation callback
  86. run on the supervisor loop immediately before CDP dispatch. It may raise
  87. to refuse a cancelled/expired operation. It must not call a blocking
  88. capture/CDP API. This is not origin or target-ownership authorization.
  89. """
  90. if timeout is not None:
  91. if (isinstance(timeout, bool) or not isinstance(timeout, (int, float))
  92. or not math.isfinite(timeout) or timeout <= 0
  93. or timeout > threading.TIMEOUT_MAX - 1.0):
  94. raise ValueError("Captured CDP timeout must be positive and finite, or None")
  95. if before_send is not None and not callable(before_send):
  96. raise TypeError("before_send must be callable")
  97. deadline = None if timeout is None else time.monotonic() + timeout
  98. try:
  99. running = asyncio.get_running_loop()
  100. except RuntimeError:
  101. running = None
  102. if running is self._loop:
  103. raise RuntimeError("CapturedCDP.call() blocks and cannot run on the supervisor loop")
  104. if not self.is_valid():
  105. raise self._invalid()
  106. from agent.async_utils import safe_schedule_threadsafe
  107. fut = safe_schedule_threadsafe(self._send(method, params, session_id, timeout, deadline, before_send), self._loop)
  108. if fut is None:
  109. raise self._invalid()
  110. while timeout is None:
  111. # Unbounded wait still ends with the loop: a closed loop drops queued callbacks.
  112. try:
  113. return fut.result(timeout=1.0)
  114. except concurrent.futures.TimeoutError:
  115. if self._loop.is_closed():
  116. fut.cancel()
  117. raise self._invalid() from None
  118. try:
  119. return fut.result(timeout=timeout + 1.0)
  120. except concurrent.futures.TimeoutError:
  121. fut.cancel()
  122. raise TimeoutError(f"CDP {method} got no reply within {timeout}s") from None
  123. def capture(registry: _SupervisorRegistry, task_id: str, *, timeout: float = 10.0) -> CapturedCDP:
  124. """Pin the running supervisor for ``task_id``; never starts, reconnects or refocuses one."""
  125. from tools.browser_supervisor import _LoopUnavailable, _schedule
  126. found = registry.get(task_id)
  127. loop = found._loop if found is not None else None
  128. if found is None or loop is None or not loop.is_running():
  129. raise CapturedCDPInvalid(f"no running browser supervisor for task {task_id!r}")
  130. sup = found
  131. async def _snapshot() -> CapturedCDP:
  132. if not sup._active or sup._ws is None or not sup._page_session_id:
  133. raise CapturedCDPInvalid(f"browser supervisor for task {task_id!r} has no attached page")
  134. return CapturedCDP(sup, registry)
  135. try:
  136. return _schedule(_snapshot(), loop, timeout=timeout)
  137. except _LoopUnavailable:
  138. raise CapturedCDPInvalid(f"no running browser supervisor for task {task_id!r}") from None