From 98ec4ee5e283740e693bbc11f6ddade74559db0c Mon Sep 17 00:00:00 2001 From: Denton Social Date: Mon, 28 Sep 2026 23:30:44 -0500 Subject: [PATCH] codegen: move bridge specifics into the catalog Bridge specifics (service, base-URL config var, auth header/token var, config-var docs, endpoints with error shapes) now live in BridgeInfo and render through describe_bridges(), which is injected into body, retry, regen, elicitation, and testgen prompts. SKILL.md/TESTGEN.md carry only the generic pattern. - regen prompt regains the catalog (was a dangling reference) - elicitation integration hint rides body/retry/regen as an advisory - top-level simplex_bridge_token config var; bootstrap syncs it - simplex seeds read the token and send X-Semif-Token when set --- AGENTS.md | 24 ++++++--- SKILL.md | 59 ++++++++++------------ TESTGEN.md | 9 ++-- config.example.json | 1 + scripts/bootstrap.sh | 4 +- seeds/simplex/connect_link/contract.json | 3 +- seeds/simplex/connect_link/skill.py | 11 +++- seeds/simplex/connect_link/skill.test.py | 31 ++++++++++-- seeds/simplex/next_message/contract.json | 3 +- seeds/simplex/next_message/skill.py | 16 +++++- seeds/simplex/next_message/skill.test.py | 33 ++++++++++-- semif_agent/bridges/__init__.py | 7 ++- semif_agent/bridges/base.py | 7 +++ semif_agent/bridges/registry.py | 37 +++++++++----- semif_agent/bridges/simplex.py | 53 ++++++++++++++++---- semif_agent/codegen.py | 27 +++++++++- semif_agent/skills.py | 3 +- tests/test_bridges.py | 21 +++++++- tests/test_codegen.py | 64 ++++++++++++++++++++++-- 19 files changed, 324 insertions(+), 89 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 17820c9..8258fcd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -111,8 +111,13 @@ codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill declare INTEGRATION service/transport/config_vars); parse/validate (compile + predict/act) + parse_integration / infer_integration / integration_findings; the bridge catalog - (describe_bridges()) is injected into the body + elicitation - prompts; elicitation questions + (describe_bridges()) is injected into the body, retry, regen, + elicitation, and testgen prompts — it is the single source of + bridge specifics (service, base-URL var, auth header/token var, + config-var docs, endpoints with error shapes), while SKILL.md/ + TESTGEN.md carry only the generic pattern; the advisory + elicitation integration hint rides on every body/retry/regen + prompt; elicitation questions + integration hint; TESTGEN.md drives two shared-context calls producing contract.json then skill.test.py (hermetic mechanics test: inline fixtures, loopback http.server for HTTP bodies, no @@ -519,7 +524,9 @@ CLI, unit tests (24) + box integration tests (2). working-tree contract differed from that commit; both degrade to `None` outside a git checkout. Recorded as `contract_ref`/`contract_dirty` on the `skill_writing` trace event; the dashboard shows `SKILL.md @ ` with a `*` - when dirty. + when dirty. **Deferred:** this pointer covers only the generic pattern now that + bridge specifics live in the runtime catalog, not SKILL.md — recording a + catalog revision on the trace is future work. - **Trust boundary**: generated skill code is executed locally (it is imported as a module and its `predict`/`act` run in-process; `skill.test.py` runs as a subprocess in the skill folder). The box is the intended target; treat the @@ -771,9 +778,14 @@ CLI, unit tests (24) + box integration tests (2). codegen-authored skill body never speaks that system's native protocol. SimpleX is the first; adding a service means adding a class to `bridges/registry.py` `CATALOG` and a `config.example.json` block. The catalog - (`BridgeInfo`: name, description, URL config var, endpoints) is injected into - the codegen prompts via `describe_bridges()`, so the model knows what it can - build against and how. + (`BridgeInfo`: name, service, description, URL config var, other config vars + with one-line docs, auth header + token config var, and endpoints with + request/response/error shapes) is injected into every codegen prompt + (body/retry/regen/elicitation/testgen) via `describe_bridges()` and is the + single source of bridge specifics — SKILL.md/TESTGEN.md carry only the generic + pattern. The bridge's optional shared secret is mirrored to the top-level + `simplex_bridge_token` config var (bootstrap syncs it) so bodies can send the + `X-Semif-Token` header. - **Run mode.** `python -m semif_agent.cli bridge [--name simplex]` builds the scheduler (engine lazy, used only for trace) and runs the selected + enabled bridges until interrupted. Each bridge owns its service daemon: `SimplexBridge` diff --git a/SKILL.md b/SKILL.md index 6a86b46..c77c8d2 100644 --- a/SKILL.md +++ b/SKILL.md @@ -154,9 +154,13 @@ talk to. Declaring a transport the body does not use is a broken skill. Some real systems are reached through a **bridge service**: a standalone local process that stands up a small, token-guarded HTTP API in front of the system -and owns its native protocol and credentials. The concrete catalog of bridges -available to you is injected into the prompt at authoring time (render it with -`semif_agent.bridges.describe_bridges()`); read it rather than guessing. +and owns its native protocol and credentials. The concrete catalog of bridges — +which services exist, their base-URL config var, auth, config vars, and the +exact endpoints with their request/response/error shapes — is injected into the +prompt at authoring time (render it with +`semif_agent.bridges.describe_bridges()`); read it rather than guessing. This +section is only the generic pattern; the catalog is the source of the +bridge-specific details. A body must never speak a service's native protocol directly — no WebSocket to `simplex-chat`, no direct daemon access. It calls the bridge's HTTP API with the @@ -165,47 +169,36 @@ integration: ```python INTEGRATION = { - "service": "simplex", + "service": "", "transport": "http", - "config_vars": ["simplex_bridge_url", "simplex_default_contact"], + "config_vars": ["", ""], } ``` -For example, the `simplex` bridge (SimpleX messaging) exposes, at the base URL -in `simplex_bridge_url`: - -| Request | Purpose | -| -------------------------------------- | ------------------------------------------------------------------ | -| `GET /health` | `{"ok": true}` — the bridge is up. | -| `GET /contacts` | `{"contacts": [{"id", "display_name"}]}` — known contacts. | -| `GET /inbox` | Peek buffered inbound messages; does not consume. | -| `GET /inbox/next?contact=` | Pop the oldest unread message (optionally from one contact). | -| `GET /address` | The agent's contact link; creates it on first call. | -| `POST /send` | `{"recipient": "", "text": "..."}` — send. | - -`GET /inbox` returns `{"messages": [{"id", "contact_id", "display_name", "text", -"received_at"}]}`; `GET /inbox/next` returns `{"message": {...} | null}`, where -`null` means nothing is buffered. `GET /address` returns -`{"short_link", "full_link", "created"}`. `POST /send` returns -`{"ok": true, "contact_id": ""}`. The bridge owns the read cursor, so a -read skill needs no state of its own. - Rules: -- **Recipient selection is a SemIf decision.** When more than one conversation - is relevant (e.g. several have buffered messages), resolve which one with a - `ctx.engine.call(...)` sub-decision over the contacts — mirroring how - `calendar.next_event` picks a calendar. Use `simplex_default_contact` only as - the configured fallback when the request does not already make it clear. +- **Read every value from `ctx.config`.** The base URL, any token, and any + default (recipient/contact/target) come from the config vars the catalog + lists. Never hardcode a host, port, or bridge address in the body. +- **Send the auth header when the catalog lists one.** If the catalog names an + auth config var and header, read the var and send it in that header when it is + set; omit the header when the value is blank. +- **Resolve the recipient/target with a SemIf sub-decision.** When more than one + conversation or target is relevant, resolve which one with a + `ctx.engine.call(...)` sub-decision over the catalog's list endpoint (e.g. + contacts or buffered senders), mirroring how `calendar.next_event` picks a + calendar. Use the catalog's default config var only as the configured + fallback when the request does not already make it clear. - **Sending requires user intent.** Send only because the request (or the requirements) asks for it. Never broadcast, never message a contact the user did not name or confirm, and never fabricate a message body as a working value. - **Report real failures.** A bridge error, an unknown recipient, or an empty - inbox is reported honestly in `action_log` / `new_state`; never claim a - message was sent or read when it was not. -- The bridge is local-only, but its URL still comes from `ctx.config` — never - hardcode a host, port, or bridge address in the body. + inbox is reported honestly in `action_log` / `new_state` — use the error + statuses the catalog documents. Never claim a message was sent or read when it + was not. +- **The bridge owns its own state.** Read cursors and similar state live in the + bridge, not in the body; the body keeps no working state of its own. ## Conventions diff --git a/TESTGEN.md b/TESTGEN.md index 28d0cce..743a528 100644 --- a/TESTGEN.md +++ b/TESTGEN.md @@ -75,10 +75,11 @@ A stdlib-only Python script that: headers, body) where practical. The loopback address exists only in the test; the body must read its endpoint from config. - For a messaging skill (a body that talks to a bridge service), stand up a - loopback server implementing the bridge endpoints the body uses (`GET /inbox`, - `GET /inbox/next?contact=`, `GET /address`, `POST /send`) and assert the body - built the real requests. Never connect to a real `simplex-chat` daemon or a - live bridge. + loopback server implementing the bridge endpoints the body uses (the bridge + catalog injected into this prompt lists them) and assert the body built the + real requests. If the catalog names an auth header, set the fixture token in + the fixture config and assert the body sent that header. Never connect to a + real service daemon or a live bridge. - For non-HTTP transports (IMAP, SMTP, subprocess, ...), exercise config resolution, argument construction, and error paths (missing or misconfigured values) without performing the real I/O. diff --git a/config.example.json b/config.example.json index 552954e..4502c0c 100644 --- a/config.example.json +++ b/config.example.json @@ -74,6 +74,7 @@ "skill_bodies": "data/skills", "skill_seeds": "seeds", "simplex_bridge_url": "http://127.0.0.1:5227", + "simplex_bridge_token": "", "log": "data/decisions.jsonl", "trace": "data/runs.jsonl", "category_registry": "data/categories.json", diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh index eb18ac9..83dddc1 100755 --- a/scripts/bootstrap.sh +++ b/scripts/bootstrap.sh @@ -286,12 +286,14 @@ simplex["home_channel"] = home_channel # The standalone SimpleX forwarding bridge owns its own daemon/profile # (simplex_chat.forward_port), separate from the command gateway, and serves the # invite-link / read / send HTTP API skills use. Expose its URL as the top-level -# `simplex_bridge_url` so the data-contract config search auto-populates it. +# `simplex_bridge_url` so the data-contract config search auto-populates it, and +# mirror its optional shared secret as `simplex_bridge_token` for the auth header. bridge = cfg.setdefault("bridges", {}).setdefault("simplex", {}) bridge_port = int(bridge.get("port", 5227)) bridge["enabled"] = True bridge["ws_url"] = f"ws://127.0.0.1:{cfg['simplex_chat'].get('forward_port', 5228)}" cfg["simplex_bridge_url"] = f"http://127.0.0.1:{bridge_port}" +cfg["simplex_bridge_token"] = bridge.get("token", "") or "" simplex.pop("bridge", None) # legacy key; forwarding is a separate service now json.dump(cfg, open(out, "w"), indent=2) PY diff --git a/seeds/simplex/connect_link/contract.json b/seeds/simplex/connect_link/contract.json index cbc03a6..48ae50a 100644 --- a/seeds/simplex/connect_link/contract.json +++ b/seeds/simplex/connect_link/contract.json @@ -1,3 +1,4 @@ { - "simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed)." + "simplex_bridge_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." } diff --git a/seeds/simplex/connect_link/skill.py b/seeds/simplex/connect_link/skill.py index 3d6076d..2aa082a 100644 --- a/seeds/simplex/connect_link/skill.py +++ b/seeds/simplex/connect_link/skill.py @@ -22,7 +22,7 @@ from semif_agent.skills import ActionResult, Prediction INTEGRATION = { "service": "simplex", "transport": "http", - "config_vars": ["simplex_bridge_url"], + "config_vars": ["simplex_bridge_url", "simplex_bridge_token"], } TIMEOUT_SECONDS = 30 @@ -39,8 +39,15 @@ def _base(ctx): 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) + 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")) diff --git a/seeds/simplex/connect_link/skill.test.py b/seeds/simplex/connect_link/skill.test.py index 6239f4f..b516634 100644 --- a/seeds/simplex/connect_link/skill.test.py +++ b/seeds/simplex/connect_link/skill.test.py @@ -24,6 +24,7 @@ class BridgeHandler(BaseHTTPRequestHandler): address = {} address_status = 200 requests = [] + tokens = [] def _send(self, payload, status=200): body = json.dumps(payload).encode("utf-8") @@ -35,6 +36,7 @@ class BridgeHandler(BaseHTTPRequestHandler): def do_GET(self): self.requests.append(self.path) + self.tokens.append(self.headers.get("X-Semif-Token")) url = urllib.parse.urlparse(self.path) if url.path == "/health": self._send({"ok": True, "platform": "simplex"}) @@ -51,15 +53,20 @@ def start_server(address=None, address_status=200): handler = type( "Handler", (BridgeHandler,), - {"address": address or {}, "address_status": address_status, "requests": []}, + { + "address": address or {}, + "address_status": address_status, + "requests": [], + "tokens": [], + }, ) server = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=server.serve_forever, daemon=True).start() return server, handler, f"http://127.0.0.1:{server.server_address[1]}" -def config(url): - return {"simplex_bridge_url": url} +def config(url, token=""): + return {"simplex_bridge_url": url, "simplex_bridge_token": token} def test_reports_existing_link(): @@ -139,12 +146,30 @@ def test_unreachable_bridge_fails_honestly(): print(action.action_log) +def test_auth_token_is_sent_when_configured(): + server, handler, url = start_server( + {"short_link": "simplex:/contact#abc", "full_link": "", "created": False} + ) + try: + ctx = ActionContext(engine=None, config=config(url, token="sekret")) + request = Request("give me your simplex link") + prediction = skill.predict(ctx, request) + action = skill.act(ctx, request, prediction) + assert "simplex:/contact#abc" in action.action_log, action.action_log + assert set(handler.tokens) == {"sekret"}, handler.tokens + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + def main(): test_reports_existing_link() test_reports_freshly_created_link() test_no_provider_is_reported_honestly() test_empty_link_is_reported_honestly() test_unreachable_bridge_fails_honestly() + test_auth_token_is_sent_when_configured() print("ok") diff --git a/seeds/simplex/next_message/contract.json b/seeds/simplex/next_message/contract.json index f2bfe9f..393159a 100644 --- a/seeds/simplex/next_message/contract.json +++ b/seeds/simplex/next_message/contract.json @@ -1,4 +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_default_contact": "Optional display name or contact id to read from by default when the conversation is not otherwise clear; leave blank to always choose among the conversations with unread messages." + "simplex_default_contact": "Optional display name or contact id to read from by default when the conversation is not otherwise clear; leave blank to always choose among the conversations with unread messages.", + "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." } diff --git a/seeds/simplex/next_message/skill.py b/seeds/simplex/next_message/skill.py index 887dd86..2102a6d 100644 --- a/seeds/simplex/next_message/skill.py +++ b/seeds/simplex/next_message/skill.py @@ -25,9 +25,14 @@ from semif_agent.skills import ActionResult, Prediction INTEGRATION = { "service": "simplex", "transport": "http", - "config_vars": ["simplex_bridge_url", "simplex_default_contact"], + "config_vars": [ + "simplex_bridge_url", + "simplex_default_contact", + "simplex_bridge_token", + ], } + TIMEOUT_SECONDS = 20 @@ -42,8 +47,15 @@ def _base(ctx): 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) + 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")) diff --git a/seeds/simplex/next_message/skill.test.py b/seeds/simplex/next_message/skill.test.py index 105e87e..3d3ecdb 100644 --- a/seeds/simplex/next_message/skill.test.py +++ b/seeds/simplex/next_message/skill.test.py @@ -42,6 +42,7 @@ class FakeEngine: class BridgeHandler(BaseHTTPRequestHandler): messages = [] requests = [] + tokens = [] def _send(self, payload, status=200): body = json.dumps(payload).encode("utf-8") @@ -53,6 +54,7 @@ class BridgeHandler(BaseHTTPRequestHandler): 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)}) @@ -72,7 +74,11 @@ class BridgeHandler(BaseHTTPRequestHandler): def start_server(messages): - handler = type("Handler", (BridgeHandler,), {"messages": list(messages), "requests": []}) + handler = type( + "Handler", + (BridgeHandler,), + {"messages": list(messages), "requests": [], "tokens": []}, + ) server = ThreadingHTTPServer(("127.0.0.1", 0), handler) threading.Thread(target=server.serve_forever, daemon=True).start() return server, handler, f"http://127.0.0.1:{server.server_address[1]}" @@ -88,8 +94,12 @@ def message(identifier, contact, name, text): } -def config(url, default=""): - return {"simplex_bridge_url": url, "simplex_default_contact": default} +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(): @@ -192,12 +202,29 @@ def test_unreachable_bridge_fails_honestly(): 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") + prediction = skill.predict(ctx, request) + action = skill.act(ctx, request, prediction) + 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 main(): test_multiple_senders_uses_semif_decision() test_default_contact_skips_decision() test_single_sender_needs_no_decision() test_empty_inbox_is_reported_honestly() test_unreachable_bridge_fails_honestly() + test_auth_token_is_sent_when_configured() print("ok") diff --git a/semif_agent/bridges/__init__.py b/semif_agent/bridges/__init__.py index 02c3095..e2fc707 100644 --- a/semif_agent/bridges/__init__.py +++ b/semif_agent/bridges/__init__.py @@ -14,8 +14,11 @@ Two boundaries matter: own processes (`python -m semif_agent.cli bridge`) against their own service daemons/profiles. This isolation is non-negotiable (see AGENTS.md). - **The catalog is visible to codegen.** `describe_bridges()` is injected into - the code-generation prompts so the model knows which real services it may - build against and how to reach them. + every code-generation prompt (body, retry, regen, elicitation, testgen) and is + the single source of bridge specifics: the model learns which real services it + may build against, each one's base-URL config var, auth header/token var, + config-var docs, and its endpoints with request/response/error shapes. SKILL.md + and TESTGEN.md carry only the generic pattern. """ from .base import BridgeInfo, BridgeService diff --git a/semif_agent/bridges/base.py b/semif_agent/bridges/base.py index efdaa26..5d25897 100644 --- a/semif_agent/bridges/base.py +++ b/semif_agent/bridges/base.py @@ -34,6 +34,13 @@ class BridgeInfo: endpoints: tuple[str, ...] = () #: Other `ctx.config` keys a body built on this bridge may read. config_vars: tuple[str, ...] = field(default=()) + #: One-line semantic description per config var: `(name, description)`. + #: Every entry in `config_vars` must be documented here. + config_var_docs: tuple[tuple[str, str], ...] = () + #: Optional shared-secret header the bridge enforces when its token is set + #: (e.g. `X-Semif-Token`), and the top-level `ctx.config` var holding it. + auth_header: str = "" + auth_config_var: str = "" class BridgeService(ABC): diff --git a/semif_agent/bridges/registry.py b/semif_agent/bridges/registry.py index d97f138..aeb769c 100644 --- a/semif_agent/bridges/registry.py +++ b/semif_agent/bridges/registry.py @@ -33,24 +33,37 @@ def known_infos() -> list[BridgeInfo]: def describe_bridges() -> str: """A prompt block describing every available bridge service. - Injected into the skill-body and elicitation prompts so codegen knows which - real services it may build a skill against, how to reach each one, and which - `ctx.config` variable carries its URL. Static — no bridge needs to be - running or enabled. + Injected into the skill-body, retry, regen, elicitation, and testgen + prompts so codegen knows which real services it may build a skill against, + how to reach and authenticate to each one, and which `ctx.config` variables + carry its URL, token, and other values. This is the single source of bridge + specifics — SKILL.md/TESTGEN.md carry only the generic pattern. Static: no + bridge needs to be running or enabled. """ lines = [ "Available bridge services (call these over HTTP with urllib.request; " - "never speak a service's native protocol directly):", + "never speak a service's native protocol directly; read every value " + "from ctx.config):", ] for info in known_infos(): - lines.append(f"- {info.name}: {info.description}") - lines.append(f" config var: {info.url_config_var}") + lines.append(f"- {info.name} (service: {info.service}): {info.description}") + lines.append(f" base URL config var: {info.url_config_var}") + if info.auth_header and info.auth_config_var: + lines.append( + f" auth: send the value of {info.auth_config_var} in the " + f"{info.auth_header} header when it is set" + ) + docs = dict(info.config_var_docs) if info.config_vars: - other = [v for v in info.config_vars if v != info.url_config_var] - if other: - lines.append(f" other config vars: {', '.join(other)}") - for endpoint in info.endpoints: - lines.append(f" {endpoint}") + lines.append(" config vars:") + for name in info.config_vars: + description = docs.get(name) + suffix = f" — {description}" if description else "" + lines.append(f" - {name}{suffix}") + if info.endpoints: + lines.append(" endpoints:") + for endpoint in info.endpoints: + lines.append(f" - {endpoint}") return "\n".join(lines) + "\n" diff --git a/semif_agent/bridges/simplex.py b/semif_agent/bridges/simplex.py index 63bbb38..8ee0d08 100644 --- a/semif_agent/bridges/simplex.py +++ b/semif_agent/bridges/simplex.py @@ -32,18 +32,51 @@ class SimplexBridge(BridgeService): ), url_config_var="simplex_bridge_url", endpoints=( - "GET /health -> {\"ok\": true} — the bridge is up", - "GET /contacts -> {\"contacts\": [{\"id\", \"display_name\"}]}", - "GET /inbox -> peek buffered inbound messages (does not consume)", - "GET /inbox/next?contact= -> pop the oldest unread message for a " - "contact (or any contact) -> {\"message\": {...}|null}", - "GET /address -> the agent's SimpleX contact link " - "(creates it on first call) -> {\"short_link\", \"full_link\", " - "\"created\"}", + "GET /health -> 200 {\"ok\": true, \"platform\": \"simplex\"} — the " + "bridge is up", + "GET /contacts -> 200 {\"contacts\": [{\"id\", \"display_name\"}]} — " + "contacts learned from inbound messages", + "GET /inbox -> 200 {\"messages\": [{\"id\", \"contact_id\", " + "\"display_name\", \"text\", \"received_at\"}]} — peek buffered " + "inbound messages; does not consume", + "GET /inbox/next?contact= -> 200 {\"message\": {...}|null} — pop " + "the oldest unread message (optionally from one contact); null means " + "none buffered. The bridge owns the read cursor", + "GET /address -> 200 {\"short_link\", \"full_link\", \"created\"} — " + "the agent's contact link; creates it on first call. 503 when the " + "daemon is not connected, 502 when the lookup fails", "POST /send {\"recipient\": \"\", \"text\": \"...\"} " - "-> {\"ok\", \"contact_id\"}", + "-> 200 {\"ok\": true, \"contact_id\": \"\"}; 400 {\"error\": " + "\"...\"} on a missing/invalid field or an unknown recipient", + "any request -> 401 {\"error\": \"unauthorized\"} when the token is " + "configured and the auth header is missing or wrong", ), - config_vars=("simplex_bridge_url", "simplex_default_contact"), + config_vars=( + "simplex_bridge_url", + "simplex_default_contact", + "simplex_bridge_token", + ), + config_var_docs=( + ( + "simplex_bridge_url", + "Base URL of the local SimpleX forwarding bridge " + "(e.g. http://127.0.0.1:5227); never hardcode it in the body.", + ), + ( + "simplex_default_contact", + "Optional default SimpleX contact (contact id or display name) " + "used when the request does not already make the conversation " + "clear; leave blank to always choose among senders.", + ), + ( + "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.", + ), + ), + auth_header="X-Semif-Token", + auth_config_var="simplex_bridge_token", ) def __init__(self, config: dict | None = None, trace=None, daemon=None): diff --git a/semif_agent/codegen.py b/semif_agent/codegen.py index c3fa421..9957eb4 100644 --- a/semif_agent/codegen.py +++ b/semif_agent/codegen.py @@ -652,6 +652,24 @@ def _requirements_block(requirements: dict[str, str] | None) -> str: return f"Requirements gathered from the product owner:\n{lines}\n" +def _integration_hint_block(draft: SkillDraft) -> str: + """Advisory integration hint from elicitation: service + transport. + + Never overrides the request, requirements, or SKILL.md contract — it only + biases the body writer toward the integration the questions were aiming at. + """ + integration = getattr(draft, "integration", None) or {} + service = integration.get("service") + transport = integration.get("transport") + if not service and not transport: + return "" + return ( + "Elicitation pointed at this integration (advisory only: follow the " + "request, requirements, and contract if they disagree): " + f"service={service or 'unknown'}, transport={transport or 'unknown'}.\n" + ) + + def build_skill_body_prompt( request: Request, category: str, @@ -683,6 +701,7 @@ def build_skill_body_prompt( f"Existing skills in this category: {existing}\n" f"Existing categories:\n{tree_summary(tree)}\n" f"{req_block}" + f"{_integration_hint_block(draft)}" f"{describe_bridges()}\n" f"{BODY_DIRECTIVES}" "Write the Python module body now. Reply with ONLY valid Python code " @@ -997,6 +1016,7 @@ def _retry_prompt( f"Skill name: {draft.name}\n" f"Skill description: {draft.description}\n" f"{_requirements_block(requirements)}" + f"{_integration_hint_block(draft)}" f"{describe_bridges()}\n" f"{BODY_DIRECTIVES}" "Reply with ONLY valid Python defining `predict` and `act`. No prose, " @@ -1070,7 +1090,7 @@ ELICITATION_EXAMPLES = [ "How does it authenticate with the service, and should that credential come from the app's config?", "What does a successful run look like — what should it report back to you?", "If the service is unreachable or refuses the action, should the run fail loudly or record 'could not complete' as the result?", - "Should this skill send or read SimpleX messages through the simplex bridge, and if so which conversation (resolved by contact name)?", + "Should this skill read or send through one of the available bridge services (see the catalog below), and if so which conversation or target?", ] @@ -1287,7 +1307,8 @@ def build_testgen_base_prompt( user = ( f"Skill: {category}.{name}\n" f"Request: {request.text}\n" - f"Finished skill body:\n```python\n{skill_code}\n```" + f"Finished skill body:\n```python\n{skill_code}\n```\n" + f"{describe_bridges()}" ) return [ {"role": "system", "content": system}, @@ -1527,6 +1548,8 @@ def _regen_body_prompt( f"Skill description: {draft.description}\n" f"Evidence:\n{render_evidence(evidence)}\n" f"Previous body:\n```python\n{previous_code}\n```\n" + f"{_integration_hint_block(draft)}" + f"{describe_bridges()}\n" f"{BODY_DIRECTIVES}" "Reply with ONLY valid Python defining `predict` and `act`. No prose, " "no markdown fences, no JSON." diff --git a/semif_agent/skills.py b/semif_agent/skills.py index 5153eed..b355ec4 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -124,7 +124,8 @@ class SkillDraft: `requirements` maps elicitation questions (asked of the human during authoring) to their answers; they are fed to the body-writer so the body reflects the refined product goal. `integration` carries the service and - transport the answers point at, so the body writer implements exactly that. + transport the answers point at; it is fed to the body writer as an advisory + hint only — the SKILL.md contract, request, and requirements still win. """ name: str diff --git a/tests/test_bridges.py b/tests/test_bridges.py index e71970d..d6aa873 100644 --- a/tests/test_bridges.py +++ b/tests/test_bridges.py @@ -240,12 +240,29 @@ def test_stop_closes_the_daemon(): def test_known_infos_include_simplex(): infos = {info.name: info for info in known_infos()} assert "simplex" in infos - assert infos["simplex"].url_config_var == "simplex_bridge_url" + info = infos["simplex"] + assert info.service == "simplex" + assert info.url_config_var == "simplex_bridge_url" + assert info.auth_header == "X-Semif-Token" + assert info.auth_config_var == "simplex_bridge_token" -def test_describe_bridges_names_the_service_and_config_var(): +def test_every_bridge_documents_its_config_vars_and_auth(): + for info in known_infos(): + docs = dict(info.config_var_docs) + assert set(info.config_vars) <= set(docs), info.name + assert all(description.strip() for description in docs.values()), info.name + if info.auth_header or info.auth_config_var: + assert info.auth_header and info.auth_config_var, info.name + assert info.auth_config_var in info.config_vars, info.name + + +def test_describe_bridges_renders_service_auth_and_endpoints(): text = describe_bridges() assert "simplex" in text + assert "service: simplex" in text assert "simplex_bridge_url" in text + assert "X-Semif-Token" in text + assert "simplex_bridge_token" in text assert "/inbox/next" in text assert "never speak" in text diff --git a/tests/test_codegen.py b/tests/test_codegen.py index d5986e6..fd6c425 100644 --- a/tests/test_codegen.py +++ b/tests/test_codegen.py @@ -23,6 +23,7 @@ from semif_agent.codegen import ( _retry_prompt, build_elicitation_prompt, build_skill_body_prompt, + build_testgen_base_prompt, extract_integration, generate_data_contract, generate_requirements, @@ -42,6 +43,7 @@ from semif_agent.codegen import ( run_skill_test, skill_contract_ref, ) +from semif_agent.bridges.registry import describe_bridges from semif_agent.decisions import Request from semif_agent.skills import ( Skill, @@ -1681,12 +1683,14 @@ def test_skill_contract_lists_all_transports(): assert transport in text -def test_skill_contract_documents_bridge_services(): +def test_skill_contract_documents_bridge_pattern_only(): text = read_skill_contract() - assert "simplex_bridge_url" in text - assert "/inbox/next" in text - assert "/send" in text + # The generic pattern lives in SKILL.md; the bridge specifics do not. + assert "describe_bridges()" in text assert "never speak a service's native protocol" in text + assert "simplex_bridge_url" not in text + assert "/inbox/next" not in text + assert "X-Semif-Token" not in text def test_body_directives_expose_bridge_services(): @@ -1704,6 +1708,8 @@ def test_body_prompts_require_real_action_and_integration(): assert "Perform the real action" in joined assert "INTEGRATION" in joined assert "hermetic mechanics check" in joined + assert "service: simplex" in joined + assert "simplex_bridge_url" in joined retry = _retry_prompt( Request("check if the service is up"), "tracking", @@ -1713,6 +1719,56 @@ def test_body_prompts_require_real_action_and_integration(): ) assert "INTEGRATION" in retry[1]["content"] assert BODY_DIRECTIVES in retry[1]["content"] + assert "service: simplex" in retry[1]["content"] + + +def test_body_prompt_carries_the_advisory_integration_hint(): + tree = build_tree(build_skills({"skills": {}})) + draft = SkillDraft( + name="probe", + description="Probe the service.", + integration={"service": "simplex", "transport": "http"}, + ) + messages = build_skill_body_prompt( + Request("send a message"), "messaging", draft, tree, "THE CONTRACT" + ) + joined = messages[1]["content"] + assert "advisory only" in joined + assert "service=simplex" in joined + assert "transport=http" in joined + + +def test_regen_prompt_includes_catalog_and_integration_hint(): + from semif_agent.codegen import _regen_body_prompt + + draft = SkillDraft( + name="probe", + description="Probe the service.", + integration={"service": "simplex", "transport": "http"}, + ) + messages = _regen_body_prompt( + Request("send a message"), + "messaging", + draft, + "THE CONTRACT", + GOOD_BODY, + {"error": "boom"}, + reason_kind="run_failure", + ) + joined = messages[1]["content"] + assert "service: simplex" in joined + assert "simplex_bridge_url" in joined + assert "service=simplex" in joined + assert BODY_DIRECTIVES in joined + + +def test_testgen_base_prompt_includes_catalog(): + messages = build_testgen_base_prompt( + Request("send a message"), "messaging", "send_message", GOOD_BODY, "THE CONTRACT" + ) + joined = messages[1]["content"] + assert describe_bridges().strip() in joined + assert "simplex_bridge_url" in joined def test_retry_prompt_carries_requirements():