"""Report the next upcoming event on the user's Nextcloud 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` 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. A failure talking to the bridge is reported honestly rather than guessed at. """ from __future__ import annotations import json import urllib.error import urllib.parse import urllib.request from datetime import datetime, timedelta, timezone from semif_agent.decisions import DecisionRequest, Option from semif_agent.skills import ActionResult from semif_agent.timers import local_now INTEGRATION = { "service": "nextcloud", "transport": "http", "config_vars": [ "nextcloud_bridge_url", "nextcloud_bridge_token", ], } CONTRACT = { "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.", } LOOKAHEAD_DAYS = 60 # 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 def _now(ctx): """Current time (aware) in the user's timezone: the top-level `timezone` config value when set, else host local. A test seam; never freezes time.""" return local_now(ctx.config) 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 _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(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: 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(calendars, default_name): """The configured default calendar, if it is one of the account's.""" default_name = str(default_name or "").strip().lower() for calendar in calendars: 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, 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(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.get("label") or c["name"]) for c in calendars ], ) result = ctx.engine.call(decision) decisions.append((decision, result)) winner = result.selected if result.prob(winner) >= CALENDAR_WINNER_TAU: return winner if default is not None: return default["name"] return winner # ---- event parsing ---- def _parse_when(value, default_tz): """Parse a bridge event timestamp into an aware datetime. 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 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 _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 start + timedelta(days=1) return start 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(candidates, key=lambda pair: pair[0])[1] 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") # ---- skill phases ---- def act(ctx, request): 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"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, ) calendar = _resolve_calendar( ctx, request, calendars, payload.get("default"), decisions ) if not calendar: return ActionResult( action_log="aborted: no calendar resolved.", new_state=request.text, decisions=decisions, ) now = _now(ctx) local_tz = now.tzinfo or timezone.utc window_start = now - timedelta(days=1) window_end = now + timedelta(days=LOOKAHEAD_DAYS) 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}: status {status}, " f"{payload.get('error', payload)}" ), new_state=request.text, decisions=decisions, ) 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 " f"{window_end.strftime('%Y-%m-%d')}." ) return ActionResult(action_log=message, new_state=message, decisions=decisions) summary = next_event.get("summary") or "(no title)" 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']}" return ActionResult(action_log=message, new_state=message, decisions=decisions)