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,8 +1,9 @@
|
||||
"""Create a calendar event on the user's Nextcloud calendar from a request.
|
||||
|
||||
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 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`,
|
||||
@@ -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
|
||||
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 discovered over PROPFIND 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 with a real CalDAV PUT (iCalendar, UTC timestamps,
|
||||
`If-None-Match: *`) and the real outcome is reported.
|
||||
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
|
||||
@@ -25,14 +26,10 @@ rather than guessing.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import datetime, time, timedelta, timezone
|
||||
|
||||
from semif_agent.decisions import DecisionRequest, Option
|
||||
@@ -40,42 +37,28 @@ 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",
|
||||
"llm_bridge_url",
|
||||
"llm_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 used.",
|
||||
"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).",
|
||||
"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.",
|
||||
}
|
||||
|
||||
DAV = "DAV:"
|
||||
CALDAV = "urn:ietf:params:xml:ns:caldav"
|
||||
TIMEOUT_SECONDS = 30
|
||||
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
|
||||
|
||||
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 = {
|
||||
"monday": 0,
|
||||
"mon": 0,
|
||||
@@ -118,13 +101,6 @@ _MONTH_ALT = (
|
||||
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):
|
||||
"""Current time (aware) in the user's timezone: the top-level `timezone`
|
||||
@@ -132,84 +108,33 @@ def _now(ctx):
|
||||
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):
|
||||
url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/")
|
||||
username = str(ctx.config.get("nextcloud_username", "") or "").strip()
|
||||
password = str(ctx.config.get("nextcloud_app_password", "") or "")
|
||||
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")
|
||||
headers = {"Authorization": f"Basic {token}", "Depth": depth}
|
||||
if body is not None:
|
||||
headers["Content-Type"] = content_type
|
||||
if extra_headers:
|
||||
headers.update(extra_headers)
|
||||
request = urllib.request.Request(
|
||||
url + path, data=body, method=method, headers=headers
|
||||
)
|
||||
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(request, timeout=TIMEOUT_SECONDS) as response:
|
||||
return response.status, 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 ----
|
||||
|
||||
|
||||
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)}/"
|
||||
)
|
||||
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 ----
|
||||
@@ -219,13 +144,12 @@ 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. Raises `BridgeError` when the bridge is
|
||||
unreachable or the reply carries no usable object.
|
||||
object the prompt asks for. Returns `(fields, error)`.
|
||||
"""
|
||||
base = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
|
||||
if not base:
|
||||
raise BridgeError("llm_bridge_url is not configured")
|
||||
token = str(ctx.config.get("llm_bridge_token", "") or "").strip()
|
||||
return None, "llm_bridge_url is not configured"
|
||||
headers = _headers(ctx.config.get("llm_bridge_token", ""))
|
||||
messages = [
|
||||
{
|
||||
"role": "system",
|
||||
@@ -238,41 +162,40 @@ def _extract_fields(ctx, request):
|
||||
},
|
||||
{"role": "user", "content": request.text},
|
||||
]
|
||||
payload = json.dumps({"messages": messages}).encode("utf-8")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Semif-Token"] = token
|
||||
http_request = urllib.request.Request(
|
||||
base + "/chat", data=payload, method="POST", headers=headers
|
||||
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:
|
||||
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
|
||||
data = json.loads(response.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as 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 ""))
|
||||
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 BridgeError("llm bridge returned no JSON object")
|
||||
raise ValueError("llm bridge returned no JSON object")
|
||||
try:
|
||||
data = json.loads(text[start : end + 1])
|
||||
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):
|
||||
raise BridgeError("llm bridge returned JSON that is not an object")
|
||||
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])
|
||||
|
||||
@@ -432,21 +355,29 @@ def _parse_when(text, now):
|
||||
# ---- calendar resolution ----
|
||||
|
||||
|
||||
def _resolve_calendar(ctx, request, calendars, decisions):
|
||||
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
|
||||
default = None
|
||||
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(), calendar["label"].lower()):
|
||||
default = calendar
|
||||
break
|
||||
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["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))
|
||||
@@ -458,48 +389,6 @@ def _resolve_calendar(ctx, request, calendars, decisions):
|
||||
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 ----
|
||||
|
||||
|
||||
@@ -522,13 +411,9 @@ def act(ctx, request):
|
||||
|
||||
fields = request.meta.get("create_event_fields")
|
||||
if fields is None:
|
||||
try:
|
||||
fields = _extract_fields(ctx, request)
|
||||
except BridgeError as exc:
|
||||
return ActionResult(
|
||||
action_log=str(exc),
|
||||
new_state=request.text,
|
||||
)
|
||||
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"]
|
||||
@@ -572,42 +457,56 @@ def act(ctx, request):
|
||||
duration = timedelta(minutes=parsed["duration_minutes"] or DEFAULT_DURATION_MINUTES)
|
||||
end = start + duration
|
||||
|
||||
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"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,
|
||||
)
|
||||
|
||||
decisions = []
|
||||
calendar = _resolve_calendar(ctx, request, calendars, decisions)
|
||||
|
||||
uid = f"{uuid.uuid4().hex}@semif-agent"
|
||||
body = _build_ics(
|
||||
uid, title, start, end, all_day, _utc_stamp(now), description=description
|
||||
calendar = _resolve_calendar(
|
||||
ctx, request, calendars, payload.get("default"), decisions
|
||||
)
|
||||
path = _calendar_path(ctx, calendar) + urllib.parse.quote(uid, safe="") + ".ics"
|
||||
try:
|
||||
_request(
|
||||
ctx,
|
||||
"PUT",
|
||||
path,
|
||||
body=body,
|
||||
depth="0",
|
||||
content_type="text/calendar; charset=utf-8",
|
||||
extra_headers={"If-None-Match": "*"},
|
||||
)
|
||||
except CalDavError as exc:
|
||||
|
||||
# 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 "
|
||||
f"{calendar!r}: {exc}"
|
||||
f"could not create {title!r} on {calendar!r}: status {status}, "
|
||||
f"{payload.get('error', payload)}"
|
||||
),
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
@@ -620,9 +519,10 @@ def act(ctx, request):
|
||||
f"{start.strftime('%Y-%m-%d %H:%M %Z')}–"
|
||||
f"{end.strftime('%H:%M %Z')}"
|
||||
)
|
||||
report = f"Created {title!r} on calendar {calendar!r}: {when_text} (UID {uid})."
|
||||
return ActionResult(
|
||||
action_log=report,
|
||||
new_state=report,
|
||||
decisions=decisions,
|
||||
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)
|
||||
Reference in new issue
Block a user