Skip to content

The agent that grows with you

feat(browser): public captured CDP call seam for trusted plugins

Teknium6bf7de73e1d5
diff --git a/tests/tools/test_browser_supervisor_capture.py b/tests/tools/test_browser_supervisor_capture.py
new file mode 100644
index 00000000000..6e4ee2cbde4
--- /dev/null
+++ b/tests/tools/test_browser_supervisor_capture.py
@@ -0,0 +1,146 @@
+"""Behavior contract for ``SUPERVISOR_REGISTRY.capture`` (public CDP seam for trusted plugins).
+
+A real ``CDPSupervisor`` talks to a real local WebSocket server that speaks just enough CDP
+(getTargets / attachToTarget / echo). Each connection gets its own page session id
+(``S1``, ``S2``, ...) so the tests can tell which socket a frame travelled on.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import threading
+import time
+
+import pytest
+
+from tools.browser_supervisor import _SupervisorRegistry
+from tools.browser_supervisor_capture import CapturedCDPInvalid
+
+
+class _FakeCDP:
+ def __init__(self) -> None:
+ self.frames: list[tuple[int, str, str | None]] = [] # (connection no, method, sessionId)
+ self.connections: list = []
+ self.url = ""
+ self.loop = asyncio.new_event_loop()
+ ready = threading.Event()
+ threading.Thread(target=self._serve, args=(ready,), daemon=True).start()
+ assert ready.wait(5)
+
+ def _serve(self, ready: threading.Event) -> None:
+ from websockets.asyncio.server import serve
+
+ async def main():
+ async with serve(self._handle, "127.0.0.1", 0) as server:
+ self.url = f"ws://127.0.0.1:{list(server.sockets)[0].getsockname()[1]}/devtools/browser/x"
+ ready.set()
+ await asyncio.Event().wait()
+
+ self.loop.run_until_complete(main())
+
+ async def _handle(self, ws) -> None:
+ self.connections.append(ws)
+ conn = len(self.connections)
+ async for raw in ws:
+ msg = json.loads(raw)
+ method, sid = msg["method"], msg.get("sessionId")
+ self.frames.append((conn, method, sid))
+ if method == "Test.hang":
+ continue
+ if method == "Test.error":
+ await ws.send(json.dumps({"id": msg["id"], "error": {"code": -32000, "message": "boom"}}))
+ continue
+ result = {"echo": method, "sessionId": sid, "params": msg.get("params")}
+ if method == "Target.getTargets":
+ result = {"targetInfos": [{"targetId": "T1", "type": "page", "url": "about:blank"}]}
+ elif method == "Target.attachToTarget":
+ result = {"sessionId": f"S{conn}"}
+ await ws.send(json.dumps({"id": msg["id"], "result": result}))
+
+ def drop_current(self) -> None:
+ asyncio.run_coroutine_threadsafe(self.connections[-1].close(), self.loop).result(5)
+
+ def methods_on(self, conn: int) -> list[str]:
+ return [m for c, m, _ in self.frames if c == conn]
+
+
+def cdp():
+ return _FakeCDP()
+
+
+def registry():
+ reg = _SupervisorRegistry()
+ yield reg
+ reg.stop_all()
+
+
+def _wait(pred, timeout=10.0):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if pred():
+ return
+ time.sleep(0.02)
+ raise AssertionError("condition not reached")
+
+
+def test_call_round_trips_on_captured_connection(cdp, registry):
+ registry.get_or_start("t", cdp.url, start_timeout=5)
+ handle = registry.capture("t")
+ assert handle.is_valid() and handle.page_session_id == "S1"
+
+ reply = handle.call("Runtime.evaluate", {"expression": "1"}, session_id=handle.page_session_id)
+ assert reply["result"] == {"echo": "Runtime.evaluate", "sessionId": "S1", "params": {"expression": "1"}}
+ assert handle.call("Target.getTargets")["result"]["targetInfos"][0]["targetId"] == "T1" # browser-level
+
+ with pytest.raises(RuntimeError, match="boom"):
+ handle.call("Test.error")
+ started = time.monotonic()
+ with pytest.raises(TimeoutError):
+ handle.call("Test.hang", timeout=0.3)
+ assert time.monotonic() - started < 2
+ assert handle.is_valid() # neither an error reply nor a timeout invalidates the handle
+
+ with pytest.raises(CapturedCDPInvalid):
+ registry.capture("no-such-task")
+
+
+def test_handle_never_follows_a_reconnect_or_replacement(cdp, registry):
+ sup = registry.get_or_start("t", cdp.url, start_timeout=5)
+ old = registry.capture("t")
+
+ # A call in flight when the socket drops fails promptly as invalidation, not at its timeout.
+ errors: list = []
+ caller = threading.Thread(target=lambda: errors.append(_raises(lambda: old.call("Test.hang", timeout=30))))
+ caller.start()
+ _wait(lambda: "Test.hang" in cdp.methods_on(1))
+ started = time.monotonic()
+ cdp.drop_current()
+ caller.join(10)
+ assert errors and isinstance(errors[0], CapturedCDPInvalid), errors
+ assert time.monotonic() - started < 5
+
+ _wait(lambda: len(cdp.connections) == 2 and sup.snapshot().active)
+ assert not old.is_valid()
+ with pytest.raises(CapturedCDPInvalid):
+ old.call("Probe.afterReconnect", session_id=old.page_session_id)
+ assert "Probe.afterReconnect" not in cdp.methods_on(2) # never silently retargeted
+
+ fresh = registry.capture("t")
+ assert fresh.page_session_id == "S2"
+ assert fresh.call("Probe.fresh", session_id=fresh.page_session_id)["result"]["sessionId"] == "S2"
+
+ registry.stop("t") # stop / replacement in the registry invalidates too
+ assert not fresh.is_valid()
+ with pytest.raises(CapturedCDPInvalid):
+ fresh.call("Probe.afterStop")
+
+
+def _raises(fn) -> BaseException | None:
+ try:
+ fn()
+ except BaseException as exc: # noqa: BLE001 — handed back to the asserting thread
+ return exc
+ return None
diff --git a/tools/browser_supervisor.py b/tools/browser_supervisor.py
index 23d1a6f3311..917ad1999b8 100644
--- a/tools/browser_supervisor.py
+++ b/tools/browser_supervisor.py
@@ -30,6 +30,8 @@ from tools.browser_supervisor_frames import FrameInfo, FrameTrackingMixin
if TYPE_CHECKING:
from websockets.asyncio.client import ClientConnection
+ from tools.browser_supervisor_capture import CapturedCDP
+
logger = logging.getLogger(__name__)
# Browserbase can transiently drop a CDP socket while a short-lived client
@@ -422,6 +424,12 @@ class CDPSupervisor(DialogSupervisionMixin, FrameTrackingMixin):
handle.cancel()
self._dialog_watchdogs.clear()
await self._close_ws()
+ # Replies to calls still in flight died with the socket: fail them now
+ # instead of letting each caller sit out its full timeout.
+ for fut in self._pending_calls.values():
+ if not fut.done():
+ fut.set_exception(ConnectionError("CDP connection closed before reply"))
+ self._pending_calls.clear()
if self._stop_requested:
return
@@ -505,6 +513,13 @@ class _SupervisorRegistry:
with self._lock:
return self._by_task.pop(task_id, None)
+ def capture(self, task_id: str, *, timeout: float = 10.0) -> "CapturedCDP":
+ """Public CDP seam for trusted in-process plugins: a handle pinned to this task's
+ current connection and default page session (``tools.browser_supervisor_capture``)."""
+ from tools.browser_supervisor_capture import capture
+
+ return capture(self, task_id, timeout=timeout)
+
def get_or_start(self, task_id: str, cdp_url: str, *, dialog_policy: str = DEFAULT_DIALOG_POLICY,
dialog_timeout_s: float = DEFAULT_DIALOG_TIMEOUT_S, start_timeout: float = 15.0) -> CDPSupervisor:
"""Idempotently ensure a supervisor runs for ``(task_id, cdp_url)``; one bound to a
diff --git a/tools/browser_supervisor_capture.py b/tools/browser_supervisor_capture.py
new file mode 100644
index 00000000000..fbfd279d1d8
--- /dev/null
+++ b/tools/browser_supervisor_capture.py
@@ -0,0 +1,115 @@
+"""Captured CDP connection handle for trusted in-process plugins.
+
+``SUPERVISOR_REGISTRY.capture(task_id)`` pins one supervisor's current WebSocket and the
+default page session attached on it. ``call()`` sends only over that socket. Once the
+supervisor reconnects, stops, or is replaced in the registry, the handle is invalid and
+every call raises ``CapturedCDPInvalid``: it never retargets a newer connection.
+
+This grants no new capability. In-process plugin code can already reach the supervisor;
+the handle exists so plugins stop writing its private call table and socket (catalog
+review on #132272). It performs no origin, consent or target-ownership checks.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import concurrent.futures
+from typing import TYPE_CHECKING, Any, Dict, Optional
+
+if TYPE_CHECKING:
+ from tools.browser_supervisor import CDPSupervisor, _SupervisorRegistry
+
+
+class CapturedCDPInvalid(RuntimeError):
+ """The captured connection is gone (reconnect, stop, or registry replacement)."""
+
+
+class CapturedCDP:
+ """A CDP channel pinned to one supervisor connection. Build via ``SUPERVISOR_REGISTRY.capture``."""
+
+ def __init__(self, supervisor: CDPSupervisor, registry: _SupervisorRegistry) -> None:
+ # Runs on the supervisor loop (see ``capture``) so ws and session id are one snapshot.
+ self._supervisor = supervisor
+ self._registry = registry
+ self._loop: asyncio.AbstractEventLoop = supervisor._loop # type: ignore[assignment]
+ self._ws = supervisor._ws
+ self.task_id: str = supervisor.task_id
+ self.cdp_url: str = supervisor.cdp_url
+ # The default page session at capture time. A later ``focus_page`` on the supervisor
+ # does not change it: calls with this id keep reaching the page captured here.
+ self.page_session_id: str = supervisor._page_session_id or ""
+
+ def is_valid(self) -> bool:
+ """True while the captured connection is still the supervisor's live one."""
+ sup = self._supervisor
+ return (self._registry.get(self.task_id) is sup and sup._active and not sup._stop_requested
+ and sup._ws is self._ws and self._loop.is_running())
+
+ def _invalid(self) -> CapturedCDPInvalid:
+ return CapturedCDPInvalid(f"captured CDP connection for task {self.task_id!r} is gone "
+ "(supervisor reconnected, stopped or was replaced); capture again")
+
+ async def _send(self, method: str, params: Optional[Dict[str, Any]],
+ session_id: Optional[str], timeout: float) -> Dict[str, Any]:
+ # ``_cdp`` reaches its send without awaiting, so this check and the send run in one
+ # loop step: a reconnect cannot swap the socket in between.
+ if not self.is_valid():
+ raise self._invalid()
+ try:
+ return await self._supervisor._cdp(method, params, session_id=session_id, timeout=timeout)
+ except Exception:
+ # A reply lost to a dropped socket (timeout, ConnectionError, ConnectionClosed)
+ # surfaces as invalidation; a CDP error on a live connection passes through.
+ if not self.is_valid():
+ raise self._invalid() from None
+ raise
+
+ def call(self, method: str, params: Optional[Dict[str, Any]] = None, *,
+ session_id: Optional[str] = None, timeout: float = 10.0) -> Dict[str, Any]:
+ """Send ``method`` on the captured connection and return the raw CDP reply
+ (``{"id", "result"}``). ``session_id=None`` targets the browser endpoint;
+ pass ``page_session_id`` (or a session you attached) for page domains.
+
+ Raises ``CapturedCDPInvalid`` when the connection is gone, ``TimeoutError`` when no
+ reply arrives in ``timeout`` seconds, ``RuntimeError`` for a CDP error reply.
+ Blocks the calling thread; never call it from the supervisor's own loop.
+ """
+ try:
+ running = asyncio.get_running_loop()
+ except RuntimeError:
+ running = None
+ if running is self._loop:
+ raise RuntimeError("CapturedCDP.call() blocks and cannot run on the supervisor loop")
+ if not self.is_valid():
+ raise self._invalid()
+ from agent.async_utils import safe_schedule_threadsafe
+
+ fut = safe_schedule_threadsafe(self._send(method, params, session_id, timeout), self._loop)
+ if fut is None:
+ raise self._invalid()
+ try:
+ return fut.result(timeout=timeout + 1.0)
+ except concurrent.futures.TimeoutError:
+ fut.cancel()
+ raise TimeoutError(f"CDP {method} got no reply within {timeout}s") from None
+
+
+def capture(registry: _SupervisorRegistry, task_id: str, *, timeout: float = 10.0) -> CapturedCDP:
+ """Pin the running supervisor for ``task_id``; never starts, reconnects or refocuses one."""
+ from tools.browser_supervisor import _LoopUnavailable, _schedule
+
+ found = registry.get(task_id)
+ loop = found._loop if found is not None else None
+ if found is None or loop is None or not loop.is_running():
+ raise CapturedCDPInvalid(f"no running browser supervisor for task {task_id!r}")
+ sup = found
+
+ async def _snapshot() -> CapturedCDP:
+ if not sup._active or sup._ws is None or not sup._page_session_id:
+ raise CapturedCDPInvalid(f"browser supervisor for task {task_id!r} has no attached page")
+ return CapturedCDP(sup, registry)
+
+ try:
+ return _schedule(_snapshot(), loop, timeout=timeout)
+ except _LoopUnavailable:
+ raise CapturedCDPInvalid(f"no running browser supervisor for task {task_id!r}") from None
diff --git a/website/docs/developer-guide/browser-supervisor.md b/website/docs/developer-guide/browser-supervisor.md
index 44a7823704c..2d8adef0acf 100644
--- a/website/docs/developer-guide/browser-supervisor.md
+++ b/website/docs/developer-guide/browser-supervisor.md
@@ -97,6 +97,47 @@ Configurable via `config.yaml` under `browser.dialog_policy`:
Policy is per-task; no per-dialog overrides.
+## Trusted plugin CDP access
+
+In-process plugin code can send raw CDP commands over a task's supervisor
+connection through one public call, instead of writing the supervisor's private
+call table or socket:
+
+```python
+from tools.browser_supervisor import SUPERVISOR_REGISTRY
+from tools.browser_supervisor_capture import CapturedCDPInvalid
+
+cdp = SUPERVISOR_REGISTRY.capture(task_id) # raises CapturedCDPInvalid if no attached supervisor
+reply = cdp.call("Runtime.evaluate", {"expression": "document.title", "returnByValue": True},
+ session_id=cdp.page_session_id, timeout=5)
+title = reply["result"]["result"]["value"]
+```
+
+- `SUPERVISOR_REGISTRY.capture(task_id, *, timeout=10.0) -> CapturedCDP` pins the
+ supervisor's current WebSocket and the default page session attached on it. It
+ never starts, reconnects or refocuses a supervisor.
+- `CapturedCDP.call(method, params=None, *, session_id=None, timeout=10.0) -> dict`
+ returns the raw CDP reply (`{"id", "result"}`). `session_id=None` addresses the
+ browser endpoint (`Target.*`); pass `page_session_id` or a session you attached
+ yourself for page domains. A CDP error reply raises `RuntimeError`; no reply
+ within `timeout` raises `TimeoutError`. The call blocks its thread, so call it
+ from a worker thread, never from the supervisor's own event loop.
+- `CapturedCDP.is_valid()` stays true until the supervisor reconnects, stops, or
+ is replaced in the registry. After that every `call` raises
+ `CapturedCDPInvalid`, including a call already in flight when the socket
+ drops. A handle never follows the supervisor to a new connection: capture
+ again and re-check whatever state you depend on.
+- `page_session_id` is the default page session at capture time. A later
+ `focus_page` on the supervisor does not change it.
+- Sessions you attach (`Target.attachToTarget`) are yours to detach. A reply
+ that arrives after `timeout` is dropped, so a timed-out attach can leave a
+ session attached until the connection closes; give attaches a generous timeout.
+
+This is a trusted, in-process seam. It grants nothing in-process Python could
+not already reach, and it enforces no origin, consent or target-ownership
+policy: a plugin that acts on pages must enforce its own. It is not exposed as a
+model tool and has no config switch.
+
## Agent surface
### `browser_dialog` tool
@@ -179,6 +220,7 @@ expiry, while the supervisor's long-lived connection keeps a valid session.
## File layout
- `tools/browser_supervisor.py` — `CDPSupervisor`, `SupervisorRegistry`, `PendingDialog`, `FrameInfo`
+- `tools/browser_supervisor_capture.py` — `CapturedCDP` / `CapturedCDPInvalid`, the trusted-plugin CDP seam behind `SUPERVISOR_REGISTRY.capture`
- `tools/browser_dialog_tool.py` — `browser_dialog` tool handler
- `tools/browser_tool.py` — `browser_navigate` start-hook, `browser_snapshot` merge, `/browser connect` reattach, `_cleanup_browser_session` teardown
- `toolsets.py` — registers `browser_dialog` in `browser`, `hermes-acp`, `hermes-api-server`, and core toolsets (gated on CDP reachability)
diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.md
index 9447a26faf3..c3c168735e7 100644
--- a/website/docs/developer-guide/plugins/index.md
+++ b/website/docs/developer-guide/plugins/index.md
@@ -1465,6 +1465,18 @@ def register(ctx):
For running a full `hermes <subcommand>` (e.g. `hermes kanban show`), shell out with the `terminal` tool via `ctx.dispatch_tool("terminal", {"command": "hermes kanban show ..."})` — there is no in-process slash-command bridge for headless worker sessions, and tools are the supported way to drive Hermes from a hook.
+### Send raw CDP commands to the agent's browser
+
+A plugin that must drive the agent's browser below the browser tools can get a
+CDP handle pinned to a task's live supervisor connection with
+`SUPERVISOR_REGISTRY.capture(task_id)` and send commands with
+`call(method, params=None, *, session_id=None, timeout=10.0)`. The handle
+raises `CapturedCDPInvalid` once that connection is gone and never retargets a
+newer one. Use it instead of reading or writing `CDPSupervisor` private
+attributes, which the catalog rejects. It is trusted in-process transport only:
+it performs no origin, consent or ownership checks for you. Full contract:
+[Browser CDP Supervisor](../browser-supervisor.md#trusted-plugin-cdp-access).
+
### Know which cron run you are in
`ctx.current_cron_execution()` returns the scheduled run the current code executes inside, or `None` outside cron. It works from any hook that fires during the run (`pre_tool_call`, `post_tool_call`, `pre_llm_call`, ...) and from tool handlers. The value is a frozen `CronExecution`: