bridges: browser automation via Playwright

Add a `browser` bridge: real browser automation behind the standard
token-guarded localhost JSON surface, so a codegen-authored skill body never
bundles a browser stack. It opens a URL, reads a page's text or links, takes a
screenshot, and clicks/fills/presses/selects to complete a flow.

Unlike the stdlib-only Nextcloud/Outlook bridges this one owns a browser and
needs a heavy optional dependency, so it is disabled by default and installed
with `scripts/bootstrap.sh --browser` (Playwright pinned in
requirements/browser.txt; the browser binary lands under the checkout's
.runtime/browser, which the driver points PLAYWRIGHT_BROWSERS_PATH at).

- `BrowserBridge` (`bridges/browser.py`) + `BrowserDriver`
  (`bridges/browser_client.py`). A real navigation/timeout/selector failure is a
  502, a missing package/browser a 503 install hint, bad input a 400 -- never a
  fabricated success.
- `check_requirements()` deliberately never blocks: `run_bridges()` aborts all
  bridges when one fails, and this dependency is optional, so a missing
  Playwright must degrade to a per-call 503, not take down the others.
- Playwright's sync API is bound to its creating thread while the bridge serves
  each request on a new one, so the driver runs the async API on one dedicated
  event-loop thread and serializes whole operations behind an asyncio.Lock
  (submitted with run_coroutine_threadsafe).
- Persistent profile under .runtime/browser/profile so logins/cookies survive
  across calls and restarts; POST /reset with purge=true wipes it, and
  headless=false shows the window for a first sign-in. Route set: /health,
  /state, /content, /text, /links, /screenshot, /goto, /click, /fill, /press,
  /select, /wait, /back, /forward, /reset. No arbitrary JS evaluate (out of
  scope for this cut).
- Seeds: `seeds/browser/{open_page,read_page,screenshot}`, each hermetically
  tested against a loopback bridge. A `browser` category description is seeded
  so the leaf softmax has signal.
- `tests/test_browser_bridge.py` exercises the routes over a loopback HTTP
  server with an injected fake driver (no browser or Playwright needed). The
  live browser is a provisioned-host concern: this box could not reach the
  Playwright CDN, so no real-browser run backs it yet.
This commit is contained in:
gabby committed 2026-10-11 09:32:47 +00:00
1 parent c010cdb44e
commit 6240392632
24 files changed
+2079 -7

No files matched your search

