diff --git a/AGENTS.md b/AGENTS.md index a5e7e63..4fe9da4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -120,12 +120,14 @@ gateway/ messenger intake/reply. base.py: GatewayAdapter contract + pending-run ownership, queue drain, authoring questions/repairs routed back to the origin chat). simplex.py: SimplexAdapter — local simplex-chat daemon over its JSON WebSocket API - (lazy `websockets`, allowlist, batching, structured `/_send`). + (lazy `websockets`, allowlist, batching, structured `/_send`, + corrId→Future request path for `/_show_address`/`/_address`). bridge.py: MessagingBridge — a localhost stdlib HTTP API the gateway serves so skills can send/read SimpleX messages without touching the daemon (`/health`, `/contacts`, `/inbox`, - `/inbox/next`, `/send`); owns the read cursor (bounded inbox), - reuses the adapter's outbound queue. Run with `python -m + `/inbox/next`, `/address`, `/send`); owns the read cursor + (bounded inbox), reuses the adapter's outbound queue, and takes + an injected `address_provider` for the connect link. Run with `python -m semif_agent.cli gateway [--dashboard]`; config under `gateway.simplex` in config.json ``` @@ -452,7 +454,9 @@ unit tests (24) + box integration tests (2). at first fire) is written to the runtime store `data/skills/`, so the committed seed never holds secrets, and a generated body with the same name replaces the seed. `calendar.next_event` (Nextcloud CalDAV, recurring events expanded - server-side) is the reference seed; `tests/test_seed_skills.py` keeps it + server-side) is the reference seed; `simplex.next_message` (read via the + messaging bridge) and `simplex.connect_link` (show/create the bot's contact + link) are the messenger seeds; `tests/test_seed_skills.py` keeps them honest. - **Contract provenance.** Each authored body records the SKILL.md revision it was written against. `skill_contract_ref()` (`codegen.py`) returns @@ -675,11 +679,19 @@ unit tests (24) + box integration tests (2). never opens a WebSocket to the daemon. `run_gateway` starts a `MessagingBridge` (`gateway.simplex.bridge`: `enabled` default true, `host`/`port` default `127.0.0.1:5227`, optional `token` checked as `X-Semif-Token`, `max_inbox`) - and wires `service.observer = bridge.record_inbound`. Endpoints: `GET + and wires `service.observer = bridge.record_inbound` plus + `bridge.address_provider = adapter.request_address`. Endpoints: `GET /health`, `GET /contacts`, `GET /inbox` (peek), `GET /inbox/next?contact=` - (pop oldest unread — the bridge owns the cursor), `POST /send` - `{"recipient": "", "text"}` (resolves a numeric id or a known - display name and enqueues on the adapter's existing outbound queue). The + (pop oldest unread — the bridge owns the cursor), `GET /address` (show or + create the bot's user contact link; `{short_link, full_link, created}`, or + 503 when no provider is wired and 502 when the daemon lookup fails), `POST + /send` `{"recipient": "", "text"}` (resolves a numeric id or + a known display name and enqueues on the adapter's existing outbound queue). + The adapter gained a reusable **corrId→Future request path** + (`SimplexAdapter._roundtrip` / `request_address`, with `user_id` config, + default 1): `_consume` resolves a pending future for any frame whose `corrId` + is registered, so `/_show_address` / `/_address` can be called from the bridge + thread via `run_coroutine_threadsafe` without touching the event loop. The top-level `messaging_bridge_url` config is the skill-facing address (the data contract's config search auto-populates it); bootstrap keeps it in sync with the bridge port. `gateway.simplex.inbox.dispatch` (default true) preserves the @@ -688,33 +700,36 @@ unit tests (24) + box integration tests (2). with the ordinary `http` transport, so their hermetic tests are loopback HTTP like any other HTTP body. Recipient resolution is a SemIf sub-decision; no mark-read command exists in the v7 API and contact-list refresh from the - daemon (`/_contacts`) is a follow-up. + daemon (`/_contacts`) is a follow-up (the corrId request path it needs now + exists). - **Tests.** `tests/test_gateway.py` (stdlib, dev box): allowlist/auth, `newChatItems` parsing + echo/group/non-text filtering, structured send - command, batching (real `asyncio`), `GatewayService` routing against a - real `Scheduler` (lazy engine, unreachable LLM), the observer hook, and - pull mode. `tests/test_gateway_bridge.py` exercises the bridge over a real - loopback server (peek/pop, recipient resolution, outbound routing, token/body - validation). `tests/test_seed_skills.py` hermetically tests every - `seeds///` package, including `simplex.next_message`. The live - `websockets` transport against a real daemon is a jarvis integration concern. + command, batching (real `asyncio`), corrId→Future round-trips and address + normalization, `GatewayService` routing against a real `Scheduler` (lazy + engine, unreachable LLM), the observer hook, and pull mode. + `tests/test_gateway_bridge.py` exercises the bridge over a real loopback + server (peek/pop, recipient resolution, outbound routing, token/body + validation, `/address` success/503/502). `tests/test_seed_skills.py` + hermetically tests every `seeds///` package, including + `simplex.next_message` and `simplex.connect_link`. The live `websockets` + transport against a real daemon is a jarvis integration concern. - **Deps.** `websockets` is pinned in `requirements/staging.txt` (staging only); the dev box core stays stdlib-only. ## Gateway messaging backlog (one session per item) -The `MessagingBridge` + `simplex.next_message` seed cover the read path and -outbound sends onto the adapter's queue. Deferred follow-ups: +The `MessagingBridge` + `simplex.next_message` / `simplex.connect_link` seeds +cover the read path, outbound sends onto the adapter's queue, and the bot's +contact-link lookup. Deferred follow-ups: - [ ] **1. Contact-list refresh from the daemon** (`gateway/bridge.py`, `gateway/simplex.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`. Needs a request/response path (corrId → Future) in the - adapter or a bridge-owned short-lived WebSocket client — - `scripts/simplex-address.py` already proves a second client can issue - correlated commands. + `profile.displayName`. The adapter now has the reusable corrId→Future path + this needs (`_roundtrip` / `request_address`, used by `GET /address`), so + reuse it rather than opening a second WebSocket client. - [ ] **2. Message history + true unread** (`gateway/bridge.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/config.example.json b/config.example.json index db0c89b..a3a182b 100644 --- a/config.example.json +++ b/config.example.json @@ -86,13 +86,14 @@ "display_name": "semif" }, "gateway": { - "_comment": "Messenger intake. `python -m semif_agent.cli gateway` connects to the local simplex-chat daemon (see `simplex_chat` above) over its JSON WebSocket API and feeds authorized DM text through the normal gate/score/queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. Requires the optional `websockets` package (lazy-imported; the gateway refuses to start without it). allowed_users entries match either a numeric contactId or a display name; default is deny-all unless allow_all_users is set. home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). text_batch_delay concatenates rapid-fire messages from one contact. Groups/attachments are not supported in this first cut.", + "_comment": "Messenger intake. `python -m semif_agent.cli gateway` connects to the local simplex-chat daemon (see `simplex_chat` above) over its JSON WebSocket API and feeds authorized DM text through the normal gate/score/queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat. Requires the optional `websockets` package (lazy-imported; the gateway refuses to start without it). allowed_users entries match either a numeric contactId or a display name; default is deny-all unless allow_all_users is set. home_channel receives messages whose origin chat is unknown (e.g. a background repair offer). text_batch_delay concatenates rapid-fire messages from one contact. `user_id` is the daemon user whose contact address the connect-link lookup shows/creates (default 1). Groups/attachments are not supported in this first cut.", "simplex": { "enabled": false, "ws_url": "ws://127.0.0.1:5226", "allowed_users": [], "allow_all_users": false, "auto_accept": true, + "user_id": 1, "home_channel": "", "reply_prefix": "", "text_batch_delay": 0.8, @@ -103,7 +104,7 @@ "max_size": 100 }, "bridge": { - "_comment": "Local HTTP API the gateway serves to skills (send/read SimpleX messages). Skills call it over `http` with the top-level `messaging_bridge_url`; keep that URL in sync with host/port. Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. Set enabled=false to run the gateway without the bridge.", + "_comment": "Local HTTP API the gateway serves to skills (send/read SimpleX messages). Skills call it over `http` with the top-level `messaging_bridge_url`; keep that URL in sync with host/port. GET /address shows/creates the bot's contact link (wired to the adapter); /health, /contacts, /inbox, /inbox/next and POST /send are the rest. Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. Set enabled=false to run the gateway without the bridge.", "enabled": true, "host": "127.0.0.1", "port": 5227, diff --git a/seeds/simplex/connect_link/contract.json b/seeds/simplex/connect_link/contract.json new file mode 100644 index 0000000..edd5913 --- /dev/null +++ b/seeds/simplex/connect_link/contract.json @@ -0,0 +1,3 @@ +{ + "messaging_bridge_url": "Base URL of the messenger gateway's local HTTP bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed)." +} diff --git a/seeds/simplex/connect_link/manifest.json b/seeds/simplex/connect_link/manifest.json new file mode 100644 index 0000000..3272c79 --- /dev/null +++ b/seeds/simplex/connect_link/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Show (creating if needed) the SimpleX contact link others use to connect to this agent." +} diff --git a/seeds/simplex/connect_link/skill.py b/seeds/simplex/connect_link/skill.py new file mode 100644 index 0000000..c948f46 --- /dev/null +++ b/seeds/simplex/connect_link/skill.py @@ -0,0 +1,93 @@ +"""Show the SimpleX contact link others use to connect to this agent. + +Real integration: the running messenger gateway serves a local HTTP bridge +(`messaging_bridge_url`). The gateway's own connection to the `simplex-chat` +daemon is the only thing that can read (or create) the bot's *user contact +address*; this body asks the bridge for it and reports the link honestly. It +never opens a WebSocket to the daemon and never invents a link: if the gateway +is not running or has no address, it says so. + +`GET /address` shows the existing link and creates one on first call, returning +`{short_link, full_link, created}`. +""" + +from __future__ import annotations + +import json +import urllib.error +import urllib.request + +from semif_agent.skills import ActionResult, Prediction + +INTEGRATION = { + "service": "simplex", + "transport": "http", + "config_vars": ["messaging_bridge_url"], +} + +TIMEOUT_SECONDS = 30 + + +class BridgeError(Exception): + """The local messaging bridge is unreachable or returned an error.""" + + +def _base(ctx): + url = str(ctx.config.get("messaging_bridge_url", "") or "").strip().rstrip("/") + if not url: + raise BridgeError("messaging_bridge_url is not configured") + return url + + +def _get(ctx, path): + request = urllib.request.Request(_base(ctx) + path) + try: + with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response: + return json.loads(response.read().decode("utf-8")) + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace").strip()[:200] + raise BridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + raise BridgeError(f"GET {path}: {exc}") from exc + + +def predict(ctx, request): + try: + payload = _get(ctx, "/health") + except BridgeError as exc: + return Prediction(text=f"bridge error: {exc}") + if not payload.get("ok"): + return Prediction(text="bridge error: gateway bridge is not healthy") + return Prediction(text="ready: messenger bridge reachable") + + +def act(ctx, request, prediction): + text = prediction.text if prediction else "" + if text.startswith("bridge error:"): + return ActionResult(action_log=text, new_state=request.text) + try: + payload = _get(ctx, "/address") + except BridgeError as exc: + return ActionResult( + action_log=f"simplex.connect_link failed: {exc}", + new_state=request.text, + ) + short = str(payload.get("short_link") or "").strip() + full = str(payload.get("full_link") or "").strip() + if not (short or full): + return ActionResult( + action_log=( + "simplex.connect_link: the gateway returned no SimpleX " + "contact link; the bot has no address yet." + ), + new_state=request.text, + ) + verb = "created" if payload.get("created") else "current" + lines = [f"SimpleX contact link ({verb}): {short or full}"] + if short and full: + lines.append(f"Full link: {full}") + lines.append( + "Share this link with someone so they can add the agent and message it." + ) + report = "\n".join(lines) + return ActionResult(action_log=report, new_state=report) diff --git a/seeds/simplex/connect_link/skill.test.py b/seeds/simplex/connect_link/skill.test.py new file mode 100644 index 0000000..bf6938e --- /dev/null +++ b/seeds/simplex/connect_link/skill.test.py @@ -0,0 +1,156 @@ +"""Hermetic mechanics test for simplex.connect_link. + +Run from this folder: `python skill.test.py`. No external network: a loopback +http.server plays the messenger gateway's bridge. This proves the body health- +checks the bridge, fetches the contact link, reports a freshly created link, and +fails honestly when the bridge has no provider or is unreachable. It does NOT +prove the live integration — only a real run against the gateway and a real +simplex-chat daemon does. +""" + +import json +import sys +import threading +import urllib.parse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from semif_agent.decisions import Request +from semif_agent.skills import ActionContext + +import skill + + +class BridgeHandler(BaseHTTPRequestHandler): + address = {} + address_status = 200 + requests = [] + + def _send(self, payload, status=200): + 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 do_GET(self): + self.requests.append(self.path) + url = urllib.parse.urlparse(self.path) + if url.path == "/health": + self._send({"ok": True, "platform": "simplex"}) + elif url.path == "/address": + self._send(self.address, self.address_status) + else: + self._send({"error": "not found"}, 404) + + def log_message(self, *args): + pass + + +def start_server(address=None, address_status=200): + handler = type( + "Handler", + (BridgeHandler,), + {"address": address or {}, "address_status": address_status, "requests": []}, + ) + server = ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, handler, f"http://127.0.0.1:{server.server_address[1]}" + + +def config(url): + return {"messaging_bridge_url": url} + + +def test_reports_existing_link(): + server, handler, url = start_server( + {"short_link": "simplex:/contact#abc", "full_link": "https://smp/short", "created": False} + ) + try: + ctx = ActionContext(engine=None, config=config(url)) + request = Request("give me your simplex link") + prediction = skill.predict(ctx, request) + action = skill.act(ctx, request, prediction) + assert "simplex:/contact#abc" in action.action_log, action.action_log + assert "https://smp/short" in action.action_log, action.action_log + assert "current" in action.action_log, action.action_log + assert handler.requests == ["/health", "/address"], handler.requests + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_reports_freshly_created_link(): + server, handler, url = start_server( + {"short_link": "simplex:/contact#new", "full_link": "", "created": True} + ) + try: + ctx = ActionContext(engine=None, config=config(url)) + request = Request("create a simplex invitation link") + prediction = skill.predict(ctx, request) + action = skill.act(ctx, request, prediction) + assert "simplex:/contact#new" in action.action_log, action.action_log + assert "created" in action.action_log, action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_no_provider_is_reported_honestly(): + server, handler, url = start_server({"error": "address lookup is not available"}, 503) + try: + ctx = ActionContext(engine=None, config=config(url)) + request = Request("give me your simplex link") + prediction = skill.predict(ctx, request) + action = skill.act(ctx, request, prediction) + assert "503" in action.action_log, action.action_log + assert action.new_state == request.text, "a failed lookup must not fake a result" + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_empty_link_is_reported_honestly(): + server, handler, url = start_server({"short_link": "", "full_link": "", "created": False}) + try: + ctx = ActionContext(engine=None, config=config(url)) + request = Request("give me your simplex link") + prediction = skill.predict(ctx, request) + action = skill.act(ctx, request, prediction) + assert "no SimpleX" in action.action_log, action.action_log + assert action.new_state == request.text + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_unreachable_bridge_fails_honestly(): + ctx = ActionContext(engine=None, config=config("http://127.0.0.1:1")) + request = Request("give me your simplex link") + prediction = skill.predict(ctx, request) + assert prediction.text.startswith("bridge error:"), prediction.text + action = skill.act(ctx, request, prediction) + assert action.action_log.startswith("bridge error:"), action.action_log + assert action.new_state == request.text + print(action.action_log) + + +def main(): + test_reports_existing_link() + test_reports_freshly_created_link() + test_no_provider_is_reported_honestly() + test_empty_link_is_reported_honestly() + test_unreachable_bridge_fails_honestly() + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1) diff --git a/semif_agent/cli.py b/semif_agent/cli.py index 9625fd4..66cc648 100644 --- a/semif_agent/cli.py +++ b/semif_agent/cli.py @@ -323,7 +323,11 @@ def run_gateway( bridge_cfg = cfg.get("bridge", {}) or {} bridge = None if bridge_cfg.get("enabled", True): - bridge = MessagingBridge(service.outbound, config=bridge_cfg) + bridge = MessagingBridge( + service.outbound, + config=bridge_cfg, + address_provider=adapter.request_address, + ) service.observer = bridge.record_inbound port = bridge.start() print( diff --git a/semif_agent/gateway/bridge.py b/semif_agent/gateway/bridge.py index c9f520d..a7770c0 100644 --- a/semif_agent/gateway/bridge.py +++ b/semif_agent/gateway/bridge.py @@ -8,6 +8,8 @@ the running gateway serves this small stdlib HTTP API on localhost: GET /inbox peek buffered inbound messages GET /inbox/next?contact= pop the oldest unread message (optionally for one contact) -> {"message": {...}|null} + GET /address the bot's user contact link, creating it if + needed -> {"short_link", "full_link", "created"} POST /send {"recipient": "", "text": "..."} The bridge owns the read cursor (a bounded FIFO of authorized inbound DMs), so @@ -91,6 +93,11 @@ class MessagingBridge: `gateway..bridge` block: `host` (default 127.0.0.1), `port` (default 5227, `0` picks an ephemeral port), `token` (optional shared secret checked against the `X-Semif-Token` header), `max_inbox`. + + `address_provider` is an optional zero-arg callable returning + `{short_link, full_link, created}` — the gateway wires it to the adapter's + contact-address lookup. When absent, `GET /address` answers 503 so a skill + reports that the link is unavailable rather than inventing one. """ name = "simplex" @@ -99,6 +106,7 @@ class MessagingBridge: self, outbound: "queue.Queue[OutboundMessage | None]", config: dict | None = None, + address_provider=None, ): cfg = config or {} self.host = str(cfg.get("host", "127.0.0.1")) @@ -106,6 +114,7 @@ class MessagingBridge: self.token = str(cfg.get("token", "") or "") self.inbox = MessagingInbox(int(cfg.get("max_inbox", 100))) self.outbound = outbound + self.address_provider = address_provider self._server: ThreadingHTTPServer | None = None self._thread: threading.Thread | None = None @@ -207,6 +216,20 @@ class _BridgeHandler(BaseHTTPRequestHandler): elif url.path == "/inbox/next": contact = (parse_qs(url.query).get("contact") or [None])[0] self._json(200, {"message": bridge.inbox.pop(contact)}) + elif url.path == "/address": + provider = bridge.address_provider + if provider is None: + self._json(503, {"error": "address lookup is not available"}) + return + try: + link = provider() + except Exception as exc: + self._json(502, {"error": f"address lookup failed: {exc}"[:300]}) + return + if not isinstance(link, dict): + self._json(502, {"error": "address lookup returned no link"}) + return + self._json(200, link) else: self._json(404, {"error": "not found"}) @@ -246,7 +269,8 @@ class _BridgeHandler(BaseHTTPRequestHandler): def start_bridge( outbound: "queue.Queue[OutboundMessage | None]", config: dict | None = None, + address_provider=None, ) -> tuple[MessagingBridge, int]: - bridge = MessagingBridge(outbound, config=config) + bridge = MessagingBridge(outbound, config=config, address_provider=address_provider) port = bridge.start() return bridge, port diff --git a/semif_agent/gateway/simplex.py b/semif_agent/gateway/simplex.py index 6b15130..0da8f81 100644 --- a/semif_agent/gateway/simplex.py +++ b/semif_agent/gateway/simplex.py @@ -13,6 +13,7 @@ dependency; `check_requirements()` gates the gateway off with an install hint. from __future__ import annotations import asyncio +import concurrent.futures import json import queue import random @@ -32,12 +33,16 @@ class SimplexAdapter(GatewayAdapter): self.allow_all_users = bool(cfg.get("allow_all_users", False)) self.auto_accept = bool(cfg.get("auto_accept", True)) self.batch_delay = float(cfg.get("text_batch_delay", 0.8)) + self.user_id = int(cfg.get("user_id", 1)) reconnect = cfg.get("reconnect", {}) or {} self.reconnect_initial = float(reconnect.get("initial", 1.0)) self.reconnect_max = float(reconnect.get("max", 60.0)) self.reconnect_jitter = float(reconnect.get("jitter", 0.2)) self.trace = trace self._corr = 0 + self._pending: dict[str, asyncio.Future] = {} + self._loop: asyncio.AbstractEventLoop | None = None + self._ws = None self._buffers: dict[str, str] = {} self._buffered: dict[str, InboundMessage] = {} self._flush_tasks: dict[str, asyncio.Task] = {} @@ -81,10 +86,12 @@ class SimplexAdapter(GatewayAdapter): async def _serve(self, on_inbound, outbound: "queue.Queue") -> None: import websockets + self._loop = asyncio.get_running_loop() backoff = self.reconnect_initial while not self._stop.is_set(): try: async with websockets.connect(self.ws_url, max_size=None) as ws: + self._ws = ws backoff = self.reconnect_initial self._event("gateway_connected", url=self.ws_url) sender = asyncio.create_task(self._outbound_loop(ws, outbound)) @@ -95,6 +102,9 @@ class SimplexAdapter(GatewayAdapter): sender.cancel() except Exception as exc: # reconnect on any transport failure self._event("gateway_error", message=str(exc)[:300]) + finally: + self._ws = None + self._fail_pending("simplex gateway disconnected") delay = min(backoff, self.reconnect_max) delay *= 1 + random.random() * self.reconnect_jitter try: @@ -133,6 +143,67 @@ class SimplexAdapter(GatewayAdapter): composed = [{"msgContent": {"type": "text", "text": text}}] return f"/_send @{chat_id} json {json.dumps(composed)}" + # ---- request/response + address ---- + + async def _roundtrip(self, command: str, timeout: float) -> dict: + """Send a command and await its correlated `resp` from the event loop.""" + ws = self._ws + if ws is None or self._loop is None: + raise RuntimeError("simplex gateway is not connected") + self._corr += 1 + corr = f"req-{self._corr}" + future = self._loop.create_future() + self._pending[corr] = future + await ws.send(json.dumps({"corrId": corr, "cmd": command})) + try: + return await asyncio.wait_for(future, timeout) + finally: + self._pending.pop(corr, None) + + def _fail_pending(self, reason: str) -> None: + pending, self._pending = self._pending, {} + for future in pending.values(): + if not future.done(): + future.set_exception(RuntimeError(reason)) + + async def address(self, timeout: float = 20.0) -> dict: + """Show the bot's user contact address, creating it on first call. + + Mirrors `scripts/simplex-address.py`: `/_show_address ` returns an + existing link; when there is none, `/_address ` creates one. + Returns `{short_link, full_link, created}`. + """ + resp = await self._roundtrip(f"/_show_address {self.user_id}", timeout) + link: dict = {} + created = False + if resp.get("type") == "userContactLink": + link = resp.get("contactLink") or {} + if not (link.get("connShortLink") or link.get("connFullLink")): + resp = await self._roundtrip(f"/_address {self.user_id}", timeout) + link = resp.get("connLinkContact") or {} + created = True + return { + "short_link": link.get("connShortLink") or "", + "full_link": link.get("connFullLink") or "", + "created": created, + } + + def request_address(self, timeout: float = 20.0) -> dict: + """Thread-safe address lookup for callers off the event loop (the bridge). + + Raises `RuntimeError` when no live connection exists and `TimeoutError` + when the daemon does not answer in time — never a fabricated link. + """ + 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.address(timeout=timeout), loop) + try: + return future.result(timeout=timeout + 5.0) + except concurrent.futures.TimeoutError as exc: + future.cancel() + raise TimeoutError("simplex address request timed out") from exc + # ---- inbound ---- async def _consume(self, raw: Any, on_inbound, ws) -> None: @@ -140,6 +211,15 @@ class SimplexAdapter(GatewayAdapter): data = json.loads(raw) except (TypeError, ValueError): return + corr_id = data.get("corrId") + if corr_id is not None: + # A correlated command response (round-trip): resolve the waiting + # requester. Fire-and-forget commands (`_send`, `_accept`) never + # register a future, so their responses are dropped here as before. + future = self._pending.pop(corr_id, None) + if future is not None and not future.done(): + future.set_result(data.get("resp") or {}) + return resp = data.get("resp") or {} kind = resp.get("type") if kind == "receivedContactRequest": diff --git a/tests/test_gateway.py b/tests/test_gateway.py index a3fc766..426d112 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -361,3 +361,93 @@ def test_service_pull_mode_buffers_without_dispatch(tmp_path): assert drain_outbound(service) == [], "pull mode must not reply or dispatch" assert scheduler.current is None assert scheduler.pending is None + + +# ---- adapter: correlated request/response + contact address ---- + + +class FakeWS: + """A fake simplex-chat socket that answers correlated commands.""" + + def __init__(self, adapter, responses): + self.adapter = adapter + self.responses = list(responses) + self.sent = [] + + async def send(self, raw): + message = json.loads(raw) + self.sent.append(message) + response = self.responses.pop(0) + await self.adapter._consume( + json.dumps({"corrId": message["corrId"], "resp": response}), None, self + ) + + +def test_correlated_response_resolves_pending_future(): + adapter = SimplexAdapter({}) + + async def scenario(): + adapter._loop = asyncio.get_running_loop() + adapter._ws = FakeWS(adapter, []) + future = adapter._loop.create_future() + adapter._pending["req-9"] = future + await adapter._consume( + json.dumps({"corrId": "req-9", "resp": {"type": "ok", "value": 1}}), None, adapter._ws + ) + assert "req-9" not in adapter._pending, "a resolved request must be dropped" + return future.result() + + assert asyncio.run(scenario()) == {"type": "ok", "value": 1} + + +def test_address_returns_existing_link(): + adapter = SimplexAdapter({"user_id": 3}) + + async def scenario(): + adapter._loop = asyncio.get_running_loop() + ws = FakeWS( + adapter, + [ + { + "type": "userContactLink", + "contactLink": {"connShortLink": "simplex:/a", "connFullLink": "https://a"}, + } + ], + ) + adapter._ws = ws + return await adapter.address(timeout=5), ws + + result, ws = asyncio.run(scenario()) + assert result == {"short_link": "simplex:/a", "full_link": "https://a", "created": False} + assert [m["cmd"] for m in ws.sent] == ["/_show_address 3"] + + +def test_address_creates_when_missing(): + adapter = SimplexAdapter({"user_id": 1}) + + async def scenario(): + adapter._loop = asyncio.get_running_loop() + ws = FakeWS( + adapter, + [ + {"type": "userContactLink", "contactLink": None}, + { + "type": "userContactLinkCreated", + "connLinkContact": {"connShortLink": "simplex:/new", "connFullLink": ""}, + }, + ], + ) + adapter._ws = ws + return await adapter.address(timeout=5), ws + + result, ws = asyncio.run(scenario()) + assert result == {"short_link": "simplex:/new", "full_link": "", "created": True} + assert [m["cmd"] for m in ws.sent] == ["/_show_address 1", "/_address 1"] + + +def test_request_address_without_connection_raises(): + import pytest + + adapter = SimplexAdapter({}) + with pytest.raises(RuntimeError): + adapter.request_address(timeout=1) diff --git a/tests/test_gateway_bridge.py b/tests/test_gateway_bridge.py index 75e7484..6e6784f 100644 --- a/tests/test_gateway_bridge.py +++ b/tests/test_gateway_bridge.py @@ -17,9 +17,11 @@ from semif_agent.gateway.base import InboundMessage, OutboundMessage from semif_agent.gateway.bridge import MessagingBridge -def start_bridge(**config): +def start_bridge(address_provider=None, **config): outbound = queue.Queue() - bridge = MessagingBridge(outbound, config=config) + bridge = MessagingBridge( + outbound, config=config, address_provider=address_provider + ) port = bridge.start() return bridge, outbound, f"http://127.0.0.1:{port}" @@ -160,3 +162,35 @@ def test_token_is_required_when_configured(): assert get(f"{base}/inbox", token="sekret") == {"messages": []} finally: bridge.stop() + + +def test_address_uses_provider(): + link = {"short_link": "simplex:/abc", "full_link": "https://x", "created": False} + bridge, _, base = start_bridge(address_provider=lambda: link) + try: + assert get(f"{base}/address") == link + finally: + bridge.stop() + + +def test_address_without_provider_is_unavailable(): + bridge, _, base = start_bridge() + try: + with pytest.raises(urllib.error.HTTPError) as exc: + get(f"{base}/address") + assert exc.value.code == 503 + finally: + bridge.stop() + + +def test_address_provider_failure_is_reported(): + def boom(): + raise RuntimeError("not connected") + + bridge, _, base = start_bridge(address_provider=boom) + try: + with pytest.raises(urllib.error.HTTPError) as exc: + get(f"{base}/address") + assert exc.value.code == 502 + finally: + bridge.stop() diff --git a/tests/test_seed_skills.py b/tests/test_seed_skills.py index 605b70c..59f7ac8 100644 --- a/tests/test_seed_skills.py +++ b/tests/test_seed_skills.py @@ -27,6 +27,7 @@ def test_expected_seeds_exist(): ids = {seed_id(seed) for seed in SEED_DIRS} assert "calendar.next_event" in ids assert "simplex.next_message" in ids + assert "simplex.connect_link" in ids @pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])