gateway: SimpleX messenger intake/reply

Add a gateway adapter contract plus a SimpleX adapter (lazy websockets,
default-deny allowlist, batching, structured /_send) and a GatewayService
that maps chats onto the single-slot scheduler: submit_request, owner maps,
pending-run ownership, queue drain, and authoring questions/repairs routed
back to the origin chat. Wire `cli gateway [--platform simplex] [--dashboard]`
and the gateway.simplex config block. Scheduler gains submit_request() and an
on_request_requeued hook. DMs only for the first cut.
This commit is contained in:
Denton Social committed 2026-09-26 10:14:09 -05:00
1 parent a627f59a67
commit 6ab4d94423
10 files changed
+973 -12

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
"""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.
"""
from .base import GatewayAdapter, InboundMessage, OutboundMessage
from .service import GatewayService
__all__ = ["GatewayAdapter", "InboundMessage", "OutboundMessage", "GatewayService"]
+65
View File
@@ -0,0 +1,65 @@
"""The messaging-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.
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.
"""
from __future__ import annotations
import queue
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any, Callable
@dataclass
class InboundMessage:
"""One (possibly batched) inbound text message from an external chat."""
text: str
chat_id: str
chat_type: str = "dm" # dm | group
contact_id: str | None = None
display_name: str | None = None
raw: dict[str, Any] = field(default_factory=dict)
@dataclass
class OutboundMessage:
"""One reply destined for an external chat."""
chat_id: str
text: str
#: Callback the adapter invokes for each authorized inbound message.
InboundHandler = Callable[[InboundMessage], None]
class GatewayAdapter(ABC):
"""Transport contract for a messenger platform."""
#: short platform name used in request sources (`"simplex:<chat_id>"`)
name: str = "gateway"
@abstractmethod
def check_requirements(self) -> tuple[bool, str | None]:
"""Return `(ok, install_hint)`. Must never raise on a missing dep."""
@abstractmethod
def run(self, on_inbound: InboundHandler, outbound: "queue.Queue[OutboundMessage | None]") -> None:
"""Block, delivering inbound messages and sending queued outbound ones.
A `None` sentinel in `outbound` asks `run` to return.
"""
def close(self) -> None:
"""Release transport resources. Best-effort; must not raise."""
+228
View File
@@ -0,0 +1,228 @@
"""GatewayService: map external messenger traffic onto the SemIf scheduler.
The scheduler is a single execution slot with one global `pending` run. The
service does not fake concurrency: inbound text is fed through the existing
gate (`submit_request` -> gate/score/queue/dispatch), results and deferred
questions are routed back to the originating chat, and while one chat owns a
`needs_input` pause that chat answers it. Another chat messaging during that
pause is told to wait rather than silently abandoning the first chat's run.
Ownership: a request id maps to the chat that sent it. A run re-queued by the
scheduler (updated request) mints a new id; the scheduler's
`on_request_requeued` hook copies the owner across so the completion still
reaches the right chat.
"""
from __future__ import annotations
import queue
import re
import threading
from .base import GatewayAdapter, InboundMessage, OutboundMessage
_LEADING_RUN_ID = re.compile(r"^\[[0-9a-f]{6,}\]\s*")
_REPAIR_ACTIONS = {
"retry": "retry",
"repair": "repair_skill",
"repair_skill": "repair_skill",
"ask": "ask_user",
"ask_user": "ask_user",
"no": "no_repair",
"skip": "no_repair",
"no_repair": "no_repair",
}
def _strip_run_id(text: str) -> str:
return _LEADING_RUN_ID.sub("", text or "")
def _leading_run_id(text: str) -> str:
match = _LEADING_RUN_ID.match(text or "")
return match.group(0)[1:-2] if match else ""
class GatewayService:
def __init__(
self,
scheduler,
adapter: GatewayAdapter,
config: dict | None = None,
poll_interval: float = 1.0,
):
self.scheduler = scheduler
self.adapter = adapter
self.platform = adapter.name
cfg = config or {}
self.home_channel = str(cfg.get("home_channel", "") or "")
self.reply_prefix = str(cfg.get("reply_prefix", "") or "")
self.poll_interval = float(poll_interval)
self.outbound: "queue.Queue[OutboundMessage | None]" = queue.Queue()
self._owners: dict[str, str] = {}
self._parents: dict[str, str] = {}
self._pending_owner: str | None = None
self._question_for_chat: dict[str, str] = {}
self._repair_for_chat: dict[str, str] = {}
self._surfaced: set[str] = set()
self._route_lock = threading.Lock()
self._stop = threading.Event()
self._thread: threading.Thread | None = None
# ---- lifecycle ----
def start(self) -> None:
"""Start the background queue-drain loop (codegen re-queues, etc.)."""
self._thread = threading.Thread(target=self._poll_loop, daemon=True)
self._thread.start()
def stop(self) -> None:
self._stop.set()
if self._thread is not None:
self._thread.join(timeout=2.0)
self.outbound.put(None)
def _poll_loop(self) -> None:
while not self._stop.wait(self.poll_interval):
try:
with self._route_lock:
self.drain()
self.surface()
except Exception:
self.scheduler.trace.append("gateway_error", "?", phase="poll")
# ---- routing ----
def source_for(self, chat_id: str) -> str:
return f"{self.platform}:{chat_id}"
def _owner_from_source(self, source: str) -> str | None:
prefix = f"{self.platform}:"
if source.startswith(prefix):
return source[len(prefix):]
return None
def handle_inbound(self, msg: InboundMessage) -> None:
"""Handle one authorized inbound message. Called by the adapter."""
with self._route_lock:
reply_to = msg.chat_id
pending = self.scheduler.pending
if pending is not None and self._pending_owner is None:
self._pending_owner = self._owner_from_source(pending.request.source)
if pending is not None and pending.request.source == self.source_for(msg.chat_id):
status, detail = self.scheduler.answer(msg.text)
if self.scheduler.pending is None:
self._pending_owner = None
self._reply(reply_to, detail)
elif pending is not None and self._pending_owner not in (None, msg.chat_id):
self._reply(
reply_to,
"I'm waiting for a reply in another conversation; please resend in a moment.",
)
elif msg.chat_id in self._question_for_chat:
question_id = self._question_for_chat.pop(msg.chat_id)
status, detail = self.scheduler.answer_question(question_id, msg.text)
self._surfaced.add(question_id)
self._reply(reply_to, detail)
elif msg.chat_id in self._repair_for_chat and msg.text.strip().lower() in _REPAIR_ACTIONS:
offer_id = self._repair_for_chat.pop(msg.chat_id)
action = _REPAIR_ACTIONS[msg.text.strip().lower()]
status, detail = self.scheduler.resolve_repair(offer_id, action)
self._surfaced.add(offer_id)
self._reply(reply_to, detail)
else:
status, detail, run_id = self.scheduler.submit_request(
msg.text, source=self.source_for(msg.chat_id)
)
if run_id:
self._owners[run_id] = msg.chat_id
if status == "needs_input":
self._pending_owner = msg.chat_id
self._reply(reply_to, detail)
self.drain()
self.surface(origin=msg.chat_id)
def drain(self) -> None:
"""Run queued work and route each outcome back to its owner."""
for _ in range(100):
results = self.scheduler.run_queue()
if not results:
break
for status, detail in results:
run_id = _leading_run_id(detail)
chat = self._owner_of(run_id)
text = _strip_run_id(detail)
if status == "needs_input" and chat:
self._pending_owner = chat
if chat is None:
chat = self.home_channel
if chat:
self._reply(chat, text)
def surface(self, origin: str | None = None) -> None:
"""Send any newly posted authoring questions / repair offers."""
questions = self.scheduler.pending_questions()
live_ids = {q["id"] for q in questions}
self._question_for_chat = {
chat: qid for chat, qid in self._question_for_chat.items() if qid in live_ids
}
for item in questions:
if item["id"] in self._surfaced:
continue
self._surfaced.add(item["id"])
chat = self._owner_of(item["run_id"]) or origin or self.home_channel
if chat:
self._question_for_chat[chat] = item["id"]
self._reply(
chat,
f"(authoring {item['category']}.{item['skill']}) {item['question']}",
)
repairs = self.scheduler.pending_repairs()
live_ids = {r["id"] for r in repairs}
self._repair_for_chat = {
chat: rid for chat, rid in self._repair_for_chat.items() if rid in live_ids
}
for offer in repairs:
if offer["id"] in self._surfaced:
continue
self._surfaced.add(offer["id"])
chat = self._owner_of(offer["run_id"]) or origin or self.home_channel
if chat:
self._repair_for_chat[chat] = offer["id"]
self._reply(
chat,
(
f"{offer['category']}.{offer['skill']} failed: "
f"{offer['failure'][:200]}\nReply retry / repair / ask / no."
),
)
# ---- scheduler requeue hook (called under the scheduler lock) ----
def on_request_requeued(self, parent_id: str, child_id: str) -> None:
"""Copy run ownership across a scheduler requeue. Must not lock."""
owner = self._owners.get(parent_id)
if owner:
self._owners[child_id] = owner
self._parents[child_id] = parent_id
def _owner_of(self, run_id: str) -> str | None:
seen = 0
while run_id and seen < 16:
owner = self._owners.get(run_id)
if owner:
return owner
run_id = self._parents.get(run_id)
seen += 1
return None
# ---- outbound ----
def _reply(self, chat_id: str, text: str) -> None:
text = _strip_run_id(text)
if self.reply_prefix:
text = f"{self.reply_prefix}{text}"
if text:
self.outbound.put(OutboundMessage(chat_id=str(chat_id), text=text))
+231
View File
@@ -0,0 +1,231 @@
"""SimpleX Chat 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.
`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.
"""
from __future__ import annotations
import asyncio
import json
import queue
import random
import threading
from typing import Any
from .base import GatewayAdapter, InboundMessage, OutboundMessage
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))
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._buffers: dict[str, str] = {}
self._buffered: dict[str, InboundMessage] = {}
self._flush_tasks: dict[str, asyncio.Task] = {}
self._stop = threading.Event()
# ---- 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
# ---- authorization ----
def is_authorized(self, contact_id: str, display_name: str | None) -> bool:
if self.allow_all_users:
return True
candidates = {contact_id}
if display_name:
candidates.add(display_name)
if not self.allowed_users:
return False
return any(user in candidates for user in self.allowed_users)
# ---- transport ----
def run(
self,
on_inbound,
outbound: "queue.Queue[OutboundMessage | None]",
) -> None:
asyncio.run(self._serve(on_inbound, outbound))
def close(self) -> None:
self._stop.set()
async def _serve(self, on_inbound, outbound: "queue.Queue") -> None:
import websockets
backoff = self.reconnect_initial
while not self._stop.is_set():
try:
async with websockets.connect(self.ws_url, max_size=None) as 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])
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))
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)}"
# ---- inbound ----
async def _consume(self, raw: Any, on_inbound, ws) -> None:
try:
data = json.loads(raw)
except (TypeError, ValueError):
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 {}
if content.get("type") != "text":
return None
text = str(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 "")
display_name = contact.get("displayName") or contact.get("localDisplayName")
if not contact_id:
return None
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,
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
contact_id = (resp.get("contactRequest") or {}).get("contactId")
if contact_id is None:
return
self._corr += 1
await ws.send(
json.dumps({"corrId": f"sf-{self._corr}", "cmd": f"/_accept {contact_id}"})
)
self._event("gateway_accepted", contact_id=str(contact_id))
def _schedule_flush(self, message: InboundMessage, on_inbound) -> None:
chat = message.chat_id
existing = self._buffers.get(chat)
self._buffers[chat] = f"{existing}\n{message.text}" if existing else message.text
self._buffered[chat] = message
task = self._flush_tasks.get(chat)
if task is not None:
task.cancel()
self._flush_tasks[chat] = asyncio.ensure_future(self._flush(chat, on_inbound))
async def _flush(self, chat: str, on_inbound) -> None:
try:
await asyncio.sleep(self.batch_delay)
except asyncio.CancelledError:
return
text = self._buffers.pop(chat, "")
message = self._buffered.pop(chat, None)
self._flush_tasks.pop(chat, None)
if message is None or not text:
return
message.text = text
self._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)