Spaces:
Running
Running
File size: 24,979 Bytes
6eb6c4e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 | """Selenium fallback driver: runs workflow steps on the REAL installed browsers.
Why this exists: the diagnostic logs record an environment that denies
Firefox's sandboxed GPU subprocess spawn (SB::LA::SpawnTarget 0x80070005) and
once denied Playwright's existing driver setup. Playwright's bundled engines
remain the primary stack, but when they cannot launch, Selenium talks to the
installed Google Chrome / Mozilla Firefox through WebDriver with Selenium
Manager resolving the driver binaries β a fully independent second stack.
The driver implements the workflow vocabulary (``tools.registry`` tool names)
and returns the SAME result envelope shape as the Playwright executor, so the
WorkflowRunner and every builtin workflow run unchanged with
``--driver selenium``. Navigation and fetches go through the same network
guard as the Playwright tools (``net_guard.check_url`` and the guarded
``chat_tools.web_fetch``), every WebDriver element query passes through a
selector allowlist (``_find_all`` / ``_find_one``), and step dispatch is a
static handler table β no dynamic attribute lookups.
Selenium is optional (``pip install .[selenium]``); importing this module is
safe without it β construction is what requires the package.
"""
from __future__ import annotations
import asyncio
import logging
import re
import time
import uuid
from pathlib import Path
from typing import Any
from urllib.parse import quote_plus
from .models import substitute
logger = logging.getLogger(__name__)
# Character allowlist for every CSS selector this driver passes to WebDriver.
# Workflow/library selectors are simple structural selectors; the validator
# keeps unbounded strings (workflow args) out of the query path.
_SELECTOR_RE = re.compile(r"""^[A-Za-z0-9_\-\s\[\]=."'(),:#>~*+|^$@%]+$""")
_FORBIDDEN_IN_SELECTOR = ("--", "/*", ";", "\x00")
class SeleniumDriverUnavailable(RuntimeError):
"""selenium is not installed in this environment."""
class SeleniumWorkflowDriver:
"""Envelope-compatible workflow driver over Selenium WebDriver."""
def __init__(self, engine: str = "chrome", headless: bool = True) -> None:
try:
import selenium # noqa: F401 β availability probe only
except ImportError as exc:
raise SeleniumDriverUnavailable(
"selenium is not installed β install the fallback extra with "
"`pip install .[selenium]` (or plain `pip install selenium`)"
) from exc
engine = engine.lower()
if engine not in {"chrome", "firefox", "edge", "chromium"}:
raise ValueError(
f"selenium driver engine must be chrome, firefox or edge, got '{engine}'"
)
self.engine = "chrome" if engine == "chromium" else engine
self.headless = headless
self._driver: Any = None
self._lock = asyncio.Lock()
# Latest observe snapshot only (same contract as ChatBrowserSession).
self._snapshot: dict[str, Any] | None = None
self._snapshot_id: str | None = None
self._started = False
# Static dispatch table (no dynamic attribute lookup on tool names).
self._handlers: dict[str, Any] = {
"browser_capabilities": self._tool_browser_capabilities,
"tab_open": self._tool_tab_open,
"tab_list": self._tool_tab_list,
"tab_select": self._tool_tab_select,
"tab_close": self._tool_tab_close,
"navigate": self._tool_navigate,
"observe": self._tool_observe,
"click": self._tool_click,
"type": self._tool_type,
"select_option": self._tool_select_option,
"press_key": self._tool_press_key,
"scroll": self._tool_scroll,
"extract_text": self._tool_extract_text,
"screenshot": self._tool_screenshot,
"wait_for": self._tool_wait_for,
"http_fetch": self._tool_http_fetch,
"web_search": self._tool_web_search,
}
# ββ lifecycle ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def start(self) -> None:
if self._started:
return
await asyncio.to_thread(self._start_sync)
self._started = True
def _prepare_runtime_dirs(self) -> None:
"""Redirect Selenium Manager's cache + temp into the app runtime root.
This environment denies writes under the user profile root AND the
real %TEMP% (the Playwright manager applies the same workaround):
Selenium Manager extracts its helper binary to TEMP and caches
drivers under ~/.cache/selenium β both fail with access denied.
"""
runtime = Path(__file__).resolve().parents[3] / ".browser-runtime"
cache = runtime / "selenium-cache"
temp = runtime / "tmp"
for directory in (cache, temp):
directory.mkdir(parents=True, exist_ok=True)
import os
os.environ["SE_CACHE_DIRECTORY"] = str(cache)
os.environ["TMP"] = str(temp)
os.environ["TEMP"] = str(temp)
def _start_sync(self) -> None:
from selenium import webdriver
self._prepare_runtime_dirs()
if self.engine == "chrome":
chrome_options = webdriver.ChromeOptions()
if self.headless:
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("--window-size=1280,800")
# Restricted-runtime workaround (diagnostics: session not created,
# DevToolsActivePort missing): chromedriver-launched Chrome cannot
# spawn its sandboxed helper processes here, so drop the sandbox
# and the GPU path β same spirit as manager's Firefox MOZ flags.
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-gpu")
self._driver = webdriver.Chrome(options=chrome_options)
elif self.engine == "edge":
edge_options = webdriver.EdgeOptions()
if self.headless:
edge_options.add_argument("--headless=new")
edge_options.add_argument("--window-size=1280,800")
edge_options.add_argument("--no-sandbox")
edge_options.add_argument("--disable-gpu")
self._driver = webdriver.Edge(options=edge_options)
else:
firefox_options = webdriver.FirefoxOptions()
if self.headless:
firefox_options.add_argument("-headless")
self._driver = webdriver.Firefox(options=firefox_options)
self._driver.set_window_size(1280, 800)
async def stop(self) -> None:
if self._driver is not None:
await asyncio.to_thread(self._safe_quit)
self._driver = None
self._started = False
self._snapshot = None
self._snapshot_id = None
def _safe_quit(self) -> None:
try:
self._driver.quit()
except Exception:
logger.debug("selenium driver quit failed during shutdown", exc_info=True)
def browser_connected(self) -> bool:
if self._driver is None:
return True # no session yet β handlers bootstrap one
try:
_ = self._driver.title # any command proves the session is alive
return True
except Exception: # noqa: BLE001
return False
# ββ element query gate βββββββββββββββββββββββββββββββββββββββββββββββββββ
# Every WebDriver lookup funnels through these two methods so nothing raw
# reaches the query API.
def _find_all(self, selector: str) -> list[Any]:
from selenium.webdriver.common.by import By
self._validate_selector(selector)
found: list[Any] = self._driver.find_elements(By.CSS_SELECTOR, selector)
return found
def _find_one(self, selector: str) -> Any:
elements = self._find_all(selector)
if not elements:
raise ValueError("no element matches the given selector")
return elements[0]
@staticmethod
def _validate_selector(selector: str) -> None:
if not selector or not _SELECTOR_RE.match(selector):
raise ValueError("selector rejected by the driver's allowlist")
for fragment in _FORBIDDEN_IN_SELECTOR:
if fragment in selector:
raise ValueError("selector contains a forbidden fragment")
# ββ network guard (the SAME policy the Playwright tools answer to) βββββββ
def _checked_url(self, url: str) -> str:
"""Validate a URL through the same guard ChatBrowserSession uses."""
from ..chat_tools import check_url
# Handlers run inside asyncio.to_thread workers: no running loop here,
# so a short-lived loop is the correct bridge.
return asyncio.run(check_url(url, context="selenium navigation"))
# ββ dispatch βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def run_tool(self, tool: str, args: dict[str, Any]) -> dict[str, Any]:
"""One workflow step -> the same envelope shape as tools.executor."""
handler = self._handlers.get(tool)
if handler is None:
# The supported list is built at runtime from the handler table so
# no tool name ever lands inside a string literal.
supported = ", ".join(sorted(self._handlers))
return {
"ok": False,
"tool": tool,
"error": {
"code": "UNSUPPORTED_IN_SELENIUM",
"message": (
"this tool is not implemented by the selenium driver "
f"(requested: {tool!r}); supported tools: {supported}"
),
},
}
try:
async with self._lock:
data = await asyncio.to_thread(handler, args or {})
if not isinstance(data, dict):
data = {"result": data}
# Match the executor's envelope contract: tab_id and verification
# live at the envelope's top level, never inside data.
tab_id = data.pop("tab_id", None)
verification = data.pop("verification", None)
envelope: dict[str, Any] = {"ok": True, "tool": tool, "data": data}
if tab_id is not None:
envelope["tab_id"] = tab_id
if verification is not None:
envelope["verification"] = verification
return envelope
except Exception as exc: # noqa: BLE001 β mirror the executor envelope
return {
"ok": False,
"tool": tool,
"error": {"code": _error_code(exc), "message": str(exc)[:500]},
}
# ββ capability βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _tool_browser_capabilities(self, args: dict[str, Any]) -> dict[str, Any]:
caps = self._driver.capabilities
return {
"name": str(caps.get("browserName", self.engine)),
"version": str(caps.get("browserVersion", caps.get("version", "unknown"))),
"channel": f"selenium:{self.engine}",
"headless": self.headless,
"webdriver": True,
}
# ββ tabs (browser windows) βββββββββββββββββββββββββββββββββββββββββββββββ
def _tool_tab_open(self, args: dict[str, Any]) -> dict[str, Any]:
url = (args.get("url") or "").strip()
if url and url.lower() != "about:blank":
url = self._checked_url(url)
self._driver.switch_to.new_window("tab")
if url and url.lower() != "about:blank":
self._driver.get(url)
tab_id = self._driver.current_window_handle
return {
"url": self._driver.current_url,
"title": self._driver.title,
"tab_id": tab_id,
"open_tabs": len(self._driver.window_handles),
"verification": {"passed": True, "description": f"window {tab_id} is active"},
}
def _tool_tab_list(self, args: dict[str, Any]) -> dict[str, Any]:
current = self._driver.current_window_handle
listed = []
for i, handle in enumerate(self._driver.window_handles):
self._driver.switch_to.window(handle)
listed.append({
"tab": i + 1,
"tab_id": handle,
"active": handle == current,
"title": self._driver.title,
"url": self._driver.current_url,
})
self._driver.switch_to.window(current)
return {"tabs": listed}
def _tool_tab_select(self, args: dict[str, Any]) -> dict[str, Any]:
tab_id = str(args.get("tab_id") or "")
if tab_id not in self._driver.window_handles:
raise ValueError(f"unknown tab id '{tab_id}' β call tab_list for the current ids")
self._driver.switch_to.window(tab_id)
return {"selected": tab_id, "url": self._driver.current_url, "title": self._driver.title}
def _tool_tab_close(self, args: dict[str, Any]) -> dict[str, Any]:
tab_id = args.get("tab_id")
if tab_id:
if tab_id not in self._driver.window_handles:
raise ValueError(f"unknown tab id '{tab_id}' β call tab_list for the current ids")
self._driver.switch_to.window(tab_id)
self._driver.close()
handles = self._driver.window_handles
if handles:
self._driver.switch_to.window(handles[0])
return {"closed": True, "open_tabs": len(handles)}
# Last window closed β the session ends with it; the next tool call
# restarts a driver, mirroring the Playwright rebuild behavior.
self._safe_quit()
self._driver = None
self._started = False
self._snapshot = None
self._snapshot_id = None
return {"closed": True, "open_tabs": 0}
# ββ navigation + reading βββββββββββββββββββββββββββββββββββββββββββββββββ
def _tool_navigate(self, args: dict[str, Any]) -> dict[str, Any]:
url = str(args.get("url") or "")
if not url:
raise ValueError("navigate requires a url")
url = self._checked_url(url)
self._driver.get(url)
return {"url": self._driver.current_url, "title": self._driver.title}
def _tool_extract_text(self, args: dict[str, Any]) -> dict[str, Any]:
selector = args.get("selector")
max_chars = int(args.get("max_chars") or 4000)
if selector:
elements = self._find_all(str(selector))
text = "\n".join(e.text for e in elements if e.text)
else:
text = self._find_one("body").text
return {"text": text[:max_chars], "selector": selector or "body"}
def _tool_screenshot(self, args: dict[str, Any]) -> dict[str, Any]:
shots_dir = Path.cwd() / ".browser-runtime" / "screenshots"
shots_dir.mkdir(parents=True, exist_ok=True)
path = shots_dir / f"selenium_{int(time.time() * 1000)}.png"
png = self._driver.get_screenshot_as_png()
path.write_bytes(png)
return {"path": str(path.resolve()), "bytes": len(png), "url": self._driver.current_url}
def _tool_wait_for(self, args: dict[str, Any]) -> dict[str, Any]:
from selenium.webdriver.support.ui import WebDriverWait
condition = args.get("condition", "selector")
timeout_s = min(int(args.get("timeout_ms", 5000)) / 1000.0, 15.0)
if condition == "selector":
selector = str(args.get("selector") or "")
if not selector:
raise ValueError("the wait_for selector condition needs a selector value")
WebDriverWait(self._driver, timeout_s).until(lambda d: self._find_all(selector))
return {"waited": selector}
if condition == "navigation":
WebDriverWait(self._driver, timeout_s).until(
lambda d: d.execute_script("return document.readyState") == "complete"
)
return {"waited": "navigation"}
# network_idle: best-effort settle
time.sleep(min(timeout_s, 2.0))
return {"waited": "network_idle"}
# ββ snapshot + actions (observe/find contract) βββββββββββββββββββββββββββ
OBSERVE_SELECTOR = (
'a, button, input, select, textarea, [role="button"], [role="link"], '
'[role="textbox"], [role="checkbox"], [role="combobox"]'
)
def _tool_observe(self, args: dict[str, Any]) -> dict[str, Any]:
elements: list[dict[str, Any]] = []
refs: list[Any] = []
for el in self._find_all(self.OBSERVE_SELECTOR)[:200]:
try:
if not el.is_displayed() or not el.is_enabled():
continue
except Exception:
logger.debug("skipping detached element during observe", exc_info=True)
continue
tag = el.tag_name.lower()
role = el.get_attribute("role") or _selenium_role(tag, el)
name = (
el.get_attribute("aria-label")
or el.get_attribute("placeholder")
or el.get_attribute("title")
or (el.text.strip().splitlines() or [""])[0]
)
elements.append({
"index": len(elements),
"role": role,
"accessible_name": str(name or "").strip()[:120],
"state": "",
"visible": True,
"enabled": True,
})
refs.append(el)
self._snapshot = {"elements": elements, "refs": refs}
self._snapshot_id = uuid.uuid4().hex
return {
"url": self._driver.current_url,
"title": self._driver.title,
"elements": elements,
"snapshot_id": self._snapshot_id,
}
def _resolve_element(self, args: dict[str, Any]) -> Any:
snapshot_id = str(args.get("snapshot_id") or "")
index = int(args.get("index", -1))
if self._snapshot is None or snapshot_id != self._snapshot_id:
raise ValueError(
f"snapshot_id '{snapshot_id}' is stale or unknown β call observe again"
)
refs = self._snapshot["refs"]
if not 0 <= index < len(refs):
raise ValueError(
f"element index {index} is not in snapshot '{snapshot_id}' β call observe again"
)
return refs[index]
def _tool_click(self, args: dict[str, Any]) -> dict[str, Any]:
el = self._resolve_element(args)
el.click()
return {"clicked": int(args.get("index", -1)), "url": self._driver.current_url}
def _tool_type(self, args: dict[str, Any]) -> dict[str, Any]:
el = self._resolve_element(args)
text = str(args.get("text") or "")
el.clear()
el.send_keys(text)
if args.get("submit"):
from selenium.webdriver.common.keys import Keys
el.send_keys(Keys.ENTER)
return {
"typed": int(args.get("index", -1)),
"text": text,
"submitted": bool(args.get("submit")),
}
def _tool_select_option(self, args: dict[str, Any]) -> dict[str, Any]:
from selenium.webdriver.support.ui import Select
el = self._resolve_element(args)
value = str(args.get("value") or "")
Select(el).select_by_value(value)
return {"selected": value}
def _tool_press_key(self, args: dict[str, Any]) -> dict[str, Any]:
from selenium.webdriver.common.keys import Keys
key = str(args.get("key") or "").strip()
token = _key_token(key, Keys)
self._driver.switch_to.active_element.send_keys(token)
return {"pressed": key}
def _tool_scroll(self, args: dict[str, Any]) -> dict[str, Any]:
pixels = int(args.get("pixels", 600))
# Parameterized script arguments β never string-built JS.
self._driver.execute_script("window.scrollBy(arguments[0], arguments[1]);", 0, pixels)
y = self._driver.execute_script("return window.scrollY;")
return {"scrolled": pixels, "scroll_y": y}
# ββ outside-the-browser tools (guarded, same as the Playwright path) βββββ
def _tool_http_fetch(self, args: dict[str, Any]) -> dict[str, Any]:
from .. import chat_tools
url = str(args.get("url") or "")
max_chars = int(args.get("max_chars") or 6000)
# chat_tools.web_fetch applies the network guard itself (DNS-checked,
# redirect-safe) β no raw fetch exists in this driver.
result = asyncio.run(chat_tools.web_fetch(url, max_chars))
return {**result, "source": "http"}
def _tool_web_search(self, args: dict[str, Any]) -> dict[str, Any]:
query = str(args.get("query") or "")
limit = int(args.get("max_results", 6))
url = "https://html.duckduckgo.com/html/?q=" + quote_plus(query)
self._driver.get(self._checked_url(url))
results = []
for el in self._find_all("div.result")[:limit]:
try:
link = el.find_element("css selector", "a")
results.append({"title": link.text.strip(), "url": link.get_attribute("href")})
except Exception:
logger.debug("skipping malformed search result block", exc_info=True)
continue
return {"query": query, "results": results, "count": len(results), "source": "search"}
def _selenium_role(tag: str, el: Any) -> str:
if tag == "a":
return "link"
if tag == "button" or (
tag == "input" and (el.get_attribute("type") or "") in {"button", "submit"}
):
return "button"
if tag == "select":
return "combobox"
if tag in {"textarea", "input"}:
return "textbox"
return tag
def _key_token(key: str, keys: Any) -> Any:
"""Map a workflow key name onto a Selenium Keys token (combo-aware)."""
lowered = key.lower().replace("control+", "ctrl+")
parts = [p for p in lowered.split("+") if p]
# Attribute names resolved lazily via getattr so fake Keys objects in
# tests only need the entries actually used.
named_attrs = {
"ctrl": "CONTROL", "alt": "ALT", "shift": "SHIFT",
"enter": "ENTER", "escape": "ESCAPE", "esc": "ESCAPE",
"tab": "TAB", "backspace": "BACK_SPACE", "delete": "DELETE",
"home": "HOME", "end": "END", "pageup": "PAGE_UP",
"pagedown": "PAGE_DOWN", "space": "SPACE",
"arrowup": "ARROW_UP", "arrowdown": "ARROW_DOWN",
"arrowleft": "ARROW_LEFT", "arrowright": "ARROW_RIGHT",
}
tokens = []
for part in parts:
if part in named_attrs:
tokens.append(getattr(keys, named_attrs[part]))
elif len(part) == 1:
tokens.append(part)
else:
raise ValueError(f"unrecognized key name: '{part}'")
if not tokens:
raise ValueError(f"unusable key spec: '{key}'")
return "".join(str(token) for token in tokens)
def _error_code(exc: Exception) -> str:
text = str(exc).lower()
if "invalid session" in text or "no such window" in text:
return "BROWSER_DISCONNECTED"
if "stale" in text or "snapshot" in text:
return "STALE_ELEMENT"
if "only http/https" in text or "forbidden address" in text or "loopback" in text:
return "POLICY_BLOCKED"
return "UNKNOWN"
# Variable substitution is re-exported so CLI callers pre-resolve {{var}} exactly
# like the Playwright path.
__all__ = ["SeleniumDriverUnavailable", "SeleniumWorkflowDriver", "substitute"]
|