bridges: add a Nextcloud bridge (files, calendars, tasks, contacts, notes)

A standalone bridge wrapping the account's native protocols — WebDAV files,
CalDAV events and tasks, CardDAV contacts, and the OCS Notes API — behind one
token-guarded localhost JSON surface, so a codegen-authored body never speaks
DAV/OCS directly.

- nextcloud_client.py: stdlib-only client (urllib + xml.etree + ssl + base64)
  with Basic auth, DAV/OCS request bodies, and minimal iCalendar/vCard build +
  parse; every failure is a NextcloudError carrying the HTTP status.
- nextcloud.py: NextcloudBridge with no service daemon (check_requirements is
  always (True, None)), ~35 routes (GET reads, POST mutations). Event/task
  updates edit the stored iCalendar in place (preserving VALARM/ATTENDEE) behind
  If-Match; creates use If-None-Match. Missing connection is 503; a real
  Nextcloud failure is 502, never a fabricated success.
- registry: CATALOG entry + build_bridge passes the top-level nextcloud_* values
  as a fallback so the account the calendar seeds collect is configured once.
- config.example.json: bridges.nextcloud block + nextcloud_bridge_url/token.
- docs: README, AGENTS, bridges/__init__, bootstrap closing notes.

Tests drive the real client over a loopback http.server faking Nextcloud's
DAV/OCS shapes. One codegen test's context window was raised because the bridge
catalog injected into every prompt grew the baseline prompt.
This commit is contained in:
gabby committed 2026-10-07 12:17:39 +00:00
1 parent e64354e78d
commit d9cc7e4fed
10 files changed
+2819 -14

No files matched your search

+42 -4
View File
@@ -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
@@ -1287,6 +1293,35 @@ CLI, unit tests (24) + integration tests (2).
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 top-level `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)
@@ -1324,9 +1359,12 @@ The bridge read path (`simplex.next_message`) and contact-link lookup
(threaded through `run_bridges`/`build_bridge`, never re-configured), registered
in `CATALOG` and seeded under `bridges.llm` + top-level `llm_bridge_url`.
`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
+46 -4
View File
@@ -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
@@ -516,6 +516,8 @@ Key blocks:
| `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) |
| `nextcloud_bridge_url` / `nextcloud_bridge_token` | what skill bodies call for Nextcloud |
| `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) |
| `dashboard` | bind host/port |
@@ -684,9 +686,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:
@@ -728,6 +731,45 @@ carries just the local listener. Skills call it via `llm_bridge_url`
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 via `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
```sh
+16
View File
@@ -121,6 +121,8 @@
"simplex_bridge_token": "",
"llm_bridge_url": "http://127.0.0.1:5229",
"llm_bridge_token": "",
"nextcloud_bridge_url": "http://127.0.0.1:5230",
"nextcloud_bridge_token": "",
"log": "data/decisions.jsonl",
"trace": "data/runs.jsonl",
"category_registry": "data/categories.json",
@@ -151,6 +153,20 @@
"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 use the top-level `nextcloud_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.",
"enabled": true,
"host": "127.0.0.1",
"port": 5230,
"token": "",
"url": "",
"username": "",
"app_password": "",
"default_calendar": "",
"default_addressbook": "",
"verify_tls": true,
"timeout": 30
}
},
"gateway": {
+7
View File
@@ -624,6 +624,13 @@ 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).
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 via the
top-level nextcloud_bridge_url (default http://127.0.0.1:5230).
EOF
if [[ "$VOICE" = 1 ]]; then
+3 -3
View File
@@ -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.
+501
View File
@@ -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
+17 -2
View File
@@ -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:
@@ -75,7 +76,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 +86,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)
+4 -1
View File
@@ -1559,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,
+954
View File
@@ -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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
)
@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