"""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"]