+2 -1
View File
@@ -1,7 +1,8 @@
"""Third-party API bridges: a secure local layer between skills and services.
A **bridge service** is a standalone process that exposes one third-party system
(SimpleX, the local language model, Nextcloud, Microsoft Graph / Outlook) to
(SimpleX, the local language model, Nextcloud, Microsoft Graph / Outlook, a real
web browser via Playwright) to
codegen-authored skill bodies
over a local, token-guarded HTTP API. It exists so a generated body never speaks
a system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat
+362
View File
@@ -0,0 +1,362 @@
"""Browser bridge: real browser automation (Playwright) behind HTTP.
A codegen-authored skill body must never drive a browser directly, and it must
never bundle a heavy, platform-specific automation stack. This bridge owns the
browser — a single Chromium (or Firefox/WebKit) instance with a persistent
profile — and exposes one uniform, token-guarded localhost JSON API for reading
a page (text/links/screenshot) and acting on it (goto/click/fill/press/select/
wait/back/forward), so a body only reads `browser_bridge_url` and
`browser_bridge_token` from `ctx.config` and calls a documented route.
Unlike Nextcloud/Outlook this bridge needs a real optional dependency
(`playwright` plus browser binaries), so it is **disabled by default**; install
it with `scripts/bootstrap.sh --browser` (browsers land under
`.runtime/browser`). The dependency and the browser are lazy: a host without
them still runs every other bridge. `check_requirements()` deliberately always
returns ok — `run_bridges()` aborts *all* bridges when one's requirements fail,
and this dependency is optional, so a missing Playwright must degrade to a
per-call 503 (with an install hint), never take down simplex/llm/nextcloud.
The actual Playwright work lives in `browser_client.py`; the routes here
validate input and map a real failure (`BrowserError`) to a 502, a missing
dependency/browser (`BrowserUnavailable`) to a 503, and bad input to a 400 —
never a fabricated success.
"""
from __future__ import annotations
from pathlib import Path
from .base import BridgeInfo, BridgeService
from .browser_client import (
DEFAULT_MAX_TEXT_CHARS,
DEFAULT_TIMEOUT,
ENGINES,
WAIT_UNTIL,
BrowserDriver,
BrowserError,
BrowserUnavailable,
)
#: The checkout root (`semif_agent/bridges/browser.py` -> repo root), used to
#: anchor the browser profile, binaries, and screenshots under the gitignored
#: `.runtime/` tree (the containment rule).
_REPO_ROOT = Path(__file__).resolve().parents[2]
DEFAULT_BROWSER_ROOT = str(_REPO_ROOT / ".runtime" / "browser")
DEFAULT_PROFILE_DIR = str(Path(DEFAULT_BROWSER_ROOT) / "profile")
DEFAULT_SCREENSHOT_DIR = str(Path(DEFAULT_BROWSER_ROOT) / "screenshots")
class BrowserBridge(BridgeService):
name = "browser"
INFO = BridgeInfo(
name="browser",
service="browser",
description=(
"Drive a real web browser (Playwright): open a URL, read a page's "
"text or links, take a screenshot, and click/fill/press/select to "
"navigate a site and complete a flow. Keeps a persistent profile so "
"logins and cookies survive across calls."
),
url_config_var="browser_bridge_url",
endpoints=(
"GET /health -> 200 {\"ok\": true, \"platform\": \"browser\", "
"\"engine\", \"headless\"} — the bridge is up",
"GET /state -> 200 {\"url\", \"title\"} — the current page",
"GET /content?format=text|html&max_chars=<n> -> 200 {\"url\", "
"\"title\", \"format\", \"content\", \"truncated\"} — the whole page's "
"rendered text (format defaults to text, the default when you just "
"want to read a page); content is truncated to max_chars",
"GET /text?selector=<css> -> 200 {\"url\", \"selector\", \"count\", "
"\"matches\": [{\"text\"}]} — text of every element matching a CSS "
"selector",
"GET /links?query=<text>&limit=<n> -> 200 {\"url\", \"links\": "
"[{\"text\", \"href\"}]} — anchors on the page, optionally filtered "
"by a substring of the label or href",
"GET /screenshot?full_page=<bool>&selector=<css>&inline=<bool> -> 200 "
"{\"ok\": true, \"path\", \"bytes\", \"url\", \"title\"} — saves a PNG "
"under the checkout's .runtime/browser/screenshots (add inline=true "
"for base64 in the reply)",
"POST /goto {\"url\", \"wait_until\"?: commit|domcontentloaded|load|"
"networkidle, \"timeout\"?: seconds} -> 200 {\"url\", \"title\", "
"\"status\"} — navigates; a navigation error (bad host, TLS, timeout) "
"is a 502",
"POST /click {\"selector\"?| \"text\"?, \"index\"?: 0, \"timeout\"?} "
"-> 200 {\"url\", \"title\"} — clicks by CSS selector or by visible "
"text (index picks among several matches)",
"POST /fill {\"selector\", \"value\", \"submit\"?: bool, "
"\"timeout\"?} -> 200 {\"url\", \"title\"} — types into an input; "
"submit=true presses Enter",
"POST /press {\"key\", \"selector\"?, \"timeout\"?} -> 200 {\"url\", "
"\"title\"} — presses a keyboard key (e.g. Enter, Escape, Tab)",
"POST /select {\"selector\", \"value\"?|\"label\"?, \"timeout\"?} -> "
"200 {\"url\", \"title\"} — chooses an option in a <select>",
"POST /wait {\"selector\"?| \"text\"?, \"timeout\"?} -> 200 {\"url\", "
"\"title\"} — waits for an element/text to appear",
"POST /back | /forward {\"timeout\"?} -> 200 {\"url\", \"title\"}",
"POST /reset {\"purge\"?: bool default true} -> 200 {\"ok\", "
"\"purged\"} — closes the browser; purge=true (default) also deletes "
"the stored profile so the next call starts logged out",
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
"configured and the auth header is missing or wrong",
"503 {\"error\": \"...\"} when Playwright or its browser binaries are "
"not installed (run scripts/bootstrap.sh --browser); 502 {\"error\": "
"\"...\"} on a real browser failure (navigation, timeout, bad "
"selector)",
),
config_vars=("browser_bridge_url", "browser_bridge_token"),
config_var_docs=(
(
"browser_bridge_url",
"Base URL of the local browser bridge (e.g. "
"http://127.0.0.1:5232); never hardcode it in the body.",
),
(
"browser_bridge_token",
"Shared secret for the bridge, if one is configured; sent as the "
"X-Semif-Token header. Leave blank when the bridge requires no auth.",
),
),
auth_header="X-Semif-Token",
auth_config_var="browser_bridge_token",
)
def __init__(self, config: dict | None = None, trace=None, client=None):
super().__init__(config, trace)
cfg = config or {}
engine = str(cfg.get("engine", "chromium") or "chromium").strip().lower()
self.engine = engine if engine in ENGINES else "chromium"
self.headless = bool(cfg.get("headless", True))
self.profile_dir = str(cfg.get("profile_dir") or DEFAULT_PROFILE_DIR)
self.browsers_path = str(cfg.get("browsers_path") or DEFAULT_BROWSER_ROOT)
self.screenshot_dir = str(cfg.get("screenshot_dir") or DEFAULT_SCREENSHOT_DIR)
self.default_timeout = float(cfg.get("default_timeout", DEFAULT_TIMEOUT))
self.max_text_chars = int(cfg.get("max_text_chars", DEFAULT_MAX_TEXT_CHARS))
#: A test seam: inject a driver double. Production builds the real one.
self.client = client or BrowserDriver(
engine=self.engine,
headless=self.headless,
profile_dir=self.profile_dir,
browsers_path=self.browsers_path,
screenshot_dir=self.screenshot_dir,
default_timeout=self.default_timeout,
max_text_chars=self.max_text_chars,
)
# ---- lifecycle ----
def check_requirements(self) -> tuple[bool, str | None]:
# Deliberately never blocks startup: a missing Playwright/browser is an
# optional-dependency problem and must not take down the other bridges
# (run_bridges aborts them all on a failed check). It surfaces as a 503
# on the call instead.
return True, None
def _stop_transport(self) -> None:
close = getattr(self.client, "close", None)
if callable(close):
try:
close()
except Exception:
pass
# ---- routes ----
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
if path == "/health":
return 200, {
"ok": True,
"platform": self.name,
"engine": self.engine,
"headless": self.headless,
}
try:
return self._get(path, query)
except BrowserUnavailable as exc:
return 503, {"error": str(exc)[:400]}
except BrowserError as exc:
return 502, {"error": str(exc)[:300]}
except ValueError as exc:
return 400, {"error": str(exc)[:300]}
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
try:
return self._post(path, payload)
except BrowserUnavailable as exc:
return 503, {"error": str(exc)[:400]}
except BrowserError as exc:
return 502, {"error": str(exc)[:300]}
except ValueError as exc:
return 400, {"error": str(exc)[:300]}
def _get(self, path: str, query: dict) -> tuple[int, dict]:
if path == "/state":
return 200, self.client.state()
if path == "/content":
fmt = (self._q(query, "format", "text") or "text").strip().lower()
if fmt not in ("text", "html"):
raise ValueError("format must be text or html")
max_chars = self._int_query_opt(query, "max_chars")
return 200, self.client.content(fmt, max_chars)
if path == "/text":
return 200, self.client.text(self._required_query(query, "selector"))
if path == "/links":
return 200, self.client.links(
self._q(query, "query", "") or "", self._int_query(query, "limit", 50)
)
if path == "/screenshot":
return 200, self.client.screenshot(
self._bool_query(query, "full_page", False),
self._q(query, "selector", "") or "",
self._bool_query(query, "inline", False),
)
return 404, {"error": "not found"}
def _post(self, path: str, payload: dict) -> tuple[int, dict]:
if path == "/goto":
wait_until = (
self._optional_str(payload, "wait_until", "load") or "load"
).strip().lower()
if wait_until not in WAIT_UNTIL:
raise ValueError(f"wait_until must be one of {', '.join(WAIT_UNTIL)}")
return 200, self.client.goto(
self._required(payload, "url"),
wait_until,
self._optional_float(payload, "timeout"),
)
if path == "/click":
selector = self._optional_str(payload, "selector")
text = self._optional_str(payload, "text")
if not selector and not text:
raise ValueError("selector or text is required")
return 200, self.client.click(
selector,
text,
self._optional_int(payload, "index", 0) or 0,
self._optional_float(payload, "timeout"),
)
if path == "/fill":
return 200, self.client.fill(
self._required(payload, "selector"),
self._required(payload, "value", allow_empty=True),
self._optional_bool(payload, "submit", False),
self._optional_float(payload, "timeout"),
)
if path == "/press":
return 200, self.client.press(
self._required(payload, "key"),
self._optional_str(payload, "selector"),
self._optional_float(payload, "timeout"),
)
if path == "/select":
value = self._optional_str(payload, "value") or None
label = self._optional_str(payload, "label") or None
if value is None and label is None:
raise ValueError("value or label is required")
return 200, self.client.select(
self._required(payload, "selector"),
value,
label,
self._optional_float(payload, "timeout"),
)
if path == "/wait":
selector = self._optional_str(payload, "selector")
text = self._optional_str(payload, "text")
if not selector and not text:
raise ValueError("selector or text is required")
return 200, self.client.wait_for(
selector, text, self._optional_float(payload, "timeout")
)
if path == "/back":
return 200, self.client.back(self._optional_float(payload, "timeout"))
if path == "/forward":
return 200, self.client.forward(self._optional_float(payload, "timeout"))
if path == "/reset":
return 200, self.client.reset(self._optional_bool(payload, "purge", True))
return 404, {"error": "not found"}
# ---- input helpers ----
@staticmethod
def _q(query: dict, key: str, default=None):
values = query.get(key)
if not values:
return default
return values[0]
@staticmethod
def _required_query(query: dict, key: str) -> str:
value = BrowserBridge._q(query, key)
if value is None or not str(value).strip():
raise ValueError(f"{key} is required")
return str(value).strip()
@staticmethod
def _int_query(query: dict, key: str, default: int) -> int:
value = BrowserBridge._q(query, key)
if value is None or str(value).strip() == "":
return default
try:
return int(str(value))
except ValueError as exc:
raise ValueError(f"{key} must be an integer") from exc
@staticmethod
def _int_query_opt(query: dict, key: str):
value = BrowserBridge._q(query, key)
if value is None or str(value).strip() == "":
return None
try:
return int(str(value))
except ValueError as exc:
raise ValueError(f"{key} must be an integer") from exc
@staticmethod
def _bool_query(query: dict, key: str, default: bool) -> bool:
value = BrowserBridge._q(query, key)
if value is None or str(value).strip() == "":
return default
return str(value).strip().lower() in ("1", "true", "yes", "on")
@staticmethod
def _required(payload: dict, key: str, allow_empty: bool = False) -> str:
value = payload.get(key)
if not isinstance(value, str) or (not allow_empty and not value.strip()):
raise ValueError(f"{key} is required")
return value if allow_empty else value.strip()
@staticmethod
def _optional_str(payload: dict, key: str, default: str = "") -> str:
value = payload.get(key)
if value is None:
return default
if not isinstance(value, str):
raise ValueError(f"{key} must be a string")
return value
@staticmethod
def _optional_bool(payload: dict, key: str, default: bool) -> bool:
value = payload.get(key)
if value is None:
return default
if not isinstance(value, bool):
raise ValueError(f"{key} must be a boolean")
return value
@staticmethod
def _optional_int(payload: dict, key: str, default: int | None = None):
value = payload.get(key)
if value is None:
return default
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError(f"{key} must be an integer")
return value
@staticmethod
def _optional_float(payload: dict, key: str):
value = payload.get(key)
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError(f"{key} must be a number")
return float(value)
+427
View File
@@ -0,0 +1,427 @@
"""A real browser driver for the browser bridge, backed by Playwright.
The browser bridge calls this instead of a skill body driving a browser
directly. It owns a single Chromium (or Firefox/WebKit) instance with a
**persistent profile** under the checkout's `.runtime/browser/profile`, so a
logged-in session survives across calls and restarts, and exposes plain methods
that return dicts.
Playwright's synchronous API is bound to the thread that created it and is not
thread-safe, but the bridge's HTTP server handles each request on a new thread.
So this driver runs the **async** API on one dedicated event-loop thread and
serializes whole operations behind an `asyncio.Lock`; route handlers submit a
coroutine onto that loop with `run_coroutine_threadsafe` and wait for the
result. Browser automation is inherently serial, so one loop is enough.
Only the standard library is imported eagerly; `playwright` is imported lazily
the first time the browser is actually needed, so a host without it still runs
every other bridge. A missing package (or a missing browser binary) raises
`BrowserUnavailable`, which the bridge maps to a 503 install hint; every other
failure is a `BrowserError`, mapped to a 502 — never a fabricated success.
"""
from __future__ import annotations
import asyncio
import base64
import importlib.util
import os
import shutil
import tempfile
import threading
import uuid
from concurrent.futures import TimeoutError as FuturesTimeoutError
from pathlib import Path
DEFAULT_ENGINE = "chromium"
ENGINES = ("chromium", "firefox", "webkit")
DEFAULT_TIMEOUT = 30.0
DEFAULT_MAX_TEXT_CHARS = 20000
#: Cap on how many elements a single `text` / `links` call returns.
DEFAULT_MAX_MATCHES = 50
WAIT_UNTIL = ("commit", "domcontentloaded", "load", "networkidle")
INSTALL_HINT = (
"install the browser bridge stack: pip install -r requirements/browser.txt "
"&& PLAYWRIGHT_BROWSERS_PATH=<repo>/.runtime/browser python -m playwright "
"install chromium"
)
class BrowserError(Exception):
"""A real failure driving the browser (navigation, timeout, bad selector)."""
class BrowserUnavailable(BrowserError):
"""Playwright or its browser binaries are not installed / cannot launch."""
class BrowserDriver:
"""One persistent browser, driven from a single dedicated event-loop thread."""
def __init__(
self,
engine: str = DEFAULT_ENGINE,
headless: bool = True,
profile_dir: str = "",
browsers_path: str = "",
screenshot_dir: str = "",
default_timeout: float = DEFAULT_TIMEOUT,
max_text_chars: int = DEFAULT_MAX_TEXT_CHARS,
):
self.engine = engine if engine in ENGINES else DEFAULT_ENGINE
self.headless = bool(headless)
self.profile_dir = str(profile_dir or "")
self.browsers_path = str(browsers_path or "")
self.screenshot_dir = str(screenshot_dir or "")
self.default_timeout = float(default_timeout)
self.max_text_chars = max(200, int(max_text_chars))
self._loop: asyncio.AbstractEventLoop | None = None
self._thread: threading.Thread | None = None
self._lock: asyncio.Lock | None = None
self._start_lock = threading.Lock()
self._playwright = None
self._context = None
self._page = None
# ---- availability ----
@property
def configured(self) -> bool:
"""Whether the `playwright` package is importable (cheap; no browser)."""
return importlib.util.find_spec("playwright") is not None
# ---- lifecycle ----
def _ensure_started(self) -> None:
with self._start_lock:
if self._loop is not None:
return
if not self.configured:
raise BrowserUnavailable(INSTALL_HINT)
# Locate browser binaries under the checkout before Playwright reads
# the env var. The bridge cannot rely on the shell exporting it.
if self.browsers_path:
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = self.browsers_path
loop = asyncio.new_event_loop()
self._loop = loop
ready = threading.Event()
def runner() -> None:
asyncio.set_event_loop(loop)
self._lock = asyncio.Lock()
ready.set()
loop.run_forever()
self._thread = threading.Thread(target=runner, name="browser-driver", daemon=True)
self._thread.start()
ready.wait(5.0)
def _run(self, coro, timeout: float | None = None):
"""Schedule `coro` on the driver loop and wait for its result."""
if self._loop is None:
coro.close()
raise BrowserUnavailable(INSTALL_HINT)
budget = (timeout if timeout else self.default_timeout) + 15.0
future = asyncio.run_coroutine_threadsafe(coro, self._loop)
try:
return future.result(budget)
except FuturesTimeoutError as exc:
future.cancel()
raise BrowserError(f"browser operation timed out after {budget:.0f}s") from exc
def _operation(self, fn, timeout: float | None = None):
"""Run `fn(page)` under the serialization lock, launching if needed."""
self._ensure_started()
async def runner():
assert self._lock is not None
async with self._lock:
page = await self._ensure_context()
return await fn(page)
return self._run(runner(), timeout=timeout)
async def _ensure_context(self):
if self._page is not None and not self._page.is_closed():
return self._page
if self._playwright is None:
from playwright.async_api import async_playwright
self._playwright = await async_playwright().start()
browser_type = getattr(self._playwright, self.engine, None)
if browser_type is None:
raise BrowserError(f"unknown browser engine {self.engine!r}")
if self.profile_dir:
Path(self.profile_dir).mkdir(parents=True, exist_ok=True)
user_data_dir = self.profile_dir
else:
# No persistent profile configured: still a real context, just
# ephemeral (Playwright rejects a None user_data_dir).
user_data_dir = tempfile.mkdtemp(prefix="semif-browser-")
try:
# A persistent context keeps cookies/logins on disk across calls and
# restarts; it is the browser analog of the SimpleX bridge owning its
# own profile.
self._context = await browser_type.launch_persistent_context(
user_data_dir,
headless=self.headless,
viewport={"width": 1280, "height": 800},
timeout=self.default_timeout * 1000,
)
except BrowserUnavailable:
raise
except Exception as exc: # missing browser binary, launch failure, ...
raise BrowserUnavailable(
f"could not launch {self.engine} (is the browser installed? "
f"{INSTALL_HINT}): {exc}"
) from exc
pages = self._context.pages
self._page = pages[0] if pages else await self._context.new_page()
return self._page
async def _close_context(self) -> None:
self._page = None
context, self._context = self._context, None
if context is not None:
try:
await context.close()
except Exception:
pass
def close(self) -> None:
"""Tear down the browser and the driver loop (from `_stop_transport`)."""
loop, self._loop = self._loop, None
if loop is None:
return
try:
future = asyncio.run_coroutine_threadsafe(self._shutdown(), loop)
future.result(timeout=15.0)
except Exception:
pass
loop.call_soon_threadsafe(loop.stop)
thread, self._thread = self._thread, None
if thread is not None:
thread.join(timeout=5.0)
try:
loop.close()
except Exception:
pass
async def _shutdown(self) -> None:
await self._close_context()
if self._playwright is not None:
try:
await self._playwright.stop()
except Exception:
pass
self._playwright = None
# ---- operations (each returns a plain dict) ----
def state(self) -> dict:
async def _do(page):
return {"url": page.url, "title": await page.title()}
return self._operation(_do)
def goto(self, url: str, wait_until: str = "load", timeout: float | None = None) -> dict:
async def _do(page):
response = await page.goto(
url, wait_until=wait_until, timeout=(timeout or self.default_timeout) * 1000
)
return {
"url": page.url,
"title": await page.title(),
"status": response.status if response is not None else None,
}
return self._operation(_do, timeout=timeout)
def content(self, fmt: str = "text", max_chars: int | None = None) -> dict:
limit = max(200, int(max_chars)) if max_chars else self.max_text_chars
async def _do(page):
if fmt == "html":
raw = await page.content()
else:
raw = await page.inner_text("body")
text = raw or ""
return {
"url": page.url,
"title": await page.title(),
"format": fmt,
"content": text[:limit],
"truncated": len(text) > limit,
}
return self._operation(_do)
def text(self, selector: str) -> dict:
async def _do(page):
locator = page.locator(selector)
count = await locator.count()
matches = []
for index in range(min(count, DEFAULT_MAX_MATCHES)):
value = await locator.nth(index).inner_text()
matches.append({"text": (value or "").strip()[:2000]})
return {
"url": page.url,
"selector": selector,
"count": count,
"matches": matches,
}
return self._operation(_do)
def links(self, query: str = "", limit: int = 50) -> dict:
max_links = max(1, min(int(limit), 200))
async def _do(page):
anchors = await page.query_selector_all("a")
needle = query.strip().lower()
out = []
for element in anchors:
href = await element.get_attribute("href")
if not href:
continue
label = ((await element.inner_text()) or "").strip()
if needle and needle not in f"{label} {href}".lower():
continue
out.append({"text": label[:300], "href": href})
if len(out) >= max_links:
break
return {"url": page.url, "links": out}
return self._operation(_do)
def screenshot(
self, full_page: bool = False, selector: str = "", inline: bool = False
) -> dict:
async def _do(page):
directory = self.screenshot_dir or "/tmp"
Path(directory).mkdir(parents=True, exist_ok=True)
path = os.path.join(directory, f"{uuid.uuid4().hex}.png")
if selector:
await page.locator(selector).first.screenshot(path=path)
else:
await page.screenshot(path=path, full_page=bool(full_page))
result = {
"ok": True,
"path": path,
"bytes": os.path.getsize(path),
"url": page.url,
"title": await page.title(),
}
if inline:
with open(path, "rb") as handle:
result["base64"] = base64.b64encode(handle.read()).decode("ascii")
return result
return self._operation(_do)
def click(
self,
selector: str = "",
text: str = "",
index: int = 0,
timeout: float | None = None,
) -> dict:
async def _do(page):
if selector:
locator = page.locator(selector).nth(int(index))
else:
locator = page.get_by_text(text, exact=False).nth(int(index))
await locator.click(timeout=(timeout or self.default_timeout) * 1000)
return {"url": page.url, "title": await page.title()}
return self._operation(_do, timeout=timeout)
def fill(
self,
selector: str,
value: str,
submit: bool = False,
timeout: float | None = None,
) -> dict:
async def _do(page):
budget = (timeout or self.default_timeout) * 1000
await page.fill(selector, value, timeout=budget)
if submit:
await page.press(selector, "Enter", timeout=budget)
return {"url": page.url, "title": await page.title()}
return self._operation(_do, timeout=timeout)
def press(self, key: str, selector: str = "", timeout: float | None = None) -> dict:
async def _do(page):
await page.press(
selector or "body", key, timeout=(timeout or self.default_timeout) * 1000
)
return {"url": page.url, "title": await page.title()}
return self._operation(_do, timeout=timeout)
def select(
self,
selector: str,
value: str | None = None,
label: str | None = None,
timeout: float | None = None,
) -> dict:
async def _do(page):
budget = (timeout or self.default_timeout) * 1000
if value is not None:
await page.select_option(selector, value=value, timeout=budget)
else:
await page.select_option(selector, label=label, timeout=budget)
return {"url": page.url, "title": await page.title()}
return self._operation(_do, timeout=timeout)
def wait_for(
self, selector: str = "", text: str = "", timeout: float | None = None
) -> dict:
async def _do(page):
budget = (timeout or self.default_timeout) * 1000
if selector:
await page.wait_for_selector(selector, timeout=budget)
else:
await page.get_by_text(text, exact=False).first.wait_for(timeout=budget)
return {"url": page.url, "title": await page.title()}
return self._operation(_do, timeout=timeout)
def back(self, timeout: float | None = None) -> dict:
async def _do(page):
await page.go_back(
wait_until="load", timeout=(timeout or self.default_timeout) * 1000
)
return {"url": page.url, "title": await page.title()}
return self._operation(_do, timeout=timeout)
def forward(self, timeout: float | None = None) -> dict:
async def _do(page):
await page.go_forward(
wait_until="load", timeout=(timeout or self.default_timeout) * 1000
)
return {"url": page.url, "title": await page.title()}
return self._operation(_do, timeout=timeout)
def reset(self, purge: bool = True) -> dict:
"""Close the browser; delete the stored profile when `purge` is true."""
self._ensure_started()
async def _do():
assert self._lock is not None
async with self._lock:
await self._close_context()
purged = False
if purge and self.profile_dir:
shutil.rmtree(self.profile_dir, ignore_errors=True)
purged = True
return {"ok": True, "purged": purged}
return self._run(_do())
+2
View File
@@ -13,6 +13,7 @@ from __future__ import annotations
import threading
from .base import BridgeInfo, BridgeService
from .browser import BrowserBridge
from .llm import LLMBridge
from .nextcloud import NextcloudBridge
from .outlook import OutlookBridge
@@ -24,6 +25,7 @@ CATALOG: tuple[type[BridgeService], ...] = (
LLMBridge,
NextcloudBridge,
OutlookBridge,
BrowserBridge,
)