bridges: standalone third-party API bridges; isolate the command gateway
Split messaging UX (invite links, read, send) out of the command gateway into a
new `semif_agent.bridges` layer. Each bridge is its own process (`cli bridge`)
against its own service daemon/profile; the SimpleX bridge owns a second
simplex-chat daemon and buffers every inbound DM, so a message sent to the
connect-link address shows up in `simplex.next_message`.
- new: bridges/{base,inbox,registry,simplex}.py + neutral semif_agent/simplex_ws.py
- gateway: delete bridge.py; drop address/observer/pull-mode from the command path
- codegen: inject the bridge catalog (describe_bridges) into body + elicitation prompts
- seeds: repoint simplex.next_message/connect_link to top-level `simplex_bridge_url`
- config/bootstrap: new top-level `bridges` block + `simplex_bridge_url`; render
semif-simplex-forward + semif-bridge units; gateway config loses bridge/inbox
- docs: AGENTS.md gateway isolation is non-negotiable
This commit is contained in:
1 parent
d46fbdca19
commit
ddc5cb66c8
31 files changed
+1702
-1088
No files matched your search
@@ -0,0 +1,38 @@
|
||||
"""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 first, more later) 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, a CLI's private flags) directly: it
|
||||
calls a small, documented, uniform HTTP surface instead, and the bridge owns the
|
||||
messy integration details and credentials.
|
||||
|
||||
Two boundaries matter:
|
||||
|
||||
- **Bridges are not the gateway.** The command gateway only takes commands and
|
||||
replies; it must never grow read/send/invite endpoints. Bridges run as their
|
||||
own processes (`python -m semif_agent.cli bridge`) against their own service
|
||||
daemons/profiles. This isolation is non-negotiable (see AGENTS.md).
|
||||
- **The catalog is visible to codegen.** `describe_bridges()` is injected into
|
||||
the code-generation prompts so the model knows which real services it may
|
||||
build against and how to reach them.
|
||||
"""
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .inbox import MessagingInbox
|
||||
from .registry import (
|
||||
build_bridge,
|
||||
describe_bridges,
|
||||
known_infos,
|
||||
run_bridges,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"BridgeInfo",
|
||||
"BridgeService",
|
||||
"MessagingInbox",
|
||||
"build_bridge",
|
||||
"describe_bridges",
|
||||
"known_infos",
|
||||
"run_bridges",
|
||||
]
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Bridge service contract + the shared secure HTTP layer.
|
||||
|
||||
Every bridge stands up the same thin HTTP surface: JSON in, JSON out, bound to
|
||||
localhost, optionally guarded by a shared-secret header. A subclass only
|
||||
implements its routes (`handle_get` / `handle_post`) and, if it needs a service
|
||||
daemon, starts it in `start()`. The HTTP/JSON/auth plumbing lives here once so
|
||||
each new bridge is small and hard to get wrong.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import threading
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BridgeInfo:
|
||||
"""Static, prompt-safe metadata about a bridge.
|
||||
|
||||
Fed to the code-generation model so it knows what it can build against,
|
||||
and used to describe the service in docs. Holds no secrets and needs no
|
||||
running process.
|
||||
"""
|
||||
|
||||
name: str
|
||||
service: str
|
||||
description: str
|
||||
url_config_var: str
|
||||
#: Human-readable `METHOD /path` -> purpose lines.
|
||||
endpoints: tuple[str, ...] = ()
|
||||
#: Other `ctx.config` keys a body built on this bridge may read.
|
||||
config_vars: tuple[str, ...] = field(default=())
|
||||
|
||||
|
||||
class BridgeService(ABC):
|
||||
"""Base class for a standalone third-party API bridge."""
|
||||
|
||||
#: short snake_case id (`simplex`)
|
||||
name: str = "bridge"
|
||||
#: static catalog entry
|
||||
info: BridgeInfo
|
||||
|
||||
def __init__(self, config: dict | None = None, trace=None):
|
||||
cfg = config or {}
|
||||
self.host = str(cfg.get("host", "127.0.0.1"))
|
||||
self.port = int(cfg.get("port", 0))
|
||||
self.token = str(cfg.get("token", "") or "")
|
||||
self.trace = trace
|
||||
self._server: ThreadingHTTPServer | None = None
|
||||
self._thread: threading.Thread | None = None
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
@abstractmethod
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
"""Return `(ok, install_hint)`. Must never raise on a missing dep."""
|
||||
|
||||
def start(self) -> int:
|
||||
"""Start serving HTTP; returns the bound port (`port=0` is ephemeral)."""
|
||||
server = ThreadingHTTPServer((self.host, self.port), _BridgeHTTPHandler)
|
||||
server.bridge = self # type: ignore[attr-defined]
|
||||
self._server = server
|
||||
self._thread = threading.Thread(
|
||||
target=server.serve_forever,
|
||||
name=f"bridge-{self.name}",
|
||||
daemon=True,
|
||||
)
|
||||
self._thread.start()
|
||||
return int(server.server_address[1])
|
||||
|
||||
def stop(self) -> None:
|
||||
self._stop_transport()
|
||||
server, self._server = self._server, None
|
||||
if server is not None:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread, self._thread = self._thread, None
|
||||
if thread is not None:
|
||||
thread.join(timeout=2.0)
|
||||
|
||||
def _stop_transport(self) -> None:
|
||||
"""Hook for subclasses that own a background transport (daemon)."""
|
||||
|
||||
# ---- routes ----
|
||||
|
||||
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
# ---- helpers ----
|
||||
|
||||
def _event(self, kind: str, **fields) -> None:
|
||||
if self.trace is not None:
|
||||
self.trace.append(kind, "?", **fields)
|
||||
|
||||
|
||||
class _BridgeHTTPHandler(BaseHTTPRequestHandler):
|
||||
"""JSON request handler; the owning bridge is on `self.server.bridge`."""
|
||||
|
||||
def log_message(self, *args) -> None: # silence the default stderr spam
|
||||
pass
|
||||
|
||||
def _bridge(self) -> BridgeService:
|
||||
return self.server.bridge # type: ignore[attr-defined]
|
||||
|
||||
def _authorized(self) -> bool:
|
||||
token = self._bridge().token
|
||||
if not token:
|
||||
return True
|
||||
return self.headers.get("X-Semif-Token") == token
|
||||
|
||||
def _json(self, status: int, payload: dict) -> None:
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _require_auth(self) -> bool:
|
||||
if self._authorized():
|
||||
return True
|
||||
self._json(401, {"error": "unauthorized"})
|
||||
return False
|
||||
|
||||
def do_GET(self) -> None:
|
||||
if not self._require_auth():
|
||||
return
|
||||
url = urlparse(self.path)
|
||||
status, payload = self._bridge().handle_get(url.path, parse_qs(url.query))
|
||||
self._json(status, payload)
|
||||
|
||||
def do_POST(self) -> None:
|
||||
if not self._require_auth():
|
||||
return
|
||||
url = urlparse(self.path)
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(length) if length else b""
|
||||
try:
|
||||
payload = json.loads(raw.decode("utf-8") or "{}")
|
||||
except ValueError:
|
||||
self._json(400, {"error": "invalid JSON body"})
|
||||
return
|
||||
if not isinstance(payload, dict):
|
||||
self._json(400, {"error": "body must be a JSON object"})
|
||||
return
|
||||
status, response = self._bridge().handle_post(url.path, payload)
|
||||
self._json(status, response)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""A bounded, thread-safe FIFO of buffered inbound messages + known contacts.
|
||||
|
||||
The bridge owns the read cursor so a read skill stays stateless. Generic over
|
||||
transports: entries are normalized message dicts (`contact_id`, `display_name`,
|
||||
`text`), which is exactly what `semif_agent.simplex_ws` yields.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from collections import deque
|
||||
|
||||
|
||||
class MessagingInbox:
|
||||
def __init__(self, max_size: int = 100):
|
||||
self._lock = threading.Lock()
|
||||
self._items: deque[dict] = deque()
|
||||
self._max = max(1, int(max_size))
|
||||
self._contacts: dict[str, str] = {}
|
||||
|
||||
def record(self, message: dict) -> dict:
|
||||
contact_id = str(message.get("contact_id") or "")
|
||||
display_name = message.get("display_name") or ""
|
||||
entry = {
|
||||
"id": uuid.uuid4().hex[:12],
|
||||
"contact_id": contact_id,
|
||||
"display_name": display_name,
|
||||
"text": message.get("text") or "",
|
||||
"received_at": time.time(),
|
||||
}
|
||||
with self._lock:
|
||||
if display_name:
|
||||
self._contacts[contact_id] = display_name
|
||||
else:
|
||||
self._contacts.setdefault(contact_id, "")
|
||||
self._items.append(entry)
|
||||
while len(self._items) > self._max:
|
||||
self._items.popleft()
|
||||
return entry
|
||||
|
||||
def peek(self) -> list[dict]:
|
||||
with self._lock:
|
||||
return list(self._items)
|
||||
|
||||
def pop(self, contact_id: str | None = None) -> dict | None:
|
||||
with self._lock:
|
||||
if contact_id is None:
|
||||
return self._items.popleft() if self._items else None
|
||||
target = str(contact_id)
|
||||
for index, entry in enumerate(self._items):
|
||||
if entry["contact_id"] == target:
|
||||
del self._items[index]
|
||||
return entry
|
||||
return None
|
||||
|
||||
def contacts(self) -> list[dict]:
|
||||
with self._lock:
|
||||
return [
|
||||
{"id": contact_id, "display_name": name}
|
||||
for contact_id, name in self._contacts.items()
|
||||
]
|
||||
@@ -0,0 +1,111 @@
|
||||
"""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 .simplex import SimplexBridge
|
||||
|
||||
#: Known bridge services. Order is presentation order.
|
||||
CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge,)
|
||||
|
||||
|
||||
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 describe_bridges() -> str:
|
||||
"""A prompt block describing every available bridge service.
|
||||
|
||||
Injected into the skill-body and elicitation prompts so codegen knows which
|
||||
real services it may build a skill against, how to reach each one, and which
|
||||
`ctx.config` variable carries its URL. 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):",
|
||||
]
|
||||
for info in known_infos():
|
||||
lines.append(f"- {info.name}: {info.description}")
|
||||
lines.append(f" config var: {info.url_config_var}")
|
||||
if info.config_vars:
|
||||
other = [v for v in info.config_vars if v != info.url_config_var]
|
||||
if other:
|
||||
lines.append(f" other config vars: {', '.join(other)}")
|
||||
for endpoint in info.endpoints:
|
||||
lines.append(f" {endpoint}")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def build_bridge(config: dict, name: str, trace=None) -> BridgeService:
|
||||
"""Instantiate one bridge from the top-level `bridges.<name>` config block."""
|
||||
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 {}
|
||||
return bridge_class(block, trace=trace)
|
||||
|
||||
|
||||
def run_bridges(
|
||||
config: dict,
|
||||
names: list[str] | None = None,
|
||||
trace=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.
|
||||
"""
|
||||
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 = bridge_class(block, trace=trace)
|
||||
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
|
||||
@@ -0,0 +1,148 @@
|
||||
"""SimpleX forwarding bridge: invite links, reading, and sending for skills.
|
||||
|
||||
The first third-party API bridge. It stands up a small HTTP API that a skill
|
||||
body calls instead of talking to `simplex-chat` directly, and it owns its **own**
|
||||
SimpleX daemon/profile — separate from the command gateway's. That separation is
|
||||
the point: the gateway takes commands; this bridge forwards the user's messaging
|
||||
UX (show/create the contact link, read the next message, compose a send).
|
||||
|
||||
It buffers every inbound direct message (no allowlist — the user wants to see
|
||||
who reached the bot through its invite link), and it never runs inside the
|
||||
gateway process.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
from semif_agent.simplex_ws import SimplexDaemon
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .inbox import MessagingInbox
|
||||
|
||||
|
||||
class SimplexBridge(BridgeService):
|
||||
name = "simplex"
|
||||
INFO = BridgeInfo(
|
||||
name="simplex",
|
||||
service="simplex",
|
||||
description=(
|
||||
"Read and send SimpleX messages on the user's behalf, and show or "
|
||||
"create the contact link others use to reach this agent."
|
||||
),
|
||||
url_config_var="simplex_bridge_url",
|
||||
endpoints=(
|
||||
"GET /health -> {\"ok\": true} — the bridge is up",
|
||||
"GET /contacts -> {\"contacts\": [{\"id\", \"display_name\"}]}",
|
||||
"GET /inbox -> peek buffered inbound messages (does not consume)",
|
||||
"GET /inbox/next?contact=<id> -> pop the oldest unread message for a "
|
||||
"contact (or any contact) -> {\"message\": {...}|null}",
|
||||
"GET /address -> the agent's SimpleX contact link "
|
||||
"(creates it on first call) -> {\"short_link\", \"full_link\", "
|
||||
"\"created\"}",
|
||||
"POST /send {\"recipient\": \"<id|display_name>\", \"text\": \"...\"} "
|
||||
"-> {\"ok\", \"contact_id\"}",
|
||||
),
|
||||
config_vars=("simplex_bridge_url", "simplex_default_contact"),
|
||||
)
|
||||
|
||||
def __init__(self, config: dict | None = None, trace=None, daemon=None):
|
||||
super().__init__(config, trace)
|
||||
cfg = config or {}
|
||||
self.inbox = MessagingInbox(int(cfg.get("max_inbox", 100)))
|
||||
self.daemon = daemon or SimplexDaemon(
|
||||
cfg.get("ws_url", "ws://127.0.0.1:5228"),
|
||||
user_id=int(cfg.get("user_id", 1)),
|
||||
auto_accept=bool(cfg.get("auto_accept", True)),
|
||||
reconnect=cfg.get("reconnect", {}) or {},
|
||||
trace=trace,
|
||||
name=self.name,
|
||||
)
|
||||
self._daemon_thread: threading.Thread | None = None
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
return self.daemon.check_requirements()
|
||||
|
||||
def start(self) -> int:
|
||||
port = super().start()
|
||||
self._daemon_thread = threading.Thread(
|
||||
target=self.daemon.run,
|
||||
args=(self._on_message,),
|
||||
name="bridge-simplex-daemon",
|
||||
daemon=True,
|
||||
)
|
||||
self._daemon_thread.start()
|
||||
return port
|
||||
|
||||
def _stop_transport(self) -> None:
|
||||
self.daemon.close()
|
||||
|
||||
def _on_message(self, message: dict) -> None:
|
||||
self.inbox.record(message)
|
||||
|
||||
# ---- routes ----
|
||||
|
||||
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/health":
|
||||
return 200, {"ok": True, "platform": self.name}
|
||||
if path == "/contacts":
|
||||
return 200, {"contacts": self.inbox.contacts()}
|
||||
if path == "/inbox":
|
||||
return 200, {"messages": self.inbox.peek()}
|
||||
if path == "/inbox/next":
|
||||
contact = (query.get("contact") or [None])[0]
|
||||
return 200, {"message": self.inbox.pop(contact)}
|
||||
if path == "/address":
|
||||
return self._address()
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if path != "/send":
|
||||
return 404, {"error": "not found"}
|
||||
recipient = payload.get("recipient")
|
||||
text = payload.get("text")
|
||||
if not isinstance(recipient, str) or not recipient.strip():
|
||||
return 400, {"error": "recipient is required"}
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return 400, {"error": "text is required"}
|
||||
try:
|
||||
contact_id = self.send(recipient, text)
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)}
|
||||
return 200, {"ok": True, "contact_id": contact_id}
|
||||
|
||||
# ---- actions ----
|
||||
|
||||
def _address(self) -> tuple[int, dict]:
|
||||
try:
|
||||
link = self.daemon.request_address()
|
||||
except RuntimeError as exc:
|
||||
return 503, {"error": f"address lookup is not available: {exc}"[:300]}
|
||||
except Exception as exc: # TimeoutError, daemon error
|
||||
return 502, {"error": f"address lookup failed: {exc}"[:300]}
|
||||
if not isinstance(link, dict):
|
||||
return 502, {"error": "address lookup returned no link"}
|
||||
return 200, link
|
||||
|
||||
def send(self, recipient: str, text: str) -> str:
|
||||
"""Resolve a recipient and enqueue the message. Returns the contact id."""
|
||||
contact_id = self.resolve(recipient)
|
||||
if contact_id is None:
|
||||
raise ValueError(f"unknown SimpleX recipient: {recipient!r}")
|
||||
self.daemon.enqueue(contact_id, text)
|
||||
return contact_id
|
||||
|
||||
def resolve(self, recipient: str) -> str | None:
|
||||
"""A numeric id (with or without `@`) or a known display name."""
|
||||
recipient = str(recipient or "").strip()
|
||||
if not recipient:
|
||||
return None
|
||||
bare = recipient.lstrip("@")
|
||||
if bare.isdigit():
|
||||
return bare
|
||||
for contact in self.inbox.contacts():
|
||||
if contact["display_name"] == recipient or contact["id"] == recipient:
|
||||
return contact["id"]
|
||||
return None
|
||||
Reference in new issue
Block a user