"""Real-time web access and browser-control tools for the Dracull chat agent. The chat endpoint (/api/chat) runs an agentic tool loop: the model can call these tools to search the live web, fetch pages, and drive a real Playwright browser — open new tabs, navigate, observe, click, type, select options, scroll, and capture screenshots — with tabs persisting across chat turns. The registry in :mod:`browser_automation_agent.tools.registry` is the authoritative model-facing tool surface. Legacy methods on this session remain for tests and helper integrations, but they are not the tool registry. Security policy: every URL a tool touches passes through `check_url` — http/https only and the host must resolve to a public address. Localhost, loopback, private, and reserved ranges are rejected unless the operator's private-network setting explicitly enables them. """ import asyncio import ipaddress import logging import os import re import socket import time import uuid from html.parser import HTMLParser from pathlib import Path from typing import Any, ClassVar from urllib.parse import SplitResult, parse_qs, quote_plus, urljoin, urlsplit import aiohttp from playwright.async_api import Page from .browser.errors import ( STALE_ELEMENT, UNKNOWN, ClassifiedError, ) from .config import settings from .exa_search import ExaNotConfiguredError, ExaSearchError, exa_client from .tools.constants import ( MAX_EXTRACT_TEXT, MAX_OBSERVE_ELEMENTS, MAX_OBSERVE_TEXT, MAX_WAIT_FOR_MS, ) from .tools.executor import execute_tool from .tools.registry import tool_schemas from .tools.url_policy import PolicyViolation, enforce_domain_lists, enforce_url_policy from . import web_search_providers logger = logging.getLogger(__name__) # Words that mark a control as SUBMITTING the surrounding form. Used by the # approval gate so a click on "Pay now" or "Place order" asks the human first. _SUBMIT_NAME_WORDS = ( "submit", "pay", "buy", "purchase", "checkout", "place order", "confirm", "transfer", "send payment", "sign in", "sign up", "log in", "register", ) # A control whose accessible name, label, or value describes an irreversible, # account/security-changing, money-moving, publication, or subscription action # is consequential even when it is outside a form. These words are deliberately # action-oriented: ordinary controls (including non-submit buttons inside a # form) remain non-consequential unless their name matches this list. _CONSEQUENTIAL_ACTION_WORDS = ( "delete", "remove", "destroy", "drop", "disable", "deactivate", "transfer", "withdraw", "pay", "purchase", "checkout", "subscribe", "publish", "deploy", "close account", "delete account", "reset password", "change password", "revoke", "unsubscribe", ) # Matching is word-boundary based rather than raw substring based. This avoids # classifying harmless names such as "display" as "pay" or "undropdown" as # "drop", while still matching the multi-word actions above. _CONSEQUENTIAL_ACTION_PATTERN = re.compile( r"(? bool: # The settings flag (Phase 2) enables localhost testing end to end; the # environment escape hatch keeps its existing meaning. if bool(getattr(settings, "allow_private_networks", False)): return True return os.environ.get("DRACULL_ALLOW_PRIVATE_NET", "").strip().lower() in ("1", "true", "yes") def _is_blocked_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool: # Unwrap IPv4-mapped IPv6 (::ffff:127.0.0.1) so loopback/private checks # hold on every supported Python, not only versions that classify mapped # addresses natively; a mapped *public* address still passes. mapped = getattr(ip, "ipv4_mapped", None) if mapped is not None: ip = mapped return ( ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved or ip.is_multicast or ip.is_unspecified or any(ip in net for net in _BLOCKED_NETS) ) def _parse(url: str, context: str) -> SplitResult: parts = urlsplit((url or "").strip()) if parts.scheme not in ("http", "https"): raise ToolError(f"{context} scheme must be http or https (got '{parts.scheme or 'none'}')") if not parts.hostname: raise ToolError(f"{context} is missing a host") if parts.username or parts.password: raise ToolError(f"{context} must not embed credentials") return parts def _resolve_ips(host: str, port: int) -> list[str]: try: infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM) except socket.gaierror as exc: raise ToolError(f"host '{host}' could not be resolved: {exc}") from exc ips: list[str] = [] for info in infos: addr = info[4][0] if addr and addr not in ips: ips.append(str(addr)) if not ips: raise ToolError(f"host '{host}' resolved to no addresses") return ips async def check_url(raw_url: str, *, context: str = "URL") -> str: """Async check — DNS resolution runs in a worker thread to avoid blocking the loop.""" parts = _parse(raw_url, context) # The operator's domain kill switch applies on EVERY path - including the # localhost testing escape hatch, which is about private ADDRESSES, not # about hosts the operator has blocked. The executor applies the same # lists (tools/url_policy.enforce_domain_lists); without this call the # HTTP browse API, client research and the selenium driver could reach a # host the operator had blocked. try: enforce_domain_lists(parts.hostname or "", context) except PolicyViolation as exc: raise ToolError(str(exc)) from exc if _allow_private(): return raw_url.strip() port = parts.port or (443 if parts.scheme == "https" else 80) host = parts.hostname if not host: raise ToolError(f"{context} is missing a host") for ip_text in await asyncio.to_thread(_resolve_ips, host, port): try: ip = ipaddress.ip_address(ip_text) except ValueError: continue if _is_blocked_ip(ip): raise ToolError( f"{context} host '{parts.hostname}' resolves to a non-public address ({ip}); blocked" ) return raw_url.strip() # ── HTML → readable text ───────────────────────────────────────────────────── class _TextExtractor(HTMLParser): """Extracts visible text and the from an HTML document.""" # NB: <head> is NOT skipped — <title> lives inside it; metadata tags carry # no text data, and script/style/noscript are skipped individually. SKIP: ClassVar[set[str]] = {"script", "style", "noscript", "template", "svg", "iframe"} BREAKS: ClassVar[set[str]] = {"br", "p", "div", "li", "tr", "h1", "h2", "h3", "h4", "section", "article", "table"} def __init__(self) -> None: super().__init__(convert_charrefs=True) self.chunks: list[str] = [] self.title = "" self._skip_depth = 0 self._in_title = False def handle_starttag(self, tag: str, attrs: Any) -> None: if tag in self.SKIP: self._skip_depth += 1 elif tag == "title": self._in_title = True elif tag in self.BREAKS: self.chunks.append("\n") def handle_endtag(self, tag: str) -> None: if tag in self.SKIP and self._skip_depth: self._skip_depth -= 1 elif tag == "title": self._in_title = False def handle_data(self, data: str) -> None: if self._skip_depth: return if self._in_title: self.title += data elif data.strip(): self.chunks.append(data) def text(self) -> str: joined = " ".join(self.chunks) lines = [ln.strip() for ln in joined.split("\n")] return "\n".join(ln for ln in lines if ln) def html_to_text(html: str) -> tuple[str, str]: """Return (title, visible text) for an HTML document; tolerant of malformed markup.""" extractor = _TextExtractor() try: extractor.feed(html) extractor.close() except Exception: # noqa: BLE001, S110 — malformed HTML still yields partial text pass return extractor.title.strip(), extractor.text()[:120_000] # ── Web tools ──────────────────────────────────────────────────────────────── _TEXTISH_TYPES = ("text/", "application/json", "application/xhtml", "application/xml", "application/ld+json", "+json", "+xml") # Sites like foodready.ai ship multi-KB CSP headers; the 8190-byte default # header field limit aborts those responses before the body is read. HTTP_PARSER_LIMITS = {"max_line_size": 65536, "max_field_size": 65536, "max_headers": 256} def client_session(**kwargs: Any) -> aiohttp.ClientSession: """Build a ClientSession with the oversized-header limits enabled. aiohttp accepts ``max_line_size``/``max_field_size`` at runtime but its type stubs omit them, so the keyword splat is deliberately unchecked. """ return aiohttp.ClientSession(**HTTP_PARSER_LIMITS, **kwargs) # type: ignore[arg-type] _REDIRECT_STATUSES = (301, 302, 303, 307, 308) async def _get_guarded(session: aiohttp.ClientSession, url: str) -> tuple[int, str, str, bytes, str]: """GET a URL following redirects MANUALLY, re-running check_url on every hop. With aiohttp's auto-redirects a public page could 302 to a loopback or metadata address and the body would be fetched before any gate runs — manual hops keep the SSRF policy in force end to end. """ current = url for _ in range(6): # same budget the previous max_redirects allowed async with session.get(current, allow_redirects=False) as resp: location = resp.headers.get("Location") if resp.status in _REDIRECT_STATUSES and location: await resp.content.read(4096) # drain the small hop body current = await check_url(urljoin(current, location), context="web_fetch redirect") continue ctype = (resp.headers.get("Content-Type") or "").lower() if not any(t in ctype for t in _TEXTISH_TYPES): raise ToolError(f"unsupported content type '{ctype or 'unknown'}' — only text pages can be fetched") raw = await resp.content.read(MAX_BODY_BYTES) return resp.status, str(resp.url), ctype, raw, resp.get_encoding() or "utf-8" raise ToolError("web_fetch exceeded 6 redirects") async def web_fetch(url: str, max_chars: int = TOOL_TEXT_CAP) -> dict: """Fetch a public page server-side and return its readable text. Firecrawl (app-shipped key) is tried first: it renders JS-heavy pages the plain fetch below cannot read. Any Firecrawl failure silently falls back to the direct, SSRF-guarded GET, which is exact for static pages. """ url = await check_url(url, context="web_fetch url") try: max_chars = max(500, min(int(max_chars or TOOL_TEXT_CAP), 12000)) except (TypeError, ValueError): max_chars = TOOL_TEXT_CAP # Preferred reader: Firecrawl-rendered markdown (handles SPA pages). scraped = await web_search_providers.scrape_page(url, max_chars) if scraped and scraped.get("text"): text = scraped["text"] return { "url": url, "status": 200, "title": scraped.get("title") or "", "text": text, "truncated": False, "provider": "firecrawl", } async with client_session(timeout=FETCH_TIMEOUT, headers={"User-Agent": USER_AGENT}) as session: status, final_url, ctype, raw, charset = await _get_guarded(session, url) try: body = raw.decode(charset, errors="replace") except (LookupError, UnicodeDecodeError): body = raw.decode("utf-8", errors="replace") if "html" in ctype: title, text = html_to_text(body) else: title, text = "", body.strip() truncated = len(text) > max_chars return { "url": final_url, "status": status, "title": title, "text": text[:max_chars] + ("…[truncated]" if truncated else ""), "truncated": truncated, "provider": "direct", } def _unwrap_ddg_url(href: str) -> str | None: """DuckDuckGo wraps result links as .../l/?uddg=<encoded>&rut=... — unwrap.""" if "uddg=" not in href: return href or None try: qs = parse_qs(urlsplit(href).query) targets = qs.get("uddg") or [] return targets[0] if targets else None except ValueError: return None def _parse_ddg(html: str, limit: int) -> list[dict]: """Parse result links + snippets out of either DDG endpoint's HTML.""" results: list[dict] = [] class _Parser(HTMLParser): def __init__(self) -> None: super().__init__(convert_charrefs=True) self.in_link = False self.in_snippet = False def handle_starttag(self, tag: str, attrs: Any) -> None: a = dict(attrs) cls = a.get("class") or "" href = a.get("href") or "" if tag == "a" and href and ("uddg=" in href or cls in ("result-link", "result__a")): real = _unwrap_ddg_url(href) if real and real.startswith("http"): results.append({"title": "", "url": real, "snippet": ""}) self.in_link = True elif tag == "a" and "result__snippet" in cls or tag == "td" and "result-snippet" in cls: self.in_snippet = True def handle_endtag(self, tag: str) -> None: if tag == "a": self.in_link = False self.in_snippet = False elif tag == "td": self.in_snippet = False def handle_data(self, data: str) -> None: if not results: return text = data.strip() if not text: return if self.in_link and not results[-1]["title"]: results[-1]["title"] = text elif self.in_snippet: results[-1]["snippet"] = (results[-1]["snippet"] + " " + text).strip()[:300] parser = _Parser() try: parser.feed(html) parser.close() except Exception: # noqa: BLE001, S110 pass out: list[dict] = [] seen: set[str] = set() for r in results: if r["url"] in seen: continue seen.add(r["url"]) out.append({"title": (r["title"] or r["url"])[:200], "url": r["url"], "snippet": r["snippet"]}) if len(out) >= limit: break return out async def web_search(query: str, max_results: int = 6) -> dict: """Live web search — Tavily -> Firecrawl (app keys) -> Exa -> DuckDuckGo. The app-shipped Tavily/Firecrawl keys make the first two hops work with zero operator configuration; Exa remains the optional neural upgrade and the keyless DuckDuckGo scrape is the last resort. """ query = (query or "").strip() if not query: raise ToolError("search query is empty") try: max_results = max(1, min(int(max_results or 6), 10)) except (TypeError, ValueError): max_results = 6 # Preferred chain: app-shipped keys (Tavily, then Firecrawl). combined = await web_search_providers.combined_search(query, max_results) if combined: return { "query": query, "engine": combined["engine"], "results": combined["results"], } # Optional neural upgrade: Exa (only when the operator set a key). if exa_client.configured: try: results = await exa_client.search(query, num_results=max_results) normalized = [ {"title": r["title"], "url": r["url"], "snippet": r["snippet"]} for r in results ] return {"query": query, "engine": "exa", "results": normalized} except ExaNotConfiguredError: pass # Fall through to DuckDuckGo except ExaSearchError as exc: logger.warning("Exa search failed, falling back to DuckDuckGo: %s", exc) # Fallback: DuckDuckGo (keyless, but rate-limited and lower quality) headers = {"User-Agent": USER_AGENT, "Accept-Language": "en-US,en;q=0.9"} q = quote_plus(query) last_error: str | None = None for endpoint in ("https://lite.duckduckgo.com/lite/?q=", "https://html.duckduckgo.com/html/?q="): engine = urlsplit(endpoint).netloc try: await check_url(endpoint, context="search engine") async with client_session(timeout=FETCH_TIMEOUT, headers=headers) as session: status, _final_url, _ctype, raw, charset = await _get_guarded(session, endpoint + q) if status != 200: last_error = f"{engine} returned HTTP {status}" continue try: body = raw.decode(charset, errors="replace") except (LookupError, UnicodeDecodeError): body = raw.decode("utf-8", errors="replace") results = _parse_ddg(body, max_results) if results: return {"query": query, "engine": engine, "results": results} last_error = f"{engine} returned no parseable results" except ToolError: raise except Exception as exc: # noqa: BLE001 last_error = f"{type(exc).__name__}: {exc}" raise ToolError(f"web search failed — {last_error}. Try web_fetch on a known URL instead.") # ── Browser tools (Playwright) ─────────────────────────────────────────────── # 7.2 observe probe: interactive elements with a stable index → CSS selector. _OBSERVE_JS = """() => { function cssPath(el) { const parts = []; let node = el; while (node && node.nodeType === 1 && node !== document.documentElement) { let part = node.tagName.toLowerCase(); const parent = node.parentNode; if (parent) { const sibs = Array.from(parent.children).filter(c => c.tagName === node.tagName); if (sibs.length > 1) part += ':nth-of-type(' + (sibs.indexOf(node) + 1) + ')'; } parts.unshift(part); node = parent; } return parts.length ? parts.join(' > ') : 'html'; } const sel = 'a, button, input, select, textarea, [contenteditable="true"], ' + '[role="button"], [role="link"], [role="textbox"], [role="checkbox"], [role="combobox"]'; const out = []; document.querySelectorAll(sel).forEach((el) => { const tag = el.tagName.toLowerCase(); const type = (el.getAttribute('type') || '').toLowerCase(); let role = el.getAttribute('role') || ''; if (!role) { if (tag === 'a') role = 'link'; else if (tag === 'button' || (tag === 'input' && (type === 'button' || type === 'submit'))) role = 'button'; else if (tag === 'select') role = 'combobox'; else if (tag === 'textarea' || (tag === 'input' && type !== 'checkbox')) role = 'textbox'; else if (tag === 'input') role = 'checkbox'; else role = tag; } let name = el.getAttribute('aria-label') || el.getAttribute('alt') || el.getAttribute('placeholder') || el.getAttribute('title') || ''; if (!name && tag !== 'select' && el.innerText) name = el.innerText.trim().split('\\n')[0]; if (!name && el.value !== undefined && tag !== 'select') name = String(el.value); let label = ''; if (el.labels && el.labels.length) { label = Array.from(el.labels).map((item) => String(item.innerText || '').trim()).join(' '); } let state = ''; if (tag === 'input' && type === 'checkbox') state = el.checked ? 'checked' : 'unchecked'; else if (tag === 'select') { const opt = el.selectedOptions && el.selectedOptions[0]; state = opt ? String(opt.value) : ''; } else if (tag === 'input' || tag === 'textarea') state = 'value=' + String(el.value ?? ''); else state = (el.innerText || '').trim().slice(0, 80); const inForm = !!el.closest('form'); const rect = el.getBoundingClientRect(); const visible = !!(rect && rect.width > 0 && rect.height > 0) && !el.closest('[hidden]'); const enabled = !el.disabled && el.getAttribute('aria-disabled') !== 'true'; out.push({ selector: cssPath(el), role: role, tag: tag, type: type, accessible_name: String(name).trim().slice(0, 120), label: label.trim().slice(0, 120), value: el.value === undefined || el.value === null ? '' : String(el.value).slice(0, 120), state: state, in_form: inForm, visible: visible, enabled: enabled, }); }); return out; }""" class ChatBrowserSession: """A persistent multi-tab Playwright session shared by all chat turns. Tabs are tracked as sub-session page ids inside the shared BrowserManager, so pages (and cookies, via persistent contexts) survive between requests. """ SESSION_ID = "dracull_chat" SNAPSHOT_CHARS = 6000 @staticmethod async def _guard_context(context: Any) -> None: """Install the request guard on a browser context (idempotent). The pre-flight URL check only sees the URL the MODEL asked for. The browser then follows redirects and loads subresources on its own, so a public page could steer the browser at a loopback/private address (SSRF) without the policy ever seeing it. A context-level route handler validates EVERY http(s) request — main document, redirect hops and subresources alike — and aborts the ones the policy refuses. """ if getattr(context, "_dracull_navigation_guard", False): return async def _guard(route: Any) -> None: url = route.request.url if url.startswith(("http://", "https://")): try: await enforce_url_policy( url, allow_private=_allow_private(), context="browser request", ) except PolicyViolation: await route.abort() return except Exception: # noqa: BLE001 — never let the guard break the page await route.abort() return await route.continue_() try: await context.route("**/*", _guard) except Exception: # noqa: BLE001 — a context without routing support return context._dracull_navigation_guard = True def __init__(self, manager: Any) -> None: self._manager = manager self._tabs: list[str] = [] self._active = 0 self._lock = asyncio.Lock() # 7.2 snapshots: snapshot_id -> record; only the LATEST snapshot per # tab stays valid, so actions on an outdated one fail STALE_ELEMENT. self._snapshots: dict[str, dict[str, Any]] = {} self._current_snapshot: dict[str, str | None] = {} # A snapshot may authorize one in-flight mutating action at a time. # The reservation prevents two concurrent actions from both consuming # the same snapshot before either successful action invalidates it. self._snapshot_inflight: set[str] = set() # Snapshot ids already consumed by a successful mutating action. They # stay in the audit record but can never authorize another action. self._snapshot_consumed: set[str] = set() def _live_page(self, tab_id: str) -> Page | None: page: Page | None = self._manager._pages.get(tab_id) if page is not None and not page.is_closed(): return page return None # ── approval-gate helpers (what only the session can know) ────────────── # A click on a submit/pay control and an Enter keypress in a credential # form both SEND data. The generic executor gate cannot see that, so the # session answers from the snapshot it recorded. @staticmethod def _is_submit_control(element: dict[str, Any]) -> bool: """True when clicking the control sends data or changes consequential state. A control is consequential when it submits a form, or when its accessible name, associated label, or value contains an action word from ``_CONSEQUENTIAL_ACTION_WORDS``. The latter check applies outside forms too (for example, a standalone "Delete account" button). Explicit ``type=button`` / ``type=reset`` controls inside a form do not submit, and ordinary controls whose names contain no action word remain allowed. """ tag = str(element.get("tag") or "").lower() input_type = str(element.get("type") or "").lower() name_parts = ( element.get("accessible_name"), element.get("label"), element.get("value"), ) name = " ".join(str(part or "") for part in name_parts) if _CONSEQUENTIAL_ACTION_PATTERN.search(name): return True if input_type in {"submit", "image"}: return True if tag != "button": return False if bool(element.get("in_form")): # HTML defaults a <button> without an explicit type to type=submit. # An explicit non-submit type still overrides that default. return input_type not in {"button", "reset"} return any(word in name.lower() for word in _SUBMIT_NAME_WORDS) def element_requires_approval(self, index: int, snapshot_id: str) -> bool: """Does clicking element `index` of `snapshot_id` send data?""" record = self._snapshots.get(snapshot_id) if not record: return False elements = record.get("elements") or [] if not isinstance(index, int) or index < 0 or index >= len(elements): return False element = elements[index] if not isinstance(element, dict): return False return self._is_submit_control(element) def key_requires_approval(self, key: str) -> bool: """Would pressing `key` submit something sensitive? Enter submits the focused form. That is only consequential when the page is a credential or payment form, so the page's latest snapshot is consulted: a password field or a payment control means a human should approve. A search box is not. """ if str(key or "").strip().lower() != "enter": return False tab_id = self.current_tab_id() snapshot_id = self._current_snapshot.get(tab_id) if tab_id else None record = self._snapshots.get(snapshot_id) if snapshot_id else None if not record: return False for element in record.get("elements") or []: if not isinstance(element, dict): continue if str(element.get("type") or "").lower() == "password": return True if self._is_submit_control(element): name = str(element.get("accessible_name") or "").lower() if any(word in name for word in _PAYMENT_NAME_WORDS): return True return False async def _ensure(self) -> Page: page = self._live_page(self.SESSION_ID) if page is None: # Rebuild after root-tab death: close and deregister the orphaned # persistent context FIRST, or Chromium processes accumulate behind # the dead context until stop() (audit finding iv). Only the # browser object is closed — no profile data is ever deleted. await self._close_orphaned_context() await self._manager.create_session(self.SESSION_ID) page = self._live_page(self.SESSION_ID) self._tabs = [self.SESSION_ID] self._active = 0 if page is None: raise ToolError("browser session could not be created") return page async def _close_orphaned_context(self) -> None: """Close + deregister the context behind a dead root tab (audit iv).""" try: status = await self._manager.get_session_status(self.SESSION_ID) except Exception: # a status probe failure must not block the rebuild logger.debug("could not read session status during rebuild", exc_info=True) return context_id = getattr(status, "context_id", None) if status is not None else None if not context_id: return try: await self._manager.delete_context(context_id) except Exception: # a dead context must not block the rebuild logger.debug( "could not close orphaned context %s", context_id, exc_info=True ) def _prune_dead_tabs(self) -> None: """Drop tabs closed externally, keeping the same page active. _tabs must only ever contain live pages, so the numbering browser_tabs prints (and the open_tabs counts snapshot/new_tab report) is exactly what switch_tab/close_tab accept — dead entries may not linger as index gaps until the next active_page() call happens to prune them. Callers hold self._lock and bootstrap via _ensure_tabbed_session() afterwards; pruning runs BEFORE _ensure() so a rebuild of the closed root tab cannot reset the still-live sub-tabs away. """ live = [t for t in self._tabs if self._live_page(t)] if len(live) == len(self._tabs): return was_active = self._tabs[self._active] if self._active < len(self._tabs) else None self._tabs = live if not self._tabs: return if was_active in self._tabs: self._active = self._tabs.index(was_active) else: # The active tab was among the dead — fall back to the first. self._active = 0 async def _ensure_tabbed_session(self) -> None: """Prune externally-closed tabs, then bootstrap the session tab when nothing survives (fresh session, or every tab died underneath us).""" self._prune_dead_tabs() if not self._tabs: await self._ensure() self._tabs = [self.SESSION_ID] self._active = 0 async def active_page(self) -> Page: async with self._lock: await self._ensure_tabbed_session() page = self._live_page(self._tabs[self._active]) if page is None: raise ToolError("no live browser tab available") return page def _register_tab(self, tab_id: str) -> int: """Register a tab, make it active, and return its 1-based index. The index is captured HERE, at registration, so a caller can report its own tab even when another tab is registered before the caller reads the session state back. """ if tab_id not in self._tabs: self._tabs.append(tab_id) self._active = self._tabs.index(tab_id) return self._active + 1 async def _settle(self, page: Page) -> None: try: await page.wait_for_load_state("networkidle", timeout=6000) except Exception: # noqa: BLE001 — pages with long-polling never go idle await asyncio.sleep(0.3) async def navigate(self, url: str) -> dict: url = await check_url(url, context="browser url") page = await self.active_page() tab_id = self.current_tab_id() await self._guard_context(page.context) await page.goto(url, wait_until="domcontentloaded", timeout=30000) await self._settle(page) if tab_id: self._invalidate_snapshot(tab_id) return {"url": page.url, "title": await page.title(), "tab": self._active + 1} async def new_tab(self, url: str = "") -> dict: target_url = (url or "").strip() or "about:blank" if target_url.lower() != "about:blank": target_url = await check_url(target_url, context="browser url") page = await self.active_page() new_page = await page.context.new_page() new_page.set_default_timeout(30000) await self._guard_context(new_page.context) # The id must be unique even when several tabs are opened at the same # moment: a counter-plus-timestamp id collides under concurrency (two # calls read the same tab count and the same second), and a colliding # id makes two different tabs indistinguishable to the model. tab_id = f"{self.SESSION_ID}_tab{uuid.uuid4().hex[:12]}" self._manager._pages[tab_id] = new_page tab_index = self._register_tab(tab_id) if target_url.lower() != "about:blank": await new_page.goto(target_url, wait_until="domcontentloaded", timeout=30000) await self._settle(new_page) # The id and index belong to THIS tab. Reading the session's active tab # after the awaits above would report a DIFFERENT tab when calls run # concurrently, because the last registration wins the active slot. return {"url": new_page.url, "title": await new_page.title(), "tab": tab_index, "open_tabs": len(self._tabs), "tab_id": tab_id} async def snapshot(self) -> dict: page = await self.active_page() title = await page.title() _, text = html_to_text(await page.content()) truncated = len(text) > self.SNAPSHOT_CHARS return { "url": page.url, "title": title, "tab": self._active + 1, "open_tabs": len(self._tabs), "text": text[: self.SNAPSHOT_CHARS] + ("…[truncated — scroll or extract_text for more]" if truncated else ""), "truncated": truncated, } async def click(self, selector: str = "", text: str = "") -> dict: page = await self.active_page() if selector: await page.click(selector, timeout=10000) target = selector elif text: await page.get_by_text(text, exact=False).first.click(timeout=10000) target = f"text='{text}'" else: raise ToolError("click needs either a CSS selector or visible text") await asyncio.sleep(0.6) return {"clicked": target, "url": page.url, "title": await page.title()} async def fill(self, selector: str, text: str, submit: bool = False) -> dict: if not selector: raise ToolError("fill needs a CSS selector") page = await self.active_page() await page.fill(selector, text, timeout=10000) if submit: await page.keyboard.press("Enter") await asyncio.sleep(0.8) return {"filled": selector, "submitted": bool(submit), "url": page.url} async def press_key(self, key: str) -> dict: page = await self.active_page() await page.keyboard.press(key) return {"pressed": key, "url": page.url} async def scroll(self, pixels: int = 600) -> dict: page = await self.active_page() await page.evaluate(f"window.scrollBy(0, {int(pixels)})") pos = await page.evaluate("({y: window.scrollY, h: document.body.scrollHeight})") return {"scrolled": int(pixels), "scroll_y": pos.get("y"), "page_height": pos.get("h")} async def screenshot(self) -> dict: page = await self.active_page() shots_dir = Path( getattr( self._manager, "browser_artifacts_dir", Path(settings.browser_user_data_dir).parent / "screenshots", ) ) shots_dir.mkdir(parents=True, exist_ok=True) path = shots_dir / f"chat_{int(time.time() * 1000)}.png" shot = await page.screenshot(full_page=False, type="png") path.write_bytes(shot) return {"path": str(path.resolve()), "bytes": len(shot), "url": page.url} async def tabs(self) -> dict: async with self._lock: await self._ensure_tabbed_session() listed = [] for i, tab_id in enumerate(self._tabs): page = self._live_page(tab_id) if page is None: continue listed.append({"tab": i + 1, "tab_id": tab_id, "active": i == self._active, "title": await page.title(), "url": page.url}) return {"tabs": listed} async def switch_tab(self, index: int) -> dict: await self._ensure() try: idx = int(index) - 1 except (TypeError, ValueError): raise ToolError(f"tab index must be an integer, got {index!r}") page = self._live_page(self._tabs[idx]) if 0 <= idx < len(self._tabs) else None if page is None: raise ToolError(f"tab {index} does not exist or is closed") self._active = idx return {"switched_to": idx + 1, "url": page.url, "title": await page.title()} async def close_tab(self, index: int = 0) -> dict: await self._ensure() idx = (int(index) - 1) if index else self._active if idx < 0 or idx >= len(self._tabs) or self._live_page(self._tabs[idx]) is None: raise ToolError(f"tab {index or self._active + 1} does not exist or is closed") tab_id = self._tabs.pop(idx) page = self._live_page(tab_id) if page: await page.close() if tab_id != self.SESSION_ID: self._manager._pages.pop(tab_id, None) if idx < self._active: # A tab before the active one closed — every later tab shifted left, # so decrement to keep the *same* page active (not the next one). self._active -= 1 self._active = min(self._active, max(len(self._tabs) - 1, 0)) if not self._tabs: await self._ensure() self._tabs = [self.SESSION_ID] self._active = 0 return {"closed": idx + 1, "open_tabs": len(self._tabs)} async def back(self) -> dict: page = await self.active_page() tab_id = self.current_tab_id() await page.go_back(timeout=15000) if tab_id: self._invalidate_snapshot(tab_id) return {"url": page.url, "title": await page.title()} # ── Phase 2 registry surface (plan Table 5) ────────────────────────────── def current_tab_id(self) -> str | None: """The active tab's id, or None before any tab exists.""" if self._tabs and 0 <= self._active < len(self._tabs): return self._tabs[self._active] return None def browser_connected(self) -> bool: """Best-effort connectivity probe for the executor (plan Chapter 7, step 6). Any context whose browser reports closed means the connection dropped. No context yet counts as connected — the handler bootstraps one. """ for context in getattr(self._manager, "_contexts", {}).values(): browser_obj = getattr(context, "browser", None) if browser_obj is None: continue is_connected = getattr(browser_obj, "is_connected", None) if callable(is_connected) and not is_connected(): return False return True async def capabilities(self) -> dict: """The REAL identity of the running browser (plan 7.1) — never assumed.""" page = await self.active_page() browser_obj = getattr(page.context, "browser", None) if browser_obj is None: raise ClassifiedError( UNKNOWN, message="browser identity is not available from the running context", operation="tool:browser_capabilities", ) name = str(getattr(getattr(browser_obj, "browser_type", None), "name", "") or "unknown") version = str(getattr(browser_obj, "version", "") or "unknown") capabilities: dict[str, Any] = { "name": name, "version": version, "channel": settings.browser_channel, "headless": bool(settings.browser_headless), } # When the configured profile directory was unusable and the manager # fell back to its own runtime profile, say so HERE - this is the tool # the model and the user read. The user must not silently get a # logged-out browser because their profile could not be opened. notice_getter = getattr(self._manager, "profile_root_notice", None) if callable(notice_getter): notice = notice_getter() if notice: capabilities["profile_notice"] = notice return capabilities async def open_tab(self, url: str = "") -> dict: """tab_open: create a tab (about:blank without a URL) and CONFIRM it in the browser's own tab list before reporting success.""" result = await self.new_tab(url) # Verify THIS call's tab. Re-reading the session's active tab here # would verify - and report - a concurrent call's tab instead. tab_id = result.get("tab_id") page = self._live_page(tab_id) if tab_id else None if tab_id is None or page is None: raise ClassifiedError( UNKNOWN, message="tab_open could not confirm the new tab is live", operation="tool:tab_open", ) context_pages = getattr(getattr(page, "context", None), "pages", None) if context_pages is not None and page not in context_pages: raise ClassifiedError( UNKNOWN, message="tab_open could not confirm the new tab in the browser's own tab list", operation="tool:tab_open", ) return { **result, "tab_id": tab_id, "verification": { "passed": True, "description": f"tab {tab_id} confirmed in the browser tab list at {page.url}", }, } async def select_tab(self, tab_id: str) -> dict: """tab_select: activate a tab by ID — tab_list is the source of truth.""" async with self._lock: await self._ensure_tabbed_session() page = self._live_page(tab_id) if tab_id in self._tabs else None if page is None: raise ToolError(f"unknown tab id '{tab_id}' — call tab_list for the current ids") self._active = self._tabs.index(tab_id) return {"selected": tab_id, "url": page.url, "title": await page.title()} async def close_tab_by_id(self, tab_id: str | None = None) -> dict: """tab_close: close by stable ID (active tab when omitted). Validation, removal, and the browser close are one critical section. The selected page is captured by tab ID before removal, so a concurrent close can never re-resolve a stale numeric index against a changed list. """ async with self._lock: await self._ensure_tabbed_session() if not tab_id: target_id = self._tabs[self._active] else: target_id = tab_id if target_id not in self._tabs or self._live_page(target_id) is None: raise ToolError( f"unknown tab id '{target_id}' — call tab_list for the current ids" ) index = self._tabs.index(target_id) page = self._live_page(target_id) self._tabs.pop(index) if page: await page.close() if target_id != self.SESSION_ID: self._manager._pages.pop(target_id, None) if index < self._active: # A tab before the active one closed — every later tab shifted left, # so decrement to keep the *same* page active (not the next one). self._active -= 1 self._active = min(self._active, max(len(self._tabs) - 1, 0)) if not self._tabs: await self._ensure() self._tabs = [self.SESSION_ID] self._active = 0 return {"closed": index + 1, "open_tabs": len(self._tabs)} async def observe(self) -> dict: """7.2 snapshot: url, title, capped text, interactive elements, snapshot_id.""" page = await self.active_page() tab_id = self.current_tab_id() if tab_id is None: # active_page() succeeded, so this is unreachable in practice — the # guard keeps the snapshot bookkeeping honestly typed. raise ClassifiedError( UNKNOWN, message="observe could not identify the active browser tab", operation="tool:observe", ) title = await page.title() raw_elements = await page.evaluate(_OBSERVE_JS) elements: list[dict] = [] selectors: list[str] = [] for raw in list(raw_elements or [])[:MAX_OBSERVE_ELEMENTS]: if not isinstance(raw, dict): continue selectors.append(str(raw.get("selector") or "")) elements.append({ "index": len(elements), "role": str(raw.get("role") or "unknown"), # tag/type let the approval gate recognise a submit control # precisely (an <input type=submit> is a button by role alone). "tag": str(raw.get("tag") or ""), "type": str(raw.get("type") or ""), "accessible_name": str(raw.get("accessible_name") or ""), "label": str(raw.get("label") or ""), "value": str(raw.get("value") or ""), "state": str(raw.get("state") or ""), "in_form": bool(raw.get("in_form", False)), "visible": bool(raw.get("visible", True)), "enabled": bool(raw.get("enabled", True)), }) _, text = html_to_text(await page.content()) truncated = len(text) > MAX_OBSERVE_TEXT snapshot_id = uuid.uuid4().hex previous = self._current_snapshot.get(tab_id) if previous: self._snapshots.pop(previous, None) self._snapshots[snapshot_id] = { "snapshot_id": snapshot_id, "tab_id": tab_id, "selectors": selectors, # The element metadata travels with the snapshot so the approval # gate can recognise a submit control at click time. "elements": elements, "url": page.url, } self._current_snapshot[tab_id] = snapshot_id return { "url": page.url, "title": title, "tab": self._active + 1, "open_tabs": len(self._tabs), "tab_id": tab_id, "text": text[:MAX_OBSERVE_TEXT] + ("…[truncated]" if truncated else ""), "truncated": truncated, "elements": elements, "snapshot_id": snapshot_id, } def _invalidate_snapshot(self, tab_id: str) -> None: """Invalidate the current snapshot for one tab, if any.""" snapshot_id = self._current_snapshot.pop(tab_id, None) if snapshot_id: self._snapshots.pop(snapshot_id, None) self._snapshot_inflight.discard(snapshot_id) self._snapshot_consumed.add(snapshot_id) def _consume_snapshot(self, tab_id: str, snapshot_id: str) -> None: """Consume a snapshot after one successful mutating action.""" self._snapshot_consumed.add(snapshot_id) if self._current_snapshot.get(tab_id) == snapshot_id: self._current_snapshot.pop(tab_id, None) self._snapshots.pop(snapshot_id, None) self._snapshot_inflight.discard(snapshot_id) def _snapshot_record(self, snapshot_id: str) -> dict: """Resolve a snapshot for an action; unknown/expired/foreign → STALE_ELEMENT.""" record = self._snapshots.get(snapshot_id) if snapshot_id in self._snapshot_consumed: raise ClassifiedError( STALE_ELEMENT, message=( f"snapshot_id '{snapshot_id}' has already been used — observe " "again for a fresh snapshot" ), operation="tool:snapshot action", ) if snapshot_id in self._snapshot_inflight: raise ClassifiedError( STALE_ELEMENT, message=( f"snapshot_id '{snapshot_id}' is already being used — observe " "again after the current action finishes" ), operation="tool:snapshot action", ) active_tab = self.current_tab_id() current = self._current_snapshot.get(active_tab) if active_tab else None if record is None or record.get("tab_id") != active_tab or current != snapshot_id: raise ClassifiedError( STALE_ELEMENT, message=( f"snapshot_id '{snapshot_id}' is stale or unknown — call " "observe again for a fresh snapshot" ), operation="tool:snapshot action", ) return record def _element_selector(self, record: dict, index: int) -> str: selectors = record.get("selectors") or [] if not 0 <= index < len(selectors): raise ToolError( f"element index {index} is not in snapshot '{record.get('snapshot_id')}' " "— call observe again" ) return str(selectors[index]) async def click_element(self, index: int, snapshot_id: str) -> dict: page = await self.active_page() async with self._lock: record = self._snapshot_record(snapshot_id) selector = self._element_selector(record, index) self._snapshot_inflight.add(snapshot_id) try: await page.click(selector, timeout=10000) # Actions never assume a click navigates (plan 7.2): settle briefly, # then report what actually happened. try: await page.wait_for_load_state("networkidle", timeout=2000) except Exception: # noqa: BLE001 — long-polling pages never go idle await asyncio.sleep(0.2) finally: async with self._lock: self._snapshot_inflight.discard(snapshot_id) tab_id = str(record.get("tab_id") or "") async with self._lock: self._consume_snapshot(tab_id, snapshot_id) return { "clicked": selector, "url": page.url, "title": await page.title(), "verification": { "passed": True, "description": f"clicked element {index} ({selector}); final URL {page.url}", }, } async def type_element(self, index: int, snapshot_id: str, text: str, *, submit: bool = False) -> dict: page = await self.active_page() async with self._lock: record = self._snapshot_record(snapshot_id) selector = self._element_selector(record, index) self._snapshot_inflight.add(snapshot_id) try: await page.fill(selector, text, timeout=10000) if submit: await page.keyboard.press("Enter") try: await page.wait_for_load_state("networkidle", timeout=2000) except Exception: # noqa: BLE001 — long-polling pages never go idle await asyncio.sleep(0.3) finally: async with self._lock: self._snapshot_inflight.discard(snapshot_id) tab_id = str(record.get("tab_id") or "") async with self._lock: if submit: # A submit can navigate, so the page the snapshot described is # gone with it. self._invalidate_snapshot(tab_id) # Otherwise typing changed a field's VALUE, not the element # structure the snapshot indexed, so the snapshot stays usable for # the action it was taken for (observe -> type -> click). return {"filled": selector, "submitted": bool(submit), "url": page.url} async def select_option_element(self, index: int, snapshot_id: str, value: str) -> dict: page = await self.active_page() async with self._lock: record = self._snapshot_record(snapshot_id) selector = self._element_selector(record, index) self._snapshot_inflight.add(snapshot_id) try: await page.select_option(selector, value=value, timeout=10000) finally: async with self._lock: self._snapshot_inflight.discard(snapshot_id) # Choosing an option changes a value, not the element structure # the snapshot indexed, so the snapshot stays usable. return {"selected": value, "selector": selector, "url": page.url} async def extract_text(self, selector: str | None = None, max_chars: int | None = None) -> dict: """extract_text: trimmed text of a selector or the page, size-capped.""" page = await self.active_page() if selector: text = await page.inner_text(selector) else: _, text = html_to_text(await page.content()) limit = MAX_EXTRACT_TEXT if max_chars is None else min(int(max_chars), MAX_EXTRACT_TEXT) truncated = len(text) > limit return { "url": page.url, "selector": selector or None, "text": text[:limit] + ("…[truncated]" if truncated else ""), "truncated": truncated, } async def wait_for(self, condition: str, selector: str | None = None, timeout_ms: int = 5000) -> dict: """wait_for: a named condition; timeout_ms hard-capped at MAX_WAIT_FOR_MS.""" page = await self.active_page() timeout = min(max(int(timeout_ms), 1), MAX_WAIT_FOR_MS) if condition == "selector": target = (selector or "").strip() if not target: raise ToolError("wait_for condition 'selector' needs a selector") await page.wait_for_selector(target, timeout=timeout) return {"waited_for": target, "timeout_ms": timeout, "url": page.url} if condition == "network_idle": await page.wait_for_load_state("networkidle", timeout=timeout) return {"waited_for": "network_idle", "timeout_ms": timeout, "url": page.url} if condition == "navigation": await page.wait_for_load_state("load", timeout=timeout) return {"waited_for": "navigation", "timeout_ms": timeout, "url": page.url} raise ToolError(f"unknown wait_for condition '{condition}'") # ── Tool schemas — DERIVED from the Phase 2 registry (OpenAI function-calling) ─ def build_tool_schemas() -> list[dict]: """OpenAI function-calling schemas for the chat tool loop. Derived from the tool registry — the single source of truth (plan Chapter 7 Table 5). The function name is kept so litellm call sites keep working; the schema shape is the one the provider actually receives through ``litellm.acompletion(tools=...)`` (see docs/AUDIT.md). """ return tool_schemas() async def dispatch_tool(browser: ChatBrowserSession, name: str, args: dict) -> dict: """Execute one registry tool through the deterministic executor (plan Ch. 7). The executor validates the tool name and the arguments, applies the permission/risk gate and the URL policy, checks browser connectivity, runs the handler under a timeout, and wraps everything in the result envelope: ``{"ok", "tool", "data"}`` plus ``{"error": {code, message, retryable, diagnostic_id}}`` on failure. Every failure surfaces exactly ONCE, never as an exception escape, and no failure is retried here. """ return await execute_tool(browser, name, args)