From a929d647b7fa46834fa42458aa5cc8ead1c2611c Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Tue, 13 Oct 2026 23:52:52 +0000 Subject: [PATCH] Ship the bridge with the pack (moved from the agent core) The core now keeps only the shared bridge contract (semif_agent/bridges/base.py) and the discovery registry (semif_agent/bridges/registry.py); a pack ships its own bridge under bridge/.py and the registry imports it by convention from the pack's declared `bridges`. The bridge's hermetic test moves here too and runs via the agent repo's tests/test_packs.py (or standalone with conftest.py). --- bridge/__init__.py | 7 + bridge/simplex.py | 492 +++++++++++++++++++++++++ bridge/test_simplex_bridge.py | 675 ++++++++++++++++++++++++++++++++++ conftest.py | 17 + 4 files changed, 1191 insertions(+) create mode 100644 bridge/__init__.py create mode 100644 bridge/simplex.py create mode 100644 bridge/test_simplex_bridge.py create mode 100644 conftest.py diff --git a/bridge/__init__.py b/bridge/__init__.py new file mode 100644 index 0000000..54c7c90 --- /dev/null +++ b/bridge/__init__.py @@ -0,0 +1,7 @@ +"""The simplex pack's bridge: a localhost HTTP surface in front of its service. + +The bridge implementation ships with the pack (see PACKGEN.md, "Authoring a +bridge"); the core imports it by convention from this package. It subclasses +`semif_agent.bridges.base.BridgeService` and declares a `BridgeInfo` catalog +entry that codegen reads via `describe_bridges()`. +""" diff --git a/bridge/simplex.py b/bridge/simplex.py new file mode 100644 index 0000000..0f782e1 --- /dev/null +++ b/bridge/simplex.py @@ -0,0 +1,492 @@ +"""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 +import time + +from semif_agent.bridges.base import BridgeInfo, BridgeService +from semif_agent.bridges.inbox import MessagingInbox +from semif_agent.simplex_ws import SimplexDaemon, parse_send_response + +#: Send statuses that mean the message really left the agent. +SEND_OK_STATUSES = frozenset({"sndSent", "sndRcvd"}) +#: Send statuses that are final (no further polling needed). +SEND_TERMINAL_STATUSES = frozenset({"sndSent", "sndRcvd", "sndError"}) +#: How long to poll the daemon for a terminal send status before giving up. +SEND_CONFIRM_TIMEOUT = 6.0 +SEND_POLL_INTERVAL = 0.5 + + +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 -> 200 {\"ok\": true, \"platform\": \"simplex\"} — the " + "bridge is up", + "GET /contacts -> 200 {\"contacts\": [{\"id\", \"display_name\", " + "\"local_name\"?, \"connected\"?}]} — contacts known to the daemon " + "(learned from inbound messages and refreshed from the daemon's " + "contact list). `display_name` is the peer's profile name and can " + "collide; `local_name` is the daemon's unique local name; " + "`connected` (when the daemon reports it) is false for a peer whose " + "connection is not ready — prefer a connected peer", + "GET /inbox -> 200 {\"messages\": [{\"id\", \"contact_id\", " + "\"display_name\", \"text\", \"received_at\"}]} — peek buffered " + "inbound messages; does not consume", + "GET /inbox/next?contact= -> 200 {\"message\": {...}|null} — pop " + "the oldest unread message (optionally from one contact); null means " + "none buffered. The bridge owns the read cursor", + "GET /unread -> 200 {\"chats\": [{\"contact_id\", \"display_name\", " + "\"unread_count\", \"min_unread_item_id\", \"unread\", " + "\"connected\"?, \"auth_errors\"?, \"messages\": " + "[{item_id, text, status, unread, direction, sent_at}]}]} — the " + "daemon's persistent unread chats (survives bridge restarts), not " + "just what arrived while connected. Read-only; 503 when the daemon " + "is not connected, 502 when the lookup fails", + "GET /history?contact=&count= -> 200 {\"contact_id\", " + "\"messages\": [{item_id, text, status, unread, direction, " + "sent_at, error?}]} — recent message history for one contact (count " + "default 20); status is rcvNew (unread), rcvRead, sndSent, sndRcvd, " + "or sndError, and `error` carries the agent reason (e.g. auth) on a " + "failed send. Read-only; 503/502 as /unread, 400 without a contact", + "GET /address -> 200 {\"short_link\", \"full_link\", \"created\"} — " + "the agent's contact link; creates it on first call. 503 when the " + "daemon is not connected, 502 when the lookup fails", + "POST /send {\"recipient\": \"\", " + "\"text\": \"...\"} -> 200 {\"ok\": bool, \"contact_id\": \"\", " + "\"item_id\": \"\", \"status\": \"sndSent|sndRcvd|sndError\", " + "\"error\": \"...\"?}. The bridge resolves the recipient, sends, and " + "waits for the daemon's real send status: `ok` is true only for " + "sndSent/sndRcvd, and a failed send (e.g. an auth error on a dead " + "connection) returns ok:false with the reason — never a false " + "success. 400 on a missing/invalid field or an unknown recipient", + "POST /read {\"contact\": \"\", \"item_ids\": [\"\", ...]} -> " + "200 {\"ok\": bool, \"contact_id\": \"\", \"item_ids\": [...], " + "\"status\": \"read|rejected|error|unavailable\", \"error\": " + "\"...\"?} — mark the given received items read on the daemon so they " + "leave its persistent unread state; only the listed ids are consumed. " + "`ok` is true only when the daemon accepted it — never a fabricated " + "success. 400 on a missing contact or empty item_ids", + "any request -> 401 {\"error\": \"unauthorized\"} when the token is " + "configured and the auth header is missing or wrong", + ), + config_vars=( + "simplex_bridge_url", + "simplex_default_contact", + "simplex_bridge_token", + ), + config_var_docs=( + ( + "simplex_bridge_url", + "Base URL of the local SimpleX forwarding bridge " + "(e.g. http://127.0.0.1:5227); never hardcode it in the body.", + ), + ( + "simplex_default_contact", + "Optional default SimpleX contact (contact id or display name) " + "used when the request does not already make the conversation " + "clear; leave blank to always choose among senders.", + ), + ( + "simplex_bridge_token", + "Shared secret for the bridge, if one is configured; sent as the " + "X-Semif-Token header. Leave blank when the bridge requires no " + "auth.", + ), + ), + auth_header="X-Semif-Token", + auth_config_var="simplex_bridge_token", + ) + + 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 {}, + on_connected=self._refresh_on_connect, + 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) + + async def _refresh_on_connect(self) -> None: + """Prime the contact list from the daemon on (re)connect. + + Runs on the daemon's event loop, so it awaits `contacts()` directly + rather than the thread-safe wrapper. A failure is traced, not fatal. + """ + contacts = await self.daemon.contacts() + self.inbox.merge_contacts(contacts) + self._event("contacts_refreshed", count=len(contacts)) + + # ---- 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.refresh_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 == "/unread": + return self._unread(query) + if path == "/history": + contact = (query.get("contact") or [None])[0] + count = (query.get("count") or [None])[0] + return self._history(contact, count) + if path == "/address": + return self._address() + return 404, {"error": "not found"} + + def handle_post(self, path: str, payload: dict) -> tuple[int, dict]: + if path == "/read": + return self._read(payload) + 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: + result = self.send(recipient, text) + except ValueError as exc: + return 400, {"error": str(exc)} + return 200, result + + # ---- actions ---- + + def _read(self, payload: dict) -> tuple[int, dict]: + contact = payload.get("contact") + item_ids = payload.get("item_ids") + if not isinstance(contact, str) or not contact.strip(): + return 400, {"error": "contact is required"} + if not isinstance(item_ids, list) or not item_ids: + return 400, {"error": "item_ids is required"} + try: + result = self.mark_read(contact, item_ids) + except ValueError as exc: + return 400, {"error": str(exc)} + return 200, result + + def mark_read(self, contact: str, item_ids) -> dict: + """Mark the given received items read on the bridge's own daemon. + + Returns `{ok, contact_id, item_ids, status, error?}`. `ok` is True only + when the daemon accepted the command; a disconnected or failing daemon + reports the reason (never a false success). Reading is precise: only the + listed item ids are consumed, so the rest of the chat stays unread. + """ + contact_id = str(contact or "").strip() + ids = [str(i).strip() for i in (item_ids or []) if str(i).strip()] + if not contact_id: + raise ValueError("contact is required") + if not ids: + raise ValueError("item_ids is required") + try: + response = self.daemon.request_mark_read(contact_id, ids) + except RuntimeError as exc: + return { + "ok": False, + "contact_id": contact_id, + "item_ids": ids, + "status": "unavailable", + "error": str(exc)[:300], + } + except Exception as exc: # TimeoutError, daemon error + return { + "ok": False, + "contact_id": contact_id, + "item_ids": ids, + "status": "error", + "error": str(exc)[:300], + } + ok = bool(response.get("ok")) if isinstance(response, dict) else False + result = { + "ok": ok, + "contact_id": contact_id, + "item_ids": ids, + "status": "read" if ok else "rejected", + } + if not ok: + detail = response.get("error") if isinstance(response, dict) else "" + result["error"] = detail or "the daemon did not mark the items read" + return result + + def refresh_contacts(self) -> list[dict]: + """Best-effort refresh of the daemon's contact list into the inbox. + + Never raises: when the daemon is not connected (or is slow) it returns + whatever contacts are already cached, so `/contacts` and `/send` stay + available. The read cursor and inbound-learned names are preserved. + """ + try: + contacts = self.daemon.request_contacts() + except Exception as exc: # RuntimeError, TimeoutError, daemon error + self._event("contacts_refresh_failed", message=str(exc)[:200]) + return self.inbox.contacts() + self.inbox.merge_contacts(contacts) + self._event("contacts_refreshed", count=len(contacts)) + return self.inbox.contacts() + + def _unread(self, query: dict) -> tuple[int, dict]: + """The daemon's persistent unread chats (not the live receive buffer). + + Read-only: there is no mark-read command in v7, so this never consumes. + Best-effort like `/address` — 503 when the daemon is not connected, 502 + when the lookup fails, never a fabricated chat. + """ + count = self._count((query.get("count") or [None])[0]) + try: + chats = self.daemon.request_chats(unread_only=True, count=count) + except RuntimeError as exc: + return 503, {"error": f"unread lookup is not available: {exc}"[:300]} + except Exception as exc: # TimeoutError, daemon error + return 502, {"error": f"unread lookup failed: {exc}"[:300]} + self._attach_health(chats) + return 200, {"chats": chats} + + def _attach_health(self, chats: list[dict]) -> None: + """Merge cached connection health into each chat summary, in place. + + Lets a caller prefer a live conversation over a stale duplicate when + several chats share a display name. Best-effort: a chat with no cached + contact is left untouched. + """ + health = {c["id"]: c for c in self.inbox.contacts()} + for chat in chats: + info = health.get(str(chat.get("contact_id") or "")) + if not info: + continue + for key in ("connected", "auth_errors"): + if key in info: + chat[key] = info[key] + + def _history(self, contact: str | None, count: str | None) -> tuple[int, dict]: + """Recent message history for one contact, straight from the daemon. + + Read-only. A missing contact is a client error; a disconnected or + failing daemon degrades like `/unread`. + """ + contact = str(contact or "").strip() + if not contact: + return 400, {"error": "contact is required"} + try: + messages = self.daemon.request_chat_history( + contact, count=self._count(count) + ) + except RuntimeError as exc: + return 503, {"error": f"history lookup is not available: {exc}"[:300]} + except Exception as exc: # TimeoutError, daemon error + return 502, {"error": f"history lookup failed: {exc}"[:300]} + return 200, {"contact_id": contact, "messages": messages} + + @staticmethod + def _count(raw: str | None, default: int = 20, maximum: int = 100) -> int: + try: + value = int(raw) if raw is not None else default + except (TypeError, ValueError): + value = default + return max(1, min(value, maximum)) + + 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) -> dict: + """Resolve a recipient, send the text, and report the real outcome. + + Returns `{ok, contact_id, item_id?, status?, error?}`. `ok` is True only + when the daemon created the message and it reached a terminal status of + `sndSent` (relayed to the server) or `sndRcvd` (delivered to the peer). + A dead connection surfaces as `ok: false` carrying the daemon's agent + error (e.g. `auth`) — never a false success. + """ + contact_id = self.resolve(recipient) + if contact_id is None: + raise ValueError(f"unknown SimpleX recipient: {recipient!r}") + try: + response = self.daemon.request_send(contact_id, text) + except RuntimeError as exc: + return { + "ok": False, + "contact_id": contact_id, + "status": "unavailable", + "error": str(exc)[:300], + } + except Exception as exc: # TimeoutError, daemon error + return { + "ok": False, + "contact_id": contact_id, + "status": "error", + "error": str(exc)[:300], + } + parsed = parse_send_response(response) + if parsed["item_id"] is None: + return { + "ok": False, + "contact_id": contact_id, + "status": "rejected", + "error": parsed["error"] or "the daemon rejected the send", + } + item_id = parsed["item_id"] + status, error = parsed["status"], parsed["error"] + if status not in SEND_TERMINAL_STATUSES: + status, error = self._await_send_status(contact_id, item_id, status) + result = { + "ok": status in SEND_OK_STATUSES, + "contact_id": contact_id, + "item_id": item_id, + "status": status, + } + if not result["ok"]: + result["error"] = error or f"send status {status}" + return result + + def _await_send_status( + self, contact_id: str, item_id: str, current: str, + timeout: float = SEND_CONFIRM_TIMEOUT, + ) -> tuple[str, str]: + """Poll the daemon for the item's terminal send status + agent error. + + A send is `sndNew` the moment it is created; the agent then resolves it + to `sndSent`/`sndRcvd` (success) or `sndError` (failure, with the reason + in `agentError`). Returns `(status, error)`; a still-`sndNew` item after + the window stays unconfirmed rather than being reported as sent. + """ + deadline = time.monotonic() + timeout + status, error = current, "" + while True: + try: + messages = self.daemon.request_chat_history(contact_id, count=20) + except Exception: + return status or "unknown", error + for message in messages: + if str(message.get("item_id")) == str(item_id): + status = str(message.get("status") or "") + error = str(message.get("error") or "") + if status in SEND_TERMINAL_STATUSES: + return status, error + if time.monotonic() >= deadline: + return status or "unknown", error + time.sleep(SEND_POLL_INTERVAL) + + def resolve(self, recipient: str) -> str | None: + """A numeric id (with or without `@`), a unique local name, or a display name. + + An explicit id always wins. Two peers can share a profile display name + (the daemon suffixes its own local names, e.g. `pepper` / `pepper_1`), + so a local-name or display-name match that hits several peers prefers + the healthiest (connected, no recorded auth errors). On a miss, refresh + the daemon's contact list once and retry: a contact the bridge has never + received from is still addressable as long as the daemon knows them. + """ + recipient = str(recipient or "").strip() + if not recipient: + return None + bare = recipient.lstrip("@") + if bare.isdigit(): + return bare + match = self._match_contact(recipient) + if match is None: + self.refresh_contacts() + match = self._match_contact(recipient) + return match + + def _match_contact(self, recipient: str) -> str | None: + contacts = self.inbox.contacts() + for contact in contacts: + if contact["id"] == recipient: + return contact["id"] + exact = [ + c + for c in contacts + if c.get("local_name") == recipient or c["display_name"] == recipient + ] + if exact: + return self._prefer_connected(exact) + lowered = recipient.lower() + partial = [ + c + for c in contacts + if lowered in c["display_name"].lower() + or lowered in str(c.get("local_name", "")).lower() + ] + if len(partial) == 1: + return partial[0]["id"] + if partial: + return self._prefer_connected(partial) + return None + + @staticmethod + def _prefer_connected(matches: list[dict]) -> str: + """Pick the healthiest peer among equally-named matches. + + Prefer a ready connection, then a connection with no recorded auth + errors (a stale duplicate that fails to send), and finally the first. + """ + + def rank(contact: dict) -> tuple[bool, bool]: + try: + clean = int(contact.get("auth_errors") or 0) == 0 + except (TypeError, ValueError): + clean = True + return (bool(contact.get("connected")), clean) + + return max(matches, key=rank)["id"] diff --git a/bridge/test_simplex_bridge.py b/bridge/test_simplex_bridge.py new file mode 100644 index 0000000..4daa1fe --- /dev/null +++ b/bridge/test_simplex_bridge.py @@ -0,0 +1,675 @@ +"""Pure-stdlib tests for the SimpleX forwarding bridge. + +The bridge ships with the `simplex` pack (`bridge/simplex.py`); the core loads it +by convention. It is exercised over a real loopback HTTP server (no mocking of +its HTTP transport) with a fake daemon standing in for the `simplex-chat` +connection — the decision engine and LLM are never involved. These prove the +mechanics a skill depends on: peek/pop of buffered inbound messages, recipient +resolution, outbound routing, address lookup, and token/body validation. + +The bridge module is imported through the core registry +(`load_pack_bridge_module`) — the same path production uses — so the test also +proves the pack's bridge is discoverable and wired. +""" + +import asyncio +import json +import urllib.error +import urllib.request + +import pytest + +from semif_agent.bridges.registry import ( + describe_bridges, + known_infos, + load_pack_bridge_module, +) + +_simplex = load_pack_bridge_module("simplex", "simplex") +SimplexBridge = _simplex.SimplexBridge + +class FakeDaemon: + """Stands in for the bridge's own simplex-chat connection.""" + + def __init__( + self, + link=None, + error=None, + contacts=None, + contacts_error=None, + chats=None, + chats_error=None, + history=None, + history_error=None, + send_response=None, + send_error=None, + read_response=None, + read_error=None, + ): + self.link = link + self.error = error + self.contacts_list = contacts or [] + self.contacts_error = contacts_error + self.chats_list = chats or [] + self.chats_error = chats_error + self.history_list = history or [] + self.history_error = history_error + self.send_response = send_response + self.send_error = send_error + self.read_response = read_response + self.read_error = read_error + self.refresh_count = 0 + self.chat_calls = [] + self.history_calls = [] + self.read_calls = [] + self.sent = [] + self.closed = False + self.on_message = None + + def check_requirements(self): + return True, None + + def run(self, on_message): + self.on_message = on_message + + def enqueue(self, chat_id, text=""): + if chat_id is not None: + self.sent.append((chat_id, text)) + + def request_send(self, chat_id, text, timeout=20.0): + self.sent.append((chat_id, text)) + if self.send_error is not None: + raise self.send_error + if self.send_response is not None: + return self.send_response + return { + "type": "newChatItems", + "chatItems": [ + {"chatItem": {"meta": {"itemId": 1, "itemStatus": {"type": "sndRcvd"}}}} + ], + } + + def request_address(self, timeout=20.0): + if self.error is not None: + raise self.error + return self.link + + def request_contacts(self, timeout=20.0): + self.refresh_count += 1 + if self.contacts_error is not None: + raise self.contacts_error + return list(self.contacts_list) + + async def contacts(self, timeout=20.0): + return self.request_contacts(timeout) + + def request_chats(self, unread_only=True, count=20, timeout=20.0): + self.chat_calls.append((unread_only, count)) + if self.chats_error is not None: + raise self.chats_error + return list(self.chats_list) + + def request_chat_history(self, contact_id, count=20, timeout=20.0): + self.history_calls.append((contact_id, count)) + if self.history_error is not None: + raise self.history_error + return list(self.history_list) + + def request_mark_read(self, chat_id, item_ids=None, timeout=20.0): + self.read_calls.append((str(chat_id), list(item_ids or []))) + if self.read_error is not None: + raise self.read_error + if self.read_response is not None: + return self.read_response + return {"ok": True, "type": "itemsReadForChat", "error": ""} + + def close(self): + self.closed = True + + +def start_bridge(daemon=None, **config): + daemon = daemon or FakeDaemon() + bridge = SimplexBridge(config, daemon=daemon) + port = bridge.start() + return bridge, daemon, f"http://127.0.0.1:{port}" + + +def inbound(text, contact_id="4", display_name="Alice", item_id=""): + return { + "text": text, + "contact_id": contact_id, + "display_name": display_name, + "item_id": item_id, + } + + +def get(url, token=None): + headers = {"X-Semif-Token": token} if token else {} + request = urllib.request.Request(url, headers=headers) + with urllib.request.urlopen(request, timeout=5) as response: + return json.loads(response.read().decode("utf-8")) + + +def post(url, payload, token=None): + body = json.dumps(payload).encode("utf-8") + headers = {"Content-Type": "application/json"} + if token: + headers["X-Semif-Token"] = token + request = urllib.request.Request(url, data=body, headers=headers) + with urllib.request.urlopen(request, timeout=5) as response: + return json.loads(response.read().decode("utf-8")) + + +def test_health_and_contacts(): + bridge, _, base = start_bridge() + try: + assert get(f"{base}/health") == {"ok": True, "platform": "simplex"} + bridge._on_message(inbound("hi", contact_id="4", display_name="Alice")) + assert get(f"{base}/contacts") == { + "contacts": [{"id": "4", "display_name": "Alice"}] + } + finally: + bridge.stop() + + +def test_inbox_peek_then_pop_consumes_oldest(): + bridge, _, base = start_bridge() + try: + bridge._on_message(inbound("first", contact_id="4", display_name="Alice")) + bridge._on_message(inbound("second", contact_id="7", display_name="Bob")) + peeked = get(f"{base}/inbox")["messages"] + assert [m["text"] for m in peeked] == ["first", "second"] + assert get(f"{base}/inbox")["messages"] == peeked, "peek must not consume" + + popped = get(f"{base}/inbox/next")["message"] + assert popped["text"] == "first" + assert popped["contact_id"] == "4" + remaining = get(f"{base}/inbox")["messages"] + assert [m["text"] for m in remaining] == ["second"] + finally: + bridge.stop() + + +def test_inbox_next_filters_by_contact(): + bridge, _, base = start_bridge() + try: + bridge._on_message(inbound("first", contact_id="4", display_name="Alice")) + bridge._on_message(inbound("second", contact_id="7", display_name="Bob")) + popped = get(f"{base}/inbox/next?contact=7")["message"] + assert popped["text"] == "second" + assert get(f"{base}/inbox/next?contact=7")["message"] is None + assert [m["text"] for m in get(f"{base}/inbox")["messages"]] == ["first"] + finally: + bridge.stop() + + +def test_inbox_buffers_any_sender(): + # No allowlist: a brand-new contact who reached the bot via its invite link + # must be visible, which is the whole point of the forwarding bridge. + bridge, _, base = start_bridge() + try: + bridge._on_message(inbound("who are you?", contact_id="99", display_name="stranger")) + messages = get(f"{base}/inbox")["messages"] + assert [m["text"] for m in messages] == ["who are you?"] + finally: + bridge.stop() + + +def test_inbox_is_bounded(): + bridge, _, base = start_bridge(max_inbox=2) + try: + for text in ("one", "two", "three"): + bridge._on_message(inbound(text)) + messages = get(f"{base}/inbox")["messages"] + assert [m["text"] for m in messages] == ["two", "three"], "oldest must be dropped" + finally: + bridge.stop() + + +def test_send_routes_to_daemon(): + bridge, daemon, base = start_bridge() + try: + result = post(f"{base}/send", {"recipient": "7", "text": "on my way"}) + assert result["ok"] is True, result + assert result["contact_id"] == "7", result + assert result["status"] == "sndRcvd", result + assert daemon.sent == [("7", "on my way")] + finally: + bridge.stop() + + +def test_send_resolves_known_display_name(): + bridge, daemon, base = start_bridge() + try: + bridge._on_message(inbound("hi", contact_id="4", display_name="Alice")) + result = post(f"{base}/send", {"recipient": "Alice", "text": "hello"}) + assert result["contact_id"] == "4" + assert daemon.sent == [("4", "hello")] + finally: + bridge.stop() + + +def test_send_reports_a_failed_send_not_a_false_success(): + # A dead connection: the daemon creates the item then marks it sndError. + # The bridge must surface ok:false with the reason, never a false success. + failed = { + "type": "newChatItems", + "chatItems": [ + { + "chatItem": { + "meta": { + "itemId": 12, + "itemStatus": { + "type": "sndError", + "agentError": {"type": "auth"}, + }, + } + } + } + ], + } + daemon = FakeDaemon(send_response=failed) + bridge, _, base = start_bridge(daemon=daemon) + try: + result = post(f"{base}/send", {"recipient": "7", "text": "hey"}) + assert result["ok"] is False, result + assert result["status"] == "sndError", result + assert result["error"] == "auth", result + assert result["contact_id"] == "7" + finally: + bridge.stop() + + +def test_send_verifies_status_via_history(): + # The daemon accepts the send (sndNew) and only later resolves it to a + # delivered status; the bridge polls history to confirm. + accepted = { + "type": "newChatItems", + "chatItems": [ + {"chatItem": {"meta": {"itemId": 5, "itemStatus": {"type": "sndNew"}}}} + ], + } + history = [ + {"item_id": "5", "text": "hi", "status": "sndRcvd", "unread": False, + "direction": "directSnd", "sent_at": ""}, + ] + daemon = FakeDaemon(send_response=accepted, history=history) + bridge, _, base = start_bridge(daemon=daemon) + try: + result = post(f"{base}/send", {"recipient": "7", "text": "hi"}) + assert result["ok"] is True, result + assert result["status"] == "sndRcvd", result + assert daemon.history_calls, "the bridge must poll for the real status" + finally: + bridge.stop() + + +def test_resolve_prefers_a_healthy_duplicate(): + # Two peers share the display name "pepper"; the stale one has auth errors. + daemon = FakeDaemon( + contacts=[ + {"id": "3", "display_name": "pepper", "local_name": "pepper", + "connected": True, "auth_errors": 2}, + {"id": "4", "display_name": "pepper", "local_name": "pepper_1", + "connected": True, "auth_errors": 0}, + ] + ) + bridge, _, _ = start_bridge(daemon=daemon) + try: + assert bridge.resolve("pepper") == "4", "a stale duplicate must lose" + assert bridge.resolve("pepper_1") == "4" + assert bridge.resolve("3") == "3", "an explicit id always wins" + finally: + bridge.stop() + + +def test_contacts_refreshed_from_daemon(): + # A contact the bridge has never received from must still be visible: the + # daemon knows them, so /send can address them. + daemon = FakeDaemon(contacts=[{"id": "42", "display_name": "Zed"}]) + bridge, _, base = start_bridge(daemon=daemon) + try: + assert get(f"{base}/contacts") == { + "contacts": [{"id": "42", "display_name": "Zed"}] + } + assert daemon.refresh_count >= 1 + finally: + bridge.stop() + + +def test_send_resolves_daemon_only_contact(): + daemon = FakeDaemon(contacts=[{"id": "42", "display_name": "Zed"}]) + bridge, _, base = start_bridge(daemon=daemon) + try: + result = post(f"{base}/send", {"recipient": "Zed", "text": "hello"}) + assert result["ok"] is True and result["contact_id"] == "42", result + assert daemon.sent == [("42", "hello")] + finally: + bridge.stop() + + +def test_refresh_on_connect_primes_contacts(): + daemon = FakeDaemon(contacts=[{"id": "42", "display_name": "Zed"}]) + bridge, _, base = start_bridge(daemon=daemon) + try: + asyncio.run(bridge._refresh_on_connect()) + assert get(f"{base}/contacts")["contacts"] == [ + {"id": "42", "display_name": "Zed"} + ] + finally: + bridge.stop() + + +def test_contacts_failure_keeps_cached_and_stays_available(): + bridge, _, base = start_bridge() + try: + bridge._on_message(inbound("hi", contact_id="4", display_name="Alice")) + bridge.daemon.contacts_error = RuntimeError("not connected") + assert get(f"{base}/contacts") == { + "contacts": [{"id": "4", "display_name": "Alice"}] + } + finally: + bridge.stop() + + +def test_daemon_refresh_does_not_clobber_inbound_name(): + daemon = FakeDaemon(contacts=[{"id": "4", "display_name": ""}]) + bridge, _, base = start_bridge(daemon=daemon) + try: + bridge._on_message(inbound("hi", contact_id="4", display_name="Alice")) + assert get(f"{base}/contacts") == { + "contacts": [{"id": "4", "display_name": "Alice"}] + } + finally: + bridge.stop() + + +def test_send_rejects_unknown_recipient(): + bridge, daemon, base = start_bridge() + try: + with pytest.raises(urllib.error.HTTPError) as exc: + post(f"{base}/send", {"recipient": "ghost", "text": "hello"}) + assert exc.value.code == 400 + assert daemon.sent == [], "a rejected send must not enqueue anything" + finally: + bridge.stop() + + +def test_send_validates_body(): + bridge, daemon, base = start_bridge() + try: + for payload in ({"recipient": "", "text": "hi"}, {"recipient": "4", "text": " "}): + with pytest.raises(urllib.error.HTTPError) as exc: + post(f"{base}/send", payload) + assert exc.value.code == 400 + assert daemon.sent == [] + finally: + bridge.stop() + + +def test_token_is_required_when_configured(): + bridge, _, base = start_bridge(token="sekret") + try: + with pytest.raises(urllib.error.HTTPError) as exc: + get(f"{base}/inbox") + assert exc.value.code == 401 + with pytest.raises(urllib.error.HTTPError) as exc: + post(f"{base}/send", {"recipient": "4", "text": "hi"}) + assert exc.value.code == 401 + assert get(f"{base}/inbox", token="sekret") == {"messages": []} + finally: + bridge.stop() + + +def test_address_returns_daemon_link(): + link = {"short_link": "simplex:/abc", "full_link": "https://x", "created": False} + bridge, _, base = start_bridge(daemon=FakeDaemon(link=link)) + try: + assert get(f"{base}/address") == link + finally: + bridge.stop() + + +def test_address_without_connection_is_unavailable(): + bridge, _, base = start_bridge( + daemon=FakeDaemon(error=RuntimeError("not connected")) + ) + try: + with pytest.raises(urllib.error.HTTPError) as exc: + get(f"{base}/address") + assert exc.value.code == 503 + finally: + bridge.stop() + + +def test_address_lookup_failure_is_reported(): + bridge, _, base = start_bridge(daemon=FakeDaemon(error=TimeoutError("slow"))) + try: + with pytest.raises(urllib.error.HTTPError) as exc: + get(f"{base}/address") + assert exc.value.code == 502 + finally: + bridge.stop() + + +def test_stop_closes_the_daemon(): + bridge, daemon, _ = start_bridge() + bridge.stop() + assert daemon.closed is True + + +# ---- daemon-backed unread / history ---- + +def chat_summary(contact_id="4", display_name="Alice", unread_count=2): + return { + "contact_id": contact_id, + "display_name": display_name, + "unread_count": unread_count, + "min_unread_item_id": "10", + "unread": True, + "messages": [ + { + "item_id": "10", + "text": "hello there", + "status": "rcvNew", + "unread": True, + "direction": "directRcv", + "sent_at": "2026-01-01T00:00:00Z", + } + ], + } + + +def test_unread_returns_daemon_chats(): + daemon = FakeDaemon(chats=[chat_summary()]) + bridge, _, base = start_bridge(daemon=daemon) + try: + assert get(f"{base}/unread") == {"chats": [chat_summary()]} + assert daemon.chat_calls == [(True, 20)], "must ask the daemon for unread" + finally: + bridge.stop() + + +def test_unread_attaches_cached_connection_health(): + daemon = FakeDaemon(chats=[chat_summary(contact_id="4", display_name="pepper")]) + bridge, _, base = start_bridge(daemon=daemon) + try: + bridge.inbox.merge_contacts( + [ + {"id": "4", "display_name": "pepper", "local_name": "pepper_1", + "connected": True, "auth_errors": 0}, + ] + ) + chats = get(f"{base}/unread")["chats"] + assert chats[0]["connected"] is True + assert chats[0]["auth_errors"] == 0 + finally: + bridge.stop() + + +def test_unread_honours_count_query(): + daemon = FakeDaemon(chats=[]) + bridge, _, base = start_bridge(daemon=daemon) + try: + get(f"{base}/unread?count=5") + assert daemon.chat_calls == [(True, 5)] + finally: + bridge.stop() + + +def test_unread_without_connection_is_unavailable(): + bridge, _, base = start_bridge(daemon=FakeDaemon(chats_error=RuntimeError("not connected"))) + try: + with pytest.raises(urllib.error.HTTPError) as exc: + get(f"{base}/unread") + assert exc.value.code == 503 + finally: + bridge.stop() + + +def test_unread_lookup_failure_is_reported(): + bridge, _, base = start_bridge(daemon=FakeDaemon(chats_error=TimeoutError("slow"))) + try: + with pytest.raises(urllib.error.HTTPError) as exc: + get(f"{base}/unread") + assert exc.value.code == 502 + finally: + bridge.stop() + + +def test_history_returns_messages_for_contact(): + messages = [{"item_id": "11", "text": "hi", "status": "rcvRead", "unread": False, + "direction": "directRcv", "sent_at": ""}] + daemon = FakeDaemon(history=messages) + bridge, _, base = start_bridge(daemon=daemon) + try: + assert get(f"{base}/history?contact=7") == {"contact_id": "7", "messages": messages} + assert daemon.history_calls == [("7", 20)] + finally: + bridge.stop() + + +def test_history_requires_a_contact(): + bridge, daemon, base = start_bridge() + try: + with pytest.raises(urllib.error.HTTPError) as exc: + get(f"{base}/history") + assert exc.value.code == 400 + assert daemon.history_calls == [] + finally: + bridge.stop() + + +def test_history_without_connection_is_unavailable(): + bridge, _, base = start_bridge(daemon=FakeDaemon(history_error=RuntimeError("not connected"))) + try: + with pytest.raises(urllib.error.HTTPError) as exc: + get(f"{base}/history?contact=4") + assert exc.value.code == 503 + finally: + bridge.stop() + + +def test_history_lookup_failure_is_reported(): + bridge, _, base = start_bridge(daemon=FakeDaemon(history_error=TimeoutError("slow"))) + try: + with pytest.raises(urllib.error.HTTPError) as exc: + get(f"{base}/history?contact=4") + assert exc.value.code == 502 + finally: + bridge.stop() + + + +def test_known_infos_include_simplex(): + infos = {info.name: info for info in known_infos()} + assert "simplex" in infos + info = infos["simplex"] + assert info.service == "simplex" + assert info.url_config_var == "simplex_bridge_url" + assert info.auth_header == "X-Semif-Token" + assert info.auth_config_var == "simplex_bridge_token" + + +def test_describe_bridges_renders_service_auth_and_endpoints(): + text = describe_bridges() + assert "simplex" in text + assert "service: simplex" in text + assert "simplex_bridge_url" in text + assert "X-Semif-Token" in text + assert "simplex_bridge_token" in text + assert "/inbox/next" in text + assert "/unread" in text + assert "/history" in text + assert "rather than reaching around it" in text + + +def test_read_marks_given_items_only(): + daemon = FakeDaemon() + bridge, _, base = start_bridge(daemon=daemon) + try: + result = post(f"{base}/read", {"contact": "4", "item_ids": ["8", "9"]}) + assert result == { + "ok": True, + "contact_id": "4", + "item_ids": ["8", "9"], + "status": "read", + } + assert daemon.read_calls == [("4", ["8", "9"])], "only the listed items" + finally: + bridge.stop() + + +def test_read_validates_body(): + bridge, daemon, base = start_bridge() + try: + payloads = ( + {"item_ids": ["8"]}, + {"contact": "4"}, + {"contact": "4", "item_ids": []}, + {"contact": " ", "item_ids": ["8"]}, + ) + for payload in payloads: + with pytest.raises(urllib.error.HTTPError) as exc: + post(f"{base}/read", payload) + assert exc.value.code == 400 + assert daemon.read_calls == [] + finally: + bridge.stop() + + +def test_read_without_connection_is_unavailable(): + bridge, _, base = start_bridge( + daemon=FakeDaemon(read_error=RuntimeError("not connected")) + ) + try: + result = post(f"{base}/read", {"contact": "4", "item_ids": ["8"]}) + assert result["ok"] is False + assert result["status"] == "unavailable" + assert "not connected" in result["error"] + finally: + bridge.stop() + + +def test_read_reports_a_rejected_read(): + bridge, _, base = start_bridge( + daemon=FakeDaemon(read_response={"ok": False, "error": "agent error"}) + ) + try: + result = post(f"{base}/read", {"contact": "4", "item_ids": ["8"]}) + assert result["ok"] is False + assert result["status"] == "rejected" + assert result["error"] == "agent error" + finally: + bridge.stop() + + +def test_inbox_carries_item_id_for_consumption(): + bridge, _, base = start_bridge() + try: + bridge._on_message(inbound("hi", contact_id="4", item_id="33")) + popped = get(f"{base}/inbox/next")["message"] + assert popped["item_id"] == "33" + finally: + bridge.stop() + diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..89c927a --- /dev/null +++ b/conftest.py @@ -0,0 +1,17 @@ +"""Make the agent checkout importable when running this pack's tests standalone. + +A pack's bridge test imports `semif_agent` (the shared bridge contract and the +discovery registry). The pack lives inside an agent checkout at `packs//`, +so this adds the checkout root to `sys.path` — running the tests through the +agent repo (`pytest tests/test_packs.py`) already provides it, but +`cd packs/ && pytest` needs this. +""" + +import sys +from pathlib import Path + +for _parent in Path(__file__).resolve().parents: + if (_parent / "semif_agent" / "__init__.py").is_file(): + if str(_parent) not in sys.path: + sys.path.insert(0, str(_parent)) + break