"""Create a calendar event on the user's Nextcloud calendar from a request. Real integration: the Nextcloud bridge over HTTP, which fronts the user's Nextcloud (CalDAV). The bridge URL/token and the LLM 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` 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`, `llm_bridge_token`) with one generic chat call, cached in `request.meta` so a `needs_input` resume does not re-call it; the start date/time and duration are 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 from the top after a `needs_input` pause, the body never re-asks a question it already has an answer for. Calendars are listed through the bridge (`GET /calendars`) and the target is resolved by a single SemIf choice over every owned calendar (state = the user query), asking which one the request refers to; a strong winner (probability >= `CALENDAR_WINNER_TAU`) is used, otherwise the configured default calendar is used. The event is created for real with `POST /calendars/events` and the real outcome is reported. 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 rather than guessing. """ from __future__ import annotations import json import re import urllib.error import urllib.request from datetime import datetime, time, 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", "llm_bridge_url", "llm_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 create the event.", "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.", "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.", } DEFAULT_DURATION_MINUTES = 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 _WEEKDAYS = { "monday": 0, "mon": 0, "tuesday": 1, "tue": 1, "tues": 1, "wednesday": 2, "wed": 2, "thursday": 3, "thu": 3, "thur": 3, "thurs": 3, "friday": 4, "fri": 4, "saturday": 5, "sat": 5, "sunday": 6, "sun": 6, } _WEEKDAY_RE = re.compile( r"\b(" + "|".join(sorted(_WEEKDAYS, key=len, reverse=True)) + r")\b", re.I ) _MONTHS = { "jan": 1, "feb": 2, "mar": 3, "apr": 4, "may": 5, "jun": 6, "jul": 7, "aug": 8, "sep": 9, "oct": 10, "nov": 11, "dec": 12, } _MONTH_ALT = ( r"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?" r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?" ) 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) # ---- bridge 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 _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)} # ---- LLM field extraction ---- def _extract_fields(ctx, request): """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 object the prompt asks for. Returns `(fields, error)`. """ base = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/") if not base: return None, "llm_bridge_url is not configured" headers = _headers(ctx.config.get("llm_bridge_token", "")) messages = [ { "role": "system", "content": ( "Extract the calendar event from the user's request. Reply with " 'ONLY a JSON object: {"title": "", ' '"description": ""}. The title must ' "not contain the date, the time, or words like add/schedule/create." ), }, {"role": "user", "content": request.text}, ] status, payload = _call( "POST", f"{base}/chat", headers, {"messages": messages, "max_tokens": 200} ) if status != 200: return ( None, f"llm bridge /chat: status {status}, {payload.get('error', payload)}", ) try: return _parse_fields(str(payload.get("text") or "")), None except ValueError as exc: return None, str(exc) def _parse_fields(text): """Pull the `{"title","description"}` object out of the model's reply.""" start, end = text.find("{"), text.rfind("}") if start == -1 or end < start: raise ValueError("llm bridge returned no JSON object") try: data = json.loads(text[start : end + 1]) except ValueError as exc: raise ValueError(f"llm bridge returned invalid JSON: {exc}") from exc if not isinstance(data, dict): raise ValueError("llm bridge returned JSON that is not an object") return { "title": str(data.get("title") or "").strip(), "description": str(data.get("description") or "").strip(), } # ---- date/time parsing ---- def _month_number(token): return _MONTHS.get(token.lower()[:3]) def _resolve_month_day(month, day, year, now): if not (month and 1 <= day <= 31): return None given_year = year is not None year = year or now.year try: candidate = datetime(year, month, day).date() except ValueError: return None if not given_year and candidate < now.date(): try: candidate = datetime(year + 1, month, day).date() except ValueError: return None return candidate def _parse_when(text, now): """Best-effort extraction of date/time/duration from free text. Returns a dict with `date` (datetime.date | None), `time` (datetime.time | None), `all_day` (bool), `duration_minutes` (int | None) and `from_weekday` (bool). The title and description come from the LLM bridge, so no matched spans are tracked here. """ text = text or "" result = { "date": None, "time": None, "all_day": False, "duration_minutes": None, "from_weekday": False, } match = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", text, re.I) if match: result["all_day"] = True match = re.search(r"\bfor\s+(\d+(?:\.\d+)?)\s*(hours?|hrs?|h)\b", text, re.I) if match: result["duration_minutes"] = int(round(float(match.group(1)) * 60)) else: match = re.search(r"\bfor\s+(\d+)\s*(minutes?|mins?|m)\b", text, re.I) if match: result["duration_minutes"] = int(match.group(1)) else: for phrase, minutes in ( (r"\bfor\s+half\s+an?\s+hour\b", 30), (r"\bfor\s+an?\s+hour\b", 60), (r"\bfor\s+a\s+couple\s+of\s+hours\b", 120), ): match = re.search(phrase, text, re.I) if match: result["duration_minutes"] = minutes break date = None match = re.search(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", text) if match: try: date = datetime( int(match.group(1)), int(match.group(2)), int(match.group(3)) ).date() except ValueError: date = None if date is None: match = re.search( r"\b(" + _MONTH_ALT + r")\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?\b", text, re.I, ) if match: month = _month_number(match.group(1)) year = int(match.group(3)) if match.group(3) else None date = _resolve_month_day(month, int(match.group(2)), year, now) if date is None: match = re.search( r"\b(\d{1,2})(?:st|nd|rd|th)?\s+(?:of\s+)?(" + _MONTH_ALT + r")(?:,?\s*(\d{4}))?\b", text, re.I, ) if match: month = _month_number(match.group(2)) year = int(match.group(3)) if match.group(3) else None date = _resolve_month_day(month, int(match.group(1)), year, now) if date is None: match = re.search(r"\b(\d{1,2})/(\d{1,2})(?:/(\d{2,4}))?\b", text) if match: first, second = int(match.group(1)), int(match.group(2)) month, day = (first, second) if first <= 12 else (second, first) year = int(match.group(3)) if match.group(3) else None if year is not None and year < 100: year += 2000 date = _resolve_month_day(month, day, year, now) if date is None: match = re.search( r"\b(today|tonight|tomorrow|tmrw|tomorow|next\s+week)\b", text, re.I ) if match: word = re.sub(r"\s+", " ", match.group(1).lower()) if word in ("today", "tonight"): date = now.date() elif word in ("tomorrow", "tmrw", "tomorow"): date = now.date() + timedelta(days=1) else: date = now.date() + timedelta(days=7) if date is None: match = _WEEKDAY_RE.search(text) if match: target = _WEEKDAYS[match.group(1).lower()] date = now.date() + timedelta(days=(target - now.date().weekday()) % 7) prefix = text[max(0, match.start() - 6):match.start()] if re.search(r"\bnext\s*$", prefix, re.I): date += timedelta(days=7) result["from_weekday"] = True parsed_time = None match = re.search(r"\bnoon\b", text, re.I) if match: parsed_time = time(12, 0) elif re.search(r"\bmidnight\b", text, re.I): parsed_time = time(0, 0) else: match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I) if match: hour = int(match.group(1)) % 12 minute = int(match.group(2) or 0) if match.group(3).lower() == "p": hour += 12 if hour < 24 and minute < 60: parsed_time = time(hour, minute) else: match = re.search(r"\b(\d{1,2}):(\d{2})\b", text) if match: hour, minute = int(match.group(1)), int(match.group(2)) if hour < 24 and minute < 60: parsed_time = time(hour, minute) else: match = re.search(r"\bat\s+(\d{1,2})\b", text, re.I) if match and 13 <= int(match.group(1)) < 24: parsed_time = time(int(match.group(1)), 0) result["date"] = date result["time"] = parsed_time return result # ---- 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): 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 # ---- skill phases ---- def _ask(request, field, question): request.meta["create_event_awaiting"] = field return ActionResult( action_log=f"waiting for {field}", new_state=request.text, needs_input=question, ) def act(ctx, request): answers = request.meta.setdefault("create_event_answers", {}) awaiting = request.meta.get("create_event_awaiting") if request.user_input is not None and awaiting: if answers.get(awaiting) != request.user_input.strip(): answers[awaiting] = request.user_input.strip() request.meta.pop("create_event_awaiting", None) fields = request.meta.get("create_event_fields") if fields is None: fields, error = _extract_fields(ctx, request) if error: return ActionResult(action_log=error, new_state=request.text) request.meta["create_event_fields"] = fields title = fields["title"] description = fields["description"] now = _now(ctx) parsed = _parse_when(request.text, now) if answers.get("title"): title = answers["title"].strip() for key in ("date", "time"): if answers.get(key): extra = _parse_when(answers[key], now) if extra["date"] is not None: parsed["date"] = extra["date"] parsed["from_weekday"] = extra["from_weekday"] if extra["time"] is not None: parsed["time"] = extra["time"] if extra["all_day"]: parsed["all_day"] = True if extra["duration_minutes"]: parsed["duration_minutes"] = extra["duration_minutes"] if not title: return _ask(request, "title", "What should I call the event?") if parsed["date"] is None: return _ask(request, "date", f"What day should I schedule {title!r}?") if not parsed["all_day"] and parsed["time"] is None: return _ask(request, "time", f"What time should {title!r} start? (or say 'all day')") local_tz = now.tzinfo or timezone.utc all_day = bool(parsed["all_day"]) if all_day: start_date = parsed["date"] end_date = start_date + timedelta(days=1) start = datetime.combine(start_date, time(0, 0), tzinfo=local_tz) end = datetime.combine(end_date, time(0, 0), tzinfo=local_tz) else: start = datetime.combine(parsed["date"], parsed["time"], tzinfo=local_tz) if start <= now and parsed.get("from_weekday"): start += timedelta(days=7) duration = timedelta(minutes=parsed["duration_minutes"] or DEFAULT_DURATION_MINUTES) end = start + duration 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: status {status}, " f"{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="no calendars found on the account", new_state=request.text, decisions=decisions, ) calendar = _resolve_calendar( ctx, request, calendars, payload.get("default"), decisions ) # An all-day event sends date-only bounds; a timed event sends ISO instants. if all_day: start_value, end_value = start_date.isoformat(), end_date.isoformat() else: start_value, end_value = start.isoformat(), end.isoformat() status, payload = _call( "POST", f"{base_url}/calendars/events", headers, { "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( action_log=( f"could not create {title!r} on {calendar!r}: status {status}, " f"{payload.get('error', payload)}" ), new_state=request.text, decisions=decisions, ) if all_day: when_text = f"{start_date.isoformat()} (all day)" else: when_text = ( f"{start.strftime('%Y-%m-%d %H:%M %Z')}–" f"{end.strftime('%H:%M %Z')}" ) uid = payload.get("uid", "") created_calendar = payload.get("calendar", calendar) report = ( f"Created {title!r} on calendar {created_calendar!r}: {when_text} " f"(UID {uid})." ) return ActionResult(action_log=report, new_state=report, decisions=decisions)