gateway: show/create the SimpleX contact link (simplex.connect_link seed)

Add a reusable corrId->Future request path to SimplexAdapter so the daemon
can be queried off the event loop, expose it as GET /address on the local
messaging bridge (injected address_provider; 503 unwired, 502 on daemon
failure), and ship a simplex.connect_link seed that reports the bot's short
and full contact link honestly, creating it on first call.
This commit is contained in:
Denton Social committed 2026-09-28 05:14:01 -05:00
1 parent 9057213217
commit a9b096f2e8
12 files changed
+532 -28

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
{
"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)."
}
+3
View File
@@ -0,0 +1,3 @@
{
"description": "Show (creating if needed) the SimpleX contact link others use to connect to this agent."
}
+93
View File
@@ -0,0 +1,93 @@
"""Show the SimpleX contact link others use to connect to this agent.
Real integration: the running messenger gateway serves a local HTTP bridge
(`messaging_bridge_url`). The gateway's own connection to the `simplex-chat`
daemon is the only thing that can read (or create) the bot's *user contact
address*; this body asks the bridge for it and reports the link honestly. It
never opens a WebSocket to the daemon and never invents a link: if the gateway
is not running or has no address, it says so.
`GET /address` shows the existing link and creates one on first call, returning
`{short_link, full_link, created}`.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.request
from semif_agent.skills import ActionResult, Prediction
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": ["messaging_bridge_url"],
}
TIMEOUT_SECONDS = 30
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 predict(ctx, request):
try:
payload = _get(ctx, "/health")
except BridgeError as exc:
return Prediction(text=f"bridge error: {exc}")
if not payload.get("ok"):
return Prediction(text="bridge error: gateway bridge is not healthy")
return Prediction(text="ready: messenger bridge reachable")
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)
try:
payload = _get(ctx, "/address")
except BridgeError as exc:
return ActionResult(
action_log=f"simplex.connect_link failed: {exc}",
new_state=request.text,
)
short = str(payload.get("short_link") or "").strip()
full = str(payload.get("full_link") or "").strip()
if not (short or full):
return ActionResult(
action_log=(
"simplex.connect_link: the gateway returned no SimpleX "
"contact link; the bot has no address yet."
),
new_state=request.text,
)
verb = "created" if payload.get("created") else "current"
lines = [f"SimpleX contact link ({verb}): {short or full}"]
if short and full:
lines.append(f"Full link: {full}")
lines.append(
"Share this link with someone so they can add the agent and message it."
)
report = "\n".join(lines)
return ActionResult(action_log=report, new_state=report)
+156
View File
@@ -0,0 +1,156 @@
"""Hermetic mechanics test for simplex.connect_link.
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 health-
checks the bridge, fetches the contact link, reports a freshly created link, and
fails honestly when the bridge has no provider or is unreachable. It does NOT
prove the live integration — only a real run against the gateway and a real
simplex-chat daemon does.
"""
import json
import sys
import threading
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from semif_agent.decisions import Request
from semif_agent.skills import ActionContext
import skill
class BridgeHandler(BaseHTTPRequestHandler):
address = {}
address_status = 200
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 == "/health":
self._send({"ok": True, "platform": "simplex"})
elif url.path == "/address":
self._send(self.address, self.address_status)
else:
self._send({"error": "not found"}, 404)
def log_message(self, *args):
pass
def start_server(address=None, address_status=200):
handler = type(
"Handler",
(BridgeHandler,),
{"address": address or {}, "address_status": address_status, "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 config(url):
return {"messaging_bridge_url": url}
def test_reports_existing_link():
server, handler, url = start_server(
{"short_link": "simplex:/contact#abc", "full_link": "https://smp/short", "created": False}
)
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
assert "simplex:/contact#abc" in action.action_log, action.action_log
assert "https://smp/short" in action.action_log, action.action_log
assert "current" in action.action_log, action.action_log
assert handler.requests == ["/health", "/address"], handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_reports_freshly_created_link():
server, handler, url = start_server(
{"short_link": "simplex:/contact#new", "full_link": "", "created": True}
)
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("create a simplex invitation link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
assert "simplex:/contact#new" in action.action_log, action.action_log
assert "created" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_no_provider_is_reported_honestly():
server, handler, url = start_server({"error": "address lookup is not available"}, 503)
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
assert "503" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed lookup must not fake a result"
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_empty_link_is_reported_honestly():
server, handler, url = start_server({"short_link": "", "full_link": "", "created": False})
try:
ctx = ActionContext(engine=None, config=config(url))
request = Request("give me your simplex link")
prediction = skill.predict(ctx, request)
action = skill.act(ctx, request, prediction)
assert "no SimpleX" in action.action_log, action.action_log
assert action.new_state == request.text
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_unreachable_bridge_fails_honestly():
ctx = ActionContext(engine=None, config=config("http://127.0.0.1:1"))
request = Request("give me your simplex link")
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
print(action.action_log)
def main():
test_reports_existing_link()
test_reports_freshly_created_link()
test_no_provider_is_reported_honestly()
test_empty_link_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)