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:
commit
6b5f79eca9
13 files changed
+1958
No files matched your search
@@ -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)
|
||||
Reference in new issue
Block a user