seeds: ship simplex.send_message (promoted from the runtime store)
Move the authored simplex.send_simplex_message skill out of data/skills/ into the committed simplex seed folder as send_message. Expand its CONTRACT to cover every declared config var (SimpleX bridge + LLM bridge) so it satisfies the seed contract test, add its manifest.json, and update the navigation tuning labels, the seed-existence test, the committed-seed tree assertions, the docs, and the bridge backlog (item 3 shipped).
This commit is contained in:
1 parent
b8f86849ea
commit
f1ea9f0c2c
10 files changed
+885
-14
No files matched your search
@@ -869,8 +869,9 @@ CLI, unit tests (24) + integration tests (2).
|
||||
adds a task to a Nextcloud task list through the Nextcloud bridge (`GET
|
||||
/tasklists` for a VTODO-capable target, `POST /tasks` to create it, the LLM
|
||||
bridge to phrase the summary/description); `simplex.next_message` (read via the
|
||||
forwarding bridge) and `simplex.connect_link` (show/create the forwarding bot's
|
||||
contact link) are the messenger seeds; `time.now`, `time.date`, `time.set_timer`, and
|
||||
forwarding bridge), `simplex.send_message` (send to a contact resolved over the
|
||||
bridge's contact list), and `simplex.connect_link` (show/create the forwarding
|
||||
bot's contact link) are the messenger seeds; `time.now`, `time.date`, `time.set_timer`, and
|
||||
`time.set_alarm` are the local time utilities (`compute` transport, empty
|
||||
contract) — they read the host clock and schedule on `ctx.timers`. Local time
|
||||
is the top-level `timezone` config value (an IANA name such as
|
||||
@@ -1248,7 +1249,8 @@ CLI, unit tests (24) + integration tests (2).
|
||||
resolution, outbound routing, token/body validation, `/address` success/503/502,
|
||||
daemon close on stop, catalog/`describe_bridges()`).
|
||||
`tests/test_seed_skills.py` hermetically tests every
|
||||
`seeds/<category>/<name>/` package, including `simplex.next_message` and
|
||||
`seeds/<category>/<name>/` package, including `simplex.next_message`,
|
||||
`simplex.send_message`, and
|
||||
`simplex.connect_link`. `tests/test_voice_gateway.py` drives the voice loop
|
||||
with injected fake engines (wake gating, endpointing, half-duplex,
|
||||
follow-up window, `speak` truncation/failure, adapter + CLI wiring) — no
|
||||
@@ -1319,7 +1321,8 @@ CLI, unit tests (24) + integration tests (2).
|
||||
keep in sync and the data-contract config search finds it and auto-populates the
|
||||
skill config. Skills reach a bridge with the ordinary `http`
|
||||
transport, so their hermetic tests are loopback HTTP like any other HTTP body.
|
||||
`simplex.next_message` and `simplex.connect_link` are the seeds.
|
||||
`simplex.next_message`, `simplex.send_message`, and `simplex.connect_link` are
|
||||
the seeds.
|
||||
- **LLM bridge** (`bridges/llm.py`). A generic `POST /chat`
|
||||
`{"messages": [{"role","content"}, ...], "max_tokens"?: int}` ->
|
||||
`{"text": "<model reply>"}` (plus `GET /health`, `400` bad body, `502` model
|
||||
@@ -1399,8 +1402,9 @@ CLI, unit tests (24) + integration tests (2).
|
||||
|
||||
## Bridge backlog (one session per item)
|
||||
|
||||
The bridge read path (`simplex.next_message`) and contact-link lookup
|
||||
(`simplex.connect_link`) are covered. Deferred follow-ups:
|
||||
The bridge read path (`simplex.next_message`), outbound send
|
||||
(`simplex.send_message`), and contact-link lookup (`simplex.connect_link`) are
|
||||
covered. Deferred follow-ups:
|
||||
|
||||
- [x] **1. Contact-list refresh from the daemon** (`bridges/simplex.py`,
|
||||
`simplex_ws.py`). Shipped: `SimplexDaemon.contacts()` /
|
||||
@@ -1424,10 +1428,12 @@ The bridge read path (`simplex.next_message`) and contact-link lookup
|
||||
`/address` (503 not connected / 502 lookup failure; `/history` 400 without a
|
||||
contact). The live `/inbox` buffer is unchanged. Note: v7 has **no mark-read
|
||||
command**, so acking is via read receipts, not an API call.
|
||||
- [ ] **3. `simplex.send_message` seed** (`seeds/simplex/send_message/`). The
|
||||
outbound counterpart to `simplex.next_message`: resolve the recipient with a
|
||||
SemIf sub-decision over `/contacts`, send only on explicit user intent, and
|
||||
report the bridge's `contact_id` / errors honestly.
|
||||
- [x] **3. `simplex.send_message` seed** (`seeds/simplex/send_message/`). The
|
||||
outbound counterpart to `simplex.next_message`: resolves the recipient with a
|
||||
SemIf sub-decision over the bridge's `/contacts` (falling back to the
|
||||
configured default contact), writes the message from the request or the LLM
|
||||
bridge when no literal text is given, sends via `POST /send`, and reports the
|
||||
bridge's `contact_id` / errors honestly.
|
||||
- [x] **4. LLM bridge** (`bridges/llm.py`). Shipped: `LLMBridge` exposes a
|
||||
generic `POST /chat` in front of the scheduler's configured `llm` client
|
||||
(threaded through `run_bridges`/`build_bridge`, never re-configured), registered
|
||||
|
||||
@@ -346,7 +346,7 @@ fine-tuning loop — it is not yet the fine-tune itself.
|
||||
- **Seeds** — shipped real starter skills: `nextcloud.create_event` (the
|
||||
authoritative worked example), `nextcloud.next_event` (Nextcloud CalDAV),
|
||||
`nextcloud.create_task` (Nextcloud task list), and
|
||||
`simplex.next_message` / `simplex.connect_link`.
|
||||
`simplex.next_message` / `simplex.send_message` / `simplex.connect_link`.
|
||||
- **Fatal-on-engine-loss** — the engine is always real; its absence exits the app.
|
||||
- **Stdlib-only core** — SemIf/llama.cpp are lazy imports, so the package stays
|
||||
importable and testable without the heavy engine installed.
|
||||
@@ -873,6 +873,11 @@ committed seed never holds secrets.
|
||||
- `simplex.next_message` — read the next unread message via the forwarding
|
||||
bridge; config vars `simplex_bridge_url`, `simplex_bridge_token`,
|
||||
`simplex_default_contact`.
|
||||
- `simplex.send_message` — send a message to a contact resolved over the
|
||||
bridge's contact list (a SemIf choice, defaulting to the configured contact);
|
||||
config vars `simplex_bridge_url`, `simplex_bridge_token`,
|
||||
`simplex_default_contact`, plus the LLM bridge (`llm_bridge_url`,
|
||||
`llm_bridge_token`) to write the text when the request states none.
|
||||
- `simplex.connect_link` — show/create the forwarding bot's contact link.
|
||||
|
||||
---
|
||||
|
||||
@@ -58,8 +58,8 @@ LEAF_EVAL: list[tuple[str, str]] = [
|
||||
("check my next message on simplex", "simplex.next_message"),
|
||||
("read the next simplex message", "simplex.next_message"),
|
||||
("show me my simplex messages", "simplex.next_message"),
|
||||
('send a message on simplex to pepper: "hey!"', "simplex.send_simplex_message"),
|
||||
("send a simplex message to pepper saying hi", "simplex.send_simplex_message"),
|
||||
('send a message on simplex to pepper: "hey!"', "simplex.send_message"),
|
||||
("send a simplex message to pepper saying hi", "simplex.send_message"),
|
||||
("what is my simplex connection link?", "simplex.connect_link"),
|
||||
("give me my simplex contact link", "simplex.connect_link"),
|
||||
("tell me the next event in my nextcloud calendar", "nextcloud.next_event"),
|
||||
|
||||
@@ -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,477 @@
|
||||
"""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
|
||||
|
||||
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 -----------------------------------------
|
||||
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:
|
||||
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,371 @@
|
||||
"""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=""):
|
||||
self.text = text
|
||||
self.user_input = user_input
|
||||
|
||||
|
||||
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_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_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()
|
||||
@@ -583,7 +583,7 @@ def test_create_simplex_send_skill(tmp_path):
|
||||
scheduler, config = build_scheduler(config)
|
||||
|
||||
seeded = {s.name for s in scheduler.tree.get("simplex", [])}
|
||||
assert {"next_message", "connect_link"} <= seeded, (
|
||||
assert {"next_message", "send_message", "connect_link"} <= seeded, (
|
||||
f"the simplex seeds must be loaded, got {seeded}"
|
||||
)
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ def test_expected_seeds_exist():
|
||||
assert "nextcloud.next_event" in ids
|
||||
assert "nextcloud.create_event" in ids
|
||||
assert "simplex.next_message" in ids
|
||||
assert "simplex.send_message" in ids
|
||||
assert "simplex.connect_link" in ids
|
||||
assert "time.now" in ids
|
||||
assert "time.date" in ids
|
||||
|
||||
@@ -539,6 +539,7 @@ def test_committed_seeds_load_from_a_foreign_cwd(tmp_path, monkeypatch):
|
||||
assert [s.name for s in scheduler.tree["simplex"]] == [
|
||||
"connect_link",
|
||||
"next_message",
|
||||
"send_message",
|
||||
]
|
||||
assert [s.name for s in scheduler.tree["nextcloud"]] == [
|
||||
"create_event",
|
||||
|
||||
Reference in new issue
Block a user