The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(browser): vault/cdp/dialog run on browser_session + CDP only
Teknium3870e5a597ef
diff --git a/tools/browser_cdp_tool.py b/tools/browser_cdp_tool.pyindex 1ac5db764c2..5f1b4207eab 100644--- a/tools/browser_cdp_tool.py+++ b/tools/browser_cdp_tool.py@@ -2,9 +2,9 @@"""Raw Chrome DevTools Protocol (CDP) passthrough tool ``browser_cdp``.Sends arbitrary CDP commands to the browser's DevTools WebSocket when a CDP URL is-configured (``/browser connect`` → ``BROWSER_CDP_URL``, ``browser.cdp_url``, or a-CDP-backed cloud session). Escape hatch for operations the main browser tools don't-cover. Method reference: https://chromedevtools.github.io/devtools-protocol/+configured (``/browser connect`` → ``BROWSER_CDP_URL``, ``browser.cdp_url``). Escape hatch+for operations ``browser_exec``'s helpers don't cover. Method reference:+https://chromedevtools.github.io/devtools-protocol/"""from __future__ import annotations@@ -124,65 +124,75 @@ def _run_async(coro):def _resolve_cdp_endpoint() -> str:- """Normalized CDP WebSocket URL via ``browser_tool_cdp._get_cdp_override``, or ""."""- try:- from tools.browser_tool_cdp 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)- return ""+ """Normalized CDP WebSocket URL via ``browser_session_cdp.get_cdp_override``, or ""."""+ from tools.browser_session_cdp import get_cdp_override+ return (get_cdp_override() or "").strip()def _blocked(message: str, method: str) -> str:return tool_error(message, method=method, cdp_docs=CDP_DOCS_URL)-def _expression_private_target(expression: str) -> Optional[str]:- from tools.browser_tool_eval_policy import _expression_targets_private_url- return _expression_targets_private_url(expression)+def _expression_private_target(params: dict[str, Any]) -> Optional[str]:+ from tools.browser_url_policy import expression_targets_private_url+ return expression_targets_private_url(str(params.get("expression") or ""))-def _navigate_private_target(bt: Any, params: dict[str, Any]) -> Optional[str]:+def _navigate_private_target(params: dict[str, Any]) -> Optional[str]:"""Blocked URL literal for ``Page.navigate`` params, else ``None``."""- from tools.browser_tool_eval_policy import _url_blocked+ from tools.browser_url_policy import url_blockedtarget_url = str(params.get("url") or "").strip()- return target_url if target_url and _url_blocked(bt, target_url) else None+ return target_url if target_url and url_blocked(target_url) else None-# method → (probe(bt, params) -> blocked literal | None, error template)+# method → (probe(params) -> blocked literal | None, error template)_METHOD_PARAM_GUARDS = {"Page.navigate": (_navigate_private_target,"Blocked: CDP Page.navigate target is a private or internal address ({})."),- "Runtime.evaluate": (lambda bt, params: _expression_private_target(str(params.get("expression") or "")),+ "Runtime.evaluate": (_expression_private_target,"Blocked: CDP Runtime.evaluate expression targets a private or internal address ({})."),}-def _browser_cdp_private_guard(*, task_id: str, method: str, params: dict[str, Any]) -> Optional[str]:+def _current_page_private_url(endpoint: str, target_id: Optional[str]) -> Optional[str]:+ """URL of the page this call acts on (``target_id``'s, else the first page target) when it targets a+ private/internal address, else None. Read from ``Target.getTargets`` on the same endpoint; fail-open on+ probe failure, like the other page guards."""+ from tools.browser_url_policy import url_blocked+ if not endpoint or not _WS_AVAILABLE:+ return None+ try:+ infos = _run_async(_cdp_call(endpoint, "Target.getTargets", {}, None, 5.0)).get("targetInfos") or []+ except (TimeoutError, RuntimeError, OSError, WebSocketException) as exc:+ logger.debug("browser_cdp: page-URL probe failed: %s", exc)+ return None+ pages = [t for t in infos if t.get("type") == "page"]+ page = next((t for t in pages if t.get("targetId") == target_id), None) if target_id else (pages[:1] or [None])[0]+ url = str((page or {}).get("url") or "")+ return url if url and url_blocked(url) else None+++def _browser_cdp_private_guard(*, method: str, params: dict[str, Any], endpoint: str = "",+ target_id: Optional[str] = None) -> Optional[str]:"""Apply the browser SSRF/private-page guard to raw CDP calls.- Raw CDP shares the cloud/private-network boundary of ``browser_snapshot`` /- ``browser_console`` / ``browser_eval`` and must not become their bypass. Probes are- best-effort; a probe failure never breaks local/custom CDP workflows.+ Raw CDP shares the cloud/private-network boundary of ``browser_exec``'s URL policy and must not become+ its bypass. Probes are best-effort; a probe failure never breaks local/custom CDP workflows."""- try:- from tools import browser_tool as bt # type: ignore[import-not-found]- from tools import browser_tool_eval_policy as policy- if not policy._eval_ssrf_guard_active(task_id):- return None- guard = _METHOD_PARAM_GUARDS.get(method)- if guard is not None:- probe, template = guard- literal = probe(bt, params or {})- if literal:- return _blocked(template.format(literal), method)- if method not in _CDP_PRIVATE_PAGE_ALLOWED_METHODS:- blocked_url = policy._current_page_private_url(task_id)- if blocked_url:- 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:- logger.debug("browser_cdp: private-page guard probe failed: %s", exc)+ from tools.browser_url_policy import eval_ssrf_guard_active+ if not eval_ssrf_guard_active():+ return None+ guard = _METHOD_PARAM_GUARDS.get(method)+ if guard is not None:+ probe, template = guard+ literal = probe(params or {})+ if literal:+ return _blocked(template.format(literal), method)+ if method not in _CDP_PRIVATE_PAGE_ALLOWED_METHODS:+ blocked_url = _current_page_private_url(endpoint, target_id)+ if blocked_url:+ 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)return None@@ -239,9 +249,9 @@ def _browser_cdp_via_supervisor(task_id: str, frame_id: str, method: str, paramssupervisor = SUPERVISOR_REGISTRY.get(task_id)if supervisor is None:- return tool_error(f"No CDP supervisor is attached for task={task_id!r}. Call browser_navigate or "- "/browser connect first so the supervisor can attach. Once attached, browser_snapshot "- "will populate frame_tree with frame_ids you can pass here.")+ return tool_error(f"No CDP supervisor is attached for task={task_id!r}. Call browser_exec or "+ "/browser connect first so the supervisor can attach; Page.getFrameTree lists the "+ "frame ids you can pass here.")tree = supervisor.snapshot().frame_treeframe_info: Optional[dict[str, Any]] = next(@@ -252,7 +262,7 @@ def _browser_cdp_via_supervisor(task_id: str, frame_id: str, method: str, paramsframe_info = raw.to_dict() if raw is not None else Noneif 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.")+ "Call Page.getFrameTree to see the current frames.")child_sid = frame_info.get("session_id")if not child_sid: # same-origin iframes have no dedicated session; reach them via contentWindow/contentDocument@@ -281,14 +291,15 @@ def _browser_cdp_via_supervisor(task_id: str, frame_id: str, method: str, paramsdef 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+ to a tab; ``frame_id`` (an OOPIF from ``Page.getFrameTree``) routes through the supervisor's liveWebSocket instead — the only reliable way to evaluate inside an iframe where fresh per-call connectionshit 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:- blocked = _browser_cdp_private_guard(task_id=effective_task_id, method=method, params=params or {})+ blocked = _browser_cdp_private_guard(method=method, params=params or {},+ endpoint=_resolve_cdp_endpoint() if _WS_AVAILABLE else "")if blocked:return blockedreturn _browser_cdp_via_supervisor(task_id=effective_task_id, frame_id=frame_id, method=method,@@ -312,7 +323,7 @@ def browser_cdp(method: str, params: Optional[dict[str, Any]] = None, target_id:if not isinstance(call_params, dict):return tool_error(f"'params' must be an object/dict, got {type(call_params).__name__}")- blocked = _browser_cdp_private_guard(task_id=effective_task_id, method=method, params=call_params)+ blocked = _browser_cdp_private_guard(method=method, params=call_params, endpoint=endpoint, target_id=target_id)if blocked:return blocked@@ -345,8 +356,8 @@ def browser_cdp(method: str, params: Optional[dict[str, Any]] = None, target_id:BROWSER_CDP_SCHEMA: dict[str, Any] = {"name": "browser_cdp","description": (- "Send a raw Chrome DevTools Protocol (CDP) command. Escape hatch for browser operations not covered "- "by browser_navigate, browser_click, browser_console, etc.\n\n"+ "Send a raw Chrome DevTools Protocol (CDP) command. Escape hatch for browser operations the other "+ "browser tools don't cover.\n\n""**Requires a reachable CDP endpoint.** Available when the user has run '/browser connect' to attach ""to a running Chrome, Brave, Chromium, or Edge browser, or when 'browser.cdp_url' is set in ""config.yaml. Not currently wired up for cloud backends (Browserbase, Browser Use, Firecrawl) — "@@ -369,7 +380,7 @@ BROWSER_CDP_SCHEMA: dict[str, Any] = {"- Page-level methods (Page.*, Runtime.*, DOM.*, Emulation.*, Network.* scoped to a tab): pass ""target_id from Target.getTargets.\n""- **Cross-origin iframe scope** (Runtime.evaluate inside an OOPIF, Page.* targeting a frame target, "- "etc.): pass frame_id from the browser_snapshot frame_tree output. This routes through the CDP "+ "etc.): pass a frame_id from Page.getFrameTree. This routes through the CDP ""supervisor's live connection — the only reliable way on Browserbase where stateless CDP calls hit ""signed-URL expiry.\n""- Each stateless call (without frame_id) is independent — sessions and event subscriptions do not "@@ -387,8 +398,8 @@ BROWSER_CDP_SCHEMA: dict[str, Any] = {"Optional. Target/tab ID from Target.getTargets result (each entry's 'targetId'). Use for ""page-level methods at the top-level tab scope. Mutually exclusive with frame_id.")},"frame_id": {"type": "string", "description": (- "Optional. Out-of-process iframe (OOPIF) frame_id from browser_snapshot.frame_tree.children[] "- "where is_oopif=true. When set, routes the call through the CDP supervisor's live session for "+ "Optional. Out-of-process iframe (OOPIF) frame id from Page.getFrameTree. "+ "When set, routes the call through the CDP supervisor's live session for ""that iframe. Essential for Runtime.evaluate inside cross-origin iframes, especially on ""Browserbase where fresh per-call CDP connections can't keep up with signed URL rotation. For ""same-origin iframes, use parent contentWindow/contentDocument from Runtime.evaluate at the "@@ -401,17 +412,13 @@ BROWSER_CDP_SCHEMA: dict[str, Any] = {def _browser_cdp_check() -> bool:- """Availability check: offered only when a static CDP URL is set (Camofox is REST-only;- the default local agent-browser hides its CDP port; cloud per-session ``cdp_url`` isn't- 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_cdp import _get_cdp_override_raw- from tools.browser_tool_install import 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- return bool(check_browser_requirements() and _get_cdp_override_raw())+ """Availability check: offered only when a static CDP URL is set (a launched or cloud per-session+ ``cdp_url`` isn't surfaced) and the browser surface exists (browser-harness importable). 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."""+ from tools.browser_session_cdp import get_cdp_override_raw+ from tools.browser_use_cli import browser_exec_available+ return bool(browser_exec_available() and get_cdp_override_raw())registry.register(diff --git a/tools/browser_dialog_tool.py b/tools/browser_dialog_tool.pyindex dc1f877eb41..f85615ab5a6 100644--- a/tools/browser_dialog_tool.py+++ b/tools/browser_dialog_tool.py@@ -1,6 +1,6 @@"""Agent-facing tool: respond to a native JS dialog captured by the CDP supervisor.-Response-only: the agent reads ``pending_dialogs`` from ``browser_snapshot``,+Response-only: the agent reads ``pending_dialogs`` from a ``browser_exec`` result,then calls ``browser_dialog(action=...)``. Gated on ``_browser_cdp_check`` so itappears together with ``browser_cdp``. Design: ``website/docs/developer-guide/browser-supervisor.md``."""@@ -18,20 +18,18 @@ BROWSER_DIALOG_SCHEMA: dict[str, Any] = {"description": ("Respond to a native JavaScript dialog (alert / confirm / prompt / ""beforeunload) that is currently blocking the page.\n\n"- "**Workflow:** call ``browser_snapshot`` first — if a dialog is open, "- "it appears in the ``pending_dialogs`` field with ``id``, ``type``, "+ "**Workflow:** when a dialog is open, the browser_exec result lists "+ "it in the ``pending_dialogs`` field with ``id``, ``type``, ""and ``message``. Then call this tool with ``action='accept'`` or ""``action='dismiss'``.\n\n""**Prompt dialogs:** pass ``prompt_text`` to supply the response ""string. Ignored for alert/confirm/beforeunload.\n\n""**Multiple dialogs:** if more than one dialog is queued (rare — ""happens when a second dialog fires while the first is still open), "- "pass ``dialog_id`` from the snapshot to disambiguate.\n\n"- "**Availability:** only present when a CDP-capable backend is "- "attached — Browserbase sessions, local Chromium-family browser via "- "``/browser connect``, or ``browser.cdp_url`` in config.yaml. "- "Not available on Camofox (REST-only) or the default Playwright "- "local browser (CDP port is hidden)."+ "pass ``dialog_id`` from ``pending_dialogs`` to disambiguate.\n\n"+ "**Availability:** only present when a CDP endpoint is attached — "+ "a local Chromium-family browser via ``/browser connect``, or "+ "``browser.cdp_url`` in config.yaml."),"parameters": {"type": "object",@@ -57,7 +55,7 @@ BROWSER_DIALOG_SCHEMA: dict[str, Any] = {"type": "string","description": ("Specific dialog to respond to, from "- "``browser_snapshot.pending_dialogs[].id``. Required "+ "``pending_dialogs[].id``. Required ""only when multiple dialogs are queued."),},@@ -79,10 +77,9 @@ def browser_dialog(return json.dumps({"success": False,"error": (- "No CDP supervisor is attached to this task. Either the "- "browser backend doesn't expose CDP (Camofox, default "- "Playwright) or no browser session has been started yet. "- "Call browser_navigate or /browser connect first."+ "No CDP supervisor is attached to this task: no browser "+ "session has been started yet. Call browser_exec or "+ "/browser connect first."),})result = supervisor.respond_to_dialog(action=action, prompt_text=prompt_text, dialog_id=dialog_id)diff --git a/tools/browser_extension_router.py b/tools/browser_extension_router.pyindex 3a5e3a84524..40d7ef84551 100644--- a/tools/browser_extension_router.py+++ b/tools/browser_extension_router.py@@ -1,8 +1,9 @@"""Registry-level browser extension router.-Agent-side half of browser-extension-control: decides, per ``browser_*`` handler-invocation, whether an attached extension controller (via-:mod:`gateway.browser_control_broker`) or the legacy backend executes it.+Agent-side half of browser-extension-control: decides, per ``browser_cdp``+invocation (the one core browser tool it serves), whether an attached extension+controller (via :mod:`gateway.browser_control_broker`) or the local CDP path+executes it.Routing contract (see ``tests/tools/test_browser_extension_router.py``):- Feature off ⇒ legacy, broker never touched, ``fallback()`` called exactly once.@@ -114,7 +115,7 @@ def routed_browser_handler(session_id: Optional[str] = None, principal_id: Optional[str] = None,transport_family: Optional[str] = None, tool_call_id: Optional[str] = None,) -> Any:- """Lazy registry-handler route wrapper for ``browser_*`` tools.+ """Lazy registry-handler route wrapper for ``browser_cdp``.Feature off (or gateway unimportable) ⇒ the legacy handler runs unchanged."""try:from gateway.browser_control_broker import browser_control_enabled, get_browser_control_brokerdiff --git a/tools/browser_supervisor.py b/tools/browser_supervisor.pyindex 3ea1770f85c..dddcd3e12f8 100644--- a/tools/browser_supervisor.py+++ b/tools/browser_supervisor.py@@ -369,7 +369,7 @@ class CDPSupervisor(DialogSupervisionMixin, FrameTrackingMixin):async def _run(self) -> None:"""Top-level reconnecting supervisor coroutine. Browserbase tears down the CDP- socket whenever a short-lived client (agent-browser's per-command CDP client)+ socket whenever a short-lived client (a per-call browser_cdp or harness CDP connection)disconnects, so on drop we reset per-session ids, re-attach, and keep going.A failure before the first successful attach is fatal for ``start()``."""reconnect_failures, last_success_at, backoff = 0, 0.0, 0.5diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex 6b1422351af..0cf4f26aa41 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -666,6 +666,19 @@ def _reload_if_republished(env: dict, generation: int) -> None:_reload_daemons([daemon])+def _pending_dialogs(task_id: Optional[str]) -> dict:+ """Native dialogs the task's CDP supervisor is holding open (``browser_dialog`` answers them), page text+ redacted like every other browser output."""+ from agent.redact import redact_sensitive_text+ from tools.browser_supervisor import SUPERVISOR_REGISTRY+ supervisor = SUPERVISOR_REGISTRY.get(task_id or "default")+ snapshot = supervisor.snapshot() if supervisor is not None else None+ if snapshot is None or not snapshot.active or not snapshot.pending_dialogs:+ return {}+ return {"pending_dialogs": [{k: redact_sensitive_text(v, force=True) if isinstance(v, str) else v+ for k, v in d.to_dict().items()} for d in snapshot.pending_dialogs]}++def _take_real_profile_note(route_key: str) -> dict:"""The fallback note for the first result this route returns after falling back, then nothing."""if route_key not in _real_profile_fallback or route_key in _real_profile_note_delivered:@@ -770,6 +783,7 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUTif session:result["session"] = sessionresult.update(_take_real_profile_note(route_key))+ result.update(_pending_dialogs(task_id))stderr = redact_sensitive_text((proc.stderr or "").strip(), force=True)if len(stderr) > _STDERR_CAP_CHARS:stderr = stderr[:_STDERR_CAP_CHARS] + "\n… (stderr truncated)"diff --git a/tools/browser_vault_tool.py b/tools/browser_vault_tool.pyindex 9474435dc68..7cdfbe10571 100644--- a/tools/browser_vault_tool.py+++ b/tools/browser_vault_tool.py@@ -41,11 +41,9 @@ def _check_vault_available() -> bool:"""Schema-gate: the vault rides with the browser. An empty vault still needs save_login so theagent can offer to remember a login the first time it meets a form; hiding the tool until an itemexists meant nobody ever discovered the feature. Deferral keeps that presence nearly free."""- from tools.browser_tool_install import check_browser_requirements- from tools.browser_use_cli import is_browser_use_cli_mode- # check_browser_requirements() is False by design in Browser Use mode (browser_exec replaces the- # built-in surface); the vault serves both stacks.- return bool(is_browser_use_cli_mode() or check_browser_requirements())+ from tools.browser_session_cdp import get_cdp_override_raw+ from tools.browser_use_cli import browser_exec_available+ return bool(browser_exec_available() or get_cdp_override_raw())# ---------------------------------------------------------------------------@@ -53,76 +51,50 @@ def _check_vault_available() -> bool:# ---------------------------------------------------------------------------def _eval_js(task_id: str, expression: str) -> dict[str, Any]:- """Evaluate NON-SECRET JS on the current page (inspection, origin reads).-- Prefers the supervisor's persistent CDP WebSocket, falls back to the- agent-browser CLI ``eval`` command. Never use this for expressions that- embed secret values — the fallback places the expression in subprocess- argv. Use :func:`_eval_js_secret` for secret-bearing expressions.- """- try:- from tools.browser_supervisor import SUPERVISOR_REGISTRY-- supervisor = SUPERVISOR_REGISTRY.get(task_id)- if supervisor is not None:- sup = supervisor.evaluate_runtime(expression)- if sup.get("ok"):- return {"success": True, "result": sup.get("result")}- err = str(sup.get("error") or "")- if "supervisor" not in err.lower():- return {"success": False, "error": err}- except ImportError:- pass- except Exception as exc: # pragma: no cover — defensive- logger.debug("vault fill: supervisor eval unavailable (%s)", exc)-- from tools.browser_tool import _last_session_key- from tools.browser_tool_session import _run_browser_command-- effective = _last_session_key(task_id)- result = _run_browser_command(effective, "eval", [expression])- if not result.get("success"):- return {"success": False, "error": result.get("error", "eval failed")}- return {"success": True, "result": result.get("data", {}).get("result")}+ """Evaluate NON-SECRET JS on the current page (inspection, origin reads) over the task's CDP+ supervisor. There is no other path: without a supervisor the call reports it."""+ supervisor = _ensure_supervisor(task_id)+ if supervisor is None:+ return {"success": False, "error": "no supervised browser session for this task; open the page with "+ "browser_exec first"}+ sup = supervisor.evaluate_runtime(expression)+ if sup.get("ok"):+ return {"success": True, "result": sup.get("result")}+ return {"success": False, "error": str(sup.get("error") or "evaluate failed")}def _ensure_supervisor(task_id: str):- """The supervisor for ``task_id``, attaching one on demand for a LOCAL built-in browser session.-- Cloud/CDP-override sessions and browser_exec attach their supervisor when the session is created;- a local agent-browser ``--session`` has no ``cdp_url`` of its own, so nothing did. Ask the daemon- for the packaged Chromium's endpoint (``get cdp-url``: same daemon, same reaper) and attach.- Returns None when no endpoint is reachable; the fill then refuses rather than touching argv."""+ """The supervisor for ``task_id`` (browser_exec attaches one on every call), attaching one on demand to+ the task's session CDP endpoint when none is running. None when no endpoint is known; a fill then+ refuses rather than touching argv."""from tools.browser_supervisor import SUPERVISOR_REGISTRYsupervisor = SUPERVISOR_REGISTRY.get(task_id)if supervisor is not None:return supervisor- from tools.browser_tool import _last_session_key- from tools.browser_tool_cdp import _get_dialog_policy_config, _resolve_cdp_override- from tools.browser_tool_session import _run_browser_command+ from tools.browser_session import session_for_task+ from tools.browser_session_cdp import get_dialog_policy_config, resolve_cdp_override- res = _run_browser_command(_last_session_key(task_id), "get", ["cdp-url"])- cdp_url = str(((res or {}).get("data") or {}).get("cdpUrl") or "") if (res or {}).get("success") else ""+ cdp_url = str(session_for_task(task_id).get("cdp_url") or "")if not cdp_url:return None- policy, timeout_s = _get_dialog_policy_config()+ policy, timeout_s = get_dialog_policy_config()try:- return SUPERVISOR_REGISTRY.get_or_start(task_id=task_id, cdp_url=_resolve_cdp_override(cdp_url),+ return SUPERVISOR_REGISTRY.get_or_start(task_id=task_id, cdp_url=resolve_cdp_override(cdp_url),dialog_policy=policy, dialog_timeout_s=timeout_s)- except Exception as exc:- logger.debug("vault fill: supervisor attach to local session failed (%s)", exc)+ except Exception as exc: # health: allow BLE001 -- a failed attach is reported as supervisor_required+ logger.debug("vault fill: supervisor attach to the task's session failed (%s)", exc)return Nonedef _eval_js_secret(task_id: str, expression: str) -> dict[str, Any]:"""Evaluate a SECRET-BEARING JS expression. Supervisor CDP-WS only.- Fails closed: there is deliberately NO fallback to the agent-browser CLI- ``eval`` path, because that places the expression — and therefore the- credential bytes — in subprocess argv, visible to any process listing.- When no supervisor session is available the caller gets a typed refusal- (``error_type='supervisor_required'``) and nothing is written.+ Fails closed: there is deliberately NO subprocess path, because that would+ place the expression — and therefore the credential bytes — in argv,+ visible to any process listing. When no supervisor session is available+ the caller gets a typed refusal (``error_type='supervisor_required'``) and+ nothing is written."""try:supervisor = _ensure_supervisor(task_id)@@ -136,10 +108,8 @@ def _eval_js_secret(task_id: str, expression: str) -> dict[str, Any]:"error_type": "supervisor_required","error": ("Vault fill requires the supervised browser session (direct "- "CDP WebSocket). The fallback eval path would place the "- "credential in subprocess argv, so it is never used for "- "secrets. Start the browser through the Hermes-managed "- "session and retry."+ "CDP WebSocket), and this task has none. Open the page with "+ "browser_exec and retry."),}@@ -614,20 +584,17 @@ BROWSER_VAULT_SCHEMA = {def _bot_desktop_browser_session(task_id: Optional[str]) -> bool:- from tools.browser_tool import _active_sessions, _last_session_key- from tools.browser_tool_session import _shares_bot_desktop_browser- return _shares_bot_desktop_browser(_active_sessions.get(_last_session_key(task_id or "default")) or {})+ from tools.browser_session import session_for_task, shares_bot_desktop_browser+ return shares_bot_desktop_browser(session_for_task(task_id))def _fenced_page_op(task_id: Optional[str], fn) -> str:"""Vault operations focus, inspect and fill the page over the supervisor socket, bypassing- ``_run_browser_command``; they must honour the Bot Desktop lease like every other page access,- or a human typing a credential on the taken-over screen could be read or written to."""- from tools.browser_tool import _active_sessions, _last_session_key- from tools.browser_tool_session import run_fenced+ browser_exec; they must honour the Bot Desktop lease like every other page access, or a human+ typing a credential on the taken-over screen could be read or written to."""+ from tools.browser_session import run_fenced, session_for_task- session = _active_sessions.get(_last_session_key(task_id or "default")) or {}- res = run_fenced(session, lambda: {"raw": fn()})+ res = run_fenced(session_for_task(task_id), lambda: {"raw": fn()})return res["raw"] if "raw" in res else json.dumps(res)