diff --git a/AGENTS.md b/AGENTS.md index 0ddfad3..71353a1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -242,7 +242,9 @@ decisions.py contract dataclasses (Option, DecisionRequest, DecisionResult, Request) dashboard.py stdlib http.server + JSON API (tree/trace/dream/status/ 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: GatewayAdapter contract + Inbound/OutboundMessage. service.py: 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 `.runtime/outlook/token.json` and seeded once with `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 into the codegen prompts), run_bridges() (threads the scheduler's `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 0.12); with descriptions it picks `create_category` 0.87. `Skill` carries `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 empty bucket is never offered bare. The old category threshold gate (`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. `tests/test_outlook_bridge.py` drives the real client over a loopback `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) @@ -1571,6 +1612,16 @@ covered. Deferred follow-ups: `create_task`, `list_contacts`, `list_files`). Deferred: writing/reusing Outlook app-registration guidance in the docs, and a mail-send seed that 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 - **Contain installation artifacts in the repo.** Everything a machine installs diff --git a/README.md b/README.md index 9531497..a754ccc 100644 --- a/README.md +++ b/README.md @@ -399,8 +399,9 @@ semif_agent/ voice_transport.py neutral voice transport: mic capture, wake word, VAD, speech-to-text (faster-whisper), text-to-speech (Piper) gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice) - bridges/ standalone third-party API bridges (SimpleX, LLM, Nextcloud) -seeds/ committed starter skills (nextcloud, simplex) + bridges/ standalone third-party API bridges (SimpleX, LLM, Nextcloud, + Outlook, browser) +seeds/ committed starter skills (nextcloud, simplex, outlook, browser) scripts/ bootstrap.sh, simplex-address.py, systemd/*.in requirements/ staging.txt — the pinned engine deps 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.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.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`) | | `dashboard` | bind host/port | 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.` 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 @@ -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 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= # whole page's rendered text +GET /text?selector= # text of matching elements +GET /links?query=&limit= # anchors (label + href) +GET /screenshot?full_page=&selector=&inline= +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 ```sh diff --git a/config.example.json b/config.example.json index 80df4a5..f8585d2 100644 --- a/config.example.json +++ b/config.example.json @@ -194,6 +194,20 @@ "default_timezone": "UTC", "verify_tls": true, "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": { diff --git a/requirements/browser.txt b/requirements/browser.txt new file mode 100644 index 0000000..8231b62 --- /dev/null +++ b/requirements/browser.txt @@ -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 diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh index fc952b2..2af1736 100755 --- a/scripts/bootstrap.sh +++ b/scripts/bootstrap.sh @@ -32,7 +32,8 @@ # # Usage: # 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. set -euo pipefail @@ -43,6 +44,7 @@ LLM_MODEL="" CODEGEN_MODEL="" COPY_DATA="" VOICE=0 +BROWSER=0 GPU_MODE="auto" usage() { @@ -54,6 +56,7 @@ usage() { 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 " --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 " -h this help" exit "${1:-0}" @@ -67,6 +70,7 @@ while [[ $# -gt 0 ]]; do --codegen-model) CODEGEN_MODEL="$2"; shift 2 ;; --copy-data) COPY_DATA="$2"; shift 2 ;; --voice) VOICE=1; shift ;; + --browser) BROWSER=1; shift ;; --gpu) GPU_MODE="$2"; shift 2 ;; -h|--help) usage 0 ;; *) echo "unknown option: $1" >&2; usage 1 ;; @@ -87,6 +91,7 @@ TOOLDIR="$RUNTIME/bin" SIMPLEX_DB="$RUNTIME/simplex" UNITS="$RUNTIME/systemd" USER_UNITS="$HOME/.config/systemd/user" +BROWSERS="$RUNTIME/browser" PYTHON="$VENV/bin/python" PIP="$VENV/bin/pip" @@ -360,6 +365,29 @@ if [[ "$VOICE" = 1 ]]; then "$PIP" install --no-deps openwakeword==0.6.0 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 -------------------------------------------------------------- GGUF_NAME="$(basename "$GGUF_URL")" 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 nextcloud_* values the nextcloud seeds collect. Skills call it at the address 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 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 EOF fi + +if [[ "$BROWSER" = 1 ]]; then + cat <\"')]+", 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) diff --git a/seeds/browser/open_page/skill.test.py b/seeds/browser/open_page/skill.test.py new file mode 100644 index 0000000..702a9e4 --- /dev/null +++ b/seeds/browser/open_page/skill.test.py @@ -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) diff --git a/seeds/browser/read_page/contract.json b/seeds/browser/read_page/contract.json new file mode 100644 index 0000000..ce2237b --- /dev/null +++ b/seeds/browser/read_page/contract.json @@ -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." +} diff --git a/seeds/browser/read_page/manifest.json b/seeds/browser/read_page/manifest.json new file mode 100644 index 0000000..a274360 --- /dev/null +++ b/seeds/browser/read_page/manifest.json @@ -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." +} diff --git a/seeds/browser/read_page/skill.py b/seeds/browser/read_page/skill.py new file mode 100644 index 0000000..273f198 --- /dev/null +++ b/seeds/browser/read_page/skill.py @@ -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) diff --git a/seeds/browser/read_page/skill.test.py b/seeds/browser/read_page/skill.test.py new file mode 100644 index 0000000..39e519e --- /dev/null +++ b/seeds/browser/read_page/skill.test.py @@ -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) diff --git a/seeds/browser/screenshot/contract.json b/seeds/browser/screenshot/contract.json new file mode 100644 index 0000000..ce2237b --- /dev/null +++ b/seeds/browser/screenshot/contract.json @@ -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." +} diff --git a/seeds/browser/screenshot/manifest.json b/seeds/browser/screenshot/manifest.json new file mode 100644 index 0000000..7bc2711 --- /dev/null +++ b/seeds/browser/screenshot/manifest.json @@ -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." +} diff --git a/seeds/browser/screenshot/skill.py b/seeds/browser/screenshot/skill.py new file mode 100644 index 0000000..1eb7d6f --- /dev/null +++ b/seeds/browser/screenshot/skill.py @@ -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) diff --git a/seeds/browser/screenshot/skill.test.py b/seeds/browser/screenshot/skill.test.py new file mode 100644 index 0000000..46c34fb --- /dev/null +++ b/seeds/browser/screenshot/skill.test.py @@ -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) diff --git a/semif_agent/bridges/__init__.py b/semif_agent/bridges/__init__.py index 68c9a07..8b5d74c 100644 --- a/semif_agent/bridges/__init__.py +++ b/semif_agent/bridges/__init__.py @@ -1,7 +1,8 @@ """Third-party API bridges: a secure local layer between skills and services. A **bridge service** is a standalone process that exposes one third-party system -(SimpleX, the local language model, Nextcloud, Microsoft Graph / Outlook) to +(SimpleX, the local language model, Nextcloud, Microsoft Graph / Outlook, a real +web browser via Playwright) to codegen-authored skill bodies over a local, token-guarded HTTP API. It exists so a generated body never speaks a system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat diff --git a/semif_agent/bridges/browser.py b/semif_agent/bridges/browser.py new file mode 100644 index 0000000..9122f82 --- /dev/null +++ b/semif_agent/bridges/browser.py @@ -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= -> 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= -> 200 {\"url\", \"selector\", \"count\", " + "\"matches\": [{\"text\"}]} — text of every element matching a CSS " + "selector", + "GET /links?query=&limit= -> 200 {\"url\", \"links\": " + "[{\"text\", \"href\"}]} — anchors on the page, optionally filtered " + "by a substring of the label or href", + "GET /screenshot?full_page=&selector=&inline= -> 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