"""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: is NOT skipped — 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=&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