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.
190 lines
7.2 KiB
Python
190 lines
7.2 KiB
Python
"""The bridge catalog: discovery, prompt description, and standalone runner.
|
|
|
|
Every known bridge class is listed in `CATALOG`. `known_infos()` exposes their
|
|
static metadata, `describe_bridges()` renders the catalog block injected into
|
|
the code-generation prompts, and `run_bridges()` starts the enabled ones as a
|
|
standalone process (`python -m semif_agent.cli bridge`). Adding a bridge means
|
|
adding its class here and a `config.example.json` block; the gateway is never
|
|
touched.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
|
|
from .base import BridgeInfo, BridgeService
|
|
from .browser import BrowserBridge
|
|
from .llm import LLMBridge
|
|
from .nextcloud import NextcloudBridge
|
|
from .outlook import OutlookBridge
|
|
from .simplex import SimplexBridge
|
|
|
|
#: Known bridge services. Order is presentation order.
|
|
CATALOG: tuple[type[BridgeService], ...] = (
|
|
SimplexBridge,
|
|
LLMBridge,
|
|
NextcloudBridge,
|
|
OutlookBridge,
|
|
BrowserBridge,
|
|
)
|
|
|
|
|
|
def _class_for(name: str) -> type[BridgeService] | None:
|
|
for bridge_class in CATALOG:
|
|
if bridge_class.INFO.name == name:
|
|
return bridge_class
|
|
return None
|
|
|
|
|
|
def known_infos() -> list[BridgeInfo]:
|
|
return [bridge_class.INFO for bridge_class in CATALOG]
|
|
|
|
|
|
def derived_config_vars(config: dict) -> dict[str, str]:
|
|
"""Skill-facing config vars for every bridge, derived from its own block.
|
|
|
|
The `bridges.<name>` block is the single source of truth: its `host`/`port`
|
|
are the listener a skill body calls and its `token` is the shared secret.
|
|
There is deliberately no duplicate top-level `*_bridge_url`/`*_bridge_token`
|
|
to keep in sync — the values are derived here and injected into the config a
|
|
skill reads (`ctx.config`). A bridge with no block (or no port) contributes
|
|
nothing, so an unconfigured bridge still surfaces as an unresolved contract
|
|
variable the operator is asked for.
|
|
"""
|
|
blocks = config.get("bridges", {}) or {}
|
|
derived: dict[str, str] = {}
|
|
for info in known_infos():
|
|
block = blocks.get(info.name)
|
|
if not isinstance(block, dict):
|
|
continue
|
|
host = str(block.get("host") or "127.0.0.1").strip()
|
|
# A bind-all address is not a callable one; skills always call loopback.
|
|
if host in ("", "0.0.0.0", "::", "[::]"):
|
|
host = "127.0.0.1"
|
|
port = block.get("port")
|
|
if info.url_config_var and port:
|
|
derived[info.url_config_var] = f"http://{host}:{int(port)}"
|
|
if info.auth_config_var:
|
|
derived[info.auth_config_var] = str(block.get("token") or "")
|
|
return derived
|
|
|
|
|
|
def describe_bridges() -> str:
|
|
"""A prompt block describing every available bridge service.
|
|
|
|
Injected into the skill-body, retry, regen, and testgen
|
|
prompts so codegen knows which real services it may build a skill against,
|
|
how to reach and authenticate to each one, and which `ctx.config` variables
|
|
carry its URL, token, and other values. This is the single source of bridge
|
|
specifics — CODEGEN.md/TESTGEN.md carry only the generic pattern. Static: no
|
|
bridge needs to be running or enabled.
|
|
"""
|
|
lines = [
|
|
"Available bridge services (call these over HTTP with urllib.request; "
|
|
"never speak a service's native protocol directly; read every value "
|
|
"from ctx.config):",
|
|
]
|
|
for info in known_infos():
|
|
lines.append(f"- {info.name} (service: {info.service}): {info.description}")
|
|
lines.append(f" base URL config var: {info.url_config_var}")
|
|
if info.auth_header and info.auth_config_var:
|
|
lines.append(
|
|
f" auth: send the value of {info.auth_config_var} in the "
|
|
f"{info.auth_header} header when it is set"
|
|
)
|
|
docs = dict(info.config_var_docs)
|
|
if info.config_vars:
|
|
lines.append(" config vars:")
|
|
for name in info.config_vars:
|
|
description = docs.get(name)
|
|
suffix = f" — {description}" if description else ""
|
|
lines.append(f" - {name}{suffix}")
|
|
if info.endpoints:
|
|
lines.append(" endpoints:")
|
|
for endpoint in info.endpoints:
|
|
lines.append(f" - {endpoint}")
|
|
return "\n".join(lines) + "\n"
|
|
|
|
|
|
def build_bridge(
|
|
config: dict, name: str, trace=None, llm=None
|
|
) -> BridgeService:
|
|
"""Instantiate one bridge from the top-level `bridges.<name>` config block.
|
|
|
|
`llm` is the scheduler's configured language-model client, handed to the LLM
|
|
bridge so it reuses the top-level `llm` endpoint/model instead of duplicating
|
|
that config. The Nextcloud bridge gets the top-level `nextcloud_*` values as a
|
|
fallback, so the same account the nextcloud seeds use is configured once. Other
|
|
bridges ignore both.
|
|
"""
|
|
bridge_class = _class_for(name)
|
|
if bridge_class is None:
|
|
raise KeyError(f"unknown bridge: {name!r}")
|
|
block = (config.get("bridges", {}) or {}).get(name, {}) or {}
|
|
if bridge_class is LLMBridge:
|
|
return LLMBridge(block, trace=trace, client=llm)
|
|
if bridge_class is NextcloudBridge:
|
|
return NextcloudBridge(
|
|
block,
|
|
trace=trace,
|
|
fallback={
|
|
"url": config.get("nextcloud_url"),
|
|
"username": config.get("nextcloud_username"),
|
|
"app_password": config.get("nextcloud_app_password"),
|
|
"default_calendar": config.get("nextcloud_default_calendar"),
|
|
"default_task_calendar": config.get("nextcloud_default_task_calendar"),
|
|
"default_addressbook": config.get("nextcloud_default_addressbook"),
|
|
},
|
|
)
|
|
return bridge_class(block, trace=trace)
|
|
|
|
|
|
def run_bridges(
|
|
config: dict,
|
|
names: list[str] | None = None,
|
|
trace=None,
|
|
llm=None,
|
|
) -> int:
|
|
"""Run the selected (+ enabled) bridges until interrupted.
|
|
|
|
With explicit `names`, a bridge runs even if disabled is not set; with no
|
|
names, only `enabled` bridges run. Returns a process exit code. `llm` is the
|
|
scheduler's configured language-model client (see `build_bridge`).
|
|
"""
|
|
blocks = config.get("bridges", {}) or {}
|
|
selected: list[BridgeService] = []
|
|
for bridge_class in CATALOG:
|
|
name = bridge_class.INFO.name
|
|
if names and name not in names:
|
|
continue
|
|
block = blocks.get(name, {}) or {}
|
|
if not names and not block.get("enabled", False):
|
|
continue
|
|
bridge = build_bridge(config, name, trace=trace, llm=llm)
|
|
ok, hint = bridge.check_requirements()
|
|
if not ok:
|
|
print(f"bridge {name} unavailable: {hint}")
|
|
for running in selected:
|
|
running.stop()
|
|
return 1
|
|
port = bridge.start()
|
|
selected.append(bridge)
|
|
print(
|
|
f"bridge {name} listening on http://{bridge.host}:{port} "
|
|
f"(skills use the {bridge_class.INFO.url_config_var} config var)"
|
|
)
|
|
if not selected:
|
|
print("no bridge services enabled (set bridges.<name>.enabled)")
|
|
return 1
|
|
|
|
stop = threading.Event()
|
|
try:
|
|
while not stop.wait(0.5):
|
|
pass
|
|
except KeyboardInterrupt:
|
|
pass
|
|
finally:
|
|
for bridge in selected:
|
|
bridge.stop()
|
|
return 0
|