From 6ab4d94423977ee1c7ecf90be8e6757b9c028939 Mon Sep 17 00:00:00 2001 From: Denton Social Date: Sat, 26 Sep 2026 10:13:56 -0500 Subject: [PATCH] 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. --- AGENTS.md | 73 ++++++++++ config.example.json | 14 ++ requirements/staging.txt | 5 +- semif_agent/cli.py | 74 ++++++++++ semif_agent/gateway/__init__.py | 12 ++ semif_agent/gateway/base.py | 65 +++++++++ semif_agent/gateway/service.py | 228 +++++++++++++++++++++++++++++ semif_agent/gateway/simplex.py | 231 ++++++++++++++++++++++++++++++ semif_agent/scheduler.py | 38 +++-- tests/test_gateway.py | 245 ++++++++++++++++++++++++++++++++ 10 files changed, 973 insertions(+), 12 deletions(-) create mode 100644 semif_agent/gateway/__init__.py create mode 100644 semif_agent/gateway/base.py create mode 100644 semif_agent/gateway/service.py create mode 100644 semif_agent/gateway/simplex.py create mode 100644 tests/test_gateway.py diff --git a/AGENTS.md b/AGENTS.md index 6148985..8aaa2f8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -114,6 +114,15 @@ decisions.py contract dataclasses (Option, DecisionRequest, DecisionResult, dashboard.py stdlib http.server + JSON API (tree/trace/dream/status/ questions/repairs + POST submit/answer/questions/repair/restart/ relabel); static/ frontend served at / +gateway/ messenger intake/reply. base.py: GatewayAdapter contract + + Inbound/OutboundMessage. service.py: GatewayService maps chats + onto the single-slot scheduler (submit_request, owner maps, + 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`). + Run with `python -m semif_agent.cli gateway [--dashboard]`; + config under `gateway.simplex` in config.json ``` ## Run / verify @@ -257,6 +266,18 @@ unit tests (24) + box integration tests (2). dashboard gain the ability to inspect a skill's generated code body (read-only view of `data/skills///` and its trace) so the author can audit what was generated. +- **Messenger gateway (SimpleX first)** (Sep 2026): `python -m semif_agent.cli + gateway` runs a dedicated process that connects to the local `simplex-chat` + daemon 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. `gateway/base.py` is the + transport contract (`GatewayAdapter`, `InboundMessage`, `OutboundMessage`), + `gateway/service.py` the scheduler glue (single execution slot, owner maps, + pending-run ownership, queue drain), `gateway/simplex.py` the SimpleX adapter + (lazy `websockets`, default-deny allowlist by contactId/display name, + rapid-message batching, structured `/_send`). DMs only for the first cut; + groups/attachments/reactions are future work. See "### gateway (messenger + intake)". ### Later / open questions - Safety/authority: which inputs may interrupt high-stakes processes; is @@ -523,6 +544,58 @@ unit tests (24) + box integration tests (2). available (`enabled` defaults true; the runtime engine check is what gates it off the box). +### gateway (messenger intake) + +- **Run mode.** `python -m semif_agent.cli gateway [--platform simplex] + [--dashboard]` builds the normal scheduler (engine lazy) and runs the + configured `gateway.simplex` adapter in the foreground. `--dashboard` + co-serves the browser UI from a daemon thread. Config lives under + `gateway.simplex` in `config.json`; `enabled` defaults false. The gateway is + its own process — the REPL and the gateway are independent front ends onto + the same on-disk logs/registry (do not run two scheduler processes over one + skill store concurrently). +- **Transport contract** (`gateway/base.py`): `GatewayAdapter.run(on_inbound, + outbound_queue)` blocks, delivering `InboundMessage`s and draining a stdlib + `queue.Queue[OutboundMessage | None]`. Scheduler work is synchronous and can + block on the decision engine, so the adapter bridges it off its event loop + (`asyncio.to_thread`) and puts replies on the queue. A second platform means + a new adapter subclass; the service is unchanged. +- **SimpleX adapter** (`gateway/simplex.py`): connects to `simplex-chat -p + 5225` at `gateway.simplex.ws_url`, XML-JSON WebSocket protocol + (`{"corrId","cmd"}` → `{"corrId","resp"}` / events). `websockets` is + **lazy-imported**; `check_requirements()` returns an install hint and the + gateway refuses to start without it, so the core stays importable on a + websocket-free machine. Default-deny allowlist matches either a numeric + `contactId` or a display name (`allowed_users`); `allow_all_users` is the + dev escape hatch. `auto_accept` answers `receivedContactRequest` with + `/_accept`. Inbound `newChatItems` are filtered to direct, non-echo + (`chatDir.type` not `*Snd`), text-only items, buffered per contact and + flushed after `text_batch_delay`. Outbound uses the **structured** command + `/_send @ json [{"msgContent":{"type":"text","text":...}}]` — the + `@ ` shortcut is silently rejected over WebSocket. Groups, + attachments, reactions, and typing are out of scope for this cut. +- **Scheduler glue** (`gateway/service.py`): inbound text → + `Scheduler.submit_request(text, source=f"simplex:")`; the returned + request id maps to the chat (`owners`), and `Scheduler.on_request_requeued` + (a scheduler hook, default `None`) copies that ownership across an updated + request so its completion still routes home. A `needs_input` pause sets + `pending_owner` from the pending run's source; the same chat's next message + goes straight to `Scheduler.answer` (no gate/score/navigation). A *different* + chat during another chat's pause is told to wait — the single-slot scheduler + must not silently abandon the first chat's run. A background poll calls + `Scheduler.run_queue()` (routing each `[run_id] summary` to its owner) and + surfaces newly posted authoring questions / repair offers (`defer_questions + = True`; the service routes them by `run_id` → origin, falling back to + `home_channel`); a chat's plain reply answers the question or picks the + repair action (`retry`/`repair`/`ask`/`no`). +- **Tests.** `tests/test_gateway.py` (stdlib, dev box): allowlist/auth, + `newChatItems` parsing + echo/group/non-text filtering, structured send + command, batching (real `asyncio`), and `GatewayService` routing against a + real `Scheduler` (lazy engine, unreachable LLM). 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. + ## Codegen guardrails backlog (one session per item) Context learned 2026-09-24 on the box: qwen38-iq3s looped ~40 min on one skill diff --git a/config.example.json b/config.example.json index 2e40e51..d696d23 100644 --- a/config.example.json +++ b/config.example.json @@ -72,5 +72,19 @@ "log": "data/decisions.jsonl", "trace": "data/runs.jsonl", "category_registry": "data/categories.json", + "gateway": { + "_comment": "Messenger intake. `python -m semif_agent.cli gateway` connects to the local simplex-chat daemon (simplex-chat -p 5225) 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.", + "simplex": { + "enabled": false, + "ws_url": "ws://127.0.0.1:5225", + "allowed_users": [], + "allow_all_users": false, + "auto_accept": true, + "home_channel": "", + "reply_prefix": "", + "text_batch_delay": 0.8, + "reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2} + } + }, "dashboard": {"port": 8765, "host": "0.0.0.0"} } \ No newline at end of file diff --git a/requirements/staging.txt b/requirements/staging.txt index f4d1a5e..637e170 100644 --- a/requirements/staging.txt +++ b/requirements/staging.txt @@ -12,4 +12,7 @@ transformers==5.17.0 tokenizers==0.23.2 huggingface-hub==1.31.0 llama-cpp-python==0.3.35 -pytest \ No newline at end of file +pytest +# Messaging gateway transport (SimpleX adapter). Optional: lazy-imported, the +# gateway refuses to start without it. Not needed by the decision engine. +websockets==15.0.1 \ No newline at end of file diff --git a/semif_agent/cli.py b/semif_agent/cli.py index 7fd28d2..f0343a9 100644 --- a/semif_agent/cli.py +++ b/semif_agent/cli.py @@ -286,6 +286,65 @@ def scripted(scheduler: Scheduler, path: str) -> None: print(f"[{status}] {detail}") +def run_gateway( + scheduler: Scheduler, + config: dict, + platform: str = "simplex", + serve_dashboard: bool = False, +) -> int: + """Run the messenger gateway in the foreground (SimpleX first).""" + cfg = (config.get("gateway", {}) or {}).get(platform, {}) or {} + if not cfg.get("enabled", False): + print(f"gateway.{platform} is not enabled in config") + return 1 + + if platform == "simplex": + from .gateway.simplex import SimplexAdapter + + adapter = SimplexAdapter(cfg, trace=scheduler.trace) + else: + print(f"unknown gateway platform {platform!r}") + return 1 + + ok, hint = adapter.check_requirements() + if not ok: + print(f"gateway {platform} unavailable: {hint}") + return 1 + + from .gateway.service import GatewayService + + scheduler.defer_questions = True + service = GatewayService(scheduler, adapter, config=cfg) + scheduler.on_request_requeued = service.on_request_requeued + service.start() + + if serve_dashboard: + import threading + + from .dashboard import serve + + dash_cfg = config.get("dashboard", {}) or {} + threading.Thread( + target=serve, + args=(scheduler,), + kwargs={ + "port": int(dash_cfg.get("port", 8765)), + "host": str(dash_cfg.get("host", "127.0.0.1")), + }, + daemon=True, + ).start() + + print(f"gateway {platform} listening on {adapter.ws_url} (Ctrl-C to stop)") + try: + adapter.run(service.handle_inbound, service.outbound) + except KeyboardInterrupt: + pass + finally: + service.stop() + adapter.close() + return 0 + + 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)) @@ -317,6 +376,14 @@ def main(argv: list[str] | None = None) -> int: help="replay mode: do not warm the decision engine", ) + gw_p = sub.add_parser("gateway", help="run the messenger gateway (SimpleX)") + gw_p.add_argument("--platform", default="simplex", help="gateway platform (default simplex)") + gw_p.add_argument( + "--dashboard", + action="store_true", + help="also serve the browser dashboard from the same process", + ) + args = parser.parse_args(argv) scheduler, config = build_scheduler(config) @@ -341,6 +408,13 @@ def main(argv: list[str] | None = None) -> int: if args.replay: print("replay mode: reading decision log + trace; engine not warmed.") serve(scheduler, port=args.port, host=args.host) + elif args.command == "gateway": + return run_gateway( + scheduler, + config, + platform=args.platform, + serve_dashboard=args.dashboard, + ) else: parser.print_help() return 0 diff --git a/semif_agent/gateway/__init__.py b/semif_agent/gateway/__init__.py new file mode 100644 index 0000000..e19138b --- /dev/null +++ b/semif_agent/gateway/__init__.py @@ -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"] diff --git a/semif_agent/gateway/base.py b/semif_agent/gateway/base.py new file mode 100644 index 0000000..a3d3bc3 --- /dev/null +++ b/semif_agent/gateway/base.py @@ -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:"`) + 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.""" diff --git a/semif_agent/gateway/service.py b/semif_agent/gateway/service.py new file mode 100644 index 0000000..0654b71 --- /dev/null +++ b/semif_agent/gateway/service.py @@ -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)) diff --git a/semif_agent/gateway/simplex.py b/semif_agent/gateway/simplex.py new file mode 100644 index 0000000..a019baf --- /dev/null +++ b/semif_agent/gateway/simplex.py @@ -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 `@ ` 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) diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 4c09a0b..7f03f9e 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -214,6 +214,7 @@ class Scheduler: regen_decision_factory: Callable[[str], Callable[[str], str] | None] | None = None, asker: Callable[[str], str | None] | None = None, + on_request_requeued: Callable[[str, str], None] | None = None, ): self.engine = engine self.llm = llm @@ -226,6 +227,7 @@ class Scheduler: self.degeneration_check_factory = degeneration_check_factory self.regen_decision_factory = regen_decision_factory self.asker = asker + self.on_request_requeued = on_request_requeued codegen_cfg = config.get("codegen", {}) or {} elicitation_cfg = codegen_cfg.get("elicitation", {}) or {} self.elicitation_enabled = bool(elicitation_cfg.get("enabled", True)) @@ -312,23 +314,34 @@ class Scheduler: def submit(self, text: str, source: str = "typed") -> tuple[str, str]: """Feed one input. Returns (status, detail).""" + status, detail, _ = self.submit_request(text, source) + return status, detail + + def submit_request( + self, text: str, source: str = "typed" + ) -> tuple[str, str, str]: + """Feed one input, also returning the request id. + + The id lets out-of-band interfaces (the messenger gateway) map a run + back to the chat that originated it. + """ from .engine import EngineUnavailable try: return self._submit(text, source) except EngineUnavailable as exc: - return "error", f"decision engine unavailable: {exc}" + return "error", f"decision engine unavailable: {exc}", "" - def _submit(self, text: str, source: str = "typed") -> tuple[str, str]: + def _submit(self, text: str, source: str = "typed") -> tuple[str, str, str]: with self._lock: return self._submit_locked(text, source) - def _submit_locked(self, text: str, source: str = "typed") -> tuple[str, str]: + def _submit_locked(self, text: str, source: str = "typed") -> tuple[str, str, str]: request = Request(text, source=source) self.trace.append("submit", request.id, text=text, source=source) if not self._contains_request(request): self.trace.append("dropped", request.id, reason="no actionable request") - return "dropped", "no actionable request" + return "dropped", "no actionable request", request.id if self.current is None: weight, label = self._score(request) @@ -339,9 +352,9 @@ class Scheduler: if self.pending is None: self.current = None if outcome.kind == "needs_input": - return "needs_input", outcome.summary + return "needs_input", outcome.summary, request.id self.trace.append("ran", request.id, skill=outcome.skill, summary=outcome.summary) - return "running", f"[{label}] {outcome.summary}" + return "running", f"[{label}] {outcome.summary}", request.id interrupt = self._choice(request, self.current) if interrupt: @@ -355,18 +368,18 @@ class Scheduler: self.trace.append("preempted", request.id, preempted=previous.skill) outcome = self._dispatch(request, weight=1.0) if outcome.kind == "needs_input": - return "preempted", f"interrupted {previous.skill}; {outcome.summary}" + return "preempted", f"interrupted {previous.skill}; {outcome.summary}", request.id self.current = None self.trace.append("ran", request.id, skill=outcome.skill, summary=outcome.summary) - return "preempted", f"interrupted {previous.skill}; {outcome.summary}" + return "preempted", f"interrupted {previous.skill}; {outcome.summary}", request.id weight, label = self._score(request, current=self.current.skill) ok = self.queue.push(request, weight) if not ok: self.trace.append("rejected", request.id, reason="queue is full") - return "rejected", "queue is full" + return "rejected", "queue is full", request.id self.trace.append("queued", request.id, weight=weight, label=label) - return "queued", f"urgency {label} (weight {weight:.2f})" + return "queued", f"urgency {label} (weight {weight:.2f})", request.id def busy(self, text: str, skill: str = "(driving)") -> None: """Set a fake in-progress process so the choice/score path is exercised.""" @@ -600,8 +613,11 @@ class Scheduler: updated_request=outcome.updated_request, ) if outcome.updated_request and request.reentries < self.max_reentries: - self.queue.push(_requeue(request, outcome.updated_request), 0.5) + child = _requeue(request, outcome.updated_request) + self.queue.push(child, 0.5) self.trace.append("requeued", request.id, text=outcome.updated_request) + if self.on_request_requeued is not None: + self.on_request_requeued(request.id, child.id) if not outcome.success and not outcome.updated_request: self._propose_repair(skill, request, outcome) return DispatchResult( diff --git a/tests/test_gateway.py b/tests/test_gateway.py new file mode 100644 index 0000000..6dd2c71 --- /dev/null +++ b/tests/test_gateway.py @@ -0,0 +1,245 @@ +"""Pure-stdlib tests for the messenger gateway (SimpleX adapter + router). + +The decision engine is never loaded and the LLM endpoint is unreachable, so +scheduler calls degrade to errors — which is fine: these tests exercise the +gateway's own routing, authorization, parsing, and batching. The real +`websockets` transport against a live `simplex-chat` daemon is a jarvis +integration concern, not a dev-box unit test. +""" + +import asyncio +import json + +from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Request +from semif_agent.engine import EngineConfig, SemIfEngine +from semif_agent.gateway.base import InboundMessage +from semif_agent.gateway.service import GatewayService +from semif_agent.gateway.simplex import SimplexAdapter +from semif_agent.llm import LLMClient +from semif_agent.log import DecisionLog +from semif_agent.scheduler import Scheduler +from semif_agent.skills import ActionResult, Prediction, Skill +from semif_agent.trace import TraceLog + + +def build_scheduler(tmp_path): + log = DecisionLog(str(tmp_path / "decisions.jsonl")) + trace = TraceLog(str(tmp_path / "runs.jsonl")) + engine = SemIfEngine(EngineConfig()) + llm = LLMClient(base_url="http://localhost:1/v1", model="test") + return Scheduler( + engine=engine, + llm=llm, + log=log, + config={"skills": {}, "skill_seeds": str(tmp_path / "seeds")}, + trace=trace, + ) + + +def drain_outbound(service) -> list[str]: + texts = [] + while not service.outbound.empty(): + item = service.outbound.get_nowait() + if item is not None: + texts.append(item.text) + return texts + + +# ---- adapter: authorization ---- + +def test_default_deny_and_allowlist(): + assert SimplexAdapter({}).is_authorized("4", "alice") is False + assert SimplexAdapter({"allowed_users": ["4"]}).is_authorized("4", "alice") is True + assert SimplexAdapter({"allowed_users": ["alice"]}).is_authorized("4", "alice") is True + assert SimplexAdapter({"allowed_users": ["bob"]}).is_authorized("4", "alice") is False + assert SimplexAdapter({"allow_all_users": True}).is_authorized("7", None) is True + + +# ---- adapter: requirements ---- + +def test_check_requirements_needs_url(): + ok, hint = SimplexAdapter({"ws_url": ""}).check_requirements() + assert ok is False + assert "ws_url" in hint + + +# ---- adapter: parsing ---- + +def direct_item(text="hello", contact_id="4", display="alice", direction="directRcv", kind="text"): + return { + "chatInfo": { + "type": "direct", + "chatId": contact_id, + "contact": {"contactId": contact_id, "displayName": display}, + }, + "chatItem": { + "chatDir": {"type": direction}, + "content": {"type": kind, "text": text}, + }, + } + + +def test_parse_authorized_direct_text(): + adapter = SimplexAdapter({"allowed_users": ["4"]}) + message = adapter._parse_chat_item(direct_item()) + assert message is not None + assert message.text == "hello" + assert message.chat_id == "4" + assert message.contact_id == "4" + assert message.display_name == "alice" + + +def test_parse_filters_echo_group_and_non_text(): + adapter = SimplexAdapter({"allow_all_users": True}) + assert adapter._parse_chat_item(direct_item(direction="directSnd")) is None + assert adapter._parse_chat_item(direct_item(kind="image")) is None + group = direct_item() + group["chatInfo"]["type"] = "group" + assert adapter._parse_chat_item(group) is None + + +def test_parse_filters_unauthorized_contact(): + adapter = SimplexAdapter({"allowed_users": ["9"]}) + assert adapter._parse_chat_item(direct_item(contact_id="4", display="alice")) is None + + +# ---- adapter: send command ---- + +def test_send_command_is_structured_not_shortcut(): + adapter = SimplexAdapter({}) + command = adapter.send_command("4", "hello") + assert command.startswith("/_send @4 json ") + payload = json.loads(command.split(" json ", 1)[1]) + assert payload[0]["msgContent"]["type"] == "text" + assert payload[0]["msgContent"]["text"] == "hello" + assert command != "/_send @4 hello" + + +# ---- adapter: batching ---- + +def test_batching_concatenates_rapid_messages(): + adapter = SimplexAdapter({"allow_all_users": True, "text_batch_delay": 0.05}) + seen = [] + + async def go(): + adapter._schedule_flush( + InboundMessage(text="one", chat_id="4", contact_id="4"), seen.append + ) + adapter._schedule_flush( + InboundMessage(text="two", chat_id="4", contact_id="4"), seen.append + ) + await asyncio.sleep(0.2) + + asyncio.run(go()) + assert len(seen) == 1 + assert "one" in seen[0].text and "two" in seen[0].text + + +# ---- service: routing ---- + +def need_input_skill(seen): + def predict(ctx, request): + return Prediction(text="", decisions=[]) + + def act(ctx, request, prediction): + if request.user_input: + seen.append(request.user_input) + return ActionResult(action_log=f"got {request.user_input}", new_state="done") + return ActionResult( + action_log="ask", new_state=request.text, needs_input="Tracking number?" + ) + + return Skill( + name="track.manual", + category="tracking", + description="Resolve a tracking number with the human.", + predict=predict, + act=act, + ) + + +class FakeAdapter: + name = "simplex" + + +def build_service(scheduler): + return GatewayService(scheduler, FakeAdapter(), config={}) + + +def test_service_submit_error_is_replied(tmp_path): + scheduler = build_scheduler(tmp_path) + service = build_service(scheduler) + service.handle_inbound(InboundMessage(text="hi", chat_id="4", contact_id="4")) + outbound = drain_outbound(service) + assert outbound, "expected a reply" + assert "unavailable" in outbound[-1] + + +def test_service_routes_pending_answer_to_same_chat(tmp_path): + scheduler = build_scheduler(tmp_path) + service = build_service(scheduler) + seen = [] + scheduler._run_skill( + need_input_skill(seen), Request("track it", source="simplex:4") + ) + assert scheduler.pending is not None + + service.handle_inbound(InboundMessage(text="AB123", chat_id="4", contact_id="4")) + assert seen == ["AB123"] + assert scheduler.pending is None + assert any("AB123" in text for text in drain_outbound(service)) + + +def test_service_refuses_other_chat_during_pending(tmp_path): + scheduler = build_scheduler(tmp_path) + service = build_service(scheduler) + scheduler._run_skill(need_input_skill([]), Request("track it", source="simplex:4")) + question = scheduler.pending.question + + service.handle_inbound(InboundMessage(text="hello", chat_id="7", contact_id="7")) + assert scheduler.pending is not None + assert scheduler.pending.question == question + assert any("another conversation" in text for text in drain_outbound(service)) + + +def test_service_requeue_hook_carries_ownership(tmp_path): + scheduler = build_scheduler(tmp_path) + service = build_service(scheduler) + service._owners["parent"] = "4" + service.on_request_requeued("parent", "child") + assert service._owner_of("child") == "4" + + +def test_service_drain_routes_queued_run_to_owner(tmp_path): + scheduler = build_scheduler(tmp_path) + service = build_service(scheduler) + request = Request("queued work", source="simplex:4") + scheduler.queue.push(request, 0.5) + service._owners[request.id] = "4" + + service.drain() + outbound = drain_outbound(service) + assert any("queued work" in text or "unavailable" in text or "failed" in text for text in outbound) + + +def test_service_answered_question_routes_back(tmp_path): + scheduler = build_scheduler(tmp_path) + service = build_service(scheduler) + # Post a deferred question as the codegen worker would. + from semif_agent.scheduler import PendingQuestion + import uuid + scheduler.questions.append( + PendingQuestion( + id=uuid.uuid4().hex[:12], + run_id="r1", + category="c", + skill="s", + question="Which account?", + ) + ) + service._owners["r1"] = "4" + service.surface() + assert any("Which account?" in text for text in drain_outbound(service)) + + service.handle_inbound(InboundMessage(text="work", chat_id="4", contact_id="4")) + assert not scheduler.pending_questions()