skills: route create_event/next_event through the bridge

Both skills spoke CalDAV directly and declared the account as flat contract
vars (nextcloud_url/username/app_password/default_calendar). Bootstrap now
stores the account under bridges.nextcloud and only the derived
nextcloud_bridge_url/_token reach ctx.config, so the runner asked for the URL
and credentials on first fire.

Call the bridge instead, like create_task:
- create_event: GET /calendars -> SemIf choice -> POST /calendars/events
- next_event:  GET /calendars -> SemIf choice -> GET /calendars/events

The bridge gains two small affordances so the skills keep their behavior:
- GET /calendars also returns the configured default calendar name
- GET /calendars/events expands recurrences server-side when given a window
This commit is contained in:
gabby committed 2026-10-14 04:25:54 +00:00
1 parent ace251a829
commit 1a1d28dffd
9 files changed
+486 -748

No files matched your search

+12 -7
View File
@@ -9,10 +9,10 @@ token-guarded localhost JSON API, so a body only reads `nextcloud_bridge_url` an
There is no service daemon: Nextcloud is plain HTTPS, so the bridge is stdlib-only 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 (`urllib` + `xml.etree`) and starts instantly. The connection comes from
`bridges.nextcloud` (url/username/app_password/default_calendar/default_addressbook), `bridges.nextcloud` (url/username/app_password/default_calendar/default_addressbook);
falling back to the top-level `nextcloud_url`/`nextcloud_username`/ `from_config` also accepts the top-level `nextcloud_url`/`nextcloud_username`/
`nextcloud_app_password`/`nextcloud_default_calendar` values the nextcloud pack's skills `nextcloud_app_password`/`nextcloud_default_calendar` values as a fallback for a
already use, so the same account is configured in one place. hand-edited config, so the same account is configured in one place.
The actual DAV/OCS work lives in `nextcloud_client.py`; the routes here validate 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 input and map a real failure (`NextcloudError`) to a 502 rather than a fabricated
@@ -101,7 +101,8 @@ class NextcloudBridge(BridgeService):
"POST /files/copy {\"path\", \"destination\", \"overwrite\"?: bool} " "POST /files/copy {\"path\", \"destination\", \"overwrite\"?: bool} "
"-> 200 {\"ok\": true, \"path\", \"destination\"}", "-> 200 {\"ok\": true, \"path\", \"destination\"}",
"GET /calendars -> 200 {\"calendars\": [{name, label, description, " "GET /calendars -> 200 {\"calendars\": [{name, label, description, "
"color, ctag, components}]} — components lists the CalDAV component " "color, ctag, components}], \"default\": \"<configured default "
"calendar name, or empty>\"} — components lists the CalDAV component "
"types each collection accepts (VEVENT, VTODO, VJOURNAL)", "types each collection accepts (VEVENT, VTODO, VJOURNAL)",
"GET /tasklists -> 200 {\"tasklists\": [{name, label, description, " "GET /tasklists -> 200 {\"tasklists\": [{name, label, description, "
"color, ctag, components}]} — the user's task lists (calendars that " "color, ctag, components}]} — the user's task lists (calendars that "
@@ -110,7 +111,8 @@ class NextcloudBridge(BridgeService):
"GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> -> 200 " "GET /calendars/events?calendar=<name>&start=<iso>&end=<iso> -> 200 "
"{\"calendar\", \"events\": [{uid, summary, start, end, all_day, " "{\"calendar\", \"events\": [{uid, summary, start, end, all_day, "
"location, description, rrule, status, href, etag}]} — start/end " "location, description, rrule, status, href, etag}]} — start/end "
"optional (ISO 8601); without them every event is returned", "optional (ISO 8601); with both given, recurring events are expanded "
"server-side across the window; without them every event is returned",
"POST /calendars/events {\"calendar\"?, \"uid\"?, \"summary\", " "POST /calendars/events {\"calendar\"?, \"uid\"?, \"summary\", "
"\"start\", \"end\"?, \"all_day\"?, \"location\"?, \"description\"?, " "\"start\", \"end\"?, \"all_day\"?, \"location\"?, \"description\"?, "
"\"rrule\"?, \"overwrite\"?} -> 200 {\"ok\": true, \"uid\", " "\"rrule\"?, \"overwrite\"?} -> 200 {\"ok\": true, \"uid\", "
@@ -286,7 +288,10 @@ class NextcloudBridge(BridgeService):
) )
} }
if path == "/calendars": if path == "/calendars":
return 200, {"calendars": self.client.list_calendars()} return 200, {
"calendars": self.client.list_calendars(),
"default": self.default_calendar,
}
if path == "/tasklists": if path == "/tasklists":
return 200, {"tasklists": self._task_lists()} return 200, {"tasklists": self._task_lists()}
if path == "/calendars/events": if path == "/calendars/events":
+11 -1
View File
@@ -504,11 +504,21 @@ def _calendar_query_body(component: str, start: str = "", end: str = "") -> byte
if end: if end:
attrs += f' end="{_stamp(_parse_dt(end))}"' attrs += f' end="{_stamp(_parse_dt(end))}"'
time_range = f"<c:time-range{attrs}/>" time_range = f"<c:time-range{attrs}/>"
# With a bounded window, ask the server to expand recurrences into their
# instances (matching a `next event` read); `<c:expand>` needs both bounds.
calendar_data = "<c:calendar-data/>"
if start and end:
calendar_data = (
"<c:calendar-data>"
f'<c:expand start="{_stamp(_parse_dt(start))}" '
f'end="{_stamp(_parse_dt(end))}"/>'
"</c:calendar-data>"
)
return ( return (
'<?xml version="1.0"?>' '<?xml version="1.0"?>'
'<c:calendar-query xmlns:d="DAV:" ' '<c:calendar-query xmlns:d="DAV:" '
'xmlns:c="urn:ietf:params:xml:ns:caldav">' 'xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop><d:getetag/><c:calendar-data/></d:prop>" f"<d:prop><d:getetag/>{calendar_data}</d:prop>"
"<c:filter><c:comp-filter name=\"VCALENDAR\">" "<c:filter><c:comp-filter name=\"VCALENDAR\">"
f'<c:comp-filter name="{component}">{time_range}</c:comp-filter>' f'<c:comp-filter name="{component}">{time_range}</c:comp-filter>'
"</c:comp-filter></c:filter></c:calendar-query>" "</c:comp-filter></c:filter></c:calendar-query>"
+30
View File
@@ -596,6 +596,26 @@ def test_all_day_event_parses(nextcloud):
assert event["start"] == "2026-07-04" assert event["start"] == "2026-07-04"
def test_list_events_expands_recurrences_when_window_given(nextcloud):
fake, base = nextcloud
make_client(base).list_events(
"personal", "2026-03-01T00:00:00Z", "2026-04-01T00:00:00Z"
)
report = [call for call in fake.calls if call[0] == "REPORT"][-1]
body = report[3].decode("utf-8")
assert "<c:expand" in body, body
assert "c:time-range" in body, body
def test_list_events_without_a_window_does_not_expand(nextcloud):
fake, base = nextcloud
make_client(base).list_events("personal")
report = [call for call in fake.calls if call[0] == "REPORT"][-1]
body = report[3].decode("utf-8")
assert "<c:expand" not in body, body
assert "<c:calendar-data/>" in body, body
def test_create_event_sends_if_none_match(nextcloud): def test_create_event_sends_if_none_match(nextcloud):
fake, base = nextcloud fake, base = nextcloud
make_client(base).create_event("personal", "u3", "X", "2026-03-01T12:00:00Z") make_client(base).create_event("personal", "u3", "X", "2026-03-01T12:00:00Z")
@@ -786,6 +806,16 @@ def test_bridge_lists_files(nextcloud):
assert [entry["name"] for entry in payload["entries"]] == ["readme.txt"] assert [entry["name"] for entry in payload["entries"]] == ["readme.txt"]
def test_bridge_lists_calendars_with_default(nextcloud):
_fake, base = nextcloud
status, payload = bridge_for(base, default_calendar="personal").handle_get(
"/calendars", {}
)
assert status == 200
assert payload["default"] == "personal"
assert [c["name"] for c in payload["calendars"]] == ["personal"]
def test_bridge_create_event(nextcloud): def test_bridge_create_event(nextcloud):
_fake, base = nextcloud _fake, base = nextcloud
status, payload = bridge_for(base, default_calendar="personal").handle_post( status, payload = bridge_for(base, default_calendar="personal").handle_post(
+2 -4
View File
@@ -1,8 +1,6 @@
{ {
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).", "nextcloud_bridge_url": "Base URL of the local Nextcloud bridge, e.g. http://127.0.0.1:5230 (no trailing slash needed); used to list calendars and create the event.",
"nextcloud_username": "The Nextcloud username whose calendars are used.", "nextcloud_bridge_token": "Shared secret for the Nextcloud bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar new events go to by default, e.g. personal (a request may still name another calendar).",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to extract the event title and description.", "llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to extract the event title and description.",
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth." "llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
} }
+120 -220
View File
@@ -1,8 +1,9 @@
"""Create a calendar event on the user's Nextcloud calendar from a request. """Create a calendar event on the user's Nextcloud calendar from a request.
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection Real integration: the Nextcloud bridge over HTTP, which fronts the user's
details and the default calendar come from `ctx.config` (`nextcloud_url`, Nextcloud (CalDAV). The bridge URL/token and the LLM bridge URL/token come from
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`). `ctx.config` (declared in CONTRACT); the account connection and default calendar
live in the bridge's own `bridges.nextcloud` block.
`act` reads `request.text` and derives the event's per-request arguments. The `act` reads `request.text` and derives the event's per-request arguments. The
title and description are extracted by the local LLM bridge (`llm_bridge_url`, title and description are extracted by the local LLM bridge (`llm_bridge_url`,
@@ -11,12 +12,12 @@ title and description are extracted by the local LLM bridge (`llm_bridge_url`,
parsed deterministically. Missing arguments are asked one at a time and the parsed deterministically. Missing arguments are asked one at a time and the
answer is stashed in `request.meta`; because `act` is single-phase and re-runs answer is stashed in `request.meta`; because `act` is single-phase and re-runs
from the top after a `needs_input` pause, the body never re-asks a question it from the top after a `needs_input` pause, the body never re-asks a question it
already has an answer for. Calendars are discovered over PROPFIND and the target already has an answer for. Calendars are listed through the bridge
is resolved by a single SemIf choice over every owned calendar (state = the user (`GET /calendars`) and the target is resolved by a single SemIf choice over every
query), asking which one the request refers to; a strong winner (probability >= owned calendar (state = the user query), asking which one the request refers to;
`CALENDAR_WINNER_TAU`) is used, otherwise the configured default calendar is a strong winner (probability >= `CALENDAR_WINNER_TAU`) is used, otherwise the
used. The event is created with a real CalDAV PUT (iCalendar, UTC timestamps, configured default calendar is used. The event is created for real with
`If-None-Match: *`) and the real outcome is reported. `POST /calendars/events` and the real outcome is reported.
The date/time parse is deliberately bounded; the title/description come from the The date/time parse is deliberately bounded; the title/description come from the
model. When the model bridge is unavailable the body reports the real failure model. When the model bridge is unavailable the body reports the real failure
@@ -25,14 +26,10 @@ rather than guessing.
from __future__ import annotations from __future__ import annotations
import base64
import json import json
import re import re
import urllib.error import urllib.error
import urllib.parse
import urllib.request import urllib.request
import uuid
import xml.etree.ElementTree as ET
from datetime import datetime, time, timedelta, timezone from datetime import datetime, time, timedelta, timezone
from semif_agent.decisions import DecisionRequest, Option from semif_agent.decisions import DecisionRequest, Option
@@ -40,42 +37,28 @@ from semif_agent.skills import ActionResult
from semif_agent.timers import local_now from semif_agent.timers import local_now
INTEGRATION = { INTEGRATION = {
"service": "nextcloud_calendar", "service": "nextcloud",
"transport": "caldav", "transport": "http",
"config_vars": [ "config_vars": [
"nextcloud_url", "nextcloud_bridge_url",
"nextcloud_username", "nextcloud_bridge_token",
"nextcloud_app_password",
"nextcloud_default_calendar",
"llm_bridge_url", "llm_bridge_url",
"llm_bridge_token", "llm_bridge_token",
], ],
} }
CONTRACT = { CONTRACT = {
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).", "nextcloud_bridge_url": "Base URL of the local Nextcloud bridge, e.g. http://127.0.0.1:5230 (no trailing slash needed); used to list calendars and create the event.",
"nextcloud_username": "The Nextcloud username whose calendars are used.", "nextcloud_bridge_token": "Shared secret for the Nextcloud bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar new events go to by default, e.g. personal (a request may still name another calendar).",
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to extract the event title and description.", "llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to extract the event title and description.",
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.", "llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
} }
DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav"
TIMEOUT_SECONDS = 30
DEFAULT_DURATION_MINUTES = 60 DEFAULT_DURATION_MINUTES = 60
# A SemIf probability at or above this counts as a "strong winner" for the # A SemIf probability at or above this counts as a "strong winner" for the
# target calendar; below it the configured default calendar is used instead. # target calendar; below it the configured default calendar is used instead.
CALENDAR_WINNER_TAU = 0.6 CALENDAR_WINNER_TAU = 0.6
PROPFIND_BODY = (
'<?xml version="1.0" encoding="utf-8"?>'
'<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop><d:displayname/><d:resourcetype/></d:prop>"
"</d:propfind>"
).encode("utf-8")
_WEEKDAYS = { _WEEKDAYS = {
"monday": 0, "monday": 0,
"mon": 0, "mon": 0,
@@ -118,13 +101,6 @@ _MONTH_ALT = (
r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?" r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"
) )
class CalDavError(Exception):
"""A real failure talking to the calendar service."""
class BridgeError(Exception):
"""A real failure talking to the local LLM bridge."""
def _now(ctx): def _now(ctx):
"""Current time (aware) in the user's timezone: the top-level `timezone` """Current time (aware) in the user's timezone: the top-level `timezone`
@@ -132,84 +108,33 @@ def _now(ctx):
return local_now(ctx.config) return local_now(ctx.config)
# ---- transport ---- # ---- bridge transport ----
def _request(ctx, method, path, body=None, depth="0", content_type="application/xml; charset=utf-8", extra_headers=None): def _headers(token):
url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/") """Build request headers, sending the bridge token only when one is set."""
username = str(ctx.config.get("nextcloud_username", "") or "").strip() headers = {"Content-Type": "application/json"}
password = str(ctx.config.get("nextcloud_app_password", "") or "") if token:
if not url: headers["X-Semif-Token"] = token
raise CalDavError("nextcloud_url is not configured") return headers
if not username or not password:
raise CalDavError("nextcloud_username and nextcloud_app_password are not configured")
token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii") def _call(method, url, headers, payload=None, timeout=25):
headers = {"Authorization": f"Basic {token}", "Depth": depth} """Perform one HTTP call, returning (status, decoded_json_or_error_dict)."""
if body is not None: data = json.dumps(payload).encode("utf-8") if payload is not None else None
headers["Content-Type"] = content_type req = urllib.request.Request(url, data=data, headers=headers, method=method)
if extra_headers:
headers.update(extra_headers)
request = urllib.request.Request(
url + path, data=body, method=method, headers=headers
)
try: try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response: with urllib.request.urlopen(req, timeout=timeout) as response:
return response.status, response.read() body = response.read().decode("utf-8")
return response.status, (json.loads(body) if body else {})
except urllib.error.HTTPError as exc: except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200] try:
raise CalDavError(f"{method} {path}: HTTP {exc.code} {detail}") from exc detail = json.loads(exc.read().decode("utf-8"))
except (urllib.error.URLError, OSError) as exc: except Exception:
raise CalDavError(f"{method} {path}: {exc}") from exc detail = {"error": str(exc)}
return exc.code, detail
except (urllib.error.URLError, ValueError) as exc:
# ---- CalDAV discovery ---- return None, {"error": str(exc)}
def _multistatus(body):
try:
root = ET.fromstring(body)
except ET.ParseError as exc:
raise CalDavError(f"unparseable CalDAV XML: {exc}") from exc
if root.tag != f"{{{DAV}}}multistatus":
raise CalDavError(f"unexpected CalDAV response root {root.tag!r}")
return root
def _response_prop(response):
return response.find(f"{{{DAV}}}propstat/{{{DAV}}}prop")
def _discover_calendars(ctx):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
if not username:
raise CalDavError("nextcloud_username is not configured")
home = f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
_status, body = _request(ctx, "PROPFIND", home, PROPFIND_BODY, depth="1")
calendars = []
for response in _multistatus(body).findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
resourcetype = prop.find(f"{{{DAV}}}resourcetype")
if resourcetype is None or resourcetype.find(f"{{{CALDAV}}}calendar") is None:
continue
href = response.find(f"{{{DAV}}}href")
path = urllib.parse.urlparse((href.text if href is not None else "") or "").path
name = urllib.parse.unquote(path.rstrip("/").rsplit("/", 1)[-1])
if not name:
continue
display = prop.find(f"{{{DAV}}}displayname")
label = (display.text or "").strip() if display is not None else ""
calendars.append({"name": name, "label": label or name})
return calendars
def _calendar_path(ctx, calendar):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
return (
f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
f"{urllib.parse.quote(calendar)}/"
)
# ---- LLM field extraction ---- # ---- LLM field extraction ----
@@ -219,13 +144,12 @@ def _extract_fields(ctx, request):
"""Ask the LLM bridge for the event title and description. """Ask the LLM bridge for the event title and description.
One generic `POST /chat` call to the local LLM bridge; the reply is the JSON One generic `POST /chat` call to the local LLM bridge; the reply is the JSON
object the prompt asks for. Raises `BridgeError` when the bridge is object the prompt asks for. Returns `(fields, error)`.
unreachable or the reply carries no usable object.
""" """
base = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/") base = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
if not base: if not base:
raise BridgeError("llm_bridge_url is not configured") return None, "llm_bridge_url is not configured"
token = str(ctx.config.get("llm_bridge_token", "") or "").strip() headers = _headers(ctx.config.get("llm_bridge_token", ""))
messages = [ messages = [
{ {
"role": "system", "role": "system",
@@ -238,41 +162,40 @@ def _extract_fields(ctx, request):
}, },
{"role": "user", "content": request.text}, {"role": "user", "content": request.text},
] ]
payload = json.dumps({"messages": messages}).encode("utf-8") status, payload = _call(
headers = {"Content-Type": "application/json"} "POST", f"{base}/chat", headers, {"messages": messages, "max_tokens": 200}
if token:
headers["X-Semif-Token"] = token
http_request = urllib.request.Request(
base + "/chat", data=payload, method="POST", headers=headers
) )
if status != 200:
return (
None,
f"llm bridge /chat: status {status}, {payload.get('error', payload)}",
)
try: try:
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response: return _parse_fields(str(payload.get("text") or "")), None
data = json.loads(response.read().decode("utf-8")) except ValueError as exc:
except urllib.error.HTTPError as exc: return None, str(exc)
detail = exc.read().decode("utf-8", "replace").strip()[:200]
raise BridgeError(f"llm bridge /chat: HTTP {exc.code} {detail}") from exc
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise BridgeError(f"llm bridge /chat: {exc}") from exc
return _parse_fields(str(data.get("text") or ""))
def _parse_fields(text): def _parse_fields(text):
"""Pull the `{"title","description"}` object out of the model's reply.""" """Pull the `{"title","description"}` object out of the model's reply."""
start, end = text.find("{"), text.rfind("}") start, end = text.find("{"), text.rfind("}")
if start == -1 or end < start: if start == -1 or end < start:
raise BridgeError("llm bridge returned no JSON object") raise ValueError("llm bridge returned no JSON object")
try: try:
data = json.loads(text[start : end + 1]) data = json.loads(text[start : end + 1])
except ValueError as exc: except ValueError as exc:
raise BridgeError(f"llm bridge returned invalid JSON: {exc}") from exc raise ValueError(f"llm bridge returned invalid JSON: {exc}") from exc
if not isinstance(data, dict): if not isinstance(data, dict):
raise BridgeError("llm bridge returned JSON that is not an object") raise ValueError("llm bridge returned JSON that is not an object")
return { return {
"title": str(data.get("title") or "").strip(), "title": str(data.get("title") or "").strip(),
"description": str(data.get("description") or "").strip(), "description": str(data.get("description") or "").strip(),
} }
# ---- date/time parsing ----
def _month_number(token): def _month_number(token):
return _MONTHS.get(token.lower()[:3]) return _MONTHS.get(token.lower()[:3])
@@ -432,21 +355,29 @@ def _parse_when(text, now):
# ---- calendar resolution ---- # ---- calendar resolution ----
def _resolve_calendar(ctx, request, calendars, decisions): def _default_calendar(calendars, default_name):
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower() """The configured default calendar, if it is one of the account's."""
default = None default_name = str(default_name or "").strip().lower()
for calendar in calendars: for calendar in calendars:
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()): if default_name and default_name in (
default = calendar calendar["name"].lower(),
break str(calendar.get("label") or calendar["name"]).lower(),
):
return calendar
return None
def _resolve_calendar(ctx, request, calendars, default_name, decisions):
default = _default_calendar(calendars, default_name)
if len(calendars) == 1: if len(calendars) == 1:
return calendars[0]["name"] return calendars[0]["name"]
decision = DecisionRequest( decision = DecisionRequest(
state=request.text, state=request.text,
question="Which calendar is referred to in the user query?", question="Which calendar is referred to in the user query?",
options=[Option(c["name"], c["label"]) for c in calendars], options=[
Option(c["name"], c.get("label") or c["name"]) for c in calendars
],
) )
result = ctx.engine.call(decision) result = ctx.engine.call(decision)
decisions.append((decision, result)) decisions.append((decision, result))
@@ -458,48 +389,6 @@ def _resolve_calendar(ctx, request, calendars, decisions):
return winner return winner
# ---- iCalendar ----
def _escape_ics(value):
return (
str(value)
.replace("\\", "\\\\")
.replace(";", "\\;")
.replace(",", "\\,")
.replace("\r\n", "\\n")
.replace("\n", "\\n")
.replace("\r", "\\n")
)
def _utc_stamp(moment):
return moment.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def _build_ics(uid, summary, start, end, all_day, stamp, description=""):
lines = [
"BEGIN:VCALENDAR",
"VERSION:2.0",
"PRODID:-//semif-agent//nextcloud.create_event//EN",
"CALSCALE:GREGORIAN",
"BEGIN:VEVENT",
f"UID:{uid}",
f"DTSTAMP:{stamp}",
]
if all_day:
lines.append(f"DTSTART;VALUE=DATE:{start.strftime('%Y%m%d')}")
lines.append(f"DTEND;VALUE=DATE:{end.strftime('%Y%m%d')}")
else:
lines.append(f"DTSTART:{_utc_stamp(start)}")
lines.append(f"DTEND:{_utc_stamp(end)}")
lines.append(f"SUMMARY:{_escape_ics(summary)}")
if description:
lines.append(f"DESCRIPTION:{_escape_ics(description)}")
lines += ["END:VEVENT", "END:VCALENDAR", ""]
return "\r\n".join(lines).encode("utf-8")
# ---- skill phases ---- # ---- skill phases ----
@@ -522,13 +411,9 @@ def act(ctx, request):
fields = request.meta.get("create_event_fields") fields = request.meta.get("create_event_fields")
if fields is None: if fields is None:
try: fields, error = _extract_fields(ctx, request)
fields = _extract_fields(ctx, request) if error:
except BridgeError as exc: return ActionResult(action_log=error, new_state=request.text)
return ActionResult(
action_log=str(exc),
new_state=request.text,
)
request.meta["create_event_fields"] = fields request.meta["create_event_fields"] = fields
title = fields["title"] title = fields["title"]
description = fields["description"] description = fields["description"]
@@ -572,42 +457,56 @@ def act(ctx, request):
duration = timedelta(minutes=parsed["duration_minutes"] or DEFAULT_DURATION_MINUTES) duration = timedelta(minutes=parsed["duration_minutes"] or DEFAULT_DURATION_MINUTES)
end = start + duration end = start + duration
try: decisions = []
calendars = _discover_calendars(ctx) base_url = str(ctx.config.get("nextcloud_bridge_url", "") or "").rstrip("/")
except CalDavError as exc: headers = _headers(ctx.config.get("nextcloud_bridge_token", ""))
status, payload = _call("GET", f"{base_url}/calendars", headers)
if status != 200:
return ActionResult( return ActionResult(
action_log=f"calendar discovery failed: {exc}", action_log=(
f"calendar discovery failed: status {status}, "
f"{payload.get('error', payload)}"
),
new_state=request.text, new_state=request.text,
decisions=decisions,
) )
calendars = [c for c in (payload.get("calendars") or []) if c.get("name")]
if not calendars: if not calendars:
return ActionResult( return ActionResult(
action_log="no calendars found on the account", action_log="no calendars found on the account",
new_state=request.text, new_state=request.text,
decisions=decisions,
) )
decisions = [] calendar = _resolve_calendar(
calendar = _resolve_calendar(ctx, request, calendars, decisions) ctx, request, calendars, payload.get("default"), decisions
uid = f"{uuid.uuid4().hex}@semif-agent"
body = _build_ics(
uid, title, start, end, all_day, _utc_stamp(now), description=description
) )
path = _calendar_path(ctx, calendar) + urllib.parse.quote(uid, safe="") + ".ics"
try: # An all-day event sends date-only bounds; a timed event sends ISO instants.
_request( if all_day:
ctx, start_value, end_value = start_date.isoformat(), end_date.isoformat()
"PUT", else:
path, start_value, end_value = start.isoformat(), end.isoformat()
body=body,
depth="0", status, payload = _call(
content_type="text/calendar; charset=utf-8", "POST",
extra_headers={"If-None-Match": "*"}, f"{base_url}/calendars/events",
) headers,
except CalDavError as exc: {
"calendar": calendar,
"summary": title,
"start": start_value,
"end": end_value,
"all_day": all_day,
"description": description,
},
)
if status != 200 or not payload.get("ok"):
return ActionResult( return ActionResult(
action_log=( action_log=(
f"could not create {title!r} on " f"could not create {title!r} on {calendar!r}: status {status}, "
f"{calendar!r}: {exc}" f"{payload.get('error', payload)}"
), ),
new_state=request.text, new_state=request.text,
decisions=decisions, decisions=decisions,
@@ -620,9 +519,10 @@ def act(ctx, request):
f"{start.strftime('%Y-%m-%d %H:%M %Z')}–" f"{start.strftime('%Y-%m-%d %H:%M %Z')}–"
f"{end.strftime('%H:%M %Z')}" f"{end.strftime('%H:%M %Z')}"
) )
report = f"Created {title!r} on calendar {calendar!r}: {when_text} (UID {uid})." uid = payload.get("uid", "")
return ActionResult( created_calendar = payload.get("calendar", calendar)
action_log=report, report = (
new_state=report, f"Created {title!r} on calendar {created_calendar!r}: {when_text} "
decisions=decisions, f"(UID {uid})."
) )
return ActionResult(action_log=report, new_state=report, decisions=decisions)
+97 -127
View File
@@ -1,15 +1,15 @@
"""Hermetic mechanics test for nextcloud.create_event. """Hermetic mechanics test for nextcloud.create_event.
Run from this folder: `python skill.test.py`. No external network: a loopback Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays a Nextcloud CalDAV endpoint (PROPFIND discovery + PUT create) http.server plays the Nextcloud bridge's JSON API (`GET /calendars`,
and the LLM bridge's `POST /chat`. This proves the body extracts the event title `POST /calendars/events`) and the LLM bridge's `POST /chat`. This proves the body
and description through the LLM bridge (caching the call across a `needs_input` extracts the event title and description through the LLM bridge (caching the call
resume), parses the date/time from the request, asks for a missing field and across a `needs_input` resume), parses the date/time from the request, asks for a
resumes, resolves the target calendar with a SemIf choice over the owned missing field and resumes, resolves the target calendar with a SemIf choice over
calendars (a strong winner is used, otherwise the configured default), writes a the owned calendars (a strong winner is used, otherwise the configured default),
real iCalendar PUT, and fails honestly when the LLM bridge or the server errors. creates the event through the bridge, and fails honestly when the LLM bridge or
It does NOT prove the live integration — only a real run against the user's the bridge errors. It does NOT prove the live integration — only a real run
Nextcloud does. against the user's Nextcloud does.
""" """
import json import json
@@ -62,11 +62,12 @@ class FakeEngine:
) )
class CalDavHandler(BaseHTTPRequestHandler): class BridgeHandler(BaseHTTPRequestHandler):
calendars = [] calendars = []
put_status = 201 default = "personal"
create_status = 200
requests = [] requests = []
puts = [] creates = []
llm_reply = DEFAULT_LLM_REPLY llm_reply = DEFAULT_LLM_REPLY
llm_status = 200 llm_status = 200
llm_requests = [] llm_requests = []
@@ -75,66 +76,63 @@ class CalDavHandler(BaseHTTPRequestHandler):
length = int(self.headers.get("Content-Length") or 0) length = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(length) if length else b"" return self.rfile.read(length) if length else b""
def _send(self, payload, status, content_type): def _send(self, payload, status=200):
body = payload if isinstance(payload, bytes) else payload.encode("utf-8") body = payload if isinstance(payload, bytes) else payload.encode("utf-8")
self.send_response(status) self.send_response(status)
self.send_header("Content-Type", content_type) self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body))) self.send_header("Content-Length", str(len(body)))
self.end_headers() self.end_headers()
self.wfile.write(body) self.wfile.write(body)
def do_PROPFIND(self): def do_GET(self):
self._read_body() path = urllib.parse.urlparse(self.path).path
self.requests.append(("PROPFIND", self.path)) self.requests.append(("GET", path))
responses = [] if path == "/calendars":
for calendar in self.calendars: self._send(
responses.append( json.dumps({"calendars": self.calendars, "default": self.default})
f'<d:response><d:href>/remote.php/dav/calendars/alice/'
f'{calendar["name"]}/</d:href>'
f"<d:propstat><d:prop>"
f'<d:displayname>{calendar["label"]}</d:displayname>'
f"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
f"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>"
f"</d:response>"
) )
body = ( return
'<?xml version="1.0" encoding="utf-8"?>' self._send(json.dumps({"error": "not found"}), 404)
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
+ "".join(responses)
+ "</d:multistatus>"
)
self._send(body, 207, "application/xml; charset=utf-8")
def do_PUT(self):
body = self._read_body()
self.puts.append(
{"path": self.path, "body": body, "headers": dict(self.headers)}
)
self._send(b"", self.put_status, "text/plain")
def do_POST(self): def do_POST(self):
body = self._read_body() body = self._read_body()
if self.path != "/chat": path = urllib.parse.urlparse(self.path).path
self._send(json.dumps({"error": "not found"}), 404, "application/json") if path == "/chat":
self.llm_requests.append(body)
if self.llm_status != 200:
self._send(json.dumps({"error": "boom"}), self.llm_status)
return
self._send(json.dumps({"text": json.dumps(self.llm_reply)}))
return return
self.llm_requests.append(body) if path == "/calendars/events":
if self.llm_status != 200: data = json.loads(body or b"{}")
self._send(json.dumps({"error": "boom"}), self.llm_status, "application/json") self.creates.append(data)
if self.create_status != 200:
self._send(json.dumps({"error": "boom"}), self.create_status)
return
self._send(
json.dumps(
{
"ok": True,
"uid": "uid-1",
"calendar": data.get("calendar", self.default),
"etag": '"etag-1"',
}
)
)
return return
self._send( self._send(json.dumps({"error": "not found"}), 404)
json.dumps({"text": json.dumps(self.llm_reply)}),
200,
"application/json",
)
def log_message(self, *args): def log_message(self, *args):
pass pass
def start_server(calendars=None, put_status=201, llm_reply=None, llm_status=200): def start_server(
calendars=None, default="personal", create_status=200, llm_reply=None, llm_status=200
):
handler = type( handler = type(
"Handler", "Handler",
(CalDavHandler,), (BridgeHandler,),
{ {
"calendars": calendars "calendars": calendars
if calendars is not None if calendars is not None
@@ -142,9 +140,10 @@ def start_server(calendars=None, put_status=201, llm_reply=None, llm_status=200)
{"name": "personal", "label": "Personal"}, {"name": "personal", "label": "Personal"},
{"name": "work", "label": "Work"}, {"name": "work", "label": "Work"},
], ],
"put_status": put_status, "default": default,
"create_status": create_status,
"requests": [], "requests": [],
"puts": [], "creates": [],
"llm_reply": llm_reply if llm_reply is not None else DEFAULT_LLM_REPLY, "llm_reply": llm_reply if llm_reply is not None else DEFAULT_LLM_REPLY,
"llm_status": llm_status, "llm_status": llm_status,
"llm_requests": [], "llm_requests": [],
@@ -155,20 +154,18 @@ def start_server(calendars=None, put_status=201, llm_reply=None, llm_status=200)
return server, handler, f"http://127.0.0.1:{server.server_address[1]}" return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def config(url, default="personal", llm_url=None): def config(url, llm_url=None):
return { return {
"nextcloud_url": url, "nextcloud_bridge_url": url,
"nextcloud_username": "alice", "nextcloud_bridge_token": "",
"nextcloud_app_password": "secret",
"nextcloud_default_calendar": default,
"llm_bridge_url": url if llm_url is None else llm_url, "llm_bridge_url": url if llm_url is None else llm_url,
"llm_bridge_token": "", "llm_bridge_token": "",
} }
def run(handler, url, text, default="personal", engine=None, llm_url=None): def run(url, text, engine=None, llm_url=None):
engine = engine or FakeEngine() engine = engine or FakeEngine()
ctx = ActionContext(engine=engine, config=config(url, default, llm_url)) ctx = ActionContext(engine=engine, config=config(url, llm_url))
request = Request(text) request = Request(text)
action = skill.act(ctx, request) action = skill.act(ctx, request)
return action, request, engine return action, request, engine
@@ -186,7 +183,6 @@ def test_example_creates_event_on_default_calendar():
# configured default ("personal") wins. # configured default ("personal") wins.
engine = FakeEngine(probs={"personal": 0.4, "work": 0.35}) engine = FakeEngine(probs={"personal": 0.4, "work": 0.35})
action, _request, engine = run( action, _request, engine = run(
handler,
url, url,
"add Ashley's dance recital to the calendar for 5pm Tuesday", "add Ashley's dance recital to the calendar for 5pm Tuesday",
engine=engine, engine=engine,
@@ -197,17 +193,15 @@ def test_example_creates_event_on_default_calendar():
"add Ashley's dance recital to the calendar for 5pm Tuesday" "add Ashley's dance recital to the calendar for 5pm Tuesday"
), engine.decisions[0] ), engine.decisions[0]
assert "referred to in the user query" in engine.decisions[0].question assert "referred to in the user query" in engine.decisions[0].question
assert len(handler.puts) == 1, handler.puts assert len(handler.creates) == 1, handler.creates
put = handler.puts[0] created = handler.creates[0]
assert put["path"].startswith("/remote.php/dav/calendars/alice/personal/"), put assert created["calendar"] == "personal", created
assert put["path"].endswith(".ics"), put assert created["summary"] == "Ashley's dance recital", created
assert put["headers"].get("If-None-Match") == "*" assert created["description"] == "Dance recital at 5pm.", created
body = put["body"].decode("utf-8")
assert "SUMMARY:Ashley's dance recital" in body, body
assert "DESCRIPTION:Dance recital at 5pm." in body, body
tuesday = next_weekday(FIXED_NOW, 1) tuesday = next_weekday(FIXED_NOW, 1)
assert f"DTSTART:{tuesday.strftime('%Y%m%d')}T170000Z" in body, body assert created["start"] == f"{tuesday.isoformat()}T17:00:00+00:00", created
assert f"DTEND:{tuesday.strftime('%Y%m%d')}T180000Z" in body, body assert created["end"] == f"{tuesday.isoformat()}T18:00:00+00:00", created
assert created["all_day"] is False, created
assert "Ashley's dance recital" in action.action_log, action.action_log assert "Ashley's dance recital" in action.action_log, action.action_log
print(action.action_log) print(action.action_log)
finally: finally:
@@ -220,22 +214,18 @@ def test_missing_time_asks_then_creates():
llm_reply={"title": "dentist appointment", "description": ""} llm_reply={"title": "dentist appointment", "description": ""}
) )
try: try:
action, request, engine = run( action, request, engine = run(url, "add dentist appointment on 2026-11-10")
handler, url, "add dentist appointment on 2026-11-10"
)
assert action.needs_input, "a missing start time must be asked" assert action.needs_input, "a missing start time must be asked"
assert "time" in action.needs_input.lower(), action.needs_input assert "time" in action.needs_input.lower(), action.needs_input
assert handler.puts == [] assert handler.creates == []
assert len(handler.llm_requests) == 1, "the LLM is called once, then cached" assert len(handler.llm_requests) == 1, "the LLM is called once, then cached"
request.user_input = "2pm" request.user_input = "2pm"
ctx = ActionContext(engine=engine, config=config(url)) ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, request) action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input assert action.needs_input is None, action.needs_input
assert len(handler.puts) == 1, handler.puts assert len(handler.creates) == 1, handler.creates
assert len(handler.llm_requests) == 1, "the resume must reuse the cached fields" assert len(handler.llm_requests) == 1, "the resume must reuse the cached fields"
body = handler.puts[0]["body"].decode("utf-8") assert handler.creates[0]["start"] == "2026-11-10T14:00:00+00:00", handler.creates[0]
assert "SUMMARY:dentist appointment" in body, body
assert "DTSTART:20261110T140000Z" in body, body
print(action.action_log) print(action.action_log)
finally: finally:
server.shutdown() server.shutdown()
@@ -247,15 +237,14 @@ def test_missing_day_asks_then_creates():
llm_reply={"title": "dentist appointment", "description": ""} llm_reply={"title": "dentist appointment", "description": ""}
) )
try: try:
action, request, engine = run(handler, url, "add dentist appointment at 2pm") action, request, engine = run(url, "add dentist appointment at 2pm")
assert action.needs_input, "a missing day must be asked" assert action.needs_input, "a missing day must be asked"
assert "day" in action.needs_input.lower(), action.needs_input assert "day" in action.needs_input.lower(), action.needs_input
request.user_input = "2026-11-10" request.user_input = "2026-11-10"
ctx = ActionContext(engine=engine, config=config(url)) ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, request) action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input assert action.needs_input is None, action.needs_input
body = handler.puts[0]["body"].decode("utf-8") assert handler.creates[0]["start"] == "2026-11-10T14:00:00+00:00", handler.creates[0]
assert "DTSTART:20261110T140000Z" in body, body
print(action.action_log) print(action.action_log)
finally: finally:
server.shutdown() server.shutdown()
@@ -265,10 +254,10 @@ def test_missing_day_asks_then_creates():
def test_missing_title_asks(): def test_missing_title_asks():
server, handler, url = start_server(llm_reply={"title": "", "description": ""}) server, handler, url = start_server(llm_reply={"title": "", "description": ""})
try: try:
action, _request, _engine = run(handler, url, "schedule on 2026-11-10 at 2pm") action, _request, _engine = run(url, "schedule on 2026-11-10 at 2pm")
assert action.needs_input, "a missing title must be asked" assert action.needs_input, "a missing title must be asked"
assert "call the event" in action.needs_input.lower(), action.needs_input assert "call the event" in action.needs_input.lower(), action.needs_input
assert handler.puts == [] assert handler.creates == []
print(action.needs_input) print(action.needs_input)
finally: finally:
server.shutdown() server.shutdown()
@@ -282,7 +271,6 @@ def test_named_calendar_is_used():
try: try:
engine = FakeEngine(pick="work") engine = FakeEngine(pick="work")
action, _request, engine = run( action, _request, engine = run(
handler,
url, url,
"add team sync to my work calendar on 2026-11-10 at 9am", "add team sync to my work calendar on 2026-11-10 at 9am",
engine=engine, engine=engine,
@@ -293,11 +281,8 @@ def test_named_calendar_is_used():
"personal", "personal",
"work", "work",
], engine.decisions[0].options ], engine.decisions[0].options
assert handler.puts[0]["path"].startswith( assert handler.creates[0]["calendar"] == "work", handler.creates[0]
"/remote.php/dav/calendars/alice/work/" assert handler.creates[0]["summary"] == "team sync", handler.creates[0]
), handler.puts[0]
body = handler.puts[0]["body"].decode("utf-8")
assert "SUMMARY:team sync" in body, body
print(action.action_log) print(action.action_log)
finally: finally:
server.shutdown() server.shutdown()
@@ -311,16 +296,11 @@ def test_weak_winner_falls_back_to_default():
# the configured default ("personal") is used instead. # the configured default ("personal") is used instead.
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5}) engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
action, _request, engine = run( action, _request, engine = run(
handler, url, "add standup on 2026-11-10 at 9am", engine=engine
url,
"add standup on 2026-11-10 at 9am",
engine=engine,
) )
assert action.needs_input is None, action.needs_input assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions assert len(engine.decisions) == 1, engine.decisions
assert handler.puts[0]["path"].startswith( assert handler.creates[0]["calendar"] == "personal", handler.creates[0]
"/remote.php/dav/calendars/alice/personal/"
), handler.puts[0]
print(action.action_log) print(action.action_log)
finally: finally:
server.shutdown() server.shutdown()
@@ -328,24 +308,20 @@ def test_weak_winner_falls_back_to_default():
def test_unknown_default_uses_semif_decision(): def test_unknown_default_uses_semif_decision():
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""}) server, handler, url = start_server(
llm_reply={"title": "standup", "description": ""}, default="missing"
)
try: try:
# The configured default is not among the account's calendars and the # The configured default is not among the account's calendars and the
# SemIf winner is weak: the winner is used anyway (never blocks). # SemIf winner is weak: the winner is used anyway (never blocks).
engine = FakeEngine(probs={"personal": 0.3, "work": 0.4}) engine = FakeEngine(probs={"personal": 0.3, "work": 0.4})
action, _request, engine = run( action, _request, engine = run(
handler, url, "add standup on 2026-11-10 at 9am", engine=engine
url,
"add standup on 2026-11-10 at 9am",
default="missing",
engine=engine,
) )
assert action.needs_input is None, action.needs_input assert action.needs_input is None, action.needs_input
assert len(engine.decisions) == 1, engine.decisions assert len(engine.decisions) == 1, engine.decisions
assert action.decisions and len(action.decisions) == 1, action.decisions assert action.decisions and len(action.decisions) == 1, action.decisions
assert handler.puts[0]["path"].startswith( assert handler.creates[0]["calendar"] == "work", handler.creates[0]
"/remote.php/dav/calendars/alice/work/"
), handler.puts[0]
print(action.action_log) print(action.action_log)
finally: finally:
server.shutdown() server.shutdown()
@@ -355,14 +331,13 @@ def test_unknown_default_uses_semif_decision():
def test_all_day_event(): def test_all_day_event():
server, handler, url = start_server(llm_reply={"title": "conference", "description": ""}) server, handler, url = start_server(llm_reply={"title": "conference", "description": ""})
try: try:
action, _request, _engine = run( action, _request, _engine = run(url, "add conference all day on 2026-11-10")
handler, url, "add conference all day on 2026-11-10"
)
assert action.needs_input is None, action.needs_input assert action.needs_input is None, action.needs_input
body = handler.puts[0]["body"].decode("utf-8") created = handler.creates[0]
assert "DTSTART;VALUE=DATE:20261110" in body, body assert created["all_day"] is True, created
assert "DTEND;VALUE=DATE:20261111" in body, body assert created["start"] == "2026-11-10", created
assert "SUMMARY:conference" in body, body assert created["end"] == "2026-11-11", created
assert created["summary"] == "conference", created
print(action.action_log) print(action.action_log)
finally: finally:
server.shutdown() server.shutdown()
@@ -373,14 +348,13 @@ def test_llm_bridge_failure_is_reported_honestly():
server, handler, url = start_server() server, handler, url = start_server()
try: try:
action, request, _engine = run( action, request, _engine = run(
handler,
url, url,
"add standup on 2026-11-10 at 9am", "add standup on 2026-11-10 at 9am",
llm_url="http://127.0.0.1:1", llm_url="http://127.0.0.1:1",
) )
assert "llm bridge" in action.action_log, action.action_log assert "llm bridge" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed extraction must not fake a result" assert action.new_state == request.text, "a failed extraction must not fake a result"
assert handler.puts == [], "no event is created when the LLM bridge is down" assert handler.creates == [], "no event is created when the LLM bridge is down"
print(action.action_log) print(action.action_log)
finally: finally:
server.shutdown() server.shutdown()
@@ -390,12 +364,10 @@ def test_llm_bridge_failure_is_reported_honestly():
def test_llm_bridge_error_status_is_reported_honestly(): def test_llm_bridge_error_status_is_reported_honestly():
server, handler, url = start_server(llm_status=502) server, handler, url = start_server(llm_status=502)
try: try:
action, request, _engine = run( action, request, _engine = run(url, "add standup on 2026-11-10 at 9am")
handler, url, "add standup on 2026-11-10 at 9am" assert "502" in action.action_log, action.action_log
)
assert "HTTP 502" in action.action_log, action.action_log
assert action.new_state == request.text assert action.new_state == request.text
assert handler.puts == [] assert handler.creates == []
print(action.action_log) print(action.action_log)
finally: finally:
server.shutdown() server.shutdown()
@@ -404,12 +376,10 @@ def test_llm_bridge_error_status_is_reported_honestly():
def test_server_error_is_reported_honestly(): def test_server_error_is_reported_honestly():
server, handler, url = start_server( server, handler, url = start_server(
put_status=500, llm_reply={"title": "standup", "description": ""} create_status=500, llm_reply={"title": "standup", "description": ""}
) )
try: try:
action, request, _engine = run( action, request, _engine = run(url, "add standup on 2026-11-10 at 9am")
handler, url, "add standup on 2026-11-10 at 9am"
)
assert "500" in action.action_log, action.action_log assert "500" in action.action_log, action.action_log
assert action.new_state == request.text, "a failed create must not fake a result" assert action.new_state == request.text, "a failed create must not fake a result"
print(action.action_log) print(action.action_log)
@@ -420,7 +390,7 @@ def test_server_error_is_reported_honestly():
def test_unreachable_server_fails_honestly(): def test_unreachable_server_fails_honestly():
action, request, _engine = run( action, request, _engine = run(
None, "http://127.0.0.1:1", "add standup on 2026-11-10 at 9am" "http://127.0.0.1:1", "add standup on 2026-11-10 at 9am"
) )
assert action.action_log and "nextcloud.create_event" not in action.action_log, action.action_log assert action.action_log and "nextcloud.create_event" not in action.action_log, action.action_log
assert action.new_state == request.text assert action.new_state == request.text
+2 -4
View File
@@ -1,6 +1,4 @@
{ {
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).", "nextcloud_bridge_url": "Base URL of the local Nextcloud bridge, e.g. http://127.0.0.1:5230 (no trailing slash needed); used to list calendars and read events.",
"nextcloud_username": "The Nextcloud username whose calendars are read.", "nextcloud_bridge_token": "Shared secret for the Nextcloud bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar)."
} }
+127 -285
View File
@@ -1,81 +1,52 @@
"""Report the next upcoming event on the user's Nextcloud calendar. """Report the next upcoming event on the user's Nextcloud calendar.
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection Real integration: the Nextcloud bridge over HTTP, which fronts the user's
details and the default calendar come from `ctx.config` (`nextcloud_url`, Nextcloud (CalDAV). The bridge URL/token come from `ctx.config` (declared in
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`). CONTRACT); the account connection and default calendar live in the bridge's own
`bridges.nextcloud` block.
`act` discovers the user's calendars over PROPFIND and resolves which one the `act` lists the user's calendars through the bridge (`GET /calendars`) and
request means with a single SemIf choice over every owned calendar (state = the resolves which one the request means with a single SemIf choice over every owned
user query): a strong winner (probability >= `CALENDAR_WINNER_TAU`) is used, calendar (state = the user query): a strong winner (probability >=
otherwise the configured default calendar is used; with no configured default `CALENDAR_WINNER_TAU`) is used, otherwise the configured default calendar is used;
the weak winner stands. It then issues a `calendar-query` REPORT with with no configured default the weak winner stands. It then asks the bridge for
server-side recurrence expansion and reports the earliest instance that has not the events in a bounded window (`GET /calendars/events?start=&end=`), which expands
ended yet. recurrences server-side, and reports the earliest instance that has not ended yet.
Recurring events are expanded by the server (`<c:expand>`), so no RRULE engine A failure talking to the bridge is reported honestly rather than guessed at.
lives here; a server that ignores expansion is reported honestly rather than
guessed at.
""" """
from __future__ import annotations from __future__ import annotations
import base64 import json
import re
import urllib.error import urllib.error
import urllib.parse import urllib.parse
import urllib.request import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from semif_agent.decisions import DecisionRequest, Option from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult from semif_agent.skills import ActionResult
from semif_agent.timers import local_now from semif_agent.timers import local_now
INTEGRATION = { INTEGRATION = {
"service": "nextcloud_calendar", "service": "nextcloud",
"transport": "caldav", "transport": "http",
"config_vars": [ "config_vars": [
"nextcloud_url", "nextcloud_bridge_url",
"nextcloud_username", "nextcloud_bridge_token",
"nextcloud_app_password",
"nextcloud_default_calendar",
], ],
} }
CONTRACT = { CONTRACT = {
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).", "nextcloud_bridge_url": "Base URL of the local Nextcloud bridge, e.g. http://127.0.0.1:5230 (no trailing slash needed); used to list calendars and read events.",
"nextcloud_username": "The Nextcloud username whose calendars are read.", "nextcloud_bridge_token": "Shared secret for the Nextcloud bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar).",
} }
DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav"
LOOKAHEAD_DAYS = 60 LOOKAHEAD_DAYS = 60
TIMEOUT_SECONDS = 30
# A SemIf probability at or above this counts as a "strong winner" for the # A SemIf probability at or above this counts as a "strong winner" for the
# target calendar; below it the configured default calendar is used instead. # target calendar; below it the configured default calendar is used instead.
CALENDAR_WINNER_TAU = 0.6 CALENDAR_WINNER_TAU = 0.6
PROPFIND_BODY = (
'<?xml version="1.0" encoding="utf-8"?>'
'<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop><d:displayname/><d:resourcetype/></d:prop>"
"</d:propfind>"
).encode("utf-8")
PROPERTY_RE = re.compile(r"^(?P<name>[A-Za-z-]+)(?P<params>(?:;[^:]*)?):(?P<value>.*)$")
DURATION_RE = re.compile(
r"^(?P<sign>[+-])?P"
r"(?:(?P<weeks>\d+)W)?(?:(?P<days>\d+)D)?"
r"(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?$"
)
class CalDavError(Exception):
"""A real failure talking to the calendar service."""
def _now(ctx): def _now(ctx):
"""Current time (aware) in the user's timezone: the top-level `timezone` """Current time (aware) in the user's timezone: the top-level `timezone`
@@ -83,148 +54,63 @@ def _now(ctx):
return local_now(ctx.config) return local_now(ctx.config)
# ---- transport ---- def _headers(token):
"""Build request headers, sending the bridge token only when one is set."""
headers = {"Content-Type": "application/json"}
if token:
headers["X-Semif-Token"] = token
return headers
def _request(ctx, method, path, body=None, depth="0"): def _call(method, url, headers, payload=None, timeout=25):
username = str(ctx.config.get("nextcloud_username", "") or "").strip() """Perform one HTTP call, returning (status, decoded_json_or_error_dict)."""
password = str(ctx.config.get("nextcloud_app_password", "") or "") data = json.dumps(payload).encode("utf-8") if payload is not None else None
url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/") req = urllib.request.Request(url, data=data, headers=headers, method=method)
if not url:
raise CalDavError("nextcloud_url is not configured")
if not username or not password:
raise CalDavError("nextcloud_username and nextcloud_app_password are not configured")
token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
request = urllib.request.Request(
url + path,
data=body,
method=method,
headers={
"Authorization": f"Basic {token}",
"Depth": depth,
"Content-Type": "application/xml; charset=utf-8",
},
)
try: try:
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response: with urllib.request.urlopen(req, timeout=timeout) as response:
return response.read() body = response.read().decode("utf-8")
return response.status, (json.loads(body) if body else {})
except urllib.error.HTTPError as exc: except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace").strip()[:200] try:
raise CalDavError(f"{method} {path}: HTTP {exc.code} {detail}") from exc detail = json.loads(exc.read().decode("utf-8"))
except (urllib.error.URLError, OSError) as exc: except Exception:
raise CalDavError(f"{method} {path}: {exc}") from exc detail = {"error": str(exc)}
return exc.code, detail
except (urllib.error.URLError, ValueError) as exc:
# ---- CalDAV discovery + query ---- return None, {"error": str(exc)}
def _multistatus(body):
try:
root = ET.fromstring(body)
except ET.ParseError as exc:
raise CalDavError(f"unparseable CalDAV XML: {exc}") from exc
if root.tag != f"{{{DAV}}}multistatus":
raise CalDavError(f"unexpected CalDAV response root {root.tag!r}")
return root
def _response_prop(response):
return response.find(f"{{{DAV}}}propstat/{{{DAV}}}prop")
def _discover_calendars(ctx):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
if not username:
raise CalDavError("nextcloud_username is not configured")
home = f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
root = _multistatus(_request(ctx, "PROPFIND", home, PROPFIND_BODY, depth="1"))
calendars = []
for response in root.findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
resourcetype = prop.find(f"{{{DAV}}}resourcetype")
if resourcetype is None or resourcetype.find(f"{{{CALDAV}}}calendar") is None:
continue
href = response.find(f"{{{DAV}}}href")
path = urllib.parse.urlparse((href.text if href is not None else "") or "").path
name = urllib.parse.unquote(path.rstrip("/").rsplit("/", 1)[-1])
if not name:
continue
display = prop.find(f"{{{DAV}}}displayname")
label = (display.text or "").strip() if display is not None else ""
calendars.append({"name": name, "label": label or name})
return calendars
def _calendar_path(ctx, calendar):
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
return (
f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/"
f"{urllib.parse.quote(calendar)}/"
)
def _report_body(start, end):
start_text = start.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
end_text = end.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
return (
'<?xml version="1.0" encoding="utf-8"?>'
'<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
"<d:prop>"
f'<c:calendar-data><c:expand start="{start_text}" end="{end_text}"/>'
"</c:calendar-data>"
"</d:prop>"
"<c:filter>"
'<c:comp-filter name="VCALENDAR">'
'<c:comp-filter name="VEVENT">'
f'<c:time-range start="{start_text}" end="{end_text}"/>'
"</c:comp-filter>"
"</c:comp-filter>"
"</c:filter>"
"</c:calendar-query>"
).encode("utf-8")
def _calendar_payloads(body):
root = _multistatus(body)
payloads = []
for response in root.findall(f"{{{DAV}}}response"):
prop = _response_prop(response)
if prop is None:
continue
for data in prop.findall(f"{{{CALDAV}}}calendar-data"):
if data.text:
payloads.append(data.text)
return payloads
# ---- calendar resolution ---- # ---- calendar resolution ----
def _default_calendar(ctx, calendars): def _default_calendar(calendars, default_name):
"""The configured default calendar, if it is one of the account's.""" """The configured default calendar, if it is one of the account's."""
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower() default_name = str(default_name or "").strip().lower()
for calendar in calendars: for calendar in calendars:
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()): if default_name and default_name in (
calendar["name"].lower(),
str(calendar.get("label") or calendar["name"]).lower(),
):
return calendar return calendar
return None return None
def _resolve_calendar(ctx, request, calendars, decisions): def _resolve_calendar(ctx, request, calendars, default_name, decisions):
"""Resolve which calendar the request means, mirroring nextcloud.create_event. """Resolve which calendar the request means.
A strong SemIf winner is used; a weak winner falls back to the configured A strong SemIf winner is used; a weak winner falls back to the configured
default calendar, and with no configured default the weak winner stands. default calendar, and with no configured default the weak winner stands.
""" """
default = _default_calendar(ctx, calendars) default = _default_calendar(calendars, default_name)
if len(calendars) == 1: if len(calendars) == 1:
return calendars[0]["name"] return calendars[0]["name"]
decision = DecisionRequest( decision = DecisionRequest(
state=request.text, state=request.text,
question="Which calendar is referred to in the user query?", question="Which calendar is referred to in the user query?",
options=[Option(c["name"], c["label"]) for c in calendars], options=[
Option(c["name"], c.get("label") or c["name"]) for c in calendars
],
) )
result = ctx.engine.call(decision) result = ctx.engine.call(decision)
decisions.append((decision, result)) decisions.append((decision, result))
@@ -236,119 +122,60 @@ def _resolve_calendar(ctx, request, calendars, decisions):
return winner return winner
# ---- iCalendar parsing ---- # ---- event parsing ----
def _unfold(text): def _parse_when(value, default_tz):
lines = [] """Parse a bridge event timestamp into an aware datetime.
for raw in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
if raw[:1] in (" ", "\t") and lines:
lines[-1] += raw[1:]
else:
lines.append(raw)
return lines
The bridge returns an all-day date as `YYYY-MM-DD`, a UTC instant as an ISO
def _parse_property(line): string with an offset, and a floating (no-zone) time as an ISO string with no
match = PROPERTY_RE.match(line) offset. A floating time is read in the user's local zone.
if match is None: """
return "", {}, "" text = str(value or "").strip()
name = match.group("name").upper() if not text:
params = {}
for chunk in match.group("params").strip(";").split(";"):
key, _, value = chunk.partition("=")
if key:
params[key.strip().upper()] = value.strip().strip('"')
return name, params, match.group("value")
def _parse_datetime(value, params, default_tz):
value = value.strip()
if params.get("VALUE") == "DATE" or (len(value) == 8 and value.isdigit()):
return datetime.strptime(value, "%Y%m%d").replace(tzinfo=default_tz), True
tz = default_tz
if value.endswith("Z"):
tz = timezone.utc
value = value[:-1]
elif params.get("TZID"):
try:
tz = ZoneInfo(params["TZID"])
except Exception:
tz = default_tz
return datetime.strptime(value, "%Y%m%dT%H%M%S").replace(tzinfo=tz), False
def _parse_duration(value):
match = DURATION_RE.match(value.strip().upper())
if match is None:
return None return None
total = timedelta( if len(text) == 10 and text[4] == "-" and text[7] == "-":
weeks=int(match.group("weeks") or 0), return datetime.strptime(text, "%Y-%m-%d").replace(tzinfo=default_tz)
days=int(match.group("days") or 0), try:
hours=int(match.group("hours") or 0), moment = datetime.fromisoformat(text.replace("Z", "+00:00"))
minutes=int(match.group("minutes") or 0), except ValueError:
seconds=int(match.group("seconds") or 0), return None
) if moment.tzinfo is None:
return -total if match.group("sign") == "-" else total moment = moment.replace(tzinfo=default_tz)
return moment
def _parse_events(payloads, default_tz): def _event_end(event, default_tz):
events = [] end = _parse_when(event.get("end"), default_tz)
for payload in payloads: if end is not None:
current = None return end
for line in _unfold(payload): start = _parse_when(event.get("start"), default_tz)
name, params, value = _parse_property(line) if start is None:
if name == "BEGIN" and value.strip().upper() == "VEVENT": return None
current = {}
continue
if name == "END" and value.strip().upper() == "VEVENT":
if current is not None:
events.append(current)
current = None
continue
if current is None:
continue
if name == "DTSTART":
current["start"], current["all_day"] = _parse_datetime(
value, params, default_tz
)
elif name == "DTEND":
current["end"] = _parse_datetime(value, params, default_tz)[0]
elif name == "DURATION":
current["duration"] = _parse_duration(value)
elif name == "SUMMARY":
current["summary"] = value.strip()
elif name == "LOCATION":
current["location"] = value.strip()
elif name == "STATUS" and value.strip().upper() == "CANCELLED":
current["cancelled"] = True
if current is not None:
events.append(current)
return [
event for event in events if "start" in event and not event.get("cancelled")
]
def _event_end(event):
if event.get("end") is not None:
return event["end"]
duration = event.get("duration")
if duration is not None:
return event["start"] + duration
if event.get("all_day"): if event.get("all_day"):
return event["start"] + timedelta(days=1) return start + timedelta(days=1)
return event["start"] return start
def _pick_next(events, now): def _pick_next(events, now, default_tz):
current_or_future = [event for event in events if _event_end(event) >= now] candidates = []
if not current_or_future: for event in events:
start = _parse_when(event.get("start"), default_tz)
end = _event_end(event, default_tz)
if start is None or end is None:
continue
if end >= now:
candidates.append((start, event))
if not candidates:
return None return None
return min(current_or_future, key=lambda event: event["start"]) return min(candidates, key=lambda pair: pair[0])[1]
def _format_when(event): def _format_when(event, default_tz):
start = event["start"] start = _parse_when(event.get("start"), default_tz)
if start is None:
return "(unknown time)"
if event.get("all_day"): if event.get("all_day"):
return start.strftime("%Y-%m-%d (all day)") return start.strftime("%Y-%m-%d (all day)")
return start.strftime("%Y-%m-%d %H:%M %Z") return start.strftime("%Y-%m-%d %H:%M %Z")
@@ -358,21 +185,31 @@ def _format_when(event):
def act(ctx, request): def act(ctx, request):
try: decisions = []
calendars = _discover_calendars(ctx) base_url = str(ctx.config.get("nextcloud_bridge_url", "") or "").rstrip("/")
except CalDavError as exc: headers = _headers(ctx.config.get("nextcloud_bridge_token", ""))
status, payload = _call("GET", f"{base_url}/calendars", headers)
if status != 200:
return ActionResult( return ActionResult(
action_log=f"calendar discovery failed: {exc}", action_log=(
f"could not list Nextcloud calendars from {base_url}: "
f"status {status}, {payload.get('error', payload)}"
),
new_state=request.text, new_state=request.text,
decisions=decisions,
) )
calendars = [c for c in (payload.get("calendars") or []) if c.get("name")]
if not calendars: if not calendars:
return ActionResult( return ActionResult(
action_log="calendar discovery failed: no calendars found", action_log="calendar discovery failed: no calendars found",
new_state=request.text, new_state=request.text,
decisions=decisions,
) )
decisions = [] calendar = _resolve_calendar(
calendar = _resolve_calendar(ctx, request, calendars, decisions) ctx, request, calendars, payload.get("default"), decisions
)
if not calendar: if not calendar:
return ActionResult( return ActionResult(
action_log="aborted: no calendar resolved.", action_log="aborted: no calendar resolved.",
@@ -384,23 +221,28 @@ def act(ctx, request):
local_tz = now.tzinfo or timezone.utc local_tz = now.tzinfo or timezone.utc
window_start = now - timedelta(days=1) window_start = now - timedelta(days=1)
window_end = now + timedelta(days=LOOKAHEAD_DAYS) window_end = now + timedelta(days=LOOKAHEAD_DAYS)
try: query = urllib.parse.urlencode(
body = _request( {
ctx, "calendar": calendar,
"REPORT", "start": window_start.isoformat(),
_calendar_path(ctx, calendar), "end": window_end.isoformat(),
_report_body(window_start, window_end), }
depth="1", )
) status, payload = _call(
events = _parse_events(_calendar_payloads(body), local_tz) "GET", f"{base_url}/calendars/events?{query}", headers
except CalDavError as exc: )
if status != 200:
return ActionResult( return ActionResult(
action_log=f"failed on {calendar!r}: {exc}", action_log=(
f"failed on {calendar!r}: status {status}, "
f"{payload.get('error', payload)}"
),
new_state=request.text, new_state=request.text,
decisions=decisions, decisions=decisions,
) )
next_event = _pick_next(events, now) events = payload.get("events") or []
next_event = _pick_next(events, now, local_tz)
if next_event is None: if next_event is None:
message = ( message = (
f"No events on calendar {calendar!r} through " f"No events on calendar {calendar!r} through "
@@ -409,7 +251,7 @@ def act(ctx, request):
return ActionResult(action_log=message, new_state=message, decisions=decisions) return ActionResult(action_log=message, new_state=message, decisions=decisions)
summary = next_event.get("summary") or "(no title)" summary = next_event.get("summary") or "(no title)"
when = _format_when(next_event) when = _format_when(next_event, local_tz)
message = f"Next event on {calendar!r}: {summary} — {when}" message = f"Next event on {calendar!r}: {summary} — {when}"
if next_event.get("location"): if next_event.get("location"):
message += f" at {next_event['location']}" message += f" at {next_event['location']}"
+85 -100
View File
@@ -1,17 +1,19 @@
"""Hermetic mechanics test for nextcloud.next_event. """Hermetic mechanics test for nextcloud.next_event.
Run from this folder: `python skill.test.py`. No external network: a loopback Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the Nextcloud CalDAV endpoint. This proves the body builds http.server plays the Nextcloud bridge's JSON API (`GET /calendars` and
real CalDAV requests, discovers calendars, resolves the calendar through a `GET /calendars/events`). This proves the body lists calendars through the
SemIf sub-decision (a strong winner is used, otherwise the configured default, bridge, resolves the calendar through a SemIf sub-decision (a strong winner is
otherwise the weak winner), parses expanded iCalendar events, and fails honestly used, otherwise the configured default, otherwise the weak winner), asks for the
when the service errors. It does NOT prove the live integration — only a real events in a bounded window, picks the earliest not-yet-ended one, and fails
run against the user's Nextcloud does. honestly when the bridge errors. It does NOT prove the live integration — only a
real run against the user's Nextcloud does.
""" """
import base64 import json
import sys import sys
import threading import threading
import urllib.parse
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -21,32 +23,42 @@ from semif_agent.skills import ActionContext
import skill import skill
CALENDARS = [("personal", "Personal"), ("work", "Work")] CALENDARS = [("personal", "Personal"), ("work", "Work")]
ICS = ""
def build_ics(): def build_events():
"""Fixture events relative to now, so the test never rots.""" """Fixture events relative to now, so the test never rots."""
now = datetime.now(timezone.utc) now = datetime.now(timezone.utc)
past = now - timedelta(days=2) past = now - timedelta(days=2)
soon = now + timedelta(hours=2) soon = now + timedelta(hours=2)
all_day = (now + timedelta(days=2)).date() all_day = (now + timedelta(days=2)).date()
def stamp(value): def iso(value):
return value.strftime("%Y%m%dT%H%M%SZ") return value.isoformat()
return ( return [
"BEGIN:VCALENDAR\nVERSION:2.0\n" {
"BEGIN:VEVENT\nUID:past@example\n" "uid": "past@example",
f"DTSTART:{stamp(past)}\nDTEND:{stamp(past + timedelta(hours=1))}\n" "summary": "Already happened",
"SUMMARY:Already happened\nEND:VEVENT\n" "start": iso(past),
"BEGIN:VEVENT\nUID:soon@example\n" "end": iso(past + timedelta(hours=1)),
f"DTSTART:{stamp(soon)}\nDTEND:{stamp(soon + timedelta(hours=1))}\n" "all_day": False,
"SUMMARY:Team sync\nLOCATION:Room 3\nEND:VEVENT\n" },
"BEGIN:VEVENT\nUID:allday@example\n" {
f"DTSTART;VALUE=DATE:{all_day.strftime('%Y%m%d')}\n" "uid": "soon@example",
"SUMMARY:Offsite\nEND:VEVENT\n" "summary": "Team sync",
"END:VCALENDAR" "location": "Room 3",
) "start": iso(soon),
"end": iso(soon + timedelta(hours=1)),
"all_day": False,
},
{
"uid": "allday@example",
"summary": "Offsite",
"start": all_day.isoformat(),
"end": (all_day + timedelta(days=1)).isoformat(),
"all_day": True,
},
]
class FakeEngine: class FakeEngine:
@@ -77,89 +89,64 @@ class FakeEngine:
) )
class CalDavHandler(BaseHTTPRequestHandler): class BridgeHandler(BaseHTTPRequestHandler):
requests = [] requests = []
calendar_count = 2 calendar_count = 2
report_status = 207 events_status = 200
default = "personal"
events = []
def _record(self): def _json(self, payload, status=200):
length = int(self.headers.get("Content-Length") or 0) body = json.dumps(payload).encode("utf-8")
body = self.rfile.read(length) if length else b"" self.send_response(status)
self.requests.append( self.send_header("Content-Type", "application/json")
{
"command": self.command,
"path": self.path,
"depth": self.headers.get("Depth"),
"authorization": self.headers.get("Authorization"),
"body": body.decode("utf-8", "replace"),
}
)
def _multistatus(self, payload):
body = payload.encode("utf-8")
self.send_response(207)
self.send_header("Content-Type", "application/xml; charset=utf-8")
self.send_header("Content-Length", str(len(body))) self.send_header("Content-Length", str(len(body)))
self.end_headers() self.end_headers()
self.wfile.write(body) self.wfile.write(body)
def do_PROPFIND(self): def do_GET(self):
self._record() parsed = urllib.parse.urlparse(self.path)
responses = "".join( query = urllib.parse.parse_qs(parsed.query)
f"<d:response><d:href>/remote.php/dav/calendars/testuser/{name}/</d:href>" self.requests.append({"path": parsed.path, "query": query})
"<d:propstat><d:prop>" if parsed.path == "/calendars":
f"<d:displayname>{label}</d:displayname>" calendars = [
"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>" {"name": name, "label": label}
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>" for name, label in CALENDARS[: self.calendar_count]
for name, label in CALENDARS[: self.calendar_count] ]
) self._json({"calendars": calendars, "default": self.default})
self._multistatus(
'<?xml version="1.0" encoding="utf-8"?>'
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
f"{responses}</d:multistatus>"
)
def do_REPORT(self):
self._record()
if self.report_status != 207:
self.send_response(self.report_status)
self.end_headers()
return return
self._multistatus( if parsed.path == "/calendars/events":
'<?xml version="1.0" encoding="utf-8"?>' if self.events_status != 200:
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">' self._json({"error": "boom"}, self.events_status)
"<d:response>" return
"<d:href>/remote.php/dav/calendars/testuser/work/event.ics</d:href>" calendar = query.get("calendar", [""])[0]
"<d:propstat><d:prop>" self._json({"calendar": calendar, "events": self.events})
f"<c:calendar-data>{ICS}</c:calendar-data>" return
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>" self._json({"error": "not found"}, 404)
"</d:response></d:multistatus>"
)
def log_message(self, *args): def log_message(self, *args):
pass pass
def start_server(**overrides): def start_server(**overrides):
handler = type("Handler", (CalDavHandler,), {"requests": [], **overrides}) handler = type(
"Handler",
(BridgeHandler,),
{"requests": [], "events": build_events(), **overrides},
)
server = ThreadingHTTPServer(("127.0.0.1", 0), handler) server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start() threading.Thread(target=server.serve_forever, daemon=True).start()
return server, handler, f"http://127.0.0.1:{server.server_address[1]}" return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def fixture_config(url, default="personal"): def fixture_config(url):
return { return {
"nextcloud_url": url, "nextcloud_bridge_url": url,
"nextcloud_username": "testuser", "nextcloud_bridge_token": "",
"nextcloud_app_password": "app-pw",
"nextcloud_default_calendar": default,
} }
def main(): def main():
global ICS
ICS = build_ics()
# A strong winner is used even though a default is configured. # A strong winner is used even though a default is configured.
server, handler, url = start_server() server, handler, url = start_server()
try: try:
@@ -176,15 +163,13 @@ def main():
assert "Team sync" in action.action_log, action.action_log assert "Team sync" in action.action_log, action.action_log
assert action.new_state, "act must set a new state" assert action.new_state, "act must set a new state"
commands = [entry["command"] for entry in handler.requests] assert [entry["path"] for entry in handler.requests] == [
assert commands == ["PROPFIND", "REPORT"], commands "/calendars",
report = handler.requests[1] "/calendars/events",
assert report["path"] == "/remote.php/dav/calendars/testuser/work/", report["path"] ], handler.requests
assert report["depth"] == "1", report["depth"] events_call = handler.requests[1]
expected_auth = "Basic " + base64.b64encode(b"testuser:app-pw").decode("ascii") assert events_call["query"]["calendar"] == ["work"], events_call["query"]
assert report["authorization"] == expected_auth, report["authorization"] assert "start" in events_call["query"] and "end" in events_call["query"]
assert "<c:expand" in report["body"], "recurrence expansion must be requested"
assert "c:time-range" in report["body"], "the query must bound a time range"
print(action.action_log) print(action.action_log)
finally: finally:
server.shutdown() server.shutdown()
@@ -194,11 +179,11 @@ def main():
server, handler, url = start_server() server, handler, url = start_server()
try: try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5}) engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default="personal")) ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?") request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request) action = skill.act(ctx, request)
assert len(engine.decisions) == 1 assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/", handler.requests[1]["path"] assert handler.requests[1]["query"]["calendar"] == ["personal"], handler.requests[1]
assert "Team sync" in action.action_log, action.action_log assert "Team sync" in action.action_log, action.action_log
print(action.action_log) print(action.action_log)
finally: finally:
@@ -206,14 +191,14 @@ def main():
server.server_close() server.server_close()
# A weak winner with no configured default stands. # A weak winner with no configured default stands.
server, handler, url = start_server() server, handler, url = start_server(default="")
try: try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5}) engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default="")) ctx = ActionContext(engine=engine, config=fixture_config(url))
request = Request("what is the next event on my calendar?") request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request) action = skill.act(ctx, request)
assert len(engine.decisions) == 1 assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/work/", handler.requests[1]["path"] assert handler.requests[1]["query"]["calendar"] == ["work"], handler.requests[1]
print(action.action_log) print(action.action_log)
finally: finally:
server.shutdown() server.shutdown()
@@ -228,14 +213,14 @@ def main():
action = skill.act(ctx, request) action = skill.act(ctx, request)
assert engine.decisions == [], "a single calendar needs no SemIf decision" assert engine.decisions == [], "a single calendar needs no SemIf decision"
assert "Team sync" in action.action_log, action.action_log assert "Team sync" in action.action_log, action.action_log
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/" assert handler.requests[1]["query"]["calendar"] == ["personal"]
print(action.action_log) print(action.action_log)
finally: finally:
server.shutdown() server.shutdown()
server.server_close() server.server_close()
# A failing REPORT is reported honestly. # A failing events read is reported honestly.
server, handler, url = start_server(report_status=500) server, handler, url = start_server(events_status=500)
try: try:
engine = FakeEngine(pick="personal") engine = FakeEngine(pick="personal")
ctx = ActionContext(engine=engine, config=fixture_config(url)) ctx = ActionContext(engine=engine, config=fixture_config(url))