commit 0836498b02915d00f2e9844e36b6d8b4adbf8f3b Author: Gabby Morgan Date: Tue Oct 13 14:20:35 2026 +0000 Abstract seeds into modular skill packs + split config Group committed starter skills into packs (semif_agent/packs.py) that bind a concern to its categories, bridge(s), requirements, and config schema: - seeds/ -> packs// with a pack.json manifest + skills///. Shipped: nextcloud, simplex, outlook, browser (each owning its bridge) and essentials (time + calculator, no bridge). - PackRegistry discovers packs (a root with no manifest is one implicit pack); merge_packs loads every enabled pack. Pack enable is one switch (packs..enabled -> bridges..enabled -> enabled_by_default); disabling a pack drops its categories (incl. generated bodies) and its bridge. - CATEGORY_DESCRIPTIONS now comes from the pack manifests (built-ins stay). Adopt a Home-Assistant-style layered config (semif_agent/config.py): - config.json is a thin index ({"include": [...]}) over config/core.json, config/gateway.json, config/bridges.json, config/packs/*.json, deep-merged. - Secrets live in the gitignored secrets.json, referenced as "!secret "; api_key_env is removed. - CORE_SCHEMA + each pack's config schema own defaults and GENERATE the committed config.example.json; new `check-config` (validate + --write-example) and `config-init` (seed the split layout) commands. - scripts/config_merge.py (stdlib) lets bootstrap read the merged config. Tests: tests/test_packs.py (renamed from test_seed_skills, +enable/merge), new tests/test_config.py. All unit tests pass (772). diff --git a/pack.json b/pack.json new file mode 100644 index 0000000..f37f8ee --- /dev/null +++ b/pack.json @@ -0,0 +1,26 @@ +{ + "name": "browser", + "title": "Browser", + "concern": "Real browser automation (Playwright): open a web page, read its text or links, take a screenshot, and click, type, or fill forms to carry out a task on a website.", + "categories": { + "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." + }, + "bridges": ["browser"], + "requires": ["playwright"], + "enabled_by_default": false, + "config": { + "enabled": {"type": "bool", "default": false, "doc": "Load this pack's skills and run its bridge. Disabled by default: it needs the optional Playwright deps + browser binaries (scripts/bootstrap.sh --browser)."}, + "host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."}, + "port": {"type": "int", "default": 5232, "doc": "Bridge listen port."}, + "token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."}, + "engine": {"type": "str", "default": "chromium", "doc": "chromium | firefox | webkit."}, + "headless": {"type": "bool", "default": true, "doc": "false shows the browser window (to sign in once)."}, + "channel": {"type": "str", "default": "", "doc": "Use an already-installed browser channel (chrome/msedge) and skip Playwright's download."}, + "executable_path": {"type": "str", "default": "", "doc": "Use a specific browser binary; wins over channel."}, + "profile_dir": {"type": "str", "default": "", "doc": "Persistent profile directory (logins survive across calls)."}, + "browsers_path": {"type": "str", "default": "", "doc": "PLAYWRIGHT_BROWSERS_PATH override."}, + "screenshot_dir": {"type": "str", "default": "", "doc": "Where screenshots are saved."}, + "default_timeout": {"type": "float", "default": 30.0, "doc": "Default navigation/action timeout (seconds)."}, + "max_text_chars": {"type": "int", "default": 20000, "doc": "Bound on returned page text."} + } +} diff --git a/skills/browser/open_page/contract.json b/skills/browser/open_page/contract.json new file mode 100644 index 0000000..ce2237b --- /dev/null +++ b/skills/browser/open_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/skills/browser/open_page/manifest.json b/skills/browser/open_page/manifest.json new file mode 100644 index 0000000..b9c9609 --- /dev/null +++ b/skills/browser/open_page/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Open a web page in the browser bridge and report its title and readable text." +} diff --git a/skills/browser/open_page/skill.py b/skills/browser/open_page/skill.py new file mode 100644 index 0000000..6553abf --- /dev/null +++ b/skills/browser/open_page/skill.py @@ -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) diff --git a/skills/browser/open_page/skill.test.py b/skills/browser/open_page/skill.test.py new file mode 100644 index 0000000..702a9e4 --- /dev/null +++ b/skills/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/skills/browser/read_page/contract.json b/skills/browser/read_page/contract.json new file mode 100644 index 0000000..ce2237b --- /dev/null +++ b/skills/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/skills/browser/read_page/manifest.json b/skills/browser/read_page/manifest.json new file mode 100644 index 0000000..a274360 --- /dev/null +++ b/skills/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/skills/browser/read_page/skill.py b/skills/browser/read_page/skill.py new file mode 100644 index 0000000..273f198 --- /dev/null +++ b/skills/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/skills/browser/read_page/skill.test.py b/skills/browser/read_page/skill.test.py new file mode 100644 index 0000000..39e519e --- /dev/null +++ b/skills/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/skills/browser/screenshot/contract.json b/skills/browser/screenshot/contract.json new file mode 100644 index 0000000..ce2237b --- /dev/null +++ b/skills/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/skills/browser/screenshot/manifest.json b/skills/browser/screenshot/manifest.json new file mode 100644 index 0000000..7bc2711 --- /dev/null +++ b/skills/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/skills/browser/screenshot/skill.py b/skills/browser/screenshot/skill.py new file mode 100644 index 0000000..1eb7d6f --- /dev/null +++ b/skills/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/skills/browser/screenshot/skill.test.py b/skills/browser/screenshot/skill.test.py new file mode 100644 index 0000000..46c34fb --- /dev/null +++ b/skills/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)