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

+53 -2
View File
@@ -242,7 +242,9 @@ decisions.py contract dataclasses (Option, DecisionRequest, DecisionResult,
Request) Request)
dashboard.py stdlib http.server + JSON API (tree/trace/dream/status/ dashboard.py stdlib http.server + JSON API (tree/trace/dream/status/
questions/repairs + POST submit/answer/questions/repair/restart/ questions/repairs + POST submit/answer/questions/repair/restart/
relabel); static/ frontend served at / relabel); static/ frontend served at /; submit/answer drain the
queue after replying (like the CLI and gateway) so a multi-step
`continue` chain completes instead of stranding its child
gateway/ messenger COMMAND intake/reply — and nothing else. base.py: gateway/ messenger COMMAND intake/reply — and nothing else. base.py:
GatewayAdapter contract + Inbound/OutboundMessage. service.py: GatewayAdapter contract + Inbound/OutboundMessage. service.py:
GatewayService maps chats onto the single-slot scheduler GatewayService maps chats onto the single-slot scheduler
@@ -297,6 +299,12 @@ bridges/ standalone third-party API bridges (SimpleX, the LLM bridge,
daemon (stdlib-only `urllib`); tokens stored under daemon (stdlib-only `urllib`); tokens stored under
`.runtime/outlook/token.json` and seeded once with `.runtime/outlook/token.json` and seeded once with
`scripts/outlook-auth.py`; connection from `bridges.outlook`. `scripts/outlook-auth.py`; connection from `bridges.outlook`.
browser.py + browser_client.py: BrowserBridge — real browser
automation via Playwright (open/read/click/fill/screenshot),
owning a persistent browser profile; optional heavy dep
(requirements/browser.txt, `bootstrap.sh --browser`), lazy so a
missing browser is a per-call 503 and never blocks the other
bridges. Runs the async API on one dedicated event-loop thread.
registry.py: CATALOG, describe_bridges() (catalog injected registry.py: CATALOG, describe_bridges() (catalog injected
into the codegen prompts), run_bridges() (threads the scheduler's into the codegen prompts), run_bridges() (threads the scheduler's
`llm` client into the LLM bridge). Run with `python -m `llm` client into the LLM bridge). Run with `python -m
@@ -409,7 +417,8 @@ CLI, unit tests (24) + integration tests (2).
model sent "book a flight to japan" to `simplex` (0.49 vs create_category model sent "book a flight to japan" to `simplex` (0.49 vs create_category
0.12); with descriptions it picks `create_category` 0.87. `Skill` carries 0.12); with descriptions it picks `create_category` 0.87. `Skill` carries
`category_description`, seeded by `CATEGORY_DESCRIPTIONS` for the built-ins `category_description`, seeded by `CATEGORY_DESCRIPTIONS` for the built-ins
(response/nextcloud/simplex) and read from the registry for authored (response/nextcloud/simplex/time/calculator/browser) and read from the registry
for authored
categories; `category_descriptions(tree)` collapses it per category so an categories; `category_descriptions(tree)` collapses it per category so an
empty bucket is never offered bare. The old category threshold gate empty bucket is never offered bare. The old category threshold gate
(`create_tau`/`create_margin`) is **retired**. Leaf level: the softmax (`create_tau`/`create_margin`) is **retired**. Leaf level: the softmax
@@ -1512,6 +1521,38 @@ CLI, unit tests (24) + integration tests (2).
`429`/`Retry-After` backoff are handled in the client. `429`/`Retry-After` backoff are handled in the client.
`tests/test_outlook_bridge.py` drives the real client over a loopback `tests/test_outlook_bridge.py` drives the real client over a loopback
`http.server` faking the token endpoint and Graph shapes. `http.server` faking the token endpoint and Graph shapes.
- **Browser bridge** (`bridges/browser.py` + `bridges/browser_client.py`).
Real browser automation via **Playwright** — open a URL, read a page's text or
links, take a screenshot, and click/fill/press/select to complete a flow —
behind one uniform JSON surface, so a body never bundles a browser stack. It is
the first bridge with a heavy optional dependency, so it is **disabled by
default** and installed with `scripts/bootstrap.sh --browser`
(`requirements/browser.txt` pins Playwright; the Chromium binary is downloaded
into the checkout's `.runtime/browser`, and the bridge sets
`PLAYWRIGHT_BROWSERS_PATH` there at launch). Unlike Nextcloud/Outlook it owns a
browser and keeps a **persistent profile** (`.runtime/browser/profile`), so a
login done once survives across calls and restarts — the browser analog of the
SimpleX bridge owning its own daemon (`POST /reset` with `purge=true` wipes it,
and `headless:false` shows the window so the operator can sign in).
`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/browser must be a per-call `503` (with an
install hint), never take down simplex/llm/nextcloud. Playwright's sync API is
bound to its creating thread and 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`, submitting coroutines
with `run_coroutine_threadsafe`. A real navigation/timeout/selector failure is a
`502` (`BrowserError`), a missing package/browser a `503`
(`BrowserUnavailable`), bad input a `400` — never a fabricated success. Routes
(reads `GET`, mutations `POST`): `/health`, `/state`, `/content`
(text|html, bounded), `/text`, `/links`, `/screenshot`
(`full_page`/`selector`/`inline`, saved under `.runtime/browser/screenshots`),
`/goto`, `/click` (selector or visible text), `/fill`, `/press`, `/select`,
`/wait`, `/back`, `/forward`, `/reset`. Bodies reach it via the derived
`browser_bridge_url` (+ optional `browser_bridge_token`). Three
`seeds/browser/*` skills ship (`open_page`, `read_page`, `screenshot`).
`tests/test_browser_bridge.py` exercises the routes over a loopback HTTP server
with an injected fake driver (no browser, no Playwright needed).
## Bridge backlog (one session per item) ## Bridge backlog (one session per item)
@@ -1571,6 +1612,16 @@ covered. Deferred follow-ups:
`create_task`, `list_contacts`, `list_files`). Deferred: writing/reusing `create_task`, `list_contacts`, `list_files`). Deferred: writing/reusing
Outlook app-registration guidance in the docs, and a mail-send seed that Outlook app-registration guidance in the docs, and a mail-send seed that
attaches files. attaches files.
- [x] **7. Browser bridge (Playwright)** (`bridges/browser.py` +
`bridges/browser_client.py`). Shipped: `BrowserBridge` exposes open/read
(text/links/screenshot) and act (goto/click/fill/press/select/wait/back/
forward/reset) over one JSON surface in front of a real Playwright browser
with a persistent profile; optional heavy dep installed via
`requirements/browser.txt` + `bootstrap.sh --browser`, lazy so a missing
browser is a per-call 503 and never aborts the other bridges; the async API
runs on one dedicated event-loop thread. Three `seeds/browser/*` skills
(`open_page`, `read_page`, `screenshot`). Deferred: arbitrary JS `evaluate`,
file upload/download, multiple tabs/contexts, and a per-URL allowlist.
### Code principles ### Code principles
- **Contain installation artifacts in the repo.** Everything a machine installs - **Contain installation artifacts in the repo.** Everything a machine installs
+43 -3
View File
@@ -399,8 +399,9 @@ semif_agent/
voice_transport.py neutral voice transport: mic capture, wake word, VAD, voice_transport.py neutral voice transport: mic capture, wake word, VAD,
speech-to-text (faster-whisper), text-to-speech (Piper) speech-to-text (faster-whisper), text-to-speech (Piper)
gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice) gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice)
bridges/ standalone third-party API bridges (SimpleX, LLM, Nextcloud) bridges/ standalone third-party API bridges (SimpleX, LLM, Nextcloud,
seeds/ committed starter skills (nextcloud, simplex) Outlook, browser)
seeds/ committed starter skills (nextcloud, simplex, outlook, browser)
scripts/ bootstrap.sh, simplex-address.py, systemd/*.in scripts/ bootstrap.sh, simplex-address.py, systemd/*.in
requirements/ staging.txt — the pinned engine deps requirements/ staging.txt — the pinned engine deps
tests/ stdlib unit tests + tests/integration (real engine + LLM) tests/ stdlib unit tests + tests/integration (real engine + LLM)
@@ -531,11 +532,13 @@ Key blocks:
| `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) | | `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) |
| `bridges.nextcloud` | Nextcloud bridge: host/port/token + connection (url/username/app_password/defaults) | | `bridges.nextcloud` | Nextcloud bridge: host/port/token + connection (url/username/app_password/defaults) |
| `bridges.outlook` | Outlook bridge: host/port/token + Microsoft Graph connection (client_id/tenant/defaults) | | `bridges.outlook` | Outlook bridge: host/port/token + Microsoft Graph connection (client_id/tenant/defaults) |
| `bridges.browser` | Browser bridge: host/port/token + Playwright settings (engine/headless/profile dirs) |
| `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) | | `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) |
| `dashboard` | bind host/port | | `dashboard` | bind host/port |
Bridge skills read `simplex_bridge_url` / `llm_bridge_url` / Bridge skills read `simplex_bridge_url` / `llm_bridge_url` /
`nextcloud_bridge_url` / `outlook_bridge_url` (+ their `_token`) from `nextcloud_bridge_url` / `outlook_bridge_url` / `browser_bridge_url` (+ their
`_token`) from
`ctx.config`; each is **derived** at startup from its `bridges.<name>` `ctx.config`; each is **derived** at startup from its `bridges.<name>`
host/port/token, so there is no duplicate top-level key to keep in sync. A bridge host/port/token, so there is no duplicate top-level key to keep in sync. A bridge
with no block (or no port) leaves the variable unresolved and the operator is with no block (or no port) leaves the variable unresolved and the operator is
@@ -845,6 +848,43 @@ Seven `seeds/outlook/*` skills ship (`next_message`, `send_message`,
`send_message` composes the message through the LLM bridge and asks for `send_message` composes the message through the LLM bridge and asks for
confirmation before it sends. confirmation before it sends.
The **browser bridge** (`semif_agent/bridges/browser.py`) is real browser
automation via **Playwright**: open a URL, read a page's text or links, take a
screenshot, and click/fill/press/select to complete a flow. It is the first
bridge with a heavy optional dependency, so it is **disabled by default** and
installed with `scripts/bootstrap.sh --browser` (Playwright + Chromium land under
`.runtime/browser`; the bridge sets `PLAYWRIGHT_BROWSERS_PATH` there at launch).
Unlike the others it owns a browser and keeps a **persistent profile**
(`.runtime/browser/profile`) so a login you do once survives across calls and
restarts — the browser analog of the SimpleX bridge owning its own daemon
(`POST /reset` with `purge=true` wipes it). A dedicated event-loop thread runs
Playwright's async API and serializes whole operations, because the sync API is
bound to its creating thread and the bridge serves each request on a new one.
`check_requirements()` never blocks startup, so a host without Playwright still
runs every other bridge; a missing package/browser is a `503` install hint on the
call, and a real navigation/timeout/selector failure is a `502`. Skills call it
at the address derived from `bridges.browser` (`browser_bridge_url`, + optional
`browser_bridge_token`). Its HTTP surface:
```
GET /health
GET /state # current url + title
GET /content?format=text|html&max_chars=<n> # whole page's rendered text
GET /text?selector=<css> # text of matching elements
GET /links?query=<text>&limit=<n> # anchors (label + href)
GET /screenshot?full_page=<bool>&selector=<css>&inline=<bool>
POST /goto {"url","wait_until"?,"timeout"?}
POST /click {"selector"?|"text"?,"index"?,"timeout"?}
POST /fill {"selector","value","submit"?,"timeout"?}
POST /press {"key","selector"?,"timeout"?}
POST /select {"selector","value"?|"label"?,"timeout"?}
POST /wait {"selector"?|"text"?,"timeout"?}
POST /back | /forward {"timeout"?}
POST /reset {"purge"?} # close; purge deletes the profile
```
Three `seeds/browser/*` skills ship (`open_page`, `read_page`, `screenshot`).
### Dream report ### Dream report
```sh ```sh
+14
View File
@@ -194,6 +194,20 @@
"default_timezone": "UTC", "default_timezone": "UTC",
"verify_tls": true, "verify_tls": true,
"timeout": 30 "timeout": 30
},
"browser": {
"_comment": "Browser bridge: real browser automation via Playwright — open a URL, read a page's text/links, take a screenshot, and click/fill/press/select to complete a flow — behind one uniform local JSON API, so skill bodies never bundle a browser stack. Disabled by default because it needs the optional Playwright deps + browser binaries: install with `scripts/bootstrap.sh --browser` (browsers land under .runtime/browser). The bridge keeps a PERSISTENT profile under .runtime/browser/profile, so logins/cookies survive across calls and restarts (POST /reset with purge=true wipes it); `engine` is chromium|firefox|webkit and `headless` false shows the window. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. A missing Playwright/browser is a 503 install hint, never a startup failure (the other bridges keep running).",
"enabled": false,
"host": "127.0.0.1",
"port": 5232,
"token": "",
"engine": "chromium",
"headless": true,
"profile_dir": "",
"browsers_path": "",
"screenshot_dir": "",
"default_timeout": 30,
"max_text_chars": 20000
} }
}, },
"gateway": { "gateway": {
+21
View File
@@ -0,0 +1,21 @@
# Browser bridge deps (optional).
#
# Only needed on a host that runs the browser bridge (browser automation skills).
# Lazy-imported by semif_agent/bridges/browser_client.py, so the core stays
# stdlib-only and every other bridge keeps running without it. Install with
# scripts/bootstrap.sh --browser, or:
# .runtime/venv/bin/pip install -r requirements/browser.txt
# PLAYWRIGHT_BROWSERS_PATH=.runtime/browser \
# .runtime/venv/bin/python -m playwright install chromium
#
# The browser binaries are NOT shipped in the wheel: `playwright install`
# downloads Chromium into PLAYWRIGHT_BROWSERS_PATH. bootstrap.sh points that at
# the checkout's .runtime/browser (the containment rule); the bridge sets the
# same env var at launch, so the binaries live with the rest of the stack. Add
# `--with-deps` to the install command on a bare host to fetch the system
# libraries Chromium needs (needs sudo).
#
# Only `chromium` is installed by default; switch bridges.browser.engine to
# firefox/webkit and run `python -m playwright install firefox`/`webkit` for
# those.
playwright==1.63.0
+57 -1
View File
@@ -32,7 +32,8 @@
# #
# Usage: # Usage:
# scripts/bootstrap.sh [--llm-url URL] [--codegen-url URL] [--llm-model MODEL] # scripts/bootstrap.sh [--llm-url URL] [--codegen-url URL] [--llm-model MODEL]
# [--codegen-model MODEL] [--copy-data SRC] [--voice] [--gpu MODE] [-h] # [--codegen-model MODEL] [--copy-data SRC] [--voice]
# [--browser] [--gpu MODE] [-h]
# #
# Run as the human user; sudo is used internally for system bits. # Run as the human user; sudo is used internally for system bits.
set -euo pipefail set -euo pipefail
@@ -43,6 +44,7 @@ LLM_MODEL=""
CODEGEN_MODEL="" CODEGEN_MODEL=""
COPY_DATA="" COPY_DATA=""
VOICE=0 VOICE=0
BROWSER=0
GPU_MODE="auto" GPU_MODE="auto"
usage() { usage() {
@@ -54,6 +56,7 @@ usage() {
echo " --codegen-model MODEL override codegen.model from config.json for this run" echo " --codegen-model MODEL override codegen.model from config.json for this run"
echo " --copy-data SRC rsync SRC (e.g. user@host:/path/to/semif-agent/data) to data/ — opt-in" echo " --copy-data SRC rsync SRC (e.g. user@host:/path/to/semif-agent/data) to data/ — opt-in"
echo " --voice install the optional voice-gateway stack + download its models" echo " --voice install the optional voice-gateway stack + download its models"
echo " --browser install the optional browser-bridge stack (Playwright + Chromium)"
echo " --gpu MODE decision-engine llama.cpp backend: auto (default; a GPU build only when engine.gpu_layers is set), vulkan, rocm, cuda, cpu" echo " --gpu MODE decision-engine llama.cpp backend: auto (default; a GPU build only when engine.gpu_layers is set), vulkan, rocm, cuda, cpu"
echo " -h this help" echo " -h this help"
exit "${1:-0}" exit "${1:-0}"
@@ -67,6 +70,7 @@ while [[ $# -gt 0 ]]; do
--codegen-model) CODEGEN_MODEL="$2"; shift 2 ;; --codegen-model) CODEGEN_MODEL="$2"; shift 2 ;;
--copy-data) COPY_DATA="$2"; shift 2 ;; --copy-data) COPY_DATA="$2"; shift 2 ;;
--voice) VOICE=1; shift ;; --voice) VOICE=1; shift ;;
--browser) BROWSER=1; shift ;;
--gpu) GPU_MODE="$2"; shift 2 ;; --gpu) GPU_MODE="$2"; shift 2 ;;
-h|--help) usage 0 ;; -h|--help) usage 0 ;;
*) echo "unknown option: $1" >&2; usage 1 ;; *) echo "unknown option: $1" >&2; usage 1 ;;
@@ -87,6 +91,7 @@ TOOLDIR="$RUNTIME/bin"
SIMPLEX_DB="$RUNTIME/simplex" SIMPLEX_DB="$RUNTIME/simplex"
UNITS="$RUNTIME/systemd" UNITS="$RUNTIME/systemd"
USER_UNITS="$HOME/.config/systemd/user" USER_UNITS="$HOME/.config/systemd/user"
BROWSERS="$RUNTIME/browser"
PYTHON="$VENV/bin/python" PYTHON="$VENV/bin/python"
PIP="$VENV/bin/pip" PIP="$VENV/bin/pip"
@@ -360,6 +365,29 @@ if [[ "$VOICE" = 1 ]]; then
"$PIP" install --no-deps openwakeword==0.6.0 "$PIP" install --no-deps openwakeword==0.6.0
fi fi
# --- stage 3c: optional browser-bridge stack (--browser) -----------------------
# Playwright + its Chromium binaries. Optional: lazy-imported, so a host without
# it still runs every other bridge. Browsers go under the checkout's
# .runtime/browser (the containment rule); the bridge sets PLAYWRIGHT_BROWSERS_PATH
# to the same path at launch.
if [[ "$BROWSER" = 1 ]]; then
echo "== installing browser-bridge deps into $VENV"
"$PIP" install -r "$REPO_ROOT/requirements/browser.txt"
BROWSER_ENGINE="$("$PYTHON" - "$CONFIG" <<'PY' 2>/dev/null || true
import json, sys
try:
cfg = json.load(open(sys.argv[1]))
except Exception:
print("chromium"); raise SystemExit(0)
print(cfg.get("bridges", {}).get("browser", {}).get("engine", "chromium") or "chromium")
PY
)"
case "$BROWSER_ENGINE" in chromium|firefox|webkit) ;; *) BROWSER_ENGINE=chromium ;; esac
echo "== downloading Playwright browser '$BROWSER_ENGINE' into $BROWSERS"
PLAYWRIGHT_BROWSERS_PATH="$BROWSERS" "$PYTHON" -m playwright install "$BROWSER_ENGINE" \
|| echo "WARN: playwright browser download failed; re-run: PLAYWRIGHT_BROWSERS_PATH=$BROWSERS $PYTHON -m playwright install $BROWSER_ENGINE" >&2
fi
# --- stage 4: GGUF -------------------------------------------------------------- # --- stage 4: GGUF --------------------------------------------------------------
GGUF_NAME="$(basename "$GGUF_URL")" GGUF_NAME="$(basename "$GGUF_URL")"
GGUF="$MODELS/$GGUF_NAME" GGUF="$MODELS/$GGUF_NAME"
@@ -639,6 +667,13 @@ Nextcloud bridge (files/calendar/tasks/contacts/notes for skills):
bridges.nextcloud (url/username/app_password) — or reuse the top-level bridges.nextcloud (url/username/app_password) — or reuse the top-level
nextcloud_* values the nextcloud seeds collect. Skills call it at the address nextcloud_* values the nextcloud seeds collect. Skills call it at the address
derived from bridges.nextcloud (default http://127.0.0.1:5230). derived from bridges.nextcloud (default http://127.0.0.1:5230).
Browser bridge (browser automation for skills):
- Disabled by default; it needs the optional Playwright stack. Enable it with
bridges.browser.enabled = true (install the deps with scripts/bootstrap.sh
--browser). It runs inside the same 'semif-bridge' process and keeps a
persistent browser profile under .runtime/browser/profile. Skills call it at
the address derived from bridges.browser (default http://127.0.0.1:5232).
EOF EOF
if [[ "$VOICE" = 1 ]]; then if [[ "$VOICE" = 1 ]]; then
@@ -663,3 +698,24 @@ Voice command gateway (wake word + speech-to-text + text-to-speech):
HF_HOME="$HF_CACHE" "$PYTHON" scripts/voice-models.py --config config.json HF_HOME="$HF_CACHE" "$PYTHON" scripts/voice-models.py --config config.json
EOF EOF
fi fi
if [[ "$BROWSER" = 1 ]]; then
cat <<EOF
Browser bridge (browser automation for skills):
- The Playwright stack is installed and the '$BROWSER_ENGINE' browser is under
$BROWSERS. Enable it in config.json with bridges.browser.enabled = true, then
restart the bridge service:
systemctl --user restart semif-bridge.service
- It runs inside 'semif-bridge' (no separate daemon) and keeps a persistent
profile at .runtime/browser/profile, so a login you do once survives across
calls and restarts. Set bridges.browser.headless = false to watch the window
(useful the first time you sign in to a site); POST /reset with purge=true
wipes the stored profile.
- Skills call it at the address derived from bridges.browser (host/port,
default http://127.0.0.1:5232); the shipped seeds are browser.open_page,
browser.read_page, and browser.screenshot.
- If the bridge reports 503, the browser failed to launch — run:
PLAYWRIGHT_BROWSERS_PATH=$BROWSERS "$PYTHON" -m playwright install $BROWSER_ENGINE
EOF
fi
+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": "Open a web page in the browser bridge and report its title and readable text."
}
+121
View File
@@ -0,0 +1,121 @@
"""Open a web page in the browser bridge and report what is on it.
Real integration: the local browser bridge (`browser_bridge_url`,
`browser_bridge_token`); the body never drives a browser directly. It opens the
URL from the request, then reads the page's text through the bridge. The URL is
taken from the request, or asked for if the request does not contain one. A
missing URL or a bridge failure is reported honestly — never a fabricated page.
"""
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
EXCERPT_CHARS = 1200
_URL_RE = re.compile(r"https?://[^\s<>\"')]+", re.IGNORECASE)
class BrowserBridgeError(Exception):
"""A real failure talking to the local browser bridge."""
def _headers(ctx):
token = str(ctx.config.get("browser_bridge_token", "") or "").strip()
headers = {"Accept": "application/json"}
if token:
headers["X-Semif-Token"] = token
return headers
def _base(ctx):
base = str(ctx.config.get("browser_bridge_url", "") or "").strip().rstrip("/")
if not base:
raise BrowserBridgeError("browser_bridge_url is not configured")
return base
def _request(ctx, path, payload=None, params=None):
url = _base(ctx) + path
if params:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
headers = _headers(ctx)
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):
"""The URL to open, or None. Uses the answer after a needs_input pause."""
if request.user_input is not None:
answer = (request.user_input or "").strip()
if not answer:
return None
match = _URL_RE.search(answer)
return match.group(0) if match else answer
match = _URL_RE.search(request.text or "")
return match.group(0) if match else None
def act(ctx, request):
url = _resolve_url(request)
if not url:
return ActionResult(
action_log="no web address in the request",
new_state=request.text,
needs_input="Which web address (URL) should I open?",
)
if not url.lower().startswith(("http://", "https://")):
url = "https://" + url
try:
opened = _request(ctx, "/goto", {"url": url})
page = _request(ctx, "/content", params={"format": "text", "max_chars": EXCERPT_CHARS})
except BrowserBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
title = opened.get("title") or page.get("title") or url
final_url = page.get("url") or opened.get("url") or url
status = opened.get("status")
body = (page.get("content") or "").strip()
excerpt = body[:EXCERPT_CHARS]
if len(body) > EXCERPT_CHARS or page.get("truncated"):
excerpt = excerpt.rstrip() + " …"
summary = f"Opened {title} ({final_url})"
if status is not None:
summary += f" [HTTP {status}]"
if excerpt:
report = f"{summary}:\n{excerpt}"
else:
report = f"{summary}: the page has no readable text."
return ActionResult(action_log=report, new_state=report)
+147
View File
@@ -0,0 +1,147 @@
"""Hermetic mechanics test for browser.open_page.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local browser bridge's `/goto` and `/content` routes. This
proves the body asks the bridge to open a URL and reports the page (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.open_page must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
title = "Example Domain"
body = "This domain is for use in illustrative examples."
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": self.title, "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("/content"):
self._send(
{
"url": "https://example.com/",
"title": self.title,
"format": "text",
"content": self.body,
"truncated": False,
},
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="open 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_page():
server, handler, url = start_server()
try:
action = run(url)
assert "Example Domain" in action.action_log, action.action_log
assert "illustrative examples" in action.action_log, action.action_log
assert action.new_state == action.action_log
assert any(method == "POST" and path == "/goto" for method, path, _ in handler.requests)
assert any(method == "GET" and path.startswith("/content") for method, path, _ in handler.requests)
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_missing_url_asks_for_one():
ctx = ActionContext(engine=FakeEngine(), config={"browser_bridge_url": "http://127.0.0.1:1"})
action = skill.act(ctx, Request("open a web page"))
assert action.needs_input, "a request with no URL must ask for one"
print(action.needs_input)
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 == "open https://example.com", "a failed open must not fake a page"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
action = run("http://127.0.0.1:1")
assert "browser.open_page" not in action.action_log, action.action_log
assert action.new_state == "open https://example.com"
print(action.action_log)
def main():
test_reports_the_page()
test_missing_url_asks_for_one()
test_bridge_error_is_reported_honestly()
test_unreachable_bridge_fails_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
+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": "Read the readable text of a web page (a URL in the request, or the page the browser is already on) through the browser bridge."
}
+93
View File
@@ -0,0 +1,93 @@
"""Read the readable text 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 reads the page the
browser is already on. A bridge failure is reported honestly — never invented
page text.
"""
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
TEXT_CHARS = 4000
_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})
page = _request(ctx, "/content", params={"format": "text", "max_chars": TEXT_CHARS})
except BrowserBridgeError as exc:
return ActionResult(action_log=str(exc), new_state=request.text)
title = page.get("title") or ""
final_url = page.get("url") or url or "the current page"
text = (page.get("content") or "").strip()
if not text:
report = f"{title or final_url} ({final_url}) has no readable text."
return ActionResult(action_log=report, new_state=report)
if len(text) > TEXT_CHARS or page.get("truncated"):
text = text[:TEXT_CHARS].rstrip() + " …"
heading = f"{title} ({final_url})" if title else str(final_url)
report = f"{heading}:\n{text}"
return ActionResult(action_log=report, new_state=report)
+138
View File
@@ -0,0 +1,138 @@
"""Hermetic mechanics test for browser.read_page.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the local browser bridge's `/goto` and `/content` routes. This
proves the body reads the page through the bridge (navigating first only when the
request names a URL) 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.read_page must not ask the decision engine")
class BridgeHandler(BaseHTTPRequestHandler):
body = "First line.\nSecond line."
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("/content"):
self._send(
{
"url": "https://example.com/",
"title": "Example",
"format": "text",
"content": self.body,
"truncated": False,
},
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="read the current page"):
ctx = ActionContext(engine=FakeEngine(), config={"browser_bridge_url": url, "browser_bridge_token": ""})
return skill.act(ctx, Request(text))
def test_reads_the_current_page_without_navigating():
server, handler, url = start_server()
try:
action = run(url)
assert "First line." in action.action_log, action.action_log
assert "Second line." in action.action_log, action.action_log
assert action.new_state == action.action_log
assert not any(path == "/goto" for _method, path, _ in handler.requests), "no URL means no navigation"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_navigates_when_the_request_names_a_url():
server, handler, url = start_server()
try:
action = run(url, "read https://example.com/")
assert "Example" in action.action_log, action.action_log
assert any(method == "POST" and path == "/goto" 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 == "read the current page"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def main():
test_reads_the_current_page_without_navigating()
test_navigates_when_the_request_names_a_url()
test_bridge_error_is_reported_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
+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)
+2 -1
View File
@@ -1,7 +1,8 @@
"""Third-party API bridges: a secure local layer between skills and services. """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 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 codegen-authored skill bodies
over a local, token-guarded HTTP API. It exists so a generated body never speaks 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 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 import threading
from .base import BridgeInfo, BridgeService from .base import BridgeInfo, BridgeService
from .browser import BrowserBridge
from .llm import LLMBridge from .llm import LLMBridge
from .nextcloud import NextcloudBridge from .nextcloud import NextcloudBridge
from .outlook import OutlookBridge from .outlook import OutlookBridge
@@ -24,6 +25,7 @@ CATALOG: tuple[type[BridgeService], ...] = (
LLMBridge, LLMBridge,
NextcloudBridge, NextcloudBridge,
OutlookBridge, OutlookBridge,
BrowserBridge,
) )
+5
View File
@@ -747,6 +747,11 @@ CATEGORY_DESCRIPTIONS: dict[str, str] = {
"addition, subtraction, multiplication, division, powers and exponents, " "addition, subtraction, multiplication, division, powers and exponents, "
"squares, cubes, square roots, cube roots, fractions, and percentages." "squares, cubes, square roots, cube roots, fractions, and percentages."
), ),
"browser": (
"Browser automation: opening a web page, reading its text or links, "
"taking a screenshot, and clicking, typing, or filling forms to carry "
"out a task on a website."
),
"housekeeping": ( "housekeeping": (
"Agent self-maintenance: deleting, reconfiguring, regenerating, and " "Agent self-maintenance: deleting, reconfiguring, regenerating, and "
"cancelling the agent's own skills." "cancelling the agent's own skills."
+355
View File
@@ -0,0 +1,355 @@
"""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 json
import urllib.error
import urllib.request
import pytest
from semif_agent.bridges.browser import BrowserBridge
from semif_agent.bridges.browser_client import (
BrowserDriver,
BrowserError,
BrowserUnavailable,
)
from semif_agent.bridges.registry import (
build_bridge,
derived_config_vars,
describe_bridges,
known_infos,
)
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"
# ---- driver dependency handling ----
def test_driver_unavailable_without_playwright(monkeypatch):
import semif_agent.bridges.browser_client as browser_client
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)
+3
View File
@@ -41,6 +41,9 @@ def test_expected_seeds_exist():
assert "time.set_alarm" in ids assert "time.set_alarm" in ids
assert "nextcloud.create_task" in ids assert "nextcloud.create_task" in ids
assert "calculator.calculate" in ids assert "calculator.calculate" in ids
assert "browser.open_page" in ids
assert "browser.read_page" in ids
assert "browser.screenshot" in ids
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS]) @pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])