diff --git a/AGENTS.md b/AGENTS.md index cf948bb..01f8ffe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -160,10 +160,12 @@ gateway/ messenger COMMAND intake/reply — and nothing else. base.py: bridges/ standalone third-party API bridges (SimpleX first). base.py: BridgeInfo + BridgeService (shared localhost JSON HTTP layer, `X-Semif-Token` guard). inbox.py: MessagingInbox (bounded FIFO + - contacts, bridge-owned read cursor). simplex.py: SimplexBridge — + contacts learned from inbound DMs and the daemon contact list, + bridge-owned read cursor). simplex.py: SimplexBridge — owns its OWN simplex-chat daemon/profile (separate from the - gateway's), buffers every inbound DM, serves invite-link/read/ - send. registry.py: CATALOG, describe_bridges() (catalog injected + gateway's), buffers every inbound DM, refreshes the daemon + contact list on (re)connect + on demand, serves invite-link/ + read/send. registry.py: CATALOG, describe_bridges() (catalog injected into the codegen prompts), run_bridges(). Run with `python -m semif_agent.cli bridge [--name NAME]`; config under `bridges`. simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway @@ -833,11 +835,15 @@ CLI, unit tests (24) + box integration tests (2). localhost-bound, optional shared-secret `X-Semif-Token` header. `SimplexBridge` buffers **every** inbound DM (no allowlist — the user wants to see who reached the bot through its invite link) in a bounded `MessagingInbox` that owns the - read cursor, and serves `GET /health`, `GET /contacts`, `GET /inbox` (peek), - `GET /inbox/next?contact=` (pop oldest), `GET /address` (show/create the - forwarding bot's contact link; 503 when the daemon is not connected, 502 when - the lookup fails), and `POST /send` `{"recipient","text"}` (resolves a numeric - id or a known display name and enqueues on the bridge's own daemon). + read cursor, and serves `GET /health`, `GET /contacts` (the daemon's contact + list, refreshed on (re)connect and on demand — best-effort, falling back to + the cached/inbound-learned set when the daemon is unavailable), `GET /inbox` + (peek), `GET /inbox/next?contact=` (pop oldest), `GET /address` + (show/create the forwarding bot's contact link; 503 when the daemon is not + connected, 502 when the lookup fails), and `POST /send` + `{"recipient","text"}` (resolves a numeric id or a known display name — + refreshing the daemon contact list once on a miss — and enqueues on the + bridge's own daemon). - **Skill-facing config.** The top-level `simplex_bridge_url` is the address a body calls (the data-contract config search auto-populates it); bootstrap keeps it in sync with the bridge port. Skills reach a bridge with the ordinary `http` @@ -849,13 +855,15 @@ CLI, unit tests (24) + box integration tests (2). The bridge read path (`simplex.next_message`) and contact-link lookup (`simplex.connect_link`) are covered. Deferred follow-ups: -- [ ] **1. Contact-list refresh from the daemon** (`bridges/simplex.py`, - `simplex_ws.py`). The bridge learns contacts only from observed inbound - senders, so `/send` cannot address a contact it has never received from. - Query `/_contacts ` (active user from `/user` → - `activeUser.userId`) at startup and on demand, caching `contactId` + - `profile.displayName`. Reuse the daemon's corrId→Future path - (`SimplexDaemon._roundtrip`) rather than opening a second WebSocket client. +- [x] **1. Contact-list refresh from the daemon** (`bridges/simplex.py`, + `simplex_ws.py`). Shipped: `SimplexDaemon.contacts()` / + `request_contacts()` query `/_contacts ` (active user from `/user` → + `activeUser.userId`, cached, falling back to the configured `user_id`) over + the existing corrId→Future path; `SimplexBridge` merges the result into the + inbox on (re)connect via an `on_connected` hook and on demand (`GET + /contacts`, and a send-resolution miss), so `/send` can address a contact it + has never received from. Best-effort: a disconnected daemon keeps the cached + set. - [ ] **2. Message history + true unread** (`bridges/simplex.py`). The in-memory inbox is a receive buffer, not the daemon's read state. Use `/_get chats count= ` with a `ChatListQuery` unread diff --git a/semif_agent/bridges/inbox.py b/semif_agent/bridges/inbox.py index 77e8d3c..34f2ab6 100644 --- a/semif_agent/bridges/inbox.py +++ b/semif_agent/bridges/inbox.py @@ -55,6 +55,23 @@ class MessagingInbox: return entry return None + def merge_contacts(self, contacts: list[dict]) -> None: + """Upsert contacts learned from the daemon (not from a message). + + A non-empty incoming name overwrites a cached one; an empty name never + clobbers a name already learned from an inbound message. + """ + with self._lock: + for contact in contacts: + contact_id = str(contact.get("id") or "") + if not contact_id: + continue + name = contact.get("display_name") or "" + if name: + self._contacts[contact_id] = name + else: + self._contacts.setdefault(contact_id, "") + def contacts(self) -> list[dict]: with self._lock: return [ diff --git a/semif_agent/bridges/simplex.py b/semif_agent/bridges/simplex.py index 8ee0d08..92605f5 100644 --- a/semif_agent/bridges/simplex.py +++ b/semif_agent/bridges/simplex.py @@ -35,7 +35,8 @@ class SimplexBridge(BridgeService): "GET /health -> 200 {\"ok\": true, \"platform\": \"simplex\"} — the " "bridge is up", "GET /contacts -> 200 {\"contacts\": [{\"id\", \"display_name\"}]} — " - "contacts learned from inbound messages", + "contacts known to the daemon (learned from inbound messages and " + "refreshed from the daemon's contact list)", "GET /inbox -> 200 {\"messages\": [{\"id\", \"contact_id\", " "\"display_name\", \"text\", \"received_at\"}]} — peek buffered " "inbound messages; does not consume", @@ -88,6 +89,7 @@ class SimplexBridge(BridgeService): 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, ) @@ -115,13 +117,23 @@ class SimplexBridge(BridgeService): 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.inbox.contacts()} + return 200, {"contacts": self.refresh_contacts()} if path == "/inbox": return 200, {"messages": self.inbox.peek()} if path == "/inbox/next": @@ -148,6 +160,22 @@ class SimplexBridge(BridgeService): # ---- actions ---- + 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 _address(self) -> tuple[int, dict]: try: link = self.daemon.request_address() @@ -168,13 +196,25 @@ class SimplexBridge(BridgeService): return contact_id def resolve(self, recipient: str) -> str | None: - """A numeric id (with or without `@`) or a known display name.""" + """A numeric id (with or without `@`) or a known display name. + + On a display-name 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: for contact in self.inbox.contacts(): if contact["display_name"] == recipient or contact["id"] == recipient: return contact["id"] diff --git a/semif_agent/simplex_ws.py b/semif_agent/simplex_ws.py index d58c44d..c394f4d 100644 --- a/semif_agent/simplex_ws.py +++ b/semif_agent/simplex_ws.py @@ -23,12 +23,36 @@ import json import queue import random import threading -from typing import Any, Callable +from typing import Any, Awaitable, Callable #: One received direct text message, normalized across the v7 wire shapes. InboundDict = dict[str, Any] #: Callback invoked in the event loop for each received direct text message. MessageHandler = Callable[[InboundDict], None] +#: Async callback invoked in the event loop once a connection is established. +ConnectedHandler = Callable[[], Awaitable[None]] + + +def contact_entry(contact: dict) -> dict | None: + """Normalize one daemon `Contact` into `{"id", "display_name"}`, or None. + + The single source of truth for contact identity across the wire: the same + shape appears in `newChatItems` items and in the `/_contacts` list. v7's + `Contact.displayName` is null and the real peer name lives in + `profile.displayName`; `localDisplayName` is auto-suffixed on collisions + (e.g. a second contact becomes `pepper_1`). + """ + contact_id = str(contact.get("contactId") or contact.get("chatId") or "") + if not contact_id: + return None + profile = contact.get("profile") or {} + display_name = ( + profile.get("displayName") + or contact.get("displayName") + or contact.get("localDisplayName") + or "" + ) + return {"id": contact_id, "display_name": display_name} def contact_link(resp: dict) -> dict: @@ -84,23 +108,16 @@ def parse_direct_text_item(item: dict) -> InboundDict | None: text = str(msg_content.get("text", "")).strip() if not text: return None - contact = chat_info.get("contact") or {} - contact_id = str(contact.get("contactId") or chat_info.get("chatId") or "") - if not contact_id: + contact = dict(chat_info.get("contact") or {}) + if not contact.get("contactId") and not contact.get("chatId"): + contact["chatId"] = chat_info.get("chatId") + entry = contact_entry(contact) + if entry is None: return None - profile = contact.get("profile") or {} - # v7's Contact has `displayName: null`; the real peer name lives in - # `profile.displayName`, and `localDisplayName` is auto-suffixed on - # collisions (e.g. a second contact becomes `pepper_1`). - display_name = ( - profile.get("displayName") - or contact.get("displayName") - or contact.get("localDisplayName") - ) return { "text": text, - "contact_id": contact_id, - "display_name": display_name, + "contact_id": entry["id"], + "display_name": entry["display_name"], "raw": item, } @@ -149,6 +166,7 @@ class SimplexDaemon: user_id: int = 1, auto_accept: bool = True, reconnect: dict | None = None, + on_connected: ConnectedHandler | None = None, trace=None, name: str = "simplex", ): @@ -159,6 +177,7 @@ class SimplexDaemon: self.reconnect_initial = float(settings.get("initial", 1.0)) self.reconnect_max = float(settings.get("max", 60.0)) self.reconnect_jitter = float(settings.get("jitter", 0.2)) + self.on_connected = on_connected self.trace = trace self.name = name self._corr = 0 @@ -168,6 +187,7 @@ class SimplexDaemon: self._outbound: "queue.Queue[tuple[str, str] | None]" = queue.Queue() self._stop = threading.Event() self._on_message: MessageHandler | None = None + self._active_user_id: int | None = None # ---- requirements ---- @@ -208,6 +228,7 @@ class SimplexDaemon: self._ws = ws backoff = self.reconnect_initial self._event("gateway_connected", url=self.ws_url) + await self._notify_connected() sender = asyncio.create_task(self._outbound_loop(ws)) try: async for raw in ws: @@ -231,6 +252,20 @@ class SimplexDaemon: while not self._stop.is_set(): await asyncio.sleep(0.2) + async def _notify_connected(self) -> None: + """Run the optional `on_connected` hook; a hook failure must not drop + the socket (it is traced and the connection stays up).""" + if self.on_connected is None: + return + try: + await self.on_connected() + except Exception as exc: + self._event( + "gateway_error", + phase="on_connected", + message=str(exc)[:300], + ) + async def _outbound_loop(self, ws) -> None: loop = asyncio.get_running_loop() while True: @@ -313,6 +348,54 @@ class SimplexDaemon: future.cancel() raise TimeoutError("simplex address request timed out") from exc + # ---- contacts ---- + + async def active_user(self, timeout: float = 20.0) -> int: + """Resolve the active user id via `/user`, caching it after first use. + + Falls back to the configured `user_id` when the daemon does not report + one, so a profile with a single user keeps working even on a shape drift. + """ + if self._active_user_id is not None: + return self._active_user_id + resp = await self._roundtrip("/user", timeout) + user = resp.get("user") or {} + user_id = user.get("userId") + self._active_user_id = int(user_id) if user_id is not None else self.user_id + return self._active_user_id + + async def contacts(self, timeout: float = 20.0) -> list[dict]: + """The daemon's contact list as `[{"id", "display_name"}]`. + + `/_contacts ` returns `contactsList` with a `Contact` array. + A `chatCmdError` or malformed reply yields an empty list rather than a + fabricated contact. + """ + user_id = await self.active_user(timeout) + resp = await self._roundtrip(f"/_contacts {user_id}", timeout) + contacts: list[dict] = [] + for contact in resp.get("contacts") or []: + entry = contact_entry(contact) + if entry is not None: + contacts.append(entry) + return contacts + + def request_contacts(self, timeout: float = 20.0) -> list[dict]: + """Thread-safe contact-list lookup for callers off the event loop. + + Raises `RuntimeError` when no live connection exists and `TimeoutError` + when the daemon does not answer in time — never a fabricated list. + """ + loop = self._loop + if loop is None or not loop.is_running(): + raise RuntimeError("simplex gateway is not connected") + future = asyncio.run_coroutine_threadsafe(self.contacts(timeout=timeout), loop) + try: + return future.result(timeout=timeout + 5.0) + except concurrent.futures.TimeoutError as exc: + future.cancel() + raise TimeoutError("simplex contacts request timed out") from exc + # ---- inbound ---- async def _consume(self, raw: Any) -> None: diff --git a/tests/test_bridges.py b/tests/test_bridges.py index d6aa873..78c4185 100644 --- a/tests/test_bridges.py +++ b/tests/test_bridges.py @@ -7,6 +7,7 @@ mechanics a skill depends on: peek/pop of buffered inbound messages, recipient resolution, outbound routing, address lookup, and token/body validation. """ +import asyncio import json import urllib.error import urllib.request @@ -20,9 +21,12 @@ from semif_agent.bridges.simplex import SimplexBridge class FakeDaemon: """Stands in for the bridge's own simplex-chat connection.""" - def __init__(self, link=None, error=None): + def __init__(self, link=None, error=None, contacts=None, contacts_error=None): self.link = link self.error = error + self.contacts_list = contacts or [] + self.contacts_error = contacts_error + self.refresh_count = 0 self.sent = [] self.closed = False self.on_message = None @@ -42,6 +46,15 @@ class FakeDaemon: 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 close(self): self.closed = True @@ -161,6 +174,67 @@ def test_send_resolves_known_display_name(): 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": True, "contact_id": "42"} + 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: diff --git a/tests/test_simplex_ws.py b/tests/test_simplex_ws.py index 1c79707..9b9cd2e 100644 --- a/tests/test_simplex_ws.py +++ b/tests/test_simplex_ws.py @@ -14,6 +14,7 @@ import pytest from semif_agent.simplex_ws import ( SimplexDaemon, accept_command, + contact_entry, contact_link, parse_direct_text_item, send_text_command, @@ -135,6 +136,21 @@ def test_contact_link_reads_both_shapes(): assert contact_link({}) == {} +def test_contact_entry_reads_v7_shape(): + assert contact_entry( + {"contactId": 4, "displayName": None, "profile": {"displayName": "Alice"}} + ) == {"id": "4", "display_name": "Alice"} + assert contact_entry({"contactId": 7, "localDisplayName": "bob_1"}) == { + "id": "7", + "display_name": "bob_1", + } + assert contact_entry({"chatId": 9, "profile": {"displayName": "Carol"}}) == { + "id": "9", + "display_name": "Carol", + } + assert contact_entry({"profile": {"displayName": "no id"}}) is None + + # ---- daemon: accept + round-trips ---- class FakeWS: @@ -269,3 +285,118 @@ def test_request_address_without_connection_raises(): daemon = SimplexDaemon("ws://x") with pytest.raises(RuntimeError): daemon.request_address(timeout=1) + + +# ---- daemon: contacts + on_connected hook ---- + +def test_contacts_parses_contacts_list(): + daemon = SimplexDaemon("ws://x", user_id=1) + + async def scenario(): + daemon._loop = asyncio.get_running_loop() + ws = FakeWS( + daemon, + [ + {"type": "activeUser", "user": {"userId": 3}}, + { + "type": "contactsList", + "contacts": [ + {"contactId": 4, "profile": {"displayName": "Alice"}}, + {"contactId": 7, "localDisplayName": "bob_1"}, + {"profile": {"displayName": "no id"}}, + ], + }, + ], + ) + daemon._ws = ws + return await daemon.contacts(timeout=5), ws + + result, ws = asyncio.run(scenario()) + assert result == [ + {"id": "4", "display_name": "Alice"}, + {"id": "7", "display_name": "bob_1"}, + ] + assert [m["cmd"] for m in ws.sent] == ["/user", "/_contacts 3"] + + +def test_contacts_falls_back_to_configured_user_id(): + daemon = SimplexDaemon("ws://x", user_id=1) + + async def scenario(): + daemon._loop = asyncio.get_running_loop() + ws = FakeWS( + daemon, + [ + {"type": "chatCmdError", "chatError": {"type": "error"}}, + {"type": "contactsList", "contacts": []}, + ], + ) + daemon._ws = ws + return await daemon.contacts(timeout=5), ws + + result, ws = asyncio.run(scenario()) + assert result == [] + assert [m["cmd"] for m in ws.sent] == ["/user", "/_contacts 1"] + + +def test_active_user_is_cached_across_calls(): + daemon = SimplexDaemon("ws://x", user_id=1) + + async def scenario(): + daemon._loop = asyncio.get_running_loop() + ws = FakeWS( + daemon, + [ + {"type": "activeUser", "user": {"userId": 3}}, + {"type": "contactsList", "contacts": []}, + {"type": "contactsList", "contacts": []}, + ], + ) + daemon._ws = ws + await daemon.contacts(timeout=5) + await daemon.contacts(timeout=5) + return ws + + ws = asyncio.run(scenario()) + assert [m["cmd"] for m in ws.sent] == ["/user", "/_contacts 3", "/_contacts 3"] + + +def test_contacts_returns_empty_on_error_response(): + daemon = SimplexDaemon("ws://x", user_id=1) + + async def scenario(): + daemon._loop = asyncio.get_running_loop() + ws = FakeWS( + daemon, + [ + {"type": "activeUser", "user": {"userId": 1}}, + {"type": "chatCmdError", "chatError": {"type": "error"}}, + ], + ) + daemon._ws = ws + return await daemon.contacts(timeout=5) + + assert asyncio.run(scenario()) == [] + + +def test_request_contacts_without_connection_raises(): + daemon = SimplexDaemon("ws://x") + with pytest.raises(RuntimeError): + daemon.request_contacts(timeout=1) + + +def test_on_connected_hook_runs_and_failures_are_swallowed(): + calls = [] + + async def hook(): + calls.append(1) + + asyncio.run(SimplexDaemon("ws://x", on_connected=hook)._notify_connected()) + assert calls == [1] + + async def bad(): + raise ValueError("nope") + + # A hook failure must not propagate (it would tear down the connection). + asyncio.run(SimplexDaemon("ws://x", on_connected=bad)._notify_connected()) + asyncio.run(SimplexDaemon("ws://x")._notify_connected())