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:
1 parent
b348f19486
commit
08d6bb23e2
19 files changed
+1006
-29
No files matched your search
@@ -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."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Read the next unread SimpleX message through the messenger gateway."
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user