Decouple bridges: ship each with its pack
The core no longer owns concrete bridge implementations. A bridge now ships inside the pack that declares it (packs/<name>/bridge/<name>.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.<name>.
This commit is contained in:
1 parent
16e8583921
commit
41c18e6c47
21 files changed
+485
-7476
No files matched your search
@@ -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/<name>/skills/<category>/<leaf>/` 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/<name>/bridge/test_<bridge>_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/<name>/`. 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/<name>/bridge/<name>.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 <userId>` (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 <userId> count=<n>
|
||||
{"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/<name>.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/<name>/bridge/<name>.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
|
||||
|
||||
+76
-46
@@ -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/<name>/skills/<category>/<leaf>/`),
|
||||
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/<name>/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/<name>/
|
||||
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
|
||||
<bridge>.py # the BridgeService subclass (bridge name)
|
||||
<bridge>_client.py # optional protocol client (e.g. nextcloud_client.py)
|
||||
test_<bridge>_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/<name>/
|
||||
- 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/<name>.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.<bridges[0]>`; 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/<name>.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/<name>/bridge/<name>.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.<name>` 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/<name>.py`, subclassing
|
||||
1. **Write the bridge class** in the pack's `bridge/<name>.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/<name>_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/<name>.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_<name>_bridge.py` driving the real
|
||||
7. **Test it hermetically:** add `bridge/test_<name>_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("<pack>", "<name>")`) 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/<name>/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/<name>.py` module defining its `BridgeService` subclass.
|
||||
2. Every leaf under `skills/<category>/<leaf>/` 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.<bridges[0]>` (or `packs.<name>` 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>_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.<name>`): `packs/<name>/pack.json`
|
||||
with `name`, `title`, `concern`, `categories`, `bridges` (if any), `requires`,
|
||||
`enabled_by_default`, and the `config` schema.
|
||||
4. Add each leaf under `skills/<category>/<leaf>/` 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/<name>.py` with its `bridge/test_<name>_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_<name>_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
|
||||
|
||||
@@ -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.<name>)
|
||||
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/<name>.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
|
||||
|
||||
@@ -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/<name>/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",
|
||||
]
|
||||
@@ -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/<name>/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.<name>`` 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
|
||||
|
||||
@@ -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=<n> -> 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=<css> -> 200 {\"url\", \"selector\", \"count\", "
|
||||
"\"matches\": [{\"text\"}]} — text of every element matching a CSS "
|
||||
"selector",
|
||||
"GET /links?query=<text>&limit=<n> -> 200 {\"url\", \"links\": "
|
||||
"[{\"text\", \"href\"}]} — anchors on the page, optionally filtered "
|
||||
"by a substring of the label or href",
|
||||
"GET /screenshot?full_page=<bool>&selector=<css>&inline=<bool> -> 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 <select>",
|
||||
"POST /wait {\"selector\"?| \"text\"?, \"timeout\"?} -> 200 {\"url\", "
|
||||
"\"title\"} — waits for an element/text to appear",
|
||||
"POST /back | /forward {\"timeout\"?} -> 200 {\"url\", \"title\"}",
|
||||
"POST /reset {\"purge\"?: bool default true} -> 200 {\"ok\", "
|
||||
"\"purged\"} — closes the browser; purge=true (default) also deletes "
|
||||
"the stored profile so the next call starts logged out",
|
||||
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
|
||||
"configured and the auth header is missing or wrong",
|
||||
"503 {\"error\": \"...\"} when Playwright or its browser binaries are "
|
||||
"not installed (run scripts/bootstrap.sh --browser); 502 {\"error\": "
|
||||
"\"...\"} on a real browser failure (navigation, timeout, bad "
|
||||
"selector)",
|
||||
),
|
||||
config_vars=("browser_bridge_url", "browser_bridge_token"),
|
||||
config_var_docs=(
|
||||
(
|
||||
"browser_bridge_url",
|
||||
"Base URL of the local browser bridge (e.g. "
|
||||
"http://127.0.0.1:5232); never hardcode it in the body.",
|
||||
),
|
||||
(
|
||||
"browser_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="browser_bridge_token",
|
||||
)
|
||||
|
||||
def __init__(self, config: dict | None = None, trace=None, client=None):
|
||||
super().__init__(config, trace)
|
||||
cfg = config or {}
|
||||
engine = str(cfg.get("engine", "chromium") or "chromium").strip().lower()
|
||||
self.engine = engine if engine in ENGINES else "chromium"
|
||||
self.headless = bool(cfg.get("headless", True))
|
||||
self.profile_dir = str(cfg.get("profile_dir") or DEFAULT_PROFILE_DIR)
|
||||
self.browsers_path = str(cfg.get("browsers_path") or DEFAULT_BROWSER_ROOT)
|
||||
self.screenshot_dir = str(cfg.get("screenshot_dir") or DEFAULT_SCREENSHOT_DIR)
|
||||
self.default_timeout = float(cfg.get("default_timeout", DEFAULT_TIMEOUT))
|
||||
self.max_text_chars = int(cfg.get("max_text_chars", DEFAULT_MAX_TEXT_CHARS))
|
||||
#: Optional escape hatch: use an installed browser instead of Playwright's
|
||||
#: managed download. `channel` is a Playwright channel (chrome/msedge/...),
|
||||
#: `executable_path` a specific binary; `executable_path` wins if both set.
|
||||
self.channel = str(cfg.get("channel", "") or "").strip()
|
||||
self.executable_path = str(cfg.get("executable_path", "") or "").strip()
|
||||
#: A test seam: inject a driver double. Production builds the real one.
|
||||
self.client = client or BrowserDriver(
|
||||
engine=self.engine,
|
||||
headless=self.headless,
|
||||
profile_dir=self.profile_dir,
|
||||
browsers_path=self.browsers_path,
|
||||
screenshot_dir=self.screenshot_dir,
|
||||
default_timeout=self.default_timeout,
|
||||
max_text_chars=self.max_text_chars,
|
||||
channel=self.channel,
|
||||
executable_path=self.executable_path,
|
||||
)
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
# Deliberately never blocks startup: a missing Playwright/browser is an
|
||||
# optional-dependency problem and must not take down the other bridges
|
||||
# (run_bridges aborts them all on a failed check). It surfaces as a 503
|
||||
# on the call instead.
|
||||
return True, None
|
||||
|
||||
def _stop_transport(self) -> None:
|
||||
close = getattr(self.client, "close", None)
|
||||
if callable(close):
|
||||
try:
|
||||
close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ---- routes ----
|
||||
|
||||
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/health":
|
||||
return 200, {
|
||||
"ok": True,
|
||||
"platform": self.name,
|
||||
"engine": self.engine,
|
||||
"headless": self.headless,
|
||||
}
|
||||
try:
|
||||
return self._get(path, query)
|
||||
except BrowserUnavailable as exc:
|
||||
return 503, {"error": str(exc)[:400]}
|
||||
except BrowserError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
try:
|
||||
return self._post(path, payload)
|
||||
except BrowserUnavailable as exc:
|
||||
return 503, {"error": str(exc)[:400]}
|
||||
except BrowserError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def _get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/state":
|
||||
return 200, self.client.state()
|
||||
if path == "/content":
|
||||
fmt = (self._q(query, "format", "text") or "text").strip().lower()
|
||||
if fmt not in ("text", "html"):
|
||||
raise ValueError("format must be text or html")
|
||||
max_chars = self._int_query_opt(query, "max_chars")
|
||||
return 200, self.client.content(fmt, max_chars)
|
||||
if path == "/text":
|
||||
return 200, self.client.text(self._required_query(query, "selector"))
|
||||
if path == "/links":
|
||||
return 200, self.client.links(
|
||||
self._q(query, "query", "") or "", self._int_query(query, "limit", 50)
|
||||
)
|
||||
if path == "/screenshot":
|
||||
return 200, self.client.screenshot(
|
||||
self._bool_query(query, "full_page", False),
|
||||
self._q(query, "selector", "") or "",
|
||||
self._bool_query(query, "inline", False),
|
||||
)
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
def _post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if path == "/goto":
|
||||
wait_until = (
|
||||
self._optional_str(payload, "wait_until", "load") or "load"
|
||||
).strip().lower()
|
||||
if wait_until not in WAIT_UNTIL:
|
||||
raise ValueError(f"wait_until must be one of {', '.join(WAIT_UNTIL)}")
|
||||
return 200, self.client.goto(
|
||||
self._required(payload, "url"),
|
||||
wait_until,
|
||||
self._optional_float(payload, "timeout"),
|
||||
)
|
||||
if path == "/click":
|
||||
selector = self._optional_str(payload, "selector")
|
||||
text = self._optional_str(payload, "text")
|
||||
if not selector and not text:
|
||||
raise ValueError("selector or text is required")
|
||||
return 200, self.client.click(
|
||||
selector,
|
||||
text,
|
||||
self._optional_int(payload, "index", 0) or 0,
|
||||
self._optional_float(payload, "timeout"),
|
||||
)
|
||||
if path == "/fill":
|
||||
return 200, self.client.fill(
|
||||
self._required(payload, "selector"),
|
||||
self._required(payload, "value", allow_empty=True),
|
||||
self._optional_bool(payload, "submit", False),
|
||||
self._optional_float(payload, "timeout"),
|
||||
)
|
||||
if path == "/press":
|
||||
return 200, self.client.press(
|
||||
self._required(payload, "key"),
|
||||
self._optional_str(payload, "selector"),
|
||||
self._optional_float(payload, "timeout"),
|
||||
)
|
||||
if path == "/select":
|
||||
value = self._optional_str(payload, "value") or None
|
||||
label = self._optional_str(payload, "label") or None
|
||||
if value is None and label is None:
|
||||
raise ValueError("value or label is required")
|
||||
return 200, self.client.select(
|
||||
self._required(payload, "selector"),
|
||||
value,
|
||||
label,
|
||||
self._optional_float(payload, "timeout"),
|
||||
)
|
||||
if path == "/wait":
|
||||
selector = self._optional_str(payload, "selector")
|
||||
text = self._optional_str(payload, "text")
|
||||
if not selector and not text:
|
||||
raise ValueError("selector or text is required")
|
||||
return 200, self.client.wait_for(
|
||||
selector, text, self._optional_float(payload, "timeout")
|
||||
)
|
||||
if path == "/back":
|
||||
return 200, self.client.back(self._optional_float(payload, "timeout"))
|
||||
if path == "/forward":
|
||||
return 200, self.client.forward(self._optional_float(payload, "timeout"))
|
||||
if path == "/reset":
|
||||
return 200, self.client.reset(self._optional_bool(payload, "purge", True))
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
# ---- input helpers ----
|
||||
|
||||
@staticmethod
|
||||
def _q(query: dict, key: str, default=None):
|
||||
values = query.get(key)
|
||||
if not values:
|
||||
return default
|
||||
return values[0]
|
||||
|
||||
@staticmethod
|
||||
def _required_query(query: dict, key: str) -> str:
|
||||
value = BrowserBridge._q(query, key)
|
||||
if value is None or not str(value).strip():
|
||||
raise ValueError(f"{key} is required")
|
||||
return str(value).strip()
|
||||
|
||||
@staticmethod
|
||||
def _int_query(query: dict, key: str, default: int) -> int:
|
||||
value = BrowserBridge._q(query, key)
|
||||
if value is None or str(value).strip() == "":
|
||||
return default
|
||||
try:
|
||||
return int(str(value))
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"{key} must be an integer") from exc
|
||||
|
||||
@staticmethod
|
||||
def _int_query_opt(query: dict, key: str):
|
||||
value = BrowserBridge._q(query, key)
|
||||
if value is None or str(value).strip() == "":
|
||||
return None
|
||||
try:
|
||||
return int(str(value))
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"{key} must be an integer") from exc
|
||||
|
||||
@staticmethod
|
||||
def _bool_query(query: dict, key: str, default: bool) -> bool:
|
||||
value = BrowserBridge._q(query, key)
|
||||
if value is None or str(value).strip() == "":
|
||||
return default
|
||||
return str(value).strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
@staticmethod
|
||||
def _required(payload: dict, key: str, allow_empty: bool = False) -> str:
|
||||
value = payload.get(key)
|
||||
if not isinstance(value, str) or (not allow_empty and not value.strip()):
|
||||
raise ValueError(f"{key} is required")
|
||||
return value if allow_empty else value.strip()
|
||||
|
||||
@staticmethod
|
||||
def _optional_str(payload: dict, key: str, default: str = "") -> str:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"{key} must be a string")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_bool(payload: dict, key: str, default: bool) -> bool:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError(f"{key} must be a boolean")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_int(payload: dict, key: str, default: int | None = None):
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ValueError(f"{key} must be an integer")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_float(payload: dict, key: str):
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise ValueError(f"{key} must be a number")
|
||||
return float(value)
|
||||
@@ -1,441 +0,0 @@
|
||||
"""A real browser driver for the browser bridge, backed by Playwright.
|
||||
|
||||
The browser bridge calls this instead of a skill body driving a browser
|
||||
directly. It owns a single Chromium (or Firefox/WebKit) instance with a
|
||||
**persistent profile** under the checkout's `.runtime/browser/profile`, so a
|
||||
logged-in session survives across calls and restarts, and exposes plain methods
|
||||
that return dicts.
|
||||
|
||||
Playwright's synchronous API is bound to the thread that created it and is not
|
||||
thread-safe, but the bridge's HTTP server handles each request on a new thread.
|
||||
So this driver runs the **async** API on one dedicated event-loop thread and
|
||||
serializes whole operations behind an `asyncio.Lock`; route handlers submit a
|
||||
coroutine onto that loop with `run_coroutine_threadsafe` and wait for the
|
||||
result. Browser automation is inherently serial, so one loop is enough.
|
||||
|
||||
Only the standard library is imported eagerly; `playwright` is imported lazily
|
||||
the first time the browser is actually needed, so a host without it still runs
|
||||
every other bridge. A missing package (or a missing browser binary) raises
|
||||
`BrowserUnavailable`, which the bridge maps to a 503 install hint; every other
|
||||
failure is a `BrowserError`, mapped to a 502 — never a fabricated success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import importlib.util
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import uuid
|
||||
from concurrent.futures import TimeoutError as FuturesTimeoutError
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_ENGINE = "chromium"
|
||||
ENGINES = ("chromium", "firefox", "webkit")
|
||||
DEFAULT_TIMEOUT = 30.0
|
||||
DEFAULT_MAX_TEXT_CHARS = 20000
|
||||
#: Cap on how many elements a single `text` / `links` call returns.
|
||||
DEFAULT_MAX_MATCHES = 50
|
||||
WAIT_UNTIL = ("commit", "domcontentloaded", "load", "networkidle")
|
||||
INSTALL_HINT = (
|
||||
"install the browser bridge stack: pip install -r requirements/browser.txt "
|
||||
"&& PLAYWRIGHT_BROWSERS_PATH=<repo>/.runtime/browser python -m playwright "
|
||||
"install chromium"
|
||||
)
|
||||
|
||||
|
||||
class BrowserError(Exception):
|
||||
"""A real failure driving the browser (navigation, timeout, bad selector)."""
|
||||
|
||||
|
||||
class BrowserUnavailable(BrowserError):
|
||||
"""Playwright or its browser binaries are not installed / cannot launch."""
|
||||
|
||||
|
||||
class BrowserDriver:
|
||||
"""One persistent browser, driven from a single dedicated event-loop thread."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
engine: str = DEFAULT_ENGINE,
|
||||
headless: bool = True,
|
||||
profile_dir: str = "",
|
||||
browsers_path: str = "",
|
||||
screenshot_dir: str = "",
|
||||
default_timeout: float = DEFAULT_TIMEOUT,
|
||||
max_text_chars: int = DEFAULT_MAX_TEXT_CHARS,
|
||||
channel: str = "",
|
||||
executable_path: str = "",
|
||||
):
|
||||
self.engine = engine if engine in ENGINES else DEFAULT_ENGINE
|
||||
self.headless = bool(headless)
|
||||
self.profile_dir = str(profile_dir or "")
|
||||
self.browsers_path = str(browsers_path or "")
|
||||
self.screenshot_dir = str(screenshot_dir or "")
|
||||
self.default_timeout = float(default_timeout)
|
||||
self.max_text_chars = max(200, int(max_text_chars))
|
||||
#: Use an already-installed browser instead of Playwright's own build:
|
||||
#: `channel` names a Playwright channel (`chrome`, `msedge`, ...) and
|
||||
#: `executable_path` points at a specific binary. Both bypass the
|
||||
#: managed-download requirement, useful where the CDN is unreachable.
|
||||
self.channel = str(channel or "").strip()
|
||||
self.executable_path = str(executable_path or "").strip()
|
||||
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._thread: threading.Thread | None = None
|
||||
self._lock: asyncio.Lock | None = None
|
||||
self._start_lock = threading.Lock()
|
||||
self._playwright = None
|
||||
self._context = None
|
||||
self._page = None
|
||||
|
||||
# ---- availability ----
|
||||
|
||||
@property
|
||||
def configured(self) -> bool:
|
||||
"""Whether the `playwright` package is importable (cheap; no browser)."""
|
||||
return importlib.util.find_spec("playwright") is not None
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def _ensure_started(self) -> None:
|
||||
with self._start_lock:
|
||||
if self._loop is not None:
|
||||
return
|
||||
if not self.configured:
|
||||
raise BrowserUnavailable(INSTALL_HINT)
|
||||
# Locate browser binaries under the checkout before Playwright reads
|
||||
# the env var. The bridge cannot rely on the shell exporting it.
|
||||
if self.browsers_path:
|
||||
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = self.browsers_path
|
||||
loop = asyncio.new_event_loop()
|
||||
self._loop = loop
|
||||
ready = threading.Event()
|
||||
|
||||
def runner() -> None:
|
||||
asyncio.set_event_loop(loop)
|
||||
self._lock = asyncio.Lock()
|
||||
ready.set()
|
||||
loop.run_forever()
|
||||
|
||||
self._thread = threading.Thread(target=runner, name="browser-driver", daemon=True)
|
||||
self._thread.start()
|
||||
ready.wait(5.0)
|
||||
|
||||
def _run(self, coro, timeout: float | None = None):
|
||||
"""Schedule `coro` on the driver loop and wait for its result."""
|
||||
if self._loop is None:
|
||||
coro.close()
|
||||
raise BrowserUnavailable(INSTALL_HINT)
|
||||
budget = (timeout if timeout else self.default_timeout) + 15.0
|
||||
future = asyncio.run_coroutine_threadsafe(coro, self._loop)
|
||||
try:
|
||||
return future.result(budget)
|
||||
except FuturesTimeoutError as exc:
|
||||
future.cancel()
|
||||
raise BrowserError(f"browser operation timed out after {budget:.0f}s") from exc
|
||||
|
||||
def _operation(self, fn, timeout: float | None = None):
|
||||
"""Run `fn(page)` under the serialization lock, launching if needed."""
|
||||
self._ensure_started()
|
||||
|
||||
async def runner():
|
||||
assert self._lock is not None
|
||||
async with self._lock:
|
||||
page = await self._ensure_context()
|
||||
return await fn(page)
|
||||
|
||||
return self._run(runner(), timeout=timeout)
|
||||
|
||||
async def _ensure_context(self):
|
||||
if self._page is not None and not self._page.is_closed():
|
||||
return self._page
|
||||
if self._playwright is None:
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
self._playwright = await async_playwright().start()
|
||||
browser_type = getattr(self._playwright, self.engine, None)
|
||||
if browser_type is None:
|
||||
raise BrowserError(f"unknown browser engine {self.engine!r}")
|
||||
if self.profile_dir:
|
||||
Path(self.profile_dir).mkdir(parents=True, exist_ok=True)
|
||||
user_data_dir = self.profile_dir
|
||||
else:
|
||||
# No persistent profile configured: still a real context, just
|
||||
# ephemeral (Playwright rejects a None user_data_dir).
|
||||
user_data_dir = tempfile.mkdtemp(prefix="semif-browser-")
|
||||
try:
|
||||
# A persistent context keeps cookies/logins on disk across calls and
|
||||
# restarts; it is the browser analog of the SimpleX bridge owning its
|
||||
# own profile.
|
||||
launch_options = {
|
||||
"headless": self.headless,
|
||||
"viewport": {"width": 1280, "height": 800},
|
||||
"timeout": self.default_timeout * 1000,
|
||||
}
|
||||
if self.executable_path:
|
||||
launch_options["executable_path"] = self.executable_path
|
||||
elif self.channel:
|
||||
launch_options["channel"] = self.channel
|
||||
self._context = await browser_type.launch_persistent_context(
|
||||
user_data_dir, **launch_options
|
||||
)
|
||||
except BrowserUnavailable:
|
||||
raise
|
||||
except Exception as exc: # missing browser binary, launch failure, ...
|
||||
raise BrowserUnavailable(
|
||||
f"could not launch {self.engine} (is the browser installed? "
|
||||
f"{INSTALL_HINT}): {exc}"
|
||||
) from exc
|
||||
pages = self._context.pages
|
||||
self._page = pages[0] if pages else await self._context.new_page()
|
||||
return self._page
|
||||
|
||||
async def _close_context(self) -> None:
|
||||
self._page = None
|
||||
context, self._context = self._context, None
|
||||
if context is not None:
|
||||
try:
|
||||
await context.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def close(self) -> None:
|
||||
"""Tear down the browser and the driver loop (from `_stop_transport`)."""
|
||||
loop, self._loop = self._loop, None
|
||||
if loop is None:
|
||||
return
|
||||
try:
|
||||
future = asyncio.run_coroutine_threadsafe(self._shutdown(), loop)
|
||||
future.result(timeout=15.0)
|
||||
except Exception:
|
||||
pass
|
||||
loop.call_soon_threadsafe(loop.stop)
|
||||
thread, self._thread = self._thread, None
|
||||
if thread is not None:
|
||||
thread.join(timeout=5.0)
|
||||
try:
|
||||
loop.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def _shutdown(self) -> None:
|
||||
await self._close_context()
|
||||
if self._playwright is not None:
|
||||
try:
|
||||
await self._playwright.stop()
|
||||
except Exception:
|
||||
pass
|
||||
self._playwright = None
|
||||
|
||||
# ---- operations (each returns a plain dict) ----
|
||||
|
||||
def state(self) -> dict:
|
||||
async def _do(page):
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do)
|
||||
|
||||
def goto(self, url: str, wait_until: str = "load", timeout: float | None = None) -> dict:
|
||||
async def _do(page):
|
||||
response = await page.goto(
|
||||
url, wait_until=wait_until, timeout=(timeout or self.default_timeout) * 1000
|
||||
)
|
||||
return {
|
||||
"url": page.url,
|
||||
"title": await page.title(),
|
||||
"status": response.status if response is not None else None,
|
||||
}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def content(self, fmt: str = "text", max_chars: int | None = None) -> dict:
|
||||
limit = max(200, int(max_chars)) if max_chars else self.max_text_chars
|
||||
|
||||
async def _do(page):
|
||||
if fmt == "html":
|
||||
raw = await page.content()
|
||||
else:
|
||||
raw = await page.inner_text("body")
|
||||
text = raw or ""
|
||||
return {
|
||||
"url": page.url,
|
||||
"title": await page.title(),
|
||||
"format": fmt,
|
||||
"content": text[:limit],
|
||||
"truncated": len(text) > limit,
|
||||
}
|
||||
|
||||
return self._operation(_do)
|
||||
|
||||
def text(self, selector: str) -> dict:
|
||||
async def _do(page):
|
||||
locator = page.locator(selector)
|
||||
count = await locator.count()
|
||||
matches = []
|
||||
for index in range(min(count, DEFAULT_MAX_MATCHES)):
|
||||
value = await locator.nth(index).inner_text()
|
||||
matches.append({"text": (value or "").strip()[:2000]})
|
||||
return {
|
||||
"url": page.url,
|
||||
"selector": selector,
|
||||
"count": count,
|
||||
"matches": matches,
|
||||
}
|
||||
|
||||
return self._operation(_do)
|
||||
|
||||
def links(self, query: str = "", limit: int = 50) -> dict:
|
||||
max_links = max(1, min(int(limit), 200))
|
||||
|
||||
async def _do(page):
|
||||
anchors = await page.query_selector_all("a")
|
||||
needle = query.strip().lower()
|
||||
out = []
|
||||
for element in anchors:
|
||||
href = await element.get_attribute("href")
|
||||
if not href:
|
||||
continue
|
||||
label = ((await element.inner_text()) or "").strip()
|
||||
if needle and needle not in f"{label} {href}".lower():
|
||||
continue
|
||||
out.append({"text": label[:300], "href": href})
|
||||
if len(out) >= max_links:
|
||||
break
|
||||
return {"url": page.url, "links": out}
|
||||
|
||||
return self._operation(_do)
|
||||
|
||||
def screenshot(
|
||||
self, full_page: bool = False, selector: str = "", inline: bool = False
|
||||
) -> dict:
|
||||
async def _do(page):
|
||||
directory = self.screenshot_dir or "/tmp"
|
||||
Path(directory).mkdir(parents=True, exist_ok=True)
|
||||
path = os.path.join(directory, f"{uuid.uuid4().hex}.png")
|
||||
if selector:
|
||||
await page.locator(selector).first.screenshot(path=path)
|
||||
else:
|
||||
await page.screenshot(path=path, full_page=bool(full_page))
|
||||
result = {
|
||||
"ok": True,
|
||||
"path": path,
|
||||
"bytes": os.path.getsize(path),
|
||||
"url": page.url,
|
||||
"title": await page.title(),
|
||||
}
|
||||
if inline:
|
||||
with open(path, "rb") as handle:
|
||||
result["base64"] = base64.b64encode(handle.read()).decode("ascii")
|
||||
return result
|
||||
|
||||
return self._operation(_do)
|
||||
|
||||
def click(
|
||||
self,
|
||||
selector: str = "",
|
||||
text: str = "",
|
||||
index: int = 0,
|
||||
timeout: float | None = None,
|
||||
) -> dict:
|
||||
async def _do(page):
|
||||
if selector:
|
||||
locator = page.locator(selector).nth(int(index))
|
||||
else:
|
||||
locator = page.get_by_text(text, exact=False).nth(int(index))
|
||||
await locator.click(timeout=(timeout or self.default_timeout) * 1000)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def fill(
|
||||
self,
|
||||
selector: str,
|
||||
value: str,
|
||||
submit: bool = False,
|
||||
timeout: float | None = None,
|
||||
) -> dict:
|
||||
async def _do(page):
|
||||
budget = (timeout or self.default_timeout) * 1000
|
||||
await page.fill(selector, value, timeout=budget)
|
||||
if submit:
|
||||
await page.press(selector, "Enter", timeout=budget)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def press(self, key: str, selector: str = "", timeout: float | None = None) -> dict:
|
||||
async def _do(page):
|
||||
await page.press(
|
||||
selector or "body", key, timeout=(timeout or self.default_timeout) * 1000
|
||||
)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def select(
|
||||
self,
|
||||
selector: str,
|
||||
value: str | None = None,
|
||||
label: str | None = None,
|
||||
timeout: float | None = None,
|
||||
) -> dict:
|
||||
async def _do(page):
|
||||
budget = (timeout or self.default_timeout) * 1000
|
||||
if value is not None:
|
||||
await page.select_option(selector, value=value, timeout=budget)
|
||||
else:
|
||||
await page.select_option(selector, label=label, timeout=budget)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def wait_for(
|
||||
self, selector: str = "", text: str = "", timeout: float | None = None
|
||||
) -> dict:
|
||||
async def _do(page):
|
||||
budget = (timeout or self.default_timeout) * 1000
|
||||
if selector:
|
||||
await page.wait_for_selector(selector, timeout=budget)
|
||||
else:
|
||||
await page.get_by_text(text, exact=False).first.wait_for(timeout=budget)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def back(self, timeout: float | None = None) -> dict:
|
||||
async def _do(page):
|
||||
await page.go_back(
|
||||
wait_until="load", timeout=(timeout or self.default_timeout) * 1000
|
||||
)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def forward(self, timeout: float | None = None) -> dict:
|
||||
async def _do(page):
|
||||
await page.go_forward(
|
||||
wait_until="load", timeout=(timeout or self.default_timeout) * 1000
|
||||
)
|
||||
return {"url": page.url, "title": await page.title()}
|
||||
|
||||
return self._operation(_do, timeout=timeout)
|
||||
|
||||
def reset(self, purge: bool = True) -> dict:
|
||||
"""Close the browser; delete the stored profile when `purge` is true."""
|
||||
self._ensure_started()
|
||||
|
||||
async def _do():
|
||||
assert self._lock is not None
|
||||
async with self._lock:
|
||||
await self._close_context()
|
||||
purged = False
|
||||
if purge and self.profile_dir:
|
||||
shutil.rmtree(self.profile_dir, ignore_errors=True)
|
||||
purged = True
|
||||
return {"ok": True, "purged": purged}
|
||||
|
||||
return self._run(_do())
|
||||
@@ -60,6 +60,12 @@ class LLMBridge(BridgeService):
|
||||
#: the bridge is built without one; calls then report 502, never a guess.
|
||||
self.client = client
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, block, config=None, trace=None, llm=None) -> "LLMBridge":
|
||||
# The LLM bridge reuses the scheduler's already-configured `llm` client
|
||||
# (endpoint/model/sampler configured once in the top-level `llm` block).
|
||||
return cls(block, trace=trace, client=llm)
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
|
||||
@@ -1,604 +0,0 @@
|
||||
"""Nextcloud bridge: files, calendars, tasks, contacts, and notes over HTTP.
|
||||
|
||||
Nextcloud speaks several native protocols (WebDAV for files, CalDAV for events
|
||||
and tasks, CardDAV for contacts, and OCS for the Notes app and server info). A
|
||||
codegen-authored skill body must never speak those directly. This bridge owns the
|
||||
connection — base URL, username, and app password — and exposes one uniform,
|
||||
token-guarded localhost JSON API, so a body only reads `nextcloud_bridge_url` and
|
||||
`nextcloud_bridge_token` from `ctx.config` and calls a documented route.
|
||||
|
||||
There is no service daemon: Nextcloud is plain HTTPS, so the bridge is stdlib-only
|
||||
(`urllib` + `xml.etree`) and starts instantly. The connection comes from
|
||||
`bridges.nextcloud` (url/username/app_password/default_calendar/default_addressbook),
|
||||
falling back to the top-level `nextcloud_url`/`nextcloud_username`/
|
||||
`nextcloud_app_password`/`nextcloud_default_calendar` values the nextcloud pack's skills
|
||||
already use, so the same account is configured in one place.
|
||||
|
||||
The actual DAV/OCS work lives in `nextcloud_client.py`; the routes here validate
|
||||
input and map a real failure (`NextcloudError`) to a 502 rather than a fabricated
|
||||
success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .nextcloud_client import DEFAULT_TIMEOUT, NextcloudClient, NextcloudError
|
||||
|
||||
#: Nextcloud Deck backs each board with a VTODO-only calendar named like this.
|
||||
_DECK_PREFIX = "app-generated--deck--"
|
||||
|
||||
_COMPONENT_KINDS = {
|
||||
"VTODO": "task list",
|
||||
"VEVENT": "event calendar",
|
||||
"VJOURNAL": "journal",
|
||||
}
|
||||
|
||||
|
||||
def _supports(calendar: dict, component: str) -> bool:
|
||||
"""Whether a calendar accepts `component`; unknown (empty) means allow."""
|
||||
components = calendar.get("components") or []
|
||||
return not components or component in components
|
||||
|
||||
|
||||
def _is_deck_board(calendar: dict) -> bool:
|
||||
return str(calendar.get("name") or "").startswith(_DECK_PREFIX)
|
||||
|
||||
|
||||
def _component_kind(component: str) -> str:
|
||||
return _COMPONENT_KINDS.get(component, "calendar of that kind")
|
||||
|
||||
|
||||
def _join_components(calendar: dict) -> str:
|
||||
components = calendar.get("components") or []
|
||||
return ", ".join(components) if components else "an unknown component set"
|
||||
|
||||
|
||||
def _task_list_hint(calendars: list[dict]) -> str:
|
||||
names = [
|
||||
c["name"]
|
||||
for c in calendars
|
||||
if _supports(c, "VTODO") and not _is_deck_board(c)
|
||||
]
|
||||
if names:
|
||||
return "task lists: " + ", ".join(names)
|
||||
return "no VTODO-capable task lists are available"
|
||||
|
||||
|
||||
class NextcloudBridge(BridgeService):
|
||||
name = "nextcloud"
|
||||
INFO = BridgeInfo(
|
||||
name="nextcloud",
|
||||
service="nextcloud",
|
||||
description=(
|
||||
"Read and write the user's Nextcloud: files (WebDAV), calendar events "
|
||||
"and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app)."
|
||||
),
|
||||
url_config_var="nextcloud_bridge_url",
|
||||
endpoints=(
|
||||
"GET /health -> 200 {\"ok\": true, \"platform\": \"nextcloud\"} — the "
|
||||
"bridge is up",
|
||||
"GET /user -> 200 {\"user\": {id, display_name, email, language, "
|
||||
"locale}} — the account (OCS)",
|
||||
"GET /capabilities -> 200 {Nextcloud server capabilities} (OCS)",
|
||||
"GET /files?path=<dir> -> 200 {\"path\", \"entries\": [{name, path, "
|
||||
"type (file|dir), size, modified, etag, content_type}]} — list a "
|
||||
"folder (default /)",
|
||||
"GET /files/stat?path=<path> -> 200 {one entry, same fields as an "
|
||||
"entries item}",
|
||||
"GET /files/read?path=<path> -> 200 {\"path\", \"content\", "
|
||||
"\"encoding\" (utf-8|base64), \"size\"} — file contents; binary is "
|
||||
"base64",
|
||||
"GET /files/search?query=<text>&path=<dir> -> 200 {\"results\": "
|
||||
"[entry]} — filename search under a folder",
|
||||
"POST /files/write {\"path\", \"content\", \"encoding\"?: "
|
||||
"utf-8|base64, \"overwrite\"?: bool} -> 200 {\"ok\": true, \"path\"}",
|
||||
"POST /files/mkdir {\"path\"} -> 200 {\"ok\": true, \"path\"}",
|
||||
"POST /files/delete {\"path\"} -> 200 {\"ok\": true, \"path\"}",
|
||||
"POST /files/move {\"path\", \"destination\", \"overwrite\"?: bool} "
|
||||
"-> 200 {\"ok\": true, \"path\", \"destination\"}",
|
||||
"POST /files/copy {\"path\", \"destination\", \"overwrite\"?: bool} "
|
||||
"-> 200 {\"ok\": true, \"path\", \"destination\"}",
|
||||
"GET /calendars -> 200 {\"calendars\": [{name, label, description, "
|
||||
"color, ctag, components}]} — components lists the CalDAV component "
|
||||
"types each collection accepts (VEVENT, VTODO, VJOURNAL)",
|
||||
"GET /tasklists -> 200 {\"tasklists\": [{name, label, description, "
|
||||
"color, ctag, components}]} — the user's task lists (calendars that "
|
||||
"accept VTODO), excluding Nextcloud Deck boards; use this to pick a "
|
||||
"target for POST /tasks",
|
||||
"GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> -> 200 "
|
||||
"{\"calendar\", \"events\": [{uid, summary, start, end, all_day, "
|
||||
"location, description, rrule, status, href, etag}]} — start/end "
|
||||
"optional (ISO 8601); without them every event is returned",
|
||||
"POST /calendars/events {\"calendar\"?, \"uid\"?, \"summary\", "
|
||||
"\"start\", \"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
|
||||
"\"rrule\"?, \"overwrite\"?} -> 200 {\"ok\": true, \"uid\", "
|
||||
"\"calendar\", \"etag\"}",
|
||||
"POST /calendars/events/update {\"calendar\"?, \"uid\", \"summary\"?, "
|
||||
"\"start\"?, \"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
|
||||
"\"rrule\"?} -> 200 {\"ok\": true, \"uid\", \"calendar\", \"etag\"} — "
|
||||
"only the named fields change",
|
||||
"POST /calendars/events/delete {\"calendar\"?, \"uid\"} -> 200 "
|
||||
"{\"ok\": true, \"uid\", \"calendar\"}",
|
||||
"GET /tasks?calendar=<name> -> 200 {\"calendar\", \"tasks\": [{uid, "
|
||||
"summary, due, status, percent_complete, priority, description, href, "
|
||||
"etag}]} — CalDAV VTODO; calendar must be a VTODO-capable task list "
|
||||
"(see GET /tasklists), defaulting to the configured task calendar",
|
||||
"POST /tasks {\"calendar\"?, \"uid\"?, \"summary\", \"due\"?, "
|
||||
"\"priority\"?, \"description\"?} -> 200 {\"ok\": true, \"uid\", "
|
||||
"\"calendar\", \"etag\"} — calendar must be a VTODO-capable task list "
|
||||
"(see GET /tasklists); an event-only calendar is rejected with 400",
|
||||
"POST /tasks/update {\"calendar\"?, \"uid\", \"summary\"?, \"due\"?, "
|
||||
"\"priority\"?, \"description\"?, \"status\"?, \"percent_complete\"?} "
|
||||
"-> 200 {ok, uid}",
|
||||
"POST /tasks/complete {\"calendar\"?, \"uid\"} -> 200 {ok, uid} — "
|
||||
"marks the task COMPLETED",
|
||||
"POST /tasks/delete {\"calendar\"?, \"uid\"} -> 200 {ok}",
|
||||
"GET /addressbooks -> 200 {\"addressbooks\": [{name, label, "
|
||||
"description}]}",
|
||||
"GET /contacts?addressbook=<name>&query=<text> -> 200 "
|
||||
"{\"addressbook\", \"contacts\": [{uid, fn, n, emails, phones, org, "
|
||||
"title, note, url, href, etag}]} — query filters by name/org/email/"
|
||||
"phone",
|
||||
"POST /contacts {\"addressbook\"?, \"uid\"?, \"fn\", \"emails\"?, "
|
||||
"\"phones\"?, \"org\"?, \"title\"?, \"note\"?, \"url\"?, \"n\"?} -> "
|
||||
"200 {ok, uid}",
|
||||
"POST /contacts/update {\"addressbook\"?, \"uid\", ...fields} -> 200 "
|
||||
"{ok, uid}",
|
||||
"POST /contacts/delete {\"addressbook\"?, \"uid\"} -> 200 {ok}",
|
||||
"GET /notes -> 200 {\"notes\": [{id, title, category, modified, ...}]} "
|
||||
"— Nextcloud Notes app (metadata only)",
|
||||
"GET /notes/get?id=<id> -> 200 {\"note\": {id, title, content, "
|
||||
"category, ...}}",
|
||||
"POST /notes {\"title\", \"content\"?, \"category\"?} -> 200 "
|
||||
"{\"note\": {...}}",
|
||||
"POST /notes/update {\"id\", \"title\"?, \"content\"?, "
|
||||
"\"category\"?} -> 200 {\"note\": {...}}",
|
||||
"POST /notes/delete {\"id\"} -> 200 {\"ok\": true, \"id\"}",
|
||||
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
|
||||
"configured and the auth header is missing or wrong",
|
||||
"503 {\"error\": \"...\"} when the bridge has no Nextcloud connection "
|
||||
"configured; 502 {\"error\": \"...\"} on a real Nextcloud failure "
|
||||
"(transport, HTTP error, or bad reply)",
|
||||
),
|
||||
config_vars=("nextcloud_bridge_url", "nextcloud_bridge_token"),
|
||||
config_var_docs=(
|
||||
(
|
||||
"nextcloud_bridge_url",
|
||||
"Base URL of the local Nextcloud bridge (e.g. "
|
||||
"http://127.0.0.1:5230); never hardcode it in the body.",
|
||||
),
|
||||
(
|
||||
"nextcloud_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="nextcloud_bridge_token",
|
||||
)
|
||||
|
||||
def __init__(self, config: dict | None = None, trace=None, fallback: dict | None = None, client=None):
|
||||
super().__init__(config, trace)
|
||||
cfg = config or {}
|
||||
fb = fallback or {}
|
||||
|
||||
def pick(key: str, default=""):
|
||||
value = cfg.get(key)
|
||||
if value in (None, ""):
|
||||
value = fb.get(key)
|
||||
return default if value in (None, "") else value
|
||||
|
||||
self.url = str(pick("url")).strip()
|
||||
self.username = str(pick("username")).strip()
|
||||
self.app_password = str(pick("app_password"))
|
||||
self.default_calendar = str(pick("default_calendar")).strip()
|
||||
self.default_task_calendar = str(pick("default_task_calendar")).strip()
|
||||
self.default_addressbook = str(pick("default_addressbook")).strip()
|
||||
self.verify_tls = bool(cfg.get("verify_tls", fb.get("verify_tls", True)))
|
||||
self.timeout = float(cfg.get("timeout", DEFAULT_TIMEOUT))
|
||||
#: A test seam: inject a client double. Production builds the real one.
|
||||
self.client = client or NextcloudClient(
|
||||
self.url,
|
||||
self.username,
|
||||
self.app_password,
|
||||
timeout=self.timeout,
|
||||
verify_tls=self.verify_tls,
|
||||
default_calendar=self.default_calendar,
|
||||
default_addressbook=self.default_addressbook,
|
||||
)
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
# Stdlib only: no missing dependency can make the bridge unstartable. A
|
||||
# missing connection surfaces as a 503 on the call, not a startup failure.
|
||||
return True, None
|
||||
|
||||
# ---- routes ----
|
||||
|
||||
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/health":
|
||||
return 200, {"ok": True, "platform": self.name}
|
||||
if not self.client.configured:
|
||||
return self._unconfigured()
|
||||
try:
|
||||
return self._get(path, query)
|
||||
except NextcloudError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if not self.client.configured:
|
||||
return self._unconfigured()
|
||||
try:
|
||||
return self._post(path, payload)
|
||||
except NextcloudError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def _unconfigured(self) -> tuple[int, dict]:
|
||||
return 503, {
|
||||
"error": (
|
||||
"the Nextcloud bridge has no connection configured (set "
|
||||
"bridges.nextcloud.url/username/app_password, or the top-level "
|
||||
"nextcloud_url/nextcloud_username/nextcloud_app_password)"
|
||||
)
|
||||
}
|
||||
|
||||
def _get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/user":
|
||||
return 200, {"user": self.client.user_info()}
|
||||
if path == "/capabilities":
|
||||
return 200, self.client.capabilities()
|
||||
if path == "/files":
|
||||
return 200, self.client.list_files(self._q(query, "path", "/") or "/")
|
||||
if path == "/files/stat":
|
||||
return 200, self.client.stat(self._required_query(query, "path"))
|
||||
if path == "/files/read":
|
||||
return 200, self.client.read_file(self._required_query(query, "path"))
|
||||
if path == "/files/search":
|
||||
query_text = self._required_query(query, "query")
|
||||
return 200, {
|
||||
"results": self.client.search(
|
||||
query_text, self._q(query, "path", "/") or "/"
|
||||
)
|
||||
}
|
||||
if path == "/calendars":
|
||||
return 200, {"calendars": self.client.list_calendars()}
|
||||
if path == "/tasklists":
|
||||
return 200, {"tasklists": self._task_lists()}
|
||||
if path == "/calendars/events":
|
||||
calendar = self._resolve_calendar(self._q(query, "calendar"))
|
||||
return 200, {
|
||||
"calendar": calendar,
|
||||
"events": self.client.list_events(
|
||||
calendar,
|
||||
self._q(query, "start", "") or "",
|
||||
self._q(query, "end", "") or "",
|
||||
),
|
||||
}
|
||||
if path == "/tasks":
|
||||
calendar = self._resolve_calendar(self._q(query, "calendar"), "VTODO")
|
||||
return 200, {"calendar": calendar, "tasks": self.client.list_tasks(calendar)}
|
||||
if path == "/addressbooks":
|
||||
return 200, {"addressbooks": self.client.list_addressbooks()}
|
||||
if path == "/contacts":
|
||||
addressbook = self._resolve_addressbook(self._q(query, "addressbook"))
|
||||
return 200, {
|
||||
"addressbook": addressbook,
|
||||
"contacts": self.client.list_contacts(
|
||||
addressbook, self._q(query, "query", "") or ""
|
||||
),
|
||||
}
|
||||
if path == "/notes":
|
||||
return 200, {"notes": self.client.list_notes()}
|
||||
if path == "/notes/get":
|
||||
return 200, {"note": self.client.get_note(self._required_query(query, "id"))}
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
def _post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if path == "/files/write":
|
||||
return 200, self.client.write_file(
|
||||
self._required(payload, "path"),
|
||||
self._required(payload, "content", allow_empty=True),
|
||||
self._optional_str(payload, "encoding", "utf-8"),
|
||||
self._optional_bool(payload, "overwrite", True),
|
||||
)
|
||||
if path == "/files/mkdir":
|
||||
return 200, self.client.mkdir(self._required(payload, "path"))
|
||||
if path == "/files/delete":
|
||||
return 200, self.client.delete(self._required(payload, "path"))
|
||||
if path == "/files/move":
|
||||
return 200, self.client.move(
|
||||
self._required(payload, "path"),
|
||||
self._required(payload, "destination"),
|
||||
self._optional_bool(payload, "overwrite", False),
|
||||
)
|
||||
if path == "/files/copy":
|
||||
return 200, self.client.copy(
|
||||
self._required(payload, "path"),
|
||||
self._required(payload, "destination"),
|
||||
self._optional_bool(payload, "overwrite", False),
|
||||
)
|
||||
if path == "/calendars/events":
|
||||
return 200, self._create_event(payload)
|
||||
if path == "/calendars/events/update":
|
||||
return 200, self._update_event(payload)
|
||||
if path == "/calendars/events/delete":
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
return 200, self.client.delete_object(calendar, self._required(payload, "uid"))
|
||||
if path == "/tasks":
|
||||
return 200, self._create_task(payload)
|
||||
if path == "/tasks/update":
|
||||
return 200, self._update_task(payload)
|
||||
if path == "/tasks/complete":
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO")
|
||||
return 200, self.client.complete_task(calendar, self._required(payload, "uid"))
|
||||
if path == "/tasks/delete":
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO")
|
||||
return 200, self.client.delete_object(calendar, self._required(payload, "uid"))
|
||||
if path == "/contacts":
|
||||
return 200, self._create_contact(payload)
|
||||
if path == "/contacts/update":
|
||||
return 200, self._update_contact(payload)
|
||||
if path == "/contacts/delete":
|
||||
addressbook = self._resolve_addressbook(
|
||||
self._optional_str(payload, "addressbook")
|
||||
)
|
||||
return 200, self.client.delete_contact(
|
||||
addressbook, self._required(payload, "uid")
|
||||
)
|
||||
if path == "/notes":
|
||||
return 200, {
|
||||
"note": self.client.create_note(
|
||||
self._required(payload, "title"),
|
||||
self._optional_str(payload, "content"),
|
||||
self._optional_str(payload, "category"),
|
||||
)
|
||||
}
|
||||
if path == "/notes/update":
|
||||
return 200, {"note": self._update_note(payload)}
|
||||
if path == "/notes/delete":
|
||||
return 200, self.client.delete_note(self._required_id(payload))
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
# ---- calendar/task helpers ----
|
||||
|
||||
def _create_event(self, payload: dict) -> dict:
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
uid = self._optional_str(payload, "uid") or uuid.uuid4().hex
|
||||
return self.client.create_event(
|
||||
calendar,
|
||||
uid,
|
||||
summary=self._required(payload, "summary"),
|
||||
start=self._required(payload, "start"),
|
||||
end=self._optional_str(payload, "end"),
|
||||
all_day=self._optional_bool(payload, "all_day", False),
|
||||
location=self._optional_str(payload, "location"),
|
||||
description=self._optional_str(payload, "description"),
|
||||
rrule=self._optional_str(payload, "rrule"),
|
||||
overwrite=self._optional_bool(payload, "overwrite", False),
|
||||
)
|
||||
|
||||
def _update_event(self, payload: dict) -> dict:
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
uid = self._required(payload, "uid")
|
||||
changes = {
|
||||
key: payload[key]
|
||||
for key in ("summary", "start", "end", "location", "description", "rrule")
|
||||
if key in payload
|
||||
}
|
||||
if "all_day" in payload:
|
||||
changes["all_day"] = self._optional_bool(payload, "all_day", False)
|
||||
return self.client.update_event(calendar, uid, **changes)
|
||||
|
||||
def _create_task(self, payload: dict) -> dict:
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO")
|
||||
uid = self._optional_str(payload, "uid") or uuid.uuid4().hex
|
||||
return self.client.create_task(
|
||||
calendar,
|
||||
uid,
|
||||
summary=self._required(payload, "summary"),
|
||||
due=self._optional_str(payload, "due"),
|
||||
priority=self._optional_int(payload, "priority"),
|
||||
description=self._optional_str(payload, "description"),
|
||||
)
|
||||
|
||||
def _update_task(self, payload: dict) -> dict:
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO")
|
||||
uid = self._required(payload, "uid")
|
||||
changes = {
|
||||
key: payload[key]
|
||||
for key in ("summary", "due", "priority", "description", "status", "percent_complete")
|
||||
if key in payload
|
||||
}
|
||||
return self.client.update_task(calendar, uid, **changes)
|
||||
|
||||
# ---- contact helpers ----
|
||||
|
||||
def _create_contact(self, payload: dict) -> dict:
|
||||
addressbook = self._resolve_addressbook(self._optional_str(payload, "addressbook"))
|
||||
uid = self._optional_str(payload, "uid") or uuid.uuid4().hex
|
||||
return self.client.create_contact(
|
||||
addressbook,
|
||||
uid,
|
||||
fn=self._required(payload, "fn"),
|
||||
n=self._optional_str(payload, "n"),
|
||||
emails=self._string_list(payload, "emails"),
|
||||
phones=self._string_list(payload, "phones"),
|
||||
org=self._optional_str(payload, "org"),
|
||||
title=self._optional_str(payload, "title"),
|
||||
note=self._optional_str(payload, "note"),
|
||||
url=self._optional_str(payload, "url"),
|
||||
)
|
||||
|
||||
def _update_contact(self, payload: dict) -> dict:
|
||||
addressbook = self._resolve_addressbook(self._optional_str(payload, "addressbook"))
|
||||
uid = self._required(payload, "uid")
|
||||
changes = {}
|
||||
for key in ("fn", "n", "org", "title", "note", "url"):
|
||||
if key in payload:
|
||||
changes[key] = payload[key]
|
||||
for key in ("emails", "phones"):
|
||||
if key in payload:
|
||||
changes[key] = self._string_list(payload, key)
|
||||
return self.client.update_contact(addressbook, uid, **changes)
|
||||
|
||||
# ---- notes helpers ----
|
||||
|
||||
def _update_note(self, payload: dict) -> dict:
|
||||
note_id = self._required_id(payload)
|
||||
changes = {
|
||||
key: payload[key] for key in ("title", "content", "category") if key in payload
|
||||
}
|
||||
return self.client.update_note(note_id, **changes)
|
||||
|
||||
# ---- default resolution ----
|
||||
|
||||
def _resolve_calendar(self, name, component: str | None = None) -> str:
|
||||
"""Resolve a calendar name, honoring the CalDAV component it must accept.
|
||||
|
||||
An explicit name is validated when the collection's component set is
|
||||
known: asking a task operation to write to an event-only calendar is a
|
||||
real error (a `VTODO` PUT there is rejected), not a silent redirect. With
|
||||
no name, a task operation falls back to the configured task calendar, then
|
||||
the event default when it also accepts VTODO, then the sole user task
|
||||
list. `component=None` (events, files) keeps the historical behavior.
|
||||
"""
|
||||
requested = str(name or "").strip()
|
||||
if requested:
|
||||
if component:
|
||||
calendars = self.client.list_calendars()
|
||||
match = next((c for c in calendars if c.get("name") == requested), None)
|
||||
if match is not None and not _supports(match, component):
|
||||
raise ValueError(
|
||||
f"{requested!r} is not a {_component_kind(component)} "
|
||||
f"(it accepts {_join_components(match)}); "
|
||||
f"{_task_list_hint(calendars)}"
|
||||
)
|
||||
return requested
|
||||
|
||||
# The configured defaults, most specific first. For a task operation the
|
||||
# event default is still consulted when it also accepts VTODO.
|
||||
defaults = [self.default_task_calendar] if component == "VTODO" else []
|
||||
defaults.append(self.default_calendar)
|
||||
calendars = None
|
||||
for default in defaults:
|
||||
if not default:
|
||||
continue
|
||||
if not component:
|
||||
return default
|
||||
if calendars is None:
|
||||
calendars = self.client.list_calendars()
|
||||
match = next((c for c in calendars if c.get("name") == default), None)
|
||||
if match is None or _supports(match, component):
|
||||
return default
|
||||
|
||||
if calendars is None:
|
||||
calendars = self.client.list_calendars()
|
||||
if component:
|
||||
calendars = [c for c in calendars if _supports(c, component)]
|
||||
if component == "VTODO":
|
||||
calendars = [c for c in calendars if not _is_deck_board(c)]
|
||||
if len(calendars) == 1:
|
||||
return calendars[0]["name"]
|
||||
raise ValueError(
|
||||
f"calendar is required (name one in the request, or set "
|
||||
f"bridges.nextcloud.default_calendar"
|
||||
+ (
|
||||
" / default_task_calendar"
|
||||
if component == "VTODO"
|
||||
else ""
|
||||
)
|
||||
+ ")"
|
||||
)
|
||||
|
||||
def _task_lists(self) -> list[dict]:
|
||||
"""The user's task lists: VTODO-capable calendars, minus Deck boards."""
|
||||
return [
|
||||
calendar
|
||||
for calendar in self.client.list_calendars()
|
||||
if _supports(calendar, "VTODO") and not _is_deck_board(calendar)
|
||||
]
|
||||
|
||||
def _resolve_addressbook(self, name) -> str:
|
||||
name = str(name or self.default_addressbook or "").strip()
|
||||
if name:
|
||||
return name
|
||||
addressbooks = self.client.list_addressbooks()
|
||||
if len(addressbooks) == 1:
|
||||
return addressbooks[0]["name"]
|
||||
raise ValueError(
|
||||
"addressbook is required (name one in the request, or set "
|
||||
"bridges.nextcloud.default_addressbook)"
|
||||
)
|
||||
|
||||
# ---- input helpers ----
|
||||
|
||||
@staticmethod
|
||||
def _q(query: dict, key: str, default=None):
|
||||
values = query.get(key)
|
||||
if not values:
|
||||
return default
|
||||
return values[0]
|
||||
|
||||
@staticmethod
|
||||
def _required_query(query: dict, key: str) -> str:
|
||||
value = NextcloudBridge._q(query, key)
|
||||
if value is None or not str(value).strip():
|
||||
raise ValueError(f"{key} is required")
|
||||
return str(value).strip()
|
||||
|
||||
@staticmethod
|
||||
def _required(payload: dict, key: str, allow_empty: bool = False) -> str:
|
||||
value = payload.get(key)
|
||||
if not isinstance(value, str) or (not allow_empty and not value.strip()):
|
||||
raise ValueError(f"{key} is required")
|
||||
return value if allow_empty else value.strip()
|
||||
|
||||
@staticmethod
|
||||
def _required_id(payload: dict):
|
||||
value = payload.get("id")
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
raise ValueError("id is required")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_str(payload: dict, key: str, default: str = "") -> str:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"{key} must be a string")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_bool(payload: dict, key: str, default: bool) -> bool:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError(f"{key} must be a boolean")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_int(payload: dict, key: str):
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ValueError(f"{key} must be an integer")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _string_list(payload: dict, key: str) -> list[str]:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
||||
raise ValueError(f"{key} must be a list of strings")
|
||||
return value
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,398 +0,0 @@
|
||||
"""Outlook bridge: the user's Microsoft account (Graph) over HTTP.
|
||||
|
||||
Microsoft Graph is a plain HTTPS/JSON API, but a codegen-authored skill body
|
||||
must still never speak it (or OAuth) directly. This bridge owns the connection —
|
||||
the Entra ID client id, the tenant, and the stored refresh token — and exposes
|
||||
one uniform, token-guarded localhost JSON API for mail, calendar, Microsoft To Do
|
||||
tasks, contacts, and OneDrive files, so a body only reads `outlook_bridge_url`
|
||||
and `outlook_bridge_token` from `ctx.config` and calls a documented route.
|
||||
|
||||
There is no service daemon and no third-party dependency: Graph is plain HTTPS,
|
||||
so the bridge is stdlib-only (`urllib`) and starts instantly, like Nextcloud.
|
||||
Authorization is the OAuth2 device code flow, run once with
|
||||
`packs/outlook/scripts/outlook-auth.py`; the resulting tokens are stored (0600) under the
|
||||
checkout's `.runtime/outlook/token.json`. The bridge starts without them and an
|
||||
unauthenticated route returns 503 telling the operator to run that helper.
|
||||
|
||||
The actual Graph work lives in `outlook_client.py`; the routes here validate
|
||||
input and map a real failure (`OutlookError`) to a 502 — or a missing
|
||||
authorization (`OutlookAuthRequired`) to a 503 — rather than a fabricated
|
||||
success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .outlook_client import (
|
||||
DEFAULT_SCOPES,
|
||||
DEFAULT_TENANT,
|
||||
DEFAULT_TIMEOUT,
|
||||
OutlookAuthRequired,
|
||||
OutlookClient,
|
||||
OutlookError,
|
||||
)
|
||||
|
||||
#: The checkout root (`semif_agent/bridges/outlook.py` -> repo root), used to
|
||||
#: anchor the default token store under the gitignored `.runtime/` tree.
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
DEFAULT_TOKEN_PATH = str(_REPO_ROOT / ".runtime" / "outlook" / "token.json")
|
||||
|
||||
|
||||
class OutlookBridge(BridgeService):
|
||||
name = "outlook"
|
||||
INFO = BridgeInfo(
|
||||
name="outlook",
|
||||
service="outlook",
|
||||
description=(
|
||||
"Read and write the user's Microsoft account (Outlook / Microsoft "
|
||||
"365) through Microsoft Graph: mail, calendar events, Microsoft To "
|
||||
"Do tasks, contacts, and OneDrive files."
|
||||
),
|
||||
url_config_var="outlook_bridge_url",
|
||||
endpoints=(
|
||||
"GET /health -> 200 {\"ok\": true, \"platform\": \"outlook\"} — the "
|
||||
"bridge is up",
|
||||
"GET /user -> 200 {\"user\": {id, display_name, mail, "
|
||||
"user_principal_name}} — the signed-in account",
|
||||
"GET /mail/folders -> 200 {\"folders\": [{id, name, total, unread}]}",
|
||||
"GET /mail/messages?folder=<name|id>&count=<n>&search=<text>&unread=<bool> "
|
||||
"-> 200 {\"folder\", \"messages\": [{id, subject, from, to, cc, "
|
||||
"received, is_read, has_attachments, importance, preview, web_link}]} "
|
||||
"— newest first; folder defaults to inbox (a well-known name like "
|
||||
"sentitems/drafts/archive or a folder display name/id)",
|
||||
"GET /mail/messages/get?id=<id> -> 200 {\"message\": {..., body, "
|
||||
"body_type}} — the full message",
|
||||
"POST /mail/send {\"to\": [addr, ...], \"cc\"?: [addr, ...], "
|
||||
"\"subject\"?, \"body\"?, \"content_type\"?: text|html} -> 200 "
|
||||
"{\"ok\": true, \"to\", \"cc\", \"subject\"} — sends immediately",
|
||||
"POST /mail/draft {\"to\"?, \"cc\"?, \"subject\"?, \"body\"?, "
|
||||
"\"content_type\"?} -> 200 {\"ok\": true, \"id\", \"subject\"} — "
|
||||
"saves a draft in the Drafts folder",
|
||||
"GET /calendars -> 200 {\"calendars\": [{id, name, color, "
|
||||
"is_default, can_edit}]}",
|
||||
"GET /calendars/events?calendar=<name|id>&start=<iso>&end=<iso> -> "
|
||||
"200 {\"calendar\", \"events\": [{id, subject, start, end, timezone, "
|
||||
"all_day, location, preview, show_as, is_online_meeting, web_link, "
|
||||
"organizer}]} — start/end are ISO 8601 (default: now to +30 days); "
|
||||
"recurring events are expanded, calendar defaults to the configured "
|
||||
"or primary calendar",
|
||||
"POST /calendars/events {\"calendar\"?, \"subject\", \"start\", "
|
||||
"\"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
|
||||
"\"attendees\"?: [addr, ...], \"timezone\"?} -> 200 {\"ok\": true, "
|
||||
"\"id\", \"subject\", \"calendar\", \"web_link\"} — start/end are "
|
||||
"local ISO 8601 in the named timezone (default UTC when absent); end "
|
||||
"defaults to +1h (+1 day when all_day)",
|
||||
"POST /calendars/events/update {\"id\", \"subject\"?, \"start\"?, "
|
||||
"\"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
|
||||
"\"timezone\"?} -> 200 {ok, id, subject} — only the named fields change",
|
||||
"POST /calendars/events/delete {\"id\"} -> 200 {\"ok\": true, \"id\"}",
|
||||
"GET /tasklists -> 200 {\"tasklists\": [{id, name, is_owner, "
|
||||
"is_default}]} — Microsoft To Do lists",
|
||||
"GET /tasks?list=<name|id> -> 200 {\"list\", \"tasks\": [{id, title, "
|
||||
"status, importance, due, completed, description, list_id}]} — list "
|
||||
"defaults to the configured or default list",
|
||||
"POST /tasks {\"list\"?, \"title\", \"due\"?, \"importance\"?, "
|
||||
"\"description\"?} -> 200 {\"ok\": true, \"id\", \"title\", "
|
||||
"\"list_id\"} — importance is low|normal|high; due is ISO 8601",
|
||||
"POST /tasks/update {\"id\", \"list\"?, \"title\"?, \"due\"?, "
|
||||
"\"importance\"?, \"status\"?, \"description\"?} -> 200 {ok, id, status}",
|
||||
"POST /tasks/complete {\"id\", \"list\"?} -> 200 {ok, id, status} — "
|
||||
"marks the task completed",
|
||||
"POST /tasks/delete {\"id\", \"list\"?} -> 200 {\"ok\": true, \"id\"}",
|
||||
"GET /contacts?query=<text>&count=<n> -> 200 {\"contacts\": [{id, "
|
||||
"display_name, given_name, surname, emails, phones, company, "
|
||||
"job_title}]} — query filters by name/email/company",
|
||||
"GET /files?path=<dir> -> 200 {\"path\", \"entries\": [{id, name, "
|
||||
"path, size, modified, is_folder, content_type, web_url}]} — OneDrive "
|
||||
"folder listing (default root)",
|
||||
"GET /files/read?path=<path> -> 200 {\"path\", \"name\", \"content\", "
|
||||
"\"encoding\" (utf-8|base64), \"size\", \"content_type\", \"modified\"} "
|
||||
"— file contents; binary is base64",
|
||||
"POST /files/write {\"path\", \"content\", \"encoding\"?: "
|
||||
"utf-8|base64, \"overwrite\"?: bool} -> 200 {\"ok\": true, \"path\", "
|
||||
"\"id\", \"size\", \"web_url\"}",
|
||||
"any request -> 401 {\"error\": \"unauthorized\"} when the token is "
|
||||
"configured and the auth header is missing or wrong",
|
||||
"503 {\"error\": \"...\"} when the bridge is not authenticated "
|
||||
"(run packs/outlook/scripts/outlook-auth.py) or has no client id configured; 502 "
|
||||
"{\"error\": \"...\"} on a real Microsoft Graph failure (transport, "
|
||||
"HTTP error, or bad reply)",
|
||||
),
|
||||
config_vars=("outlook_bridge_url", "outlook_bridge_token"),
|
||||
config_var_docs=(
|
||||
(
|
||||
"outlook_bridge_url",
|
||||
"Base URL of the local Outlook bridge (e.g. "
|
||||
"http://127.0.0.1:5231); never hardcode it in the body.",
|
||||
),
|
||||
(
|
||||
"outlook_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="outlook_bridge_token",
|
||||
)
|
||||
|
||||
def __init__(self, config: dict | None = None, trace=None, client=None):
|
||||
super().__init__(config, trace)
|
||||
cfg = config or {}
|
||||
self.client_id = str(cfg.get("client_id", "") or "").strip()
|
||||
self.tenant = str(cfg.get("tenant", DEFAULT_TENANT) or DEFAULT_TENANT).strip() or DEFAULT_TENANT
|
||||
self.token_path = str(cfg.get("token_path") or DEFAULT_TOKEN_PATH)
|
||||
self.default_timezone = str(cfg.get("default_timezone", "UTC") or "UTC").strip() or "UTC"
|
||||
self.default_mail_folder = str(cfg.get("default_mail_folder", "inbox") or "inbox").strip() or "inbox"
|
||||
#: A test seam: inject a client double. Production builds the real one.
|
||||
self.client = client or OutlookClient(
|
||||
self.client_id,
|
||||
tenant=self.tenant,
|
||||
token_path=self.token_path,
|
||||
scopes=cfg.get("scopes") or DEFAULT_SCOPES,
|
||||
timeout=float(cfg.get("timeout", DEFAULT_TIMEOUT)),
|
||||
verify_tls=bool(cfg.get("verify_tls", True)),
|
||||
default_calendar=str(cfg.get("default_calendar", "") or "").strip(),
|
||||
default_task_list=str(cfg.get("default_task_list", "") or "").strip(),
|
||||
default_mail_folder=self.default_mail_folder,
|
||||
default_timezone=self.default_timezone,
|
||||
)
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
# Stdlib only: no missing dependency can make the bridge unstartable. A
|
||||
# missing authorization surfaces as a 503 on the call, not a startup failure.
|
||||
return True, None
|
||||
|
||||
# ---- routes ----
|
||||
|
||||
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/health":
|
||||
return 200, {"ok": True, "platform": self.name}
|
||||
if not self.client.configured:
|
||||
return self._unconfigured()
|
||||
try:
|
||||
return self._get(path, query)
|
||||
except OutlookAuthRequired as exc:
|
||||
return 503, {"error": str(exc)[:300]}
|
||||
except OutlookError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if not self.client.configured:
|
||||
return self._unconfigured()
|
||||
try:
|
||||
return self._post(path, payload)
|
||||
except OutlookAuthRequired as exc:
|
||||
return 503, {"error": str(exc)[:300]}
|
||||
except OutlookError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def _unconfigured(self) -> tuple[int, dict]:
|
||||
return 503, {
|
||||
"error": (
|
||||
"the Outlook bridge has no connection configured (set "
|
||||
"bridges.outlook.client_id, then run packs/outlook/scripts/outlook-auth.py)"
|
||||
)
|
||||
}
|
||||
|
||||
def _get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/user":
|
||||
return 200, {"user": self.client.me()}
|
||||
if path == "/mail/folders":
|
||||
return 200, {"folders": self.client.list_mail_folders()}
|
||||
if path == "/mail/messages":
|
||||
folder = self._q(query, "folder", "") or ""
|
||||
return 200, {
|
||||
"folder": folder or self.default_mail_folder,
|
||||
"messages": self.client.list_messages(
|
||||
folder,
|
||||
self._int_query(query, "count", 25),
|
||||
self._q(query, "search", "") or "",
|
||||
self._bool_query(query, "unread", False),
|
||||
),
|
||||
}
|
||||
if path == "/mail/messages/get":
|
||||
return 200, {"message": self.client.get_message(self._required_query(query, "id"))}
|
||||
if path == "/calendars":
|
||||
return 200, {"calendars": self.client.list_calendars()}
|
||||
if path == "/calendars/events":
|
||||
return 200, {
|
||||
"calendar": self._q(query, "calendar", "") or "",
|
||||
"events": self.client.list_events(
|
||||
self._q(query, "calendar", "") or "",
|
||||
self._q(query, "start", "") or "",
|
||||
self._q(query, "end", "") or "",
|
||||
),
|
||||
}
|
||||
if path == "/tasklists":
|
||||
return 200, {"tasklists": self.client.list_task_lists()}
|
||||
if path == "/tasks":
|
||||
task_list = self._q(query, "list", "") or ""
|
||||
return 200, {"list": task_list, "tasks": self.client.list_tasks(task_list)}
|
||||
if path == "/contacts":
|
||||
return 200, {
|
||||
"contacts": self.client.list_contacts(
|
||||
self._q(query, "query", "") or "", self._int_query(query, "count", 50)
|
||||
)
|
||||
}
|
||||
if path == "/files":
|
||||
folder = self._q(query, "path", "/") or "/"
|
||||
return 200, {"path": folder, "entries": self.client.list_files(folder)}
|
||||
if path == "/files/read":
|
||||
return 200, self.client.read_file(self._required_query(query, "path"))
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
def _post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if path == "/mail/send":
|
||||
recipients = self._string_list(payload, "to")
|
||||
if not recipients:
|
||||
raise ValueError("to is required")
|
||||
return 200, self.client.send_mail(
|
||||
recipients,
|
||||
self._optional_str(payload, "subject"),
|
||||
self._optional_str(payload, "body"),
|
||||
self._string_list(payload, "cc"),
|
||||
self._optional_str(payload, "content_type", "text") or "text",
|
||||
)
|
||||
if path == "/mail/draft":
|
||||
return 200, self.client.create_draft(
|
||||
self._string_list(payload, "to"),
|
||||
self._optional_str(payload, "subject"),
|
||||
self._optional_str(payload, "body"),
|
||||
self._string_list(payload, "cc"),
|
||||
self._optional_str(payload, "content_type", "text") or "text",
|
||||
)
|
||||
if path == "/calendars/events":
|
||||
return 200, self.client.create_event(
|
||||
calendar=self._optional_str(payload, "calendar"),
|
||||
subject=self._required(payload, "subject"),
|
||||
start=self._required(payload, "start"),
|
||||
end=self._optional_str(payload, "end"),
|
||||
all_day=self._optional_bool(payload, "all_day", False),
|
||||
location=self._optional_str(payload, "location"),
|
||||
description=self._optional_str(payload, "description"),
|
||||
attendees=self._string_list(payload, "attendees"),
|
||||
timezone_name=self._optional_str(payload, "timezone"),
|
||||
)
|
||||
if path == "/calendars/events/update":
|
||||
event_id = self._required(payload, "id")
|
||||
changes = {
|
||||
key: payload[key]
|
||||
for key in ("subject", "start", "end", "location", "description")
|
||||
if key in payload
|
||||
}
|
||||
if "all_day" in payload:
|
||||
changes["all_day"] = self._optional_bool(payload, "all_day", False)
|
||||
return 200, self.client.update_event(
|
||||
event_id, timezone_name=self._optional_str(payload, "timezone"), **changes
|
||||
)
|
||||
if path == "/calendars/events/delete":
|
||||
return 200, self.client.delete_event(self._required(payload, "id"))
|
||||
if path == "/tasks":
|
||||
return 200, self.client.create_task(
|
||||
task_list=self._optional_str(payload, "list"),
|
||||
title=self._required(payload, "title"),
|
||||
due=self._optional_str(payload, "due"),
|
||||
importance=self._optional_str(payload, "importance"),
|
||||
description=self._optional_str(payload, "description"),
|
||||
)
|
||||
if path == "/tasks/update":
|
||||
task_id = self._required(payload, "id")
|
||||
changes = {
|
||||
key: payload[key]
|
||||
for key in ("title", "due", "importance", "status", "description")
|
||||
if key in payload
|
||||
}
|
||||
return 200, self.client.update_task(
|
||||
task_id, task_list=self._optional_str(payload, "list"), **changes
|
||||
)
|
||||
if path == "/tasks/complete":
|
||||
return 200, self.client.complete_task(
|
||||
self._required(payload, "id"), task_list=self._optional_str(payload, "list")
|
||||
)
|
||||
if path == "/tasks/delete":
|
||||
return 200, self.client.delete_task(
|
||||
self._required(payload, "id"), task_list=self._optional_str(payload, "list")
|
||||
)
|
||||
if path == "/files/write":
|
||||
return 200, self.client.write_file(
|
||||
self._required(payload, "path"),
|
||||
self._required(payload, "content", allow_empty=True),
|
||||
self._optional_str(payload, "encoding", "utf-8") or "utf-8",
|
||||
self._optional_bool(payload, "overwrite", True),
|
||||
)
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
# ---- input helpers ----
|
||||
|
||||
@staticmethod
|
||||
def _q(query: dict, key: str, default=None):
|
||||
values = query.get(key)
|
||||
if not values:
|
||||
return default
|
||||
return values[0]
|
||||
|
||||
@staticmethod
|
||||
def _required_query(query: dict, key: str) -> str:
|
||||
value = OutlookBridge._q(query, key)
|
||||
if value is None or not str(value).strip():
|
||||
raise ValueError(f"{key} is required")
|
||||
return str(value).strip()
|
||||
|
||||
@staticmethod
|
||||
def _int_query(query: dict, key: str, default: int) -> int:
|
||||
value = OutlookBridge._q(query, key)
|
||||
if value is None or str(value).strip() == "":
|
||||
return default
|
||||
try:
|
||||
return int(str(value))
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"{key} must be an integer") from exc
|
||||
|
||||
@staticmethod
|
||||
def _bool_query(query: dict, key: str, default: bool) -> bool:
|
||||
value = OutlookBridge._q(query, key)
|
||||
if value is None or str(value).strip() == "":
|
||||
return default
|
||||
return str(value).strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
@staticmethod
|
||||
def _required(payload: dict, key: str, allow_empty: bool = False) -> str:
|
||||
value = payload.get(key)
|
||||
if not isinstance(value, str) or (not allow_empty and not value.strip()):
|
||||
raise ValueError(f"{key} is required")
|
||||
return value if allow_empty else value.strip()
|
||||
|
||||
@staticmethod
|
||||
def _optional_str(payload: dict, key: str, default: str = "") -> str:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"{key} must be a string")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_bool(payload: dict, key: str, default: bool) -> bool:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError(f"{key} must be a boolean")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _string_list(payload: dict, key: str) -> list[str]:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
||||
raise ValueError(f"{key} must be a list of strings")
|
||||
return value
|
||||
File diff suppressed because it is too large.
Load diff
+206
-48
@@ -1,43 +1,216 @@
|
||||
"""The bridge catalog: discovery, prompt description, and standalone runner.
|
||||
|
||||
Every known bridge class is listed in `CATALOG`. `known_infos()` exposes their
|
||||
static metadata, `describe_bridges()` renders the catalog block injected into
|
||||
the code-generation prompts, and `run_bridges()` starts the enabled ones as a
|
||||
standalone process (`python -m semif_agent.cli bridge`). Adding a bridge means
|
||||
adding its class here and a `config.example.json` block; the gateway is never
|
||||
touched.
|
||||
A bridge implementation ships **with its pack** (``packs/<name>/bridge/``); the
|
||||
core owns only the shared contract (``bridges/base.py``) and this registry. A
|
||||
pack's ``pack.json`` names its bridge(s) in ``bridges`` and ships one module per
|
||||
name under ``bridge/`` (``bridge/<name>.py``, plus optional sibling modules such
|
||||
as ``bridge/<name>_client.py``). The registry imports each enabled pack's bridge
|
||||
by convention, so nothing in the core names a concrete bridge — a new bridge is a
|
||||
new pack, not a core edit.
|
||||
|
||||
The shared, pack-less **LLM bridge** stays a core built-in (``CORE_BRIDGES``):
|
||||
many packs call it, so it belongs to no single concern. ``known_infos()`` exposes
|
||||
every bridge's static metadata, ``describe_bridges()`` renders the catalog block
|
||||
injected into the code-generation prompts, and ``run_bridges()`` starts the
|
||||
enabled ones as a standalone process (``python -m semif_agent.cli bridge``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import importlib.util
|
||||
import sys
|
||||
import threading
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .browser import BrowserBridge
|
||||
from .llm import LLMBridge
|
||||
from .nextcloud import NextcloudBridge
|
||||
from .outlook import OutlookBridge
|
||||
from .simplex import SimplexBridge
|
||||
|
||||
#: Known bridge services. Order is presentation order.
|
||||
CATALOG: tuple[type[BridgeService], ...] = (
|
||||
SimplexBridge,
|
||||
LLMBridge,
|
||||
NextcloudBridge,
|
||||
OutlookBridge,
|
||||
BrowserBridge,
|
||||
)
|
||||
#: The agent checkout root; a relative pack root resolves against it, and the
|
||||
#: default pack root is ``<checkout>/packs``.
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
DEFAULT_PACK_ROOT = REPO_ROOT / "packs"
|
||||
|
||||
#: Bridges that belong to no pack — shared services any pack may call. They
|
||||
#: still live under ``bridges.<name>`` so ``derived_config_vars`` and
|
||||
#: ``run_bridges`` find them. Order is presentation order.
|
||||
CORE_BRIDGES: tuple[type[BridgeService], ...] = (LLMBridge,)
|
||||
|
||||
#: Pack-discovered bridge classes, keyed by ``pack:bridge:path`` (loaded once
|
||||
#: per process).
|
||||
_CLASS_CACHE: dict[str, type[BridgeService]] = {}
|
||||
|
||||
#: Packs the running scheduler discovered; ``describe_bridges()`` (called from
|
||||
#: codegen with no config) prefers these over a fresh default-root scan.
|
||||
_ACTIVE_PACKS: list | None = None
|
||||
|
||||
|
||||
def _class_for(name: str) -> type[BridgeService] | None:
|
||||
for bridge_class in CATALOG:
|
||||
def set_bridge_packs(packs) -> None:
|
||||
"""Record the packs the running agent loaded, for prompt-time discovery.
|
||||
|
||||
``describe_bridges()`` is called from codegen, which has no config in hand;
|
||||
``build_scheduler`` calls this after loading packs so the catalog reflects
|
||||
the host's real ``skill_packs`` roots. ``None`` restores default discovery.
|
||||
"""
|
||||
global _ACTIVE_PACKS
|
||||
_ACTIVE_PACKS = list(packs) if packs is not None else None
|
||||
|
||||
|
||||
def _resolve_roots(roots) -> list[Path]:
|
||||
if isinstance(roots, (str, Path)):
|
||||
roots = [roots]
|
||||
if not roots:
|
||||
roots = [DEFAULT_PACK_ROOT]
|
||||
resolved = []
|
||||
for root in roots:
|
||||
path = Path(str(root))
|
||||
resolved.append(path if path.is_absolute() else REPO_ROOT / path)
|
||||
return resolved
|
||||
|
||||
|
||||
def _packs_from_roots(roots=None) -> list:
|
||||
from ..packs import PackRegistry
|
||||
|
||||
return PackRegistry(_resolve_roots(roots)).discover()
|
||||
|
||||
|
||||
def _packs_from_config(config: dict) -> list:
|
||||
return _packs_from_roots((config or {}).get("skill_packs"))
|
||||
|
||||
|
||||
def _packs(packs=None) -> list:
|
||||
if packs is not None:
|
||||
return list(packs)
|
||||
if _ACTIVE_PACKS is not None:
|
||||
return list(_ACTIVE_PACKS)
|
||||
return _packs_from_roots(None)
|
||||
|
||||
|
||||
def _load_package(module_name: str, directory: Path) -> types.ModuleType:
|
||||
"""Import ``directory`` as a package under ``module_name`` (idempotent).
|
||||
|
||||
The pack's ``bridge/`` folder is loaded from its real path (never relying on
|
||||
it being importable by name), so sibling modules and relative imports work
|
||||
regardless of where the pack was cloned. An absent ``__init__.py`` is fine —
|
||||
a synthetic package namespace is registered instead.
|
||||
"""
|
||||
existing = sys.modules.get(module_name)
|
||||
if existing is not None:
|
||||
return existing
|
||||
init = directory / "__init__.py"
|
||||
if not init.is_file():
|
||||
package = types.ModuleType(module_name)
|
||||
package.__path__ = [str(directory)] # type: ignore[attr-defined]
|
||||
package.__package__ = module_name
|
||||
sys.modules[module_name] = package
|
||||
return package
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
module_name, init, submodule_search_locations=[str(directory)]
|
||||
)
|
||||
if spec is None or spec.loader is None:
|
||||
raise ImportError(f"cannot load bridge package at {directory}")
|
||||
package = importlib.util.module_from_spec(spec)
|
||||
sys.modules[module_name] = package
|
||||
spec.loader.exec_module(package)
|
||||
return package
|
||||
|
||||
|
||||
def _find_bridge_class(module: types.ModuleType, name: str) -> type[BridgeService] | None:
|
||||
"""The ``BridgeService`` subclass a pack bridge module defines.
|
||||
|
||||
An explicit ``BRIDGE`` attribute wins; otherwise scan for subclasses defined
|
||||
in the module, preferring one whose ``INFO.name`` matches the pack's declared
|
||||
bridge name.
|
||||
"""
|
||||
explicit = getattr(module, "BRIDGE", None)
|
||||
if isinstance(explicit, type) and issubclass(explicit, BridgeService):
|
||||
return explicit
|
||||
candidates = [
|
||||
value
|
||||
for value in vars(module).values()
|
||||
if isinstance(value, type)
|
||||
and issubclass(value, BridgeService)
|
||||
and value is not BridgeService
|
||||
and getattr(value, "__module__", None) == module.__name__
|
||||
]
|
||||
for candidate in candidates:
|
||||
info = getattr(candidate, "INFO", None)
|
||||
if info is not None and getattr(info, "name", None) == name:
|
||||
return candidate
|
||||
return candidates[0] if candidates else None
|
||||
|
||||
|
||||
def load_pack_bridge_class(pack, bridge_name: str) -> type[BridgeService] | None:
|
||||
"""Import one pack's bridge module and return its bridge class (or None)."""
|
||||
bridge_dir = Path(pack.path) / "bridge"
|
||||
module_file = bridge_dir / f"{bridge_name}.py"
|
||||
if not module_file.is_file():
|
||||
return None
|
||||
package_name = f"semif_pack_bridge_{pack.name}"
|
||||
_load_package(package_name, bridge_dir)
|
||||
module = importlib.import_module(f"{package_name}.{bridge_name}")
|
||||
return _find_bridge_class(module, bridge_name)
|
||||
|
||||
|
||||
def load_pack_bridge_package(pack_name: str, packs=None) -> types.ModuleType:
|
||||
"""Import and return a pack's ``bridge/`` package.
|
||||
|
||||
The package is registered under the stable name
|
||||
``semif_pack_bridge_<pack>``, so a caller (a pack's own test, or a tool) can
|
||||
import a sibling module with ``importlib.import_module(f"{pkg.__name__}.<mod>")``.
|
||||
"""
|
||||
pack = next((p for p in _packs(packs) if p.name == pack_name), None)
|
||||
if pack is None:
|
||||
raise KeyError(f"unknown pack: {pack_name!r}")
|
||||
bridge_dir = Path(pack.path) / "bridge"
|
||||
if not bridge_dir.is_dir():
|
||||
raise KeyError(f"pack {pack_name!r} ships no bridge/ directory")
|
||||
return _load_package(f"semif_pack_bridge_{pack.name}", bridge_dir)
|
||||
|
||||
|
||||
def load_pack_bridge_module(
|
||||
pack_name: str, bridge_name: str, packs=None
|
||||
) -> types.ModuleType:
|
||||
"""Import and return one pack's bridge module (``bridge/<bridge_name>.py``)."""
|
||||
package = load_pack_bridge_package(pack_name, packs)
|
||||
return importlib.import_module(f"{package.__name__}.{bridge_name}")
|
||||
|
||||
|
||||
def discover_bridge_classes(packs=None) -> list[type[BridgeService]]:
|
||||
"""Every bridge class: the packs' bridges (in pack order) then core built-ins.
|
||||
|
||||
With no ``packs``, uses the running scheduler's packs, else a scan of the
|
||||
default pack root. A pack that declares a bridge but ships no ``bridge/``
|
||||
module is skipped (a half-authored pack never breaks the catalog).
|
||||
"""
|
||||
classes: list[type[BridgeService]] = []
|
||||
for pack in _packs(packs):
|
||||
for bridge_name in getattr(pack, "bridges", ()) or ():
|
||||
key = f"{pack.name}:{bridge_name}:{getattr(pack, 'path', '')}"
|
||||
if key not in _CLASS_CACHE:
|
||||
found = load_pack_bridge_class(pack, bridge_name)
|
||||
if found is None:
|
||||
continue
|
||||
_CLASS_CACHE[key] = found
|
||||
bridge_class = _CLASS_CACHE[key]
|
||||
if bridge_class not in classes:
|
||||
classes.append(bridge_class)
|
||||
for bridge_class in CORE_BRIDGES:
|
||||
if bridge_class not in classes:
|
||||
classes.append(bridge_class)
|
||||
return classes
|
||||
|
||||
|
||||
def _class_for(name: str, packs=None) -> type[BridgeService] | None:
|
||||
for bridge_class in discover_bridge_classes(packs):
|
||||
if bridge_class.INFO.name == name:
|
||||
return bridge_class
|
||||
return None
|
||||
|
||||
|
||||
def known_infos() -> list[BridgeInfo]:
|
||||
return [bridge_class.INFO for bridge_class in CATALOG]
|
||||
def known_infos(packs=None) -> list[BridgeInfo]:
|
||||
return [bridge_class.INFO for bridge_class in discover_bridge_classes(packs)]
|
||||
|
||||
|
||||
def derived_config_vars(config: dict) -> dict[str, str]:
|
||||
@@ -53,7 +226,7 @@ def derived_config_vars(config: dict) -> dict[str, str]:
|
||||
"""
|
||||
blocks = config.get("bridges", {}) or {}
|
||||
derived: dict[str, str] = {}
|
||||
for info in known_infos():
|
||||
for info in known_infos(_packs_from_config(config)):
|
||||
block = blocks.get(info.name)
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
@@ -69,7 +242,7 @@ def derived_config_vars(config: dict) -> dict[str, str]:
|
||||
return derived
|
||||
|
||||
|
||||
def describe_bridges() -> str:
|
||||
def describe_bridges(packs=None) -> str:
|
||||
"""A prompt block describing every available bridge service.
|
||||
|
||||
Injected into the skill-body, retry, regen, and testgen
|
||||
@@ -87,7 +260,7 @@ def describe_bridges() -> str:
|
||||
"urllib.request rather than reaching around it; read every value from "
|
||||
"ctx.config:",
|
||||
]
|
||||
for info in known_infos():
|
||||
for info in known_infos(packs):
|
||||
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:
|
||||
@@ -114,32 +287,17 @@ def build_bridge(
|
||||
) -> BridgeService:
|
||||
"""Instantiate one bridge from the top-level `bridges.<name>` config block.
|
||||
|
||||
`llm` is the scheduler's configured language-model client, handed to the LLM
|
||||
bridge so it reuses the top-level `llm` endpoint/model instead of duplicating
|
||||
that config. The Nextcloud bridge gets the top-level `nextcloud_*` values as a
|
||||
fallback, so the same account the nextcloud pack's skills use is configured once. Other
|
||||
bridges ignore both.
|
||||
The class is discovered from the host's packs (plus the core built-ins); it
|
||||
is constructed through ``BridgeService.from_config``, so a bridge that needs
|
||||
the scheduler's ``llm`` client (the shared LLM bridge) or top-level fallback
|
||||
values (Nextcloud's ``nextcloud_*``) declares that itself rather than the
|
||||
core special-casing it by name.
|
||||
"""
|
||||
bridge_class = _class_for(name)
|
||||
bridge_class = _class_for(name, _packs_from_config(config))
|
||||
if bridge_class is None:
|
||||
raise KeyError(f"unknown bridge: {name!r}")
|
||||
block = (config.get("bridges", {}) or {}).get(name, {}) or {}
|
||||
if bridge_class is LLMBridge:
|
||||
return LLMBridge(block, trace=trace, client=llm)
|
||||
if bridge_class is NextcloudBridge:
|
||||
return NextcloudBridge(
|
||||
block,
|
||||
trace=trace,
|
||||
fallback={
|
||||
"url": config.get("nextcloud_url"),
|
||||
"username": config.get("nextcloud_username"),
|
||||
"app_password": config.get("nextcloud_app_password"),
|
||||
"default_calendar": config.get("nextcloud_default_calendar"),
|
||||
"default_task_calendar": config.get("nextcloud_default_task_calendar"),
|
||||
"default_addressbook": config.get("nextcloud_default_addressbook"),
|
||||
},
|
||||
)
|
||||
return bridge_class(block, trace=trace)
|
||||
return bridge_class.from_config(block, config=config, trace=trace, llm=llm)
|
||||
|
||||
|
||||
def run_bridges(
|
||||
@@ -156,7 +314,7 @@ def run_bridges(
|
||||
"""
|
||||
blocks = config.get("bridges", {}) or {}
|
||||
selected: list[BridgeService] = []
|
||||
for bridge_class in CATALOG:
|
||||
for bridge_class in discover_bridge_classes(_packs_from_config(config)):
|
||||
name = bridge_class.INFO.name
|
||||
if names and name not in names:
|
||||
continue
|
||||
|
||||
@@ -1,493 +0,0 @@
|
||||
"""SimpleX forwarding bridge: invite links, reading, and sending for skills.
|
||||
|
||||
The first third-party API bridge. It stands up a small HTTP API that a skill
|
||||
body calls instead of talking to `simplex-chat` directly, and it owns its **own**
|
||||
SimpleX daemon/profile — separate from the command gateway's. That separation is
|
||||
the point: the gateway takes commands; this bridge forwards the user's messaging
|
||||
UX (show/create the contact link, read the next message, compose a send).
|
||||
|
||||
It buffers every inbound direct message (no allowlist — the user wants to see
|
||||
who reached the bot through its invite link), and it never runs inside the
|
||||
gateway process.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
from semif_agent.simplex_ws import SimplexDaemon, parse_send_response
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .inbox import MessagingInbox
|
||||
|
||||
#: Send statuses that mean the message really left the agent.
|
||||
SEND_OK_STATUSES = frozenset({"sndSent", "sndRcvd"})
|
||||
#: Send statuses that are final (no further polling needed).
|
||||
SEND_TERMINAL_STATUSES = frozenset({"sndSent", "sndRcvd", "sndError"})
|
||||
#: How long to poll the daemon for a terminal send status before giving up.
|
||||
SEND_CONFIRM_TIMEOUT = 6.0
|
||||
SEND_POLL_INTERVAL = 0.5
|
||||
|
||||
|
||||
class SimplexBridge(BridgeService):
|
||||
name = "simplex"
|
||||
INFO = BridgeInfo(
|
||||
name="simplex",
|
||||
service="simplex",
|
||||
description=(
|
||||
"Read and send SimpleX messages on the user's behalf, and show or "
|
||||
"create the contact link others use to reach this agent."
|
||||
),
|
||||
url_config_var="simplex_bridge_url",
|
||||
endpoints=(
|
||||
"GET /health -> 200 {\"ok\": true, \"platform\": \"simplex\"} — the "
|
||||
"bridge is up",
|
||||
"GET /contacts -> 200 {\"contacts\": [{\"id\", \"display_name\", "
|
||||
"\"local_name\"?, \"connected\"?}]} — contacts known to the daemon "
|
||||
"(learned from inbound messages and refreshed from the daemon's "
|
||||
"contact list). `display_name` is the peer's profile name and can "
|
||||
"collide; `local_name` is the daemon's unique local name; "
|
||||
"`connected` (when the daemon reports it) is false for a peer whose "
|
||||
"connection is not ready — prefer a connected peer",
|
||||
"GET /inbox -> 200 {\"messages\": [{\"id\", \"contact_id\", "
|
||||
"\"display_name\", \"text\", \"received_at\"}]} — peek buffered "
|
||||
"inbound messages; does not consume",
|
||||
"GET /inbox/next?contact=<id> -> 200 {\"message\": {...}|null} — pop "
|
||||
"the oldest unread message (optionally from one contact); null means "
|
||||
"none buffered. The bridge owns the read cursor",
|
||||
"GET /unread -> 200 {\"chats\": [{\"contact_id\", \"display_name\", "
|
||||
"\"unread_count\", \"min_unread_item_id\", \"unread\", "
|
||||
"\"connected\"?, \"auth_errors\"?, \"messages\": "
|
||||
"[{item_id, text, status, unread, direction, sent_at}]}]} — the "
|
||||
"daemon's persistent unread chats (survives bridge restarts), not "
|
||||
"just what arrived while connected. Read-only; 503 when the daemon "
|
||||
"is not connected, 502 when the lookup fails",
|
||||
"GET /history?contact=<id>&count=<n> -> 200 {\"contact_id\", "
|
||||
"\"messages\": [{item_id, text, status, unread, direction, "
|
||||
"sent_at, error?}]} — recent message history for one contact (count "
|
||||
"default 20); status is rcvNew (unread), rcvRead, sndSent, sndRcvd, "
|
||||
"or sndError, and `error` carries the agent reason (e.g. auth) on a "
|
||||
"failed send. Read-only; 503/502 as /unread, 400 without a contact",
|
||||
"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\": \"<id|local_name|display_name>\", "
|
||||
"\"text\": \"...\"} -> 200 {\"ok\": bool, \"contact_id\": \"<id>\", "
|
||||
"\"item_id\": \"<id>\", \"status\": \"sndSent|sndRcvd|sndError\", "
|
||||
"\"error\": \"...\"?}. The bridge resolves the recipient, sends, and "
|
||||
"waits for the daemon's real send status: `ok` is true only for "
|
||||
"sndSent/sndRcvd, and a failed send (e.g. an auth error on a dead "
|
||||
"connection) returns ok:false with the reason — never a false "
|
||||
"success. 400 on a missing/invalid field or an unknown recipient",
|
||||
"POST /read {\"contact\": \"<id>\", \"item_ids\": [\"<id>\", ...]} -> "
|
||||
"200 {\"ok\": bool, \"contact_id\": \"<id>\", \"item_ids\": [...], "
|
||||
"\"status\": \"read|rejected|error|unavailable\", \"error\": "
|
||||
"\"...\"?} — mark the given received items read on the daemon so they "
|
||||
"leave its persistent unread state; only the listed ids are consumed. "
|
||||
"`ok` is true only when the daemon accepted it — never a fabricated "
|
||||
"success. 400 on a missing contact or empty item_ids",
|
||||
"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",
|
||||
"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):
|
||||
super().__init__(config, trace)
|
||||
cfg = config or {}
|
||||
self.inbox = MessagingInbox(int(cfg.get("max_inbox", 100)))
|
||||
self.daemon = daemon or SimplexDaemon(
|
||||
cfg.get("ws_url", "ws://127.0.0.1:5228"),
|
||||
user_id=int(cfg.get("user_id", 1)),
|
||||
auto_accept=bool(cfg.get("auto_accept", True)),
|
||||
reconnect=cfg.get("reconnect", {}) or {},
|
||||
on_connected=self._refresh_on_connect,
|
||||
trace=trace,
|
||||
name=self.name,
|
||||
)
|
||||
self._daemon_thread: threading.Thread | None = None
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
return self.daemon.check_requirements()
|
||||
|
||||
def start(self) -> int:
|
||||
port = super().start()
|
||||
self._daemon_thread = threading.Thread(
|
||||
target=self.daemon.run,
|
||||
args=(self._on_message,),
|
||||
name="bridge-simplex-daemon",
|
||||
daemon=True,
|
||||
)
|
||||
self._daemon_thread.start()
|
||||
return port
|
||||
|
||||
def _stop_transport(self) -> None:
|
||||
self.daemon.close()
|
||||
|
||||
def _on_message(self, message: dict) -> None:
|
||||
self.inbox.record(message)
|
||||
|
||||
async def _refresh_on_connect(self) -> None:
|
||||
"""Prime the contact list from the daemon on (re)connect.
|
||||
|
||||
Runs on the daemon's event loop, so it awaits `contacts()` directly
|
||||
rather than the thread-safe wrapper. A failure is traced, not fatal.
|
||||
"""
|
||||
contacts = await self.daemon.contacts()
|
||||
self.inbox.merge_contacts(contacts)
|
||||
self._event("contacts_refreshed", count=len(contacts))
|
||||
|
||||
# ---- routes ----
|
||||
|
||||
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/health":
|
||||
return 200, {"ok": True, "platform": self.name}
|
||||
if path == "/contacts":
|
||||
return 200, {"contacts": self.refresh_contacts()}
|
||||
if path == "/inbox":
|
||||
return 200, {"messages": self.inbox.peek()}
|
||||
if path == "/inbox/next":
|
||||
contact = (query.get("contact") or [None])[0]
|
||||
return 200, {"message": self.inbox.pop(contact)}
|
||||
if path == "/unread":
|
||||
return self._unread(query)
|
||||
if path == "/history":
|
||||
contact = (query.get("contact") or [None])[0]
|
||||
count = (query.get("count") or [None])[0]
|
||||
return self._history(contact, count)
|
||||
if path == "/address":
|
||||
return self._address()
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if path == "/read":
|
||||
return self._read(payload)
|
||||
if path != "/send":
|
||||
return 404, {"error": "not found"}
|
||||
recipient = payload.get("recipient")
|
||||
text = payload.get("text")
|
||||
if not isinstance(recipient, str) or not recipient.strip():
|
||||
return 400, {"error": "recipient is required"}
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return 400, {"error": "text is required"}
|
||||
try:
|
||||
result = self.send(recipient, text)
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)}
|
||||
return 200, result
|
||||
|
||||
# ---- actions ----
|
||||
|
||||
def _read(self, payload: dict) -> tuple[int, dict]:
|
||||
contact = payload.get("contact")
|
||||
item_ids = payload.get("item_ids")
|
||||
if not isinstance(contact, str) or not contact.strip():
|
||||
return 400, {"error": "contact is required"}
|
||||
if not isinstance(item_ids, list) or not item_ids:
|
||||
return 400, {"error": "item_ids is required"}
|
||||
try:
|
||||
result = self.mark_read(contact, item_ids)
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)}
|
||||
return 200, result
|
||||
|
||||
def mark_read(self, contact: str, item_ids) -> dict:
|
||||
"""Mark the given received items read on the bridge's own daemon.
|
||||
|
||||
Returns `{ok, contact_id, item_ids, status, error?}`. `ok` is True only
|
||||
when the daemon accepted the command; a disconnected or failing daemon
|
||||
reports the reason (never a false success). Reading is precise: only the
|
||||
listed item ids are consumed, so the rest of the chat stays unread.
|
||||
"""
|
||||
contact_id = str(contact or "").strip()
|
||||
ids = [str(i).strip() for i in (item_ids or []) if str(i).strip()]
|
||||
if not contact_id:
|
||||
raise ValueError("contact is required")
|
||||
if not ids:
|
||||
raise ValueError("item_ids is required")
|
||||
try:
|
||||
response = self.daemon.request_mark_read(contact_id, ids)
|
||||
except RuntimeError as exc:
|
||||
return {
|
||||
"ok": False,
|
||||
"contact_id": contact_id,
|
||||
"item_ids": ids,
|
||||
"status": "unavailable",
|
||||
"error": str(exc)[:300],
|
||||
}
|
||||
except Exception as exc: # TimeoutError, daemon error
|
||||
return {
|
||||
"ok": False,
|
||||
"contact_id": contact_id,
|
||||
"item_ids": ids,
|
||||
"status": "error",
|
||||
"error": str(exc)[:300],
|
||||
}
|
||||
ok = bool(response.get("ok")) if isinstance(response, dict) else False
|
||||
result = {
|
||||
"ok": ok,
|
||||
"contact_id": contact_id,
|
||||
"item_ids": ids,
|
||||
"status": "read" if ok else "rejected",
|
||||
}
|
||||
if not ok:
|
||||
detail = response.get("error") if isinstance(response, dict) else ""
|
||||
result["error"] = detail or "the daemon did not mark the items read"
|
||||
return result
|
||||
|
||||
def refresh_contacts(self) -> list[dict]:
|
||||
"""Best-effort refresh of the daemon's contact list into the inbox.
|
||||
|
||||
Never raises: when the daemon is not connected (or is slow) it returns
|
||||
whatever contacts are already cached, so `/contacts` and `/send` stay
|
||||
available. The read cursor and inbound-learned names are preserved.
|
||||
"""
|
||||
try:
|
||||
contacts = self.daemon.request_contacts()
|
||||
except Exception as exc: # RuntimeError, TimeoutError, daemon error
|
||||
self._event("contacts_refresh_failed", message=str(exc)[:200])
|
||||
return self.inbox.contacts()
|
||||
self.inbox.merge_contacts(contacts)
|
||||
self._event("contacts_refreshed", count=len(contacts))
|
||||
return self.inbox.contacts()
|
||||
|
||||
def _unread(self, query: dict) -> tuple[int, dict]:
|
||||
"""The daemon's persistent unread chats (not the live receive buffer).
|
||||
|
||||
Read-only: there is no mark-read command in v7, so this never consumes.
|
||||
Best-effort like `/address` — 503 when the daemon is not connected, 502
|
||||
when the lookup fails, never a fabricated chat.
|
||||
"""
|
||||
count = self._count((query.get("count") or [None])[0])
|
||||
try:
|
||||
chats = self.daemon.request_chats(unread_only=True, count=count)
|
||||
except RuntimeError as exc:
|
||||
return 503, {"error": f"unread lookup is not available: {exc}"[:300]}
|
||||
except Exception as exc: # TimeoutError, daemon error
|
||||
return 502, {"error": f"unread lookup failed: {exc}"[:300]}
|
||||
self._attach_health(chats)
|
||||
return 200, {"chats": chats}
|
||||
|
||||
def _attach_health(self, chats: list[dict]) -> None:
|
||||
"""Merge cached connection health into each chat summary, in place.
|
||||
|
||||
Lets a caller prefer a live conversation over a stale duplicate when
|
||||
several chats share a display name. Best-effort: a chat with no cached
|
||||
contact is left untouched.
|
||||
"""
|
||||
health = {c["id"]: c for c in self.inbox.contacts()}
|
||||
for chat in chats:
|
||||
info = health.get(str(chat.get("contact_id") or ""))
|
||||
if not info:
|
||||
continue
|
||||
for key in ("connected", "auth_errors"):
|
||||
if key in info:
|
||||
chat[key] = info[key]
|
||||
|
||||
def _history(self, contact: str | None, count: str | None) -> tuple[int, dict]:
|
||||
"""Recent message history for one contact, straight from the daemon.
|
||||
|
||||
Read-only. A missing contact is a client error; a disconnected or
|
||||
failing daemon degrades like `/unread`.
|
||||
"""
|
||||
contact = str(contact or "").strip()
|
||||
if not contact:
|
||||
return 400, {"error": "contact is required"}
|
||||
try:
|
||||
messages = self.daemon.request_chat_history(
|
||||
contact, count=self._count(count)
|
||||
)
|
||||
except RuntimeError as exc:
|
||||
return 503, {"error": f"history lookup is not available: {exc}"[:300]}
|
||||
except Exception as exc: # TimeoutError, daemon error
|
||||
return 502, {"error": f"history lookup failed: {exc}"[:300]}
|
||||
return 200, {"contact_id": contact, "messages": messages}
|
||||
|
||||
@staticmethod
|
||||
def _count(raw: str | None, default: int = 20, maximum: int = 100) -> int:
|
||||
try:
|
||||
value = int(raw) if raw is not None else default
|
||||
except (TypeError, ValueError):
|
||||
value = default
|
||||
return max(1, min(value, maximum))
|
||||
|
||||
def _address(self) -> tuple[int, dict]:
|
||||
try:
|
||||
link = self.daemon.request_address()
|
||||
except RuntimeError as exc:
|
||||
return 503, {"error": f"address lookup is not available: {exc}"[:300]}
|
||||
except Exception as exc: # TimeoutError, daemon error
|
||||
return 502, {"error": f"address lookup failed: {exc}"[:300]}
|
||||
if not isinstance(link, dict):
|
||||
return 502, {"error": "address lookup returned no link"}
|
||||
return 200, link
|
||||
|
||||
def send(self, recipient: str, text: str) -> dict:
|
||||
"""Resolve a recipient, send the text, and report the real outcome.
|
||||
|
||||
Returns `{ok, contact_id, item_id?, status?, error?}`. `ok` is True only
|
||||
when the daemon created the message and it reached a terminal status of
|
||||
`sndSent` (relayed to the server) or `sndRcvd` (delivered to the peer).
|
||||
A dead connection surfaces as `ok: false` carrying the daemon's agent
|
||||
error (e.g. `auth`) — never a false success.
|
||||
"""
|
||||
contact_id = self.resolve(recipient)
|
||||
if contact_id is None:
|
||||
raise ValueError(f"unknown SimpleX recipient: {recipient!r}")
|
||||
try:
|
||||
response = self.daemon.request_send(contact_id, text)
|
||||
except RuntimeError as exc:
|
||||
return {
|
||||
"ok": False,
|
||||
"contact_id": contact_id,
|
||||
"status": "unavailable",
|
||||
"error": str(exc)[:300],
|
||||
}
|
||||
except Exception as exc: # TimeoutError, daemon error
|
||||
return {
|
||||
"ok": False,
|
||||
"contact_id": contact_id,
|
||||
"status": "error",
|
||||
"error": str(exc)[:300],
|
||||
}
|
||||
parsed = parse_send_response(response)
|
||||
if parsed["item_id"] is None:
|
||||
return {
|
||||
"ok": False,
|
||||
"contact_id": contact_id,
|
||||
"status": "rejected",
|
||||
"error": parsed["error"] or "the daemon rejected the send",
|
||||
}
|
||||
item_id = parsed["item_id"]
|
||||
status, error = parsed["status"], parsed["error"]
|
||||
if status not in SEND_TERMINAL_STATUSES:
|
||||
status, error = self._await_send_status(contact_id, item_id, status)
|
||||
result = {
|
||||
"ok": status in SEND_OK_STATUSES,
|
||||
"contact_id": contact_id,
|
||||
"item_id": item_id,
|
||||
"status": status,
|
||||
}
|
||||
if not result["ok"]:
|
||||
result["error"] = error or f"send status {status}"
|
||||
return result
|
||||
|
||||
def _await_send_status(
|
||||
self, contact_id: str, item_id: str, current: str,
|
||||
timeout: float = SEND_CONFIRM_TIMEOUT,
|
||||
) -> tuple[str, str]:
|
||||
"""Poll the daemon for the item's terminal send status + agent error.
|
||||
|
||||
A send is `sndNew` the moment it is created; the agent then resolves it
|
||||
to `sndSent`/`sndRcvd` (success) or `sndError` (failure, with the reason
|
||||
in `agentError`). Returns `(status, error)`; a still-`sndNew` item after
|
||||
the window stays unconfirmed rather than being reported as sent.
|
||||
"""
|
||||
deadline = time.monotonic() + timeout
|
||||
status, error = current, ""
|
||||
while True:
|
||||
try:
|
||||
messages = self.daemon.request_chat_history(contact_id, count=20)
|
||||
except Exception:
|
||||
return status or "unknown", error
|
||||
for message in messages:
|
||||
if str(message.get("item_id")) == str(item_id):
|
||||
status = str(message.get("status") or "")
|
||||
error = str(message.get("error") or "")
|
||||
if status in SEND_TERMINAL_STATUSES:
|
||||
return status, error
|
||||
if time.monotonic() >= deadline:
|
||||
return status or "unknown", error
|
||||
time.sleep(SEND_POLL_INTERVAL)
|
||||
|
||||
def resolve(self, recipient: str) -> str | None:
|
||||
"""A numeric id (with or without `@`), a unique local name, or a display name.
|
||||
|
||||
An explicit id always wins. Two peers can share a profile display name
|
||||
(the daemon suffixes its own local names, e.g. `pepper` / `pepper_1`),
|
||||
so a local-name or display-name match that hits several peers prefers
|
||||
the healthiest (connected, no recorded auth errors). On a miss, refresh
|
||||
the daemon's contact list once and retry: a contact the bridge has never
|
||||
received from is still addressable as long as the daemon knows them.
|
||||
"""
|
||||
recipient = str(recipient or "").strip()
|
||||
if not recipient:
|
||||
return None
|
||||
bare = recipient.lstrip("@")
|
||||
if bare.isdigit():
|
||||
return bare
|
||||
match = self._match_contact(recipient)
|
||||
if match is None:
|
||||
self.refresh_contacts()
|
||||
match = self._match_contact(recipient)
|
||||
return match
|
||||
|
||||
def _match_contact(self, recipient: str) -> str | None:
|
||||
contacts = self.inbox.contacts()
|
||||
for contact in contacts:
|
||||
if contact["id"] == recipient:
|
||||
return contact["id"]
|
||||
exact = [
|
||||
c
|
||||
for c in contacts
|
||||
if c.get("local_name") == recipient or c["display_name"] == recipient
|
||||
]
|
||||
if exact:
|
||||
return self._prefer_connected(exact)
|
||||
lowered = recipient.lower()
|
||||
partial = [
|
||||
c
|
||||
for c in contacts
|
||||
if lowered in c["display_name"].lower()
|
||||
or lowered in str(c.get("local_name", "")).lower()
|
||||
]
|
||||
if len(partial) == 1:
|
||||
return partial[0]["id"]
|
||||
if partial:
|
||||
return self._prefer_connected(partial)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _prefer_connected(matches: list[dict]) -> str:
|
||||
"""Pick the healthiest peer among equally-named matches.
|
||||
|
||||
Prefer a ready connection, then a connection with no recorded auth
|
||||
errors (a stale duplicate that fails to send), and finally the first.
|
||||
"""
|
||||
|
||||
def rank(contact: dict) -> tuple[bool, bool]:
|
||||
try:
|
||||
clean = int(contact.get("auth_errors") or 0) == 0
|
||||
except (TypeError, ValueError):
|
||||
clean = True
|
||||
return (bool(contact.get("connected")), clean)
|
||||
|
||||
return max(matches, key=rank)["id"]
|
||||
@@ -434,6 +434,12 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||
degeneration_check_factory=make_degeneration_check,
|
||||
regen_decision_factory=make_regen_decision,
|
||||
)
|
||||
# Bridges ship with their packs; tell the registry which packs this host
|
||||
# loaded so `describe_bridges()` (called from codegen with no config) lists
|
||||
# the real set rather than a default-root scan.
|
||||
from .bridges.registry import set_bridge_packs
|
||||
|
||||
set_bridge_packs(scheduler.packs)
|
||||
return scheduler, config
|
||||
|
||||
|
||||
|
||||
@@ -7,11 +7,12 @@ A pack is a folder with a ``pack.json`` manifest and a ``skills/`` store::
|
||||
skills/nextcloud/{create_event,create_task,next_event}/
|
||||
|
||||
The manifest binds the pieces that used to be scattered by convention — the
|
||||
concern, its category descriptions, the bridge(s) it talks to, its runtime
|
||||
requirements, and its config schema/defaults — so "the Nextcloud product, its
|
||||
bridge, its skills, and its settings" are one thing. Bridge *code* stays in
|
||||
``semif_agent/bridges`` (isolation is non-negotiable); a pack references a
|
||||
bridge by name.
|
||||
concern, its category descriptions, the bridge(s) it ships and talks to, its
|
||||
runtime requirements, and its config schema/defaults — so "the Nextcloud
|
||||
product, its bridge, its skills, and its settings" are one thing. A bridge
|
||||
*ships with its pack* (``packs/<name>/bridge/``); the core keeps only the shared
|
||||
contract (``semif_agent/bridges/base.py``) and the discovery registry
|
||||
(``semif_agent/bridges/registry.py``). Gateway isolation is non-negotiable.
|
||||
|
||||
A pack can be enabled/disabled as a unit: disabling it drops its categories from
|
||||
the tree and stops its bridge (see ``pack_enabled``). This is the same switch
|
||||
|
||||
+8
-636
@@ -1,13 +1,13 @@
|
||||
"""Pure-stdlib tests for the standalone bridge services.
|
||||
"""Core bridge tests: the shared LLM bridge and the discovery registry.
|
||||
|
||||
The SimpleX bridge is exercised over a real loopback HTTP server (no mocking of
|
||||
its HTTP transport) with a fake daemon standing in for the `simplex-chat`
|
||||
connection — 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, address lookup, and token/body validation.
|
||||
Bridge implementations ship with their packs; their hermetic tests live in the
|
||||
pack (see `packs/*/bridge/test_*.py`, run by `tests/test_packs.py`). This file
|
||||
covers what stays in the core: the shared, pack-less LLM bridge and the registry
|
||||
surface (`known_infos`/`describe_bridges`/`derived_config_vars`) that discovers
|
||||
the packs' bridges and renders the catalog codegen reads. The decision engine and
|
||||
a real model are never involved.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
@@ -20,122 +20,6 @@ from semif_agent.bridges.registry import (
|
||||
describe_bridges,
|
||||
known_infos,
|
||||
)
|
||||
from semif_agent.bridges.simplex import SimplexBridge
|
||||
|
||||
|
||||
class FakeDaemon:
|
||||
"""Stands in for the bridge's own simplex-chat connection."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
link=None,
|
||||
error=None,
|
||||
contacts=None,
|
||||
contacts_error=None,
|
||||
chats=None,
|
||||
chats_error=None,
|
||||
history=None,
|
||||
history_error=None,
|
||||
send_response=None,
|
||||
send_error=None,
|
||||
read_response=None,
|
||||
read_error=None,
|
||||
):
|
||||
self.link = link
|
||||
self.error = error
|
||||
self.contacts_list = contacts or []
|
||||
self.contacts_error = contacts_error
|
||||
self.chats_list = chats or []
|
||||
self.chats_error = chats_error
|
||||
self.history_list = history or []
|
||||
self.history_error = history_error
|
||||
self.send_response = send_response
|
||||
self.send_error = send_error
|
||||
self.read_response = read_response
|
||||
self.read_error = read_error
|
||||
self.refresh_count = 0
|
||||
self.chat_calls = []
|
||||
self.history_calls = []
|
||||
self.read_calls = []
|
||||
self.sent = []
|
||||
self.closed = False
|
||||
self.on_message = None
|
||||
|
||||
def check_requirements(self):
|
||||
return True, None
|
||||
|
||||
def run(self, on_message):
|
||||
self.on_message = on_message
|
||||
|
||||
def enqueue(self, chat_id, text=""):
|
||||
if chat_id is not None:
|
||||
self.sent.append((chat_id, text))
|
||||
|
||||
def request_send(self, chat_id, text, timeout=20.0):
|
||||
self.sent.append((chat_id, text))
|
||||
if self.send_error is not None:
|
||||
raise self.send_error
|
||||
if self.send_response is not None:
|
||||
return self.send_response
|
||||
return {
|
||||
"type": "newChatItems",
|
||||
"chatItems": [
|
||||
{"chatItem": {"meta": {"itemId": 1, "itemStatus": {"type": "sndRcvd"}}}}
|
||||
],
|
||||
}
|
||||
|
||||
def request_address(self, timeout=20.0):
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
return self.link
|
||||
|
||||
def request_contacts(self, timeout=20.0):
|
||||
self.refresh_count += 1
|
||||
if self.contacts_error is not None:
|
||||
raise self.contacts_error
|
||||
return list(self.contacts_list)
|
||||
|
||||
async def contacts(self, timeout=20.0):
|
||||
return self.request_contacts(timeout)
|
||||
|
||||
def request_chats(self, unread_only=True, count=20, timeout=20.0):
|
||||
self.chat_calls.append((unread_only, count))
|
||||
if self.chats_error is not None:
|
||||
raise self.chats_error
|
||||
return list(self.chats_list)
|
||||
|
||||
def request_chat_history(self, contact_id, count=20, timeout=20.0):
|
||||
self.history_calls.append((contact_id, count))
|
||||
if self.history_error is not None:
|
||||
raise self.history_error
|
||||
return list(self.history_list)
|
||||
|
||||
def request_mark_read(self, chat_id, item_ids=None, timeout=20.0):
|
||||
self.read_calls.append((str(chat_id), list(item_ids or [])))
|
||||
if self.read_error is not None:
|
||||
raise self.read_error
|
||||
if self.read_response is not None:
|
||||
return self.read_response
|
||||
return {"ok": True, "type": "itemsReadForChat", "error": ""}
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def start_bridge(daemon=None, **config):
|
||||
daemon = daemon or FakeDaemon()
|
||||
bridge = SimplexBridge(config, daemon=daemon)
|
||||
port = bridge.start()
|
||||
return bridge, daemon, f"http://127.0.0.1:{port}"
|
||||
|
||||
|
||||
def inbound(text, contact_id="4", display_name="Alice", item_id=""):
|
||||
return {
|
||||
"text": text,
|
||||
"contact_id": contact_id,
|
||||
"display_name": display_name,
|
||||
"item_id": item_id,
|
||||
}
|
||||
|
||||
|
||||
def get(url, token=None):
|
||||
@@ -154,427 +38,6 @@ def post(url, payload, token=None):
|
||||
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._on_message(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._on_message(inbound("first", contact_id="4", display_name="Alice"))
|
||||
bridge._on_message(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._on_message(inbound("first", contact_id="4", display_name="Alice"))
|
||||
bridge._on_message(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_buffers_any_sender():
|
||||
# No allowlist: a brand-new contact who reached the bot via its invite link
|
||||
# must be visible, which is the whole point of the forwarding bridge.
|
||||
bridge, _, base = start_bridge()
|
||||
try:
|
||||
bridge._on_message(inbound("who are you?", contact_id="99", display_name="stranger"))
|
||||
messages = get(f"{base}/inbox")["messages"]
|
||||
assert [m["text"] for m in messages] == ["who are you?"]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_inbox_is_bounded():
|
||||
bridge, _, base = start_bridge(max_inbox=2)
|
||||
try:
|
||||
for text in ("one", "two", "three"):
|
||||
bridge._on_message(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_daemon():
|
||||
bridge, daemon, base = start_bridge()
|
||||
try:
|
||||
result = post(f"{base}/send", {"recipient": "7", "text": "on my way"})
|
||||
assert result["ok"] is True, result
|
||||
assert result["contact_id"] == "7", result
|
||||
assert result["status"] == "sndRcvd", result
|
||||
assert daemon.sent == [("7", "on my way")]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_resolves_known_display_name():
|
||||
bridge, daemon, base = start_bridge()
|
||||
try:
|
||||
bridge._on_message(inbound("hi", contact_id="4", display_name="Alice"))
|
||||
result = post(f"{base}/send", {"recipient": "Alice", "text": "hello"})
|
||||
assert result["contact_id"] == "4"
|
||||
assert daemon.sent == [("4", "hello")]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_reports_a_failed_send_not_a_false_success():
|
||||
# A dead connection: the daemon creates the item then marks it sndError.
|
||||
# The bridge must surface ok:false with the reason, never a false success.
|
||||
failed = {
|
||||
"type": "newChatItems",
|
||||
"chatItems": [
|
||||
{
|
||||
"chatItem": {
|
||||
"meta": {
|
||||
"itemId": 12,
|
||||
"itemStatus": {
|
||||
"type": "sndError",
|
||||
"agentError": {"type": "auth"},
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
}
|
||||
daemon = FakeDaemon(send_response=failed)
|
||||
bridge, _, base = start_bridge(daemon=daemon)
|
||||
try:
|
||||
result = post(f"{base}/send", {"recipient": "7", "text": "hey"})
|
||||
assert result["ok"] is False, result
|
||||
assert result["status"] == "sndError", result
|
||||
assert result["error"] == "auth", result
|
||||
assert result["contact_id"] == "7"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_verifies_status_via_history():
|
||||
# The daemon accepts the send (sndNew) and only later resolves it to a
|
||||
# delivered status; the bridge polls history to confirm.
|
||||
accepted = {
|
||||
"type": "newChatItems",
|
||||
"chatItems": [
|
||||
{"chatItem": {"meta": {"itemId": 5, "itemStatus": {"type": "sndNew"}}}}
|
||||
],
|
||||
}
|
||||
history = [
|
||||
{"item_id": "5", "text": "hi", "status": "sndRcvd", "unread": False,
|
||||
"direction": "directSnd", "sent_at": ""},
|
||||
]
|
||||
daemon = FakeDaemon(send_response=accepted, history=history)
|
||||
bridge, _, base = start_bridge(daemon=daemon)
|
||||
try:
|
||||
result = post(f"{base}/send", {"recipient": "7", "text": "hi"})
|
||||
assert result["ok"] is True, result
|
||||
assert result["status"] == "sndRcvd", result
|
||||
assert daemon.history_calls, "the bridge must poll for the real status"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_resolve_prefers_a_healthy_duplicate():
|
||||
# Two peers share the display name "pepper"; the stale one has auth errors.
|
||||
daemon = FakeDaemon(
|
||||
contacts=[
|
||||
{"id": "3", "display_name": "pepper", "local_name": "pepper",
|
||||
"connected": True, "auth_errors": 2},
|
||||
{"id": "4", "display_name": "pepper", "local_name": "pepper_1",
|
||||
"connected": True, "auth_errors": 0},
|
||||
]
|
||||
)
|
||||
bridge, _, _ = start_bridge(daemon=daemon)
|
||||
try:
|
||||
assert bridge.resolve("pepper") == "4", "a stale duplicate must lose"
|
||||
assert bridge.resolve("pepper_1") == "4"
|
||||
assert bridge.resolve("3") == "3", "an explicit id always wins"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_contacts_refreshed_from_daemon():
|
||||
# A contact the bridge has never received from must still be visible: the
|
||||
# daemon knows them, so /send can address them.
|
||||
daemon = FakeDaemon(contacts=[{"id": "42", "display_name": "Zed"}])
|
||||
bridge, _, base = start_bridge(daemon=daemon)
|
||||
try:
|
||||
assert get(f"{base}/contacts") == {
|
||||
"contacts": [{"id": "42", "display_name": "Zed"}]
|
||||
}
|
||||
assert daemon.refresh_count >= 1
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_resolves_daemon_only_contact():
|
||||
daemon = FakeDaemon(contacts=[{"id": "42", "display_name": "Zed"}])
|
||||
bridge, _, base = start_bridge(daemon=daemon)
|
||||
try:
|
||||
result = post(f"{base}/send", {"recipient": "Zed", "text": "hello"})
|
||||
assert result["ok"] is True and result["contact_id"] == "42", result
|
||||
assert daemon.sent == [("42", "hello")]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_refresh_on_connect_primes_contacts():
|
||||
daemon = FakeDaemon(contacts=[{"id": "42", "display_name": "Zed"}])
|
||||
bridge, _, base = start_bridge(daemon=daemon)
|
||||
try:
|
||||
asyncio.run(bridge._refresh_on_connect())
|
||||
assert get(f"{base}/contacts")["contacts"] == [
|
||||
{"id": "42", "display_name": "Zed"}
|
||||
]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_contacts_failure_keeps_cached_and_stays_available():
|
||||
bridge, _, base = start_bridge()
|
||||
try:
|
||||
bridge._on_message(inbound("hi", contact_id="4", display_name="Alice"))
|
||||
bridge.daemon.contacts_error = RuntimeError("not connected")
|
||||
assert get(f"{base}/contacts") == {
|
||||
"contacts": [{"id": "4", "display_name": "Alice"}]
|
||||
}
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_daemon_refresh_does_not_clobber_inbound_name():
|
||||
daemon = FakeDaemon(contacts=[{"id": "4", "display_name": ""}])
|
||||
bridge, _, base = start_bridge(daemon=daemon)
|
||||
try:
|
||||
bridge._on_message(inbound("hi", contact_id="4", display_name="Alice"))
|
||||
assert get(f"{base}/contacts") == {
|
||||
"contacts": [{"id": "4", "display_name": "Alice"}]
|
||||
}
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_rejects_unknown_recipient():
|
||||
bridge, daemon, 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 daemon.sent == [], "a rejected send must not enqueue anything"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_send_validates_body():
|
||||
bridge, daemon, 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 daemon.sent == []
|
||||
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()
|
||||
|
||||
|
||||
def test_address_returns_daemon_link():
|
||||
link = {"short_link": "simplex:/abc", "full_link": "https://x", "created": False}
|
||||
bridge, _, base = start_bridge(daemon=FakeDaemon(link=link))
|
||||
try:
|
||||
assert get(f"{base}/address") == link
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_address_without_connection_is_unavailable():
|
||||
bridge, _, base = start_bridge(
|
||||
daemon=FakeDaemon(error=RuntimeError("not connected"))
|
||||
)
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
get(f"{base}/address")
|
||||
assert exc.value.code == 503
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_address_lookup_failure_is_reported():
|
||||
bridge, _, base = start_bridge(daemon=FakeDaemon(error=TimeoutError("slow")))
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
get(f"{base}/address")
|
||||
assert exc.value.code == 502
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_stop_closes_the_daemon():
|
||||
bridge, daemon, _ = start_bridge()
|
||||
bridge.stop()
|
||||
assert daemon.closed is True
|
||||
|
||||
|
||||
# ---- daemon-backed unread / history ----
|
||||
|
||||
def chat_summary(contact_id="4", display_name="Alice", unread_count=2):
|
||||
return {
|
||||
"contact_id": contact_id,
|
||||
"display_name": display_name,
|
||||
"unread_count": unread_count,
|
||||
"min_unread_item_id": "10",
|
||||
"unread": True,
|
||||
"messages": [
|
||||
{
|
||||
"item_id": "10",
|
||||
"text": "hello there",
|
||||
"status": "rcvNew",
|
||||
"unread": True,
|
||||
"direction": "directRcv",
|
||||
"sent_at": "2026-01-01T00:00:00Z",
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_unread_returns_daemon_chats():
|
||||
daemon = FakeDaemon(chats=[chat_summary()])
|
||||
bridge, _, base = start_bridge(daemon=daemon)
|
||||
try:
|
||||
assert get(f"{base}/unread") == {"chats": [chat_summary()]}
|
||||
assert daemon.chat_calls == [(True, 20)], "must ask the daemon for unread"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_unread_attaches_cached_connection_health():
|
||||
daemon = FakeDaemon(chats=[chat_summary(contact_id="4", display_name="pepper")])
|
||||
bridge, _, base = start_bridge(daemon=daemon)
|
||||
try:
|
||||
bridge.inbox.merge_contacts(
|
||||
[
|
||||
{"id": "4", "display_name": "pepper", "local_name": "pepper_1",
|
||||
"connected": True, "auth_errors": 0},
|
||||
]
|
||||
)
|
||||
chats = get(f"{base}/unread")["chats"]
|
||||
assert chats[0]["connected"] is True
|
||||
assert chats[0]["auth_errors"] == 0
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_unread_honours_count_query():
|
||||
daemon = FakeDaemon(chats=[])
|
||||
bridge, _, base = start_bridge(daemon=daemon)
|
||||
try:
|
||||
get(f"{base}/unread?count=5")
|
||||
assert daemon.chat_calls == [(True, 5)]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_unread_without_connection_is_unavailable():
|
||||
bridge, _, base = start_bridge(daemon=FakeDaemon(chats_error=RuntimeError("not connected")))
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
get(f"{base}/unread")
|
||||
assert exc.value.code == 503
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_unread_lookup_failure_is_reported():
|
||||
bridge, _, base = start_bridge(daemon=FakeDaemon(chats_error=TimeoutError("slow")))
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
get(f"{base}/unread")
|
||||
assert exc.value.code == 502
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_history_returns_messages_for_contact():
|
||||
messages = [{"item_id": "11", "text": "hi", "status": "rcvRead", "unread": False,
|
||||
"direction": "directRcv", "sent_at": ""}]
|
||||
daemon = FakeDaemon(history=messages)
|
||||
bridge, _, base = start_bridge(daemon=daemon)
|
||||
try:
|
||||
assert get(f"{base}/history?contact=7") == {"contact_id": "7", "messages": messages}
|
||||
assert daemon.history_calls == [("7", 20)]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_history_requires_a_contact():
|
||||
bridge, daemon, base = start_bridge()
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
get(f"{base}/history")
|
||||
assert exc.value.code == 400
|
||||
assert daemon.history_calls == []
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_history_without_connection_is_unavailable():
|
||||
bridge, _, base = start_bridge(daemon=FakeDaemon(history_error=RuntimeError("not connected")))
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
get(f"{base}/history?contact=4")
|
||||
assert exc.value.code == 503
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_history_lookup_failure_is_reported():
|
||||
bridge, _, base = start_bridge(daemon=FakeDaemon(history_error=TimeoutError("slow")))
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
get(f"{base}/history?contact=4")
|
||||
assert exc.value.code == 502
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
# ---- LLM bridge ----
|
||||
|
||||
class FakeLLMClient:
|
||||
@@ -663,18 +126,9 @@ def test_llm_bridge_health_and_token():
|
||||
bridge.stop()
|
||||
|
||||
|
||||
|
||||
# ---- catalog / codegen surface ----
|
||||
|
||||
def test_known_infos_include_simplex():
|
||||
infos = {info.name: info for info in known_infos()}
|
||||
assert "simplex" in infos
|
||||
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_known_infos_include_llm():
|
||||
infos = {info.name: info for info in known_infos()}
|
||||
assert "llm" in infos
|
||||
@@ -729,85 +183,3 @@ def test_derived_config_vars_skip_unconfigured_bridges():
|
||||
assert derived["nextcloud_bridge_token"] == ""
|
||||
|
||||
|
||||
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 "/unread" in text
|
||||
assert "/history" in text
|
||||
assert "rather than reaching around it" in text
|
||||
|
||||
|
||||
def test_read_marks_given_items_only():
|
||||
daemon = FakeDaemon()
|
||||
bridge, _, base = start_bridge(daemon=daemon)
|
||||
try:
|
||||
result = post(f"{base}/read", {"contact": "4", "item_ids": ["8", "9"]})
|
||||
assert result == {
|
||||
"ok": True,
|
||||
"contact_id": "4",
|
||||
"item_ids": ["8", "9"],
|
||||
"status": "read",
|
||||
}
|
||||
assert daemon.read_calls == [("4", ["8", "9"])], "only the listed items"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_read_validates_body():
|
||||
bridge, daemon, base = start_bridge()
|
||||
try:
|
||||
payloads = (
|
||||
{"item_ids": ["8"]},
|
||||
{"contact": "4"},
|
||||
{"contact": "4", "item_ids": []},
|
||||
{"contact": " ", "item_ids": ["8"]},
|
||||
)
|
||||
for payload in payloads:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
post(f"{base}/read", payload)
|
||||
assert exc.value.code == 400
|
||||
assert daemon.read_calls == []
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_read_without_connection_is_unavailable():
|
||||
bridge, _, base = start_bridge(
|
||||
daemon=FakeDaemon(read_error=RuntimeError("not connected"))
|
||||
)
|
||||
try:
|
||||
result = post(f"{base}/read", {"contact": "4", "item_ids": ["8"]})
|
||||
assert result["ok"] is False
|
||||
assert result["status"] == "unavailable"
|
||||
assert "not connected" in result["error"]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_read_reports_a_rejected_read():
|
||||
bridge, _, base = start_bridge(
|
||||
daemon=FakeDaemon(read_response={"ok": False, "error": "agent error"})
|
||||
)
|
||||
try:
|
||||
result = post(f"{base}/read", {"contact": "4", "item_ids": ["8"]})
|
||||
assert result["ok"] is False
|
||||
assert result["status"] == "rejected"
|
||||
assert result["error"] == "agent error"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_inbox_carries_item_id_for_consumption():
|
||||
bridge, _, base = start_bridge()
|
||||
try:
|
||||
bridge._on_message(inbound("hi", contact_id="4", item_id="33"))
|
||||
popped = get(f"{base}/inbox/next")["message"]
|
||||
assert popped["item_id"] == "33"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
@@ -1,373 +0,0 @@
|
||||
"""Pure-stdlib tests for the browser (Playwright) bridge.
|
||||
|
||||
The bridge is exercised over a real loopback HTTP server with a fake driver
|
||||
standing in for the Playwright browser — the decision engine, the browser, and
|
||||
Playwright itself are never involved. These prove the mechanics a skill depends
|
||||
on: route wiring/validation, the token/auth surface, and the status mapping
|
||||
(400 bad input, 503 unavailable, 502 real failure). Passing these proves
|
||||
mechanics only; a real run against a real browser is the only proof the
|
||||
integration works.
|
||||
"""
|
||||
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import pytest
|
||||
|
||||
from semif_agent.bridges.browser import BrowserBridge
|
||||
from semif_agent.bridges.browser_client import (
|
||||
BrowserDriver,
|
||||
BrowserError,
|
||||
BrowserUnavailable,
|
||||
)
|
||||
from semif_agent.bridges.registry import (
|
||||
build_bridge,
|
||||
derived_config_vars,
|
||||
describe_bridges,
|
||||
known_infos,
|
||||
)
|
||||
|
||||
|
||||
class FakeDriver:
|
||||
"""Stands in for the Playwright browser, recording every call."""
|
||||
|
||||
def __init__(self, error=None, unavailable=None):
|
||||
self.error = error
|
||||
self.unavailable = unavailable
|
||||
self.calls = []
|
||||
self.closed = False
|
||||
|
||||
def _maybe_fail(self):
|
||||
if self.unavailable is not None:
|
||||
raise BrowserUnavailable(self.unavailable)
|
||||
if self.error is not None:
|
||||
raise BrowserError(self.error)
|
||||
|
||||
def state(self):
|
||||
self.calls.append(("state",))
|
||||
self._maybe_fail()
|
||||
return {"url": "https://example.com/", "title": "Example"}
|
||||
|
||||
def goto(self, url, wait_until="load", timeout=None):
|
||||
self.calls.append(("goto", url, wait_until, timeout))
|
||||
self._maybe_fail()
|
||||
return {"url": url, "title": "Example", "status": 200}
|
||||
|
||||
def content(self, fmt="text", max_chars=None):
|
||||
self.calls.append(("content", fmt, max_chars))
|
||||
self._maybe_fail()
|
||||
return {"url": "https://example.com/", "title": "Example", "format": fmt, "content": "hi", "truncated": False}
|
||||
|
||||
def text(self, selector):
|
||||
self.calls.append(("text", selector))
|
||||
self._maybe_fail()
|
||||
return {"url": "https://example.com/", "selector": selector, "count": 1, "matches": [{"text": "hi"}]}
|
||||
|
||||
def links(self, query="", limit=50):
|
||||
self.calls.append(("links", query, limit))
|
||||
self._maybe_fail()
|
||||
return {"url": "https://example.com/", "links": [{"text": "More", "href": "/more"}]}
|
||||
|
||||
def screenshot(self, full_page=False, selector="", inline=False):
|
||||
self.calls.append(("screenshot", full_page, selector, inline))
|
||||
self._maybe_fail()
|
||||
return {"ok": True, "path": "/tmp/shot.png", "bytes": 12, "url": "https://example.com/", "title": "Example"}
|
||||
|
||||
def click(self, selector="", text="", index=0, timeout=None):
|
||||
self.calls.append(("click", selector, text, index, timeout))
|
||||
self._maybe_fail()
|
||||
return {"url": "https://example.com/", "title": "Example"}
|
||||
|
||||
def fill(self, selector, value, submit=False, timeout=None):
|
||||
self.calls.append(("fill", selector, value, submit, timeout))
|
||||
self._maybe_fail()
|
||||
return {"url": "https://example.com/", "title": "Example"}
|
||||
|
||||
def press(self, key, selector="", timeout=None):
|
||||
self.calls.append(("press", key, selector, timeout))
|
||||
self._maybe_fail()
|
||||
return {"url": "https://example.com/", "title": "Example"}
|
||||
|
||||
def select(self, selector, value=None, label=None, timeout=None):
|
||||
self.calls.append(("select", selector, value, label, timeout))
|
||||
self._maybe_fail()
|
||||
return {"url": "https://example.com/", "title": "Example"}
|
||||
|
||||
def wait_for(self, selector="", text="", timeout=None):
|
||||
self.calls.append(("wait_for", selector, text, timeout))
|
||||
self._maybe_fail()
|
||||
return {"url": "https://example.com/", "title": "Example"}
|
||||
|
||||
def back(self, timeout=None):
|
||||
self.calls.append(("back", timeout))
|
||||
self._maybe_fail()
|
||||
return {"url": "https://example.com/", "title": "Example"}
|
||||
|
||||
def forward(self, timeout=None):
|
||||
self.calls.append(("forward", timeout))
|
||||
self._maybe_fail()
|
||||
return {"url": "https://example.com/", "title": "Example"}
|
||||
|
||||
def reset(self, purge=True):
|
||||
self.calls.append(("reset", purge))
|
||||
self._maybe_fail()
|
||||
return {"ok": True, "purged": bool(purge)}
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def start_bridge(driver=None, **config):
|
||||
driver = driver or FakeDriver()
|
||||
bridge = BrowserBridge(config, client=driver)
|
||||
port = bridge.start()
|
||||
return bridge, driver, f"http://127.0.0.1:{port}"
|
||||
|
||||
|
||||
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 http_error(url, payload=None, token=None):
|
||||
if payload is None:
|
||||
request = urllib.request.Request(url)
|
||||
else:
|
||||
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 pytest.raises(urllib.error.HTTPError) as exc:
|
||||
urllib.request.urlopen(request, timeout=5)
|
||||
return exc.value
|
||||
|
||||
|
||||
# ---- routes ----
|
||||
|
||||
def test_health_reports_engine_without_a_browser():
|
||||
bridge, _driver, base = start_bridge(headless=False, engine="firefox")
|
||||
try:
|
||||
assert get(f"{base}/health") == {
|
||||
"ok": True,
|
||||
"platform": "browser",
|
||||
"engine": "firefox",
|
||||
"headless": False,
|
||||
}
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_read_routes_wire_to_the_driver():
|
||||
bridge, driver, base = start_bridge()
|
||||
try:
|
||||
assert get(f"{base}/state") == {"url": "https://example.com/", "title": "Example"}
|
||||
assert get(f"{base}/content?format=html&max_chars=500")["content"] == "hi"
|
||||
assert get(f"{base}/text?selector=h1")["count"] == 1
|
||||
assert get(f"{base}/links?query=more&limit=5")["links"][0]["href"] == "/more"
|
||||
assert get(f"{base}/screenshot?full_page=true&inline=true")["path"] == "/tmp/shot.png"
|
||||
assert driver.calls == [
|
||||
("state",),
|
||||
("content", "html", 500),
|
||||
("text", "h1"),
|
||||
("links", "more", 5),
|
||||
("screenshot", True, "", True),
|
||||
]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_action_routes_wire_to_the_driver():
|
||||
bridge, driver, base = start_bridge()
|
||||
try:
|
||||
assert post(f"{base}/goto", {"url": "https://a.test/", "wait_until": "networkidle"})["status"] == 200
|
||||
post(f"{base}/click", {"text": "Sign in"})
|
||||
post(f"{base}/fill", {"selector": "#q", "value": "hi", "submit": True})
|
||||
post(f"{base}/press", {"key": "Enter"})
|
||||
post(f"{base}/select", {"selector": "select", "label": "Two"})
|
||||
post(f"{base}/wait", {"text": "Done", "timeout": 5})
|
||||
post(f"{base}/back", {})
|
||||
post(f"{base}/forward", {})
|
||||
post(f"{base}/reset", {"purge": False})
|
||||
assert driver.calls == [
|
||||
("goto", "https://a.test/", "networkidle", None),
|
||||
("click", "", "Sign in", 0, None),
|
||||
("fill", "#q", "hi", True, None),
|
||||
("press", "Enter", "", None),
|
||||
("select", "select", None, "Two", None),
|
||||
("wait_for", "", "Done", 5.0),
|
||||
("back", None),
|
||||
("forward", None),
|
||||
("reset", False),
|
||||
]
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_missing_url_is_400():
|
||||
bridge, driver, base = start_bridge()
|
||||
try:
|
||||
exc = http_error(f"{base}/goto", {})
|
||||
assert exc.code == 400
|
||||
assert driver.calls == [], "a rejected goto must not touch the browser"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_bad_wait_until_and_content_format_are_400():
|
||||
bridge, _driver, base = start_bridge()
|
||||
try:
|
||||
assert http_error(f"{base}/goto", {"url": "https://a.test", "wait_until": "whenever"}).code == 400
|
||||
assert http_error(f"{base}/content?format=pdf").code == 400
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_click_requires_selector_or_text():
|
||||
bridge, _driver, base = start_bridge()
|
||||
try:
|
||||
assert http_error(f"{base}/click", {}).code == 400
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_select_requires_value_or_label():
|
||||
bridge, _driver, base = start_bridge()
|
||||
try:
|
||||
assert http_error(f"{base}/select", {"selector": "s"}).code == 400
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_real_browser_failure_is_502():
|
||||
bridge, _driver, base = start_bridge(driver=FakeDriver(error="net::ERR_NAME_NOT_RESOLVED"))
|
||||
try:
|
||||
exc = http_error(f"{base}/goto", {"url": "https://nope.invalid"})
|
||||
assert exc.code == 502
|
||||
assert b"ERR_NAME_NOT_RESOLVED" in exc.read()
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_unavailable_browser_is_503_with_install_hint():
|
||||
driver = FakeDriver(unavailable="install the browser bridge stack")
|
||||
bridge, _driver, base = start_bridge(driver=driver)
|
||||
try:
|
||||
exc = http_error(f"{base}/state")
|
||||
assert exc.code == 503
|
||||
assert b"install the browser bridge stack" in exc.read()
|
||||
# /health still answers, so the bridge is diagnosable without a browser.
|
||||
assert get(f"{base}/health")["ok"] is True
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_unknown_route_is_404():
|
||||
bridge, _driver, base = start_bridge()
|
||||
try:
|
||||
assert http_error(f"{base}/nope").code == 404
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_token_guards_the_bridge():
|
||||
bridge, _driver, base = start_bridge(token="sekret")
|
||||
try:
|
||||
assert http_error(f"{base}/state", token=None).code == 401
|
||||
assert get(f"{base}/health", token="sekret")["platform"] == "browser"
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_stop_closes_the_driver():
|
||||
bridge, driver, _base = start_bridge()
|
||||
bridge.stop()
|
||||
assert driver.closed is True
|
||||
|
||||
|
||||
def test_check_requirements_never_blocks_startup():
|
||||
# An optional dependency must not take down the other bridges, so the check
|
||||
# is honest-but-permissive and a missing browser surfaces as a 503 on use.
|
||||
assert BrowserBridge({}).check_requirements() == (True, None)
|
||||
|
||||
|
||||
def test_bad_engine_falls_back_to_chromium():
|
||||
assert BrowserBridge({"engine": "netscape"}).engine == "chromium"
|
||||
assert BrowserBridge({"engine": "WebKit"}).engine == "webkit"
|
||||
|
||||
|
||||
def test_executable_path_and_channel_are_plumbed():
|
||||
bridge = BrowserBridge(
|
||||
{"channel": "chrome", "executable_path": "/usr/bin/google-chrome"}
|
||||
)
|
||||
assert bridge.channel == "chrome"
|
||||
assert bridge.executable_path == "/usr/bin/google-chrome"
|
||||
# The real driver (no injected double) carries them; executable_path wins at
|
||||
# launch, so the managed download is skipped entirely.
|
||||
assert bridge.client.channel == "chrome"
|
||||
assert bridge.client.executable_path == "/usr/bin/google-chrome"
|
||||
|
||||
|
||||
def test_driver_defaults_to_managed_browser():
|
||||
driver = BrowserDriver()
|
||||
assert driver.channel == ""
|
||||
assert driver.executable_path == ""
|
||||
|
||||
|
||||
# ---- driver dependency handling ----
|
||||
|
||||
def test_driver_unavailable_without_playwright(monkeypatch):
|
||||
import semif_agent.bridges.browser_client as browser_client
|
||||
|
||||
monkeypatch.setattr(browser_client.importlib.util, "find_spec", lambda name: None)
|
||||
driver = BrowserDriver()
|
||||
assert driver.configured is False
|
||||
with pytest.raises(BrowserUnavailable):
|
||||
driver.state()
|
||||
# No dangling loop/thread was started.
|
||||
driver.close()
|
||||
|
||||
|
||||
# ---- catalog / codegen surface ----
|
||||
|
||||
def test_known_infos_include_browser():
|
||||
infos = {info.name: info for info in known_infos()}
|
||||
assert "browser" in infos
|
||||
info = infos["browser"]
|
||||
assert info.service == "browser"
|
||||
assert info.url_config_var == "browser_bridge_url"
|
||||
assert info.auth_header == "X-Semif-Token"
|
||||
assert info.auth_config_var == "browser_bridge_token"
|
||||
assert any("/goto" in endpoint for endpoint in info.endpoints)
|
||||
|
||||
|
||||
def test_describe_bridges_covers_browser():
|
||||
text = describe_bridges()
|
||||
assert "browser_bridge_url" in text
|
||||
assert "/screenshot" in text
|
||||
assert "Playwright" in text
|
||||
|
||||
|
||||
def test_derived_config_vars_for_browser():
|
||||
config = {"bridges": {"browser": {"host": "127.0.0.1", "port": 5232, "token": "b"}}}
|
||||
derived = derived_config_vars(config)
|
||||
assert derived["browser_bridge_url"] == "http://127.0.0.1:5232"
|
||||
assert derived["browser_bridge_token"] == "b"
|
||||
|
||||
|
||||
def test_build_bridge_returns_browser():
|
||||
bridge = build_bridge({"bridges": {"browser": {"port": 5232}}}, "browser")
|
||||
assert isinstance(bridge, BrowserBridge)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,646 +0,0 @@
|
||||
"""Pure-stdlib tests for the Outlook (Microsoft Graph) bridge.
|
||||
|
||||
A loopback `http.server` plays Microsoft's token endpoint and Graph API so the
|
||||
bridge's own client is exercised over HTTP with no mocking of the transport. The
|
||||
decision engine and LLM are never involved. A few route tests inject a fake
|
||||
client to check wiring/validation without a server. Passing these proves
|
||||
mechanics only; a real run against the user's Microsoft account is the only proof
|
||||
the integration works.
|
||||
"""
|
||||
|
||||
import json
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import pytest
|
||||
|
||||
from semif_agent.bridges.outlook import OutlookBridge
|
||||
from semif_agent.bridges.outlook_client import (
|
||||
OutlookAuthRequired,
|
||||
OutlookClient,
|
||||
OutlookError,
|
||||
load_token,
|
||||
run_device_code_flow,
|
||||
save_token,
|
||||
)
|
||||
from semif_agent.bridges.registry import build_bridge, derived_config_vars, describe_bridges, known_infos
|
||||
|
||||
|
||||
class FakeGraph:
|
||||
"""A minimal but real Microsoft-shaped HTTP server (token + Graph)."""
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
self.refresh_calls = 0
|
||||
self.device_polls = 0
|
||||
self.token_status = 200
|
||||
self._server = None
|
||||
self._thread = None
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def start(self):
|
||||
fake = self
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def _read(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
return self.rfile.read(length) if length else b""
|
||||
|
||||
def _send(self, status, payload):
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _dispatch(self, method):
|
||||
body = self._read()
|
||||
fake.calls.append((method, self.path, dict(self.headers), body))
|
||||
status, payload = fake.handle(method, self.path, body)
|
||||
if status == 204:
|
||||
self.send_response(204)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
if isinstance(payload, bytes):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/octet-stream")
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
return
|
||||
self._send(status, payload)
|
||||
|
||||
def do_GET(self):
|
||||
self._dispatch("GET")
|
||||
|
||||
def do_POST(self):
|
||||
self._dispatch("POST")
|
||||
|
||||
def do_PUT(self):
|
||||
self._dispatch("PUT")
|
||||
|
||||
def do_PATCH(self):
|
||||
self._dispatch("PATCH")
|
||||
|
||||
def do_DELETE(self):
|
||||
self._dispatch("DELETE")
|
||||
|
||||
self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
|
||||
self._thread.start()
|
||||
return f"http://127.0.0.1:{self._server.server_address[1]}"
|
||||
|
||||
def stop(self):
|
||||
if self._server is not None:
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
self._server = None
|
||||
|
||||
# ---- routing ----
|
||||
|
||||
def handle(self, method, path, body):
|
||||
parsed = urlparse(path)
|
||||
route = parsed.path
|
||||
query = parse_qs(parsed.query)
|
||||
|
||||
# ---- OAuth token endpoint ----
|
||||
if route.endswith("/oauth2/v2.0/devicecode"):
|
||||
return 200, {
|
||||
"device_code": "dev-code",
|
||||
"user_code": "ABCD-EFGH",
|
||||
"verification_uri": "https://microsoft.com/devicelogin",
|
||||
"interval": 1,
|
||||
"expires_in": 900,
|
||||
"message": "go to https://microsoft.com/devicelogin and enter ABCD-EFGH",
|
||||
}
|
||||
if route.endswith("/oauth2/v2.0/token"):
|
||||
fields = parse_qs(body.decode("utf-8"))
|
||||
grant = (fields.get("grant_type") or [""])[0]
|
||||
if grant == "refresh_token":
|
||||
self.refresh_calls += 1
|
||||
return self.token_status, {
|
||||
"access_token": f"refreshed-{self.refresh_calls}",
|
||||
"refresh_token": f"rotated-{self.refresh_calls}",
|
||||
"expires_in": 3600,
|
||||
"token_type": "Bearer",
|
||||
"scope": "Mail.ReadWrite",
|
||||
}
|
||||
# device-code poll: pending once, then success
|
||||
self.device_polls += 1
|
||||
if self.device_polls < 2:
|
||||
return 400, {"error": "authorization_pending"}
|
||||
return 200, {
|
||||
"access_token": "device-access",
|
||||
"refresh_token": "device-refresh",
|
||||
"expires_in": 3600,
|
||||
"token_type": "Bearer",
|
||||
"scope": "Mail.ReadWrite",
|
||||
}
|
||||
|
||||
# ---- Graph ----
|
||||
if method == "GET" and route == "/v1.0/me":
|
||||
return 200, {
|
||||
"id": "user-1",
|
||||
"displayName": "Jane Doe",
|
||||
"mail": "jane@example.com",
|
||||
"userPrincipalName": "jane@example.com",
|
||||
}
|
||||
if method == "GET" and route == "/v1.0/me/mailFolders":
|
||||
return 200, {
|
||||
"value": [
|
||||
{"id": "inbox", "displayName": "Inbox", "totalItemCount": 3, "unreadItemCount": 1}
|
||||
]
|
||||
}
|
||||
if method == "GET" and route == "/v1.0/me/mailFolders/inbox/messages":
|
||||
return 200, {
|
||||
"value": [
|
||||
{
|
||||
"id": "m1",
|
||||
"subject": "Hello",
|
||||
"from": {"emailAddress": {"name": "Alice", "address": "alice@example.com"}},
|
||||
"toRecipients": [{"emailAddress": {"address": "jane@example.com"}}],
|
||||
"ccRecipients": [],
|
||||
"receivedDateTime": "2026-10-08T09:00:00Z",
|
||||
"isRead": False,
|
||||
"hasAttachments": False,
|
||||
"bodyPreview": "Hi there",
|
||||
"importance": "normal",
|
||||
"webLink": "https://outlook/m1",
|
||||
}
|
||||
]
|
||||
}
|
||||
if method == "GET" and route == "/v1.0/me/messages/m1":
|
||||
return 200, {
|
||||
"id": "m1",
|
||||
"subject": "Hello",
|
||||
"from": {"emailAddress": {"name": "Alice", "address": "alice@example.com"}},
|
||||
"toRecipients": [{"emailAddress": {"address": "jane@example.com"}}],
|
||||
"ccRecipients": [],
|
||||
"receivedDateTime": "2026-10-08T09:00:00Z",
|
||||
"isRead": False,
|
||||
"hasAttachments": False,
|
||||
"body": {"contentType": "text", "content": "Hi there"},
|
||||
"bodyPreview": "Hi there",
|
||||
"importance": "normal",
|
||||
"webLink": "https://outlook/m1",
|
||||
}
|
||||
if method == "POST" and route == "/v1.0/me/sendMail":
|
||||
self.sent = json.loads(body.decode("utf-8"))
|
||||
return 202, {}
|
||||
if method == "POST" and route == "/v1.0/me/messages":
|
||||
payload = json.loads(body.decode("utf-8"))
|
||||
return 201, {"id": "draft-1", "subject": payload.get("subject", "")}
|
||||
if method == "GET" and route == "/v1.0/me/calendars":
|
||||
return 200, {
|
||||
"value": [
|
||||
{"id": "cal1", "name": "Calendar", "color": "auto", "isDefaultCalendar": True, "canEdit": True}
|
||||
]
|
||||
}
|
||||
if method == "GET" and route == "/v1.0/me/calendarView":
|
||||
return 200, {
|
||||
"value": [
|
||||
{
|
||||
"id": "e1",
|
||||
"subject": "Standup",
|
||||
"start": {"dateTime": "2026-10-08T09:00:00.0000000", "timeZone": "UTC"},
|
||||
"end": {"dateTime": "2026-10-08T09:30:00.0000000", "timeZone": "UTC"},
|
||||
"isAllDay": False,
|
||||
"location": {"displayName": "Room 1"},
|
||||
"bodyPreview": "",
|
||||
"showAs": "busy",
|
||||
"isOnlineMeeting": False,
|
||||
"webLink": "https://outlook/e1",
|
||||
"organizer": {"emailAddress": {"address": "jane@example.com"}},
|
||||
}
|
||||
]
|
||||
}
|
||||
if method == "POST" and route == "/v1.0/me/events":
|
||||
payload = json.loads(body.decode("utf-8"))
|
||||
return 201, {
|
||||
"id": "new-event",
|
||||
"subject": payload.get("subject"),
|
||||
"webLink": "https://outlook/new-event",
|
||||
}
|
||||
if method == "PATCH" and route.startswith("/v1.0/me/events/"):
|
||||
payload = json.loads(body.decode("utf-8"))
|
||||
return 200, {"id": route.rsplit("/", 1)[-1], "subject": payload.get("subject", "")}
|
||||
if method == "DELETE" and route.startswith("/v1.0/me/events/"):
|
||||
return 204, {}
|
||||
if method == "GET" and route == "/v1.0/me/todo/lists":
|
||||
return 200, {
|
||||
"value": [
|
||||
{"id": "list1", "displayName": "Tasks", "isOwner": True, "wellknownListName": "defaultList"}
|
||||
]
|
||||
}
|
||||
if method == "GET" and route == "/v1.0/me/todo/lists/list1/tasks":
|
||||
return 200, {
|
||||
"value": [
|
||||
{
|
||||
"id": "t1",
|
||||
"title": "Buy milk",
|
||||
"status": "notStarted",
|
||||
"importance": "normal",
|
||||
"dueDateTime": {"dateTime": "2026-10-10T00:00:00", "timeZone": "UTC"},
|
||||
"completedDateTime": {},
|
||||
"body": {"content": ""},
|
||||
}
|
||||
]
|
||||
}
|
||||
if method == "POST" and route == "/v1.0/me/todo/lists/list1/tasks":
|
||||
payload = json.loads(body.decode("utf-8"))
|
||||
return 201, {"id": "t2", "title": payload.get("title")}
|
||||
if method == "PATCH" and route.startswith("/v1.0/me/todo/lists/list1/tasks/"):
|
||||
payload = json.loads(body.decode("utf-8"))
|
||||
return 200, {"id": route.rsplit("/", 1)[-1], "status": payload.get("status", "notStarted")}
|
||||
if method == "DELETE" and route.startswith("/v1.0/me/todo/lists/list1/tasks/"):
|
||||
return 204, {}
|
||||
if method == "GET" and route == "/v1.0/me/contacts":
|
||||
return 200, {
|
||||
"value": [
|
||||
{
|
||||
"id": "c1",
|
||||
"displayName": "Bob Smith",
|
||||
"givenName": "Bob",
|
||||
"surname": "Smith",
|
||||
"emailAddresses": [{"address": "bob@example.com"}],
|
||||
"businessPhones": ["555-1234"],
|
||||
"homePhones": [],
|
||||
"mobilePhone": None,
|
||||
"companyName": "Acme",
|
||||
"jobTitle": "Dev",
|
||||
}
|
||||
]
|
||||
}
|
||||
if method == "GET" and route == "/v1.0/me/drive/root/children":
|
||||
return 200, {
|
||||
"value": [
|
||||
{
|
||||
"id": "f1",
|
||||
"name": "notes.txt",
|
||||
"size": 5,
|
||||
"lastModifiedDateTime": "2026-10-08T08:00:00Z",
|
||||
"file": {"mimeType": "text/plain"},
|
||||
"parentReference": {"path": "/drive/root:"},
|
||||
"webUrl": "https://onedrive/f1",
|
||||
}
|
||||
]
|
||||
}
|
||||
if route.startswith("/v1.0/me/drive/root:/") and route.endswith(":"):
|
||||
return 200, {
|
||||
"id": "f1",
|
||||
"name": "notes.txt",
|
||||
"size": 5,
|
||||
"file": {"mimeType": "text/plain"},
|
||||
"lastModifiedDateTime": "2026-10-08T08:00:00Z",
|
||||
"webUrl": "https://onedrive/f1",
|
||||
}
|
||||
if route.startswith("/v1.0/me/drive/root:/") and route.endswith("/content"):
|
||||
if method == "GET":
|
||||
return 200, b"hello"
|
||||
return 201, {"id": "f2", "size": 5, "webUrl": "https://onedrive/f2"}
|
||||
|
||||
return 404, {"error": {"code": "notFound", "message": f"no fake route for {method} {route}"}}
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def fake():
|
||||
server = FakeGraph()
|
||||
base = server.start()
|
||||
try:
|
||||
yield server, base
|
||||
finally:
|
||||
server.stop()
|
||||
|
||||
|
||||
def make_client(fake, tmp_path, *, token="tok", expires_at=None, refresh="r1", graph_suffix="/v1.0"):
|
||||
server, base = fake
|
||||
token_path = tmp_path / "token.json"
|
||||
if token is not None:
|
||||
save_token(
|
||||
str(token_path),
|
||||
{
|
||||
"access_token": token,
|
||||
"refresh_token": refresh,
|
||||
"expires_at": 9999999999 if expires_at is None else expires_at,
|
||||
"token_type": "Bearer",
|
||||
},
|
||||
)
|
||||
return OutlookClient(
|
||||
"client-1",
|
||||
tenant="common",
|
||||
token_path=str(token_path),
|
||||
graph=base + graph_suffix,
|
||||
login=base,
|
||||
)
|
||||
|
||||
|
||||
# ---- OAuth ----
|
||||
|
||||
def test_device_code_flow_polls_until_success(fake):
|
||||
server, base = fake
|
||||
lines = []
|
||||
token = run_device_code_flow(
|
||||
"client-1", "common", out=lines.append, sleep=lambda _s: None, login=base
|
||||
)
|
||||
assert token["access_token"] == "device-access"
|
||||
assert token["refresh_token"] == "device-refresh"
|
||||
assert any("ABCD-EFGH" in line for line in lines)
|
||||
assert server.device_polls == 2
|
||||
|
||||
|
||||
def test_token_refresh_on_expiry(fake, tmp_path):
|
||||
server, base = fake
|
||||
client = make_client(fake, tmp_path, token="stale", expires_at=0)
|
||||
user = client.me()
|
||||
assert user["display_name"] == "Jane Doe"
|
||||
assert server.refresh_calls == 1
|
||||
stored = load_token(str(tmp_path / "token.json"))
|
||||
assert stored["access_token"] == "refreshed-1"
|
||||
assert stored["refresh_token"] == "rotated-1"
|
||||
|
||||
|
||||
def test_missing_token_raises_auth_required(tmp_path):
|
||||
client = OutlookClient(
|
||||
"client-1", token_path=str(tmp_path / "missing.json"), graph="http://127.0.0.1:1/v1.0"
|
||||
)
|
||||
with pytest.raises(OutlookAuthRequired):
|
||||
client.me()
|
||||
|
||||
|
||||
def test_not_configured_without_client_id(tmp_path):
|
||||
client = OutlookClient("", token_path=str(tmp_path / "t.json"))
|
||||
assert client.configured is False
|
||||
|
||||
|
||||
# ---- Graph client ----
|
||||
|
||||
def test_me_and_mail(fake, tmp_path):
|
||||
client = make_client(fake, tmp_path)
|
||||
assert client.me()["mail"] == "jane@example.com"
|
||||
folders = client.list_mail_folders()
|
||||
assert folders[0]["name"] == "Inbox"
|
||||
messages = client.list_messages("inbox")
|
||||
assert messages[0]["subject"] == "Hello"
|
||||
assert messages[0]["from"] == "Alice <alice@example.com>"
|
||||
assert messages[0]["to"] == ["jane@example.com"]
|
||||
full = client.get_message("m1")
|
||||
assert full["body"] == "Hi there"
|
||||
assert full["body_type"] == "text"
|
||||
|
||||
|
||||
def test_send_mail(fake, tmp_path):
|
||||
server, _base = fake
|
||||
client = make_client(fake, tmp_path)
|
||||
result = client.send_mail(["sam@example.com"], "Lunch", "Tomorrow?", cc=["bob@example.com"])
|
||||
assert result["ok"] is True
|
||||
sent = server.sent
|
||||
assert sent["message"]["subject"] == "Lunch"
|
||||
assert sent["message"]["toRecipients"][0]["emailAddress"]["address"] == "sam@example.com"
|
||||
assert sent["message"]["ccRecipients"][0]["emailAddress"]["address"] == "bob@example.com"
|
||||
assert sent["saveToSentItems"] is True
|
||||
|
||||
|
||||
def test_create_draft(fake, tmp_path):
|
||||
client = make_client(fake, tmp_path)
|
||||
result = client.create_draft(["sam@example.com"], "Draft", "body")
|
||||
assert result["id"] == "draft-1"
|
||||
assert result["subject"] == "Draft"
|
||||
|
||||
|
||||
def test_list_events(fake, tmp_path):
|
||||
client = make_client(fake, tmp_path)
|
||||
events = client.list_events()
|
||||
assert events[0]["subject"] == "Standup"
|
||||
assert events[0]["start"] == "2026-10-08T09:00:00.0000000"
|
||||
assert events[0]["location"] == "Room 1"
|
||||
assert events[0]["organizer"] == "jane@example.com"
|
||||
|
||||
|
||||
def test_create_event_builds_graph_body(fake, tmp_path):
|
||||
server, _base = fake
|
||||
client = make_client(fake, tmp_path)
|
||||
result = client.create_event(
|
||||
subject="Dentist",
|
||||
start="2026-11-10T14:00:00",
|
||||
all_day=False,
|
||||
location="Clinic",
|
||||
timezone_name="America/Chicago",
|
||||
)
|
||||
assert result["ok"] is True
|
||||
assert result["id"] == "new-event"
|
||||
call = next(c for c in server.calls if c[0] == "POST" and c[1] == "/v1.0/me/events")
|
||||
body = json.loads(call[3].decode("utf-8"))
|
||||
assert body["subject"] == "Dentist"
|
||||
assert body["start"] == {"dateTime": "2026-11-10T14:00:00", "timeZone": "America/Chicago"}
|
||||
# end defaults to one hour after start
|
||||
assert body["end"]["dateTime"] == "2026-11-10T15:00:00"
|
||||
assert body["isAllDay"] is False
|
||||
assert body["location"] == {"displayName": "Clinic"}
|
||||
|
||||
|
||||
def test_create_event_all_day_defaults_end_next_day(fake, tmp_path):
|
||||
server, _base = fake
|
||||
client = make_client(fake, tmp_path)
|
||||
client.create_event(subject="Conference", start="2026-11-10T00:00:00", all_day=True)
|
||||
call = next(c for c in server.calls if c[0] == "POST" and c[1] == "/v1.0/me/events")
|
||||
body = json.loads(call[3].decode("utf-8"))
|
||||
assert body["isAllDay"] is True
|
||||
assert body["end"]["dateTime"].startswith("2026-11-11")
|
||||
|
||||
|
||||
def test_tasks_flow(fake, tmp_path):
|
||||
client = make_client(fake, tmp_path)
|
||||
lists = client.list_task_lists()
|
||||
assert lists[0]["is_default"] is True
|
||||
tasks = client.list_tasks()
|
||||
assert tasks[0]["title"] == "Buy milk"
|
||||
created = client.create_task(title="Call mom", due="2026-10-12T09:00:00")
|
||||
assert created["id"] == "t2"
|
||||
completed = client.complete_task("t1")
|
||||
assert completed["status"] == "completed"
|
||||
|
||||
|
||||
def test_contacts(fake, tmp_path):
|
||||
client = make_client(fake, tmp_path)
|
||||
contacts = client.list_contacts("bob")
|
||||
assert contacts[0]["display_name"] == "Bob Smith"
|
||||
assert contacts[0]["emails"] == ["bob@example.com"]
|
||||
assert "555-1234" in contacts[0]["phones"]
|
||||
|
||||
|
||||
def test_files_read_and_write(fake, tmp_path):
|
||||
client = make_client(fake, tmp_path)
|
||||
entries = client.list_files("/")
|
||||
assert entries[0]["name"] == "notes.txt"
|
||||
read = client.read_file("notes.txt")
|
||||
assert read["content"] == "hello"
|
||||
assert read["encoding"] == "utf-8"
|
||||
written = client.write_file("notes.txt", "hello", overwrite=True)
|
||||
assert written["ok"] is True
|
||||
assert written["path"] == "notes.txt"
|
||||
|
||||
|
||||
def test_unreachable_graph_is_an_outlook_error(tmp_path):
|
||||
client = OutlookClient(
|
||||
"client-1", token_path=str(tmp_path / "t.json"), graph="http://127.0.0.1:1/v1.0"
|
||||
)
|
||||
save_token(str(tmp_path / "t.json"), {"access_token": "x", "refresh_token": "r", "expires_at": 9999999999})
|
||||
with pytest.raises(OutlookError):
|
||||
client.me()
|
||||
|
||||
|
||||
# ---- bridge routes ----
|
||||
|
||||
class StubClient:
|
||||
configured = True
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def me(self):
|
||||
return {"display_name": "Jane"}
|
||||
|
||||
def list_mail_folders(self):
|
||||
return [{"id": "inbox", "name": "Inbox"}]
|
||||
|
||||
def list_messages(self, folder="", count=25, search="", unread_only=False):
|
||||
self.calls.append(("list_messages", folder, count, search, unread_only))
|
||||
return [{"id": "m1", "subject": "Hello"}]
|
||||
|
||||
def get_message(self, message_id):
|
||||
return {"id": message_id, "body": "hi"}
|
||||
|
||||
def send_mail(self, to, subject, body, cc=(), content_type="text", save_to_sent=True):
|
||||
self.calls.append(("send_mail", to, subject, body, cc))
|
||||
return {"ok": True, "to": to}
|
||||
|
||||
def create_event(self, **kwargs):
|
||||
self.calls.append(("create_event", kwargs))
|
||||
return {"ok": True, "id": "e1"}
|
||||
|
||||
def list_events(self, calendar="", start="", end=""):
|
||||
return [{"id": "e1", "subject": "Standup"}]
|
||||
|
||||
def create_task(self, **kwargs):
|
||||
self.calls.append(("create_task", kwargs))
|
||||
return {"ok": True, "id": "t1"}
|
||||
|
||||
def list_files(self, path="/"):
|
||||
return [{"name": "notes.txt"}]
|
||||
|
||||
def write_file(self, path, content, encoding="utf-8", overwrite=True):
|
||||
return {"ok": True, "path": path}
|
||||
|
||||
def list_calendars(self):
|
||||
return []
|
||||
|
||||
def list_task_lists(self):
|
||||
return []
|
||||
|
||||
def list_tasks(self, task_list=""):
|
||||
return []
|
||||
|
||||
def list_contacts(self, query="", count=50):
|
||||
return []
|
||||
|
||||
|
||||
def test_bridge_routes_wire_to_client():
|
||||
stub = StubClient()
|
||||
bridge = OutlookBridge({"client_id": "c", "token_path": "/tmp/x"}, client=stub)
|
||||
assert bridge.handle_get("/health", {}) == (200, {"ok": True, "platform": "outlook"})
|
||||
status, payload = bridge.handle_get("/mail/messages", {"folder": ["inbox"], "count": ["10"]})
|
||||
assert status == 200 and payload["messages"][0]["subject"] == "Hello"
|
||||
assert stub.calls[-1] == ("list_messages", "inbox", 10, "", False)
|
||||
status, payload = bridge.handle_post(
|
||||
"/mail/send", {"to": ["sam@example.com"], "subject": "Hi", "body": "there"}
|
||||
)
|
||||
assert status == 200 and payload["ok"] is True
|
||||
assert stub.calls[-1] == ("send_mail", ["sam@example.com"], "Hi", "there", [])
|
||||
status, _payload = bridge.handle_post("/calendars/events", {"subject": "Standup", "start": "2026-01-01T09:00:00"})
|
||||
assert status == 200
|
||||
assert stub.calls[-1][0] == "create_event"
|
||||
|
||||
|
||||
def test_bridge_validation_errors():
|
||||
bridge = OutlookBridge({"client_id": "c"}, client=StubClient())
|
||||
status, payload = bridge.handle_post("/calendars/events", {"start": "2026-01-01T09:00:00"})
|
||||
assert status == 400 and "subject" in payload["error"]
|
||||
status, payload = bridge.handle_post("/mail/send", {"subject": "no recipient"})
|
||||
assert status == 400 and "to" in payload["error"]
|
||||
status, _ = bridge.handle_post("/nope", {})
|
||||
assert status == 404
|
||||
|
||||
|
||||
def test_bridge_unconfigured_is_503():
|
||||
bridge = OutlookBridge({}, client=StubClient())
|
||||
bridge.client = type("C", (), {"configured": False})()
|
||||
assert bridge.handle_get("/mail/messages", {})[0] == 503
|
||||
assert bridge.handle_post("/mail/send", {"to": ["a@b.c"]})[0] == 503
|
||||
|
||||
|
||||
def test_bridge_auth_required_is_503():
|
||||
class Unauthorized:
|
||||
configured = True
|
||||
|
||||
def list_messages(self, *args, **kwargs):
|
||||
raise OutlookAuthRequired("run packs/outlook/scripts/outlook-auth.py")
|
||||
|
||||
bridge = OutlookBridge({"client_id": "c"}, client=Unauthorized())
|
||||
status, payload = bridge.handle_get("/mail/messages", {})
|
||||
assert status == 503
|
||||
assert "outlook-auth" in payload["error"]
|
||||
|
||||
|
||||
def test_bridge_maps_real_failure_to_502():
|
||||
class Broken:
|
||||
configured = True
|
||||
|
||||
def list_messages(self, *args, **kwargs):
|
||||
raise OutlookError("boom")
|
||||
|
||||
bridge = OutlookBridge({"client_id": "c"}, client=Broken())
|
||||
assert bridge.handle_get("/mail/messages", {})[0] == 502
|
||||
|
||||
|
||||
def test_check_requirements_is_stdlib_only():
|
||||
assert OutlookBridge({}).check_requirements() == (True, None)
|
||||
|
||||
|
||||
# ---- catalog ----
|
||||
|
||||
def test_known_infos_include_outlook():
|
||||
infos = {info.name: info for info in known_infos()}
|
||||
assert "outlook" in infos
|
||||
info = infos["outlook"]
|
||||
assert info.service == "outlook"
|
||||
assert info.url_config_var == "outlook_bridge_url"
|
||||
assert info.auth_header == "X-Semif-Token"
|
||||
assert info.auth_config_var == "outlook_bridge_token"
|
||||
|
||||
|
||||
def test_describe_bridges_covers_outlook():
|
||||
text = describe_bridges()
|
||||
assert "outlook" in text
|
||||
assert "outlook_bridge_url" in text
|
||||
assert "Microsoft To Do" in text
|
||||
|
||||
|
||||
def test_derived_config_vars_for_outlook():
|
||||
derived = derived_config_vars(
|
||||
{"bridges": {"outlook": {"host": "127.0.0.1", "port": 5231, "token": "o"}}}
|
||||
)
|
||||
assert derived["outlook_bridge_url"] == "http://127.0.0.1:5231"
|
||||
assert derived["outlook_bridge_token"] == "o"
|
||||
|
||||
|
||||
def test_build_bridge_returns_outlook():
|
||||
bridge = build_bridge({"bridges": {"outlook": {"client_id": "c"}}}, "outlook")
|
||||
assert isinstance(bridge, OutlookBridge)
|
||||
assert bridge.client_id == "c"
|
||||
@@ -10,6 +10,8 @@ user's service is (see AGENTS.md).
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -29,6 +31,7 @@ from semif_agent.packs import (
|
||||
|
||||
PACKS = Path(__file__).resolve().parent.parent / "packs"
|
||||
SKILL_DIRS = sorted(path.parent for path in PACKS.glob("*/skills/*/*/skill.py"))
|
||||
BRIDGE_TESTS = sorted(PACKS.glob("*/bridge/test_*.py"))
|
||||
|
||||
|
||||
def seed_id(seed: Path) -> str:
|
||||
@@ -152,3 +155,31 @@ def test_seed_hermetic_test_passes(seed, monkeypatch):
|
||||
monkeypatch.setenv("PYTHONPATH", root + os.pathsep + existing)
|
||||
passed, output = run_skill_test(seed, timeout=30)
|
||||
assert passed, output
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"test_file", BRIDGE_TESTS, ids=[f"{p.parent.parent.name}/{p.name}" for p in BRIDGE_TESTS]
|
||||
)
|
||||
def test_pack_bridge_test_passes(test_file):
|
||||
"""A bridge ships with its pack; its hermetic test runs from the pack.
|
||||
|
||||
The bridge tests are pytest modules (they use fixtures and `pytest.raises`),
|
||||
so they run in a subprocess with the checkout on `PYTHONPATH` — the same
|
||||
import path a real run uses. A pack that declares a bridge but ships no test
|
||||
is a hole; this parametrization picks up exactly the tests that exist, and
|
||||
`test_pack_manifests_are_valid` keeps the packs present.
|
||||
"""
|
||||
root = str(PACKS.parent)
|
||||
env = {
|
||||
**os.environ,
|
||||
"PYTHONPATH": root + os.pathsep + os.environ.get("PYTHONPATH", ""),
|
||||
}
|
||||
proc = subprocess.run(
|
||||
[sys.executable, "-m", "pytest", str(test_file), "-q", "-p", "no:cacheprovider"],
|
||||
cwd=root,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=300,
|
||||
env=env,
|
||||
)
|
||||
assert proc.returncode == 0, (proc.stdout or "") + (proc.stderr or "")
|
||||
Reference in new issue
Block a user