bridges: standalone third-party API bridges; isolate the command gateway

Split messaging UX (invite links, read, send) out of the command gateway into a
new `semif_agent.bridges` layer. Each bridge is its own process (`cli bridge`)
against its own service daemon/profile; the SimpleX bridge owns a second
simplex-chat daemon and buffers every inbound DM, so a message sent to the
connect-link address shows up in `simplex.next_message`.

- new: bridges/{base,inbox,registry,simplex}.py + neutral semif_agent/simplex_ws.py
- gateway: delete bridge.py; drop address/observer/pull-mode from the command path
- codegen: inject the bridge catalog (describe_bridges) into body + elicitation prompts
- seeds: repoint simplex.next_message/connect_link to top-level `simplex_bridge_url`
- config/bootstrap: new top-level `bridges` block + `simplex_bridge_url`; render
  semif-simplex-forward + semif-bridge units; gateway config loses bridge/inbox
- docs: AGENTS.md gateway isolation is non-negotiable
This commit is contained in:
Denton Social committed 2026-09-28 15:24:44 -05:00
1 parent d46fbdca19
commit ddc5cb66c8
31 files changed
+1702 -1088

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
"""Third-party API bridges: a secure local layer between skills and services.
A **bridge service** is a standalone process that exposes one third-party system
(SimpleX first, more later) to codegen-authored skill bodies over a local,
token-guarded HTTP API. It exists so a generated body never speaks a system's
native protocol (WebSocket, SMTP, CalDAV, a CLI's private flags) directly: it
calls a small, documented, uniform HTTP surface instead, and the bridge owns the
messy integration details and credentials.
Two boundaries matter:
- **Bridges are not the gateway.** The command gateway only takes commands and
replies; it must never grow read/send/invite endpoints. Bridges run as their
own processes (`python -m semif_agent.cli bridge`) against their own service
daemons/profiles. This isolation is non-negotiable (see AGENTS.md).
- **The catalog is visible to codegen.** `describe_bridges()` is injected into
the code-generation prompts so the model knows which real services it may
build against and how to reach them.
"""
from .base import BridgeInfo, BridgeService
from .inbox import MessagingInbox
from .registry import (
build_bridge,
describe_bridges,
known_infos,
run_bridges,
)
__all__ = [
"BridgeInfo",
"BridgeService",
"MessagingInbox",
"build_bridge",
"describe_bridges",
"known_infos",
"run_bridges",
]
+154
View File
@@ -0,0 +1,154 @@
"""Bridge service contract + the shared secure HTTP layer.
Every bridge stands up the same thin HTTP surface: JSON in, JSON out, bound to
localhost, optionally guarded by a shared-secret header. A subclass only
implements its routes (`handle_get` / `handle_post`) and, if it needs a service
daemon, starts it in `start()`. The HTTP/JSON/auth plumbing lives here once so
each new bridge is small and hard to get wrong.
"""
from __future__ import annotations
import json
import threading
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
@dataclass(frozen=True)
class BridgeInfo:
"""Static, prompt-safe metadata about a bridge.
Fed to the code-generation model so it knows what it can build against,
and used to describe the service in docs. Holds no secrets and needs no
running process.
"""
name: str
service: str
description: str
url_config_var: str
#: Human-readable `METHOD /path` -> purpose lines.
endpoints: tuple[str, ...] = ()
#: Other `ctx.config` keys a body built on this bridge may read.
config_vars: tuple[str, ...] = field(default=())
class BridgeService(ABC):
"""Base class for a standalone third-party API bridge."""
#: short snake_case id (`simplex`)
name: str = "bridge"
#: static catalog entry
info: BridgeInfo
def __init__(self, config: dict | None = None, trace=None):
cfg = config or {}
self.host = str(cfg.get("host", "127.0.0.1"))
self.port = int(cfg.get("port", 0))
self.token = str(cfg.get("token", "") or "")
self.trace = trace
self._server: ThreadingHTTPServer | None = None
self._thread: threading.Thread | None = None
# ---- lifecycle ----
@abstractmethod
def check_requirements(self) -> tuple[bool, str | None]:
"""Return `(ok, install_hint)`. Must never raise on a missing dep."""
def start(self) -> int:
"""Start serving HTTP; returns the bound port (`port=0` is ephemeral)."""
server = ThreadingHTTPServer((self.host, self.port), _BridgeHTTPHandler)
server.bridge = self # type: ignore[attr-defined]
self._server = server
self._thread = threading.Thread(
target=server.serve_forever,
name=f"bridge-{self.name}",
daemon=True,
)
self._thread.start()
return int(server.server_address[1])
def stop(self) -> None:
self._stop_transport()
server, self._server = self._server, None
if server is not None:
server.shutdown()
server.server_close()
thread, self._thread = self._thread, None
if thread is not None:
thread.join(timeout=2.0)
def _stop_transport(self) -> None:
"""Hook for subclasses that own a background transport (daemon)."""
# ---- routes ----
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
return 404, {"error": "not found"}
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
return 404, {"error": "not found"}
# ---- helpers ----
def _event(self, kind: str, **fields) -> None:
if self.trace is not None:
self.trace.append(kind, "?", **fields)
class _BridgeHTTPHandler(BaseHTTPRequestHandler):
"""JSON request handler; the owning bridge is on `self.server.bridge`."""
def log_message(self, *args) -> None: # silence the default stderr spam
pass
def _bridge(self) -> BridgeService:
return self.server.bridge # type: ignore[attr-defined]
def _authorized(self) -> bool:
token = self._bridge().token
if not token:
return True
return self.headers.get("X-Semif-Token") == token
def _json(self, status: int, payload: dict) -> None:
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _require_auth(self) -> bool:
if self._authorized():
return True
self._json(401, {"error": "unauthorized"})
return False
def do_GET(self) -> None:
if not self._require_auth():
return
url = urlparse(self.path)
status, payload = self._bridge().handle_get(url.path, parse_qs(url.query))
self._json(status, payload)
def do_POST(self) -> None:
if not self._require_auth():
return
url = urlparse(self.path)
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length) if length else b""
try:
payload = json.loads(raw.decode("utf-8") or "{}")
except ValueError:
self._json(400, {"error": "invalid JSON body"})
return
if not isinstance(payload, dict):
self._json(400, {"error": "body must be a JSON object"})
return
status, response = self._bridge().handle_post(url.path, payload)
self._json(status, response)
+63
View File
@@ -0,0 +1,63 @@
"""A bounded, thread-safe FIFO of buffered inbound messages + known contacts.
The bridge owns the read cursor so a read skill stays stateless. Generic over
transports: entries are normalized message dicts (`contact_id`, `display_name`,
`text`), which is exactly what `semif_agent.simplex_ws` yields.
"""
from __future__ import annotations
import threading
import time
import uuid
from collections import deque
class MessagingInbox:
def __init__(self, max_size: int = 100):
self._lock = threading.Lock()
self._items: deque[dict] = deque()
self._max = max(1, int(max_size))
self._contacts: dict[str, str] = {}
def record(self, message: dict) -> dict:
contact_id = str(message.get("contact_id") or "")
display_name = message.get("display_name") or ""
entry = {
"id": uuid.uuid4().hex[:12],
"contact_id": contact_id,
"display_name": display_name,
"text": message.get("text") or "",
"received_at": time.time(),
}
with self._lock:
if display_name:
self._contacts[contact_id] = display_name
else:
self._contacts.setdefault(contact_id, "")
self._items.append(entry)
while len(self._items) > self._max:
self._items.popleft()
return entry
def peek(self) -> list[dict]:
with self._lock:
return list(self._items)
def pop(self, contact_id: str | None = None) -> dict | None:
with self._lock:
if contact_id is None:
return self._items.popleft() if self._items else None
target = str(contact_id)
for index, entry in enumerate(self._items):
if entry["contact_id"] == target:
del self._items[index]
return entry
return None
def contacts(self) -> list[dict]:
with self._lock:
return [
{"id": contact_id, "display_name": name}
for contact_id, name in self._contacts.items()
]
+111
View File
@@ -0,0 +1,111 @@
"""The bridge catalog: discovery, prompt description, and standalone runner.
Every known bridge class is listed in `CATALOG`. `known_infos()` exposes their
static metadata, `describe_bridges()` renders the catalog block injected into
the code-generation prompts, and `run_bridges()` starts the enabled ones as a
standalone process (`python -m semif_agent.cli bridge`). Adding a bridge means
adding its class here and a `config.example.json` block; the gateway is never
touched.
"""
from __future__ import annotations
import threading
from .base import BridgeInfo, BridgeService
from .simplex import SimplexBridge
#: Known bridge services. Order is presentation order.
CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge,)
def _class_for(name: str) -> type[BridgeService] | None:
for bridge_class in CATALOG:
if bridge_class.INFO.name == name:
return bridge_class
return None
def known_infos() -> list[BridgeInfo]:
return [bridge_class.INFO for bridge_class in CATALOG]
def describe_bridges() -> str:
"""A prompt block describing every available bridge service.
Injected into the skill-body and elicitation prompts so codegen knows which
real services it may build a skill against, how to reach each one, and which
`ctx.config` variable carries its URL. Static — no bridge needs to be
running or enabled.
"""
lines = [
"Available bridge services (call these over HTTP with urllib.request; "
"never speak a service's native protocol directly):",
]
for info in known_infos():
lines.append(f"- {info.name}: {info.description}")
lines.append(f" config var: {info.url_config_var}")
if info.config_vars:
other = [v for v in info.config_vars if v != info.url_config_var]
if other:
lines.append(f" other config vars: {', '.join(other)}")
for endpoint in info.endpoints:
lines.append(f" {endpoint}")
return "\n".join(lines) + "\n"
def build_bridge(config: dict, name: str, trace=None) -> BridgeService:
"""Instantiate one bridge from the top-level `bridges.<name>` config block."""
bridge_class = _class_for(name)
if bridge_class is None:
raise KeyError(f"unknown bridge: {name!r}")
block = (config.get("bridges", {}) or {}).get(name, {}) or {}
return bridge_class(block, trace=trace)
def run_bridges(
config: dict,
names: list[str] | None = None,
trace=None,
) -> int:
"""Run the selected (+ enabled) bridges until interrupted.
With explicit `names`, a bridge runs even if disabled is not set; with no
names, only `enabled` bridges run. Returns a process exit code.
"""
blocks = config.get("bridges", {}) or {}
selected: list[BridgeService] = []
for bridge_class in CATALOG:
name = bridge_class.INFO.name
if names and name not in names:
continue
block = blocks.get(name, {}) or {}
if not names and not block.get("enabled", False):
continue
bridge = bridge_class(block, trace=trace)
ok, hint = bridge.check_requirements()
if not ok:
print(f"bridge {name} unavailable: {hint}")
for running in selected:
running.stop()
return 1
port = bridge.start()
selected.append(bridge)
print(
f"bridge {name} listening on http://{bridge.host}:{port} "
f"(skills use the {bridge_class.INFO.url_config_var} config var)"
)
if not selected:
print("no bridge services enabled (set bridges.<name>.enabled)")
return 1
stop = threading.Event()
try:
while not stop.wait(0.5):
pass
except KeyboardInterrupt:
pass
finally:
for bridge in selected:
bridge.stop()
return 0
+148
View File
@@ -0,0 +1,148 @@
"""SimpleX forwarding bridge: invite links, reading, and sending for skills.
The first third-party API bridge. It stands up a small HTTP API that a skill
body calls instead of talking to `simplex-chat` directly, and it owns its **own**
SimpleX daemon/profile — separate from the command gateway's. That separation is
the point: the gateway takes commands; this bridge forwards the user's messaging
UX (show/create the contact link, read the next message, compose a send).
It buffers every inbound direct message (no allowlist — the user wants to see
who reached the bot through its invite link), and it never runs inside the
gateway process.
"""
from __future__ import annotations
import threading
from semif_agent.simplex_ws import SimplexDaemon
from .base import BridgeInfo, BridgeService
from .inbox import MessagingInbox
class SimplexBridge(BridgeService):
name = "simplex"
INFO = BridgeInfo(
name="simplex",
service="simplex",
description=(
"Read and send SimpleX messages on the user's behalf, and show or "
"create the contact link others use to reach this agent."
),
url_config_var="simplex_bridge_url",
endpoints=(
"GET /health -> {\"ok\": true} — the bridge is up",
"GET /contacts -> {\"contacts\": [{\"id\", \"display_name\"}]}",
"GET /inbox -> peek buffered inbound messages (does not consume)",
"GET /inbox/next?contact=<id> -> pop the oldest unread message for a "
"contact (or any contact) -> {\"message\": {...}|null}",
"GET /address -> the agent's SimpleX contact link "
"(creates it on first call) -> {\"short_link\", \"full_link\", "
"\"created\"}",
"POST /send {\"recipient\": \"<id|display_name>\", \"text\": \"...\"} "
"-> {\"ok\", \"contact_id\"}",
),
config_vars=("simplex_bridge_url", "simplex_default_contact"),
)
def __init__(self, config: dict | None = None, trace=None, daemon=None):
super().__init__(config, trace)
cfg = config or {}
self.inbox = MessagingInbox(int(cfg.get("max_inbox", 100)))
self.daemon = daemon or SimplexDaemon(
cfg.get("ws_url", "ws://127.0.0.1:5228"),
user_id=int(cfg.get("user_id", 1)),
auto_accept=bool(cfg.get("auto_accept", True)),
reconnect=cfg.get("reconnect", {}) or {},
trace=trace,
name=self.name,
)
self._daemon_thread: threading.Thread | None = None
# ---- lifecycle ----
def check_requirements(self) -> tuple[bool, str | None]:
return self.daemon.check_requirements()
def start(self) -> int:
port = super().start()
self._daemon_thread = threading.Thread(
target=self.daemon.run,
args=(self._on_message,),
name="bridge-simplex-daemon",
daemon=True,
)
self._daemon_thread.start()
return port
def _stop_transport(self) -> None:
self.daemon.close()
def _on_message(self, message: dict) -> None:
self.inbox.record(message)
# ---- routes ----
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
if path == "/health":
return 200, {"ok": True, "platform": self.name}
if path == "/contacts":
return 200, {"contacts": self.inbox.contacts()}
if path == "/inbox":
return 200, {"messages": self.inbox.peek()}
if path == "/inbox/next":
contact = (query.get("contact") or [None])[0]
return 200, {"message": self.inbox.pop(contact)}
if path == "/address":
return self._address()
return 404, {"error": "not found"}
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
if path != "/send":
return 404, {"error": "not found"}
recipient = payload.get("recipient")
text = payload.get("text")
if not isinstance(recipient, str) or not recipient.strip():
return 400, {"error": "recipient is required"}
if not isinstance(text, str) or not text.strip():
return 400, {"error": "text is required"}
try:
contact_id = self.send(recipient, text)
except ValueError as exc:
return 400, {"error": str(exc)}
return 200, {"ok": True, "contact_id": contact_id}
# ---- actions ----
def _address(self) -> tuple[int, dict]:
try:
link = self.daemon.request_address()
except RuntimeError as exc:
return 503, {"error": f"address lookup is not available: {exc}"[:300]}
except Exception as exc: # TimeoutError, daemon error
return 502, {"error": f"address lookup failed: {exc}"[:300]}
if not isinstance(link, dict):
return 502, {"error": "address lookup returned no link"}
return 200, link
def send(self, recipient: str, text: str) -> str:
"""Resolve a recipient and enqueue the message. Returns the contact id."""
contact_id = self.resolve(recipient)
if contact_id is None:
raise ValueError(f"unknown SimpleX recipient: {recipient!r}")
self.daemon.enqueue(contact_id, text)
return contact_id
def resolve(self, recipient: str) -> str | None:
"""A numeric id (with or without `@`) or a known display name."""
recipient = str(recipient or "").strip()
if not recipient:
return None
bare = recipient.lstrip("@")
if bare.isdigit():
return bare
for contact in self.inbox.contacts():
if contact["display_name"] == recipient or contact["id"] == recipient:
return contact["id"]
return None
+24 -19
View File
@@ -345,23 +345,6 @@ def run_gateway(
scheduler.on_request_requeued = service.on_request_requeued
service.start()
from .gateway.bridge import MessagingBridge
bridge_cfg = cfg.get("bridge", {}) or {}
bridge = None
if bridge_cfg.get("enabled", True):
bridge = MessagingBridge(
service.outbound,
config=bridge_cfg,
address_provider=adapter.request_address,
)
service.observer = bridge.record_inbound
port = bridge.start()
print(
f"messaging bridge listening on http://{bridge.host}:{port} "
"(skills use messaging_bridge_url)"
)
if serve_dashboard:
import threading
@@ -386,11 +369,22 @@ def run_gateway(
finally:
service.stop()
adapter.close()
if bridge is not None:
bridge.stop()
return 0
def run_bridge(scheduler: Scheduler, config: dict, name: str | None = None) -> int:
"""Run standalone third-party API bridges (SimpleX first).
Bridges are their own processes so generated skills never touch a system's
native protocol and the command gateway never grows read/send surface. See
`semif_agent.bridges`.
"""
from .bridges.registry import run_bridges
names = [name] if name else None
return run_bridges(config, names=names, trace=scheduler.trace)
def main(argv: list[str] | None = None) -> int:
argv = list(argv) if argv is not None else list(sys.argv[1:])
config = load_config(_extract_config_path(argv))
@@ -430,6 +424,15 @@ def main(argv: list[str] | None = None) -> int:
help="also serve the browser dashboard from the same process",
)
bridge_p = sub.add_parser(
"bridge", help="run standalone third-party API bridges (SimpleX first)"
)
bridge_p.add_argument(
"--name",
default=None,
help="bridge service to run (default: all enabled)",
)
args = parser.parse_args(argv)
scheduler, config = build_scheduler(config)
@@ -461,6 +464,8 @@ def main(argv: list[str] | None = None) -> int:
platform=args.platform,
serve_dashboard=args.dashboard,
)
elif args.command == "bridge":
return run_bridge(scheduler, config, name=args.name)
else:
parser.print_help()
return 0
+11 -7
View File
@@ -24,6 +24,7 @@ from typing import Callable, NamedTuple
from .decisions import Request
from .skills import SkillDraft, tree_summary
from .bridges.registry import describe_bridges
DEFAULT_CONTRACT = Path(__file__).resolve().parent.parent / "SKILL.md"
DEFAULT_CONTEXT_WINDOW = 100000
@@ -633,12 +634,12 @@ BODY_DIRECTIVES = (
"body.\n"
"Declare the integration as a module-level `INTEGRATION` dict exactly as "
"SKILL.md specifies: service, transport, config_vars.\n"
"If this skill sends or reads SimpleX messages, call the messenger "
"gateway's local HTTP bridge (the `messaging_bridge_url` value from "
"`ctx.config`; endpoints: GET /inbox, GET /inbox/next?contact=, POST "
"/send) — never open a WebSocket to the simplex-chat daemon. Resolve which "
"contact/conversation with a `ctx.engine` sub-decision, and send only when "
"the request or requirements ask for it.\n"
"If this skill interacts with one of the available bridge services listed "
"below, call that bridge over HTTP with the URL from its config variable — "
"never speak the service's native protocol directly (no WebSocket to "
"simplex-chat, no direct daemon access). Resolve which contact or "
"conversation with a `ctx.engine` sub-decision, and send only when the "
"request or requirements ask for it.\n"
)
@@ -682,6 +683,7 @@ def build_skill_body_prompt(
f"Existing skills in this category: {existing}\n"
f"Existing categories:\n{tree_summary(tree)}\n"
f"{req_block}"
f"{describe_bridges()}\n"
f"{BODY_DIRECTIVES}"
"Write the Python module body now. Reply with ONLY valid Python code "
"defining `predict` and `act`. No prose, no markdown fences, no JSON."
@@ -995,6 +997,7 @@ def _retry_prompt(
f"Skill name: {draft.name}\n"
f"Skill description: {draft.description}\n"
f"{_requirements_block(requirements)}"
f"{describe_bridges()}\n"
f"{BODY_DIRECTIVES}"
"Reply with ONLY valid Python defining `predict` and `act`. No prose, "
"no markdown fences, no JSON."
@@ -1067,7 +1070,7 @@ ELICITATION_EXAMPLES = [
"How does it authenticate with the service, and should that credential come from the app's config?",
"What does a successful run look like — what should it report back to you?",
"If the service is unreachable or refuses the action, should the run fail loudly or record 'could not complete' as the result?",
"Should this skill send or read SimpleX messages through the messaging gateway, and if so which conversation (resolved by contact name)?",
"Should this skill send or read SimpleX messages through the simplex bridge, and if so which conversation (resolved by contact name)?",
]
@@ -1122,6 +1125,7 @@ def build_elicitation_prompt(
f"Skill description: {draft.description}\n"
f"Existing skills in this category: {existing}\n"
f"Existing categories:\n{tree_summary(tree)}\n"
f"{describe_bridges()}\n"
)
return [
{"role": "system", "content": system},
+9 -8
View File
@@ -1,13 +1,17 @@
"""Messaging gateway: external messenger intake/reply for the SemIf agent.
A `GatewayAdapter` owns a transport (SimpleX first), and `GatewayService`
maps inbound text onto the scheduler's existing gate/score/queue/dispatch
pipeline and routes results, questions, and repairs back to the originating
chat. See `base.py` for the contract.
The gateway is the agent's **command** surface and nothing else. A
`GatewayAdapter` owns a transport (SimpleX first), and `GatewayService` maps
inbound text onto the scheduler's existing gate/score/queue/dispatch pipeline
and routes results, questions, and repairs back to the originating chat.
Messaging *UX* — invite links, reading a contact's messages, composing sends —
does not live here; it belongs to the standalone bridge services in
`semif_agent.bridges`. Keeping the command surface free of that functionality
is a hard boundary (see AGENTS.md "gateway isolation").
"""
from .base import GatewayAdapter, InboundMessage, OutboundMessage
from .bridge import MessagingBridge, MessagingInbox, start_bridge
from .service import GatewayService
__all__ = [
@@ -15,8 +19,5 @@ __all__ = [
"InboundMessage",
"OutboundMessage",
"GatewayService",
"MessagingBridge",
"MessagingInbox",
"start_bridge",
]
+11 -10
View File
@@ -1,15 +1,16 @@
"""The messaging-gateway adapter contract.
"""The messenger command-gateway adapter contract.
An adapter owns one transport (SimpleX WebSocket, and later Telegram, Signal,
...). It delivers inbound text as `InboundMessage` and drains outbound replies
from a stdlib queue. Everything about the SemIf scheduler — gating, scoring,
queueing, run ownership, questions, repairs — lives in `GatewayService`; an
adapter must not know it exists.
An adapter owns one command transport (SimpleX WebSocket, and later Telegram,
Signal, ...). It delivers inbound text as `InboundMessage` and drains outbound
replies from a stdlib queue. Everything about the SemIf scheduler — gating,
scoring, queueing, run ownership, questions, repairs — lives in `GatewayService`;
an adapter must not know it exists. Neither knows anything about messaging UX
(invite links, reading, composing): that is the bridge services' job.
The transport is intentionally a plain `queue.Queue` bridge: the adapter's
event loop puts an outbound message into the queue, the service puts replies
into it. This keeps scheduler work (which is synchronous and can block on the
decision engine) off the adapter's event loop.
The transport is intentionally a plain `queue.Queue`: the adapter's event loop
puts an outbound message into the queue, the service puts replies into it. This
keeps scheduler work (which is synchronous and can block on the decision engine)
off the adapter's event loop.
"""
from __future__ import annotations
-276
View File
@@ -1,276 +0,0 @@
"""Local HTTP bridge that exposes the messenger gateway to skill bodies.
A skill never opens a WebSocket to the `simplex-chat` daemon itself. Instead
the running gateway serves this small stdlib HTTP API on localhost:
GET /health {"ok": true, "platform": "simplex"}
GET /contacts {"contacts": [{"id", "display_name"}]}
GET /inbox peek buffered inbound messages
GET /inbox/next?contact=<id> 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": "<id|name>", "text": "..."}
The bridge owns the read cursor (a bounded FIFO of authorized inbound DMs), so
a read skill stays stateless. Outbound sends reuse the gateway's existing
`OutboundMessage` queue, i.e. the same transport that already replies to chats.
The bridge is deliberately the only messaging surface a generated body touches,
which keeps bodies stdlib-only and their hermetic tests ordinary loopback HTTP.
"""
from __future__ import annotations
import json
import queue
import threading
import time
import uuid
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
from .base import InboundMessage, OutboundMessage
class MessagingInbox:
"""Thread-safe, bounded FIFO of buffered inbound messages + contacts."""
def __init__(self, max_size: int = 100):
self._lock = threading.Lock()
self._items: deque[dict] = deque()
self._max = max(1, int(max_size))
self._contacts: dict[str, str] = {}
def record(self, msg: InboundMessage) -> dict:
contact_id = str(msg.contact_id or msg.chat_id)
entry = {
"id": uuid.uuid4().hex[:12],
"contact_id": contact_id,
"display_name": msg.display_name or "",
"text": msg.text,
"received_at": time.time(),
}
with self._lock:
if msg.display_name:
self._contacts[contact_id] = msg.display_name
else:
self._contacts.setdefault(contact_id, "")
self._items.append(entry)
while len(self._items) > self._max:
self._items.popleft()
return entry
def peek(self) -> list[dict]:
with self._lock:
return list(self._items)
def pop(self, contact_id: str | None = None) -> dict | None:
with self._lock:
if contact_id is None:
return self._items.popleft() if self._items else None
target = str(contact_id)
for index, entry in enumerate(self._items):
if entry["contact_id"] == target:
del self._items[index]
return entry
return None
def contacts(self) -> list[dict]:
with self._lock:
return [
{"id": contact_id, "display_name": name}
for contact_id, name in self._contacts.items()
]
class MessagingBridge:
"""The gateway's localhost messaging API for skills.
Serves the endpoints above in a background thread. `outbound` is the
adapter's send queue (the gateway drains it); posting an `OutboundMessage`
onto it is exactly how replies are sent. `config` is the
`gateway.<platform>.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"
def __init__(
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"))
self.port = int(cfg.get("port", 5227))
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
# ---- lifecycle ----
def start(self) -> int:
"""Start serving; returns the bound port (useful when `port` is 0)."""
handler = type("BridgeHandler", (_BridgeHandler,), {})
server = ThreadingHTTPServer((self.host, self.port), handler)
server.bridge = self # type: ignore[attr-defined]
self._server = server
self._thread = threading.Thread(
target=server.serve_forever, name="messaging-bridge", daemon=True
)
self._thread.start()
return int(server.server_address[1])
def stop(self) -> None:
server, self._server = self._server, None
if server is not None:
server.shutdown()
server.server_close()
thread, self._thread = self._thread, None
if thread is not None:
thread.join(timeout=2.0)
# ---- used by the gateway service ----
def record_inbound(self, msg: InboundMessage) -> None:
"""Observer callback: buffer an authorized inbound message for reads."""
self.inbox.record(msg)
def send(self, recipient: str, text: str) -> str:
"""Resolve a recipient and enqueue the message. Returns the contact id."""
contact_id = self.resolve(recipient)
if contact_id is None:
raise ValueError(f"unknown SimpleX recipient: {recipient!r}")
self.outbound.put(OutboundMessage(chat_id=contact_id, text=text))
return contact_id
def resolve(self, recipient: str) -> str | None:
"""A numeric id (with or without `@`) or a known display name."""
recipient = str(recipient or "").strip()
if not recipient:
return None
bare = recipient.lstrip("@")
if bare.isdigit():
return bare
for contact in self.inbox.contacts():
if contact["display_name"] == recipient or contact["id"] == recipient:
return contact["id"]
return None
class _BridgeHandler(BaseHTTPRequestHandler):
"""Request handler; the owning bridge is on `self.server.bridge`."""
def log_message(self, *args) -> None: # silence the default stderr spam
pass
# ---- helpers ----
def _bridge(self) -> MessagingBridge:
return self.server.bridge # type: ignore[attr-defined]
def _authorized(self) -> bool:
token = self._bridge().token
if not token:
return True
return self.headers.get("X-Semif-Token") == token
def _json(self, status: int, payload: dict) -> None:
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _require_auth(self) -> bool:
if self._authorized():
return True
self._json(401, {"error": "unauthorized"})
return False
# ---- routes ----
def do_GET(self) -> None:
if not self._require_auth():
return
url = urlparse(self.path)
bridge = self._bridge()
if url.path == "/health":
self._json(200, {"ok": True, "platform": bridge.name})
elif url.path == "/contacts":
self._json(200, {"contacts": bridge.inbox.contacts()})
elif url.path == "/inbox":
self._json(200, {"messages": bridge.inbox.peek()})
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"})
def do_POST(self) -> None:
if not self._require_auth():
return
url = urlparse(self.path)
if url.path != "/send":
self._json(404, {"error": "not found"})
return
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length) if length else b""
try:
payload = json.loads(raw.decode("utf-8") or "{}")
except ValueError:
self._json(400, {"error": "invalid JSON body"})
return
if not isinstance(payload, dict):
self._json(400, {"error": "body must be a JSON object"})
return
recipient = payload.get("recipient")
text = payload.get("text")
if not isinstance(recipient, str) or not recipient.strip():
self._json(400, {"error": "recipient is required"})
return
if not isinstance(text, str) or not text.strip():
self._json(400, {"error": "text is required"})
return
try:
contact_id = self._bridge().send(recipient, text)
except ValueError as exc:
self._json(400, {"error": str(exc)})
return
self._json(200, {"ok": True, "contact_id": contact_id})
def start_bridge(
outbound: "queue.Queue[OutboundMessage | None]",
config: dict | None = None,
address_provider=None,
) -> tuple[MessagingBridge, int]:
bridge = MessagingBridge(outbound, config=config, address_provider=address_provider)
port = bridge.start()
return bridge, port
+1 -15
View File
@@ -59,13 +59,6 @@ class GatewayService:
self.home_channel = str(cfg.get("home_channel", "") or "")
self.reply_prefix = str(cfg.get("reply_prefix", "") or "")
self.poll_interval = float(poll_interval)
inbox_cfg = cfg.get("inbox", {}) or {}
#: When false the gateway only buffers inbound messages (for a read
#: skill to pull) instead of dispatching them as scheduler requests.
self.inbox_dispatch = bool(inbox_cfg.get("dispatch", True))
#: Optional callback invoked for every authorized inbound message,
#: before routing. The bridge uses it to fill its inbox.
self.observer = None
self.outbound: "queue.Queue[OutboundMessage | None]" = queue.Queue()
self._owners: dict[str, str] = {}
self._parents: dict[str, str] = {}
@@ -111,15 +104,8 @@ class GatewayService:
return None
def handle_inbound(self, msg: InboundMessage) -> None:
"""Handle one authorized inbound message. Called by the adapter."""
"""Handle one authorized inbound command. Called by the adapter."""
with self._route_lock:
if self.observer is not None:
self.observer(msg)
if not self.inbox_dispatch:
# Pull mode: buffer only (the observer recorded it); a read
# skill will consume it later. No scheduler request, no reply.
self.drain()
return
reply_to = msg.chat_id
pending = self.scheduler.pending
if pending is not None and self._pending_owner is None:
+52 -273
View File
@@ -1,84 +1,54 @@
"""SimpleX Chat gateway adapter.
"""SimpleX command-gateway adapter.
Connects to the local `simplex-chat` daemon (`simplex-chat -p 5225`) over its
JSON WebSocket API, receives DM text from allowlisted contacts, and sends
replies with the structured `/_send` command. Groups, attachments, reactions,
and typing are deliberately out of scope for the first cut.
The gateway is the agent's **command** surface: allowlisted contacts DM the bot
and their text is fed to the scheduler, whose reply is sent back. All the
messaging *UX* surface (invite links, reading a contact's messages, composing on
the user's behalf) lives in separate bridge services, never here — see
AGENTS.md "gateway isolation".
`websockets` is imported lazily inside the functions that need it so this
module (and the gateway package) stays importable on a machine without the
dependency; `check_requirements()` gates the gateway off with an install hint.
This adapter is the policy layer over the neutral `SimplexDaemon` transport in
`semif_agent.simplex_ws`: it applies the allowlist, batches rapid messages, and
hands authorized text to the scheduler. It must not grow address/inbox/send
endpoints; those belong to a bridge.
"""
from __future__ import annotations
import asyncio
import concurrent.futures
import json
import queue
import random
import threading
from typing import Any
from semif_agent.simplex_ws import SimplexDaemon, send_text_command
from .base import GatewayAdapter, InboundMessage, OutboundMessage
def contact_link(resp: dict) -> dict:
"""Pull `{connShortLink, connFullLink}` out of a daemon address response.
`/_show_address` nests it as `contactLink.connLinkContact`; `/_address`
returns it directly as `connLinkContact`. Tolerate both (and a flat
`contactLink`) so the adapter reads the real daemon shape rather than
calling `/_address` again on an existing link and reporting nothing.
"""
for candidate in (
(resp.get("contactLink") or {}).get("connLinkContact"),
resp.get("connLinkContact"),
resp.get("contactLink"),
resp,
):
if isinstance(candidate, dict) and (
candidate.get("connShortLink") or candidate.get("connFullLink")
):
return candidate
return {}
class SimplexAdapter(GatewayAdapter):
name = "simplex"
def __init__(self, cfg: dict | None = None, trace=None):
cfg = cfg or {}
self.ws_url = str(cfg.get("ws_url", "ws://127.0.0.1:5225"))
self.allowed_users = [str(u) for u in cfg.get("allowed_users", []) or []]
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.daemon = SimplexDaemon(
cfg.get("ws_url", "ws://127.0.0.1:5225"),
user_id=int(cfg.get("user_id", 1)),
auto_accept=bool(cfg.get("auto_accept", True)),
reconnect=cfg.get("reconnect", {}) or {},
trace=trace,
name=self.name,
)
self.ws_url = self.daemon.ws_url
self._buffers: dict[str, str] = {}
self._buffered: dict[str, InboundMessage] = {}
self._flush_tasks: dict[str, asyncio.Task] = {}
self._stop = threading.Event()
self._on_inbound = None
# ---- requirements ----
def check_requirements(self) -> tuple[bool, str | None]:
if not self.ws_url:
return False, "gateway.simplex.ws_url is required"
try:
import websockets # noqa: F401
except ImportError:
return False, "pip install websockets"
return True, None
return self.daemon.check_requirements()
# ---- authorization ----
@@ -99,232 +69,47 @@ class SimplexAdapter(GatewayAdapter):
on_inbound,
outbound: "queue.Queue[OutboundMessage | None]",
) -> None:
asyncio.run(self._serve(on_inbound, outbound))
self._on_inbound = on_inbound
def _pump() -> None:
# Translate the service's OutboundMessage queue onto the daemon's
# (chat_id, text) queue without letting scheduler work touch the
# daemon's event loop.
while True:
message = outbound.get()
if message is None:
self.daemon.enqueue(None)
return
self.daemon.enqueue(message.chat_id, message.text)
threading.Thread(target=_pump, name="simplex-outbound-pump", daemon=True).start()
self.daemon.run(self._on_item)
def close(self) -> None:
self._stop.set()
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))
try:
async for raw in ws:
await self._consume(raw, on_inbound, ws)
finally:
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:
await asyncio.wait_for(self._stop_wait(), timeout=delay)
except asyncio.TimeoutError:
pass
backoff = min(max(delay, self.reconnect_initial), self.reconnect_max)
async def _stop_wait(self) -> None:
while not self._stop.is_set():
await asyncio.sleep(0.2)
async def _outbound_loop(self, ws, outbound: "queue.Queue") -> None:
loop = asyncio.get_running_loop()
while True:
message = await loop.run_in_executor(None, outbound.get)
if message is None:
return
try:
await self._send(ws, message)
except Exception as exc:
self._event("gateway_error", phase="send", message=str(exc)[:300])
async def _send(self, ws, message: OutboundMessage) -> None:
command = self.send_command(message.chat_id, message.text)
self._corr += 1
await ws.send(json.dumps({"corrId": f"sf-{self._corr}", "cmd": command}))
self._event("gateway_sent", chat_id=message.chat_id, chars=len(message.text))
self.daemon.close()
def send_command(self, chat_id: str, text: str) -> str:
"""Structured APISendMessages command for a direct contact.
The CLI shortcut `@<id> <text>` is silently rejected over WebSocket
(it resolves the ref as a display name), so always use the JSON form.
"""
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 <userId>` returns an
existing link; when there is none, `/_address <userId>` 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 = contact_link(resp)
if not (link.get("connShortLink") or link.get("connFullLink")):
resp = await self._roundtrip(f"/_address {self.user_id}", timeout)
link = contact_link(resp)
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
return send_text_command(chat_id, text)
# ---- inbound ----
async def _consume(self, raw: Any, on_inbound, ws) -> None:
try:
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":
await self._maybe_accept(ws, resp)
return
if kind != "newChatItems":
return
for item in resp.get("chatItems", []) or []:
message = self._parse_chat_item(item)
if message is not None:
self._schedule_flush(message, on_inbound)
def _parse_chat_item(self, item: dict) -> InboundMessage | None:
chat_info = item.get("chatInfo") or {}
if chat_info.get("type") != "direct":
return None
chat_item = item.get("chatItem") or {}
direction = (chat_item.get("chatDir") or {}).get("type", "")
if direction and "Snd" in direction:
return None # own echo
content = chat_item.get("content") or {}
# simplex-chat v7 tags the content union by constructor: a received text
# message is {"type": "rcvMsgContent", "msgContent": {"type": "text",
# "text": ...}}. The daemon's DB/Aeson encoding nests under the
# constructor key instead ({"rcvMsgContent": {"msgContent": ...}}), so
# accept both shapes.
if content.get("type") == "rcvMsgContent":
msg_content = content.get("msgContent") or {}
elif isinstance(content.get("rcvMsgContent"), dict):
msg_content = content["rcvMsgContent"].get("msgContent") or {}
else:
return None
if msg_content.get("type") != "text":
return 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 "")
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")
)
if not contact_id:
return None
def _on_item(self, message: dict) -> None:
contact_id = str(message.get("contact_id") or "")
display_name = message.get("display_name")
if not self.is_authorized(contact_id, display_name):
self._event("gateway_denied", contact_id=contact_id, display_name=display_name)
return None
return InboundMessage(
text=text,
self.daemon._event(
"gateway_denied", contact_id=contact_id, display_name=display_name
)
return
inbound = InboundMessage(
text=message.get("text") or "",
chat_id=contact_id,
chat_type="dm",
contact_id=contact_id,
display_name=display_name,
raw=item,
)
async def _maybe_accept(self, ws, resp: dict) -> None:
if not self.auto_accept:
return
req = resp.get("contactRequest") or {}
# v7 names the field contactRequestId_ (the trailing underscore is the
# generated-API optional marker) and /_accept takes the *request* id;
# older events exposed contactId. Fall back so both shapes work.
req_id = req.get("contactRequestId")
if req_id is None:
req_id = req.get("contactId_") or req.get("contactId")
if req_id is None:
return
self._corr += 1
await ws.send(
json.dumps({"corrId": f"sf-{self._corr}", "cmd": f"/_accept {req_id}"})
)
contact_id = req.get("contactId_") or req.get("contactId")
self._event(
"gateway_accepted",
contact_request_id=str(req_id),
contact_id=str(contact_id) if contact_id is not None else "",
raw=message.get("raw") or {},
)
self._schedule_flush(inbound, self._on_inbound)
def _schedule_flush(self, message: InboundMessage, on_inbound) -> None:
chat = message.chat_id
@@ -347,16 +132,10 @@ class SimplexAdapter(GatewayAdapter):
if message is None or not text:
return
message.text = text
self._event(
self.daemon._event(
"gateway_message",
contact_id=message.contact_id,
display_name=message.display_name,
chars=len(text),
)
await asyncio.to_thread(on_inbound, message)
# ---- tracing ----
def _event(self, kind: str, **fields) -> None:
if self.trace is not None:
self.trace.append(kind, "?", **fields)
+364
View File
@@ -0,0 +1,364 @@
"""Low-level SimpleX Chat daemon WebSocket protocol (neutral transport).
This module owns the wire protocol only: connecting to a local `simplex-chat`
daemon, parsing received events into plain message dicts, running correlated
request/response round-trips (e.g. the contact-address lookup), accepting
contact requests, and draining an outbound send queue. It knows nothing about
the SemIf scheduler, the command gateway, or the forwarding bridge — both
front ends build on top of it.
Keeping this layer neutral is deliberate (see AGENTS.md "gateway isolation"):
the command gateway and the third-party bridge services have different jobs,
and neither inherits the other's surface by sharing this module.
`websockets` is imported lazily inside the functions that need it so importing
this module stays stdlib-only on a websocket-free machine.
"""
from __future__ import annotations
import asyncio
import concurrent.futures
import json
import queue
import random
import threading
from typing import Any, 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]
def contact_link(resp: dict) -> dict:
"""Pull `{connShortLink, connFullLink}` out of a daemon address response.
`/_show_address` nests it as `contactLink.connLinkContact`; `/_address`
returns it directly as `connLinkContact`. Tolerate both (and a flat
`contactLink`) so callers read the real daemon shape rather than calling
`/_address` again on an existing link and reporting nothing.
"""
for candidate in (
(resp.get("contactLink") or {}).get("connLinkContact"),
resp.get("connLinkContact"),
resp.get("contactLink"),
resp,
):
if isinstance(candidate, dict) and (
candidate.get("connShortLink") or candidate.get("connFullLink")
):
return candidate
return {}
def parse_direct_text_item(item: dict) -> InboundDict | None:
"""Normalize one `newChatItems` entry into a message dict, or None.
Returns `{text, contact_id, display_name, raw}` for a received direct text
message. Drops group chats, own echoes, non-text content, and items with no
resolvable contact id. Authorization is the caller's job — this layer is
deliberately policy-free.
"""
chat_info = item.get("chatInfo") or {}
if chat_info.get("type") != "direct":
return None
chat_item = item.get("chatItem") or {}
direction = (chat_item.get("chatDir") or {}).get("type", "")
if direction and "Snd" in direction:
return None # own echo
content = chat_item.get("content") or {}
# simplex-chat v7 tags the content union by constructor: a received text
# message is {"type": "rcvMsgContent", "msgContent": {"type": "text",
# "text": ...}}. The daemon's DB/Aeson encoding nests under the
# constructor key instead ({"rcvMsgContent": {"msgContent": ...}}), so
# accept both shapes.
if content.get("type") == "rcvMsgContent":
msg_content = content.get("msgContent") or {}
elif isinstance(content.get("rcvMsgContent"), dict):
msg_content = content["rcvMsgContent"].get("msgContent") or {}
else:
return None
if msg_content.get("type") != "text":
return 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:
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,
"raw": item,
}
def send_text_command(chat_id: str, text: str) -> str:
"""Structured APISendMessages command for a direct contact.
The CLI shortcut `@<id> <text>` is silently rejected over WebSocket (it
resolves the ref as a display name), so always use the JSON form.
"""
composed = [{"msgContent": {"type": "text", "text": text}}]
return f"/_send @{chat_id} json {json.dumps(composed)}"
def accept_command(resp: dict) -> str | None:
"""The `/_accept` command for a `receivedContactRequest`, or None.
v7 names the field contactRequestId_ (the trailing underscore is the
generated-API optional marker) and /_accept takes the *request* id; older
events exposed contactId. Fall back so both shapes work.
"""
req = resp.get("contactRequest") or {}
req_id = req.get("contactRequestId")
if req_id is None:
req_id = req.get("contactId_") or req.get("contactId")
if req_id is None:
return None
return f"/_accept {req_id}"
class SimplexDaemon:
"""One WebSocket connection to a `simplex-chat` daemon.
`run(on_message)` blocks, reconnecting on transport failure, delivering each
received direct text message to `on_message` in the event loop and draining
`enqueue()`d sends from an internal queue. `request_address()` is safe to
call from another thread (the bridge's HTTP handler). Beware: the same
daemon/profile must not be shared by two processes — each front end points
at its own daemon.
"""
def __init__(
self,
ws_url: str,
*,
user_id: int = 1,
auto_accept: bool = True,
reconnect: dict | None = None,
trace=None,
name: str = "simplex",
):
self.ws_url = str(ws_url)
self.user_id = int(user_id)
self.auto_accept = bool(auto_accept)
settings = reconnect or {}
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.trace = trace
self.name = name
self._corr = 0
self._pending: dict[str, asyncio.Future] = {}
self._loop: asyncio.AbstractEventLoop | None = None
self._ws = None
self._outbound: "queue.Queue[tuple[str, str] | None]" = queue.Queue()
self._stop = threading.Event()
self._on_message: MessageHandler | None = None
# ---- requirements ----
def check_requirements(self) -> tuple[bool, str | None]:
if not self.ws_url:
return False, "simplex ws_url is required"
try:
import websockets # noqa: F401
except ImportError:
return False, "pip install websockets"
return True, None
# ---- lifecycle ----
def run(self, on_message: MessageHandler) -> None:
asyncio.run(self._serve(on_message))
def enqueue(self, chat_id: str | None, text: str = "") -> None:
"""Queue an outbound send. `chat_id=None` is the stop sentinel."""
if chat_id is None:
self._outbound.put(None)
else:
self._outbound.put((str(chat_id), text))
def close(self) -> None:
self._stop.set()
self._outbound.put(None)
async def _serve(self, on_message: MessageHandler) -> None:
import websockets
self._loop = asyncio.get_running_loop()
self._on_message = on_message
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))
try:
async for raw in ws:
await self._consume(raw)
finally:
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:
await asyncio.wait_for(self._stop_wait(), timeout=delay)
except asyncio.TimeoutError:
pass
backoff = min(max(delay, self.reconnect_initial), self.reconnect_max)
async def _stop_wait(self) -> None:
while not self._stop.is_set():
await asyncio.sleep(0.2)
async def _outbound_loop(self, ws) -> None:
loop = asyncio.get_running_loop()
while True:
item = await loop.run_in_executor(None, self._outbound.get)
if item is None:
return
chat_id, text = item
try:
self._corr += 1
await ws.send(
json.dumps(
{
"corrId": f"sf-{self._corr}",
"cmd": send_text_command(chat_id, text),
}
)
)
self._event("gateway_sent", chat_id=chat_id, chars=len(text))
except Exception as exc:
self._event("gateway_error", phase="send", message=str(exc)[:300])
# ---- 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 daemon user's contact address, creating it on first call.
`/_show_address <userId>` returns an existing link; when there is none,
`/_address <userId>` 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 = contact_link(resp)
if not (link.get("connShortLink") or link.get("connFullLink")):
resp = await self._roundtrip(f"/_address {self.user_id}", timeout)
link = contact_link(resp)
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.
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) -> None:
try:
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.
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":
await self._maybe_accept(resp)
return
if kind != "newChatItems":
return
for item in resp.get("chatItems", []) or []:
message = parse_direct_text_item(item)
if message is not None and self._on_message is not None:
self._on_message(message)
async def _maybe_accept(self, resp: dict) -> None:
if not self.auto_accept:
return
command = accept_command(resp)
if command is None:
return
self._corr += 1
await self._ws.send(json.dumps({"corrId": f"sf-{self._corr}", "cmd": command}))
req = resp.get("contactRequest") or {}
contact_id = req.get("contactId_") or req.get("contactId")
self._event(
"gateway_accepted",
contact_request_id=command.split()[-1],
contact_id=str(contact_id) if contact_id is not None else "",
)
# ---- tracing ----
def _event(self, kind: str, **fields) -> None:
if self.trace is not None:
self.trace.append(kind, "?", **fields)