Skip to content

The agent that grows with you

refactor(tools): compact browser backend modules to hit the 25% slice target

Teknium6e8109a9fb31
diff --git a/tools/browser_camofox.py b/tools/browser_camofox.py
index c4ad0fb993a..acc4f154b19 100644
--- a/tools/browser_camofox.py
+++ b/tools/browser_camofox.py
@@ -36,9 +36,7 @@ _DEFAULT_TIMEOUT = 30 # fallback when config is unreadable
_NO_SESSION_ERROR = "No browser session. Call browser_navigate first."
_vnc_url: Optional[str] = None # cached from /health response
_vnc_url_checked = False # only probe once per process
-
-# Cached command timeout from config (resolved lazily, like browser_tool)
-_cached_cmd_timeout: Optional[int] = None
+_cached_cmd_timeout: Optional[int] = None # browser.command_timeout, resolved lazily like browser_tool
_cmd_timeout_resolved = False
@@ -47,17 +45,15 @@ def _get_command_timeout() -> int:
global _cached_cmd_timeout, _cmd_timeout_resolved
if _cmd_timeout_resolved:
return _cached_cmd_timeout # type: ignore[return-value]
-
_cmd_timeout_resolved = True
- result = _DEFAULT_TIMEOUT
+ _cached_cmd_timeout = _DEFAULT_TIMEOUT
try:
val = cfg_get(read_raw_config(), "browser", "command_timeout")
if val is not None:
- result = max(int(val), 5)
+ _cached_cmd_timeout = max(int(val), 5)
except Exception as exc:
logger.debug("Could not read browser.command_timeout: %s", exc)
- _cached_cmd_timeout = result
- return result
+ return _cached_cmd_timeout
def _auth_headers() -> Dict[str, str]:
@@ -112,17 +108,17 @@ def check_camofox_available() -> bool:
return False
try:
resp = requests.get(f"{url}/health", timeout=5)
- if resp.status_code == 200 and not _vnc_url_checked:
- try:
- vnc_port = resp.json().get("vncPort")
- if isinstance(vnc_port, int) and 1 <= vnc_port <= 65535:
- _vnc_url = f"http://{urlsplit(url).hostname or 'localhost'}:{vnc_port}"
- except (ValueError, KeyError):
- pass
- _vnc_url_checked = True
- return resp.status_code == 200
except Exception:
return False
+ if resp.status_code == 200 and not _vnc_url_checked:
+ try:
+ vnc_port = resp.json().get("vncPort")
+ if isinstance(vnc_port, int) and 1 <= vnc_port <= 65535:
+ _vnc_url = f"http://{urlsplit(url).hostname or 'localhost'}:{vnc_port}"
+ except (ValueError, KeyError):
+ pass
+ _vnc_url_checked = True
+ return resp.status_code == 200
def get_vnc_url() -> Optional[str]:
@@ -144,9 +140,7 @@ def _get_camofox_config() -> Dict[str, Any]:
def _managed_persistence_enabled(camofox_cfg: Optional[Dict[str, Any]] = None) -> bool:
"""``browser.camofox.managed_persistence``: stable profile-scoped userId vs random per session."""
- if camofox_cfg is None:
- camofox_cfg = _get_camofox_config()
- return bool(camofox_cfg.get("managed_persistence"))
+ return bool((_get_camofox_config() if camofox_cfg is None else camofox_cfg).get("managed_persistence"))
def _env_or_cfg(env_name: str, camofox_cfg: Dict[str, Any], cfg_key: str, *, secret: bool = False) -> str:
@@ -201,7 +195,6 @@ def _rewrite_loopback_url_for_camofox(url: str) -> tuple[str, Optional[Dict[str,
camofox_cfg = _get_camofox_config()
if not _flag("CAMOFOX_REWRITE_LOOPBACK_URLS", camofox_cfg, "rewrite_loopback_urls"):
return url, None
-
try:
parsed = urlsplit(url)
except ValueError:
@@ -209,21 +202,16 @@ def _rewrite_loopback_url_for_camofox(url: str) -> tuple[str, Optional[Dict[str,
alias = _env_or_cfg("CAMOFOX_LOOPBACK_HOST_ALIAS", camofox_cfg, "loopback_host_alias") or "host.docker.internal"
if parsed.scheme not in {"http", "https"} or not _is_loopback_hostname(parsed.hostname) or not alias:
return url, None
-
- userinfo = ""
- if parsed.username:
- userinfo = parsed.username + (f":{parsed.password}" if parsed.password else "") + "@"
+ userinfo = (parsed.username + (f":{parsed.password}" if parsed.password else "") + "@") if parsed.username else ""
host_part = f"[{alias}]" if ":" in alias and not alias.startswith("[") else alias
port_part = f":{parsed.port}" if parsed.port else ""
rewritten = urlunsplit(
- SplitResult(parsed.scheme, f"{userinfo}{host_part}{port_part}", parsed.path, parsed.query, parsed.fragment)
- )
+ SplitResult(parsed.scheme, f"{userinfo}{host_part}{port_part}", parsed.path, parsed.query, parsed.fragment))
return rewritten, {"from": parsed.hostname or "", "to": alias, "original_url": url, "rewritten_url": rewritten}
# ---- Session management ----
-# Maps task_id -> {"user_id": str, "tab_id": str|None, ...}
-_sessions: Dict[str, Dict[str, Any]] = {}
+_sessions: Dict[str, Dict[str, Any]] = {} # task_id -> {"user_id": str, "tab_id": str|None, ...}
_sessions_lock = threading.Lock()
@@ -232,15 +220,12 @@ def _adopt_existing_tab(session: Dict[str, Any]) -> Dict[str, Any]:
in-memory cache while Camofox still holds the integration-owned tab."""
if session.get("tab_id") or not session.get("adopt_existing_tab") or not get_camofox_url():
return session
-
try:
tabs = _get("/tabs", params=_user_params(session), timeout=5).get("tabs", [])
except Exception as exc:
logger.debug("Camofox tab adoption failed for %s: %s", session.get("user_id"), exc)
return session
- if not isinstance(tabs, list):
- return session
- dict_tabs = [tab for tab in tabs if isinstance(tab, dict)]
+ dict_tabs = [tab for tab in tabs if isinstance(tab, dict)] if isinstance(tabs, list) else []
candidates = [tab for tab in dict_tabs if tab.get("listItemId") == session.get("session_key")] or dict_tabs
tab_id = candidates[-1].get("tabId") if candidates else None
if isinstance(tab_id, str) and tab_id:
@@ -257,7 +242,6 @@ def _get_session(task_id: Optional[str]) -> Dict[str, Any]:
with _sessions_lock:
if task_id in _sessions:
return _adopt_existing_tab(_sessions[task_id])
-
camofox_cfg = _get_camofox_config()
identity = _camofox_identity_override(task_id, camofox_cfg)
if identity is None and _managed_persistence_enabled(camofox_cfg):
@@ -276,10 +260,9 @@ def _get_session(task_id: Optional[str]) -> Dict[str, Any]:
def _ensure_tab(task_id: Optional[str], url: str = "about:blank") -> Dict[str, Any]:
"""Ensure a tab exists for the session, creating one if needed."""
session = _get_session(task_id)
- if session["tab_id"]:
- return session
- data = _post("/tabs", {"userId": session["user_id"], "listItemId": session["session_key"], "url": url})
- session["tab_id"] = data.get("tabId")
+ if not session["tab_id"]:
+ data = _post("/tabs", {"userId": session["user_id"], "listItemId": session["session_key"], "url": url})
+ session["tab_id"] = data.get("tabId")
return session
@@ -302,12 +285,10 @@ def camofox_soft_cleanup(task_id: Optional[str] = None) -> bool:
# ---- HTTP helpers ----
-
def _request(method: str, path: str, timeout: Optional[int] = None, **kwargs: Any) -> requests.Response:
"""Issue an authenticated request to camofox and return the raised-for-status response."""
- if timeout is None:
- timeout = _get_command_timeout()
- resp = getattr(requests, method)(f"{get_camofox_url()}{path}", timeout=timeout, headers=_auth_headers(), **kwargs)
+ resp = getattr(requests, method)(f"{get_camofox_url()}{path}", headers=_auth_headers(),
+ timeout=_get_command_timeout() if timeout is None else timeout, **kwargs)
resp.raise_for_status()
return resp
@@ -330,7 +311,6 @@ def _delete(path: str, body: dict = None, timeout: Optional[int] = None) -> dict
# ---- Tool implementations ----
-
def _tab_path(session: Dict[str, Any], suffix: str) -> str:
return f"/tabs/{session['tab_id']}/{suffix}"
@@ -353,9 +333,8 @@ def _parse_snapshot_images(snapshot: str) -> list[Dict[str, str]]:
if not stripped.startswith(("- img ", "img ")):
continue
alt_match = re.search(r'img\s+"([^"]*)"', stripped)
- alt = alt_match.group(1) if alt_match else ""
url_match = re.search(r'/url:\s*(\S+)', lines[i + 1].strip()) if i + 1 < len(lines) else None
- src = url_match.group(1) if url_match else ""
+ alt, src = (alt_match.group(1) if alt_match else ""), (url_match.group(1) if url_match else "")
if alt or src:
images.append({"src": src, "alt": alt})
return images
@@ -365,10 +344,9 @@ def _fetch_snapshot(session: Dict[str, Any]) -> tuple[str, int]:
"""``(snapshot_text, refs_count)`` truncated like the main browser tool (line boundaries,
full tree stored to cache/web, read_file pointer appended). Lazy import: ``browser_tool``
imports this module."""
- data = _snapshot_data(session)
- snapshot = data.get("snapshot", "")
from tools.browser_tool import _truncate_snapshot, get_browser_snapshot_threshold
- threshold = get_browser_snapshot_threshold()
+ data = _snapshot_data(session)
+ snapshot, threshold = data.get("snapshot", ""), get_browser_snapshot_threshold()
if len(snapshot) > threshold:
snapshot = _truncate_snapshot(snapshot, max_chars=threshold)
return snapshot, data.get("refsCount", 0)
@@ -386,13 +364,10 @@ def _navigate_tab(task_id: Optional[str], browser_url: str) -> tuple[Dict[str, A
except requests.HTTPError as e:
if e.response is None or e.response.status_code != 404:
raise
- logger.warning(
- "Camofox tab %s returned 404 — tab was garbage collected. Creating a fresh tab.",
- session["tab_id"],
- )
+ logger.warning("Camofox tab %s returned 404 — tab was garbage collected. Creating a fresh tab.",
+ session["tab_id"])
session["tab_id"] = None
- session = _ensure_tab(task_id, browser_url)
- return session, {"ok": True, "url": browser_url}
+ return _ensure_tab(task_id, browser_url), {"ok": True, "url": browser_url}
def camofox_navigate(url: str, task_id: Optional[str] = None) -> str:
@@ -402,8 +377,7 @@ def camofox_navigate(url: str, task_id: Optional[str] = None) -> str:
session, data = _navigate_tab(task_id, browser_url)
result = {"success": True, "url": data.get("url", browser_url), "title": data.get("title", "")}
if rewrite_info:
- result["requested_url"] = url
- result["url_rewrite"] = rewrite_info
+ result["requested_url"], result["url_rewrite"] = url, rewrite_info
result["warning"] = ("Rewrote loopback URL for Docker-hosted Camofox: "
f"{rewrite_info['from']} -> {rewrite_info['to']}")
vnc = get_vnc_url()
@@ -411,13 +385,10 @@ def camofox_navigate(url: str, task_id: Optional[str] = None) -> str:
result["vnc_url"] = vnc
result["vnc_hint"] = ("Browser is visible via VNC. "
"Share this link with the user so they can watch the browser live.")
-
- # Auto-take a compact snapshot so the model can act immediately.
- try:
+ try: # Auto-take a compact snapshot so the model can act immediately.
result["snapshot"], result["element_count"] = _fetch_snapshot(session)
except Exception:
pass # Navigation succeeded; snapshot is a bonus
-
return json.dumps(result)
except requests.HTTPError as e:
return tool_error(f"Navigation failed: {e}", success=False)
@@ -454,9 +425,7 @@ def _require_tab(task_id: Optional[str], action: Optional[str] = None) -> tuple[
session = _get_session(task_id)
if not session["tab_id"]:
return session, tool_error(_NO_SESSION_ERROR, success=False)
- if action is not None:
- return session, _camofox_private_page_block(session, task_id, action)
- return session, None
+ return session, (_camofox_private_page_block(session, task_id, action) if action is not None else None)
def _with_tab(task_id: Optional[str], guard_action: Optional[str], body: Callable[[Dict[str, Any]], str]) -> str:
@@ -575,7 +544,6 @@ def camofox_vision(question: str, annotate: bool = False, task_id: Optional[str]
resp = _get_raw(_tab_path(session, "screenshot"), params=_user_params(session))
screenshot_path = _save_screenshot(resp.content)
img_b64 = base64.b64encode(resp.content).decode("utf-8")
-
annotation_context = ""
if annotate:
try:
@@ -583,22 +551,17 @@ def camofox_vision(question: str, annotate: bool = False, task_id: Optional[str]
annotation_context = f"\n\nAccessibility tree (element refs for interaction):\n{snapshot[:3000]}"
except Exception:
pass
-
- # The screenshot itself cannot be redacted, but the text-based accessibility
- # snippet sent alongside it must not leak secret values.
+ # The screenshot itself cannot be redacted, but the text-based accessibility snippet
+ # sent alongside it must not leak secret values.
from agent.redact import redact_sensitive_text
- annotation_context = redact_sensitive_text(annotation_context)
-
from agent.auxiliary_client import call_llm
- vision_prompt = f"Analyze this browser screenshot and answer: {question}{annotation_context}"
+ vision_prompt = f"Analyze this browser screenshot and answer: {question}{redact_sensitive_text(annotation_context)}"
timeout, temperature = _vision_llm_settings()
response = call_llm(
messages=[{"role": "user", "content": [
{"type": "text", "text": vision_prompt},
- {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_b64}"}},
- ]}],
- task="vision", temperature=temperature, timeout=timeout,
- )
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_b64}"}}]}],
+ task="vision", temperature=temperature, timeout=timeout)
analysis = (response.choices[0].message.content or "").strip() if response.choices else ""
# Redact secrets the vision LLM may have read from the screenshot.
return json.dumps({"success": True, "analysis": redact_sensitive_text(analysis), "screenshot_path": screenshot_path})
@@ -610,5 +573,4 @@ def camofox_console(clear: bool = False, task_id: Optional[str] = None) -> str:
return json.dumps({
"success": True, "console_messages": [], "js_errors": [], "total_messages": 0, "total_errors": 0,
"note": "Console log capture is not available with the Camofox backend. "
- "Use browser_snapshot or browser_vision to inspect page state.",
- })
+ "Use browser_snapshot or browser_vision to inspect page state."})
diff --git a/tools/browser_cdp_tool.py b/tools/browser_cdp_tool.py
index f39cf15c951..e31d675f7a6 100644
--- a/tools/browser_cdp_tool.py
+++ b/tools/browser_cdp_tool.py
@@ -32,20 +32,16 @@ _CDP_PRIVATE_PAGE_ALLOWED_METHODS = {
# spans inside such payloads and corrupt the decoded bytes; the payload is not free text
# the model reads, so redaction protects no secret there.
_CDP_ALWAYS_BINARY_PATHS: Dict[str, tuple] = {
- "Page.captureScreenshot": (("data",),),
- "Page.printToPDF": (("data",),),
- "Network.streamResourceContent": (("bufferedData",),),
- "HeadlessExperimental.beginFrame": (("screenshotData",),),
+ "Page.captureScreenshot": (("data",),), "Page.printToPDF": (("data",),),
+ "Network.streamResourceContent": (("bufferedData",),), "HeadlessExperimental.beginFrame": (("screenshotData",),),
"CacheStorage.requestCachedResponse": (("response", "body"),),
}
# method → result paths that are opaque base64 ONLY when the carrying dict has a
# ``base64Encoded`` sibling that is exactly ``True``; otherwise text → redacted.
_CDP_FLAGGED_BINARY_PATHS: Dict[str, tuple] = {
- "Network.getResponseBody": (("body",),),
- "Fetch.getResponseBody": (("body",),),
- "IO.read": (("data",),),
- "Network.getRequestPostData": (("postData",),),
+ "Network.getResponseBody": (("body",),), "Fetch.getResponseBody": (("body",),),
+ "IO.read": (("data",),), "Network.getRequestPostData": (("postData",),),
}
@@ -58,7 +54,6 @@ def _redact_cdp_output(value: Any, *, always_paths: tuple = (), flagged_paths: t
``Runtime.evaluate`` by-value object could spoof.
"""
from agent.redact import redact_sensitive_text
-
if isinstance(value, str):
return redact_sensitive_text(value, force=True)
if isinstance(value, (list, tuple)):
@@ -66,22 +61,15 @@ def _redact_cdp_output(value: Any, *, always_paths: tuple = (), flagged_paths: t
if not isinstance(value, dict):
return value
base64_flagged = value.get("base64Encoded") is True
-
def leaf(paths: tuple, key: str) -> bool:
return any(len(p) == 1 and p[0] == key for p in paths)
-
def descend(paths: tuple, key: str) -> tuple:
return tuple(p[1:] for p in paths if len(p) > 1 and p[0] == key)
-
redacted: Dict[str, Any] = {}
for key, item in value.items():
opaque = leaf(always_paths, key) or (leaf(flagged_paths, key) and base64_flagged)
- if isinstance(item, str) and opaque:
- redacted[key] = item
- else:
- redacted[key] = _redact_cdp_output(
- item, always_paths=descend(always_paths, key), flagged_paths=descend(flagged_paths, key),
- )
+ redacted[key] = item if isinstance(item, str) and opaque else _redact_cdp_output(
+ item, always_paths=descend(always_paths, key), flagged_paths=descend(flagged_paths, key))
return redacted
@@ -105,7 +93,6 @@ def _run_async(coro):
loop = None
if loop and loop.is_running():
import concurrent.futures
-
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
return pool.submit(asyncio.run, coro).result()
return asyncio.run(coro)
@@ -115,7 +102,6 @@ def _resolve_cdp_endpoint() -> str:
"""Normalized CDP WebSocket URL via ``browser_tool._get_cdp_override``, or ""."""
try:
from tools.browser_tool import _get_cdp_override # type: ignore[import-not-found]
-
return (_get_cdp_override() or "").strip()
except Exception as exc: # pragma: no cover — defensive
logger.debug("browser_cdp: failed to resolve CDP endpoint: %s", exc)
@@ -129,7 +115,6 @@ def _blocked(message: str, method: str) -> str:
def _navigate_private_target(bt: Any, params: Dict[str, Any]) -> Optional[str]:
"""Blocked URL literal for ``Page.navigate`` params, else ``None``."""
from tools.browser_tool_eval_policy import _url_blocked
-
target_url = str(params.get("url") or "").strip()
return target_url if target_url and _url_blocked(bt, target_url) else None
@@ -152,7 +137,6 @@ def _browser_cdp_private_guard(*, task_id: str, method: str, params: Dict[str, A
"""
try:
from tools import browser_tool as bt # type: ignore[import-not-found]
-
if not bt._eval_ssrf_guard_active(task_id): # type: ignore[attr-defined]
return None
guard = _METHOD_PARAM_GUARDS.get(method)
@@ -164,27 +148,18 @@ def _browser_cdp_private_guard(*, task_id: str, method: str, params: Dict[str, A
if method not in _CDP_PRIVATE_PAGE_ALLOWED_METHODS:
blocked_url = bt._current_page_private_url(task_id) # type: ignore[attr-defined]
if blocked_url:
- return _blocked(
- "Blocked: page URL targets a private or internal address "
- f"({blocked_url}). Raw CDP method {method!r} could expose private "
- "page content or state.",
- method,
- )
+ return _blocked(f"Blocked: page URL targets a private or internal address ({blocked_url}). "
+ f"Raw CDP method {method!r} could expose private page content or state.", method)
except Exception as exc: # noqa: BLE001
logger.debug("browser_cdp: private-page guard probe failed: %s", exc)
return None
-async def _cdp_call(
- ws_url: str, method: str, params: Dict[str, Any], target_id: Optional[str], timeout: float,
-) -> Dict[str, Any]:
- """Make a single CDP call, optionally attaching to a target first.
-
- With ``target_id``, ``Target.attachToTarget(flatten=True)`` multiplexes a page-level
- session over the browser-level WebSocket; without it ``method`` runs at browser level.
- """
+async def _cdp_call(ws_url: str, method: str, params: Dict[str, Any], target_id: Optional[str],
+ timeout: float) -> Dict[str, Any]:
+ """Make a single CDP call. With ``target_id``, ``Target.attachToTarget(flatten=True)`` multiplexes a
+ page-level session over the browser-level WebSocket; without it ``method`` runs at browser level."""
assert websockets is not None # guarded by _WS_AVAILABLE at call-site
-
# max_size=None: CDP responses (e.g. DOM.getDocument) can be large; ping_interval=None: CDP
# servers don't expect pings.
async with websockets.connect(ws_url, max_size=None, open_timeout=timeout, close_timeout=5,
@@ -193,8 +168,7 @@ async def _cdp_call(
async def _send(req: Dict[str, Any], what: str) -> Dict[str, Any]:
nonlocal next_id
- call_id = next_id
- next_id += 1
+ call_id, next_id = next_id, next_id + 1
await ws.send(json.dumps({"id": call_id, **req}))
deadline = asyncio.get_running_loop().time() + timeout
while True: # ignore events / out-of-order responses
@@ -222,9 +196,8 @@ async def _cdp_call(
return msg.get("result", {})
-def _browser_cdp_via_supervisor(
- task_id: str, frame_id: str, method: str, params: Optional[Dict[str, Any]], timeout: float,
-) -> str:
+def _browser_cdp_via_supervisor(task_id: str, frame_id: str, method: str, params: Optional[Dict[str, Any]],
+ timeout: float) -> str:
"""Route a CDP call through the live supervisor session for an OOPIF frame."""
try:
from tools.browser_supervisor import SUPERVISOR_REGISTRY # type: ignore[import-not-found]
@@ -241,19 +214,16 @@ def _browser_cdp_via_supervisor(
tree = supervisor.snapshot().frame_tree
frame_info: Optional[Dict[str, Any]] = next(
(f for f in [tree.get("top"), *(tree.get("children") or [])] if f and f.get("frame_id") == frame_id), None)
- if frame_info is None:
- # frame_tree is capped at 30 entries — check the raw frames dict too.
+ if frame_info is None: # frame_tree is capped at 30 entries — check the raw frames dict too.
with supervisor._state_lock: # type: ignore[attr-defined]
raw = supervisor._frames.get(frame_id) # type: ignore[attr-defined]
- if raw is not None:
- frame_info = raw.to_dict()
+ frame_info = raw.to_dict() if raw is not None else None
if frame_info is None:
return tool_error(f"frame_id {frame_id!r} not found in supervisor state. "
"Call browser_snapshot to see current frame_tree.")
child_sid = frame_info.get("session_id")
- if not child_sid:
- # Same-origin iframes have no dedicated session; reach them via contentWindow/contentDocument.
+ if not child_sid: # same-origin iframes have no dedicated session; reach them via contentWindow/contentDocument
return tool_error(f"frame_id {frame_id!r} is not an out-of-process iframe (no dedicated CDP session). "
"For same-origin iframes, use `browser_cdp(method='Runtime.evaluate', params={'expression': "
"\"document.querySelector('iframe').contentDocument.title\"})` at the top-level page instead.")
@@ -276,22 +246,13 @@ def _browser_cdp_via_supervisor(
"result": result_msg.get("result", {})}, ensure_ascii=False)
-def browser_cdp(
- method: str,
- params: Optional[Dict[str, Any]] = None,
- target_id: Optional[str] = None,
- frame_id: Optional[str] = None,
- timeout: float = 30.0,
- task_id: Optional[str] = None,
-) -> str:
- """Send a raw CDP command (see ``CDP_DOCS_URL``).
-
- ``target_id`` attaches a fresh stateless connection to a tab; ``frame_id`` (OOPIF from
- ``browser_snapshot.frame_tree``) routes through the supervisor's live WebSocket instead
- — the only reliable way to evaluate inside an iframe where fresh per-call connections
- hit signed-URL expiry (Browserbase). Both paths share the same private-page/SSRF guard.
- Returns JSON ``{"success": True, "method", "result"}`` or ``{"error": ...}``.
- """
+def browser_cdp(method: str, params: Optional[Dict[str, Any]] = None, target_id: Optional[str] = None,
+ frame_id: Optional[str] = None, timeout: float = 30.0, task_id: Optional[str] = None) -> str:
+ """Send a raw CDP command (see ``CDP_DOCS_URL``). ``target_id`` attaches a fresh stateless connection
+ to a tab; ``frame_id`` (OOPIF from ``browser_snapshot.frame_tree``) routes through the supervisor's live
+ WebSocket instead — the only reliable way to evaluate inside an iframe where fresh per-call connections
+ hit signed-URL expiry (Browserbase). Both paths share the same private-page/SSRF guard. Returns JSON
+ ``{"success": True, "method", "result"}`` or ``{"error": ...}``."""
effective_task_id = task_id or "default"
if frame_id:
@@ -328,7 +289,6 @@ def browser_cdp(
except (TypeError, ValueError):
safe_timeout = 30.0
safe_timeout = max(1.0, min(safe_timeout, 300.0))
-
try:
result = _run_async(_cdp_call(endpoint, method, call_params, target_id, safe_timeout))
except asyncio.TimeoutError as exc:
@@ -413,10 +373,7 @@ def _browser_cdp_check() -> bool:
surfaced). Raw (no-I/O) gate: check_fns run at every startup, and resolving the endpoint
over HTTP here would block launch on a stale endpoint."""
try:
- from tools.browser_tool import ( # type: ignore[import-not-found]
- _get_cdp_override_raw,
- check_browser_requirements,
- )
+ from tools.browser_tool import _get_cdp_override_raw, check_browser_requirements # type: ignore[import-not-found]
except ImportError as exc: # pragma: no cover — defensive
logger.debug("browser_cdp check: browser_tool import failed: %s", exc)
return False
diff --git a/tools/browser_lightpanda.py b/tools/browser_lightpanda.py
index b8418d3aec3..af44f29ab90 100644
--- a/tools/browser_lightpanda.py
+++ b/tools/browser_lightpanda.py
@@ -41,8 +41,7 @@ class LightpandaServer:
@property
def cdp_url(self) -> str:
- # HTTP discovery URL; the browser-use harness resolves /json/version itself.
- return f"http://127.0.0.1:{self.port}"
+ return f"http://127.0.0.1:{self.port}" # HTTP discovery URL; the harness resolves /json/version itself
def is_alive(self) -> bool:
return self.proc.poll() is None
diff --git a/tools/browser_tool_cdp.py b/tools/browser_tool_cdp.py
index ec4dbf38f35..d7000628c43 100644
--- a/tools/browser_tool_cdp.py
+++ b/tools/browser_tool_cdp.py
@@ -34,7 +34,6 @@ def _resolve_cdp_override(cdp_url: str) -> str:
san = _bt._sanitize_url_for_logs
try:
import requests # lazy — shared module object, test patches still apply
-
response = requests.get(version_url, timeout=10)
response.raise_for_status()
payload = response.json()
@@ -76,11 +75,9 @@ def _get_dialog_policy_config() -> Tuple[str, float]:
_bt = _origin()
# Deferred so browser_tool imports in minimal environments.
from tools.browser_supervisor 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):
@@ -120,7 +117,6 @@ def _ensure_cdp_supervisor(task_id: str) -> None:
return
try:
from tools.browser_supervisor import SUPERVISOR_REGISTRY # type: ignore[import-not-found]
-
policy, timeout_s = _bt._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:
@@ -131,7 +127,6 @@ 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)
diff --git a/tools/browser_tool_cloud.py b/tools/browser_tool_cloud.py
index 46d9b6d9185..3364811f0a8 100644
--- a/tools/browser_tool_cloud.py
+++ b/tools/browser_tool_cloud.py
@@ -35,7 +35,6 @@ def _ensure_browser_plugins_loaded() -> None:
"""Idempotently trigger plugin discovery (standalone scripts/tests may never import ``model_tools``)."""
try:
from hermes_cli.plugins import _ensure_plugins_discovered
-
_ensure_plugins_discovered()
except Exception as exc:
_origin().logger.debug("Browser plugin discovery failed (non-fatal): %s", exc)
@@ -58,13 +57,11 @@ def _get_cloud_provider() -> Optional[CloudBrowserProvider]:
_bt._cloud_provider_resolved = True
_bt._cached_cloud_provider_scope = scope
return _bt._cached_cloud_provider
-
_bt._cached_cloud_provider = None
_bt._cloud_provider_resolved = False
resolved = _bt._resolve_cloud_provider_uncached()
after_generation = _bt._browser_registry_generation(scope=scope)
- if before_generation != after_generation:
- # A force reload changed this profile's registry mid-resolution: discard and resolve again.
+ if before_generation != after_generation: # force reload mid-resolution: discard, resolve again
continue
if _bt._cloud_provider_resolved:
_bt._cached_cloud_provider_scope = scope
@@ -91,7 +88,6 @@ def _instantiate_explicit_cloud_provider(provider_key: str) -> Optional[CloudBro
resolved = _bt._registry_get_browser_provider(provider_key)
if resolved is None:
from tools.tool_backend_helpers import selection_error
-
raise ValueError(selection_error(
"browser", f"'{provider_key}'",
"no registered browser plugin has that name (install the corresponding plugin or fix the config key spelling)",
@@ -186,7 +182,6 @@ def _is_local_backend() -> bool:
return False
# Scope-aware: under gateway multiplexing the routed profile's terminal backend lives in the per-turn scope.
from tools.terminal_scope import terminal_env
-
return terminal_env("TERMINAL_ENV", "local").strip().lower() in ("local", "")
@@ -197,7 +192,6 @@ def _get_browser_engine() -> str:
navigation but has no graphical renderer (no screenshots).
"""
_bt = _origin()
-
def compute() -> str:
engine = _bt._browser_cfg("engine", "auto", lambda v: str(v).strip().lower() if v and str(v).strip() else "auto", "browser.engine from config")
if engine == "auto":
@@ -208,18 +202,15 @@ def _get_browser_engine() -> str:
_bt.logger.warning("Unknown browser engine %r (valid: %s), falling back to 'auto'", engine, ", ".join(sorted(_VALID_ENGINES)))
engine = "auto"
return engine
-
return _memo(_bt, "_browser_engine_resolved", "_cached_browser_engine", compute)
def _is_headed_mode() -> bool:
"""True when the browser should launch headed: ``browser.headed``, else ``AGENT_BROWSER_HEADED``; cached."""
_bt = _origin()
-
def compute() -> bool:
headed = _bt._browser_cfg("headed", False, lambda v: False if v is None else str(v).strip().lower() in ("true", "1", "yes"), "browser.headed from config")
return headed or os.environ.get("AGENT_BROWSER_HEADED", "").strip().lower() in ("true", "1", "yes")
-
return _memo(_bt, "_headed_mode_resolved", "_cached_headed_mode", compute)
diff --git a/tools/browser_tool_eval_policy.py b/tools/browser_tool_eval_policy.py
index 72f8c958905..6059b6adfc9 100644
--- a/tools/browser_tool_eval_policy.py
+++ b/tools/browser_tool_eval_policy.py
@@ -66,7 +66,6 @@ _RISKY_BROWSER_EVAL_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
(re.compile(r"\bquerySelector(?:All)?\s*\([^)]*(?:input|textarea|password)[^)]*\).*\bvalue\b", re.I | re.S), "form value extraction"),
)
-
_JS_STRING_LITERAL_RE = re.compile(r"""'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\"|`(?:\\.|[^`\\])*`""", re.S)
diff --git a/tools/browser_tool_install.py b/tools/browser_tool_install.py
index 54d47338f9f..e0a422edb60 100644
--- a/tools/browser_tool_install.py
+++ b/tools/browser_tool_install.py
@@ -115,20 +115,21 @@ def _find_agent_browser(*, validate: bool = True) -> str:
_bt = _origin()
def _not_found(cached: bool) -> FileNotFoundError:
- return FileNotFoundError(f"agent-browser CLI not found{' (cached)' if cached else ''}. Install it with: {_bt._browser_install_hint()}\nOr ensure npx is available in your PATH.")
-
- if _bt._agent_browser_resolved:
- if _bt._cached_agent_browser is None:
- raise _not_found(cached=True)
- return _bt._cached_agent_browser
+ return FileNotFoundError(f"agent-browser CLI not found{' (cached)' if cached else ''}. Install it with: "
+ f"{_bt._browser_install_hint()}\nOr ensure npx is available in your PATH.")
def _accept(candidate: str) -> str:
- # Set resolved at each accept site (not before the search) so a concurrent reader never sees resolved=True with a None cache.
+ # Set resolved at each accept site (not before the search) so a concurrent reader never sees
+ # resolved=True with a None cache.
if validate:
_bt._cached_agent_browser = candidate
_bt._agent_browser_resolved = True
return candidate
+ if _bt._agent_browser_resolved:
+ if _bt._cached_agent_browser is None:
+ raise _not_found(cached=True)
+ return _bt._cached_agent_browser
ok = _bt.agent_browser_runnable if validate else _bt._agent_browser_candidate_present
extended_path = _bt._merge_browser_path("")
for candidate in _bt._agent_browser_candidates(extended_path):
@@ -139,9 +140,7 @@ def _find_agent_browser(*, validate: bool = True) -> str:
return _accept(_bt.NPX_AGENT_BROWSER_SENTINEL)
if not validate:
raise FileNotFoundError("agent-browser CLI not found")
-
- # Nothing found — try lazy installation before giving up.
- try:
+ try: # Nothing found — try lazy installation before giving up.
from hermes_cli.dep_ensure import ensure_dependency
if ensure_dependency("browser"):
home = _bt.get_hermes_home()
@@ -152,7 +151,6 @@ def _find_agent_browser(*, validate: bool = True) -> str:
return _accept(recheck)
except Exception:
pass
-
_bt._agent_browser_resolved = True
raise _not_found(cached=False)
diff --git a/tools/browser_tool_real_profile.py b/tools/browser_tool_real_profile.py
index 35745324bb9..f3a62e87465 100644
--- a/tools/browser_tool_real_profile.py
+++ b/tools/browser_tool_real_profile.py
@@ -172,7 +172,6 @@ def _attach_agent_browser_to_real_profile(port: int, copy_dir: str) -> Tuple[Opt
if proc.returncode != 0:
tail = (proc.stderr or proc.stdout or "").strip().splitlines()
return None, f"{_RP}the real-profile browser failed to start: {tail[-1] if tail else f'exit {proc.returncode}'}"
-
cdp = _bt._agent_browser_get_cdp(_bt._REAL_PROFILE_SESSION)
our_port = _read_devtools_port(copy_dir)
if our_port is not None and (m := re.search(r":(\d+)", cdp or "")) and m.group(1) != our_port:
diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.py
index 2cbefa02e70..8d4ea52a3c3 100644
--- a/tools/browser_use_cli.py
+++ b/tools/browser_use_cli.py
@@ -120,10 +120,9 @@ def _export_session_cdp(env: dict, get_session_info: Callable[[str], Any], cache
fail_msg: Callable[[Exception], str], no_cdp_msg: str) -> Optional[str]:
"""Export the CDP endpoint from ``get_session_info(cache_key)``; error string on failure / no CDP."""
try:
- session_info = get_session_info(cache_key)
+ cdp = str((get_session_info(cache_key) or {}).get("cdp_url") or "")
except Exception as e:
return fail_msg(e)
- cdp = str((session_info or {}).get("cdp_url") or "")
if not cdp:
return no_cdp_msg
_set_cdp_env(env, cdp)
@@ -133,11 +132,7 @@ def _export_session_cdp(env: dict, get_session_info: Callable[[str], Any], cache
def _blocked_url_in_code(code: str) -> Optional[str]:
"""Return an error if a URL literal fails the built-in navigation checks."""
from tools.browser_tool import evaluate_url_safety
- for url in _URL_RE.findall(code or ""):
- err = evaluate_url_safety(url)
- if err:
- return err.get("error", "Blocked: unsafe URL")
- return None
+ return next((err.get("error", "Blocked: unsafe URL") for err in map(evaluate_url_safety, _URL_RE.findall(code or "")) if err), None)
def _base_subprocess_env() -> dict:
@@ -163,8 +158,7 @@ def _floor_subprocess_path(path: str) -> str:
from tools.browser_tool import _merge_browser_path
return _merge_browser_path(path or "")
parts = [p for p in (path or "").split(os.pathsep) if p]
- parts.extend(d for d in _FHS_BIN_DIRS if d not in set(parts) and os.path.isdir(d))
- return os.pathsep.join(parts)
+ return os.pathsep.join(parts + [d for d in _FHS_BIN_DIRS if d not in set(parts) and os.path.isdir(d)])
def _read_browser_cfg() -> dict:
@@ -186,9 +180,7 @@ def get_browser_backend() -> str:
"""Configured browser backend key ("" = unset → default). YAML 1.1 parses an
unquoted ``off`` as False — that must mean BACKEND_DISABLED, not "unset"."""
raw = _read_browser_cfg().get("backend")
- if isinstance(raw, bool):
- return BACKEND_DISABLED if raw is False else ""
- return str(raw or "").strip().lower()
+ return (BACKEND_DISABLED if raw is False else "") if isinstance(raw, bool) else str(raw or "").strip().lower()
def is_legacy_browser_use_cloud_config(browser_cfg: dict) -> bool:
@@ -211,9 +203,7 @@ def is_browser_use_cli_mode() -> bool:
if _camofox_active():
return False
backend = get_browser_backend()
- if backend:
- return backend == _BACKEND_KEY
- return is_legacy_browser_use_cloud_config(_read_browser_cfg()) or _find_cli() is not None
+ return backend == _BACKEND_KEY if backend else (is_legacy_browser_use_cloud_config(_read_browser_cfg()) or _find_cli() is not None)
def default_downgrade_notice() -> Optional[str]:
@@ -273,7 +263,6 @@ def install_cli(timeout_s: int = 600) -> Tuple[bool, str]:
def _managed_uv() -> Optional[str]:
from hermes_cli.managed_uv import ensure_uv
return str(ensure_uv() or "") or None
-
uv_bin = _quiet(_managed_uv, None, "Managed uv bootstrap unavailable") or shutil.which("uv")
if not uv_bin:
return False, ("uv is not available and could not be bootstrapped. Install uv "
@@ -296,7 +285,6 @@ def install_cli(timeout_s: int = 600) -> Tuple[bool, str]:
if result.returncode != 0:
tail = "\n".join((result.stderr or result.stdout or "").strip().splitlines()[-3:])
return False, f"`uv tool install browser-use` failed:\n{tail}"
-
found = _find_cli()
if not found or len(found) != 1:
return False, ("install reported success but the browser-use binary is still not resolvable — "
@@ -306,9 +294,8 @@ def install_cli(timeout_s: int = 600) -> Tuple[bool, str]:
def _workspace_dir(task_id: Optional[str]) -> Optional[str]:
"""Stable per-task scratch dir that persists across browser_exec calls"""
- existing = os.environ.get("BH_AGENT_WORKSPACE")
- if existing:
- return existing
+ if os.environ.get("BH_AGENT_WORKSPACE"):
+ return os.environ["BH_AGENT_WORKSPACE"]
try:
safe = _TASK_ID_SAFE_RE.sub("_", str(task_id or "default"))[:80] or "default"
path = Path(get_hermes_home()) / "cache" / "browser-use" / "workspace" / safe
@@ -336,7 +323,6 @@ def _native_screenshot_result(result: Dict[str, Any], path: str) -> Optional[Dic
try:
from tools.vision_tools import (_EMBED_MAX_DIMENSION, _EMBED_TARGET_BYTES,
_resize_image_for_vision, _should_use_native_vision_fast_path)
-
if not _should_use_native_vision_fast_path():
return None
# History-reuse cap: this data URL bakes into the tool result and is re-sent every later turn —
@@ -345,12 +331,8 @@ def _native_screenshot_result(result: Dict[str, Any], path: str) -> Optional[Dic
max_dimension=_EMBED_MAX_DIMENSION, force_jpeg=True)
text = json.dumps(result, ensure_ascii=False)
attached = text + "\n\nThe screenshot from this call is attached — inspect it with your native vision."
- return {
- "_multimodal": True,
- "content": [{"type": "text", "text": attached}, {"type": "image_url", "image_url": {"url": data_url}}],
- "text_summary": text,
- "meta": {"screenshot_path": path, "native_vision": True},
- }
+ return {"_multimodal": True, "text_summary": text, "meta": {"screenshot_path": path, "native_vision": True},
+ "content": [{"type": "text", "text": attached}, {"type": "image_url", "image_url": {"url": data_url}}]}
except Exception as e:
logger.debug("Native screenshot attach failed (falling back to text): %s", e)
return None
@@ -395,18 +377,15 @@ def _resolve_backend_cdp(env: dict, task_id: Optional[str], session_name: str =
"""
if _has_cdp_env(env):
return None
-
try:
from tools.browser_tool import _get_cdp_override, _get_cloud_provider, _get_session_info
except Exception as e: # pragma: no cover — stubbed browser_tool in tests
logger.debug("browser_tool backend resolution unavailable: %s", e)
return None
-
override = _quiet(_get_cdp_override, "")
if override:
_set_cdp_env(env, override)
return None
-
provider = _quiet(_get_cloud_provider, None, "Cloud provider lookup failed")
if provider is None:
return _resolve_lightpanda_cdp(env, task_id, session_name)
@@ -443,28 +422,22 @@ def _resolve_real_profile_cdp(env: dict, force_local: bool) -> Optional[str]:
returned so a consented user is never silently downgraded."""
if not _real_profile_consented() or _has_cdp_env(env):
return None
-
try:
from tools.browser_tool import _get_cdp_override_raw, _get_cloud_provider, _real_profile_cdp
except Exception as e: # pragma: no cover — stubbed browser_tool in tests
logger.debug("real-profile backend resolution unavailable: %s", e)
return None
-
if _quiet(_get_cdp_override_raw, ""):
return None
-
- # Only auto-upgrade genuinely-local attaches; any cloud path (provider, provider lookup
- # failure, or legacy BU cloud config) stays on its backend unless the model passes local=true.
+ # Only auto-upgrade genuinely-local attaches; any cloud path (provider, provider lookup failure, or
+ # legacy BU cloud config) stays on its backend unless the model passes local=true.
if not force_local and (_quiet(_get_cloud_provider, object()) is not None
or is_legacy_browser_use_cloud_config(_read_browser_cfg())):
return None
-
cdp, err = _real_profile_cdp()
- if err:
- return err
- if cdp:
+ if cdp and not err:
_set_cdp_env(env, cdp)
- return None
+ return err or None
def _route_backend(env: dict, session: str, task_id: Optional[str], local: bool) -> Optional[str]:
@@ -484,15 +457,12 @@ def _route_backend(env: dict, session: str, task_id: Optional[str], local: bool)
def _windows_popen_kwargs() -> dict:
"""Hide the console the .cmd shim would flash on Windows (as browser_tool does)."""
- if os.name != "nt":
- return {}
-
def _flags() -> dict:
from hermes_cli._subprocess_compat import windows_hide_flags
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return {"creationflags": windows_hide_flags(), "startupinfo": si}
- return _quiet(_flags, {}, "Windows hide-flags unavailable")
+ return _quiet(_flags, {}, "Windows hide-flags unavailable") if os.name == "nt" else {}
def _clamp_timeout(timeout_s: Any) -> int:
@@ -568,7 +538,6 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUT
stderr = stderr[:_STDERR_CAP_CHARS] + "\n… (stderr truncated)"
if stderr:
result["stderr"] = stderr
-
screenshot = _find_screenshot(proc.stdout, started)
if screenshot:
result["screenshot_path"] = screenshot
@@ -637,9 +606,8 @@ def _description_header() -> str:
if _lazy_call("tools.browser_tool", "lightpanda_engine_status", (False, ""),
"lightpanda engine status unavailable")[0]: # no screenshots, whatever the model sees
return _HEADER_BASE + _HEADER_TEXT_ONLY + _HEADER_LIGHTPANDA
- if _lazy_call("tools.vision_tools", "_should_use_native_vision_fast_path", False, ""):
- return _HEADER_BASE + _HEADER_VISION
- return _HEADER_BASE + _HEADER_TEXT_ONLY
+ vision = _lazy_call("tools.vision_tools", "_should_use_native_vision_fast_path", False, "")
+ return _HEADER_BASE + (_HEADER_VISION if vision else _HEADER_TEXT_ONLY)
def _dynamic_schema_overrides() -> dict: