gateway: serve a local messaging bridge so skills can send/read SimpleX

The gateway now exposes a localhost stdlib HTTP API (bridge.py) that
buffers authorized inbound DMs and forwards outbound sends, so a skill
body never opens a WebSocket to the simplex-chat daemon. Endpoints:
GET /health, /contacts, /inbox (peek), /inbox/next (pop oldest unread),
POST /send (resolve id/display name onto the adapter's outbound queue).
GatewayService gains an observer hook and inbox.dispatch (pull-only mode).

Expose the capability to codegen (SKILL.md, BODY_DIRECTIVES, elicitation,
TESTGEN.md) and add the simplex.next_message seed (SemIf recipient
resolution) with its hermetic loopback test. Config: messaging_bridge_url
plus gateway.simplex.{inbox,bridge}; bootstrap keeps them in sync.
This commit is contained in:
Denton Social committed 2026-09-26 21:39:39 -05:00
1 parent b348f19486
commit 08d6bb23e2
19 files changed
+1006 -29

No files matched your search

+33 -5
View File
@@ -121,8 +121,13 @@ gateway/ messenger intake/reply. base.py: GatewayAdapter contract +
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
bridge.py: MessagingBridge — a localhost stdlib HTTP API the
gateway serves so skills can send/read SimpleX messages without
touching the daemon (`/health`, `/contacts`, `/inbox`,
`/inbox/next`, `/send`); owns the read cursor (bounded inbox),
reuses the adapter's outbound queue. Run with `python -m
semif_agent.cli gateway [--dashboard]`; config under
`gateway.simplex` in config.json
```
## Run / verify
@@ -644,11 +649,34 @@ unit tests (24) + box integration tests (2).
= 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`).
- **Messaging bridge (skills send/read SimpleX)** (`gateway/bridge.py`,
Sep 2026): the gateway serves a **localhost stdlib HTTP API** so a skill body
never opens a WebSocket to the daemon. `run_gateway` starts a `MessagingBridge`
(`gateway.simplex.bridge`: `enabled` default true, `host`/`port` default
`127.0.0.1:5227`, optional `token` checked as `X-Semif-Token`, `max_inbox`)
and wires `service.observer = bridge.record_inbound`. Endpoints: `GET
/health`, `GET /contacts`, `GET /inbox` (peek), `GET /inbox/next?contact=<id>`
(pop oldest unread — the bridge owns the cursor), `POST /send`
`{"recipient": "<id|display_name>", "text"}` (resolves a numeric id or a known
display name and enqueues on the adapter's existing outbound queue). The
top-level `messaging_bridge_url` config is the skill-facing address (the data
contract's config search auto-populates it); bootstrap keeps it in sync with
the bridge port. `gateway.simplex.inbox.dispatch` (default true) preserves the
current push behavior while buffering every authorized inbound for reads; set
false for pull-only mode (buffer without scheduling). Skills reach the bridge
with the ordinary `http` transport, so their hermetic tests are loopback HTTP
like any other HTTP body. Recipient resolution is a SemIf sub-decision; no
mark-read command exists in the v7 API and contact-list refresh from the
daemon (`/_contacts`) is a follow-up.
- **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.
command, batching (real `asyncio`), `GatewayService` routing against a
real `Scheduler` (lazy engine, unreachable LLM), the observer hook, and
pull mode. `tests/test_gateway_bridge.py` exercises the bridge over a real
loopback server (peek/pop, recipient resolution, outbound routing, token/body
validation). `tests/test_seed_skills.py` hermetically tests every
`seeds/<category>/<name>/` package, including `simplex.next_message`. 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.
+52
View File
@@ -150,6 +150,55 @@ talk to. Declaring a transport the body does not use is a broken skill.
- **Names match the manifest.** The module is imported as its manifest name;
the functions are `predict` and `act` exactly.
## Messaging through the gateway bridge
The agent can read and send SimpleX messages on the user's behalf. A skill
never opens a WebSocket to the `simplex-chat` daemon: the running messenger
gateway exposes a local HTTP bridge, and that is the only messaging surface a
body touches. Declare it like any other HTTP integration:
```python
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": ["messaging_bridge_url", "simplex_default_contact"],
}
```
`messaging_bridge_url` is the bridge base URL (e.g. `http://127.0.0.1:5227`),
supplied by the runner through `ctx.config`. Call it with `urllib.request`:
| Request | Purpose |
| -------------------------------------- | ------------------------------------------------------------------ |
| `GET <base>/health` | `{"ok": true}` — the bridge is up. |
| `GET <base>/contacts` | `{"contacts": [{"id", "display_name"}]}` — known contacts. |
| `GET <base>/inbox` | Peek buffered inbound messages; does not consume. |
| `GET <base>/inbox/next?contact=<id>` | Pop the oldest unread message (optionally from one contact). |
| `POST <base>/send` | `{"recipient": "<id\|display_name>", "text": "..."}` — send. |
`GET /inbox` returns `{"messages": [{"id", "contact_id", "display_name", "text",
"received_at"}]}`; `GET /inbox/next` returns `{"message": {...} | null}`, where
`null` means nothing is buffered. `POST /send` returns
`{"ok": true, "contact_id": "<id>"}`. The bridge owns the read cursor, so a
read skill needs no state of its own.
Rules:
- **Recipient selection is a SemIf decision.** When more than one conversation
is relevant (e.g. several have buffered messages), resolve which one with a
`ctx.engine.call(...)` sub-decision over the contacts — mirroring how
`calendar.next_event` picks a calendar. Use `simplex_default_contact` only as
the configured fallback when the request does not already make it clear.
- **Sending requires user intent.** Send only because the request (or the
requirements) asks for it. Never broadcast, never message a contact the user
did not name or confirm, and never fabricate a message body as a working
value.
- **Report real failures.** A bridge error, an unknown recipient, or an empty
inbox is reported honestly in `action_log` / `new_state`; never claim a
message was sent or read when it was not.
- The bridge is local-only, but its URL still comes from `ctx.config` — never
hardcode a host, port, or bridge address in the body.
## Conventions
- Single purpose, single file, single module.
@@ -183,6 +232,9 @@ A generated skill is accepted only if:
and reports real failures honestly.
8. `INTEGRATION` is present, flat, string-valued, uses the transport vocabulary,
and is consistent with the body's `ctx.config` reads and behavior.
9. If it is a messaging skill, it uses the gateway bridge over HTTP (never the
daemon WebSocket), resolves recipients with a SemIf sub-decision, and sends
only on explicit user intent.
## Worked example
+4
View File
@@ -74,6 +74,10 @@ A stdlib-only Python script that:
Assert the server actually received the expected request (method, path,
headers, body) where practical. The loopback address exists only in the test;
the body must read its endpoint from config.
- For a messaging skill (a body that talks to the gateway bridge), stand up a
loopback server implementing the bridge endpoints the body uses (`GET /inbox`,
`GET /inbox/next?contact=`, `POST /send`) and assert the body built the real
requests. Never connect to a real `simplex-chat` daemon or the live bridge.
- For non-HTTP transports (IMAP, SMTP, subprocess, ...), exercise config
resolution, argument construction, and error paths (missing or misconfigured
values) without performing the real I/O.
+15 -1
View File
@@ -73,6 +73,7 @@
},
"skill_bodies": "data/skills",
"skill_seeds": "seeds",
"messaging_bridge_url": "http://127.0.0.1:5227",
"log": "data/decisions.jsonl",
"trace": "data/runs.jsonl",
"category_registry": "data/categories.json",
@@ -95,7 +96,20 @@
"home_channel": "",
"reply_prefix": "",
"text_batch_delay": 0.8,
"reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2}
"reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2},
"inbox": {
"_comment": "Buffer every authorized inbound DM so a read skill can pull it (see `messaging_bridge_url`). dispatch=true keeps the current behavior (also submit the message as a scheduler request); set dispatch=false for pull-only mode, where inbound messages are buffered and only acted on when the user asks.",
"dispatch": true,
"max_size": 100
},
"bridge": {
"_comment": "Local HTTP API the gateway serves to skills (send/read SimpleX messages). Skills call it over `http` with the top-level `messaging_bridge_url`; keep that URL in sync with host/port. Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. Set enabled=false to run the gateway without the bridge.",
"enabled": true,
"host": "127.0.0.1",
"port": 5227,
"token": "",
"max_inbox": 100
}
}
},
"dashboard": {"port": 8765, "host": "0.0.0.0"}
+9
View File
@@ -280,6 +280,12 @@ simplex["enabled"] = True
simplex["ws_url"] = f"ws://127.0.0.1:{cfg['simplex_chat'].get('port', 5226)}"
simplex["allowed_users"] = allowed
simplex["home_channel"] = home_channel
# The gateway serves a localhost HTTP bridge that skills use to send/read
# SimpleX messages; expose its address as the top-level `messaging_bridge_url`
# so the data-contract config search auto-populates it.
bridge_port = int(simplex.get("bridge", {}).get("port", 5227))
simplex.setdefault("bridge", {})["enabled"] = True
cfg["messaging_bridge_url"] = f"http://127.0.0.1:{bridge_port}"
json.dump(cfg, open(out, "w"), indent=2)
PY
@@ -427,4 +433,7 @@ SimpleX gateway:
gateway.simplex.allowed_users (discover the id from a 'gateway_denied' trace
event or the daemon's /contacts) and reply. With an empty allowlist the
gateway rejects everyone — that is the safe default.
- Skills send/read SimpleX messages through the gateway's local HTTP bridge
(config.json top-level messaging_bridge_url, default
http://127.0.0.1:5227); nothing else is needed while the gateway runs.
EOF
+4
View File
@@ -0,0 +1,4 @@
{
"messaging_bridge_url": "Base URL of the messenger gateway's local HTTP bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_default_contact": "Optional display name or contact id to read from by default when the conversation is not otherwise clear; leave blank to always choose among the conversations with unread messages."
}
+3
View File
@@ -0,0 +1,3 @@
{
"description": "Read the next unread SimpleX message through the messenger gateway."
}
+143
View File
@@ -0,0 +1,143 @@
"""Read the next unread SimpleX message through the messenger gateway.
Real integration: the running messenger gateway serves a local HTTP bridge
(`messaging_bridge_url`) that buffers every inbound DM and forwards outbound
sends. `predict` peeks that inbox, finds which conversations have unread
messages, and resolves which one to read with a SemIf sub-decision when more
than one does (honoring a configured default contact); `act` pops and reports
the oldest unread message for that conversation.
The bridge owns the read cursor, so this skill keeps no state of its own. It
never opens a WebSocket to the `simplex-chat` daemon — the bridge is the only
messaging surface it uses.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.parse
import urllib.request
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult, Prediction
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": ["messaging_bridge_url", "simplex_default_contact"],
}
TIMEOUT_SECONDS = 20
class BridgeError(Exception):
"""The local messaging bridge is unreachable or returned an error."""
def _base(ctx):
url = str(ctx.config.get("messaging_bridge_url", "") or "").strip().rstrip("/")
if not url:
raise BridgeError("messaging_bridge_url is not configured")
return url
def _get(ctx, path):
request = urllib.request.Request(_base(ctx) + path)
try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"GET {path}: {exc}") from exc
def _senders(messages):
"""Distinct conversations with buffered messages, in arrival order."""
senders = []
seen = set()
for message in messages:
contact = str(message.get("contact_id") or "")
if not contact or contact in seen:
continue
seen.add(contact)
senders.append(
{"id": contact, "display_name": message.get("display_name") or contact}
)
return senders
def _match_default(senders, default):
default = str(default or "").strip()
if not default:
return None
for sender in senders:
if sender["id"] == default or sender["display_name"] == default:
return sender["id"]
return None
def predict(ctx, request):
try:
payload = _get(ctx, "/inbox")
except BridgeError as exc:
return Prediction(text=f"bridge error: {exc}")
senders = _senders(payload.get("messages") or [])
if not senders:
return Prediction(text="settled: no unread messages")
chosen = _match_default(senders, ctx.config.get("simplex_default_contact", ""))
if chosen is not None:
return Prediction(text=f"contact: {chosen}")
if len(senders) == 1:
return Prediction(text=f"contact: {senders[0]['id']}")
decision = DecisionRequest(
state=request.text,
question="Which conversation should I read the next SimpleX message from?",
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
)
result = ctx.engine.call(decision)
return Prediction(
text=f"contact: {result.selected}",
decisions=[(decision, result)],
)
def act(ctx, request, prediction):
text = prediction.text if prediction else ""
if text.startswith("bridge error:"):
return ActionResult(action_log=text, new_state=request.text)
if text == "settled: no unread messages":
return ActionResult(
action_log="simplex.next_message: no unread SimpleX messages.",
new_state="no unread SimpleX messages",
)
contact = text.removeprefix("contact: ").strip()
if not contact:
return ActionResult(
action_log=(
"simplex.next_message aborted: no conversation resolved "
f"({text or 'no prediction'})."
),
new_state=request.text,
)
try:
payload = _get(
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
)
except BridgeError as exc:
return ActionResult(
action_log=f"simplex.next_message failed reading {contact!r}: {exc}",
new_state=request.text,
)
message = payload.get("message")
if not message:
return ActionResult(
action_log=f"simplex.next_message: no unread message from {contact!r}.",
new_state="no unread SimpleX messages",
)
sender = message.get("display_name") or contact
body = str(message.get("text") or "")
report = f"SimpleX message from {sender}: {body}"
return ActionResult(action_log=report, new_state=report)
+209
View File
@@ -0,0 +1,209 @@
"""Hermetic mechanics test for simplex.next_message.
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the messenger gateway's bridge. This proves the body peeks the
inbox, resolves the conversation through a SemIf sub-decision (or a configured
default), pops the real `next` message, and fails honestly when the bridge is
unreachable. It does NOT prove the live integration — only a real run against
the gateway and a real contact does.
"""
import json
import sys
import threading
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import DecisionResult, Request
from semif_agent.skills import ActionContext
import skill
class FakeEngine:
"""Test-only engine: picks the requested option id, else the first."""
def __init__(self, pick=None):
self.pick = pick
self.decisions = []
def call(self, decision):
self.decisions.append(decision)
option_ids = [option.id for option in decision.options]
chosen = self.pick if self.pick in option_ids else option_ids[0]
probabilities = [
1.0 if option_id == chosen else 0.0 for option_id in option_ids
]
return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities
)
class BridgeHandler(BaseHTTPRequestHandler):
messages = []
requests = []
def _send(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
self.requests.append(self.path)
url = urllib.parse.urlparse(self.path)
if url.path == "/inbox":
self._send({"messages": list(self.messages)})
elif url.path == "/inbox/next":
contact = (urllib.parse.parse_qs(url.query).get("contact") or [None])[0]
found = None
for index, message in enumerate(self.messages):
if contact is None or message["contact_id"] == str(contact):
found = self.messages.pop(index)
break
self._send({"message": found})
else:
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(messages):
handler = type("Handler", (BridgeHandler,), {"messages": list(messages), "requests": []})
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def message(identifier, contact, name, text):
return {
"id": identifier,
"contact_id": contact,
"display_name": name,
"text": text,
"received_at": 1.0,
}
def config(url, default=""):
return {"messaging_bridge_url": url, "simplex_default_contact": default}
def test_multiple_senders_uses_semif_decision():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(pick="7")
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text == "contact: 7", prediction.text
assert len(prediction.decisions) == 1, "predict must log the conversation choice"
assert len(engine.decisions) == 1
action = skill.act(ctx, request, prediction)
assert "Bob" in action.action_log, action.action_log
assert "shipment arrived" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
assert handler.requests[0] == "/inbox", handler.requests
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
assert [m["id"] for m in handler.messages] == ["m1"], "the popped message must be consumed"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_default_contact_skips_decision():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text == "contact: 4", prediction.text
assert engine.decisions == [], "a configured default needs no SemIf decision"
action = skill.act(ctx, request, prediction)
assert "Alice" in action.action_log, action.action_log
assert handler.requests[1] == "/inbox/next?contact=4", handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_single_sender_needs_no_decision():
server, handler, url = start_server([message("m1", "4", "Alice", "hi")])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text == "contact: 4", prediction.text
assert engine.decisions == []
action = skill.act(ctx, request, prediction)
assert "hi" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_inbox_is_reported_honestly():
server, handler, url = start_server([])
try:
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text == "settled: no unread messages", prediction.text
action = skill.act(ctx, request, prediction)
assert "no unread" in action.action_log, action.action_log
assert handler.requests == ["/inbox"], "an empty inbox needs no pop"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
engine = FakeEngine()
ctx = ActionContext(engine=engine, config=config("http://127.0.0.1:1"))
request = Request("read my next simplex message")
prediction = skill.predict(ctx, request)
assert prediction.text.startswith("bridge error:"), prediction.text
action = skill.act(ctx, request, prediction)
assert action.action_log.startswith("bridge error:"), action.action_log
assert action.new_state == request.text, "a failed read must not fake a result"
print(action.action_log)
def main():
test_multiple_senders_uses_semif_decision()
test_default_contact_skips_decision()
test_single_sender_needs_no_decision()
test_empty_inbox_is_reported_honestly()
test_unreachable_bridge_fails_honestly()
print("ok")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAILED: {exc}")
sys.exit(1)
+15
View File
@@ -318,6 +318,19 @@ 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)
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
@@ -342,6 +355,8 @@ def run_gateway(
finally:
service.stop()
adapter.close()
if bridge is not None:
bridge.stop()
return 0
+7
View File
@@ -633,6 +633,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"
)
@@ -1061,6 +1067,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)?",
]
+11 -1
View File
@@ -7,6 +7,16 @@ chat. See `base.py` for the contract.
"""
from .base import GatewayAdapter, InboundMessage, OutboundMessage
from .bridge import MessagingBridge, MessagingInbox, start_bridge
from .service import GatewayService
__all__ = ["GatewayAdapter", "InboundMessage", "OutboundMessage", "GatewayService"]
__all__ = [
"GatewayAdapter",
"InboundMessage",
"OutboundMessage",
"GatewayService",
"MessagingBridge",
"MessagingInbox",
"start_bridge",
]
+252
View File
@@ -0,0 +1,252 @@
"""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}
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`.
"""
name = "simplex"
def __init__(
self,
outbound: "queue.Queue[OutboundMessage | None]",
config: dict | None = 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._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)})
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,
) -> tuple[MessagingBridge, int]:
bridge = MessagingBridge(outbound, config=config)
port = bridge.start()
return bridge, port
+14
View File
@@ -59,6 +59,13 @@ 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] = {}
@@ -106,6 +113,13 @@ class GatewayService:
def handle_inbound(self, msg: InboundMessage) -> None:
"""Handle one authorized inbound message. 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:
+17 -4
View File
@@ -357,7 +357,7 @@ def _respond_show(handler, body: dict | None = None) -> bool:
if not handler.path.endswith("/api/show"):
return False
encoded = json.dumps(
body if body is not None else {"parameters": {"num_ctx": 4242}}
body if body is not None else {"parameters": {"num_ctx": 32768}}
).encode("utf-8")
handler.send_response(200)
handler.send_header("Content-Type", "application/json")
@@ -369,7 +369,7 @@ def _respond_show(handler, body: dict | None = None) -> bool:
class _FakeOpenAI(BaseHTTPRequestHandler):
"""Single-shot SSE server: the reply arrives as one content delta. The
`/api/show` window query is answered too (default num_ctx 4242) but never
`/api/show` window query is answered too (default num_ctx 32768) but never
recorded in `received`, so chat-payload assertions stay unambiguous."""
reply: str = GOOD_BODY
@@ -858,7 +858,7 @@ def test_chat_stream_false_returns_content_without_echo(capsys):
class _UsageOpenAI(BaseHTTPRequestHandler):
"""Streams a small content delta, then the exact-token usage chunk
(`choices: []` — OpenAI's shape when include_usage is set) before
[DONE]. The `/api/show` window query is answered (default num_ctx 4242)
[DONE]. The `/api/show` window query is answered (default num_ctx 32768)
and never recorded."""
usage: dict = {"prompt_tokens": 5, "completion_tokens": 10, "total_tokens": 15}
@@ -1208,7 +1208,7 @@ def test_degeneration_disabled_no_callback_no_abort():
class _SequencedOpenAI(BaseHTTPRequestHandler):
"""Returns one reply per chat request, in order; counts chat calls.
`/api/show` is answered (default num_ctx 4242) and never counted, so chat
`/api/show` is answered (default num_ctx 32768) and never counted, so chat
payload and retry-count assertions stay unambiguous.
"""
@@ -1680,6 +1680,19 @@ def test_skill_contract_lists_all_transports():
assert transport in text
def test_skill_contract_documents_messaging_bridge():
text = read_skill_contract()
assert "messaging_bridge_url" in text
assert "/inbox/next" in text
assert "/send" in text
assert "never opens a WebSocket" in text
def test_body_directives_expose_messaging_bridge():
assert "messaging_bridge_url" in BODY_DIRECTIVES
assert "never open a WebSocket" in BODY_DIRECTIVES
def test_body_prompts_require_real_action_and_integration():
tree = build_tree(build_skills({"skills": {}}))
draft = SkillDraft(name="probe", description="Probe the service.")
+21
View File
@@ -340,3 +340,24 @@ def test_service_answered_question_routes_back(tmp_path):
service.handle_inbound(InboundMessage(text="work", chat_id="4", contact_id="4"))
assert not scheduler.pending_questions()
def test_service_observer_sees_authorized_inbound(tmp_path):
scheduler = build_scheduler(tmp_path)
service = build_service(scheduler)
seen = []
service.observer = seen.append
service.handle_inbound(InboundMessage(text="hi", chat_id="4", contact_id="4"))
assert [m.text for m in seen] == ["hi"]
def test_service_pull_mode_buffers_without_dispatch(tmp_path):
scheduler = build_scheduler(tmp_path)
service = GatewayService(scheduler, FakeAdapter(), config={"inbox": {"dispatch": False}})
seen = []
service.observer = seen.append
service.handle_inbound(InboundMessage(text="hi", chat_id="4", contact_id="4"))
assert [m.text for m in seen] == ["hi"], "pull mode must still buffer for a read skill"
assert drain_outbound(service) == [], "pull mode must not reply or dispatch"
assert scheduler.current is None
assert scheduler.pending is None
+162
View File
@@ -0,0 +1,162 @@
"""Pure-stdlib tests for the gateway's local messaging bridge.
The bridge is exercised over a real loopback HTTP server (no mocking of its
transport); the decision engine and LLM are never involved. These prove the
mechanics a skill depends on: peek/pop of buffered inbound messages, recipient
resolution, outbound routing onto the adapter queue, and token/body validation.
"""
import json
import queue
import urllib.error
import urllib.request
import pytest
from semif_agent.gateway.base import InboundMessage, OutboundMessage
from semif_agent.gateway.bridge import MessagingBridge
def start_bridge(**config):
outbound = queue.Queue()
bridge = MessagingBridge(outbound, config=config)
port = bridge.start()
return bridge, outbound, f"http://127.0.0.1:{port}"
def inbound(text, contact_id="4", display_name="Alice"):
return InboundMessage(
text=text, chat_id=contact_id, contact_id=contact_id, display_name=display_name
)
def get(url, token=None):
headers = {"X-Semif-Token": token} if token else {}
request = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(request, timeout=5) as response:
return json.loads(response.read().decode("utf-8"))
def post(url, payload, token=None):
body = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json"}
if token:
headers["X-Semif-Token"] = token
request = urllib.request.Request(url, data=body, headers=headers)
with urllib.request.urlopen(request, timeout=5) as response:
return json.loads(response.read().decode("utf-8"))
def test_health_and_contacts():
bridge, _, base = start_bridge()
try:
assert get(f"{base}/health") == {"ok": True, "platform": "simplex"}
bridge.record_inbound(inbound("hi", contact_id="4", display_name="Alice"))
assert get(f"{base}/contacts") == {
"contacts": [{"id": "4", "display_name": "Alice"}]
}
finally:
bridge.stop()
def test_inbox_peek_then_pop_consumes_oldest():
bridge, _, base = start_bridge()
try:
bridge.record_inbound(inbound("first", contact_id="4", display_name="Alice"))
bridge.record_inbound(inbound("second", contact_id="7", display_name="Bob"))
peeked = get(f"{base}/inbox")["messages"]
assert [m["text"] for m in peeked] == ["first", "second"]
assert get(f"{base}/inbox")["messages"] == peeked, "peek must not consume"
popped = get(f"{base}/inbox/next")["message"]
assert popped["text"] == "first"
assert popped["contact_id"] == "4"
remaining = get(f"{base}/inbox")["messages"]
assert [m["text"] for m in remaining] == ["second"]
finally:
bridge.stop()
def test_inbox_next_filters_by_contact():
bridge, _, base = start_bridge()
try:
bridge.record_inbound(inbound("first", contact_id="4", display_name="Alice"))
bridge.record_inbound(inbound("second", contact_id="7", display_name="Bob"))
popped = get(f"{base}/inbox/next?contact=7")["message"]
assert popped["text"] == "second"
assert get(f"{base}/inbox/next?contact=7")["message"] is None
assert [m["text"] for m in get(f"{base}/inbox")["messages"]] == ["first"]
finally:
bridge.stop()
def test_inbox_is_bounded():
bridge, _, base = start_bridge(max_inbox=2)
try:
for text in ("one", "two", "three"):
bridge.record_inbound(inbound(text))
messages = get(f"{base}/inbox")["messages"]
assert [m["text"] for m in messages] == ["two", "three"], "oldest must be dropped"
finally:
bridge.stop()
def test_send_routes_to_outbound_queue():
bridge, outbound, base = start_bridge()
try:
result = post(f"{base}/send", {"recipient": "7", "text": "on my way"})
assert result == {"ok": True, "contact_id": "7"}
message = outbound.get_nowait()
assert isinstance(message, OutboundMessage)
assert message.chat_id == "7"
assert message.text == "on my way"
finally:
bridge.stop()
def test_send_resolves_known_display_name():
bridge, outbound, base = start_bridge()
try:
bridge.record_inbound(inbound("hi", contact_id="4", display_name="Alice"))
result = post(f"{base}/send", {"recipient": "Alice", "text": "hello"})
assert result["contact_id"] == "4"
assert outbound.get_nowait().chat_id == "4"
finally:
bridge.stop()
def test_send_rejects_unknown_recipient():
bridge, outbound, base = start_bridge()
try:
with pytest.raises(urllib.error.HTTPError) as exc:
post(f"{base}/send", {"recipient": "ghost", "text": "hello"})
assert exc.value.code == 400
assert outbound.empty(), "a rejected send must not enqueue anything"
finally:
bridge.stop()
def test_send_validates_body():
bridge, outbound, base = start_bridge()
try:
for payload in ({"recipient": "", "text": "hi"}, {"recipient": "4", "text": " "}):
with pytest.raises(urllib.error.HTTPError) as exc:
post(f"{base}/send", payload)
assert exc.value.code == 400
assert outbound.empty()
finally:
bridge.stop()
def test_token_is_required_when_configured():
bridge, _, base = start_bridge(token="sekret")
try:
with pytest.raises(urllib.error.HTTPError) as exc:
get(f"{base}/inbox")
assert exc.value.code == 401
with pytest.raises(urllib.error.HTTPError) as exc:
post(f"{base}/send", {"recipient": "4", "text": "hi"})
assert exc.value.code == 401
assert get(f"{base}/inbox", token="sekret") == {"messages": []}
finally:
bridge.stop()
+34 -17
View File
@@ -1,32 +1,47 @@
"""The committed seed skills are real, inspectable, and hermetically tested.
A seed is a starter integration shipped in the repo in the SKILL.md folder
format. These tests keep it honest: the declared integration must match the
code, the contract must cover what the body reads, and the hermetic mechanics
test must pass. They are not proof of the live integration — only a real run
against the user's service is (see AGENTS.md).
format. These tests keep every seed honest: the declared integration must match
the code, the contract must cover what the body reads, and the hermetic
mechanics test must pass. They are not proof of the live integration — only a
real run against the user's service is (see AGENTS.md).
"""
import json
import os
from pathlib import Path
import pytest
from semif_agent.codegen import integration_findings, parse_integration, run_skill_test
SEED = Path(__file__).resolve().parent.parent / "seeds" / "calendar" / "next_event"
SEEDS = Path(__file__).resolve().parent.parent / "seeds"
SEED_DIRS = sorted(path.parent for path in SEEDS.glob("*/*/skill.py"))
def test_seed_declares_a_real_integration():
code = (SEED / "skill.py").read_text()
def seed_id(seed: Path) -> str:
return f"{seed.parent.name}.{seed.name}"
def test_expected_seeds_exist():
ids = {seed_id(seed) for seed in SEED_DIRS}
assert "calendar.next_event" in ids
assert "simplex.next_message" in ids
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
def test_seed_declares_a_real_integration(seed):
code = (seed / "skill.py").read_text()
integration = parse_integration(code)
assert integration["service"] == "nextcloud_calendar"
assert integration["transport"] == "caldav"
assert integration["service"]
assert integration["transport"]
assert integration_findings(integration, "declared", code) == []
def test_seed_contract_is_flat_and_covered_by_declaration():
code = (SEED / "skill.py").read_text()
contract = json.loads((SEED / "contract.json").read_text())
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
def test_seed_contract_is_flat_and_covered_by_declaration(seed):
code = (seed / "skill.py").read_text()
contract = json.loads((seed / "contract.json").read_text())
assert contract, "the seed must carry a data contract"
for name, description in contract.items():
assert name.islower() and " " not in name, name
@@ -35,14 +50,16 @@ def test_seed_contract_is_flat_and_covered_by_declaration():
assert set(integration["config_vars"]) == set(contract)
def test_seed_has_manifest_description():
manifest = json.loads((SEED / "manifest.json").read_text())
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
def test_seed_has_manifest_description(seed):
manifest = json.loads((seed / "manifest.json").read_text())
assert manifest["description"].strip()
def test_seed_hermetic_test_passes(monkeypatch):
root = str(SEED.parents[2])
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
def test_seed_hermetic_test_passes(seed, monkeypatch):
root = str(seed.parents[2])
existing = os.environ.get("PYTHONPATH", "")
monkeypatch.setenv("PYTHONPATH", root + os.pathsep + existing)
passed, output = run_skill_test(SEED, timeout=30)
passed, output = run_skill_test(seed, timeout=30)
assert passed, output
+1 -1
View File
@@ -92,7 +92,7 @@ def _pipeline_codegen_server(replies: list) -> tuple[ThreadingHTTPServer, str]:
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length).decode("utf-8")
if self.path.endswith("/api/show"):
body = json.dumps({"parameters": {"num_ctx": 4242}}).encode("utf-8")
body = json.dumps({"parameters": {"num_ctx": 32768}}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))