gateway: serve a local messaging bridge so skills can send/read SimpleX
The gateway now exposes a localhost stdlib HTTP API (bridge.py) that
buffers authorized inbound DMs and forwards outbound sends, so a skill
body never opens a WebSocket to the simplex-chat daemon. Endpoints:
GET /health, /contacts, /inbox (peek), /inbox/next (pop oldest unread),
POST /send (resolve id/display name onto the adapter's outbound queue).
GatewayService gains an observer hook and inbox.dispatch (pull-only mode).
Expose the capability to codegen (SKILL.md, BODY_DIRECTIVES, elicitation,
TESTGEN.md) and add the simplex.next_message seed (SemIf recipient
resolution) with its hermetic loopback test. Config: messaging_bridge_url
plus gateway.simplex.{inbox,bridge}; bootstrap keeps them in sync.
This commit is contained in:
1 parent
b348f19486
commit
08d6bb23e2
19 files changed
+1006
-29
No files matched your search
+17
-4
@@ -357,7 +357,7 @@ def _respond_show(handler, body: dict | None = None) -> bool:
|
||||
if not handler.path.endswith("/api/show"):
|
||||
return False
|
||||
encoded = json.dumps(
|
||||
body if body is not None else {"parameters": {"num_ctx": 4242}}
|
||||
body if body is not None else {"parameters": {"num_ctx": 32768}}
|
||||
).encode("utf-8")
|
||||
handler.send_response(200)
|
||||
handler.send_header("Content-Type", "application/json")
|
||||
@@ -369,7 +369,7 @@ def _respond_show(handler, body: dict | None = None) -> bool:
|
||||
|
||||
class _FakeOpenAI(BaseHTTPRequestHandler):
|
||||
"""Single-shot SSE server: the reply arrives as one content delta. The
|
||||
`/api/show` window query is answered too (default num_ctx 4242) but never
|
||||
`/api/show` window query is answered too (default num_ctx 32768) but never
|
||||
recorded in `received`, so chat-payload assertions stay unambiguous."""
|
||||
|
||||
reply: str = GOOD_BODY
|
||||
@@ -858,7 +858,7 @@ def test_chat_stream_false_returns_content_without_echo(capsys):
|
||||
class _UsageOpenAI(BaseHTTPRequestHandler):
|
||||
"""Streams a small content delta, then the exact-token usage chunk
|
||||
(`choices: []` — OpenAI's shape when include_usage is set) before
|
||||
[DONE]. The `/api/show` window query is answered (default num_ctx 4242)
|
||||
[DONE]. The `/api/show` window query is answered (default num_ctx 32768)
|
||||
and never recorded."""
|
||||
|
||||
usage: dict = {"prompt_tokens": 5, "completion_tokens": 10, "total_tokens": 15}
|
||||
@@ -1208,7 +1208,7 @@ def test_degeneration_disabled_no_callback_no_abort():
|
||||
class _SequencedOpenAI(BaseHTTPRequestHandler):
|
||||
"""Returns one reply per chat request, in order; counts chat calls.
|
||||
|
||||
`/api/show` is answered (default num_ctx 4242) and never counted, so chat
|
||||
`/api/show` is answered (default num_ctx 32768) and never counted, so chat
|
||||
payload and retry-count assertions stay unambiguous.
|
||||
"""
|
||||
|
||||
@@ -1680,6 +1680,19 @@ def test_skill_contract_lists_all_transports():
|
||||
assert transport in text
|
||||
|
||||
|
||||
def test_skill_contract_documents_messaging_bridge():
|
||||
text = read_skill_contract()
|
||||
assert "messaging_bridge_url" in text
|
||||
assert "/inbox/next" in text
|
||||
assert "/send" in text
|
||||
assert "never opens a WebSocket" in text
|
||||
|
||||
|
||||
def test_body_directives_expose_messaging_bridge():
|
||||
assert "messaging_bridge_url" in BODY_DIRECTIVES
|
||||
assert "never open a WebSocket" in BODY_DIRECTIVES
|
||||
|
||||
|
||||
def test_body_prompts_require_real_action_and_integration():
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
draft = SkillDraft(name="probe", description="Probe the service.")
|
||||
|
||||
@@ -340,3 +340,24 @@ def test_service_answered_question_routes_back(tmp_path):
|
||||
|
||||
service.handle_inbound(InboundMessage(text="work", chat_id="4", contact_id="4"))
|
||||
assert not scheduler.pending_questions()
|
||||
|
||||
|
||||
def test_service_observer_sees_authorized_inbound(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
service = build_service(scheduler)
|
||||
seen = []
|
||||
service.observer = seen.append
|
||||
service.handle_inbound(InboundMessage(text="hi", chat_id="4", contact_id="4"))
|
||||
assert [m.text for m in seen] == ["hi"]
|
||||
|
||||
|
||||
def test_service_pull_mode_buffers_without_dispatch(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
service = GatewayService(scheduler, FakeAdapter(), config={"inbox": {"dispatch": False}})
|
||||
seen = []
|
||||
service.observer = seen.append
|
||||
service.handle_inbound(InboundMessage(text="hi", chat_id="4", contact_id="4"))
|
||||
assert [m.text for m in seen] == ["hi"], "pull mode must still buffer for a read skill"
|
||||
assert drain_outbound(service) == [], "pull mode must not reply or dispatch"
|
||||
assert scheduler.current is None
|
||||
assert scheduler.pending is None
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Pure-stdlib tests for the gateway's local messaging bridge.
|
||||
|
||||
The bridge is exercised over a real loopback HTTP server (no mocking of its
|
||||
transport); the decision engine and LLM are never involved. These prove the
|
||||
mechanics a skill depends on: peek/pop of buffered inbound messages, recipient
|
||||
resolution, outbound routing onto the adapter queue, and token/body validation.
|
||||
"""
|
||||
|
||||
import json
|
||||
import queue
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import pytest
|
||||
|
||||
from semif_agent.gateway.base import InboundMessage, OutboundMessage
|
||||
from semif_agent.gateway.bridge import MessagingBridge
|
||||
|
||||
|
||||
def start_bridge(**config):
|
||||
outbound = queue.Queue()
|
||||
bridge = MessagingBridge(outbound, config=config)
|
||||
port = bridge.start()
|
||||
return bridge, outbound, f"http://127.0.0.1:{port}"
|
||||
|
||||
|
||||
def inbound(text, contact_id="4", display_name="Alice"):
|
||||
return InboundMessage(
|
||||
text=text, chat_id=contact_id, contact_id=contact_id, display_name=display_name
|
||||
)
|
||||
|
||||
|
||||
def get(url, token=None):
|
||||
headers = {"X-Semif-Token": token} if token else {}
|
||||
request = urllib.request.Request(url, headers=headers)
|
||||
with urllib.request.urlopen(request, timeout=5) as response:
|
||||
return json.loads(response.read().decode("utf-8"))
|
||||
|
||||
|
||||
def post(url, payload, token=None):
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Semif-Token"] = token
|
||||
request = urllib.request.Request(url, data=body, headers=headers)
|
||||
with urllib.request.urlopen(request, timeout=5) as response:
|
||||
return json.loads(response.read().decode("utf-8"))
|
||||
|
||||
|
||||
def test_health_and_contacts():
|
||||
bridge, _, base = start_bridge()
|
||||
try:
|
||||
assert get(f"{base}/health") == {"ok": True, "platform": "simplex"}
|
||||
bridge.record_inbound(inbound("hi", contact_id="4", display_name="Alice"))
|
||||
assert get(f"{base}/contacts") == {
|
||||
"contacts": [{"id": "4", "display_name": "Alice"}]
|
||||
}
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_inbox_peek_then_pop_consumes_oldest():
|
||||
bridge, _, base = start_bridge()
|
||||
try:
|
||||
bridge.record_inbound(inbound("first", contact_id="4", display_name="Alice"))
|
||||
bridge.record_inbound(inbound("second", contact_id="7", display_name="Bob"))
|
||||
peeked = get(f"{base}/inbox")["messages"]
|
||||
assert [m["text"] for m in peeked] == ["first", "second"]
|
||||
assert get(f"{base}/inbox")["messages"] == peeked, "peek must not consume"
|
||||
|
||||
popped = get(f"{base}/inbox/next")["message"]
|
||||
assert popped["text"] == "first"
|
||||
assert popped["contact_id"] == "4"
|
||||
remaining = get(f"{base}/inbox")["messages"]
|
||||
assert [m["text"] for m in remaining] == ["second"]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_inbox_next_filters_by_contact():
|
||||
bridge, _, base = start_bridge()
|
||||
try:
|
||||
bridge.record_inbound(inbound("first", contact_id="4", display_name="Alice"))
|
||||
bridge.record_inbound(inbound("second", contact_id="7", display_name="Bob"))
|
||||
popped = get(f"{base}/inbox/next?contact=7")["message"]
|
||||
assert popped["text"] == "second"
|
||||
assert get(f"{base}/inbox/next?contact=7")["message"] is None
|
||||
assert [m["text"] for m in get(f"{base}/inbox")["messages"]] == ["first"]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_inbox_is_bounded():
|
||||
bridge, _, base = start_bridge(max_inbox=2)
|
||||
try:
|
||||
for text in ("one", "two", "three"):
|
||||
bridge.record_inbound(inbound(text))
|
||||
messages = get(f"{base}/inbox")["messages"]
|
||||
assert [m["text"] for m in messages] == ["two", "three"], "oldest must be dropped"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_routes_to_outbound_queue():
|
||||
bridge, outbound, base = start_bridge()
|
||||
try:
|
||||
result = post(f"{base}/send", {"recipient": "7", "text": "on my way"})
|
||||
assert result == {"ok": True, "contact_id": "7"}
|
||||
message = outbound.get_nowait()
|
||||
assert isinstance(message, OutboundMessage)
|
||||
assert message.chat_id == "7"
|
||||
assert message.text == "on my way"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_resolves_known_display_name():
|
||||
bridge, outbound, base = start_bridge()
|
||||
try:
|
||||
bridge.record_inbound(inbound("hi", contact_id="4", display_name="Alice"))
|
||||
result = post(f"{base}/send", {"recipient": "Alice", "text": "hello"})
|
||||
assert result["contact_id"] == "4"
|
||||
assert outbound.get_nowait().chat_id == "4"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_rejects_unknown_recipient():
|
||||
bridge, outbound, base = start_bridge()
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
post(f"{base}/send", {"recipient": "ghost", "text": "hello"})
|
||||
assert exc.value.code == 400
|
||||
assert outbound.empty(), "a rejected send must not enqueue anything"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_validates_body():
|
||||
bridge, outbound, base = start_bridge()
|
||||
try:
|
||||
for payload in ({"recipient": "", "text": "hi"}, {"recipient": "4", "text": " "}):
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
post(f"{base}/send", payload)
|
||||
assert exc.value.code == 400
|
||||
assert outbound.empty()
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_token_is_required_when_configured():
|
||||
bridge, _, base = start_bridge(token="sekret")
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
get(f"{base}/inbox")
|
||||
assert exc.value.code == 401
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
post(f"{base}/send", {"recipient": "4", "text": "hi"})
|
||||
assert exc.value.code == 401
|
||||
assert get(f"{base}/inbox", token="sekret") == {"messages": []}
|
||||
finally:
|
||||
bridge.stop()
|
||||
+34
-17
@@ -1,32 +1,47 @@
|
||||
"""The committed seed skills are real, inspectable, and hermetically tested.
|
||||
|
||||
A seed is a starter integration shipped in the repo in the SKILL.md folder
|
||||
format. These tests keep it honest: the declared integration must match the
|
||||
code, the contract must cover what the body reads, and the hermetic mechanics
|
||||
test must pass. They are not proof of the live integration — only a real run
|
||||
against the user's service is (see AGENTS.md).
|
||||
format. These tests keep every seed honest: the declared integration must match
|
||||
the code, the contract must cover what the body reads, and the hermetic
|
||||
mechanics test must pass. They are not proof of the live integration — only a
|
||||
real run against the user's service is (see AGENTS.md).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from semif_agent.codegen import integration_findings, parse_integration, run_skill_test
|
||||
|
||||
SEED = Path(__file__).resolve().parent.parent / "seeds" / "calendar" / "next_event"
|
||||
SEEDS = Path(__file__).resolve().parent.parent / "seeds"
|
||||
SEED_DIRS = sorted(path.parent for path in SEEDS.glob("*/*/skill.py"))
|
||||
|
||||
|
||||
def test_seed_declares_a_real_integration():
|
||||
code = (SEED / "skill.py").read_text()
|
||||
def seed_id(seed: Path) -> str:
|
||||
return f"{seed.parent.name}.{seed.name}"
|
||||
|
||||
|
||||
def test_expected_seeds_exist():
|
||||
ids = {seed_id(seed) for seed in SEED_DIRS}
|
||||
assert "calendar.next_event" in ids
|
||||
assert "simplex.next_message" in ids
|
||||
|
||||
|
||||
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
|
||||
def test_seed_declares_a_real_integration(seed):
|
||||
code = (seed / "skill.py").read_text()
|
||||
integration = parse_integration(code)
|
||||
assert integration["service"] == "nextcloud_calendar"
|
||||
assert integration["transport"] == "caldav"
|
||||
assert integration["service"]
|
||||
assert integration["transport"]
|
||||
assert integration_findings(integration, "declared", code) == []
|
||||
|
||||
|
||||
def test_seed_contract_is_flat_and_covered_by_declaration():
|
||||
code = (SEED / "skill.py").read_text()
|
||||
contract = json.loads((SEED / "contract.json").read_text())
|
||||
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
|
||||
def test_seed_contract_is_flat_and_covered_by_declaration(seed):
|
||||
code = (seed / "skill.py").read_text()
|
||||
contract = json.loads((seed / "contract.json").read_text())
|
||||
assert contract, "the seed must carry a data contract"
|
||||
for name, description in contract.items():
|
||||
assert name.islower() and " " not in name, name
|
||||
@@ -35,14 +50,16 @@ def test_seed_contract_is_flat_and_covered_by_declaration():
|
||||
assert set(integration["config_vars"]) == set(contract)
|
||||
|
||||
|
||||
def test_seed_has_manifest_description():
|
||||
manifest = json.loads((SEED / "manifest.json").read_text())
|
||||
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
|
||||
def test_seed_has_manifest_description(seed):
|
||||
manifest = json.loads((seed / "manifest.json").read_text())
|
||||
assert manifest["description"].strip()
|
||||
|
||||
|
||||
def test_seed_hermetic_test_passes(monkeypatch):
|
||||
root = str(SEED.parents[2])
|
||||
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
|
||||
def test_seed_hermetic_test_passes(seed, monkeypatch):
|
||||
root = str(seed.parents[2])
|
||||
existing = os.environ.get("PYTHONPATH", "")
|
||||
monkeypatch.setenv("PYTHONPATH", root + os.pathsep + existing)
|
||||
passed, output = run_skill_test(SEED, timeout=30)
|
||||
passed, output = run_skill_test(seed, timeout=30)
|
||||
assert passed, output
|
||||
@@ -92,7 +92,7 @@ def _pipeline_codegen_server(replies: list) -> tuple[ThreadingHTTPServer, str]:
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(length).decode("utf-8")
|
||||
if self.path.endswith("/api/show"):
|
||||
body = json.dumps({"parameters": {"num_ctx": 4242}}).encode("utf-8")
|
||||
body = json.dumps({"parameters": {"num_ctx": 32768}}).encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
|
||||
Reference in new issue
Block a user