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:
gabby committed 2026-10-13 14:20:35 +00:00
commit 6b5f79eca9
13 files changed
+1958

No files matched your search

@@ -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."
}
+482
View File
@@ -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,
)
+416
View File
@@ -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()