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

+4
View File
@@ -0,0 +1,4 @@
{
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
}
+3
View File
@@ -0,0 +1,3 @@
{
"description": "Take a screenshot of a web page (a URL in the request, or the page the browser is already on) through the browser bridge and report the saved file."
}
+90
View File
@@ -0,0 +1,90 @@
"""Take a screenshot of a web page through the browser bridge.
Real integration: the local browser bridge (`browser_bridge_url`,
`browser_bridge_token`); the body never drives a browser directly. If the
request names a URL it opens that page first, otherwise it captures the page the
browser is already on, and reports the real path of the saved PNG. A bridge
failure is reported honestly — never a fabricated path.
"""
from __future__ import annotations
import json
import re
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "browser",
"transport": "http",
"config_vars": ["browser_bridge_url", "browser_bridge_token"],
}
CONTRACT = {
"browser_bridge_url": "Base URL of the local browser bridge, e.g. http://127.0.0.1:5232 (no trailing slash needed).",
"browser_bridge_token": "Shared secret for the browser bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
}
TIMEOUT_SECONDS = 60
_URL_RE = re.compile(r"https?://[^\s<>\"')]+", re.IGNORECASE)
class BrowserBridgeError(Exception):
"""A real failure talking to the local browser bridge."""
def _request(ctx, path, payload=None, params=None):
base = str(ctx.config.get("browser_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise BrowserBridgeError("browser_bridge_url is not configured")
token = str(ctx.config.get("browser_bridge_token", "") or "").strip()
url = base + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
data = None
method = "GET"
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
method = "POST"
http_request = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BrowserBridgeError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BrowserBridgeError(f"{method} {path}: {exc}") from exc
def _resolve_url(request):
source = request.user_input if request.user_input is not None else request.text
match = _URL_RE.search(source or "")
return match.group(0) if match else None
def act(ctx, request):
url = _resolve_url(request)
try:
if url:
_request(ctx, "/goto", {"url": url})
shot = _request(ctx, "/screenshot", params={"full_page": "true"})
except BrowserBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
path = shot.get("path") or ""
title = shot.get("title") or ""
page_url = shot.get("url") or url or "the current page"
size = shot.get("bytes")
where = f"{title} ({page_url})" if title else str(page_url)
detail = f"Saved a screenshot of {where} to {path}"
if isinstance(size, int):
detail += f" ({size} bytes)"
return ActionResult(action_log=detail, new_state=detail)
+125
View File
@@ -0,0 +1,125 @@
"""Hermetic mechanics test for browser.screenshot.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local browser bridge's `/goto` and `/screenshot` routes.
This proves the body captures the page through the bridge and reports the saved
path (and fails honestly when the bridge is unavailable). It does NOT prove the
live integration — only a real run against a real browser does.
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
def call(self, decision): # pragma: no cover - this skill makes no decision
raise AssertionError("browser.screenshot must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
path_saved = "/home/user/.runtime/browser/screenshots/shot.png"
status = 200
requests = []
def _read(self):
length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b""
def _send(self, payload, status):
raw = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def do_POST(self):
self.requests.append(("POST", self.path, self._read().decode("utf-8")))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path == "/goto":
self._send({"url": "https://example.com/", "title": "Example", "status": 200}, 200)
return
self._send({"error": "not found"}, 404)
def do_GET(self):
self.requests.append(("GET", self.path, ""))
if self.status != 200:
self._send({"error": "boom"}, self.status)
return
if self.path.startswith("/screenshot"):
self._send(
{
"ok": True,
"path": self.path_saved,
"bytes": 12345,
"url": "https://example.com/",
"title": "Example",
},
200,
)
return
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(status=200):
handler = type("Handler", (BridgeHandler,), {"status": status, "requests": []})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def run(url, text="take a screenshot of https://example.com/"):
ctx = ActionContext(engine=FakeEngine(), config={"browser_bridge_url": url, "browser_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reports_the_saved_screenshot():
server, handler, url = start_server()
try:
action = run(url)
assert BridgeHandler.path_saved in action.action_log, action.action_log
assert "12345 bytes" in action.action_log, action.action_log
assert action.new_state == action.action_log
assert any(method == "GET" and path.startswith("/screenshot") for method, path, _ in handler.requests)
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_bridge_error_is_reported_honestly():
server, _handler, url = start_server(status=502)
try:
action = run(url)
assert "502" in action.action_log, action.action_log
assert action.new_state == "take a screenshot of https://example.com/"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_reports_the_saved_screenshot()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)