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:
1 parent
ace251a829
commit
1a1d28dffd
9 files changed
+486
-748
No files matched your search
@@ -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_username": "The Nextcloud username whose calendars are read.",
|
||||
"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)."
|
||||
"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_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."
|
||||
}
|
||||
@@ -1,81 +1,52 @@
|
||||
"""Report the next upcoming event on the user's Nextcloud calendar.
|
||||
|
||||
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
|
||||
details and the default calendar come from `ctx.config` (`nextcloud_url`,
|
||||
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`).
|
||||
Real integration: the Nextcloud bridge over HTTP, which fronts the user's
|
||||
Nextcloud (CalDAV). The bridge URL/token come from `ctx.config` (declared in
|
||||
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
|
||||
request means with a single SemIf choice over every owned calendar (state = the
|
||||
user query): a strong winner (probability >= `CALENDAR_WINNER_TAU`) is used,
|
||||
otherwise the configured default calendar is used; with no configured default
|
||||
the weak winner stands. It then issues a `calendar-query` REPORT with
|
||||
server-side recurrence expansion and reports the earliest instance that has not
|
||||
ended yet.
|
||||
`act` lists the user's calendars through the bridge (`GET /calendars`) and
|
||||
resolves which one the request means with a single SemIf choice over every owned
|
||||
calendar (state = the user query): a strong winner (probability >=
|
||||
`CALENDAR_WINNER_TAU`) is used, otherwise the configured default calendar is used;
|
||||
with no configured default the weak winner stands. It then asks the bridge for
|
||||
the events in a bounded window (`GET /calendars/events?start=&end=`), which expands
|
||||
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
|
||||
lives here; a server that ignores expansion is reported honestly rather than
|
||||
guessed at.
|
||||
A failure talking to the bridge is reported honestly rather than guessed at.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import re
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from semif_agent.decisions import DecisionRequest, Option
|
||||
from semif_agent.skills import ActionResult
|
||||
from semif_agent.timers import local_now
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "nextcloud_calendar",
|
||||
"transport": "caldav",
|
||||
"service": "nextcloud",
|
||||
"transport": "http",
|
||||
"config_vars": [
|
||||
"nextcloud_url",
|
||||
"nextcloud_username",
|
||||
"nextcloud_app_password",
|
||||
"nextcloud_default_calendar",
|
||||
"nextcloud_bridge_url",
|
||||
"nextcloud_bridge_token",
|
||||
],
|
||||
}
|
||||
|
||||
CONTRACT = {
|
||||
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
|
||||
"nextcloud_username": "The Nextcloud username whose calendars are read.",
|
||||
"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).",
|
||||
"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_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.",
|
||||
}
|
||||
|
||||
DAV = "DAV:"
|
||||
CALDAV = "urn:ietf:params:xml:ns:caldav"
|
||||
LOOKAHEAD_DAYS = 60
|
||||
TIMEOUT_SECONDS = 30
|
||||
# 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.
|
||||
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):
|
||||
"""Current time (aware) in the user's timezone: the top-level `timezone`
|
||||
@@ -83,148 +54,63 @@ def _now(ctx):
|
||||
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"):
|
||||
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
|
||||
password = str(ctx.config.get("nextcloud_app_password", "") or "")
|
||||
url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/")
|
||||
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",
|
||||
},
|
||||
)
|
||||
def _call(method, url, headers, payload=None, timeout=25):
|
||||
"""Perform one HTTP call, returning (status, decoded_json_or_error_dict)."""
|
||||
data = json.dumps(payload).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
|
||||
return response.read()
|
||||
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||||
body = response.read().decode("utf-8")
|
||||
return response.status, (json.loads(body) if body else {})
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
||||
raise CalDavError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
|
||||
except (urllib.error.URLError, OSError) as exc:
|
||||
raise CalDavError(f"{method} {path}: {exc}") from exc
|
||||
|
||||
|
||||
# ---- CalDAV discovery + query ----
|
||||
|
||||
|
||||
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
|
||||
try:
|
||||
detail = json.loads(exc.read().decode("utf-8"))
|
||||
except Exception:
|
||||
detail = {"error": str(exc)}
|
||||
return exc.code, detail
|
||||
except (urllib.error.URLError, ValueError) as exc:
|
||||
return None, {"error": str(exc)}
|
||||
|
||||
|
||||
# ---- 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."""
|
||||
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
|
||||
default_name = str(default_name or "").strip().lower()
|
||||
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 None
|
||||
|
||||
|
||||
def _resolve_calendar(ctx, request, calendars, decisions):
|
||||
"""Resolve which calendar the request means, mirroring nextcloud.create_event.
|
||||
def _resolve_calendar(ctx, request, calendars, default_name, decisions):
|
||||
"""Resolve which calendar the request means.
|
||||
|
||||
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 = _default_calendar(ctx, calendars)
|
||||
default = _default_calendar(calendars, default_name)
|
||||
if len(calendars) == 1:
|
||||
return calendars[0]["name"]
|
||||
|
||||
decision = DecisionRequest(
|
||||
state=request.text,
|
||||
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)
|
||||
decisions.append((decision, result))
|
||||
@@ -236,119 +122,60 @@ def _resolve_calendar(ctx, request, calendars, decisions):
|
||||
return winner
|
||||
|
||||
|
||||
# ---- iCalendar parsing ----
|
||||
# ---- event parsing ----
|
||||
|
||||
|
||||
def _unfold(text):
|
||||
lines = []
|
||||
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
|
||||
def _parse_when(value, default_tz):
|
||||
"""Parse a bridge event timestamp into an aware datetime.
|
||||
|
||||
|
||||
def _parse_property(line):
|
||||
match = PROPERTY_RE.match(line)
|
||||
if match is None:
|
||||
return "", {}, ""
|
||||
name = match.group("name").upper()
|
||||
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:
|
||||
The bridge returns an all-day date as `YYYY-MM-DD`, a UTC instant as an ISO
|
||||
string with an offset, and a floating (no-zone) time as an ISO string with no
|
||||
offset. A floating time is read in the user's local zone.
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
total = timedelta(
|
||||
weeks=int(match.group("weeks") or 0),
|
||||
days=int(match.group("days") or 0),
|
||||
hours=int(match.group("hours") or 0),
|
||||
minutes=int(match.group("minutes") or 0),
|
||||
seconds=int(match.group("seconds") or 0),
|
||||
)
|
||||
return -total if match.group("sign") == "-" else total
|
||||
if len(text) == 10 and text[4] == "-" and text[7] == "-":
|
||||
return datetime.strptime(text, "%Y-%m-%d").replace(tzinfo=default_tz)
|
||||
try:
|
||||
moment = datetime.fromisoformat(text.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
if moment.tzinfo is None:
|
||||
moment = moment.replace(tzinfo=default_tz)
|
||||
return moment
|
||||
|
||||
|
||||
def _parse_events(payloads, default_tz):
|
||||
events = []
|
||||
for payload in payloads:
|
||||
current = None
|
||||
for line in _unfold(payload):
|
||||
name, params, value = _parse_property(line)
|
||||
if name == "BEGIN" and value.strip().upper() == "VEVENT":
|
||||
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
|
||||
def _event_end(event, default_tz):
|
||||
end = _parse_when(event.get("end"), default_tz)
|
||||
if end is not None:
|
||||
return end
|
||||
start = _parse_when(event.get("start"), default_tz)
|
||||
if start is None:
|
||||
return None
|
||||
if event.get("all_day"):
|
||||
return event["start"] + timedelta(days=1)
|
||||
return event["start"]
|
||||
return start + timedelta(days=1)
|
||||
return start
|
||||
|
||||
|
||||
def _pick_next(events, now):
|
||||
current_or_future = [event for event in events if _event_end(event) >= now]
|
||||
if not current_or_future:
|
||||
def _pick_next(events, now, default_tz):
|
||||
candidates = []
|
||||
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 min(current_or_future, key=lambda event: event["start"])
|
||||
return min(candidates, key=lambda pair: pair[0])[1]
|
||||
|
||||
|
||||
def _format_when(event):
|
||||
start = event["start"]
|
||||
def _format_when(event, default_tz):
|
||||
start = _parse_when(event.get("start"), default_tz)
|
||||
if start is None:
|
||||
return "(unknown time)"
|
||||
if event.get("all_day"):
|
||||
return start.strftime("%Y-%m-%d (all day)")
|
||||
return start.strftime("%Y-%m-%d %H:%M %Z")
|
||||
@@ -358,21 +185,31 @@ def _format_when(event):
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
try:
|
||||
calendars = _discover_calendars(ctx)
|
||||
except CalDavError as exc:
|
||||
decisions = []
|
||||
base_url = str(ctx.config.get("nextcloud_bridge_url", "") or "").rstrip("/")
|
||||
headers = _headers(ctx.config.get("nextcloud_bridge_token", ""))
|
||||
|
||||
status, payload = _call("GET", f"{base_url}/calendars", headers)
|
||||
if status != 200:
|
||||
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,
|
||||
decisions=decisions,
|
||||
)
|
||||
calendars = [c for c in (payload.get("calendars") or []) if c.get("name")]
|
||||
if not calendars:
|
||||
return ActionResult(
|
||||
action_log="calendar discovery failed: no calendars found",
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
decisions = []
|
||||
calendar = _resolve_calendar(ctx, request, calendars, decisions)
|
||||
calendar = _resolve_calendar(
|
||||
ctx, request, calendars, payload.get("default"), decisions
|
||||
)
|
||||
if not calendar:
|
||||
return ActionResult(
|
||||
action_log="aborted: no calendar resolved.",
|
||||
@@ -384,23 +221,28 @@ def act(ctx, request):
|
||||
local_tz = now.tzinfo or timezone.utc
|
||||
window_start = now - timedelta(days=1)
|
||||
window_end = now + timedelta(days=LOOKAHEAD_DAYS)
|
||||
try:
|
||||
body = _request(
|
||||
ctx,
|
||||
"REPORT",
|
||||
_calendar_path(ctx, calendar),
|
||||
_report_body(window_start, window_end),
|
||||
depth="1",
|
||||
)
|
||||
events = _parse_events(_calendar_payloads(body), local_tz)
|
||||
except CalDavError as exc:
|
||||
query = urllib.parse.urlencode(
|
||||
{
|
||||
"calendar": calendar,
|
||||
"start": window_start.isoformat(),
|
||||
"end": window_end.isoformat(),
|
||||
}
|
||||
)
|
||||
status, payload = _call(
|
||||
"GET", f"{base_url}/calendars/events?{query}", headers
|
||||
)
|
||||
if status != 200:
|
||||
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,
|
||||
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:
|
||||
message = (
|
||||
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)
|
||||
|
||||
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}"
|
||||
if next_event.get("location"):
|
||||
message += f" at {next_event['location']}"
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
"""Hermetic mechanics test for nextcloud.next_event.
|
||||
|
||||
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
|
||||
real CalDAV requests, discovers calendars, resolves the calendar through a
|
||||
SemIf sub-decision (a strong winner is used, otherwise the configured default,
|
||||
otherwise the weak winner), parses expanded iCalendar events, and fails honestly
|
||||
when the service errors. It does NOT prove the live integration — only a real
|
||||
run against the user's Nextcloud does.
|
||||
http.server plays the Nextcloud bridge's JSON API (`GET /calendars` and
|
||||
`GET /calendars/events`). This proves the body lists calendars through the
|
||||
bridge, resolves the calendar through a SemIf sub-decision (a strong winner is
|
||||
used, otherwise the configured default, otherwise the weak winner), asks for the
|
||||
events in a bounded window, picks the earliest not-yet-ended one, and fails
|
||||
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 threading
|
||||
import urllib.parse
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
@@ -21,32 +23,42 @@ from semif_agent.skills import ActionContext
|
||||
import skill
|
||||
|
||||
CALENDARS = [("personal", "Personal"), ("work", "Work")]
|
||||
ICS = ""
|
||||
|
||||
|
||||
def build_ics():
|
||||
def build_events():
|
||||
"""Fixture events relative to now, so the test never rots."""
|
||||
now = datetime.now(timezone.utc)
|
||||
past = now - timedelta(days=2)
|
||||
soon = now + timedelta(hours=2)
|
||||
all_day = (now + timedelta(days=2)).date()
|
||||
|
||||
def stamp(value):
|
||||
return value.strftime("%Y%m%dT%H%M%SZ")
|
||||
def iso(value):
|
||||
return value.isoformat()
|
||||
|
||||
return (
|
||||
"BEGIN:VCALENDAR\nVERSION:2.0\n"
|
||||
"BEGIN:VEVENT\nUID:past@example\n"
|
||||
f"DTSTART:{stamp(past)}\nDTEND:{stamp(past + timedelta(hours=1))}\n"
|
||||
"SUMMARY:Already happened\nEND:VEVENT\n"
|
||||
"BEGIN:VEVENT\nUID:soon@example\n"
|
||||
f"DTSTART:{stamp(soon)}\nDTEND:{stamp(soon + timedelta(hours=1))}\n"
|
||||
"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"
|
||||
"SUMMARY:Offsite\nEND:VEVENT\n"
|
||||
"END:VCALENDAR"
|
||||
)
|
||||
return [
|
||||
{
|
||||
"uid": "past@example",
|
||||
"summary": "Already happened",
|
||||
"start": iso(past),
|
||||
"end": iso(past + timedelta(hours=1)),
|
||||
"all_day": False,
|
||||
},
|
||||
{
|
||||
"uid": "soon@example",
|
||||
"summary": "Team sync",
|
||||
"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:
|
||||
@@ -77,89 +89,64 @@ class FakeEngine:
|
||||
)
|
||||
|
||||
|
||||
class CalDavHandler(BaseHTTPRequestHandler):
|
||||
class BridgeHandler(BaseHTTPRequestHandler):
|
||||
requests = []
|
||||
calendar_count = 2
|
||||
report_status = 207
|
||||
events_status = 200
|
||||
default = "personal"
|
||||
events = []
|
||||
|
||||
def _record(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
body = self.rfile.read(length) if length else b""
|
||||
self.requests.append(
|
||||
{
|
||||
"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")
|
||||
def _json(self, payload, status=200):
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_PROPFIND(self):
|
||||
self._record()
|
||||
responses = "".join(
|
||||
f"<d:response><d:href>/remote.php/dav/calendars/testuser/{name}/</d:href>"
|
||||
"<d:propstat><d:prop>"
|
||||
f"<d:displayname>{label}</d:displayname>"
|
||||
"<d:resourcetype><d:collection/><c:calendar/></d:resourcetype>"
|
||||
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>"
|
||||
for name, label in CALENDARS[: self.calendar_count]
|
||||
)
|
||||
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()
|
||||
def do_GET(self):
|
||||
parsed = urllib.parse.urlparse(self.path)
|
||||
query = urllib.parse.parse_qs(parsed.query)
|
||||
self.requests.append({"path": parsed.path, "query": query})
|
||||
if parsed.path == "/calendars":
|
||||
calendars = [
|
||||
{"name": name, "label": label}
|
||||
for name, label in CALENDARS[: self.calendar_count]
|
||||
]
|
||||
self._json({"calendars": calendars, "default": self.default})
|
||||
return
|
||||
self._multistatus(
|
||||
'<?xml version="1.0" encoding="utf-8"?>'
|
||||
'<d:multistatus xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">'
|
||||
"<d:response>"
|
||||
"<d:href>/remote.php/dav/calendars/testuser/work/event.ics</d:href>"
|
||||
"<d:propstat><d:prop>"
|
||||
f"<c:calendar-data>{ICS}</c:calendar-data>"
|
||||
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>"
|
||||
"</d:response></d:multistatus>"
|
||||
)
|
||||
if parsed.path == "/calendars/events":
|
||||
if self.events_status != 200:
|
||||
self._json({"error": "boom"}, self.events_status)
|
||||
return
|
||||
calendar = query.get("calendar", [""])[0]
|
||||
self._json({"calendar": calendar, "events": self.events})
|
||||
return
|
||||
self._json({"error": "not found"}, 404)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
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)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def fixture_config(url, default="personal"):
|
||||
def fixture_config(url):
|
||||
return {
|
||||
"nextcloud_url": url,
|
||||
"nextcloud_username": "testuser",
|
||||
"nextcloud_app_password": "app-pw",
|
||||
"nextcloud_default_calendar": default,
|
||||
"nextcloud_bridge_url": url,
|
||||
"nextcloud_bridge_token": "",
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
global ICS
|
||||
ICS = build_ics()
|
||||
|
||||
# A strong winner is used even though a default is configured.
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
@@ -176,15 +163,13 @@ def main():
|
||||
assert "Team sync" in action.action_log, action.action_log
|
||||
assert action.new_state, "act must set a new state"
|
||||
|
||||
commands = [entry["command"] for entry in handler.requests]
|
||||
assert commands == ["PROPFIND", "REPORT"], commands
|
||||
report = handler.requests[1]
|
||||
assert report["path"] == "/remote.php/dav/calendars/testuser/work/", report["path"]
|
||||
assert report["depth"] == "1", report["depth"]
|
||||
expected_auth = "Basic " + base64.b64encode(b"testuser:app-pw").decode("ascii")
|
||||
assert report["authorization"] == expected_auth, report["authorization"]
|
||||
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"
|
||||
assert [entry["path"] for entry in handler.requests] == [
|
||||
"/calendars",
|
||||
"/calendars/events",
|
||||
], handler.requests
|
||||
events_call = handler.requests[1]
|
||||
assert events_call["query"]["calendar"] == ["work"], events_call["query"]
|
||||
assert "start" in events_call["query"] and "end" in events_call["query"]
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
@@ -194,11 +179,11 @@ def main():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
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?")
|
||||
action = skill.act(ctx, request)
|
||||
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
|
||||
print(action.action_log)
|
||||
finally:
|
||||
@@ -206,14 +191,14 @@ def main():
|
||||
server.server_close()
|
||||
|
||||
# A weak winner with no configured default stands.
|
||||
server, handler, url = start_server()
|
||||
server, handler, url = start_server(default="")
|
||||
try:
|
||||
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?")
|
||||
action = skill.act(ctx, request)
|
||||
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)
|
||||
finally:
|
||||
server.shutdown()
|
||||
@@ -228,14 +213,14 @@ def main():
|
||||
action = skill.act(ctx, request)
|
||||
assert engine.decisions == [], "a single calendar needs no SemIf decision"
|
||||
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)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
# A failing REPORT is reported honestly.
|
||||
server, handler, url = start_server(report_status=500)
|
||||
# A failing events read is reported honestly.
|
||||
server, handler, url = start_server(events_status=500)
|
||||
try:
|
||||
engine = FakeEngine(pick="personal")
|
||||
ctx = ActionContext(engine=engine, config=fixture_config(url))
|
||||
|
||||
Reference in new issue
Block a user