Compare commits
3
Commits
dff4849947
...
228886f7cd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
228886f7cd | ||
|
|
d9cc7e4fed | ||
|
|
e64354e78d |
No files matched your search
@@ -243,8 +243,8 @@ 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 first, plus the
|
||||
LLM bridge). base.py:
|
||||
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,
|
||||
@@ -257,6 +257,12 @@ bridges/ standalone third-party API bridges (SimpleX first, plus 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 calendar seeds use.
|
||||
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
|
||||
@@ -728,9 +734,9 @@ CLI, unit tests (24) + integration tests (2).
|
||||
`codegen.timeout: 3600`, the SimpleX gateway enabled
|
||||
(`gateway.simplex.enabled = true`, `ws_url` from `simplex_chat.port`) and the
|
||||
standalone forwarding bridge enabled (`bridges.simplex.enabled = true`,
|
||||
`ws_url` from `simplex_chat.forward_port`, top-level `simplex_bridge_url`) and
|
||||
the LLM bridge enabled (`bridges.llm.enabled = true`, top-level
|
||||
`llm_bridge_url`; it reuses the `llm` model);
|
||||
`ws_url` from `simplex_chat.forward_port`) and
|
||||
the LLM bridge enabled (`bridges.llm.enabled = true`; it reuses the `llm`
|
||||
model);
|
||||
the operator sets `llm.model`/`llm.base_url` and `codegen.model`/
|
||||
`codegen.base_url`. Bootstrap renders/enables four user services:
|
||||
`semif-simplex.service` (the command `simplex-chat` bot daemon,
|
||||
@@ -1267,9 +1273,13 @@ CLI, unit tests (24) + integration tests (2).
|
||||
(surviving bridge restarts), unlike the live `/inbox` buffer; both are
|
||||
read-only because v7 has no mark-read command (acking is a client-side read
|
||||
receipt).
|
||||
- **Skill-facing config.** The top-level `simplex_bridge_url` is the address a
|
||||
body calls (the data-contract config search auto-populates it); bootstrap keeps
|
||||
it in sync with the bridge port. Skills reach a bridge with the ordinary `http`
|
||||
- **Skill-facing config.** A body calls a bridge at the address derived from that
|
||||
bridge's own `bridges.<name>` block (`host`/`port`/`token`) — the
|
||||
`simplex_bridge_url` / `llm_bridge_url` / `nextcloud_bridge_url` var (+ `_token`)
|
||||
is injected into `ctx.config` by `build_scheduler` via
|
||||
`bridges.registry.derived_config_vars`, so there is no duplicate top-level key to
|
||||
keep in sync and the data-contract config search finds it and auto-populates the
|
||||
skill config. Skills reach a bridge with the ordinary `http`
|
||||
transport, so their hermetic tests are loopback HTTP like any other HTTP body.
|
||||
`simplex.next_message` and `simplex.connect_link` are the seeds.
|
||||
- **LLM bridge** (`bridges/llm.py`). A generic `POST /chat`
|
||||
@@ -1281,12 +1291,41 @@ CLI, unit tests (24) + integration tests (2).
|
||||
scheduler's already-configured `llm` client through `run_bridges`/`build_bridge`
|
||||
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 top-level
|
||||
(`enabled`/`host`/`port`/`token`). Bodies reach it via the derived
|
||||
`llm_bridge_url` (+ optional `llm_bridge_token`). It runs inside the existing
|
||||
`semif-bridge.service` process (all enabled bridges start together); with no
|
||||
client it reports `502`, never a fabricated reply. `calendar.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`).
|
||||
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
|
||||
daemon** (Nextcloud is plain HTTPS) and is stdlib-only (`urllib` + `xml.etree`
|
||||
+ `ssl`), so `check_requirements` is always `(True, None)` and it starts
|
||||
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
|
||||
`nextcloud_url`/`nextcloud_username`/`nextcloud_app_password`/
|
||||
`nextcloud_default_calendar`/`nextcloud_default_addressbook` as a fallback, so
|
||||
the same account the calendar seeds collect is configured once and a block value
|
||||
wins. Bodies reach it via the derived `nextcloud_bridge_url` (+ optional
|
||||
`nextcloud_bridge_token`); the `BridgeInfo` declares only those two config vars.
|
||||
Routes (reads `GET`, mutations `POST`): files (`/files`, `/files/stat`,
|
||||
`/files/read` text-or-base64, `/files/search`, `/files/write|mkdir|delete|move|copy`),
|
||||
calendars (`/calendars`, `/calendars/events` list, `POST /calendars/events` +
|
||||
`/update` + `/delete`), tasks (`/tasks` list, `POST /tasks` + `/update` +
|
||||
`/complete` + `/delete`), contacts (`/addressbooks`, `/contacts` list/search,
|
||||
`POST /contacts` + `/update` + `/delete`), notes (`/notes`, `/notes/get`,
|
||||
`POST /notes` + `/update` + `/delete`), and `/user` + `/capabilities` (OCS).
|
||||
A missing connection is `503`; a real failure (`NextcloudError` — transport,
|
||||
HTTP error, or bad reply) is `502`, never a fabricated success. Event/task
|
||||
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.
|
||||
|
||||
## Bridge backlog (one session per item)
|
||||
|
||||
@@ -1322,11 +1361,14 @@ The bridge read path (`simplex.next_message`) and contact-link lookup
|
||||
- [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` + top-level `llm_bridge_url`.
|
||||
in `CATALOG` and seeded under `bridges.llm` (its URL is derived from that block).
|
||||
`calendar.create_event` extracts its title + description through it.
|
||||
- [ ] **5. More bridges.** Each new third-party API gets its own `bridges/<name>.py`
|
||||
- [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()`.
|
||||
through `describe_bridges()`. Nextcloud shipped (`bridges/nextcloud.py` +
|
||||
`bridges/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.
|
||||
|
||||
### Code principles
|
||||
- **Contain installation artifacts in the repo.** Everything a machine installs
|
||||
|
||||
+72
-35
@@ -9,12 +9,12 @@ contract, `TESTGEN.md`. This file is about the runnable body only.
|
||||
## What a skill is
|
||||
|
||||
Semif-agent is an end-user application: an everyday person asks it to do a task,
|
||||
and it does that task using a combination of user-provided data and a catalog of basic services known as bridges. A skill is the thing that performs one of those tasks: it is the leaf in the skill tree that the agent navigates to when it has resolved a request to a single, concrete action. Navigation is performed by an llm-based classification engine known as SemIf.
|
||||
and it does that task using a combination of native python modules, user-provided data and a catalog of basic services known as bridges. A skill is the thing that performs one of those tasks: it is the leaf in the skill tree that the agent navigates to when it has resolved a request to a single, concrete action. Navigation is performed by an llm-based decision engine known as SemIf.
|
||||
|
||||
A skill is three things:
|
||||
|
||||
1. **A manifest** — the registry entry that makes it navigable and describes
|
||||
what it does.
|
||||
1. **A registry entry** — its navigable `name` + `description`, recorded in
|
||||
`data/categories.json` and mirrored in the running tree.
|
||||
2. **A code body** — a runnable Python module implementing a single `act`
|
||||
phase against a real service.
|
||||
3. **A declaration** — the `INTEGRATION` constant (which real system the body
|
||||
@@ -50,7 +50,10 @@ It performs one forward pass and reads the probabilities of the declared answer
|
||||
tokens directly. It returns a probability for each option — no sentence, no
|
||||
JSON, no decoding loop, nothing to parse. In effect it is a semantic `if`:
|
||||
software asks a yes/no/which question in natural language and gets back a typed,
|
||||
thresholdable number. The `state` may also be a nonempty JSON object or array.
|
||||
thresholdable number. In this agent the `state` is always a string
|
||||
(`request.text`, or the query plus a list of candidates); the broader SemIf
|
||||
project also accepts a nonempty JSON object or array as state, but a body here
|
||||
must pass a string.
|
||||
|
||||
The whole point is that the **question and options arrive with the request**.
|
||||
Routing, selection, and assessment are not baked into the model or the prompt;
|
||||
@@ -66,7 +69,7 @@ code.
|
||||
|
||||
### SemIf's feature set
|
||||
|
||||
SemIf (<https://github.com/TheoLeeCJ/SemIf-OpenJev>) is a broader project than
|
||||
SemIf (<https://github.com/TheoLeeCJ/SemIf>) is a broader project than
|
||||
the one call this agent makes. Its full feature set:
|
||||
|
||||
- **Runtime-defined decisions** — state, criterion, and option descriptions are
|
||||
@@ -161,33 +164,48 @@ Rules:
|
||||
the skill's confidence threshold, otherwise fall back to the configured default
|
||||
(see `calendar.create_event` and `simplex.next_message`).
|
||||
- **Use the LLM bridge for text, not for routing or assessment.** Generated text
|
||||
goes through the LLM bridge (`llm_bridge_url`, `llm_bridge_token`) — a generic
|
||||
`POST /chat` — never by speaking a model's protocol directly. Keep the model
|
||||
extractive and bounded (see how `calendar.create_event` asks only for a title
|
||||
and description), and report a real failure when the bridge is down rather than
|
||||
guessing the text.
|
||||
goes through the LLM bridge — a generic `POST /chat` whose base URL, token,
|
||||
and endpoint shapes are in the bridge catalog injected below — never by
|
||||
speaking a model's protocol directly. Keep the model extractive and bounded
|
||||
(see how `calendar.create_event` asks only for a title and description), and
|
||||
report a real failure when the bridge is down rather than guessing the text.
|
||||
- **Never blur the boundaries.** SemIf never generates; an LLM never routes,
|
||||
selects, or assesses; deterministic code never invents a value it cannot
|
||||
observe. A request input is resolved by SemIf, not by substring matching by
|
||||
hand; a title is generated by the LLM, not assembled by string concatenation
|
||||
when it should be written; a date is parsed by code, not asked of a model.
|
||||
|
||||
## Manifest schema
|
||||
## The registry entry
|
||||
|
||||
Registered in `data/categories.json` (and mirrored in the running tree). Fields:
|
||||
The body writer does **not** author a manifest. The `llm` provider authors the
|
||||
leaf's `name` and `description`, and the scheduler records them in
|
||||
`data/categories.json` (mirrored in the running tree). You are told the chosen
|
||||
`name` and `description` in the prompt; use them, and never invent or rename the
|
||||
skill.
|
||||
|
||||
| Field | Meaning |
|
||||
| -------------------- | -------------------------------------------------------------------- |
|
||||
| `name` | `category.skill` dotted snake_case id. Lowercase letters, digits, `_` and `.` only (`[a-z0-9_]+(?:\.[a-z0-9_]+)*`). Single purpose. |
|
||||
| `category` | The top-level category bucket the skill lives under. |
|
||||
| `description` | One to two sentences: what the skill does, for navigation. |
|
||||
| `allowed_inputs` | What the skill accepts / needs as input context. |
|
||||
| `actions` | The concrete actions the skill takes. |
|
||||
| `cost_budget` | Relative budget for one run; a run that exceeds it fails fast. |
|
||||
| `decision_log_ref` | Reference to the decision rows this skill logged during a run. |
|
||||
The registry is a map of category -> bucket:
|
||||
|
||||
Only `name` and `description` are required for a stub; the rest fill in as the
|
||||
skill is exercised.
|
||||
```json
|
||||
{
|
||||
"<category>": {
|
||||
"description": "<one to two sentences: the bucket's purpose>",
|
||||
"skills": [
|
||||
{
|
||||
"name": "<leaf_name>",
|
||||
"description": "<what this leaf does, for navigation>",
|
||||
"request_text": "<the originating request, optional>",
|
||||
"requirements": {"<question>": "<answer>"}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- A leaf `name` is a single snake_case token (`[a-z0-9_]+(?:\.[a-z0-9_]+)*`),
|
||||
not dotted with the category; the category is the key it lives under, and the
|
||||
runner joins them as `category.name` only when it builds the run summary.
|
||||
- `request_text` and `requirements` are recorded by the scheduler so a stub can
|
||||
be re-driven later; the body never sets them.
|
||||
|
||||
## Code body contract
|
||||
|
||||
@@ -261,8 +279,12 @@ def act(ctx, request) -> ActionResult:
|
||||
"""Perform the real action and return the result + new state."""
|
||||
```
|
||||
|
||||
- `ctx` is an `ActionContext` with `ctx.engine` (the real SemIf engine) and
|
||||
`ctx.config` (the resolved values for this skill, including its own config).
|
||||
- `ctx` is an `ActionContext` with `ctx.engine` (the real SemIf engine),
|
||||
`ctx.config` (the resolved values for this skill, including its own config),
|
||||
and `ctx.timers` (the in-process timer/alarm service — use it to schedule a
|
||||
notification, as the `time.set_timer` and `time.set_alarm` seeds do).
|
||||
`ctx.admin` exists for the built-in housekeeping meta skills only; an ordinary
|
||||
body must never touch it.
|
||||
- `request` is the `Request` being handled.
|
||||
- `ActionResult(action_log: str, new_state: str, needs_input: str | None = None,
|
||||
decisions: list = [])` is imported from `semif_agent.skills`; return that exact
|
||||
@@ -363,8 +385,10 @@ INTEGRATION = {
|
||||
(`http|caldav|imap|smtp|pop|subprocess|file|compute`). `compute` is only for
|
||||
skills that perform no external action at all (pure analysis/formatting); an
|
||||
action skill must not use it.
|
||||
- `config_vars` — the `ctx.config` keys the body reads for this integration.
|
||||
Empty list allowed for `compute`.
|
||||
- `config_vars` — the `ctx.config` keys the body reads for this integration. In
|
||||
the committed seeds this is exactly the body's `CONTRACT` key set; an empty
|
||||
list is allowed for `compute`. Declaring a variable the body never reads is a
|
||||
mismatch the fidelity check flags.
|
||||
|
||||
The auto-run test is a hermetic mechanics check and never exercises the live
|
||||
service, so this declaration is how the agent knows what the skill was built to
|
||||
@@ -488,10 +512,14 @@ Rules:
|
||||
pause the human's answer arrives on `request.user_input` and `act` is invoked
|
||||
again from the beginning — re-derive the query and config, consume
|
||||
`request.user_input`, and do not re-ask a question you already have an answer
|
||||
for.
|
||||
for. `request.meta` is a scratch dict carried on the same request across the
|
||||
pause, so a body can cache a computed value or an already-collected answer
|
||||
there and reuse it on the resume pass instead of recomputing or re-asking —
|
||||
see how `calendar.create_event` caches the extracted title/description and the
|
||||
answers it collected.
|
||||
- **Fail fast on budget.** Keep the work small; do not loop or retry in code.
|
||||
- **Names match the manifest.** The module is imported as its manifest name;
|
||||
the function is `act` exactly.
|
||||
- **The function is `act` exactly.** The module is imported under its registered
|
||||
leaf name; the entry point is a module-level `act(ctx, request)`.
|
||||
|
||||
## Bridge services
|
||||
|
||||
@@ -562,11 +590,12 @@ Rules:
|
||||
|
||||
A generated skill is accepted only if:
|
||||
|
||||
1. It compiles (`compile(..., "exec")` succeeds), imports every name it uses
|
||||
(`ActionResult` from `semif_agent.skills`; `DecisionRequest`/`Option` from
|
||||
`semif_agent.decisions` only when it actually builds a sub-decision; each
|
||||
stdlib module it calls — no `NameError` at run time), and defines `act`.
|
||||
2. Its `name` matches the manifest regex and its `category` is given.
|
||||
1. It parses as Python (`ast.parse` succeeds), defines a module-level `act`
|
||||
function, and imports every name it uses (`ActionResult` from
|
||||
`semif_agent.skills`; `DecisionRequest`/`Option` from `semif_agent.decisions`
|
||||
only when it actually builds a sub-decision; each stdlib module it calls — no
|
||||
`NameError` at run time).
|
||||
2. Its `name` matches the leaf-name regex and its `category` is given.
|
||||
3. Its body imports nothing outside the stdlib and the agent package.
|
||||
4. It uses `ctx.engine` (never mocks) and returns proper `ActionResult` types.
|
||||
5. It is single-purpose and does not duplicate an existing category leaf.
|
||||
@@ -590,3 +619,11 @@ A generated skill is accepted only if:
|
||||
13. If it is a messaging skill, it uses a bridge service over HTTP (never a
|
||||
service's native protocol), resolves recipients with a SemIf sub-decision,
|
||||
and sends only on explicit user intent.
|
||||
|
||||
Items 1 and 7 are hard checks in the parser (`parse_skill_body`) and reject the
|
||||
body outright. The rest are not statically rejected: a missing or inconsistent
|
||||
`INTEGRATION` (#11) is inferred and the body is accepted badged `unverified`, a
|
||||
third-party import (#3) only fails when the module is actually imported, and
|
||||
import-time work (#12) only shows up when it runs. The fidelity gate rewrites a
|
||||
body once for these, then accepts it — so treat every item as required, not
|
||||
optional.
|
||||
@@ -384,7 +384,7 @@ 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 + the LLM bridge)
|
||||
bridges/ standalone third-party API bridges (SimpleX, LLM, Nextcloud)
|
||||
seeds/ committed starter skills (calendar, simplex)
|
||||
scripts/ bootstrap.sh, simplex-address.py, systemd/*.in
|
||||
requirements/ staging.txt — the pinned engine deps
|
||||
@@ -513,12 +513,17 @@ Key blocks:
|
||||
| `gateway.simplex` | command gateway: ws_url, allowlist, batching |
|
||||
| `gateway.voice` | voice gateway: wake/STT/TTS engines + models, audio devices, VAD, follow-up window |
|
||||
| `bridges.simplex` | forwarding bridge: host/port/token/ws_url |
|
||||
| `simplex_bridge_url` / `simplex_bridge_token` | what skill bodies call |
|
||||
| `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) |
|
||||
| `llm_bridge_url` / `llm_bridge_token` | what skill bodies call for generation |
|
||||
| `bridges.nextcloud` | Nextcloud bridge: host/port/token + connection (url/username/app_password/defaults) |
|
||||
| `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) |
|
||||
| `dashboard` | bind host/port |
|
||||
|
||||
Bridge skills read `simplex_bridge_url` / `llm_bridge_url` / `nextcloud_bridge_url`
|
||||
(+ their `_token`) from `ctx.config`; each is **derived** at startup from its
|
||||
`bridges.<name>` host/port/token, so there is no duplicate top-level key to keep
|
||||
in sync. A bridge with no block (or no port) leaves the variable unresolved and
|
||||
the operator is asked for it.
|
||||
|
||||
`llm.model` and `codegen.model` are **required** (no default): set each to a
|
||||
model its endpoint serves. A missing model fails fast at startup with a clear
|
||||
config error rather than sending a request to a model that isn't there.
|
||||
@@ -684,9 +689,10 @@ python -m semif_agent.cli gateway --platform voice
|
||||
### Bridge services
|
||||
|
||||
`cli bridge` runs standalone bridges: each is a process that stands up a small,
|
||||
token-guarded localhost HTTP API in front of one third-party system and owns its
|
||||
own daemon/profile. Generated skill bodies call them like any HTTP service (base
|
||||
URL from a config var), so they never speak a native protocol directly.
|
||||
token-guarded localhost HTTP API in front of one third-party system (and, where
|
||||
the system needs one, owns its own daemon/profile). Generated skill bodies call
|
||||
them like any HTTP service (base URL from a config var), so they never speak a
|
||||
native protocol directly.
|
||||
|
||||
The first bridge is **SimpleX** (`semif_agent/bridges/simplex.py`), with its own
|
||||
simplex-chat daemon separate from the gateway's. Its HTTP surface:
|
||||
@@ -707,7 +713,8 @@ so they see messages that arrived while the bridge was down — unlike the live
|
||||
`/inbox` receive buffer. Both are read-only: v7 has no mark-read command, so
|
||||
acking is a client-side read receipt, not an API call.
|
||||
|
||||
`simplex_bridge_url` (top-level config) is what skills call; the bridge catalog
|
||||
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.
|
||||
@@ -723,10 +730,49 @@ text (e.g. extract an event title + description) over HTTP instead of speaking
|
||||
the OpenAI-compatible protocol itself. It does not own the model connection:
|
||||
`cli bridge` threads the scheduler's already-configured `llm` client into it, so
|
||||
the endpoint/model/sampler live only in the top-level `llm` block; `bridges.llm`
|
||||
carries just the local listener. Skills call it via `llm_bridge_url`
|
||||
(+ optional `llm_bridge_token`); with no client it returns `502`, never a
|
||||
fabricated reply. It starts in the same `semif-bridge.service` process as the
|
||||
other enabled bridges.
|
||||
carries just the local listener. Skills call it at the address derived from
|
||||
`bridges.llm` (`llm_bridge_url`, + optional `llm_bridge_token`); with no client
|
||||
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
|
||||
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
|
||||
plain HTTPS) and is stdlib-only (`urllib` + `xml.etree`), so it starts instantly
|
||||
in the same `semif-bridge` process. The connection (base URL, username, app
|
||||
password) is configured in `bridges.nextcloud` and falls back to the top-level
|
||||
`nextcloud_url` / `nextcloud_username` / `nextcloud_app_password` /
|
||||
`nextcloud_default_calendar` the calendar seeds use, so the account is
|
||||
configured once. Skills call it at the address derived from `bridges.nextcloud`
|
||||
(`nextcloud_bridge_url`, + optional `nextcloud_bridge_token`). Its HTTP surface:
|
||||
|
||||
```
|
||||
GET /health
|
||||
GET /user # account info (OCS)
|
||||
GET /capabilities # server capabilities (OCS)
|
||||
GET /files?path=<dir> # list a folder (WebDAV)
|
||||
GET /files/stat?path=<path>
|
||||
GET /files/read?path=<path> # text, or base64 for binary
|
||||
GET /files/search?query=<text>&path=<dir>
|
||||
POST /files/write {"path","content","encoding"?,"overwrite"?}
|
||||
POST /files/mkdir | /files/delete | /files/move | /files/copy
|
||||
GET /calendars
|
||||
GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> # CalDAV VEVENT
|
||||
POST /calendars/events | /calendars/events/update | /calendars/events/delete
|
||||
GET /tasks?calendar=<name> # CalDAV VTODO
|
||||
POST /tasks | /tasks/update | /tasks/complete | /tasks/delete
|
||||
GET /addressbooks
|
||||
GET /contacts?addressbook=<name>&query=<text> # CardDAV
|
||||
POST /contacts | /contacts/update | /contacts/delete
|
||||
GET /notes | /notes/get?id=<id> # Notes app (OCS)
|
||||
POST /notes | /notes/update | /notes/delete
|
||||
```
|
||||
|
||||
A missing connection is `503`; a real Nextcloud failure (transport, HTTP error,
|
||||
or a bad reply) is `502` — never a fabricated success. Calendar and addressbook
|
||||
defaults resolve from `bridges.nextcloud` when a request names none and the
|
||||
account has several.
|
||||
|
||||
### Dream report
|
||||
|
||||
@@ -744,8 +790,8 @@ rows.
|
||||
A skill is one specific, single-purpose action reachable by category → skill
|
||||
navigation. It is three things:
|
||||
|
||||
1. a **manifest** (navigable description — `name`, `category`, `description`,
|
||||
plus optional `allowed_inputs`, `actions`, `cost_budget`, `decision_log_ref`);
|
||||
1. a **registry entry** (navigable description — `name` + `description`,
|
||||
authored by the small `llm` provider and recorded in `data/categories.json`);
|
||||
2. a **code body** (a single `act`);
|
||||
3. an **`INTEGRATION` declaration** (service / transport / config_vars) and a
|
||||
flat **`CONTRACT`** (the operational values the runner must provide).
|
||||
|
||||
+13
-8
@@ -3,8 +3,8 @@
|
||||
This file is the authoritative spec for the **testing** side of a skill. It is
|
||||
fed verbatim (alongside the finished `skill.py`) to the model that produces the
|
||||
test artifact. The runnable body contract lives in `CODEGEN.md`; this file is
|
||||
deliberately separate so the body writer never embeds test data and the test
|
||||
writer never worries about body semantics.
|
||||
deliberately separate so the body writer never embeds test data and the test is
|
||||
generated from the finished body rather than the other way around.
|
||||
|
||||
A finished skill leaf is a folder
|
||||
`data/skills/<category>/<name>/` containing (among others) two artifacts:
|
||||
@@ -33,8 +33,9 @@ each value is a plain-language, semantic description of the expected values for
|
||||
that variable (what it is, what good values look like).
|
||||
|
||||
The body declares this itself as a module-level `CONTRACT` constant (see
|
||||
`CODEGEN.md`); `contract.json` is a persisted mirror of it, provided to the test
|
||||
writer as context. The test writer does not author or change the contract.
|
||||
`CODEGEN.md`); `contract.json` is a persisted mirror of it, and the same
|
||||
contract object is handed to you as context. You do not author or change the
|
||||
contract.
|
||||
|
||||
This contract exists for exactly two consumers:
|
||||
|
||||
@@ -99,10 +100,14 @@ A stdlib-only Python script that:
|
||||
|
||||
The test artifact is accepted only if:
|
||||
|
||||
1. `skill.test.py` parses as Python, imports only the stdlib and the agent
|
||||
package, embeds its fixtures inline (no external files), is hermetic, and
|
||||
runs to exit 0 when executed from the skill folder.
|
||||
2. The test stays compatible with the body's `CONTRACT` (the same variable
|
||||
1. `skill.test.py` parses as Python — the only static check — and runs to exit 0
|
||||
when executed from the skill folder; on failure the captured output drives a
|
||||
regeneration.
|
||||
2. It imports only the stdlib and the agent package, embeds its fixtures inline
|
||||
(no external files), and is hermetic (no external network, no real services).
|
||||
These are required of every test but are **not** statically verified, so do
|
||||
not rely on a checker to catch a violation.
|
||||
3. The test stays compatible with the body's `CONTRACT` (the same variable
|
||||
names the body reads from `ctx.config`).
|
||||
|
||||
Produce one artifact: `skill.test.py` (derived from `skill.py` plus its
|
||||
|
||||
+16
-6
@@ -117,10 +117,6 @@
|
||||
},
|
||||
"skill_bodies": "data/skills",
|
||||
"skill_seeds": "seeds",
|
||||
"simplex_bridge_url": "http://127.0.0.1:5227",
|
||||
"simplex_bridge_token": "",
|
||||
"llm_bridge_url": "http://127.0.0.1:5229",
|
||||
"llm_bridge_token": "",
|
||||
"log": "data/decisions.jsonl",
|
||||
"trace": "data/runs.jsonl",
|
||||
"category_registry": "data/categories.json",
|
||||
@@ -134,7 +130,7 @@
|
||||
"bridges": {
|
||||
"_comment": "Standalone third-party API bridges: a simple, secure local HTTP layer between codegen-authored skill bodies and real system services. Each bridge runs as its own process (`python -m semif_agent.cli bridge [--name NAME]`), one process per service daemon, and never runs inside the command gateway — gateway isolation is non-negotiable (see AGENTS.md). The bridge catalog (names, endpoints, config vars) is injected into the code-generation prompts via `semif_agent.bridges.describe_bridges()`.",
|
||||
"simplex": {
|
||||
"_comment": "SimpleX forwarding bridge: buffers every inbound DM (no allowlist — the point is to see who reached the bot through its invite link), and serves invite-link / read / send over HTTP. It owns its own simplex-chat daemon/profile (`ws_url`, `forward_port` above), separate from the command gateway's. Skills use the top-level `simplex_bridge_url`; keep it in sync with host/port. Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
|
||||
"_comment": "SimpleX forwarding bridge: buffers every inbound DM (no allowlist — the point is to see who reached the bot through its invite link), and serves invite-link / read / send over HTTP. It owns its own simplex-chat daemon/profile (`ws_url`, `forward_port` above), separate from the command gateway's. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
|
||||
"enabled": true,
|
||||
"host": "127.0.0.1",
|
||||
"port": 5227,
|
||||
@@ -146,11 +142,25 @@
|
||||
"reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2}
|
||||
},
|
||||
"llm": {
|
||||
"_comment": "LLM bridge: a generic `POST /chat` in front of the agent's configured `llm` model, so skill bodies can ask for short generated text (e.g. an event title + description) over HTTP instead of speaking the OpenAI-compatible protocol. It reuses the top-level `llm` client (endpoint/model/sampler configured once there); this block only carries the local listener. Skills use the top-level `llm_bridge_url`; keep it in sync with host/port. Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. It runs inside the same `semif-bridge.service` process as the other enabled bridges.",
|
||||
"_comment": "LLM bridge: a generic `POST /chat` in front of the agent's configured `llm` model, so skill bodies can ask for short generated text (e.g. an event title + description) over HTTP instead of speaking the OpenAI-compatible protocol. It reuses the top-level `llm` client (endpoint/model/sampler configured once there); this block only carries the local listener. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. It runs inside the same `semif-bridge.service` process as the other enabled bridges.",
|
||||
"enabled": true,
|
||||
"host": "127.0.0.1",
|
||||
"port": 5229,
|
||||
"token": ""
|
||||
},
|
||||
"nextcloud": {
|
||||
"_comment": "Nextcloud bridge: files (WebDAV), calendar events and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app) over one uniform local JSON API, so skill bodies never speak the native DAV/OCS protocols. It has no service daemon (Nextcloud is plain HTTPS) and runs inside the same `semif-bridge` process as the other enabled bridges. The connection is configured HERE (url/username/app_password); when a value is blank the bridge falls back to the top-level nextcloud_url/nextcloud_username/nextcloud_app_password/nextcloud_default_calendar the calendar seeds already use, so the account is configured once. `app_password` is a Nextcloud app password (Settings > Security > Devices & sessions), not the account password. `default_calendar`/`default_addressbook` are used when a request names none and the account has several. `verify_tls` false skips certificate verification (self-signed hosts). Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
|
||||
"enabled": true,
|
||||
"host": "127.0.0.1",
|
||||
"port": 5230,
|
||||
"token": "",
|
||||
"url": "",
|
||||
"username": "",
|
||||
"app_password": "",
|
||||
"default_calendar": "",
|
||||
"default_addressbook": "",
|
||||
"verify_tls": true,
|
||||
"timeout": 30
|
||||
}
|
||||
},
|
||||
"gateway": {
|
||||
|
||||
+12
-5
@@ -616,14 +616,21 @@ SimpleX forwarding bridge (messaging UX for skills):
|
||||
and 'semif-bridge' (the standalone bridge API). Its contact address is printed
|
||||
above; re-print with:
|
||||
"$PYTHON" scripts/simplex-address.py --ws-url ws://127.0.0.1:$SIMPLEX_FORWARD_PORT
|
||||
- Skills reach it over HTTP via the top-level simplex_bridge_url
|
||||
(default http://127.0.0.1:5227); simplex.connect_link shows its address and
|
||||
simplex.next_message reads messages sent to it.
|
||||
- Skills reach it over HTTP at the address derived from bridges.simplex
|
||||
(host/port, default http://127.0.0.1:5227); simplex.connect_link shows its
|
||||
address and simplex.next_message reads messages sent to it.
|
||||
|
||||
LLM bridge (generation for skills):
|
||||
- Runs inside the same 'semif-bridge' process. It reuses the top-level `llm`
|
||||
model (configured once) and serves a generic POST /chat; skills call it via
|
||||
the top-level llm_bridge_url (default http://127.0.0.1:5229).
|
||||
model (configured once) and serves a generic POST /chat; skills call it at
|
||||
the address derived from bridges.llm (default http://127.0.0.1:5229).
|
||||
|
||||
Nextcloud bridge (files/calendar/tasks/contacts/notes for skills):
|
||||
- Runs inside the same 'semif-bridge' process (Nextcloud is plain HTTPS, so
|
||||
there is no separate daemon). Configure the account once in config.json under
|
||||
bridges.nextcloud (url/username/app_password) — or reuse the top-level
|
||||
nextcloud_* values the calendar seeds collect. Skills call it at the address
|
||||
derived from bridges.nextcloud (default http://127.0.0.1:5230).
|
||||
EOF
|
||||
|
||||
if [[ "$VOICE" = 1 ]]; then
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""Third-party API bridges: a secure local layer between skills and services.
|
||||
|
||||
A **bridge service** is a standalone process that exposes one third-party system
|
||||
(SimpleX, the local language model) to codegen-authored skill bodies over a
|
||||
local, token-guarded HTTP API. It exists so a generated body never speaks a
|
||||
system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat
|
||||
(SimpleX, the local language model, Nextcloud) to codegen-authored skill bodies
|
||||
over a local, token-guarded HTTP API. It exists so a generated body never speaks
|
||||
a system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat
|
||||
API, a CLI's private flags) directly: it calls a small, documented, uniform HTTP
|
||||
surface instead, and the bridge owns the messy integration details and
|
||||
credentials.
|
||||
@@ -26,6 +26,7 @@ from .base import BridgeInfo, BridgeService
|
||||
from .inbox import MessagingInbox
|
||||
from .registry import (
|
||||
build_bridge,
|
||||
derived_config_vars,
|
||||
describe_bridges,
|
||||
known_infos,
|
||||
run_bridges,
|
||||
@@ -36,6 +37,7 @@ __all__ = [
|
||||
"BridgeService",
|
||||
"MessagingInbox",
|
||||
"build_bridge",
|
||||
"derived_config_vars",
|
||||
"describe_bridges",
|
||||
"known_infos",
|
||||
"run_bridges",
|
||||
|
||||
@@ -0,0 +1,501 @@
|
||||
"""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 calendar seeds
|
||||
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
|
||||
|
||||
|
||||
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}]}",
|
||||
"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",
|
||||
"POST /tasks {\"calendar\"?, \"uid\"?, \"summary\", \"due\"?, "
|
||||
"\"priority\"?, \"description\"?} -> 200 {\"ok\": true, \"uid\", "
|
||||
"\"calendar\", \"etag\"}",
|
||||
"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_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 == "/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"))
|
||||
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"))
|
||||
return 200, self.client.complete_task(calendar, self._required(payload, "uid"))
|
||||
if path == "/tasks/delete":
|
||||
calendar = self._resolve_calendar(self._optional_str(payload, "calendar"))
|
||||
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"))
|
||||
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"))
|
||||
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) -> str:
|
||||
name = str(name or self.default_calendar or "").strip()
|
||||
if name:
|
||||
return name
|
||||
calendars = self.client.list_calendars()
|
||||
if len(calendars) == 1:
|
||||
return calendars[0]["name"]
|
||||
raise ValueError(
|
||||
"calendar is required (name one in the request, or set "
|
||||
"bridges.nextcloud.default_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
@@ -14,10 +14,11 @@ import threading
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .llm import LLMBridge
|
||||
from .nextcloud import NextcloudBridge
|
||||
from .simplex import SimplexBridge
|
||||
|
||||
#: Known bridge services. Order is presentation order.
|
||||
CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge, LLMBridge)
|
||||
CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge, LLMBridge, NextcloudBridge)
|
||||
|
||||
|
||||
def _class_for(name: str) -> type[BridgeService] | None:
|
||||
@@ -31,6 +32,35 @@ def known_infos() -> list[BridgeInfo]:
|
||||
return [bridge_class.INFO for bridge_class in CATALOG]
|
||||
|
||||
|
||||
def derived_config_vars(config: dict) -> dict[str, str]:
|
||||
"""Skill-facing config vars for every bridge, derived from its own block.
|
||||
|
||||
The `bridges.<name>` block is the single source of truth: its `host`/`port`
|
||||
are the listener a skill body calls and its `token` is the shared secret.
|
||||
There is deliberately no duplicate top-level `*_bridge_url`/`*_bridge_token`
|
||||
to keep in sync — the values are derived here and injected into the config a
|
||||
skill reads (`ctx.config`). A bridge with no block (or no port) contributes
|
||||
nothing, so an unconfigured bridge still surfaces as an unresolved contract
|
||||
variable the operator is asked for.
|
||||
"""
|
||||
blocks = config.get("bridges", {}) or {}
|
||||
derived: dict[str, str] = {}
|
||||
for info in known_infos():
|
||||
block = blocks.get(info.name)
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
host = str(block.get("host") or "127.0.0.1").strip()
|
||||
# A bind-all address is not a callable one; skills always call loopback.
|
||||
if host in ("", "0.0.0.0", "::", "[::]"):
|
||||
host = "127.0.0.1"
|
||||
port = block.get("port")
|
||||
if info.url_config_var and port:
|
||||
derived[info.url_config_var] = f"http://{host}:{int(port)}"
|
||||
if info.auth_config_var:
|
||||
derived[info.auth_config_var] = str(block.get("token") or "")
|
||||
return derived
|
||||
|
||||
|
||||
def describe_bridges() -> str:
|
||||
"""A prompt block describing every available bridge service.
|
||||
|
||||
@@ -75,7 +105,9 @@ def build_bridge(
|
||||
|
||||
`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. Other bridges ignore it.
|
||||
that config. The Nextcloud bridge gets the top-level `nextcloud_*` values as a
|
||||
fallback, so the same account the calendar seeds use is configured once. Other
|
||||
bridges ignore both.
|
||||
"""
|
||||
bridge_class = _class_for(name)
|
||||
if bridge_class is None:
|
||||
@@ -83,6 +115,18 @@ def build_bridge(
|
||||
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_addressbook": config.get("nextcloud_default_addressbook"),
|
||||
},
|
||||
)
|
||||
return bridge_class(block, trace=trace)
|
||||
|
||||
|
||||
|
||||
@@ -313,6 +313,13 @@ def build_llm_client(config: dict, engine):
|
||||
|
||||
|
||||
def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||
# Bridge listener addresses/tokens are derived from each bridge's own
|
||||
# `bridges.<name>` block (host/port/token) — the single source of truth.
|
||||
# There is no duplicate top-level *_bridge_url to drift; skills read these
|
||||
# from ctx.config and the contract config search finds them here.
|
||||
from .bridges.registry import derived_config_vars
|
||||
|
||||
config = {**config, **derived_config_vars(config)}
|
||||
engine = build_engine(config)
|
||||
llm = build_llm_client(config, engine)
|
||||
log = DecisionLog(config.get("log", "data/decisions.jsonl"))
|
||||
|
||||
+38
-1
@@ -15,7 +15,11 @@ import urllib.request
|
||||
import pytest
|
||||
|
||||
from semif_agent.bridges.llm import LLMBridge
|
||||
from semif_agent.bridges.registry import describe_bridges, known_infos
|
||||
from semif_agent.bridges.registry import (
|
||||
derived_config_vars,
|
||||
describe_bridges,
|
||||
known_infos,
|
||||
)
|
||||
from semif_agent.bridges.simplex import SimplexBridge
|
||||
|
||||
|
||||
@@ -674,6 +678,39 @@ def test_every_bridge_documents_its_config_vars_and_auth():
|
||||
assert info.auth_config_var in info.config_vars, info.name
|
||||
|
||||
|
||||
def test_derived_config_vars_come_from_each_bridge_block():
|
||||
config = {
|
||||
"bridges": {
|
||||
"simplex": {"host": "127.0.0.1", "port": 5227, "token": "s"},
|
||||
"llm": {"host": "127.0.0.1", "port": 5229, "token": ""},
|
||||
"nextcloud": {"host": "127.0.0.1", "port": 5230, "token": "n"},
|
||||
}
|
||||
}
|
||||
derived = derived_config_vars(config)
|
||||
assert derived["simplex_bridge_url"] == "http://127.0.0.1:5227"
|
||||
assert derived["simplex_bridge_token"] == "s"
|
||||
assert derived["llm_bridge_url"] == "http://127.0.0.1:5229"
|
||||
assert derived["llm_bridge_token"] == ""
|
||||
assert derived["nextcloud_bridge_url"] == "http://127.0.0.1:5230"
|
||||
assert derived["nextcloud_bridge_token"] == "n"
|
||||
|
||||
|
||||
def test_derived_config_vars_normalize_bind_all_host():
|
||||
config = {"bridges": {"llm": {"host": "0.0.0.0", "port": 5229}}}
|
||||
assert derived_config_vars(config)["llm_bridge_url"] == "http://127.0.0.1:5229"
|
||||
|
||||
|
||||
def test_derived_config_vars_skip_unconfigured_bridges():
|
||||
# No block at all: nothing derived, so the contract variable stays
|
||||
# unresolved and the operator is asked for it.
|
||||
assert derived_config_vars({}) == {}
|
||||
# A block without a port is not a callable address: no URL, but the token
|
||||
# var is still satisfiable (empty = no auth).
|
||||
derived = derived_config_vars({"bridges": {"nextcloud": {"token": ""}}})
|
||||
assert "nextcloud_bridge_url" not in derived
|
||||
assert derived["nextcloud_bridge_token"] == ""
|
||||
|
||||
|
||||
def test_describe_bridges_renders_service_auth_and_endpoints():
|
||||
text = describe_bridges()
|
||||
assert "simplex" in text
|
||||
|
||||
+22
-1
@@ -146,6 +146,24 @@ def test_contract_directs_request_arguments_and_output():
|
||||
assert "No work at import time" in text
|
||||
|
||||
|
||||
def test_skill_contract_documents_runtime_surface():
|
||||
"""CODEGEN.md must document the ActionContext surface a body can rely on
|
||||
(ctx.timers for scheduling) and the request.meta resume cache — both are
|
||||
used by the authoritative seed set, so a body writer needs them."""
|
||||
text = read_skill_contract()
|
||||
assert "ctx.timers" in text
|
||||
assert "request.meta" in text
|
||||
|
||||
|
||||
def test_skill_contract_has_no_stale_manifest_fields():
|
||||
"""The old manifest schema (allowed_inputs/actions/cost_budget/
|
||||
decision_log_ref, a dotted leaf name) described fields the registry never
|
||||
had; keep it out of the body contract."""
|
||||
text = read_skill_contract()
|
||||
for stale in ("allowed_inputs", "decision_log_ref", "cost_budget", "Manifest schema"):
|
||||
assert stale not in text
|
||||
|
||||
|
||||
def test_body_directives_require_query_arguments_and_output():
|
||||
"""The prompt directives (used by the first, retry, and regen prompts) must
|
||||
echo the query->arguments and real-output requirements, not just CODEGEN.md."""
|
||||
@@ -1541,7 +1559,10 @@ def test_other_codegen_error_does_not_retry():
|
||||
model="test",
|
||||
timeout=10,
|
||||
stream=True,
|
||||
context_window=3000,
|
||||
# Large enough that the prompt (which carries the bridge catalog via
|
||||
# describe_bridges) passes the pre-flight budget and generation
|
||||
# starts, so the *output* cap is what trips.
|
||||
context_window=10000,
|
||||
max_output=0.01,
|
||||
idle_timeout=30,
|
||||
max_attempts=3,
|
||||
|
||||
@@ -0,0 +1,954 @@
|
||||
"""Pure-stdlib tests for the Nextcloud bridge.
|
||||
|
||||
A loopback `http.server` plays a real Nextcloud (WebDAV files, CalDAV events and
|
||||
tasks, CardDAV contacts, OCS Notes) 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 Nextcloud is the only proof the integration works.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import pytest
|
||||
|
||||
from semif_agent.bridges.nextcloud import NextcloudBridge
|
||||
from semif_agent.bridges.nextcloud_client import NextcloudClient, NextcloudError
|
||||
from semif_agent.bridges.registry import build_bridge, describe_bridges, known_infos
|
||||
|
||||
USER = "alice"
|
||||
PASSWORD = "app-secret"
|
||||
MODIFIED = "Mon, 01 Jan 2026 12:00:00 GMT"
|
||||
|
||||
|
||||
def _norm(path):
|
||||
text = "/" + str(path or "").strip("/")
|
||||
return "/" if text == "/" else text
|
||||
|
||||
|
||||
def _parent(path):
|
||||
if path == "/":
|
||||
return None
|
||||
return path.rsplit("/", 1)[0] or "/"
|
||||
|
||||
|
||||
class FakeNextcloud:
|
||||
"""A minimal but real Nextcloud-shaped HTTP server for the client."""
|
||||
|
||||
def __init__(self):
|
||||
self.files = {
|
||||
"/": {"type": "dir"},
|
||||
"/Documents": {"type": "dir"},
|
||||
"/Documents/readme.txt": {"type": "file", "content": b"hello world"},
|
||||
"/image.png": {"type": "file", "content": b"\x89PNG\x00\xff"},
|
||||
}
|
||||
self.calendars = {"personal": {"label": "Personal", "objects": {}}}
|
||||
self.addressbooks = {"contacts": {"label": "Contacts", "cards": {}}}
|
||||
self.notes = {}
|
||||
self._next_note_id = 1
|
||||
self.calls = []
|
||||
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 _authorized(self):
|
||||
expected = "Basic " + base64.b64encode(
|
||||
f"{USER}:{PASSWORD}".encode()
|
||||
).decode()
|
||||
return self.headers.get("Authorization") == expected
|
||||
|
||||
def _send(self, status, body=b"", content_type="application/xml", headers=None):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
for key, value in (headers or {}).items():
|
||||
self.send_header(key, value)
|
||||
self.end_headers()
|
||||
if body:
|
||||
self.wfile.write(body)
|
||||
|
||||
def _dispatch(self, method):
|
||||
body = self._read()
|
||||
fake.calls.append((method, self.path, dict(self.headers), body))
|
||||
if not self._authorized():
|
||||
self._send(401, b'{"error":"unauthorized"}', "application/json")
|
||||
return
|
||||
status, payload, content_type, headers = fake.handle(
|
||||
method, self.path, body
|
||||
)
|
||||
self._send(status, payload, content_type, headers)
|
||||
|
||||
def do_GET(self):
|
||||
self._dispatch("GET")
|
||||
|
||||
def do_PUT(self):
|
||||
self._dispatch("PUT")
|
||||
|
||||
def do_POST(self):
|
||||
self._dispatch("POST")
|
||||
|
||||
def do_DELETE(self):
|
||||
self._dispatch("DELETE")
|
||||
|
||||
def do_MOVE(self):
|
||||
self._dispatch("MOVE")
|
||||
|
||||
def do_COPY(self):
|
||||
self._dispatch("COPY")
|
||||
|
||||
def do_MKCOL(self):
|
||||
self._dispatch("MKCOL")
|
||||
|
||||
def do_PROPFIND(self):
|
||||
self._dispatch("PROPFIND")
|
||||
|
||||
def do_REPORT(self):
|
||||
self._dispatch("REPORT")
|
||||
|
||||
def do_SEARCH(self):
|
||||
self._dispatch("SEARCH")
|
||||
|
||||
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):
|
||||
url = urlparse(path)
|
||||
route = url.path
|
||||
query = parse_qs(url.query)
|
||||
if route.startswith("/ocs/"):
|
||||
return self._ocs(method, route, body)
|
||||
if route.startswith("/remote.php/dav/files/"):
|
||||
return self._files(method, route, body)
|
||||
if route.startswith("/remote.php/dav/calendars/"):
|
||||
return self._calendars(method, route, body)
|
||||
if route.startswith("/remote.php/dav/addressbooks/"):
|
||||
return self._addressbooks(method, route, body)
|
||||
if route == "/remote.php/dav/":
|
||||
return self._search(body)
|
||||
return 404, b"not found", "text/plain", {}
|
||||
|
||||
def _xml(self, responses):
|
||||
return (
|
||||
'<?xml version="1.0"?>'
|
||||
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" '
|
||||
'xmlns:card="urn:ietf:params:xml:ns:carddav" '
|
||||
'xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns">'
|
||||
+ "".join(responses)
|
||||
+ "</d:multistatus>"
|
||||
).encode()
|
||||
|
||||
@staticmethod
|
||||
def _response(href, props):
|
||||
return (
|
||||
f"<d:response><d:href>{href}</d:href>"
|
||||
f"<d:propstat><d:prop>{props}</d:prop>"
|
||||
"<d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>"
|
||||
)
|
||||
|
||||
# ---- files ----
|
||||
|
||||
def _file_response(self, dav_path):
|
||||
info = self.files.get(dav_path)
|
||||
if info is None:
|
||||
return None
|
||||
is_dir = info["type"] == "dir"
|
||||
suffix = dav_path if dav_path == "/" else dav_path + ("/" if is_dir else "")
|
||||
href = f"/remote.php/dav/files/{USER}{suffix}"
|
||||
name = "root" if dav_path == "/" else dav_path.rsplit("/", 1)[-1]
|
||||
size = 0 if is_dir else len(info.get("content", b""))
|
||||
resourcetype = "<d:collection/>" if is_dir else ""
|
||||
content_type = "httpd/unix-directory" if is_dir else "text/plain"
|
||||
props = (
|
||||
f"<d:resourcetype>{resourcetype}</d:resourcetype>"
|
||||
f"<d:displayname>{name}</d:displayname>"
|
||||
f"<d:getcontentlength>{size}</d:getcontentlength>"
|
||||
f"<d:getlastmodified>{MODIFIED}</d:getlastmodified>"
|
||||
f'<d:getetag>"etag-{name}"</d:getetag>'
|
||||
f"<d:getcontenttype>{content_type}</d:getcontenttype>"
|
||||
)
|
||||
return self._response(href, props)
|
||||
|
||||
def _files(self, method, route, body):
|
||||
rest = route[len("/remote.php/dav/files/") :]
|
||||
user, _, tail = rest.partition("/")
|
||||
dav_path = _norm(tail)
|
||||
if method == "PROPFIND":
|
||||
depth = None
|
||||
# depth is read from the request headers by the handler; emulate via
|
||||
# the client always sending one — Depth "1" lists children.
|
||||
if dav_path not in self.files:
|
||||
return 404, b"not found", "text/plain", {}
|
||||
responses = []
|
||||
# The Depth header is not threaded here; both stat and list are
|
||||
# covered by returning the entry, and list adds children.
|
||||
responses.append(self._file_response(dav_path))
|
||||
for candidate in self.files:
|
||||
if _parent(candidate) == dav_path and candidate != dav_path:
|
||||
responses.append(self._file_response(candidate))
|
||||
return 207, self._xml([r for r in responses if r]), "application/xml", {}
|
||||
if method == "GET":
|
||||
info = self.files.get(dav_path)
|
||||
if info is None or info["type"] != "file":
|
||||
return 404, b"not found", "text/plain", {}
|
||||
return 200, info["content"], "application/octet-stream", {}
|
||||
if method == "PUT":
|
||||
self.files[dav_path] = {"type": "file", "content": body}
|
||||
return 201, b"", "text/plain", {"ETag": '"new"'}
|
||||
if method == "MKCOL":
|
||||
self.files[dav_path] = {"type": "dir"}
|
||||
return 201, b"", "text/plain", {}
|
||||
if method == "DELETE":
|
||||
self.files.pop(dav_path, None)
|
||||
return 204, b"", "text/plain", {}
|
||||
if method in ("MOVE", "COPY"):
|
||||
return 201, b"", "text/plain", {}
|
||||
return 405, b"method not allowed", "text/plain", {}
|
||||
|
||||
def _search(self, body):
|
||||
text = body.decode("utf-8", "replace")
|
||||
needle = ""
|
||||
if "<d:literal>" in text:
|
||||
needle = text.split("<d:literal>", 1)[1].split("</d:literal>", 1)[0].strip("%")
|
||||
responses = []
|
||||
for dav_path, info in self.files.items():
|
||||
if info["type"] != "file":
|
||||
continue
|
||||
if needle and needle.lower() not in dav_path.lower():
|
||||
continue
|
||||
responses.append(self._file_response(dav_path))
|
||||
return 207, self._xml(responses), "application/xml", {}
|
||||
|
||||
# ---- calendars ----
|
||||
|
||||
def _calendar_home(self):
|
||||
responses = [
|
||||
self._response(
|
||||
f"/remote.php/dav/calendars/{USER}/",
|
||||
"<d:resourcetype><d:collection/></d:resourcetype>"
|
||||
f"<d:displayname>{USER}</d:displayname>",
|
||||
)
|
||||
]
|
||||
for name, calendar in self.calendars.items():
|
||||
responses.append(
|
||||
self._response(
|
||||
f"/remote.php/dav/calendars/{USER}/{name}/",
|
||||
"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
|
||||
f"<d:displayname>{calendar['label']}</d:displayname>"
|
||||
"<c:calendar-description>desc</c:calendar-description>"
|
||||
'<nc:calendar-color>#ff0000</nc:calendar-color>'
|
||||
"<c:getctag>ctag-1</c:getctag>",
|
||||
)
|
||||
)
|
||||
return self._xml(responses)
|
||||
|
||||
def _calendars(self, method, route, body):
|
||||
rest = route[len("/remote.php/dav/calendars/") :]
|
||||
user, _, tail = rest.partition("/")
|
||||
tail = _norm(tail)
|
||||
if tail == "/":
|
||||
if method == "PROPFIND":
|
||||
return 207, self._calendar_home(), "application/xml", {}
|
||||
return 405, b"method not allowed", "text/plain", {}
|
||||
name, _, leaf = tail.lstrip("/").partition("/")
|
||||
calendar = self.calendars.get(name)
|
||||
if calendar is None:
|
||||
return 404, b"not found", "text/plain", {}
|
||||
if not leaf:
|
||||
if method == "REPORT":
|
||||
responses = []
|
||||
for uid, ics in calendar["objects"].items():
|
||||
responses.append(
|
||||
self._response(
|
||||
f"/remote.php/dav/calendars/{USER}/{name}/{uid}.ics",
|
||||
f'<d:getetag>"etag-{uid}"</d:getetag>'
|
||||
f"<c:calendar-data>{_xml_escape(ics)}</c:calendar-data>",
|
||||
)
|
||||
)
|
||||
return 207, self._xml(responses), "application/xml", {}
|
||||
return 405, b"method not allowed", "text/plain", {}
|
||||
uid = leaf[:-4] if leaf.endswith(".ics") else leaf
|
||||
if method == "PUT":
|
||||
calendar["objects"][uid] = body.decode("utf-8")
|
||||
return 201, b"", "text/plain", {"ETag": f'"etag-{uid}"'}
|
||||
if method == "GET":
|
||||
ics = calendar["objects"].get(uid)
|
||||
if ics is None:
|
||||
return 404, b"not found", "text/plain", {}
|
||||
return 200, ics.encode(), "text/calendar", {"ETag": f'"etag-{uid}"'}
|
||||
if method == "DELETE":
|
||||
calendar["objects"].pop(uid, None)
|
||||
return 204, b"", "text/plain", {}
|
||||
return 405, b"method not allowed", "text/plain", {}
|
||||
|
||||
# ---- contacts ----
|
||||
|
||||
def _addressbook_home(self):
|
||||
responses = [
|
||||
self._response(
|
||||
f"/remote.php/dav/addressbooks/users/{USER}/",
|
||||
"<d:resourcetype><d:collection/></d:resourcetype>"
|
||||
f"<d:displayname>{USER}</d:displayname>",
|
||||
)
|
||||
]
|
||||
for name, book in self.addressbooks.items():
|
||||
responses.append(
|
||||
self._response(
|
||||
f"/remote.php/dav/addressbooks/users/{USER}/{name}/",
|
||||
"<d:resourcetype><d:collection/><card:addressbook/></d:resourcetype>"
|
||||
f"<d:displayname>{book['label']}</d:displayname>"
|
||||
"<card:addressbook-description>d</card:addressbook-description>",
|
||||
)
|
||||
)
|
||||
return self._xml(responses)
|
||||
|
||||
def _addressbooks(self, method, route, body):
|
||||
rest = route[len("/remote.php/dav/addressbooks/") :]
|
||||
parts = rest.split("/")
|
||||
tail = _norm("/".join(parts[2:]) if len(parts) > 2 else "/")
|
||||
if tail == "/":
|
||||
if method == "PROPFIND":
|
||||
return 207, self._addressbook_home(), "application/xml", {}
|
||||
return 405, b"method not allowed", "text/plain", {}
|
||||
name, _, leaf = tail.lstrip("/").partition("/")
|
||||
book = self.addressbooks.get(name)
|
||||
if book is None:
|
||||
return 404, b"not found", "text/plain", {}
|
||||
if not leaf:
|
||||
if method == "REPORT":
|
||||
responses = []
|
||||
for uid, vcf in book["cards"].items():
|
||||
responses.append(
|
||||
self._response(
|
||||
f"/remote.php/dav/addressbooks/users/{USER}/{name}/{uid}.vcf",
|
||||
f'<d:getetag>"etag-{uid}"</d:getetag>'
|
||||
f"<card:address-data>{_xml_escape(vcf)}</card:address-data>",
|
||||
)
|
||||
)
|
||||
return 207, self._xml(responses), "application/xml", {}
|
||||
return 405, b"method not allowed", "text/plain", {}
|
||||
uid = leaf[:-4] if leaf.endswith(".vcf") else leaf
|
||||
if method == "PUT":
|
||||
book["cards"][uid] = body.decode("utf-8")
|
||||
return 201, b"", "text/plain", {"ETag": f'"etag-{uid}"'}
|
||||
if method == "GET":
|
||||
vcf = book["cards"].get(uid)
|
||||
if vcf is None:
|
||||
return 404, b"not found", "text/plain", {}
|
||||
return 200, vcf.encode(), "text/vcard", {"ETag": f'"etag-{uid}"'}
|
||||
if method == "DELETE":
|
||||
book["cards"].pop(uid, None)
|
||||
return 204, b"", "text/plain", {}
|
||||
return 405, b"method not allowed", "text/plain", {}
|
||||
|
||||
# ---- OCS (notes + info) ----
|
||||
|
||||
def _ocs_json(self, data, status=200):
|
||||
return status, json.dumps({"ocs": {"meta": {"statuscode": 200}, "data": data}}).encode(), "application/json", {}
|
||||
|
||||
def _ocs(self, method, route, body):
|
||||
if route == "/ocs/v2.php/cloud/user":
|
||||
return self._ocs_json(
|
||||
{"id": USER, "display-name": "Alice", "email": "alice@example.com"}
|
||||
)
|
||||
if route == "/ocs/v2.php/cloud/capabilities":
|
||||
return self._ocs_json({"version": {"major": 28}})
|
||||
prefix = "/ocs/v2.php/apps/notes/api/v1/notes"
|
||||
if route == prefix:
|
||||
if method == "GET":
|
||||
return self._ocs_json(list(self.notes.values()))
|
||||
if method == "POST":
|
||||
payload = json.loads(body.decode() or "{}")
|
||||
note_id = self._next_note_id
|
||||
self._next_note_id += 1
|
||||
note = {"id": note_id, "title": payload.get("title", ""),
|
||||
"content": payload.get("content", ""),
|
||||
"category": payload.get("category", "")}
|
||||
self.notes[note_id] = note
|
||||
return self._ocs_json(note)
|
||||
if route.startswith(prefix + "/"):
|
||||
note_id = int(route.rsplit("/", 1)[-1])
|
||||
note = self.notes.get(note_id)
|
||||
if note is None:
|
||||
return 404, b'{"ocs":{"meta":{"statuscode":404},"data":[]}}', "application/json", {}
|
||||
if method == "GET":
|
||||
return self._ocs_json(note)
|
||||
if method == "PUT":
|
||||
payload = json.loads(body.decode() or "{}")
|
||||
note.update({k: v for k, v in payload.items() if v is not None})
|
||||
return self._ocs_json(note)
|
||||
if method == "DELETE":
|
||||
self.notes.pop(note_id, None)
|
||||
return self._ocs_json([])
|
||||
return 404, b"not found", "text/plain", {}
|
||||
|
||||
|
||||
def _xml_escape(text):
|
||||
return (
|
||||
text.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def nextcloud():
|
||||
fake = FakeNextcloud()
|
||||
base = fake.start()
|
||||
try:
|
||||
yield fake, base
|
||||
finally:
|
||||
fake.stop()
|
||||
|
||||
|
||||
def make_client(base, **kwargs):
|
||||
return NextcloudClient(base, USER, PASSWORD, **kwargs)
|
||||
|
||||
|
||||
# ---- client: files ----
|
||||
|
||||
|
||||
def test_client_sends_basic_auth(nextcloud):
|
||||
fake, base = nextcloud
|
||||
make_client(base).list_files("/")
|
||||
assert fake.calls, "the server must have received a request"
|
||||
header = fake.calls[0][2].get("Authorization")
|
||||
assert header == "Basic " + base64.b64encode(f"{USER}:{PASSWORD}".encode()).decode()
|
||||
|
||||
|
||||
def test_list_files_parses_entries(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
result = make_client(base).list_files("/")
|
||||
assert result["path"] == "/"
|
||||
names = {entry["name"]: entry for entry in result["entries"]}
|
||||
assert names["Documents"]["type"] == "dir"
|
||||
assert names["image.png"]["type"] == "file"
|
||||
assert names["image.png"]["size"] == len(b"\x89PNG\x00\xff")
|
||||
assert names["image.png"]["etag"] == '"etag-image.png"'
|
||||
# Directories sort before files.
|
||||
assert result["entries"][0]["type"] == "dir"
|
||||
|
||||
|
||||
def test_list_files_of_a_subfolder(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
result = make_client(base).list_files("/Documents")
|
||||
assert [entry["name"] for entry in result["entries"]] == ["readme.txt"]
|
||||
|
||||
|
||||
def test_stat_returns_one_entry(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
entry = make_client(base).stat("/Documents/readme.txt")
|
||||
assert entry["type"] == "file"
|
||||
assert entry["size"] == 11
|
||||
|
||||
|
||||
def test_read_text_file(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
result = make_client(base).read_file("/Documents/readme.txt")
|
||||
assert result["encoding"] == "utf-8"
|
||||
assert result["content"] == "hello world"
|
||||
|
||||
|
||||
def test_read_binary_file_is_base64(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
result = make_client(base).read_file("/image.png")
|
||||
assert result["encoding"] == "base64"
|
||||
assert base64.b64decode(result["content"]) == b"\x89PNG\x00\xff"
|
||||
|
||||
|
||||
def test_write_file_round_trip(nextcloud):
|
||||
fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
assert client.write_file("/new.txt", "content", overwrite=False)["ok"] is True
|
||||
put = [call for call in fake.calls if call[0] == "PUT"][0]
|
||||
assert put[2].get("If-None-Match") == "*"
|
||||
assert client.read_file("/new.txt")["content"] == "content"
|
||||
|
||||
|
||||
def test_write_file_base64(nextcloud):
|
||||
fake, base = nextcloud
|
||||
make_client(base).write_file("/bin.dat", base64.b64encode(b"\x00\x01").decode(), encoding="base64")
|
||||
assert fake.files["/bin.dat"]["content"] == b"\x00\x01"
|
||||
|
||||
|
||||
def test_write_file_rejects_bad_base64(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
with pytest.raises(ValueError):
|
||||
make_client(base).write_file("/bin.dat", "not base64!", encoding="base64")
|
||||
|
||||
|
||||
def test_mkdir_and_delete(nextcloud):
|
||||
fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
client.mkdir("/NewFolder")
|
||||
assert fake.files["/NewFolder"]["type"] == "dir"
|
||||
client.delete("/NewFolder")
|
||||
assert "/NewFolder" not in fake.files
|
||||
|
||||
|
||||
def test_move_sends_destination_header(nextcloud):
|
||||
fake, base = nextcloud
|
||||
result = make_client(base).move("/Documents/readme.txt", "/Documents/renamed.txt", overwrite=True)
|
||||
assert result["destination"] == "/Documents/renamed.txt"
|
||||
move = [call for call in fake.calls if call[0] == "MOVE"][0]
|
||||
assert move[2]["Destination"].endswith("/remote.php/dav/files/alice/Documents/renamed.txt")
|
||||
assert move[2]["Overwrite"] == "T"
|
||||
|
||||
|
||||
def test_copy_sends_destination_header(nextcloud):
|
||||
fake, base = nextcloud
|
||||
make_client(base).copy("/Documents/readme.txt", "/Documents/copy.txt")
|
||||
copy = [call for call in fake.calls if call[0] == "COPY"][0]
|
||||
assert copy[2]["Overwrite"] == "F"
|
||||
|
||||
|
||||
def test_search_returns_matching_files(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
results = make_client(base).search("readme")
|
||||
assert [entry["name"] for entry in results] == ["readme.txt"]
|
||||
|
||||
|
||||
# ---- client: calendars ----
|
||||
|
||||
|
||||
def test_list_calendars(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
calendars = make_client(base).list_calendars()
|
||||
assert calendars == [
|
||||
{
|
||||
"name": "personal",
|
||||
"label": "Personal",
|
||||
"description": "desc",
|
||||
"color": "#ff0000",
|
||||
"ctag": "ctag-1",
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def test_create_and_list_event(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
created = client.create_event(
|
||||
"personal",
|
||||
"uid-1",
|
||||
"Lunch with Dana",
|
||||
"2026-03-01T12:00:00+00:00",
|
||||
end="2026-03-01T13:00:00+00:00",
|
||||
location="Cafe",
|
||||
)
|
||||
assert created["uid"] == "uid-1"
|
||||
events = client.list_events("personal")
|
||||
assert len(events) == 1
|
||||
event = events[0]
|
||||
assert event["summary"] == "Lunch with Dana"
|
||||
assert event["location"] == "Cafe"
|
||||
assert event["start"] == "2026-03-01T12:00:00+00:00"
|
||||
assert event["all_day"] is False
|
||||
assert event["uid"] == "uid-1"
|
||||
|
||||
|
||||
def test_all_day_event_parses(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
client.create_event("personal", "u2", "Holiday", "2026-07-04", end="2026-07-05", all_day=True)
|
||||
event = client.list_events("personal")[0]
|
||||
assert event["all_day"] is True
|
||||
assert event["start"] == "2026-07-04"
|
||||
|
||||
|
||||
def test_create_event_sends_if_none_match(nextcloud):
|
||||
fake, base = nextcloud
|
||||
make_client(base).create_event("personal", "u3", "X", "2026-03-01T12:00:00Z")
|
||||
put = [call for call in fake.calls if call[0] == "PUT"][0]
|
||||
assert put[2].get("If-None-Match") == "*"
|
||||
|
||||
|
||||
def test_update_event_preserves_other_properties(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
client.create_event(
|
||||
"personal", "u4", "Original", "2026-03-01T12:00:00Z",
|
||||
end="2026-03-01T13:00:00Z", location="Office",
|
||||
)
|
||||
client.update_event("personal", "u4", summary="Renamed")
|
||||
event = client.list_events("personal")[0]
|
||||
assert event["summary"] == "Renamed"
|
||||
assert event["location"] == "Office", "unchanged properties must survive an update"
|
||||
assert event["start"] == "2026-03-01T12:00:00+00:00"
|
||||
|
||||
|
||||
def test_update_event_uses_if_match(nextcloud):
|
||||
fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
client.create_event("personal", "u5", "X", "2026-03-01T12:00:00Z")
|
||||
client.update_event("personal", "u5", summary="Y")
|
||||
put = [call for call in fake.calls if call[0] == "PUT"][-1]
|
||||
assert put[2].get("If-Match") == '"etag-u5"'
|
||||
|
||||
|
||||
def test_delete_event(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
client.create_event("personal", "u6", "X", "2026-03-01T12:00:00Z")
|
||||
assert client.delete_object("personal", "u6")["ok"] is True
|
||||
assert client.list_events("personal") == []
|
||||
|
||||
|
||||
def test_update_missing_event_is_a_real_failure(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
with pytest.raises(NextcloudError) as exc:
|
||||
make_client(base).update_event("personal", "ghost", summary="X")
|
||||
assert exc.value.status == 404
|
||||
|
||||
|
||||
# ---- client: tasks ----
|
||||
|
||||
|
||||
def test_create_and_list_task(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
client.create_task("personal", "t1", "Buy milk", due="2026-03-02T09:00:00Z", priority=1)
|
||||
tasks = client.list_tasks("personal")
|
||||
assert len(tasks) == 1
|
||||
task = tasks[0]
|
||||
assert task["summary"] == "Buy milk"
|
||||
assert task["status"] == "NEEDS-ACTION"
|
||||
assert task["priority"] == 1
|
||||
assert task["due"] == "2026-03-02T09:00:00+00:00"
|
||||
|
||||
|
||||
def test_complete_task(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
client.create_task("personal", "t2", "Do it")
|
||||
client.complete_task("personal", "t2")
|
||||
task = client.list_tasks("personal")[0]
|
||||
assert task["status"] == "COMPLETED"
|
||||
assert task["percent_complete"] == 100
|
||||
|
||||
|
||||
# ---- client: contacts ----
|
||||
|
||||
|
||||
def test_list_addressbooks(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
assert make_client(base).list_addressbooks() == [
|
||||
{"name": "contacts", "label": "Contacts", "description": "d"}
|
||||
]
|
||||
|
||||
|
||||
def test_create_and_list_contact(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
client.create_contact(
|
||||
"contacts", "c1", fn="Dana Lee", emails=["dana@example.com"], phones=["555-1234"], org="Acme"
|
||||
)
|
||||
contacts = client.list_contacts("contacts")
|
||||
assert len(contacts) == 1
|
||||
contact = contacts[0]
|
||||
assert contact["fn"] == "Dana Lee"
|
||||
assert contact["emails"] == ["dana@example.com"]
|
||||
assert contact["phones"] == ["555-1234"]
|
||||
assert contact["org"] == "Acme"
|
||||
|
||||
|
||||
def test_contact_query_filters(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
client.create_contact("contacts", "c2", fn="Dana Lee", emails=["dana@example.com"])
|
||||
client.create_contact("contacts", "c3", fn="Sam Ray", emails=["sam@example.com"])
|
||||
assert [c["fn"] for c in client.list_contacts("contacts", "dana")] == ["Dana Lee"]
|
||||
assert [c["fn"] for c in client.list_contacts("contacts", "nobody")] == []
|
||||
|
||||
|
||||
def test_update_contact_changes_only_named_fields(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
client.create_contact("contacts", "c4", fn="Old", emails=["old@example.com"])
|
||||
client.update_contact("contacts", "c4", fn="New")
|
||||
contact = client.list_contacts("contacts")[0]
|
||||
assert contact["fn"] == "New"
|
||||
assert contact["emails"] == ["old@example.com"]
|
||||
|
||||
|
||||
def test_delete_contact(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
client.create_contact("contacts", "c5", fn="Gone")
|
||||
client.delete_contact("contacts", "c5")
|
||||
assert client.list_contacts("contacts") == []
|
||||
|
||||
|
||||
# ---- client: notes + info ----
|
||||
|
||||
|
||||
def test_user_info(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
assert make_client(base).user_info()["display_name"] == "Alice"
|
||||
|
||||
|
||||
def test_capabilities(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
assert make_client(base).capabilities()["version"]["major"] == 28
|
||||
|
||||
|
||||
def test_notes_crud(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
client = make_client(base)
|
||||
created = client.create_note("Shopping", "milk, eggs", category="Home")
|
||||
note_id = created["id"]
|
||||
assert client.list_notes()[0]["title"] == "Shopping"
|
||||
assert client.get_note(note_id)["content"] == "milk, eggs"
|
||||
updated = client.update_note(note_id, content="milk")
|
||||
assert updated["content"] == "milk"
|
||||
assert client.delete_note(note_id)["ok"] is True
|
||||
assert client.list_notes() == []
|
||||
|
||||
|
||||
# ---- client: failure mapping ----
|
||||
|
||||
|
||||
def test_http_error_carries_status(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
with pytest.raises(NextcloudError) as exc:
|
||||
make_client(base).read_file("/missing.txt")
|
||||
assert exc.value.status == 404
|
||||
|
||||
|
||||
def test_unconfigured_client_is_not_configured():
|
||||
assert NextcloudClient("", "", "").configured is False
|
||||
assert NextcloudClient("https://cloud", "alice", "pw").configured is True
|
||||
|
||||
|
||||
# ---- bridge routes (real client over loopback) ----
|
||||
|
||||
|
||||
def bridge_for(base, **config):
|
||||
return NextcloudBridge({"url": base, "username": USER, "app_password": PASSWORD, **config})
|
||||
|
||||
|
||||
def test_bridge_health():
|
||||
bridge = NextcloudBridge({})
|
||||
assert bridge.handle_get("/health", {}) == (200, {"ok": True, "platform": "nextcloud"})
|
||||
|
||||
|
||||
def test_bridge_unconfigured_is_503():
|
||||
bridge = NextcloudBridge({})
|
||||
status, payload = bridge.handle_get("/files", {})
|
||||
assert status == 503
|
||||
assert "configured" in payload["error"]
|
||||
|
||||
|
||||
def test_bridge_lists_files(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
status, payload = bridge_for(base).handle_get("/files", {"path": ["/Documents"]})
|
||||
assert status == 200
|
||||
assert [entry["name"] for entry in payload["entries"]] == ["readme.txt"]
|
||||
|
||||
|
||||
def test_bridge_create_event(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
status, payload = bridge_for(base, default_calendar="personal").handle_post(
|
||||
"/calendars/events",
|
||||
{"summary": "Sync", "start": "2026-03-01T12:00:00Z"},
|
||||
)
|
||||
assert status == 200
|
||||
assert payload["ok"] is True and payload["calendar"] == "personal"
|
||||
assert payload["uid"]
|
||||
|
||||
|
||||
def test_bridge_create_event_requires_summary(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
status, payload = bridge_for(base, default_calendar="personal").handle_post(
|
||||
"/calendars/events", {"start": "2026-03-01T12:00:00Z"}
|
||||
)
|
||||
assert status == 400
|
||||
assert "summary" in payload["error"]
|
||||
|
||||
|
||||
def test_bridge_requires_calendar_when_ambiguous(nextcloud):
|
||||
fake, base = nextcloud
|
||||
fake.calendars["work"] = {"label": "Work", "objects": {}}
|
||||
status, payload = bridge_for(base).handle_post(
|
||||
"/calendars/events", {"summary": "X", "start": "2026-03-01T12:00:00Z"}
|
||||
)
|
||||
assert status == 400
|
||||
assert "calendar is required" in payload["error"]
|
||||
|
||||
|
||||
def test_bridge_uses_only_calendar_when_unset(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
status, payload = bridge_for(base).handle_post(
|
||||
"/calendars/events", {"summary": "Only", "start": "2026-03-01T12:00:00Z"}
|
||||
)
|
||||
assert status == 200 and payload["calendar"] == "personal"
|
||||
|
||||
|
||||
def test_bridge_maps_nextcloud_error_to_502(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
status, payload = bridge_for(base).handle_get("/files/read", {"path": ["/missing.txt"]})
|
||||
assert status == 502
|
||||
assert "404" in payload["error"]
|
||||
|
||||
|
||||
def test_bridge_notes_create_and_get(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
bridge = bridge_for(base)
|
||||
status, payload = bridge.handle_post("/notes", {"title": "T", "content": "C"})
|
||||
assert status == 200
|
||||
note_id = payload["note"]["id"]
|
||||
status, payload = bridge.handle_get("/notes/get", {"id": [str(note_id)]})
|
||||
assert status == 200 and payload["note"]["title"] == "T"
|
||||
|
||||
|
||||
def test_bridge_rejects_bad_types(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
bridge = bridge_for(base, default_calendar="personal")
|
||||
status, payload = bridge.handle_post(
|
||||
"/calendars/events", {"summary": "X", "start": "2026-01-01T00:00:00Z", "all_day": "yes"}
|
||||
)
|
||||
assert status == 400
|
||||
status, payload = bridge.handle_post("/files/write", {"path": "/x", "content": "c", "overwrite": 1})
|
||||
assert status == 400
|
||||
|
||||
|
||||
def test_bridge_token_guard(nextcloud):
|
||||
_fake, base = nextcloud
|
||||
bridge = bridge_for(base, token="sekret")
|
||||
port = bridge.start()
|
||||
try:
|
||||
with pytest.raises(urllib.error.HTTPError) as exc:
|
||||
urllib.request.urlopen(f"http://127.0.0.1:{port}/files?path=/", timeout=5)
|
||||
assert exc.value.code == 401
|
||||
request = urllib.request.Request(
|
||||
f"http://127.0.0.1:{port}/health", headers={"X-Semif-Token": "sekret"}
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=5) as response:
|
||||
assert json.loads(response.read()) == {"ok": True, "platform": "nextcloud"}
|
||||
finally:
|
||||
bridge.stop()
|
||||
|
||||
|
||||
def test_bridge_falls_back_to_top_level_config():
|
||||
bridge = build_bridge(
|
||||
{
|
||||
"nextcloud_url": "https://cloud.example.com",
|
||||
"nextcloud_username": "bob",
|
||||
"nextcloud_app_password": "pw",
|
||||
"nextcloud_default_calendar": "work",
|
||||
},
|
||||
"nextcloud",
|
||||
)
|
||||
assert isinstance(bridge, NextcloudBridge)
|
||||
assert bridge.url == "https://cloud.example.com"
|
||||
assert bridge.username == "bob"
|
||||
assert bridge.app_password == "pw"
|
||||
assert bridge.default_calendar == "work"
|
||||
|
||||
|
||||
def test_bridge_block_overrides_top_level():
|
||||
bridge = build_bridge(
|
||||
{
|
||||
"nextcloud_url": "https://fallback.example.com",
|
||||
"nextcloud_username": "fallback",
|
||||
"bridges": {"nextcloud": {"url": "https://block.example.com", "username": "block"}},
|
||||
},
|
||||
"nextcloud",
|
||||
)
|
||||
assert bridge.url == "https://block.example.com"
|
||||
assert bridge.username == "block"
|
||||
|
||||
|
||||
# ---- fake-client route tests ----
|
||||
|
||||
|
||||
class FakeClient:
|
||||
configured = True
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
self.calendars = [{"name": "personal", "label": "Personal"}]
|
||||
|
||||
def list_calendars(self):
|
||||
return self.calendars
|
||||
|
||||
def create_event(self, calendar, uid, **fields):
|
||||
self.calls.append(("create_event", calendar, uid, fields))
|
||||
return {"ok": True, "uid": uid, "calendar": calendar, "etag": ""}
|
||||
|
||||
def write_file(self, path, content, encoding, overwrite):
|
||||
self.calls.append(("write_file", path, content, encoding, overwrite))
|
||||
return {"ok": True, "path": path}
|
||||
|
||||
|
||||
def test_bridge_passes_encoding_and_overwrite_through():
|
||||
client = FakeClient()
|
||||
bridge = NextcloudBridge({"url": "x", "username": "u", "app_password": "p"}, client=client)
|
||||
status, payload = bridge.handle_post(
|
||||
"/files/write",
|
||||
{"path": "/x", "content": "ZGF0YQ==", "encoding": "base64", "overwrite": False},
|
||||
)
|
||||
assert status == 200
|
||||
assert client.calls == [("write_file", "/x", "ZGF0YQ==", "base64", False)]
|
||||
|
||||
|
||||
def test_bridge_generates_uid_when_absent():
|
||||
client = FakeClient()
|
||||
bridge = NextcloudBridge({"url": "x", "username": "u", "app_password": "p"}, client=client)
|
||||
status, payload = bridge.handle_post(
|
||||
"/calendars/events", {"summary": "X", "start": "2026-01-01T00:00:00Z"}
|
||||
)
|
||||
assert status == 200
|
||||
assert payload["uid"]
|
||||
assert client.calls[0][1] == "personal"
|
||||
|
||||
|
||||
# ---- catalog / codegen surface ----
|
||||
|
||||
|
||||
def test_known_infos_include_nextcloud():
|
||||
infos = {info.name: info for info in known_infos()}
|
||||
assert "nextcloud" in infos
|
||||
info = infos["nextcloud"]
|
||||
assert info.url_config_var == "nextcloud_bridge_url"
|
||||
assert info.auth_header == "X-Semif-Token"
|
||||
assert info.auth_config_var == "nextcloud_bridge_token"
|
||||
|
||||
|
||||
def test_describe_bridges_renders_nextcloud():
|
||||
text = describe_bridges()
|
||||
assert "service: nextcloud" in text
|
||||
assert "nextcloud_bridge_url" in text
|
||||
assert "/calendars/events" in text
|
||||
assert "/files/read" in text
|
||||
assert "/notes" in text
|
||||
|
||||
|
||||
def test_nextcloud_bridge_check_requirements_is_stdlib():
|
||||
ok, hint = NextcloudBridge({}).check_requirements()
|
||||
assert ok is True and hint is None
|
||||
Reference in new issue
Block a user