From 41c18e6c476256672b6d393e4dbf16712c13ad4e Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Tue, 13 Oct 2026 23:56:06 +0000 Subject: [PATCH] Decouple bridges: ship each with its pack MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The core no longer owns concrete bridge implementations. A bridge now ships inside the pack that declares it (packs//bridge/.py, plus its package marker, optional client module, and hermetic test), and the core registry imports it by convention from the pack's `bridges`. Core keeps only: - bridges/base.py: BridgeInfo + BridgeService (shared HTTP/JSON/auth layer), plus a new BridgeService.from_config build hook (a bridge that needs the scheduler's `llm` client or top-level fallback values declares that itself, replacing build_bridge's per-name special-casing) and checkout_root() so a pack-relative bridge can still anchor .runtime/ paths; - bridges/inbox.py: the generic MessagingInbox; - bridges/llm.py: the one shared, pack-less LLMBridge (CORE_BRIDGES); - bridges/registry.py: discovery (discover_bridge_classes/known_infos/ describe_bridges/derived_config_vars/build_bridge/run_bridges) scanning each pack's bridge/ dir, plus load_pack_bridge_module/package for tests. Moved to their packs: simplex, nextcloud (+client), outlook (+client), browser (+client) — each with its hermetic test. tests/test_bridges.py now covers the core (shared LLM bridge + registry); tests/test_packs.py runs every pack's bridge test. Docs (AGENTS.md, PACKGEN.md, README.md) updated. Packs pushed separately to pack.. --- AGENTS.md | 156 +-- PACKGEN.md | 122 ++- README.md | 27 +- semif_agent/bridges/__init__.py | 19 +- semif_agent/bridges/base.py | 30 + semif_agent/bridges/browser.py | 369 ------- semif_agent/bridges/browser_client.py | 441 -------- semif_agent/bridges/llm.py | 6 + semif_agent/bridges/nextcloud.py | 604 ----------- semif_agent/bridges/nextcloud_client.py | 1249 ----------------------- semif_agent/bridges/outlook.py | 398 -------- semif_agent/bridges/outlook_client.py | 1044 ------------------- semif_agent/bridges/registry.py | 254 ++++- semif_agent/bridges/simplex.py | 493 --------- semif_agent/cli.py | 6 + semif_agent/packs.py | 11 +- tests/test_bridges.py | 644 +----------- tests/test_browser_bridge.py | 373 ------- tests/test_nextcloud_bridge.py | 1038 ------------------- tests/test_outlook_bridge.py | 646 ------------ tests/test_packs.py | 31 + 21 files changed, 485 insertions(+), 7476 deletions(-) delete mode 100644 semif_agent/bridges/browser.py delete mode 100644 semif_agent/bridges/browser_client.py delete mode 100644 semif_agent/bridges/nextcloud.py delete mode 100644 semif_agent/bridges/nextcloud_client.py delete mode 100644 semif_agent/bridges/outlook.py delete mode 100644 semif_agent/bridges/outlook_client.py delete mode 100644 semif_agent/bridges/simplex.py delete mode 100644 tests/test_browser_bridge.py delete mode 100644 tests/test_nextcloud_bridge.py delete mode 100644 tests/test_outlook_bridge.py diff --git a/AGENTS.md b/AGENTS.md index 39e5b4a..786493b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -291,43 +291,42 @@ gateway/ messenger COMMAND intake/reply — and nothing else. base.py: `gateway.simplex` / `gateway.lxmf` / `gateway.voice`. The gateway MUST NOT read history, show/create invite links, or compose messages — see "gateway isolation" below. -bridges/ standalone third-party API bridges (SimpleX, the LLM bridge, - and Nextcloud). base.py: - BridgeInfo + BridgeService (shared localhost JSON HTTP layer, - `X-Semif-Token` guard). inbox.py: MessagingInbox (bounded FIFO + - contacts learned from inbound DMs and the daemon contact list, - bridge-owned read cursor). simplex.py: SimplexBridge — - owns its OWN simplex-chat daemon/profile (separate from the - gateway's), buffers every inbound DM, refreshes the daemon - contact list on (re)connect + on demand, serves invite-link/ - read/send plus daemon-backed unread + per-chat history. - llm.py: LLMBridge — a generic `POST /chat` in front of the - scheduler's configured `llm` client (reused, not re-configured), - so bodies get short generated text (e.g. an event title + - description) over HTTP. - nextcloud.py + nextcloud_client.py: NextcloudBridge — files - (WebDAV), calendar events + tasks (CalDAV), contacts (CardDAV), - and Notes (OCS) behind one JSON surface, so bodies never speak - DAV/OCS; no service daemon (stdlib-only), connection from - `bridges.nextcloud` with a fallback to the top-level - `nextcloud_*` values the nextcloud pack skills use. - outlook.py + outlook_client.py: OutlookBridge — the user's - Microsoft account (Outlook / Microsoft 365) over Microsoft Graph: - mail, calendar events, Microsoft To Do tasks, contacts, and - OneDrive files, plus the OAuth2 device-code + refresh flow. No - daemon (stdlib-only `urllib`); tokens stored under - `.runtime/outlook/token.json` and seeded once with - `packs/outlook/scripts/outlook-auth.py`; connection from `bridges.outlook`. - browser.py + browser_client.py: BrowserBridge — real browser - automation via Playwright (open/read/click/fill/screenshot), - owning a persistent browser profile; optional heavy dep - (requirements/browser.txt, `bootstrap.sh --browser`), lazy so a - missing browser is a per-call 503 and never blocks the other - bridges. Runs the async API on one dedicated event-loop thread. - registry.py: CATALOG, describe_bridges() (catalog injected - into the codegen prompts), run_bridges() (threads the scheduler's - `llm` client into the LLM bridge). Run with `python -m - semif_agent.cli bridge [--name NAME]`; config under `bridges`. +bridges/ standalone third-party API bridges. The core keeps only the + shared contract + discovery: base.py: BridgeInfo + + BridgeService (shared localhost JSON HTTP layer, + `X-Semif-Token` guard, `from_config` build hook, + `checkout_root()` for `.runtime/` anchoring). inbox.py: + MessagingInbox (bounded FIFO + contacts learned from inbound DMs + and the daemon contact list, bridge-owned read cursor). + llm.py: LLMBridge — the one shared, pack-less bridge (a generic + `POST /chat` in front of the scheduler's configured `llm` + client, reused not re-configured). registry.py: discovers each + bridge from its pack's `bridge/` by convention (no hardcoded + CATALOG), describe_bridges() (catalog injected into the codegen + prompts), derived_config_vars(), run_bridges() (threads the + scheduler's `llm` client through each bridge's `from_config`). + The concrete bridges ship with their packs: + packs/simplex/bridge/simplex.py (SimplexBridge — owns its OWN + simplex-chat daemon/profile, separate from the gateway's, + buffers every inbound DM, refreshes the daemon contact list on + (re)connect + on demand, serves invite-link/read/send plus + daemon-backed unread + per-chat history); + packs/nextcloud/bridge/nextcloud.py + nextcloud_client.py + (files/WebDAV, calendar events + tasks/CalDAV, contacts/CardDAV, + Notes/OCS behind one JSON surface; no daemon, stdlib-only; + `from_config` falls back to the top-level `nextcloud_*` values); + packs/outlook/bridge/outlook.py + outlook_client.py (Microsoft + Graph: mail, calendar, To Do, contacts, OneDrive, plus the + OAuth2 device-code + refresh flow; tokens under + `.runtime/outlook/token.json`, seeded once with + `packs/outlook/scripts/outlook-auth.py`); + packs/browser/bridge/browser.py + browser_client.py (Playwright + open/read/click/fill/screenshot, owning a persistent browser + profile; optional heavy dep, lazy so a missing browser is a + per-call 503 and never blocks the other bridges; runs the async + API on one dedicated event-loop thread). + Run with `python -m semif_agent.cli bridge [--name NAME]`; + config under `bridges`. simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway adapter and the bridge (parse direct text across v7 shapes, structured `/_send`, corrId→Future round-trips, contact-address @@ -1453,13 +1452,19 @@ CLI, unit tests (24) + integration tests (2). needed). `tests/test_simplex_ws.py` covers the neutral protocol layer (parse shapes, accept ids, corrId round-trips, address show/create). `tests/test_bridges.py` - exercises `SimplexBridge` over a real loopback server (peek/pop, recipient - resolution, outbound routing, token/body validation, `/address` success/503/502, - daemon close on stop, catalog/`describe_bridges()`). + covers what stays in the core: the shared LLM bridge (over a real loopback + server) and the discovery registry (`known_infos`/`describe_bridges`/ + `derived_config_vars`). `tests/test_packs.py` hermetically tests every `packs//skills///` package, including `simplex.next_message`, `simplex.send_message`, and - `simplex.connect_link`. `tests/test_voice_gateway.py` drives the voice loop + `simplex.connect_link`, and runs every pack's bridge test + (`packs//bridge/test__bridge.py`: the SimpleX bridge over a real + loopback server — peek/pop, recipient resolution, outbound routing, + token/body validation, `/address` success/503/502, daemon close on stop — and + the Nextcloud/Outlook/Browser bridges over a loopback `http.server` with a fake + service or driver). + `tests/test_voice_gateway.py` drives the voice loop with injected fake engines (wake gating, endpointing, half-duplex, `speak` truncation/failure, adapter + CLI wiring) — no hardware, network, or heavy packages. `tests/test_voice_record.py` covers the @@ -1491,9 +1496,9 @@ CLI, unit tests (24) + integration tests (2). `scripts/bootstrap.sh` into the gitignored `packs//`. The manifest binds the pieces that used to be scattered by convention: `concern`/`title`, `categories` (id -> scope description, feeding - `CATEGORY_DESCRIPTIONS`), `bridges` (names referencing `bridges/registry.py` - `CATALOG` — bridge *code* stays in `bridges/`, isolation is non-negotiable), - `requires` (optional deps like `playwright`), `enabled_by_default`, and a + `CATEGORY_DESCRIPTIONS`), `bridges` (names the pack ships under `bridge/` and + talks to; the core registry discovers them by convention), `requires` + (optional deps like `playwright`), `enabled_by_default`, and a `config` schema. `semif_agent/packs.py` discovers them (`PackRegistry`, which scans the `skill_packs` roots for `*/pack.json`; a root with no manifest is one implicit pack, so a plain skills directory works) and `merge_packs` loads every @@ -1524,10 +1529,12 @@ CLI, unit tests (24) + integration tests (2). no bridge — its skill calls the API directly. When a bridge fronts a service, a codegen-authored skill body calls the bridge and never speaks that system's native protocol. - SimpleX is the first; adding a service means adding a class to - `bridges/registry.py` `CATALOG`, a `pack.json` whose `config` schema carries - its block (see `semif_agent/packs.py`; a shared, skill-less bridge like the - LLM bridge goes in the core `SHARED_BRIDGE_SCHEMA` instead). The catalog + A bridge **ships with its pack**: the pack declares it in `bridges` and ships + `packs//bridge/.py` (+ `bridge/__init__.py` and any sibling client + module); the core registry imports it by convention — there is no core + `CATALOG` to edit. The one shared, pack-less bridge is the LLM bridge, whose + `config` block lives in the core `SHARED_BRIDGE_SCHEMA` (see + `semif_agent/packs.py`). The catalog (`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 @@ -1544,7 +1551,7 @@ CLI, unit tests (24) + integration tests (2). command gateway's. On a bootstrap-provisioned host, `scripts/bootstrap.sh` renders and enables `semif-simplex-forward.service` (the second daemon) and `semif-bridge.service` (`cli bridge`) alongside the gateway units. -- **HTTP surface** (`bridges/base.py` + `bridges/simplex.py`): JSON in/out, +- **HTTP surface** (`bridges/base.py` + `packs/simplex/bridge/simplex.py`): JSON in/out, localhost-bound, optional shared-secret `X-Semif-Token` header. `SimplexBridge` buffers **every** inbound DM (no allowlist — the user wants to see who reached the bot through its invite link) in a bounded `MessagingInbox` that owns the @@ -1583,7 +1590,7 @@ CLI, unit tests (24) + integration tests (2). error) in front of the agent's language model, so a body can ask for short generated text over HTTP instead of speaking the OpenAI-compatible protocol itself. It does **not** own the model connection: `run_bridge` passes the - scheduler's already-configured `llm` client through `run_bridges`/`build_bridge` + scheduler's already-configured `llm` client through `run_bridges`/`from_config` into `LLMBridge`, so the endpoint/model/sampler stay configured once in the top-level `llm` block; the `bridges.llm` block carries only the local listener (`enabled`/`host`/`port`/`token`). Bodies reach it via the derived @@ -1592,7 +1599,8 @@ CLI, unit tests (24) + integration tests (2). client it reports `502`, never a fabricated reply. `nextcloud.create_event` is the first consumer (title + description extraction, cached in `request.meta` across a `needs_input` resume). -- **Nextcloud bridge** (`bridges/nextcloud.py` + `bridges/nextcloud_client.py`). +- **Nextcloud bridge** (`packs/nextcloud/bridge/nextcloud.py` + + `nextcloud_client.py`). Wraps the account's native protocols — WebDAV files, CalDAV calendar events and tasks (VTODO), CardDAV contacts, and the OCS Notes API — behind one uniform JSON surface, so a body never speaks DAV/OCS directly. It has **no service @@ -1601,7 +1609,7 @@ CLI, unit tests (24) + integration tests (2). instantly inside the existing `semif-bridge.service`. HTTP Basic auth uses the username + app password. The connection is configured in `bridges.nextcloud` (`url`/`username`/`app_password`, plus `default_calendar`/`default_addressbook` - and `verify_tls`/`timeout`); `build_bridge` passes the top-level + and `verify_tls`/`timeout`); `NextcloudBridge.from_config` passes the top-level `nextcloud_url`/`nextcloud_username`/`nextcloud_app_password`/ `nextcloud_default_calendar`/`nextcloud_default_addressbook` as a fallback, so the same account the nextcloud pack skills collect is configured once and a block value @@ -1621,9 +1629,9 @@ CLI, unit tests (24) + integration tests (2). updates edit the stored iCalendar properties in place (preserving VALARM/ ATTENDEE), guarded by `If-Match`; creates use `If-None-Match: *`. Calendar/ addressbook defaults resolve from config when a request names none and the - account has several. `tests/test_nextcloud_bridge.py` drives the real client - over a loopback `http.server` faking Nextcloud's DAV/OCS shapes. -- **Outlook bridge** (`bridges/outlook.py` + `bridges/outlook_client.py`). + account has several. `packs/nextcloud/bridge/test_nextcloud_bridge.py` drives + the real client over a loopback `http.server` faking Nextcloud's DAV/OCS shapes. +- **Outlook bridge** (`packs/outlook/bridge/outlook.py` + `outlook_client.py`). Wraps the user's Microsoft account — Outlook / Microsoft 365 mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files — behind one uniform JSON surface over **Microsoft Graph**, so a body never speaks Graph or @@ -1651,9 +1659,9 @@ CLI, unit tests (24) + integration tests (2). (`/contacts` search), and OneDrive (`/files` list, `/files/read` text-or-base64, `POST /files/write`). Graph's `@odata.nextLink` paging and `429`/`Retry-After` backoff are handled in the client. - `tests/test_outlook_bridge.py` drives the real client over a loopback - `http.server` faking the token endpoint and Graph shapes. -- **Browser bridge** (`bridges/browser.py` + `bridges/browser_client.py`). + `packs/outlook/bridge/test_outlook_bridge.py` drives the real client over a + loopback `http.server` faking the token endpoint and Graph shapes. +- **Browser bridge** (`packs/browser/bridge/browser.py` + `browser_client.py`). Real browser automation via **Playwright** — open a URL, read a page's text or links, take a screenshot, and click/fill/press/select to complete a flow — behind one uniform JSON surface, so a body never bundles a browser stack. It is @@ -1692,8 +1700,9 @@ CLI, unit tests (24) + integration tests (2). `/wait`, `/back`, `/forward`, `/reset`. Bodies reach it via the derived `browser_bridge_url` (+ optional `browser_bridge_token`). Three `packs/browser/skills/browser/*` skills ship (`open_page`, `read_page`, `screenshot`). - `tests/test_browser_bridge.py` exercises the routes over a loopback HTTP server - with an injected fake driver (no browser, no Playwright needed). + `packs/browser/bridge/test_browser_bridge.py` exercises the routes over a + loopback HTTP server with an injected fake driver (no browser, no Playwright + needed). ## Bridge backlog (one session per item) @@ -1701,7 +1710,7 @@ 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`, +- [x] **1. Contact-list refresh from the daemon** (`packs/simplex/bridge/simplex.py`, `simplex_ws.py`). Shipped: `SimplexDaemon.contacts()` / `request_contacts()` query `/_contacts ` (active user from `/user` → `activeUser.userId`, cached, falling back to the configured `user_id`) over @@ -1710,7 +1719,7 @@ covered. Deferred follow-ups: /contacts`, and a send-resolution miss), so `/send` can address a contact it has never received from. Best-effort: a disconnected daemon keeps the cached set. -- [x] **2. Message history + true unread** (`bridges/simplex.py`, +- [x] **2. Message history + true unread** (`packs/simplex/bridge/simplex.py`, `simplex_ws.py`). Shipped: `SimplexDaemon.chats(unread_only, count)` / `request_chats()` query `/_get chats count= {"type":"filters","favorite":false,"unread":true}` and parse @@ -1735,17 +1744,18 @@ covered. Deferred follow-ups: 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 - in `CATALOG` and seeded under `bridges.llm` (its URL is derived from that block). - `nextcloud.create_event` extracts its title + description through it. -- [x] **5. More bridges.** Each new third-party API gets its own `bridges/.py` - + config block + `CATALOG` entry; the codegen prompts pick it up automatically - through `describe_bridges()`. Nextcloud shipped (`bridges/nextcloud.py` + - `bridges/nextcloud_client.py`): files/calendars/tasks/contacts/notes over one + (threaded through `run_bridges`/`from_config`, never re-configured), the one + shared core built-in, seeded under `bridges.llm` (its URL is derived from that + block). `nextcloud.create_event` extracts its title + description through it. +- [x] **5. More bridges.** Each new third-party API gets its own pack + (`packs//bridge/.py`) + config block; the core registry discovers it + by convention and the codegen prompts pick it up automatically + through `describe_bridges()`. Nextcloud shipped (`packs/nextcloud/bridge/nextcloud.py` + + `nextcloud_client.py`): files/calendars/tasks/contacts/notes over one JSON surface, no daemon, connection from `bridges.nextcloud` with a top-level `nextcloud_*` fallback. Future bridges follow the same shape. -- [x] **6. Outlook / Microsoft Graph bridge** (`bridges/outlook.py` + - `bridges/outlook_client.py`). Shipped: the `OutlookBridge` exposes mail, +- [x] **6. Outlook / Microsoft Graph bridge** (`packs/outlook/bridge/outlook.py` + + `outlook_client.py`). Shipped: the `OutlookBridge` exposes mail, calendar, Microsoft To Do, contacts, and OneDrive over one JSON surface in front of Graph; OAuth2 device-code + refresh (`packs/outlook/scripts/outlook-auth.py`, tokens under `.runtime/outlook/token.json`); seven `packs/outlook/skills/outlook/*` skills @@ -1753,8 +1763,8 @@ covered. Deferred follow-ups: `create_task`, `list_contacts`, `list_files`). Deferred: writing/reusing Outlook app-registration guidance in the docs, and a mail-send seed that attaches files. -- [x] **7. Browser bridge (Playwright)** (`bridges/browser.py` + - `bridges/browser_client.py`). Shipped: `BrowserBridge` exposes open/read +- [x] **7. Browser bridge (Playwright)** (`packs/browser/bridge/browser.py` + + `browser_client.py`). Shipped: `BrowserBridge` exposes open/read (text/links/screenshot) and act (goto/click/fill/press/select/wait/back/ forward/reset) over one JSON surface in front of a real Playwright browser with a persistent profile; optional heavy dep installed via diff --git a/PACKGEN.md b/PACKGEN.md index 12f8489..66ef36e 100644 --- a/PACKGEN.md +++ b/PACKGEN.md @@ -21,8 +21,8 @@ that would otherwise be scattered by convention: - the **concern** (what product/job this is) and its **title**; - its **categories** (the tree buckets it owns, each with a scope description); -- the **bridge(s)** it talks to, referenced by name (bridge *code* stays in - `semif_agent/bridges` — see "Authoring a new bridge"); +- the **bridge(s)** it talks to, referenced by name — and **ships** the bridge + code itself under `bridge/` (see "Authoring a new bridge"); - its **runtime requirements** (optional heavy deps); - its **enable flag**; and - its **config schema** (the defaults and validation for its settings). @@ -36,11 +36,15 @@ Three boundaries must stay crisp: - A **skill** is one leaf action (`packs//skills///`), governed by `CODEGEN.md`/`TESTGEN.md`. A pack contains skills; it is not one. -- A **bridge** is a standalone process in front of a third-party system - (`semif_agent/bridges/`), warranted when the system needs state (especially - auth state), a native or heavy protocol, or one sanitized surface; a system - with a plain HTTP API needs no bridge — its skill calls the API directly. A - pack *references* a bridge by name; it never contains bridge code. +- A **bridge** is a standalone process in front of a third-party system, + warranted when the system needs state (especially auth state), a native or + heavy protocol, or one sanitized surface; a system with a plain HTTP API needs + no bridge — its skill calls the API directly. A bridge **ships with its pack** + (`packs//bridge/`); the core keeps only the shared contract + (`semif_agent/bridges/base.py`) and the discovery registry + (`semif_agent/bridges/registry.py`). The one shared, pack-less bridge is the + **LLM bridge** (a core built-in many packs call). A pack's `bridges` list names + the bridge(s) it ships; a pack never edits core bridge code. - A pack is **declarative structure**, committed in its own repository. Per-machine values are the split config; credentials live in `secrets.json`. A pack repo never holds a secret. @@ -55,6 +59,11 @@ packs// manifest.json # {"description": "..."} navigation text contract.json # mirror of the body's CONTRACT — TESTGEN.md skill.test.py # hermetic mechanics test — TESTGEN.md + bridge/ # only for a bridge-backed pack (see below) + __init__.py # the pack's bridge package + .py # the BridgeService subclass (bridge name) + _client.py # optional protocol client (e.g. nextcloud_client.py) + test__bridge.py # hermetic bridge test (loopback HTTP) scripts/ # optional concern helpers (e.g. an auth or # setup script), run from the checkout ``` @@ -65,6 +74,9 @@ packs// - Every leaf carries the four artifacts above. Their contents are governed by `CODEGEN.md` (body + `CONTRACT` + `INTEGRATION`) and `TESTGEN.md` (test + `contract.json` mirror); do not restate those rules here. +- `bridge/` ships the pack's bridge (one module per name in `bridges`, plus + optional sibling modules it imports relatively). It is absent for a + bridge-less pack. See "Authoring a new bridge". - `manifest.json` holds a single non-empty `description` — the navigation text SemIf routes on. It is the seed analog of the registry entry a generated skill gets from the `llm` provider. @@ -86,7 +98,7 @@ A single JSON object. Fields (from `packs._parse_pack`): | `title` | string | no | Human display name. Defaults to `name`. | | `concern` | string | **yes** | One- to two-sentence statement of the product/job the pack serves. (`description` is accepted as a legacy alias.) | | `categories` | object | **yes** | `{category_id: scope_description}` — the tree buckets this pack owns. | -| `bridges` | array of string | no | Bridge names this pack talks to, referencing `bridges/registry.py` `CATALOG`. Empty for a bridge-less pack. | +| `bridges` | array of string | no | Bridge names this pack ships and talks to. Each name is a `bridge/.py` module in the pack; `simplex`/`llm`/`nextcloud`/`outlook`/`browser` are the shipped names. Empty for a bridge-less pack. | | `requires` | array of string | no | Optional heavy deps (e.g. `playwright`). Informational; the code's `check_requirements` is what enforces them. | | `enabled_by_default` | bool | no | Default `true`. Whether the pack loads when nothing else decides. | | `config` | object | no | The pack's config schema (see below). | @@ -106,7 +118,8 @@ Rules: Write one to two sentences naming the concrete jobs the category does. - **`bridges[0]` owns the config block.** For a bridge pack, the pack's `config` schema maps onto `bridges.`; only the first bridge gets the block - (a pack normally fronts one bridge). + (a pack normally fronts one bridge). Each name in `bridges` must have a + `bridge/.py` module that defines its `BridgeService` subclass. - Keep the manifest minimal: it binds metadata and settings, nothing executable. ## The config schema @@ -187,14 +200,16 @@ authored into one — and stops its bridge. The switch lives in the pack's ## Referencing a bridge by name A pack whose skills talk to a third-party system lists that bridge in -`bridges` and carries its config block in `config`. (A pack whose skills reach a -plain HTTP API directly needs no bridge: `bridges` stays empty and each leaf -declares the endpoint in its own `CONTRACT`.) The bridge itself is a -class in `semif_agent/bridges/` registered in `bridges/registry.py` `CATALOG`. -Its `BridgeInfo` (name, service, description, URL config var, other config -vars, auth header, endpoints) is injected into every codegen prompt via -`describe_bridges()`, so bodies learn how to reach it without the pack -restating protocol details. +`bridges`, **ships** it under `bridge/`, and carries its config block in +`config`. (A pack whose skills reach a plain HTTP API directly needs no bridge: +`bridges` stays empty and each leaf declares the endpoint in its own +`CONTRACT`.) The bridge itself is a `BridgeService` subclass in +`packs//bridge/.py`; the core registry imports it by convention and +its `BridgeInfo` (name, service, description, URL config var, other config vars, +auth header, endpoints) is injected into every codegen prompt via +`describe_bridges()`, so bodies learn how to reach it without the pack restating +protocol details. The one exception is the shared, pack-less **LLM bridge** +(a core built-in). Skill-facing config is **derived**, never duplicated: `derived_config_vars` turns the bridge's `bridges.` block (`host`/`port`/`token`) into the @@ -207,9 +222,9 @@ Rules: - The bridge block's `enabled`/`host`/`port`/`token` are the pack's config schema; the URL/token config vars are derived and must not be declared again. -- A pack references a bridge; it never imports or edits bridge code. Gateway - isolation is non-negotiable — read/send/address capability is a bridge, never - a gateway feature. +- A pack ships its own bridge and never imports or edits another pack's or the + core's. Gateway isolation is non-negotiable — read/send/address capability is + a bridge, never a gateway feature. ## Authoring a new bridge @@ -220,12 +235,14 @@ needs a native or heavy protocol, or should be reached through one sanitized surface. A system with a plain HTTP API needs no bridge: its skill calls the API directly. Adding a bridge means: -1. **Write the bridge class** in `semif_agent/bridges/.py`, subclassing +1. **Write the bridge class** in the pack's `bridge/.py`, subclassing `BridgeService` (`semif_agent/bridges/base.py`). Set the `name` attribute and - a module-level/class `INFO = BridgeInfo(...)`: + a module-level/class `INFO = BridgeInfo(...)`. Ship `bridge/__init__.py` (the + package marker) and any sibling modules the bridge imports relatively (e.g. + `bridge/_client.py` for the protocol client): ```python - from .base import BridgeInfo, BridgeService + from semif_agent.bridges.base import BridgeInfo, BridgeService class WidgetBridge(BridgeService): name = "widget" @@ -254,18 +271,23 @@ directly. Adding a bridge means: The base class owns the HTTP/JSON/auth plumbing (`start`/`stop`, the `X-Semif-Token` guard); a subclass implements only its routes. Override `start`/`stop`/`_stop_transport` only if the bridge owns a service daemon. + Anchor checkout-relative paths (e.g. a token store under `.runtime/`) with + `semif_agent.bridges.base.checkout_root()`, never from the bridge's own + `__file__` — the bridge ships in its pack, so its path is pack-relative. -2. **Register it** in `bridges/registry.py` `CATALOG` (tuple order is - presentation order). That is what makes it discoverable, describable to - codegen, and runnable via `python -m semif_agent.cli bridge`. +2. **Declare it** in the pack's `bridges` list and ship its module at + `bridge/.py`. That is what makes it discoverable, describable to + codegen, and runnable via `python -m semif_agent.cli bridge` — there is no + core `CATALOG` to edit. -3. **Give it a pack** whose `bridges` lists its name and whose `config` schema - carries its block (`enabled`/`host`/`port`/`token` plus service vars). The - schema is what gives the bridge its config defaults and validation. +3. **Carry its config block** in the pack's `config` schema + (`enabled`/`host`/`port`/`token` plus service vars). The schema is what gives + the bridge its config defaults and validation. -4. **`build_bridge` special-casing** is needed only when the bridge requires the - scheduler's configured `llm` client (pass `client=`) or top-level fallback - values (like Nextcloud's `nextcloud_*`). A plain bridge needs no branch. +4. **Override `BridgeService.from_config`** only when the bridge needs more than + its own block: the scheduler's configured `llm` client (the shared LLM + bridge) or top-level fallback values (like Nextcloud's `nextcloud_*`). A + plain bridge uses the default and needs no override. 5. **Heavy/optional deps:** `check_requirements()` must **never raise** and must return `(ok, install_hint)`. `run_bridges` aborts **all** bridges when one @@ -278,10 +300,13 @@ directly. Adding a bridge means: missing connection/dep is a `503`, bad input a `400` — never a fabricated success. The bridge owns its own state (cursors, daemons); bodies keep none. -7. **Test it hermetically:** add `tests/test__bridge.py` driving the real +7. **Test it hermetically:** add `bridge/test__bridge.py` driving the real routes over a loopback `http.server` (inject a fake driver where a real - service would be needed). No external network, no real daemon. `describe_ - bridges()` picks the new bridge up automatically. + service would be needed). No external network, no real daemon. Import the + bridge through the core registry + (`load_pack_bridge_module("", "")`) so the test also proves the + pack's bridge is discoverable; `tests/test_packs.py` runs it from the + checkout. `describe_bridges()` picks the new bridge up automatically. 8. **Regenerate** `config.example.json` and run `check-config` (see above), and document the bridge in `AGENTS.md` (bridges section). Never widen the @@ -292,8 +317,8 @@ directly. Adding a bridge means: A new pack is accepted only if: 1. `packs//pack.json` parses as JSON, declares a non-empty `concern` and - a non-empty `categories` map, and every `bridges` name exists in - `bridges/registry.py` `CATALOG`. + a non-empty `categories` map, and every `bridges` name has a + `bridge/.py` module defining its `BridgeService` subclass. 2. Every leaf under `skills///` is a complete skill folder (`skill.py`, `manifest.json`, `contract.json`, `skill.test.py`) satisfying `CODEGEN.md` and `TESTGEN.md`: a module-level `act`, a flat `CONTRACT` whose @@ -309,15 +334,17 @@ A new pack is accepted only if: marked `secret`), maps onto `bridges.` (or `packs.` for a bridge-less pack), and the regenerated `config.example.json` + `check-config` are clean. -6. Nothing deployment-specific (hostname, address, username, absolute home +6. A bridge-backed pack ships its bridge test (`bridge/test__bridge.py`) + and it passes hermetically (loopback HTTP, no external network, no daemon). +7. Nothing deployment-specific (hostname, address, username, absolute home path, local model name) appears in any committed file — `tests/test_no_env_leaks.py` enforces this for the agent repo; keep a pack repo clean too. Secrets live in `secrets.json`. -`tests/test_packs.py` enforces items 1–3 mechanically for every shipped pack +`tests/test_packs.py` enforces items 1–6 mechanically for every shipped pack (valid manifest, concern + categories, integration matches code, contract flat -and mirrored, manifest description, hermetic test passes) and keeps the shipped -pack ids present. +and mirrored, manifest description, hermetic skill test, hermetic bridge test) +and keeps the shipped pack ids present. ## Worked example — a minimal bridge-less pack @@ -364,9 +391,11 @@ The leaf's `skill.py` (a `compute`-transport body — no external action, empty `packs/essentials/skills/time/now/` is the reference for exactly this shape. For a bridge-backed pack, start from `packs/simplex/pack.json` (bridge -reference + `host`/`port`/`token` + service vars) and +reference + `host`/`port`/`token` + service vars), `packs/simplex/bridge/` (the +bridge module, its package marker, and its hermetic test), and `packs/simplex/skills/simplex/send_message/` (a body that calls the bridge over -HTTP). For a bridge with top-level fallbacks, see `packs/nextcloud/`. +HTTP). For a bridge with top-level fallbacks, see `packs/nextcloud/` (its +`bridge/nextcloud.py` overrides `from_config`). ## Checklist @@ -374,19 +403,20 @@ HTTP). For a bridge with top-level fallbacks, see `packs/nextcloud/`. descriptions. 2. If a third-party system is involved and it needs state/auth, a native or heavy protocol, or one sanitized surface, author a bridge first (see - "Authoring a new bridge") and register it in `CATALOG`. A system with a plain + "Authoring a new bridge") and ship it under `bridge/`. A system with a plain HTTP API needs no bridge — the skill calls it directly. 3. Create the pack (its own repository, `pack.`): `packs//pack.json` with `name`, `title`, `concern`, `categories`, `bridges` (if any), `requires`, `enabled_by_default`, and the `config` schema. 4. Add each leaf under `skills///` following `CODEGEN.md` and - `TESTGEN.md` (`skill.py`, `manifest.json`, `contract.json`, `skill.test.py`). + `TESTGEN.md` (`skill.py`, `manifest.json`, `contract.json`, `skill.test.py`), + and each bridge under `bridge/.py` with its `bridge/test__bridge.py`. 5. Regenerate and validate config: `python -m semif_agent.cli check-config --write-example config.example.json` then `python -m semif_agent.cli check-config`. 6. Run the tests: `python3 -m pytest tests/test_packs.py tests/test_codegen.py -q` - (plus `tests/test__bridge.py` if you added a bridge). + (it runs every pack's skill and bridge tests, including the new ones). 7. Cross-link the pack/bridge in `AGENTS.md` (and `README.md` for a shipped pack). 8. Verify a real run against the user's actual service — the only proof the diff --git a/README.md b/README.md index a2a13b2..1ffcc03 100644 --- a/README.md +++ b/README.md @@ -269,11 +269,12 @@ receives the user's request, question answers, or run output. | `generate_skill_tests` | `codegen` | full **TESTGEN.md** | skill, de-identified goal, full body code, **bridge catalog**; continued with the accepted **contract JSON** as an assistant turn + the test-gen ask | `codegen.py:942` | | `regenerate_skill_body` | `codegen` | full **CODEGEN.md** | correction header, de-identified goal + description, **de-identified evidence bundle** (rendered verbatim), previous body, integration hint, **bridge catalog**, `BODY_DIRECTIVES` | `codegen.py:1046` | -The **bridge catalog** is `describe_bridges()` (`bridges/registry.py:33`): each +The **bridge catalog** is `describe_bridges()` (`bridges/registry.py`): each known bridge's name, service, description, base-URL config var, auth header + token var, documented config vars, and endpoints. It is the single runtime source of bridge specifics — `CODEGEN.md` and `TESTGEN.md` carry only the generic -pattern — so a bridge can be added without touching either contract file. +pattern — so a bridge can be added without touching either contract file (a +bridge ships with its pack; the registry discovers it by convention). The **evidence bundle** handed to a corrective regen is de-identified: a generic failure kind, the integration, the goal, and the previous body, rendered as-is @@ -400,12 +401,13 @@ semif_agent/ voice_transport.py neutral voice transport: mic capture, wake word, VAD, speech-to-text (faster-whisper), text-to-speech (Piper) gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice) - bridges/ standalone third-party API bridges (SimpleX, LLM, Nextcloud, - Outlook, browser) + bridges/ bridge contract + discovery (base.py, registry.py, inbox.py, + llm.py); the concrete bridges ship in their packs config.py layered config: index includes + !secret + schema/example packs.py SkillPack + PackRegistry (bundles skills by concern/bridge) packs/ skill packs, each cloned from its own repo (pack.) - into this gitignored dir — see packs.json + PACKGEN.md + into this gitignored dir — each ships its own bridge/ — see + packs.json + PACKGEN.md scripts/ bootstrap.sh, config_merge.py, voice-*.py, systemd/*.in requirements/ staging.txt — the pinned engine deps tests/ stdlib unit tests + tests/integration (real engine + LLM) @@ -756,7 +758,7 @@ protocol, or one sanitized surface — a skill may call a plain HTTP API directl When a bridge fronts a service, generated skill bodies call it like any HTTP service (base URL from a config var) and never speak the native protocol. -The first bridge is **SimpleX** (`semif_agent/bridges/simplex.py`), with its own +The first bridge is **SimpleX** (`packs/simplex/bridge/simplex.py`), with its own simplex-chat daemon separate from the gateway's. Its HTTP surface: ``` @@ -778,10 +780,11 @@ acking is a client-side read receipt, not an API call. Skills call the forwarding bridge at the address derived from `bridges.simplex` (`simplex_bridge_url`); the bridge catalog is injected into every codegen prompt via `describe_bridges()`, so it is the -single source of bridge specifics. Adding a bridge = a class + a config block + -a `CATALOG` entry. +single source of bridge specifics. Adding a bridge = a pack that ships its +`bridge/.py` + a config block; the core registry discovers it by convention. -The **LLM bridge** (`semif_agent/bridges/llm.py`) is the second: a generic +The **LLM bridge** (`semif_agent/bridges/llm.py`) is the shared, pack-less one: a +generic ``` POST /chat {"messages": [{"role","content"}, ...], "max_tokens"?: int} -> {"text": "..."} @@ -797,7 +800,7 @@ carries just the local listener. Skills call it at the address derived from it returns `502`, never a fabricated reply. It starts in the same `semif-bridge.service` process as the other enabled bridges. -The **Nextcloud bridge** (`semif_agent/bridges/nextcloud.py`) is the third: it +The **Nextcloud bridge** (`packs/nextcloud/bridge/nextcloud.py`) is the third: it wraps the account's native protocols — WebDAV files, CalDAV calendar events and tasks, CardDAV contacts, and the OCS Notes API — behind one JSON surface, so a body never speaks DAV/OCS directly. It has **no service daemon** (Nextcloud is @@ -836,7 +839,7 @@ or a bad reply) is `502` — never a fabricated success. Calendar and addressboo defaults resolve from `bridges.nextcloud` when a request names none and the account has several. -The **Outlook bridge** (`semif_agent/bridges/outlook.py`) wraps the user's +The **Outlook bridge** (`packs/outlook/bridge/outlook.py`) wraps the user's Microsoft account (Outlook / Microsoft 365) through **Microsoft Graph**: mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files. Like Nextcloud it has **no service daemon** (Graph is plain HTTPS) and is stdlib-only, @@ -876,7 +879,7 @@ Seven `packs/outlook/skills/outlook/*` skills ship (`next_message`, `send_messag `send_message` composes the message through the LLM bridge and asks for confirmation before it sends. -The **browser bridge** (`semif_agent/bridges/browser.py`) is real browser +The **browser bridge** (`packs/browser/bridge/browser.py`) is real browser automation via **Playwright**: open a URL, read a page's text or links, take a screenshot, and click/fill/press/select to complete a flow. It is the first bridge with a heavy optional dependency, so it is **disabled by default** and diff --git a/semif_agent/bridges/__init__.py b/semif_agent/bridges/__init__.py index ba41768..0b7d38c 100644 --- a/semif_agent/bridges/__init__.py +++ b/semif_agent/bridges/__init__.py @@ -11,6 +11,12 @@ fronts a service, a generated body never speaks that system's native protocol directly: it calls a small, documented, uniform HTTP surface instead, and the bridge owns the messy integration details and credentials. +Bridges **ship with their pack**: the core owns only the shared contract +(``bridges/base.py``) and the discovery registry (``bridges/registry.py``); a +bridge implementation lives in ``packs//bridge/`` and is imported by +convention from the pack that declares it. The one exception is the shared, +pack-less LLM bridge (``bridges/llm.py``), which many packs call. + Two boundaries matter: - **Bridges are not the gateway.** The command gateway only takes commands and @@ -25,14 +31,19 @@ Two boundaries matter: and TESTGEN.md carry only the generic pattern. """ -from .base import BridgeInfo, BridgeService +from .base import BridgeInfo, BridgeService, checkout_root from .inbox import MessagingInbox from .registry import ( build_bridge, derived_config_vars, describe_bridges, + discover_bridge_classes, known_infos, + load_pack_bridge_class, + load_pack_bridge_module, + load_pack_bridge_package, run_bridges, + set_bridge_packs, ) __all__ = [ @@ -40,8 +51,14 @@ __all__ = [ "BridgeService", "MessagingInbox", "build_bridge", + "checkout_root", "derived_config_vars", "describe_bridges", + "discover_bridge_classes", "known_infos", + "load_pack_bridge_class", + "load_pack_bridge_module", + "load_pack_bridge_package", "run_bridges", + "set_bridge_packs", ] diff --git a/semif_agent/bridges/base.py b/semif_agent/bridges/base.py index 5d25897..e489bf3 100644 --- a/semif_agent/bridges/base.py +++ b/semif_agent/bridges/base.py @@ -14,9 +14,20 @@ import threading from abc import ABC, abstractmethod from dataclasses import dataclass, field from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path from urllib.parse import parse_qs, urlparse +def checkout_root() -> Path: + """The agent checkout root (anchors gitignored ``.runtime/`` artifacts). + + ``semif_agent/bridges/base.py`` -> repo root. A bridge implementation ships + inside its pack (``packs//bridge/...``), so it must not derive the root + from its own ``__file__``; it uses this helper instead. + """ + return Path(__file__).resolve().parents[2] + + @dataclass(frozen=True) class BridgeInfo: """Static, prompt-safe metadata about a bridge. @@ -60,6 +71,25 @@ class BridgeService(ABC): self._server: ThreadingHTTPServer | None = None self._thread: threading.Thread | None = None + @classmethod + def from_config( + cls, + block: dict | None, + config: dict | None = None, + trace=None, + llm=None, + ) -> "BridgeService": + """Build a bridge from its ``bridges.`` block. + + The registry constructs every bridge through this hook so a bridge that + needs more than its own block — the shared LLM client, or a top-level + fallback (e.g. Nextcloud's ``nextcloud_*`` values) — can declare that + itself instead of the core special-casing it by name. The default passes + the block and trace straight through; override in a pack bridge that + needs ``llm`` or the full ``config``. + """ + return cls(block, trace=trace) + # ---- lifecycle ---- @abstractmethod diff --git a/semif_agent/bridges/browser.py b/semif_agent/bridges/browser.py deleted file mode 100644 index 52f5214..0000000 --- a/semif_agent/bridges/browser.py +++ /dev/null @@ -1,369 +0,0 @@ -"""Browser bridge: real browser automation (Playwright) behind HTTP. - -A codegen-authored skill body must never drive a browser directly, and it must -never bundle a heavy, platform-specific automation stack. This bridge owns the -browser — a single Chromium (or Firefox/WebKit) instance with a persistent -profile — and exposes one uniform, token-guarded localhost JSON API for reading -a page (text/links/screenshot) and acting on it (goto/click/fill/press/select/ -wait/back/forward), so a body only reads `browser_bridge_url` and -`browser_bridge_token` from `ctx.config` and calls a documented route. - -Unlike Nextcloud/Outlook this bridge needs a real optional dependency -(`playwright` plus browser binaries), so it is **disabled by default**; install -it with `scripts/bootstrap.sh --browser` (browsers land under -`.runtime/browser`). The dependency and the browser are lazy: a host without -them still runs every other bridge. `check_requirements()` deliberately always -returns ok — `run_bridges()` aborts *all* bridges when one's requirements fail, -and this dependency is optional, so a missing Playwright must degrade to a -per-call 503 (with an install hint), never take down simplex/llm/nextcloud. - -The actual Playwright work lives in `browser_client.py`; the routes here -validate input and map a real failure (`BrowserError`) to a 502, a missing -dependency/browser (`BrowserUnavailable`) to a 503, and bad input to a 400 — -never a fabricated success. -""" - -from __future__ import annotations - -from pathlib import Path - -from .base import BridgeInfo, BridgeService -from .browser_client import ( - DEFAULT_MAX_TEXT_CHARS, - DEFAULT_TIMEOUT, - ENGINES, - WAIT_UNTIL, - BrowserDriver, - BrowserError, - BrowserUnavailable, -) - -#: The checkout root (`semif_agent/bridges/browser.py` -> repo root), used to -#: anchor the browser profile, binaries, and screenshots under the gitignored -#: `.runtime/` tree (the containment rule). -_REPO_ROOT = Path(__file__).resolve().parents[2] -DEFAULT_BROWSER_ROOT = str(_REPO_ROOT / ".runtime" / "browser") -DEFAULT_PROFILE_DIR = str(Path(DEFAULT_BROWSER_ROOT) / "profile") -DEFAULT_SCREENSHOT_DIR = str(Path(DEFAULT_BROWSER_ROOT) / "screenshots") - - -class BrowserBridge(BridgeService): - name = "browser" - INFO = BridgeInfo( - name="browser", - service="browser", - description=( - "Drive a real web browser (Playwright): open a URL, read a page's " - "text or links, take a screenshot, and click/fill/press/select to " - "navigate a site and complete a flow. Keeps a persistent profile so " - "logins and cookies survive across calls." - ), - url_config_var="browser_bridge_url", - endpoints=( - "GET /health -> 200 {\"ok\": true, \"platform\": \"browser\", " - "\"engine\", \"headless\"} — the bridge is up", - "GET /state -> 200 {\"url\", \"title\"} — the current page", - "GET /content?format=text|html&max_chars= -> 200 {\"url\", " - "\"title\", \"format\", \"content\", \"truncated\"} — the whole page's " - "rendered text (format defaults to text, the default when you just " - "want to read a page); content is truncated to max_chars", - "GET /text?selector= -> 200 {\"url\", \"selector\", \"count\", " - "\"matches\": [{\"text\"}]} — text of every element matching a CSS " - "selector", - "GET /links?query=&limit= -> 200 {\"url\", \"links\": " - "[{\"text\", \"href\"}]} — anchors on the page, optionally filtered " - "by a substring of the label or href", - "GET /screenshot?full_page=&selector=&inline= -> 200 " - "{\"ok\": true, \"path\", \"bytes\", \"url\", \"title\"} — saves a PNG " - "under the checkout's .runtime/browser/screenshots (add inline=true " - "for base64 in the reply)", - "POST /goto {\"url\", \"wait_until\"?: commit|domcontentloaded|load|" - "networkidle, \"timeout\"?: seconds} -> 200 {\"url\", \"title\", " - "\"status\"} — navigates; a navigation error (bad host, TLS, timeout) " - "is a 502", - "POST /click {\"selector\"?| \"text\"?, \"index\"?: 0, \"timeout\"?} " - "-> 200 {\"url\", \"title\"} — clicks by CSS selector or by visible " - "text (index picks among several matches)", - "POST /fill {\"selector\", \"value\", \"submit\"?: bool, " - "\"timeout\"?} -> 200 {\"url\", \"title\"} — types into an input; " - "submit=true presses Enter", - "POST /press {\"key\", \"selector\"?, \"timeout\"?} -> 200 {\"url\", " - "\"title\"} — presses a keyboard key (e.g. Enter, Escape, Tab)", - "POST /select {\"selector\", \"value\"?|\"label\"?, \"timeout\"?} -> " - "200 {\"url\", \"title\"} — chooses an option in a