Ship the bridge with the pack (moved from the agent core)

The core now keeps only the shared bridge contract (semif_agent/bridges/base.py)
and the discovery registry (semif_agent/bridges/registry.py); a pack ships its
own bridge under bridge/<name>.py and the registry imports it by convention from
the pack's declared `bridges`. The bridge's hermetic test moves here too and
runs via the agent repo's tests/test_packs.py (or standalone with conftest.py).
This commit is contained in:
gabby committed 2026-10-13 23:52:52 +00:00
1 parent e2be7e911c
commit 72bfd1ef5f
5 files changed
+1208

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
"""The browser pack's bridge: a localhost HTTP surface in front of its service.
The bridge implementation ships with the pack (see PACKGEN.md, "Authoring a
bridge"); the core imports it by convention from this package. It subclasses
`semif_agent.bridges.base.BridgeService` and declares a `BridgeInfo` catalog
entry that codegen reads via `describe_bridges()`.
"""
+369
View File
@@ -0,0 +1,369 @@
"""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 semif_agent.bridges.base import BridgeInfo, BridgeService, checkout_root
from .browser_client import (
DEFAULT_MAX_TEXT_CHARS,
DEFAULT_TIMEOUT,
ENGINES,
WAIT_UNTIL,
BrowserDriver,
BrowserError,
BrowserUnavailable,
)
#: The browser profile, binaries, and screenshots are anchored under the
#: checkout's gitignored `.runtime/` tree (the containment rule); the bridge
#: ships in its pack, so it asks the core for the root rather than deriving it
#: from its own (pack-relative) `__file__`.
DEFAULT_BROWSER_ROOT = str(checkout_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))
#: Optional escape hatch: use an installed browser instead of Playwright's
#: managed download. `channel` is a Playwright channel (chrome/msedge/...),
#: `executable_path` a specific binary; `executable_path` wins if both set.
self.channel = str(cfg.get("channel", "") or "").strip()
self.executable_path = str(cfg.get("executable_path", "") or "").strip()
#: 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,
channel=self.channel,
executable_path=self.executable_path,
)
# ---- 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)
+441
View File
@@ -0,0 +1,441 @@
"""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,
channel: str = "",
executable_path: str = "",
):
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))
#: Use an already-installed browser instead of Playwright's own build:
#: `channel` names a Playwright channel (`chrome`, `msedge`, ...) and
#: `executable_path` points at a specific binary. Both bypass the
#: managed-download requirement, useful where the CDN is unreachable.
self.channel = str(channel or "").strip()
self.executable_path = str(executable_path or "").strip()
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.
launch_options = {
"headless": self.headless,
"viewport": {"width": 1280, "height": 800},
"timeout": self.default_timeout * 1000,
}
if self.executable_path:
launch_options["executable_path"] = self.executable_path
elif self.channel:
launch_options["channel"] = self.channel
self._context = await browser_type.launch_persistent_context(
user_data_dir, **launch_options
)
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())
+374
View File
@@ -0,0 +1,374 @@
"""Pure-stdlib tests for the browser (Playwright) bridge.
The bridge is exercised over a real loopback HTTP server with a fake driver
standing in for the Playwright browser — the decision engine, the browser, and
Playwright itself are never involved. These prove the mechanics a skill depends
on: route wiring/validation, the token/auth surface, and the status mapping
(400 bad input, 503 unavailable, 502 real failure). Passing these proves
mechanics only; a real run against a real browser is the only proof the
integration works.
"""
import importlib
import json
import urllib.error
import urllib.request
import pytest
from semif_agent.bridges.registry import (
build_bridge,
derived_config_vars,
describe_bridges,
known_infos,
load_pack_bridge_module,
)
_browser = load_pack_bridge_module("browser", "browser")
BrowserBridge = _browser.BrowserBridge
_browser_client = importlib.import_module(f"{_browser.__package__}.browser_client")
BrowserDriver = _browser_client.BrowserDriver
BrowserError = _browser_client.BrowserError
BrowserUnavailable = _browser_client.BrowserUnavailable
class FakeDriver:
"""Stands in for the Playwright browser, recording every call."""
def __init__(self, error=None, unavailable=None):
self.error = error
self.unavailable = unavailable
self.calls = []
self.closed = False
def _maybe_fail(self):
if self.unavailable is not None:
raise BrowserUnavailable(self.unavailable)
if self.error is not None:
raise BrowserError(self.error)
def state(self):
self.calls.append(("state",))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def goto(self, url, wait_until="load", timeout=None):
self.calls.append(("goto", url, wait_until, timeout))
self._maybe_fail()
return {"url": url, "title": "Example", "status": 200}
def content(self, fmt="text", max_chars=None):
self.calls.append(("content", fmt, max_chars))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example", "format": fmt, "content": "hi", "truncated": False}
def text(self, selector):
self.calls.append(("text", selector))
self._maybe_fail()
return {"url": "https://example.com/", "selector": selector, "count": 1, "matches": [{"text": "hi"}]}
def links(self, query="", limit=50):
self.calls.append(("links", query, limit))
self._maybe_fail()
return {"url": "https://example.com/", "links": [{"text": "More", "href": "/more"}]}
def screenshot(self, full_page=False, selector="", inline=False):
self.calls.append(("screenshot", full_page, selector, inline))
self._maybe_fail()
return {"ok": True, "path": "/tmp/shot.png", "bytes": 12, "url": "https://example.com/", "title": "Example"}
def click(self, selector="", text="", index=0, timeout=None):
self.calls.append(("click", selector, text, index, timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def fill(self, selector, value, submit=False, timeout=None):
self.calls.append(("fill", selector, value, submit, timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def press(self, key, selector="", timeout=None):
self.calls.append(("press", key, selector, timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def select(self, selector, value=None, label=None, timeout=None):
self.calls.append(("select", selector, value, label, timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def wait_for(self, selector="", text="", timeout=None):
self.calls.append(("wait_for", selector, text, timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def back(self, timeout=None):
self.calls.append(("back", timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def forward(self, timeout=None):
self.calls.append(("forward", timeout))
self._maybe_fail()
return {"url": "https://example.com/", "title": "Example"}
def reset(self, purge=True):
self.calls.append(("reset", purge))
self._maybe_fail()
return {"ok": True, "purged": bool(purge)}
def close(self):
self.closed = True
def start_bridge(driver=None, **config):
driver = driver or FakeDriver()
bridge = BrowserBridge(config, client=driver)
port = bridge.start()
return bridge, driver, f"http://127.0.0.1:{port}"
def get(url, token=None):
headers = {"X-Semif-Token": token} if token else {}
request = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(request, timeout=5) as response:
return json.loads(response.read().decode("utf-8"))
def post(url, payload, token=None):
body = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json"}
if token:
headers["X-Semif-Token"] = token
request = urllib.request.Request(url, data=body, headers=headers)
with urllib.request.urlopen(request, timeout=5) as response:
return json.loads(response.read().decode("utf-8"))
def http_error(url, payload=None, token=None):
if payload is None:
request = urllib.request.Request(url)
else:
body = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json"}
if token:
headers["X-Semif-Token"] = token
request = urllib.request.Request(url, data=body, headers=headers)
with pytest.raises(urllib.error.HTTPError) as exc:
urllib.request.urlopen(request, timeout=5)
return exc.value
# ---- routes ----
def test_health_reports_engine_without_a_browser():
bridge, _driver, base = start_bridge(headless=False, engine="firefox")
try:
assert get(f"{base}/health") == {
"ok": True,
"platform": "browser",
"engine": "firefox",
"headless": False,
}
finally:
bridge.stop()
def test_read_routes_wire_to_the_driver():
bridge, driver, base = start_bridge()
try:
assert get(f"{base}/state") == {"url": "https://example.com/", "title": "Example"}
assert get(f"{base}/content?format=html&max_chars=500")["content"] == "hi"
assert get(f"{base}/text?selector=h1")["count"] == 1
assert get(f"{base}/links?query=more&limit=5")["links"][0]["href"] == "/more"
assert get(f"{base}/screenshot?full_page=true&inline=true")["path"] == "/tmp/shot.png"
assert driver.calls == [
("state",),
("content", "html", 500),
("text", "h1"),
("links", "more", 5),
("screenshot", True, "", True),
]
finally:
bridge.stop()
def test_action_routes_wire_to_the_driver():
bridge, driver, base = start_bridge()
try:
assert post(f"{base}/goto", {"url": "https://a.test/", "wait_until": "networkidle"})["status"] == 200
post(f"{base}/click", {"text": "Sign in"})
post(f"{base}/fill", {"selector": "#q", "value": "hi", "submit": True})
post(f"{base}/press", {"key": "Enter"})
post(f"{base}/select", {"selector": "select", "label": "Two"})
post(f"{base}/wait", {"text": "Done", "timeout": 5})
post(f"{base}/back", {})
post(f"{base}/forward", {})
post(f"{base}/reset", {"purge": False})
assert driver.calls == [
("goto", "https://a.test/", "networkidle", None),
("click", "", "Sign in", 0, None),
("fill", "#q", "hi", True, None),
("press", "Enter", "", None),
("select", "select", None, "Two", None),
("wait_for", "", "Done", 5.0),
("back", None),
("forward", None),
("reset", False),
]
finally:
bridge.stop()
def test_missing_url_is_400():
bridge, driver, base = start_bridge()
try:
exc = http_error(f"{base}/goto", {})
assert exc.code == 400
assert driver.calls == [], "a rejected goto must not touch the browser"
finally:
bridge.stop()
def test_bad_wait_until_and_content_format_are_400():
bridge, _driver, base = start_bridge()
try:
assert http_error(f"{base}/goto", {"url": "https://a.test", "wait_until": "whenever"}).code == 400
assert http_error(f"{base}/content?format=pdf").code == 400
finally:
bridge.stop()
def test_click_requires_selector_or_text():
bridge, _driver, base = start_bridge()
try:
assert http_error(f"{base}/click", {}).code == 400
finally:
bridge.stop()
def test_select_requires_value_or_label():
bridge, _driver, base = start_bridge()
try:
assert http_error(f"{base}/select", {"selector": "s"}).code == 400
finally:
bridge.stop()
def test_real_browser_failure_is_502():
bridge, _driver, base = start_bridge(driver=FakeDriver(error="net::ERR_NAME_NOT_RESOLVED"))
try:
exc = http_error(f"{base}/goto", {"url": "https://nope.invalid"})
assert exc.code == 502
assert b"ERR_NAME_NOT_RESOLVED" in exc.read()
finally:
bridge.stop()
def test_unavailable_browser_is_503_with_install_hint():
driver = FakeDriver(unavailable="install the browser bridge stack")
bridge, _driver, base = start_bridge(driver=driver)
try:
exc = http_error(f"{base}/state")
assert exc.code == 503
assert b"install the browser bridge stack" in exc.read()
# /health still answers, so the bridge is diagnosable without a browser.
assert get(f"{base}/health")["ok"] is True
finally:
bridge.stop()
def test_unknown_route_is_404():
bridge, _driver, base = start_bridge()
try:
assert http_error(f"{base}/nope").code == 404
finally:
bridge.stop()
def test_token_guards_the_bridge():
bridge, _driver, base = start_bridge(token="sekret")
try:
assert http_error(f"{base}/state", token=None).code == 401
assert get(f"{base}/health", token="sekret")["platform"] == "browser"
finally:
bridge.stop()
def test_stop_closes_the_driver():
bridge, driver, _base = start_bridge()
bridge.stop()
assert driver.closed is True
def test_check_requirements_never_blocks_startup():
# An optional dependency must not take down the other bridges, so the check
# is honest-but-permissive and a missing browser surfaces as a 503 on use.
assert BrowserBridge({}).check_requirements() == (True, None)
def test_bad_engine_falls_back_to_chromium():
assert BrowserBridge({"engine": "netscape"}).engine == "chromium"
assert BrowserBridge({"engine": "WebKit"}).engine == "webkit"
def test_executable_path_and_channel_are_plumbed():
bridge = BrowserBridge(
{"channel": "chrome", "executable_path": "/usr/bin/google-chrome"}
)
assert bridge.channel == "chrome"
assert bridge.executable_path == "/usr/bin/google-chrome"
# The real driver (no injected double) carries them; executable_path wins at
# launch, so the managed download is skipped entirely.
assert bridge.client.channel == "chrome"
assert bridge.client.executable_path == "/usr/bin/google-chrome"
def test_driver_defaults_to_managed_browser():
driver = BrowserDriver()
assert driver.channel == ""
assert driver.executable_path == ""
# ---- driver dependency handling ----
def test_driver_unavailable_without_playwright(monkeypatch):
monkeypatch.setattr(_browser_client.importlib.util, "find_spec", lambda name: None)
driver = BrowserDriver()
assert driver.configured is False
with pytest.raises(BrowserUnavailable):
driver.state()
# No dangling loop/thread was started.
driver.close()
# ---- catalog / codegen surface ----
def test_known_infos_include_browser():
infos = {info.name: info for info in known_infos()}
assert "browser" in infos
info = infos["browser"]
assert info.service == "browser"
assert info.url_config_var == "browser_bridge_url"
assert info.auth_header == "X-Semif-Token"
assert info.auth_config_var == "browser_bridge_token"
assert any("/goto" in endpoint for endpoint in info.endpoints)
def test_describe_bridges_covers_browser():
text = describe_bridges()
assert "browser_bridge_url" in text
assert "/screenshot" in text
assert "Playwright" in text
def test_derived_config_vars_for_browser():
config = {"bridges": {"browser": {"host": "127.0.0.1", "port": 5232, "token": "b"}}}
derived = derived_config_vars(config)
assert derived["browser_bridge_url"] == "http://127.0.0.1:5232"
assert derived["browser_bridge_token"] == "b"
def test_build_bridge_returns_browser():
bridge = build_bridge({"bridges": {"browser": {"port": 5232}}}, "browser")
assert isinstance(bridge, BrowserBridge)
+17
View File
@@ -0,0 +1,17 @@
"""Make the agent checkout importable when running this pack's tests standalone.
A pack's bridge test imports `semif_agent` (the shared bridge contract and the
discovery registry). The pack lives inside an agent checkout at `packs/<name>/`,
so this adds the checkout root to `sys.path` — running the tests through the
agent repo (`pytest tests/test_packs.py`) already provides it, but
`cd packs/<name> && pytest` needs this.
"""
import sys
from pathlib import Path
for _parent in Path(__file__).resolve().parents:
if (_parent / "semif_agent" / "__init__.py").is_file():
if str(_parent) not in sys.path:
sys.path.insert(0, str(_parent))
break