Abstract seeds into modular skill packs + split config
Group committed starter skills into packs (semif_agent/packs.py) that bind a
concern to its categories, bridge(s), requirements, and config schema:
- seeds/ -> packs/<name>/ with a pack.json manifest + skills/<category>/<leaf>/.
Shipped: nextcloud, simplex, outlook, browser (each owning its bridge) and
essentials (time + calculator, no bridge).
- PackRegistry discovers packs (a root with no manifest is one implicit pack);
merge_packs loads every enabled pack. Pack enable is one switch
(packs.<name>.enabled -> bridges.<bridge>.enabled -> enabled_by_default);
disabling a pack drops its categories (incl. generated bodies) and its bridge.
- CATEGORY_DESCRIPTIONS now comes from the pack manifests (built-ins stay).
Adopt a Home-Assistant-style layered config (semif_agent/config.py):
- config.json is a thin index ({"include": [...]}) over config/core.json,
config/gateway.json, config/bridges.json, config/packs/*.json, deep-merged.
- Secrets live in the gitignored secrets.json, referenced as "!secret <key>";
api_key_env is removed.
- CORE_SCHEMA + each pack's config schema own defaults and GENERATE the
committed config.example.json; new `check-config` (validate + --write-example)
and `config-init` (seed the split layout) commands.
- scripts/config_merge.py (stdlib) lets bootstrap read the merged config.
Tests: tests/test_packs.py (renamed from test_seed_skills, +enable/merge),
new tests/test_config.py. All unit tests pass (772).
This commit is contained in:
1 parent
b953475bf7
commit
78b4621ba0
115 files changed
+1701
-398
No files matched your search
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "simplex",
|
||||
"title": "SimpleX",
|
||||
"concern": "SimpleX messaging through the forwarding bridge: reading incoming messages, sending messages to contacts, and showing the user's contact link.",
|
||||
"categories": {
|
||||
"simplex": "SimpleX messaging: reading incoming messages, sending messages to contacts, and showing the user's contact link."
|
||||
},
|
||||
"bridges": ["simplex"],
|
||||
"requires": [],
|
||||
"enabled_by_default": true,
|
||||
"config": {
|
||||
"enabled": {"type": "bool", "default": true, "doc": "Load this pack's skills and run its bridge."},
|
||||
"host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."},
|
||||
"port": {"type": "int", "default": 5227, "doc": "Bridge listen port."},
|
||||
"token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."},
|
||||
"max_inbox": {"type": "int", "default": 100, "doc": "Bound on the in-memory inbound-message buffer."},
|
||||
"ws_url": {"type": "str", "default": "ws://127.0.0.1:5228", "doc": "The bridge's OWN simplex-chat daemon WebSocket URL (must match simplex_chat.forward_port)."},
|
||||
"user_id": {"type": "int", "default": 1, "doc": "Daemon user id the bridge acts as."},
|
||||
"auto_accept": {"type": "bool", "default": true, "doc": "Auto-accept inbound contact requests."},
|
||||
"reconnect": {
|
||||
"initial": {"type": "float", "default": 1.0, "doc": "Initial reconnect delay (seconds)."},
|
||||
"max": {"type": "float", "default": 60.0, "doc": "Maximum reconnect delay (seconds)."},
|
||||
"jitter": {"type": "float", "default": 0.2, "doc": "Reconnect jitter fraction."}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
||||
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Show (creating if needed) the SimpleX contact link others use to connect to this agent."
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Show the SimpleX contact link others use to connect to this agent.
|
||||
|
||||
Real integration: the standalone SimpleX forwarding bridge
|
||||
(`simplex_bridge_url`, `simplex_bridge_token`). The bridge's own connection to
|
||||
the `simplex-chat` daemon is the only thing that can read (or create) the
|
||||
forwarding 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 bridge is not running or has no address, it says so.
|
||||
|
||||
`act` health-checks the bridge, then `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
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "simplex",
|
||||
"transport": "http",
|
||||
"config_vars": ["simplex_bridge_url", "simplex_bridge_token"],
|
||||
}
|
||||
|
||||
CONTRACT = {
|
||||
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
||||
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
}
|
||||
|
||||
TIMEOUT_SECONDS = 30
|
||||
|
||||
|
||||
class BridgeError(Exception):
|
||||
"""The SimpleX forwarding bridge is unreachable or returned an error."""
|
||||
|
||||
|
||||
# ---- transport ----
|
||||
|
||||
|
||||
def _base(ctx):
|
||||
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
|
||||
if not url:
|
||||
raise BridgeError("simplex_bridge_url is not configured")
|
||||
return url
|
||||
|
||||
|
||||
def _headers(ctx):
|
||||
token = str(ctx.config.get("simplex_bridge_token", "") or "").strip()
|
||||
return {"X-Semif-Token": token} if token else {}
|
||||
|
||||
|
||||
def _get(ctx, path):
|
||||
request = urllib.request.Request(
|
||||
_base(ctx) + path, headers=_headers(ctx)
|
||||
)
|
||||
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
|
||||
|
||||
|
||||
# ---- skill phases ----
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
try:
|
||||
payload = _get(ctx, "/health")
|
||||
except BridgeError as exc:
|
||||
return ActionResult(action_log=str(exc), new_state=request.text)
|
||||
if not payload.get("ok"):
|
||||
return ActionResult(
|
||||
action_log="simplex forwarding bridge is not healthy",
|
||||
new_state=request.text,
|
||||
)
|
||||
try:
|
||||
payload = _get(ctx, "/address")
|
||||
except BridgeError as exc:
|
||||
return ActionResult(
|
||||
action_log=f"reading the contact 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=(
|
||||
"the bridge 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)
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Hermetic mechanics test for simplex.connect_link.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the standalone SimpleX forwarding 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 bridge 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 = []
|
||||
tokens = []
|
||||
|
||||
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)
|
||||
self.tokens.append(self.headers.get("X-Semif-Token"))
|
||||
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": [],
|
||||
"tokens": [],
|
||||
},
|
||||
)
|
||||
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, token=""):
|
||||
return {"simplex_bridge_url": url, "simplex_bridge_token": token}
|
||||
|
||||
|
||||
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")
|
||||
action = skill.act(ctx, request)
|
||||
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")
|
||||
action = skill.act(ctx, request)
|
||||
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")
|
||||
action = skill.act(ctx, request)
|
||||
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")
|
||||
action = skill.act(ctx, request)
|
||||
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")
|
||||
action = skill.act(ctx, request)
|
||||
assert action.action_log and "simplex.connect_link" not in action.action_log, action.action_log
|
||||
assert action.new_state == request.text
|
||||
print(action.action_log)
|
||||
|
||||
|
||||
def test_auth_token_is_sent_when_configured():
|
||||
server, handler, url = start_server(
|
||||
{"short_link": "simplex:/contact#abc", "full_link": "", "created": False}
|
||||
)
|
||||
try:
|
||||
ctx = ActionContext(engine=None, config=config(url, token="sekret"))
|
||||
request = Request("give me your simplex link")
|
||||
action = skill.act(ctx, request)
|
||||
assert "simplex:/contact#abc" in action.action_log, action.action_log
|
||||
assert set(handler.tokens) == {"sekret"}, handler.tokens
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
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()
|
||||
test_auth_token_is_sent_when_configured()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
||||
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Read the next unread SimpleX message."
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
"""Read the next unread SimpleX message through the forwarding bridge.
|
||||
|
||||
Real integration: the standalone SimpleX forwarding bridge
|
||||
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends.
|
||||
`act` peeks that inbox, finds which conversations have unread messages, and
|
||||
resolves which one to read with a SemIf choice over them (state = the user
|
||||
query): a strong winner (probability >= `CONTACT_WINNER_TAU`) is used, otherwise
|
||||
the configured default contact is used; with no configured default (or a default
|
||||
with no unread message) the weak winner stands. It then pops and reports the
|
||||
oldest unread message for that conversation.
|
||||
|
||||
When the live buffer is empty it falls back to the daemon's persistent unread
|
||||
(`/unread` + `/history`), so a message that arrived before the bridge started is
|
||||
still reported. After reporting a message, that single item is marked read on
|
||||
the daemon through the bridge (`POST /read`), so the next call advances to the
|
||||
next unread message instead of re-reporting the same one.
|
||||
|
||||
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
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "simplex",
|
||||
"transport": "http",
|
||||
"config_vars": [
|
||||
"simplex_bridge_url",
|
||||
"simplex_bridge_token",
|
||||
"simplex_default_contact",
|
||||
],
|
||||
}
|
||||
|
||||
CONTRACT = {
|
||||
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
||||
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate.",
|
||||
}
|
||||
|
||||
TIMEOUT_SECONDS = 20
|
||||
# A SemIf probability at or above this counts as a "strong winner" for the
|
||||
# conversation; below it the configured default contact is used instead.
|
||||
CONTACT_WINNER_TAU = 0.6
|
||||
|
||||
|
||||
class BridgeError(Exception):
|
||||
"""The SimpleX forwarding bridge is unreachable or returned an error."""
|
||||
|
||||
|
||||
# ---- transport ----
|
||||
|
||||
|
||||
def _base(ctx):
|
||||
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
|
||||
if not url:
|
||||
raise BridgeError("simplex_bridge_url is not configured")
|
||||
return url
|
||||
|
||||
|
||||
def _headers(ctx):
|
||||
token = str(ctx.config.get("simplex_bridge_token", "") or "").strip()
|
||||
return {"X-Semif-Token": token} if token else {}
|
||||
|
||||
|
||||
def _get(ctx, path):
|
||||
request = urllib.request.Request(
|
||||
_base(ctx) + path, headers=_headers(ctx)
|
||||
)
|
||||
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 _post(ctx, path, payload):
|
||||
data = json.dumps(payload).encode("utf-8")
|
||||
headers = {**_headers(ctx), "Content-Type": "application/json"}
|
||||
request = urllib.request.Request(
|
||||
_base(ctx) + path, data=data, headers=headers, method="POST"
|
||||
)
|
||||
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"POST {path}: HTTP {exc.code} {detail}") from exc
|
||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
||||
raise BridgeError(f"POST {path}: {exc}") from exc
|
||||
|
||||
|
||||
def _mark_read(ctx, contact, item_id):
|
||||
"""Mark one just-reported item read via the bridge.
|
||||
|
||||
Returns None on success, or a short honest reason string on failure. The
|
||||
message was still reported, so a failed consume is surfaced as a note rather
|
||||
than fabricated into a read failure.
|
||||
"""
|
||||
item = str(item_id or "").strip()
|
||||
if not item:
|
||||
return None
|
||||
try:
|
||||
payload = _post(ctx, "/read", {"contact": contact, "item_ids": [item]})
|
||||
except BridgeError as exc:
|
||||
return str(exc)
|
||||
if not payload.get("ok"):
|
||||
return payload.get("error") or "the bridge did not mark it read"
|
||||
return None
|
||||
|
||||
|
||||
# ---- conversation resolution ----
|
||||
|
||||
|
||||
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 _is_healthy(sender):
|
||||
"""A conversation is healthy when its connection is not known-bad.
|
||||
|
||||
`connected` is absent when the source did not report it (treat as unknown);
|
||||
`auth_errors` counts failed sends on the connection and marks a stale peer.
|
||||
"""
|
||||
if sender.get("connected") is False:
|
||||
return False
|
||||
try:
|
||||
return int(sender.get("auth_errors") or 0) == 0
|
||||
except (TypeError, ValueError):
|
||||
return True
|
||||
|
||||
|
||||
def _default_sender(ctx, senders):
|
||||
"""The configured default contact, if it has unread messages."""
|
||||
default = str(ctx.config.get("simplex_default_contact", "") or "").strip()
|
||||
if not default:
|
||||
return None
|
||||
for sender in senders:
|
||||
if sender["id"] == default or sender["display_name"] == default:
|
||||
return sender
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_contact(ctx, request, senders, decisions):
|
||||
"""Resolve which conversation to read, mirroring nextcloud.create_event.
|
||||
|
||||
A strong SemIf winner is used; a weak winner falls back to the configured
|
||||
default contact, and with no configured default the weak winner stands.
|
||||
"""
|
||||
default = _default_sender(ctx, senders)
|
||||
if len(senders) == 1:
|
||||
return 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)
|
||||
decisions.append((decision, result))
|
||||
winner = result.selected
|
||||
if result.prob(winner) >= CONTACT_WINNER_TAU:
|
||||
return winner
|
||||
if default is not None:
|
||||
return default["id"]
|
||||
return winner
|
||||
|
||||
|
||||
# ---- skill phases ----
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
try:
|
||||
payload = _get(ctx, "/inbox")
|
||||
except BridgeError as exc:
|
||||
return ActionResult(action_log=str(exc), new_state=request.text)
|
||||
senders = _senders(payload.get("messages") or [])
|
||||
if senders:
|
||||
return _read_live(ctx, request, senders)
|
||||
# The live buffer only holds messages that arrived while the bridge was
|
||||
# connected; fall back to the daemon's persistent unread so a message that
|
||||
# landed before the bridge started is not silently missed.
|
||||
return _read_persistent(ctx, request)
|
||||
|
||||
|
||||
def _read_live(ctx, request, senders):
|
||||
decisions = []
|
||||
contact = _resolve_contact(ctx, request, senders, decisions)
|
||||
try:
|
||||
payload = _get(
|
||||
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
|
||||
)
|
||||
except BridgeError as exc:
|
||||
return ActionResult(
|
||||
action_log=f"failed reading {contact!r}: {exc}",
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
message = payload.get("message")
|
||||
if not message:
|
||||
return ActionResult(
|
||||
action_log=f"no unread message from {contact!r}.",
|
||||
new_state="no unread SimpleX messages",
|
||||
decisions=decisions,
|
||||
)
|
||||
read_note = _mark_read(ctx, contact, message.get("item_id"))
|
||||
return _report(
|
||||
message.get("display_name") or contact,
|
||||
message.get("text"),
|
||||
decisions,
|
||||
read_note,
|
||||
)
|
||||
|
||||
|
||||
def _read_persistent(ctx, request):
|
||||
try:
|
||||
payload = _get(ctx, "/unread")
|
||||
except BridgeError as exc:
|
||||
return ActionResult(
|
||||
action_log=f"no unread SimpleX messages ({exc}).",
|
||||
new_state="no unread SimpleX messages",
|
||||
)
|
||||
chats = [c for c in (payload.get("chats") or []) if c.get("unread")]
|
||||
if not chats:
|
||||
return ActionResult(
|
||||
action_log="no unread SimpleX messages.",
|
||||
new_state="no unread SimpleX messages",
|
||||
)
|
||||
senders = [
|
||||
{
|
||||
"id": str(chat.get("contact_id") or ""),
|
||||
"display_name": chat.get("display_name") or str(chat.get("contact_id") or ""),
|
||||
"connected": chat.get("connected"),
|
||||
"auth_errors": chat.get("auth_errors"),
|
||||
}
|
||||
for chat in chats
|
||||
if chat.get("contact_id")
|
||||
]
|
||||
decisions = []
|
||||
healthy = [s for s in senders if _is_healthy(s)]
|
||||
if len(healthy) == 1:
|
||||
# Exactly one conversation is on a healthy connection (the rest are
|
||||
# stale duplicates): read it without a coin-flip decision.
|
||||
contact = healthy[0]["id"]
|
||||
else:
|
||||
contact = _resolve_contact(ctx, request, senders, decisions)
|
||||
try:
|
||||
history = _get(
|
||||
ctx, f"/history?contact={urllib.parse.quote(contact)}&count=50"
|
||||
)
|
||||
except BridgeError as exc:
|
||||
return ActionResult(
|
||||
action_log=f"failed reading {contact!r}: {exc}",
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
messages = [m for m in (history.get("messages") or []) if m.get("unread")]
|
||||
if not messages:
|
||||
# Fall back to the previewed unread messages from /unread.
|
||||
chat = next(
|
||||
(c for c in chats if str(c.get("contact_id")) == str(contact)), {}
|
||||
)
|
||||
messages = [m for m in (chat.get("messages") or []) if m.get("unread")]
|
||||
if not messages:
|
||||
return ActionResult(
|
||||
action_log=f"no unread message from {contact!r}.",
|
||||
new_state="no unread SimpleX messages",
|
||||
decisions=decisions,
|
||||
)
|
||||
sender = next(
|
||||
(s["display_name"] for s in senders if s["id"] == str(contact)), str(contact)
|
||||
)
|
||||
read_note = _mark_read(ctx, contact, messages[0].get("item_id"))
|
||||
return _report(sender, messages[0].get("text"), decisions, read_note)
|
||||
|
||||
|
||||
def _report(sender, body, decisions, read_note=None):
|
||||
report = f"SimpleX message from {sender}: {str(body or '')}"
|
||||
if read_note:
|
||||
report += f" (could not mark it read: {read_note})"
|
||||
return ActionResult(action_log=report, new_state=report, decisions=decisions)
|
||||
@@ -0,0 +1,425 @@
|
||||
"""Hermetic mechanics test for simplex.next_message.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the standalone SimpleX forwarding bridge. This proves the body
|
||||
peeks the inbox, resolves the conversation through a SemIf sub-decision (a
|
||||
strong winner is used, otherwise the configured default, otherwise the weak
|
||||
winner), 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 bridge 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.
|
||||
|
||||
By default it picks the requested option id (else the first) with full
|
||||
confidence. Pass `probs` (a mapping of option id -> probability) to script an
|
||||
arbitrary distribution, e.g. a near-tie that must fall back to the default.
|
||||
"""
|
||||
|
||||
def __init__(self, pick=None, probs=None):
|
||||
self.pick = pick
|
||||
self.probs = probs
|
||||
self.decisions = []
|
||||
|
||||
def call(self, decision):
|
||||
self.decisions.append(decision)
|
||||
option_ids = [option.id for option in decision.options]
|
||||
if self.probs is not None:
|
||||
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
|
||||
else:
|
||||
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 = []
|
||||
unread_chats = []
|
||||
history = {}
|
||||
requests = []
|
||||
tokens = []
|
||||
read_calls = []
|
||||
read_ok = True
|
||||
|
||||
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)
|
||||
self.tokens.append(self.headers.get("X-Semif-Token"))
|
||||
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})
|
||||
elif url.path == "/unread":
|
||||
self._send({"chats": list(self.unread_chats)})
|
||||
elif url.path == "/history":
|
||||
contact = (urllib.parse.parse_qs(url.query).get("contact") or [None])[0]
|
||||
self._send(
|
||||
{"contact_id": contact, "messages": list(self.history.get(str(contact), []))}
|
||||
)
|
||||
else:
|
||||
self._send({"error": "not found"}, 404)
|
||||
|
||||
def do_POST(self):
|
||||
url = urllib.parse.urlparse(self.path)
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
payload = json.loads(self.rfile.read(length).decode("utf-8") or "{}")
|
||||
if url.path != "/read":
|
||||
self._send({"error": "not found"}, 404)
|
||||
return
|
||||
self.read_calls.append(payload)
|
||||
if self.read_ok:
|
||||
self._send(
|
||||
{
|
||||
"ok": True,
|
||||
"contact_id": payload.get("contact"),
|
||||
"item_ids": payload.get("item_ids"),
|
||||
"status": "read",
|
||||
}
|
||||
)
|
||||
else:
|
||||
self._send({"ok": False, "error": "the daemon rejected the read"})
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def start_server(messages, unread_chats=None, history=None, read_ok=True):
|
||||
handler = type(
|
||||
"Handler",
|
||||
(BridgeHandler,),
|
||||
{
|
||||
"messages": list(messages),
|
||||
"unread_chats": list(unread_chats or []),
|
||||
"history": dict(history or {}),
|
||||
"requests": [],
|
||||
"tokens": [],
|
||||
"read_calls": [],
|
||||
"read_ok": read_ok,
|
||||
},
|
||||
)
|
||||
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,
|
||||
"item_id": str(identifier),
|
||||
"contact_id": contact,
|
||||
"display_name": name,
|
||||
"text": text,
|
||||
"received_at": 1.0,
|
||||
}
|
||||
|
||||
|
||||
def config(url, default="", token=""):
|
||||
return {
|
||||
"simplex_bridge_url": url,
|
||||
"simplex_default_contact": default,
|
||||
"simplex_bridge_token": token,
|
||||
}
|
||||
|
||||
|
||||
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")
|
||||
action = skill.act(ctx, request)
|
||||
assert len(action.decisions) == 1, "act must log the conversation choice"
|
||||
assert len(engine.decisions) == 1
|
||||
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"
|
||||
assert handler.read_calls == [{"contact": "7", "item_ids": ["m2"]}], (
|
||||
"the reported item must be marked read, and only it"
|
||||
)
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_strong_winner_overrides_default_contact():
|
||||
server, handler, url = start_server(
|
||||
[
|
||||
message("m1", "4", "Alice", "hello there"),
|
||||
message("m2", "7", "Bob", "shipment arrived"),
|
||||
]
|
||||
)
|
||||
try:
|
||||
engine = FakeEngine(probs={"4": 0.1, "7": 0.9})
|
||||
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
|
||||
request = Request("read my next simplex message from Bob")
|
||||
action = skill.act(ctx, request)
|
||||
assert len(engine.decisions) == 1, "the conversation is chosen with one SemIf decision"
|
||||
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_weak_winner_falls_back_to_default_contact():
|
||||
server, handler, url = start_server(
|
||||
[
|
||||
message("m1", "4", "Alice", "hello there"),
|
||||
message("m2", "7", "Bob", "shipment arrived"),
|
||||
]
|
||||
)
|
||||
try:
|
||||
# Bob edges out Alice but stays below the strong-winner threshold, so the
|
||||
# configured default ("Alice") is used instead.
|
||||
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
|
||||
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
|
||||
request = Request("read my next simplex message")
|
||||
action = skill.act(ctx, request)
|
||||
assert len(engine.decisions) == 1
|
||||
assert handler.requests[1] == "/inbox/next?contact=4", handler.requests
|
||||
assert "hello there" in action.action_log, action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_weak_winner_without_default_stands():
|
||||
server, handler, url = start_server(
|
||||
[
|
||||
message("m1", "4", "Alice", "hello there"),
|
||||
message("m2", "7", "Bob", "shipment arrived"),
|
||||
]
|
||||
)
|
||||
try:
|
||||
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
|
||||
ctx = ActionContext(engine=engine, config=config(url))
|
||||
request = Request("read my next simplex message")
|
||||
action = skill.act(ctx, request)
|
||||
assert len(engine.decisions) == 1
|
||||
assert handler.requests[1] == "/inbox/next?contact=7", 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")
|
||||
action = skill.act(ctx, request)
|
||||
assert engine.decisions == []
|
||||
assert "hi" in action.action_log, action.action_log
|
||||
assert handler.read_calls == [{"contact": "4", "item_ids": ["m1"]}]
|
||||
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")
|
||||
action = skill.act(ctx, request)
|
||||
assert "no unread" in action.action_log, action.action_log
|
||||
# An empty live buffer falls back to the daemon's persistent unread.
|
||||
assert handler.requests == ["/inbox", "/unread"], handler.requests
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_empty_live_inbox_falls_back_to_persistent_unread():
|
||||
server, handler, url = start_server(
|
||||
[],
|
||||
unread_chats=[
|
||||
{
|
||||
"contact_id": "3",
|
||||
"display_name": "pepper",
|
||||
"unread_count": 2,
|
||||
"min_unread_item_id": "8",
|
||||
"unread": True,
|
||||
"messages": [],
|
||||
}
|
||||
],
|
||||
history={
|
||||
"3": [
|
||||
{"item_id": "8", "text": "hello", "status": "rcvNew", "unread": True},
|
||||
{"item_id": "9", "text": "hey yo", "status": "rcvNew", "unread": True},
|
||||
]
|
||||
},
|
||||
)
|
||||
try:
|
||||
engine = FakeEngine()
|
||||
ctx = ActionContext(engine=engine, config=config(url))
|
||||
request = Request("read my next simplex message")
|
||||
action = skill.act(ctx, request)
|
||||
assert engine.decisions == [], "a single unread chat needs no decision"
|
||||
assert "hello" in action.action_log, action.action_log
|
||||
assert "pepper" in action.action_log, action.action_log
|
||||
assert handler.requests == ["/inbox", "/unread", "/history?contact=3&count=50"], (
|
||||
handler.requests
|
||||
)
|
||||
assert handler.read_calls == [{"contact": "3", "item_ids": ["8"]}]
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_persistent_unread_prefers_a_healthy_conversation():
|
||||
server, handler, url = start_server(
|
||||
[],
|
||||
unread_chats=[
|
||||
{
|
||||
"contact_id": "3",
|
||||
"display_name": "pepper",
|
||||
"unread_count": 1,
|
||||
"unread": True,
|
||||
"connected": True,
|
||||
"auth_errors": 2,
|
||||
"messages": [],
|
||||
},
|
||||
{
|
||||
"contact_id": "4",
|
||||
"display_name": "pepper",
|
||||
"unread_count": 1,
|
||||
"unread": True,
|
||||
"connected": True,
|
||||
"auth_errors": 0,
|
||||
"messages": [],
|
||||
},
|
||||
],
|
||||
history={
|
||||
"3": [{"item_id": "8", "text": "stale hello", "status": "rcvNew", "unread": True}],
|
||||
"4": [{"item_id": "20", "text": "fresh hello", "status": "rcvNew", "unread": True}],
|
||||
},
|
||||
)
|
||||
try:
|
||||
engine = FakeEngine()
|
||||
ctx = ActionContext(engine=engine, config=config(url))
|
||||
action = skill.act(ctx, Request("read my next simplex message"))
|
||||
assert engine.decisions == [], "one healthy chat must win without a decision"
|
||||
assert "fresh hello" in action.action_log, action.action_log
|
||||
assert handler.requests == ["/inbox", "/unread", "/history?contact=4&count=50"], (
|
||||
handler.requests
|
||||
)
|
||||
assert handler.read_calls == [{"contact": "4", "item_ids": ["20"]}]
|
||||
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")
|
||||
action = skill.act(ctx, request)
|
||||
assert action.action_log and "simplex.next_message" not in action.action_log, action.action_log
|
||||
assert action.new_state == request.text, "a failed read must not fake a result"
|
||||
print(action.action_log)
|
||||
|
||||
|
||||
def test_auth_token_is_sent_when_configured():
|
||||
server, handler, url = start_server([message("m1", "4", "Alice", "hi")])
|
||||
try:
|
||||
engine = FakeEngine()
|
||||
ctx = ActionContext(engine=engine, config=config(url, token="sekret"))
|
||||
request = Request("read my next simplex message")
|
||||
action = skill.act(ctx, request)
|
||||
assert "hi" in action.action_log, action.action_log
|
||||
assert set(handler.tokens) == {"sekret"}, handler.tokens
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_failed_read_marking_is_surfaced_honestly():
|
||||
"""A message is still reported when consuming it fails, with an honest note
|
||||
instead of a fabricated failure of the read."""
|
||||
server, handler, url = start_server(
|
||||
[message("m1", "4", "Alice", "hi")], read_ok=False
|
||||
)
|
||||
try:
|
||||
ctx = ActionContext(engine=FakeEngine(), config=config(url))
|
||||
action = skill.act(ctx, Request("read my next simplex message"))
|
||||
assert "hi" in action.action_log, action.action_log
|
||||
assert "could not mark it read" in action.action_log, action.action_log
|
||||
assert handler.read_calls == [{"contact": "4", "item_ids": ["m1"]}]
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def main():
|
||||
test_multiple_senders_uses_semif_decision()
|
||||
test_strong_winner_overrides_default_contact()
|
||||
test_weak_winner_falls_back_to_default_contact()
|
||||
test_weak_winner_without_default_stands()
|
||||
test_single_sender_needs_no_decision()
|
||||
test_empty_inbox_is_reported_honestly()
|
||||
test_empty_live_inbox_falls_back_to_persistent_unread()
|
||||
test_persistent_unread_prefers_a_healthy_conversation()
|
||||
test_unreachable_bridge_fails_honestly()
|
||||
test_auth_token_is_sent_when_configured()
|
||||
test_failed_read_marking_is_surfaced_honestly()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"simplex_bridge_url": "Base URL of the local SimpleX forwarding bridge that fronts the user's simplex daemon, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
||||
"simplex_bridge_token": "Shared secret for the SimpleX bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not clearly name a recipient; leave blank to always use the strongest candidate.",
|
||||
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to write the message text when the request does not state it.",
|
||||
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Send a SimpleX message to a contact through the forwarding bridge."
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
"""Send a text message to a SimpleX contact through the local SimpleX bridge.
|
||||
|
||||
Real integration: the simplex bridge over HTTP. The bridge owns the SimpleX
|
||||
daemon connection and its credentials; this body only calls the bridge's HTTP
|
||||
API with the base URL and token resolved from `ctx.config`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from semif_agent.decisions import DecisionRequest, Option
|
||||
from semif_agent.skills import ActionResult, last_result
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "simplex",
|
||||
"transport": "http",
|
||||
"config_vars": [
|
||||
"simplex_bridge_url",
|
||||
"simplex_bridge_token",
|
||||
"simplex_default_contact",
|
||||
"llm_bridge_url",
|
||||
"llm_bridge_token",
|
||||
],
|
||||
}
|
||||
|
||||
CONTRACT = {
|
||||
"simplex_bridge_url": (
|
||||
"Base URL of the local SimpleX forwarding bridge that fronts the "
|
||||
"user's simplex daemon, e.g. http://127.0.0.1:5227 (no trailing slash "
|
||||
"needed)."
|
||||
),
|
||||
"simplex_bridge_token": (
|
||||
"Shared secret for the SimpleX bridge, if one is configured; sent as "
|
||||
"the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
||||
),
|
||||
"simplex_default_contact": (
|
||||
"Default SimpleX contact (contact id or display name) used when the "
|
||||
"request does not clearly name a recipient; leave blank to always use "
|
||||
"the strongest candidate."
|
||||
),
|
||||
"llm_bridge_url": (
|
||||
"Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no "
|
||||
"trailing slash needed); used to write the message text when the "
|
||||
"request does not state it."
|
||||
),
|
||||
"llm_bridge_token": (
|
||||
"Shared secret for the LLM bridge, if one is configured; sent as the "
|
||||
"X-Semif-Token header. Leave blank when the bridge requires no auth."
|
||||
),
|
||||
}
|
||||
|
||||
# A contact sub-decision winner is used only when its conditional probability
|
||||
# clears this bar; otherwise the configured default contact wins.
|
||||
CONFIDENCE_THRESHOLD = 0.5
|
||||
|
||||
_HTTP_TIMEOUT = 20
|
||||
|
||||
# Ordered: the literal message text the user dictated wins over anything else.
|
||||
_MESSAGE_PATTERNS = (
|
||||
r"\b(?:saying|say|that says|which says|that reads|reads)\b\s*[:\-]?\s*(.+)$",
|
||||
r'["\u201c](.+?)["\u201d]',
|
||||
r"\b(?:message|text)\s*(?:is|:)\s*(.+)$",
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# bridge transport
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _headers(token: str, has_body: bool) -> dict:
|
||||
headers = {"Accept": "application/json"}
|
||||
if has_body:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if token:
|
||||
headers["X-Semif-Token"] = token
|
||||
return headers
|
||||
|
||||
|
||||
def _http_json(url: str, token: str, payload=None):
|
||||
"""GET the url, or POST the payload as JSON, and decode the JSON reply."""
|
||||
data = None
|
||||
if payload is not None:
|
||||
data = json.dumps(payload).encode("utf-8")
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers=_headers(token, data is not None),
|
||||
method="POST" if data is not None else "GET",
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=_HTTP_TIMEOUT) as response:
|
||||
raw = response.read().decode("utf-8")
|
||||
if not raw.strip():
|
||||
return {}
|
||||
return json.loads(raw)
|
||||
|
||||
|
||||
def _error_detail(exc) -> str:
|
||||
"""Best-effort human-readable detail from an HTTP error response."""
|
||||
try:
|
||||
raw = exc.read().decode("utf-8", "replace")
|
||||
except Exception:
|
||||
raw = ""
|
||||
if raw:
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
except ValueError:
|
||||
parsed = None
|
||||
if isinstance(parsed, dict) and parsed.get("error"):
|
||||
return str(parsed["error"])
|
||||
return raw.strip()
|
||||
return str(getattr(exc, "reason", "") or exc)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# contacts
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _contact_id(contact) -> str:
|
||||
return str(contact.get("id") or contact.get("display_name") or "").strip()
|
||||
|
||||
|
||||
def _display(contact) -> str:
|
||||
return str(contact.get("display_name") or contact.get("id") or "").strip()
|
||||
|
||||
|
||||
def _label(contact) -> str:
|
||||
"""The unique name for a contact: the daemon's local name when known.
|
||||
|
||||
Two peers can share a profile display name; the local name is unique, so it
|
||||
is the right label for a SemIf option and the right thing to match on.
|
||||
"""
|
||||
return str(
|
||||
contact.get("local_name") or _display(contact) or contact.get("id") or ""
|
||||
).strip()
|
||||
|
||||
|
||||
def _is_healthy(contact) -> bool:
|
||||
"""A contact is healthy when its connection is not known-bad.
|
||||
|
||||
`connected` is absent when the source did not report it (treat as unknown,
|
||||
i.e. not disqualifying); `auth_errors` counts failed sends on the connection
|
||||
and marks a stale/duplicate peer.
|
||||
"""
|
||||
if contact.get("connected") is False:
|
||||
return False
|
||||
try:
|
||||
return int(contact.get("auth_errors") or 0) == 0
|
||||
except (TypeError, ValueError):
|
||||
return True
|
||||
|
||||
|
||||
def _mentions(query: str, name: str) -> bool:
|
||||
if not name:
|
||||
return False
|
||||
pattern = r"(?<!\w)" + re.escape(name.lower()) + r"(?!\w)"
|
||||
return re.search(pattern, query.lower()) is not None
|
||||
|
||||
|
||||
def _match_contact(contacts, ref: str):
|
||||
"""Resolve an id or display name against the bridge's contact list."""
|
||||
ref = (ref or "").strip()
|
||||
if not ref:
|
||||
return None
|
||||
lowered = ref.lower()
|
||||
for contact in contacts:
|
||||
if _contact_id(contact).lower() == lowered:
|
||||
return contact
|
||||
exact = [
|
||||
c
|
||||
for c in contacts
|
||||
if _label(c).lower() == lowered or _display(c).lower() == lowered
|
||||
]
|
||||
if exact:
|
||||
return _preferred(exact)
|
||||
matches = [
|
||||
c
|
||||
for c in contacts
|
||||
if lowered in _display(c).lower() or lowered in _label(c).lower()
|
||||
]
|
||||
if len(matches) == 1:
|
||||
return matches[0]
|
||||
if matches:
|
||||
return _preferred(matches)
|
||||
return None
|
||||
|
||||
|
||||
def _preferred(candidates):
|
||||
"""Prefer a healthy candidate (the others are likely stale duplicates)."""
|
||||
healthy = [c for c in candidates if _is_healthy(c)]
|
||||
return (healthy or candidates)[0]
|
||||
|
||||
|
||||
def _find_by_id(contacts, contact_id):
|
||||
wanted = str(contact_id or "")
|
||||
for contact in contacts:
|
||||
if _contact_id(contact) == wanted:
|
||||
return contact
|
||||
return None
|
||||
|
||||
|
||||
def _confidence(result, option_id) -> float:
|
||||
prob = getattr(result, "prob", None)
|
||||
if callable(prob):
|
||||
try:
|
||||
return float(prob(option_id))
|
||||
except Exception:
|
||||
return 0.0
|
||||
probs = getattr(result, "probs", None)
|
||||
if isinstance(probs, dict):
|
||||
try:
|
||||
return float(probs.get(option_id, 0.0))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
return 0.0
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# message text
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _message_from_query(query: str) -> str:
|
||||
"""Pull the literal message text out of the user's request, if stated."""
|
||||
for pattern in _MESSAGE_PATTERNS:
|
||||
match = re.search(pattern, query, flags=re.IGNORECASE | re.DOTALL)
|
||||
if match:
|
||||
text = match.group(1).strip().strip("\"'\u201c\u201d").strip()
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
|
||||
|
||||
def _llm_message_text(ctx, query: str):
|
||||
"""Ask the LLM bridge to write the message body. Returns (text, reason)."""
|
||||
base_url = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
|
||||
if not base_url:
|
||||
return None, "no llm bridge is configured"
|
||||
token = str(ctx.config.get("llm_bridge_token", "") or "")
|
||||
payload = {
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"content": (
|
||||
"You write the exact text of a chat message a user wants to "
|
||||
"send. Reply with the message text only: no quotes, no "
|
||||
"preamble, no explanation."
|
||||
),
|
||||
},
|
||||
{"role": "user", "content": query},
|
||||
],
|
||||
"max_tokens": 256,
|
||||
}
|
||||
try:
|
||||
reply = _http_json(f"{base_url}/chat", token, payload)
|
||||
except urllib.error.HTTPError as exc:
|
||||
return None, f"the llm bridge returned HTTP {exc.code} {_error_detail(exc)}"
|
||||
except (urllib.error.URLError, ValueError, OSError) as exc:
|
||||
return None, f"could not reach the llm bridge: {exc}"
|
||||
if not isinstance(reply, dict):
|
||||
return None, "the llm bridge returned an unexpected reply"
|
||||
text = str(reply.get("text", "")).strip().strip('"').strip()
|
||||
if not text:
|
||||
return None, "the llm bridge returned no text"
|
||||
return text, ""
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# action
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def act(ctx, request) -> ActionResult:
|
||||
"""Send the requested message to the requested SimpleX contact."""
|
||||
base_url = str(ctx.config["simplex_bridge_url"]).strip().rstrip("/")
|
||||
token = str(ctx.config.get("simplex_bridge_token", "") or "")
|
||||
default_ref = str(ctx.config.get("simplex_default_contact", "") or "").strip()
|
||||
|
||||
query = (request.text or "").strip()
|
||||
user_input = str(getattr(request, "user_input", "") or "").strip()
|
||||
decisions = []
|
||||
|
||||
# --- the bridge's real contact list ------------------------------------
|
||||
try:
|
||||
payload = _http_json(f"{base_url}/contacts", token)
|
||||
except urllib.error.HTTPError as exc:
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"the simplex bridge at {base_url} returned HTTP {exc.code} "
|
||||
f"while listing contacts: {_error_detail(exc)}"
|
||||
),
|
||||
new_state=request.text,
|
||||
)
|
||||
except (urllib.error.URLError, ValueError, OSError) as exc:
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"could not reach the simplex bridge at {base_url} to list "
|
||||
f"contacts: {exc}"
|
||||
),
|
||||
new_state=request.text,
|
||||
)
|
||||
|
||||
raw_contacts = payload.get("contacts") if isinstance(payload, dict) else None
|
||||
contacts = (
|
||||
[c for c in raw_contacts if isinstance(c, dict)]
|
||||
if isinstance(raw_contacts, list)
|
||||
else []
|
||||
)
|
||||
|
||||
# --- resolve the recipient --------------------------------------------
|
||||
default_contact = _match_contact(contacts, default_ref)
|
||||
named = [
|
||||
c
|
||||
for c in contacts
|
||||
if _mentions(query, _display(c)) or _mentions(query, _label(c))
|
||||
]
|
||||
|
||||
chosen = None
|
||||
used_input_for_contact = False
|
||||
|
||||
if named or default_contact is not None:
|
||||
candidates = list(named)
|
||||
if default_contact is not None and all(
|
||||
_contact_id(c) != _contact_id(default_contact) for c in candidates
|
||||
):
|
||||
candidates.append(default_contact)
|
||||
|
||||
healthy = [c for c in candidates if _is_healthy(c)]
|
||||
if len(candidates) == 1:
|
||||
chosen = candidates[0]
|
||||
elif len(healthy) == 1:
|
||||
# Exactly one candidate's connection is healthy (the rest are stale
|
||||
# duplicates): pick it deterministically rather than coin-flipping.
|
||||
chosen = healthy[0]
|
||||
else:
|
||||
decision = DecisionRequest(
|
||||
state=query,
|
||||
question="Which SimpleX contact should the message be sent to?",
|
||||
options=[
|
||||
Option(_contact_id(c), _label(c) or _contact_id(c))
|
||||
for c in candidates
|
||||
],
|
||||
)
|
||||
result = ctx.engine.call(decision)
|
||||
decisions.append((decision, result))
|
||||
selected_id = getattr(result, "selected", None)
|
||||
selected = _find_by_id(candidates, selected_id)
|
||||
if (
|
||||
selected is not None
|
||||
and _confidence(result, selected_id) >= CONFIDENCE_THRESHOLD
|
||||
):
|
||||
chosen = selected
|
||||
elif default_contact is not None:
|
||||
chosen = default_contact
|
||||
else:
|
||||
chosen = selected if selected is not None else candidates[0]
|
||||
elif user_input:
|
||||
# The human answered the question asked on the previous pass.
|
||||
chosen = _match_contact(contacts, user_input) or {
|
||||
"id": user_input,
|
||||
"display_name": user_input,
|
||||
}
|
||||
used_input_for_contact = True
|
||||
|
||||
if chosen is None:
|
||||
known = ", ".join(_display(c) for c in contacts if _display(c)) or "none"
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
"the request does not identify a SimpleX contact to message; "
|
||||
f"the bridge knows these contacts: {known}"
|
||||
),
|
||||
new_state=request.text,
|
||||
needs_input="Which SimpleX contact should I message?",
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
recipient = _contact_id(chosen) or _display(chosen)
|
||||
display_name = _display(chosen) or recipient
|
||||
|
||||
# --- resolve the message text -----------------------------------------
|
||||
# Prefer the literal text the user dictated; then the result of the previous
|
||||
# step of a chain (never re-derive a computed value with the LLM); only then
|
||||
# ask the LLM bridge for genuinely new text.
|
||||
message_text = _message_from_query(query)
|
||||
if not message_text and user_input and not used_input_for_contact:
|
||||
message_text = user_input
|
||||
if not message_text:
|
||||
message_text = last_result(request)
|
||||
if not message_text:
|
||||
written, reason = _llm_message_text(ctx, query)
|
||||
if written:
|
||||
message_text = written
|
||||
else:
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"the request does not state what the message to "
|
||||
f"{display_name} should say and no message text could be "
|
||||
f"written ({reason})"
|
||||
),
|
||||
new_state=request.text,
|
||||
needs_input=f"What should the message to {display_name} say?",
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
# --- send it through the bridge ---------------------------------------
|
||||
try:
|
||||
response = _http_json(
|
||||
f"{base_url}/send", token, {"recipient": recipient, "text": message_text}
|
||||
)
|
||||
except urllib.error.HTTPError as exc:
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"the simplex bridge refused to send to {display_name}: "
|
||||
f"HTTP {exc.code} {_error_detail(exc)}"
|
||||
),
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
except (urllib.error.URLError, ValueError, OSError) as exc:
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"could not reach the simplex bridge at {base_url} to send the "
|
||||
f"message to {display_name}: {exc}"
|
||||
),
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
if not isinstance(response, dict):
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"the simplex bridge returned an unexpected reply while sending "
|
||||
f"to {display_name}"
|
||||
),
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
contact_id = str(response.get("contact_id") or recipient)
|
||||
status = str(response.get("status") or "")
|
||||
if not response.get("ok"):
|
||||
detail = str(response.get("error") or "").strip() or json.dumps(response)
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"the message to {display_name} (contact {contact_id}) did not "
|
||||
f"send (status {status or 'unknown'}: {detail})"
|
||||
),
|
||||
new_state=json.dumps(
|
||||
{
|
||||
"sent": False,
|
||||
"contact_id": contact_id,
|
||||
"display_name": display_name,
|
||||
"status": status,
|
||||
"error": detail,
|
||||
"text": message_text,
|
||||
}
|
||||
),
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"sent the message {message_text!r} to {display_name} "
|
||||
f"(contact {contact_id}, status {status or 'ok'}) through the "
|
||||
f"simplex bridge"
|
||||
),
|
||||
new_state=json.dumps(
|
||||
{
|
||||
"sent": True,
|
||||
"contact_id": contact_id,
|
||||
"display_name": display_name,
|
||||
"status": status,
|
||||
"text": message_text,
|
||||
}
|
||||
),
|
||||
decisions=decisions,
|
||||
)
|
||||
@@ -0,0 +1,416 @@
|
||||
"""Hermetic mechanics test for simplex.send_message.
|
||||
|
||||
Stands up loopback HTTP servers that imitate the simplex and llm bridges,
|
||||
points the fixture config at them, and drives the body's real `act` so the
|
||||
request construction, recipient/message resolution and error paths are
|
||||
exercised without leaving the machine.
|
||||
"""
|
||||
|
||||
import json
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import skill
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# inline fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
CONTACTS = [
|
||||
{"id": "c-pepper", "display_name": "pepper"},
|
||||
{"id": "c-salt", "display_name": "salt"},
|
||||
]
|
||||
|
||||
SIMPLEX_TOKEN = "s3cret-simplex-token"
|
||||
LLM_TOKEN = "s3cret-llm-token"
|
||||
LLM_REPLY = "a friendly hello"
|
||||
|
||||
|
||||
class FakeRequest:
|
||||
"""Minimal stand-in for the agent's Request object (test-only)."""
|
||||
|
||||
def __init__(self, text, user_input="", run_ledger=None):
|
||||
self.text = text
|
||||
self.user_input = user_input
|
||||
self.run_ledger = list(run_ledger or [])
|
||||
|
||||
|
||||
class FakeResult:
|
||||
"""Stand-in for a decision result: exposes `selected` and `prob(id)`."""
|
||||
|
||||
def __init__(self, selected, confidence):
|
||||
self.selected = selected
|
||||
self._confidence = confidence
|
||||
|
||||
def prob(self, option_id):
|
||||
return float(self._confidence) if option_id == self.selected else 0.0
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
"""Test-only decision engine."""
|
||||
|
||||
def __init__(self, selected=None, confidence=1.0):
|
||||
self.selected = selected
|
||||
self.confidence = confidence
|
||||
self.calls = []
|
||||
|
||||
def call(self, decision):
|
||||
self.calls.append(decision)
|
||||
selected = self.selected
|
||||
if selected is None:
|
||||
options = list(decision.options)
|
||||
selected = options[0].id if options else None
|
||||
return FakeResult(selected, self.confidence)
|
||||
|
||||
|
||||
class _BaseHandler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def _send_json(self, code, obj):
|
||||
body = json.dumps(obj).encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _read_body(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(length) if length else b""
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return json.loads(raw.decode("utf-8"))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
class SimplexHandler(_BaseHandler):
|
||||
contacts = []
|
||||
send_error = False
|
||||
seen = []
|
||||
|
||||
def do_GET(self):
|
||||
SimplexHandler.seen.append(
|
||||
{
|
||||
"method": "GET",
|
||||
"path": self.path,
|
||||
"token": self.headers.get("X-Semif-Token"),
|
||||
}
|
||||
)
|
||||
if self.path == "/contacts":
|
||||
self._send_json(200, {"contacts": SimplexHandler.contacts})
|
||||
else:
|
||||
self._send_json(404, {"error": "not found"})
|
||||
|
||||
def do_POST(self):
|
||||
body = self._read_body()
|
||||
SimplexHandler.seen.append(
|
||||
{
|
||||
"method": "POST",
|
||||
"path": self.path,
|
||||
"token": self.headers.get("X-Semif-Token"),
|
||||
"body": body,
|
||||
}
|
||||
)
|
||||
if self.path != "/send":
|
||||
self._send_json(404, {"error": "not found"})
|
||||
return
|
||||
if SimplexHandler.send_error:
|
||||
self._send_json(400, {"error": "unknown recipient"})
|
||||
return
|
||||
recipient = (body or {}).get("recipient", "")
|
||||
self._send_json(200, {"ok": True, "contact_id": recipient})
|
||||
|
||||
|
||||
class LlmHandler(_BaseHandler):
|
||||
reply = LLM_REPLY
|
||||
seen = []
|
||||
|
||||
def do_POST(self):
|
||||
body = self._read_body()
|
||||
LlmHandler.seen.append(
|
||||
{
|
||||
"path": self.path,
|
||||
"token": self.headers.get("X-Semif-Token"),
|
||||
"body": body,
|
||||
}
|
||||
)
|
||||
if self.path == "/chat":
|
||||
self._send_json(200, {"text": LlmHandler.reply})
|
||||
else:
|
||||
self._send_json(404, {"error": "not found"})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def start_server(handler):
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server
|
||||
|
||||
|
||||
def base_url(server):
|
||||
return f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def reset(contacts=None, send_error=False):
|
||||
SimplexHandler.contacts = [dict(c) for c in (contacts if contacts is not None else CONTACTS)]
|
||||
SimplexHandler.send_error = send_error
|
||||
SimplexHandler.seen = []
|
||||
LlmHandler.seen = []
|
||||
LlmHandler.reply = LLM_REPLY
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_happy_path():
|
||||
"""A named contact plus an explicit message: GET /contacts then POST /send."""
|
||||
reset()
|
||||
server = start_server(SimplexHandler)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={
|
||||
"simplex_bridge_url": base_url(server),
|
||||
"simplex_bridge_token": SIMPLEX_TOKEN,
|
||||
},
|
||||
)
|
||||
result = skill.act(
|
||||
ctx, FakeRequest("send a message to pepper on simplex saying hey")
|
||||
)
|
||||
|
||||
assert result.action_log, "act must log what it did"
|
||||
assert not result.needs_input, result.action_log
|
||||
assert "sent" in result.action_log.lower(), result.action_log
|
||||
|
||||
gets = [r for r in SimplexHandler.seen if r["method"] == "GET"]
|
||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
||||
assert any(r["path"] == "/contacts" for r in gets), SimplexHandler.seen
|
||||
assert len(posts) == 1, SimplexHandler.seen
|
||||
assert posts[0]["path"] == "/send", SimplexHandler.seen
|
||||
assert posts[0]["body"] == {"recipient": "c-pepper", "text": "hey"}, posts[0]
|
||||
|
||||
for seen in SimplexHandler.seen:
|
||||
assert seen["token"] == SIMPLEX_TOKEN, seen
|
||||
|
||||
state = json.loads(result.new_state)
|
||||
assert state["sent"] is True, state
|
||||
assert state["contact_id"] == "c-pepper", state
|
||||
assert state["text"] == "hey", state
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_ambiguous_contact_uses_engine():
|
||||
"""Two named contacts: the body must ask the engine and honour the pick."""
|
||||
reset()
|
||||
server = start_server(SimplexHandler)
|
||||
try:
|
||||
engine = FakeEngine(selected="c-salt", confidence=0.9)
|
||||
ctx = ActionContext(
|
||||
engine=engine,
|
||||
config={"simplex_bridge_url": base_url(server)},
|
||||
)
|
||||
result = skill.act(
|
||||
ctx, FakeRequest("send a message to pepper and salt saying hi")
|
||||
)
|
||||
|
||||
assert not result.needs_input, result.action_log
|
||||
assert len(engine.calls) == 1, engine.calls
|
||||
option_ids = [o.id for o in engine.calls[0].options]
|
||||
assert set(option_ids) == {"c-pepper", "c-salt"}, option_ids
|
||||
|
||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
||||
assert len(posts) == 1, SimplexHandler.seen
|
||||
assert posts[0]["body"] == {"recipient": "c-salt", "text": "hi"}, posts[0]
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_message_written_by_llm_bridge():
|
||||
"""No literal text: the body must ask the llm bridge, then send its reply."""
|
||||
reset()
|
||||
simplex = start_server(SimplexHandler)
|
||||
llm = start_server(LlmHandler)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={
|
||||
"simplex_bridge_url": base_url(simplex),
|
||||
"simplex_bridge_token": SIMPLEX_TOKEN,
|
||||
"llm_bridge_url": base_url(llm),
|
||||
"llm_bridge_token": LLM_TOKEN,
|
||||
},
|
||||
)
|
||||
result = skill.act(ctx, FakeRequest("tell pepper something nice"))
|
||||
|
||||
assert not result.needs_input, result.action_log
|
||||
assert len(LlmHandler.seen) == 1, LlmHandler.seen
|
||||
chat = LlmHandler.seen[0]
|
||||
assert chat["path"] == "/chat", chat
|
||||
assert chat["token"] == LLM_TOKEN, chat
|
||||
assert chat["body"]["messages"], chat
|
||||
|
||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
||||
assert len(posts) == 1, SimplexHandler.seen
|
||||
assert posts[0]["body"] == {"recipient": "c-pepper", "text": LLM_REPLY}, posts[0]
|
||||
finally:
|
||||
simplex.shutdown()
|
||||
simplex.server_close()
|
||||
llm.shutdown()
|
||||
llm.server_close()
|
||||
|
||||
|
||||
def test_chained_result_is_sent():
|
||||
"""As the later step of a chain, no literal text: send the prior step's result."""
|
||||
reset()
|
||||
simplex = start_server(SimplexHandler)
|
||||
llm = start_server(LlmHandler)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={
|
||||
"simplex_bridge_url": base_url(simplex),
|
||||
"simplex_bridge_token": SIMPLEX_TOKEN,
|
||||
"llm_bridge_url": base_url(llm),
|
||||
},
|
||||
)
|
||||
request = FakeRequest(
|
||||
"send the result of 22 * 10 to pepper on simplex",
|
||||
run_ledger=[
|
||||
{
|
||||
"query": "send the result of 22 * 10 to pepper on simplex",
|
||||
"skill": "calculator.calculate",
|
||||
"outcome": "Twenty-two times ten is two hundred twenty.",
|
||||
}
|
||||
],
|
||||
)
|
||||
result = skill.act(ctx, request)
|
||||
|
||||
assert not result.needs_input, result.action_log
|
||||
# The prior result is used verbatim; the LLM bridge must NOT be asked to
|
||||
# recompute it.
|
||||
assert LlmHandler.seen == [], LlmHandler.seen
|
||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
||||
assert len(posts) == 1, SimplexHandler.seen
|
||||
assert posts[0]["body"] == {
|
||||
"recipient": "c-pepper",
|
||||
"text": "Twenty-two times ten is two hundred twenty.",
|
||||
}, posts[0]
|
||||
finally:
|
||||
simplex.shutdown()
|
||||
simplex.server_close()
|
||||
llm.shutdown()
|
||||
llm.server_close()
|
||||
|
||||
|
||||
def test_missing_text_without_llm_asks():
|
||||
"""A clear recipient but no message text and no llm bridge: ask the user."""
|
||||
reset()
|
||||
server = start_server(SimplexHandler)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={"simplex_bridge_url": base_url(server)},
|
||||
)
|
||||
result = skill.act(ctx, FakeRequest("tell pepper something nice"))
|
||||
|
||||
assert result.needs_input, result.action_log
|
||||
assert "say" in result.needs_input.lower(), result.needs_input
|
||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
||||
assert posts == [], SimplexHandler.seen
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_unknown_contact_asks():
|
||||
"""No matching contact in the bridge list: ask which contact to message."""
|
||||
reset(contacts=[])
|
||||
server = start_server(SimplexHandler)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={"simplex_bridge_url": base_url(server)},
|
||||
)
|
||||
result = skill.act(
|
||||
ctx, FakeRequest("send a message to pepper on simplex saying hey")
|
||||
)
|
||||
|
||||
assert result.needs_input, result.action_log
|
||||
assert "contact" in result.needs_input.lower(), result.needs_input
|
||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
||||
assert posts == [], SimplexHandler.seen
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_send_refused_is_reported():
|
||||
"""A 400 from POST /send must be surfaced, not silently swallowed."""
|
||||
reset(send_error=True)
|
||||
server = start_server(SimplexHandler)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={"simplex_bridge_url": base_url(server)},
|
||||
)
|
||||
result = skill.act(
|
||||
ctx, FakeRequest("send a message to pepper on simplex saying hey")
|
||||
)
|
||||
|
||||
assert not result.needs_input, result.action_log
|
||||
assert "refused" in result.action_log.lower(), result.action_log
|
||||
assert "400" in result.action_log, result.action_log
|
||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
||||
assert len(posts) == 1, SimplexHandler.seen
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_unreachable_bridge_is_reported():
|
||||
"""A dead bridge must produce a plain failure log, not an exception."""
|
||||
reset()
|
||||
server = start_server(SimplexHandler)
|
||||
url = base_url(server)
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={"simplex_bridge_url": url},
|
||||
)
|
||||
result = skill.act(
|
||||
ctx, FakeRequest("send a message to pepper on simplex saying hey")
|
||||
)
|
||||
assert not result.needs_input, result.action_log
|
||||
assert "could not reach" in result.action_log.lower(), result.action_log
|
||||
|
||||
|
||||
def main():
|
||||
test_happy_path()
|
||||
test_ambiguous_contact_uses_engine()
|
||||
test_message_written_by_llm_bridge()
|
||||
test_chained_result_is_sent()
|
||||
test_missing_text_without_llm_asks()
|
||||
test_unknown_contact_asks()
|
||||
test_send_refused_is_reported()
|
||||
test_unreachable_bridge_is_reported()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user