Files
hermes-agent/tools/browser_tool_cdp.py
Teknium 37e36cda32 fix(browser): a session that resolved the old endpoint during /browser connect is closed, not kept
/browser connect reaps the profile's browsers, publishes the new live
endpoint, then reaps again. A tool call in the same profile that resolved the
old endpoint before the publish but registered its session after the second
reap kept driving the old browser (tui_gateway/methods_browser.py
_browser_connect / _browser_disconnect; predates #106742).

set_live_cdp_override now bumps a per-profile generation. _get_session_info
reads it before building a session and again under the lock when it registers
the session; if this profile published in between, the session is closed
through the normal teardown and rebuilt on the endpoint published now (at most
two rebuilds, so a flapping connect cannot loop a tool call). Another
profile's publish has its own generation and never invalidates this one.

Refs #134889 (GW-23)
Refs #134889 only
2026-10-19 03:10:30 -07:00

194 lines
8.9 KiB
Python

"""User-supplied CDP endpoint resolution (browser.cdp_url / real-profile), dialog-policy config and the per-task CDP supervisor lifecycle.
Split out of ``tools/browser_tool.py``. Facade-owned state is read through ``_bt`` (``tools.browser_tool``, resolved per call) — no import cycle."""
import contextlib
import os
import threading
from typing import Optional, Tuple
from agent.proxy_bypass import loopback_request_kwargs
from tools.browser_tool_origin import origin_module as _origin
def _resolve_cdp_override(cdp_url: str) -> str:
"""Normalize a user-supplied CDP endpoint into a concrete websocket URL.
Full ``ws://.../devtools/browser/...`` endpoints pass through; HTTP discovery roots and bare ``ws://host:port``
resolve via ``/json/version`` → ``webSocketDebuggerUrl`` (falls back to the raw value with a warning).
"""
_bt = _origin()
raw = (cdp_url or "").strip()
if not raw:
return ""
lowered = raw.lower()
if "/devtools/browser/" in lowered:
return raw
discovery_url = raw
if lowered.startswith(("ws://", "wss://")):
if not (raw.count(":") == 2 and raw.rstrip("/").rsplit(":", 1)[-1].isdigit() and "/" not in raw.split(":", 2)[-1]):
return raw
discovery_url = ("http://" if lowered.startswith("ws://") else "https://") + raw.split("://", 1)[1]
version_url = discovery_url if discovery_url.lower().endswith("/json/version") else discovery_url.rstrip("/") + "/json/version"
san = _bt._sanitize_url_for_logs
try:
import requests # lazy — shared module object, test patches still apply
response = requests.get(version_url, timeout=10, **loopback_request_kwargs(version_url))
response.raise_for_status()
payload = response.json()
except Exception as exc:
_bt.logger.warning("Failed to resolve CDP endpoint %s via %s: %s", san(raw), san(version_url), san(exc))
return raw
ws_url = str(payload.get("webSocketDebuggerUrl") or "").strip()
if ws_url:
_bt.logger.info("Resolved CDP endpoint %s -> %s", san(raw), san(ws_url))
return ws_url
_bt.logger.warning("CDP discovery at %s did not return webSocketDebuggerUrl; using raw endpoint", san(version_url))
return raw
# Live ``/browser connect`` endpoints, one per profile home (``hermes_home_key()``): a multiplexed
# gateway serves every profile from this process, so a process-wide value would reach them all.
_live_overrides: dict[str, str] = {}
_live_overrides_lock = threading.Lock()
def live_cdp_override() -> str:
"""The current profile's live ``/browser connect`` endpoint, or "".
On a multiplexed gateway a context with no profile bound (a bare ``threading.Thread`` or stdlib
executor that did not copy the caller's context) answers "" rather than the launch profile's
endpoint, the way ``get_secret`` fails closed. Single-profile processes are unchanged."""
from agent.secret_scope import is_multiplex_active
from hermes_constants import get_hermes_home_override, hermes_home_key
if get_hermes_home_override() is None and is_multiplex_active():
return ""
with _live_overrides_lock:
return _live_overrides.get(hermes_home_key(), "")
def set_live_cdp_override(url: Optional[str]) -> None:
"""Set (or with a falsy ``url`` clear) the current profile's live endpoint and bump its generation."""
from hermes_constants import hermes_home_key
key = hermes_home_key()
with _live_overrides_lock:
if url:
_live_overrides[key] = url
else:
_live_overrides.pop(key, None)
_live_generations[key] = _live_generations.get(key, 0) + 1
# Per-profile count of live-endpoint publishes. A browser session records the value it saw before
# resolving its endpoint; ``_get_session_info`` closes one whose profile published in between (it may
# have resolved the old URL after ``/browser connect``'s second reap had already run).
_live_generations: dict[str, int] = {}
def live_cdp_generation(home_key: Optional[str] = None) -> int:
"""The current (or ``home_key``'s) profile's live-endpoint generation."""
from hermes_constants import hermes_home_key
with _live_overrides_lock:
return _live_generations.get(home_key or hermes_home_key(), 0)
def env_cdp_url() -> str:
"""``BROWSER_CDP_URL`` from this profile's secret scope. A routed profile (multiplex, or a scope
bound for another home) reads only its own ``.env``: ``os.environ`` holds the launch profile's
value. Single-profile reads fall through to ``os.environ`` as before (``get_secret``)."""
from agent.secret_scope import current_secret_scope, get_secret, serves_routed_profile
if serves_routed_profile():
value = (current_secret_scope() or {}).get("BROWSER_CDP_URL")
else:
value = get_secret("BROWSER_CDP_URL")
return (value or "").strip()
def _get_cdp_override_raw() -> str:
"""Return the *configured* CDP override without any network I/O.
Precedence: this profile's live ``/browser connect``, then its ``BROWSER_CDP_URL`` (:func:`env_cdp_url`),
then ``browser.cdp_url``. Is-it-configured
gates (check_fns, ``_is_local_mode`` / ``_is_local_backend``, ``hermes doctor``) MUST use this, not
:func:`_get_cdp_override`: its 10s HTTP discovery against a stale ``cdp_url`` would stall every startup's
schema build with no error.
"""
env_override = live_cdp_override() or env_cdp_url()
return env_override or _origin()._browser_cfg("cdp_url", "", lambda v: str(v or "").strip(), "browser.cdp_url from config")
def _get_cdp_override() -> str:
"""Resolved CDP URL override, or "" (skips cloud AND local launch).
May perform HTTP ``/json/version`` discovery — only call on paths about to *connect*; pure gates must use
:func:`_get_cdp_override_raw`.
"""
_bt = _origin()
return _resolve_cdp_override(raw) if (raw := _get_cdp_override_raw()) else ""
def _get_dialog_policy_config() -> tuple[str, float]:
"""Read ``browser.dialog_policy`` + ``browser.dialog_timeout_s``; supervisor defaults when absent/invalid."""
_bt = _origin()
# Deferred so browser_tool imports in minimal environments.
from tools.browser_supervisor_dialogs import DEFAULT_DIALOG_POLICY, DEFAULT_DIALOG_TIMEOUT_S, _VALID_POLICIES
policy, timeout_s = DEFAULT_DIALOG_POLICY, DEFAULT_DIALOG_TIMEOUT_S
try:
from hermes_cli.config import read_raw_config
cfg = read_raw_config()
browser_cfg = cfg.get("browser", {}) if isinstance(cfg, dict) else {}
if not isinstance(browser_cfg, dict):
return policy, timeout_s
candidate = str(browser_cfg.get("dialog_policy") or DEFAULT_DIALOG_POLICY)
if candidate in _VALID_POLICIES:
policy = candidate
else:
_bt.logger.debug("Invalid browser.dialog_policy=%r; using default", candidate)
timeout_raw = browser_cfg.get("dialog_timeout_s")
try:
timeout_s = float(timeout_raw) if timeout_raw is not None else DEFAULT_DIALOG_TIMEOUT_S
if timeout_s <= 0:
timeout_s = DEFAULT_DIALOG_TIMEOUT_S
except (TypeError, ValueError):
timeout_s = DEFAULT_DIALOG_TIMEOUT_S
return policy, timeout_s
except Exception:
return DEFAULT_DIALOG_POLICY, DEFAULT_DIALOG_TIMEOUT_S
def _ensure_cdp_supervisor(task_id: str) -> None:
"""Start a CDP supervisor for ``task_id`` if an endpoint is reachable.
Idempotent (``get_or_start`` skips an existing ``(task_id, cdp_url)`` and restarts on URL change), so safe on
every navigate / ``/browser connect``. URL precedence: the CDP override, then the session's own ``cdp_url``
(cloud providers, e.g. Browserbase). Swallows all errors — a failed attach must not break the session;
snapshots just lack ``pending_dialogs`` / ``frame_tree``.
"""
_bt = _origin()
cdp_url = _get_cdp_override()
if not cdp_url:
with _bt._cleanup_lock:
session_info = _bt._active_sessions.get(task_id, {})
maybe = str(session_info.get("cdp_url") or "")
if maybe:
cdp_url = _resolve_cdp_override(maybe)
if not cdp_url:
return
try:
from tools.browser_supervisor import SUPERVISOR_REGISTRY # type: ignore[import-not-found]
policy, timeout_s = _get_dialog_policy_config()
SUPERVISOR_REGISTRY.get_or_start(task_id=task_id, cdp_url=cdp_url, dialog_policy=policy, dialog_timeout_s=timeout_s)
except Exception as exc:
_bt.logger.debug("CDP supervisor attach for task=%s failed (non-fatal): %s", task_id, exc)
def _stop_cdp_supervisor(task_id: str) -> None:
"""Stop the CDP supervisor for ``task_id`` if one exists. No-op otherwise."""
try:
from tools.browser_supervisor import SUPERVISOR_REGISTRY # type: ignore[import-not-found]
SUPERVISOR_REGISTRY.stop(task_id)
except Exception as exc:
_origin().logger.debug("CDP supervisor stop for task=%s failed (non-fatal): %s", task_id, exc)