Abstract seeds into modular skill packs + split config
Group committed starter skills into packs (semif_agent/packs.py) that bind a
concern to its categories, bridge(s), requirements, and config schema:
- seeds/ -> packs/<name>/ with a pack.json manifest + skills/<category>/<leaf>/.
Shipped: nextcloud, simplex, outlook, browser (each owning its bridge) and
essentials (time + calculator, no bridge).
- PackRegistry discovers packs (a root with no manifest is one implicit pack);
merge_packs loads every enabled pack. Pack enable is one switch
(packs.<name>.enabled -> bridges.<bridge>.enabled -> enabled_by_default);
disabling a pack drops its categories (incl. generated bodies) and its bridge.
- CATEGORY_DESCRIPTIONS now comes from the pack manifests (built-ins stay).
Adopt a Home-Assistant-style layered config (semif_agent/config.py):
- config.json is a thin index ({"include": [...]}) over config/core.json,
config/gateway.json, config/bridges.json, config/packs/*.json, deep-merged.
- Secrets live in the gitignored secrets.json, referenced as "!secret <key>";
api_key_env is removed.
- CORE_SCHEMA + each pack's config schema own defaults and GENERATE the
committed config.example.json; new `check-config` (validate + --write-example)
and `config-init` (seed the split layout) commands.
- scripts/config_merge.py (stdlib) lets bootstrap read the merged config.
Tests: tests/test_packs.py (renamed from test_seed_skills, +enable/merge),
new tests/test_config.py. All unit tests pass (772).
This commit is contained in:
1 parent
b953475bf7
commit
78b4621ba0
115 files changed
+1701
-398
No files matched your search
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "nextcloud",
|
||||
"title": "Nextcloud",
|
||||
"concern": "The user's Nextcloud account: calendar events and scheduling, to-do tasks, files, contacts, and notes.",
|
||||
"categories": {
|
||||
"nextcloud": "Nextcloud productivity: the user's calendar events and scheduling (reading or changing events and reminders) and the user's to-do tasks and task lists."
|
||||
},
|
||||
"bridges": ["nextcloud"],
|
||||
"requires": [],
|
||||
"enabled_by_default": true,
|
||||
"config": {
|
||||
"enabled": {"type": "bool", "default": true, "doc": "Load this pack's skills and run its bridge."},
|
||||
"host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."},
|
||||
"port": {"type": "int", "default": 5230, "doc": "Bridge listen port."},
|
||||
"token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."},
|
||||
"url": {"type": "str", "default": "", "doc": "Nextcloud base URL, e.g. https://cloud.example.com."},
|
||||
"username": {"type": "str", "default": "", "doc": "Nextcloud username."},
|
||||
"app_password": {"type": "str", "default": "", "secret": true, "doc": "Nextcloud app password (Settings > Security > Devices & sessions), not the account password."},
|
||||
"default_calendar": {"type": "str", "default": "", "doc": "Calendar used when a request names none and the account has several."},
|
||||
"default_task_calendar": {"type": "str", "default": "", "doc": "VTODO-capable task list used when a request names none."},
|
||||
"default_addressbook": {"type": "str", "default": "", "doc": "Addressbook used when a request names none."},
|
||||
"verify_tls": {"type": "bool", "default": true, "doc": "false skips certificate verification (self-signed hosts)."},
|
||||
"timeout": {"type": "int", "default": 30, "doc": "Per-request timeout in seconds."}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"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).",
|
||||
"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."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Create a calendar event from a request such as \"add Ashley's dance recital for 5pm Tuesday\"."
|
||||
}
|
||||
@@ -0,0 +1,628 @@
|
||||
"""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`).
|
||||
|
||||
`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 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.
|
||||
|
||||
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 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
|
||||
from semif_agent.skills import ActionResult
|
||||
from semif_agent.timers import local_now
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "nextcloud_calendar",
|
||||
"transport": "caldav",
|
||||
"config_vars": [
|
||||
"nextcloud_url",
|
||||
"nextcloud_username",
|
||||
"nextcloud_app_password",
|
||||
"nextcloud_default_calendar",
|
||||
"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).",
|
||||
"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,
|
||||
"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)?"
|
||||
)
|
||||
|
||||
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`
|
||||
config value when set, else host local. A test seam; never freezes time."""
|
||||
return local_now(ctx.config)
|
||||
|
||||
|
||||
# ---- 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
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
|
||||
return response.status, response.read()
|
||||
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)}/"
|
||||
)
|
||||
|
||||
|
||||
# ---- 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. Raises `BridgeError` when the bridge is
|
||||
unreachable or the reply carries no usable object.
|
||||
"""
|
||||
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()
|
||||
messages = [
|
||||
{
|
||||
"role": "system",
|
||||
"content": (
|
||||
"Extract the calendar event from the user's request. Reply with "
|
||||
'ONLY a JSON object: {"title": "<short event title>", '
|
||||
'"description": "<one short sentence, or empty>"}. The title must '
|
||||
"not contain the date, the time, or words like add/schedule/create."
|
||||
),
|
||||
},
|
||||
{"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
|
||||
)
|
||||
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 ""))
|
||||
|
||||
|
||||
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")
|
||||
try:
|
||||
data = json.loads(text[start : end + 1])
|
||||
except ValueError as exc:
|
||||
raise BridgeError(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")
|
||||
return {
|
||||
"title": str(data.get("title") or "").strip(),
|
||||
"description": str(data.get("description") or "").strip(),
|
||||
}
|
||||
|
||||
|
||||
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 _resolve_calendar(ctx, request, calendars, decisions):
|
||||
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
|
||||
default = None
|
||||
for calendar in calendars:
|
||||
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()):
|
||||
default = calendar
|
||||
break
|
||||
|
||||
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],
|
||||
)
|
||||
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
|
||||
|
||||
|
||||
# ---- 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 ----
|
||||
|
||||
|
||||
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:
|
||||
try:
|
||||
fields = _extract_fields(ctx, request)
|
||||
except BridgeError as exc:
|
||||
return ActionResult(
|
||||
action_log=str(exc),
|
||||
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
|
||||
|
||||
try:
|
||||
calendars = _discover_calendars(ctx)
|
||||
except CalDavError as exc:
|
||||
return ActionResult(
|
||||
action_log=f"calendar discovery failed: {exc}",
|
||||
new_state=request.text,
|
||||
)
|
||||
if not calendars:
|
||||
return ActionResult(
|
||||
action_log="no calendars found on the account",
|
||||
new_state=request.text,
|
||||
)
|
||||
|
||||
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
|
||||
)
|
||||
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:
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"could not create {title!r} on "
|
||||
f"{calendar!r}: {exc}"
|
||||
),
|
||||
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')}"
|
||||
)
|
||||
report = f"Created {title!r} on calendar {calendar!r}: {when_text} (UID {uid})."
|
||||
return ActionResult(
|
||||
action_log=report,
|
||||
new_state=report,
|
||||
decisions=decisions,
|
||||
)
|
||||
@@ -0,0 +1,451 @@
|
||||
"""Hermetic mechanics test for nextcloud.create_event.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays a Nextcloud CalDAV endpoint (PROPFIND discovery + PUT create)
|
||||
and the LLM bridge's `POST /chat`. This proves the body extracts the event title
|
||||
and description through the LLM bridge (caching the call across a `needs_input`
|
||||
resume), parses the date/time from the request, asks for a missing field and
|
||||
resumes, resolves the target calendar with a SemIf choice over the owned
|
||||
calendars (a strong winner is used, otherwise the configured default), writes a
|
||||
real iCalendar PUT, and fails honestly when the LLM bridge or the server errors.
|
||||
It does NOT prove the live integration — only a real run against the user's
|
||||
Nextcloud does.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import urllib.parse
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from semif_agent.decisions import DecisionResult, Request
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
import skill
|
||||
|
||||
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
|
||||
skill._now = lambda ctx: FIXED_NOW
|
||||
|
||||
DEFAULT_LLM_REPLY = {"title": "event", "description": ""}
|
||||
|
||||
|
||||
def next_weekday(now, weekday):
|
||||
return now.date() + timedelta(days=(weekday - now.date().weekday()) % 7)
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
"""Test-only engine.
|
||||
|
||||
By default it picks the requested option id (else the first) with full
|
||||
confidence. Pass `probs` (a mapping of option id -> probability) to script an
|
||||
arbitrary distribution, e.g. a near-tie that must fall back to the default.
|
||||
"""
|
||||
|
||||
def __init__(self, pick=None, probs=None):
|
||||
self.pick = pick
|
||||
self.probs = probs
|
||||
self.decisions = []
|
||||
|
||||
def call(self, decision):
|
||||
self.decisions.append(decision)
|
||||
option_ids = [option.id for option in decision.options]
|
||||
if self.probs is not None:
|
||||
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
|
||||
else:
|
||||
chosen = self.pick if self.pick in option_ids else option_ids[0]
|
||||
probabilities = [
|
||||
1.0 if option_id == chosen else 0.0 for option_id in option_ids
|
||||
]
|
||||
return DecisionResult(
|
||||
request=decision, option_ids=option_ids, probabilities=probabilities
|
||||
)
|
||||
|
||||
|
||||
class CalDavHandler(BaseHTTPRequestHandler):
|
||||
calendars = []
|
||||
put_status = 201
|
||||
requests = []
|
||||
puts = []
|
||||
llm_reply = DEFAULT_LLM_REPLY
|
||||
llm_status = 200
|
||||
llm_requests = []
|
||||
|
||||
def _read_body(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
return self.rfile.read(length) if length else b""
|
||||
|
||||
def _send(self, payload, status, content_type):
|
||||
body = payload if isinstance(payload, bytes) else payload.encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_PROPFIND(self):
|
||||
self._read_body()
|
||||
self.requests.append(("PROPFIND", self.path))
|
||||
responses = []
|
||||
for calendar in self.calendars:
|
||||
responses.append(
|
||||
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 = (
|
||||
'<?xml version="1.0" encoding="utf-8"?>'
|
||||
'<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):
|
||||
body = self._read_body()
|
||||
if self.path != "/chat":
|
||||
self._send(json.dumps({"error": "not found"}), 404, "application/json")
|
||||
return
|
||||
self.llm_requests.append(body)
|
||||
if self.llm_status != 200:
|
||||
self._send(json.dumps({"error": "boom"}), self.llm_status, "application/json")
|
||||
return
|
||||
self._send(
|
||||
json.dumps({"text": json.dumps(self.llm_reply)}),
|
||||
200,
|
||||
"application/json",
|
||||
)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def start_server(calendars=None, put_status=201, llm_reply=None, llm_status=200):
|
||||
handler = type(
|
||||
"Handler",
|
||||
(CalDavHandler,),
|
||||
{
|
||||
"calendars": calendars
|
||||
if calendars is not None
|
||||
else [
|
||||
{"name": "personal", "label": "Personal"},
|
||||
{"name": "work", "label": "Work"},
|
||||
],
|
||||
"put_status": put_status,
|
||||
"requests": [],
|
||||
"puts": [],
|
||||
"llm_reply": llm_reply if llm_reply is not None else DEFAULT_LLM_REPLY,
|
||||
"llm_status": llm_status,
|
||||
"llm_requests": [],
|
||||
},
|
||||
)
|
||||
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 config(url, default="personal", llm_url=None):
|
||||
return {
|
||||
"nextcloud_url": url,
|
||||
"nextcloud_username": "alice",
|
||||
"nextcloud_app_password": "secret",
|
||||
"nextcloud_default_calendar": default,
|
||||
"llm_bridge_url": url if llm_url is None else llm_url,
|
||||
"llm_bridge_token": "",
|
||||
}
|
||||
|
||||
|
||||
def run(handler, url, text, default="personal", engine=None, llm_url=None):
|
||||
engine = engine or FakeEngine()
|
||||
ctx = ActionContext(engine=engine, config=config(url, default, llm_url))
|
||||
request = Request(text)
|
||||
action = skill.act(ctx, request)
|
||||
return action, request, engine
|
||||
|
||||
|
||||
def test_example_creates_event_on_default_calendar():
|
||||
server, handler, url = start_server(
|
||||
llm_reply={
|
||||
"title": "Ashley's dance recital",
|
||||
"description": "Dance recital at 5pm.",
|
||||
}
|
||||
)
|
||||
try:
|
||||
# The query names no calendar, so the SemIf choice is a near-tie and the
|
||||
# configured default ("personal") wins.
|
||||
engine = FakeEngine(probs={"personal": 0.4, "work": 0.35})
|
||||
action, _request, engine = run(
|
||||
handler,
|
||||
url,
|
||||
"add Ashley's dance recital to the calendar for 5pm Tuesday",
|
||||
engine=engine,
|
||||
)
|
||||
assert action.needs_input is None, action.needs_input
|
||||
assert len(engine.decisions) == 1, "the calendar is chosen with one SemIf decision"
|
||||
assert engine.decisions[0].state == (
|
||||
"add Ashley's dance recital to the calendar for 5pm Tuesday"
|
||||
), engine.decisions[0]
|
||||
assert "referred to in the user query" in engine.decisions[0].question
|
||||
assert len(handler.puts) == 1, handler.puts
|
||||
put = handler.puts[0]
|
||||
assert put["path"].startswith("/remote.php/dav/calendars/alice/personal/"), put
|
||||
assert put["path"].endswith(".ics"), put
|
||||
assert put["headers"].get("If-None-Match") == "*"
|
||||
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)
|
||||
assert f"DTSTART:{tuesday.strftime('%Y%m%d')}T170000Z" in body, body
|
||||
assert f"DTEND:{tuesday.strftime('%Y%m%d')}T180000Z" in body, body
|
||||
assert "Ashley's dance recital" in action.action_log, action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_missing_time_asks_then_creates():
|
||||
server, handler, url = start_server(
|
||||
llm_reply={"title": "dentist appointment", "description": ""}
|
||||
)
|
||||
try:
|
||||
action, request, engine = run(
|
||||
handler, url, "add dentist appointment on 2026-11-10"
|
||||
)
|
||||
assert action.needs_input, "a missing start time must be asked"
|
||||
assert "time" in action.needs_input.lower(), action.needs_input
|
||||
assert handler.puts == []
|
||||
assert len(handler.llm_requests) == 1, "the LLM is called once, then cached"
|
||||
request.user_input = "2pm"
|
||||
ctx = ActionContext(engine=engine, config=config(url))
|
||||
action = skill.act(ctx, request)
|
||||
assert action.needs_input is None, action.needs_input
|
||||
assert len(handler.puts) == 1, handler.puts
|
||||
assert len(handler.llm_requests) == 1, "the resume must reuse the cached fields"
|
||||
body = handler.puts[0]["body"].decode("utf-8")
|
||||
assert "SUMMARY:dentist appointment" in body, body
|
||||
assert "DTSTART:20261110T140000Z" in body, body
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_missing_day_asks_then_creates():
|
||||
server, handler, url = start_server(
|
||||
llm_reply={"title": "dentist appointment", "description": ""}
|
||||
)
|
||||
try:
|
||||
action, request, engine = run(handler, url, "add dentist appointment at 2pm")
|
||||
assert action.needs_input, "a missing day must be asked"
|
||||
assert "day" in action.needs_input.lower(), action.needs_input
|
||||
request.user_input = "2026-11-10"
|
||||
ctx = ActionContext(engine=engine, config=config(url))
|
||||
action = skill.act(ctx, request)
|
||||
assert action.needs_input is None, action.needs_input
|
||||
body = handler.puts[0]["body"].decode("utf-8")
|
||||
assert "DTSTART:20261110T140000Z" in body, body
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_missing_title_asks():
|
||||
server, handler, url = start_server(llm_reply={"title": "", "description": ""})
|
||||
try:
|
||||
action, _request, _engine = run(handler, url, "schedule on 2026-11-10 at 2pm")
|
||||
assert action.needs_input, "a missing title must be asked"
|
||||
assert "call the event" in action.needs_input.lower(), action.needs_input
|
||||
assert handler.puts == []
|
||||
print(action.needs_input)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_named_calendar_is_used():
|
||||
server, handler, url = start_server(
|
||||
llm_reply={"title": "team sync", "description": ""}
|
||||
)
|
||||
try:
|
||||
engine = FakeEngine(pick="work")
|
||||
action, _request, engine = run(
|
||||
handler,
|
||||
url,
|
||||
"add team sync to my work calendar on 2026-11-10 at 9am",
|
||||
engine=engine,
|
||||
)
|
||||
assert action.needs_input is None, action.needs_input
|
||||
assert len(engine.decisions) == 1, engine.decisions
|
||||
assert [option.id for option in engine.decisions[0].options] == [
|
||||
"personal",
|
||||
"work",
|
||||
], engine.decisions[0].options
|
||||
assert handler.puts[0]["path"].startswith(
|
||||
"/remote.php/dav/calendars/alice/work/"
|
||||
), handler.puts[0]
|
||||
body = handler.puts[0]["body"].decode("utf-8")
|
||||
assert "SUMMARY:team sync" in body, body
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_weak_winner_falls_back_to_default():
|
||||
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
|
||||
try:
|
||||
# Work edges out personal but stays below the strong-winner threshold, so
|
||||
# the configured default ("personal") is used instead.
|
||||
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
|
||||
action, _request, engine = run(
|
||||
handler,
|
||||
url,
|
||||
"add standup on 2026-11-10 at 9am",
|
||||
engine=engine,
|
||||
)
|
||||
assert action.needs_input is None, action.needs_input
|
||||
assert len(engine.decisions) == 1, engine.decisions
|
||||
assert handler.puts[0]["path"].startswith(
|
||||
"/remote.php/dav/calendars/alice/personal/"
|
||||
), handler.puts[0]
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_unknown_default_uses_semif_decision():
|
||||
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
|
||||
try:
|
||||
# The configured default is not among the account's calendars and the
|
||||
# SemIf winner is weak: the winner is used anyway (never blocks).
|
||||
engine = FakeEngine(probs={"personal": 0.3, "work": 0.4})
|
||||
action, _request, engine = run(
|
||||
handler,
|
||||
url,
|
||||
"add standup on 2026-11-10 at 9am",
|
||||
default="missing",
|
||||
engine=engine,
|
||||
)
|
||||
assert action.needs_input is None, action.needs_input
|
||||
assert len(engine.decisions) == 1, engine.decisions
|
||||
assert action.decisions and len(action.decisions) == 1, action.decisions
|
||||
assert handler.puts[0]["path"].startswith(
|
||||
"/remote.php/dav/calendars/alice/work/"
|
||||
), handler.puts[0]
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_all_day_event():
|
||||
server, handler, url = start_server(llm_reply={"title": "conference", "description": ""})
|
||||
try:
|
||||
action, _request, _engine = run(
|
||||
handler, url, "add conference all day on 2026-11-10"
|
||||
)
|
||||
assert action.needs_input is None, action.needs_input
|
||||
body = handler.puts[0]["body"].decode("utf-8")
|
||||
assert "DTSTART;VALUE=DATE:20261110" in body, body
|
||||
assert "DTEND;VALUE=DATE:20261111" in body, body
|
||||
assert "SUMMARY:conference" in body, body
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_llm_bridge_failure_is_reported_honestly():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
action, request, _engine = run(
|
||||
handler,
|
||||
url,
|
||||
"add standup on 2026-11-10 at 9am",
|
||||
llm_url="http://127.0.0.1:1",
|
||||
)
|
||||
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 handler.puts == [], "no event is created when the LLM bridge is down"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_llm_bridge_error_status_is_reported_honestly():
|
||||
server, handler, url = start_server(llm_status=502)
|
||||
try:
|
||||
action, request, _engine = run(
|
||||
handler, url, "add standup on 2026-11-10 at 9am"
|
||||
)
|
||||
assert "HTTP 502" in action.action_log, action.action_log
|
||||
assert action.new_state == request.text
|
||||
assert handler.puts == []
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_server_error_is_reported_honestly():
|
||||
server, handler, url = start_server(
|
||||
put_status=500, llm_reply={"title": "standup", "description": ""}
|
||||
)
|
||||
try:
|
||||
action, request, _engine = run(
|
||||
handler, url, "add standup on 2026-11-10 at 9am"
|
||||
)
|
||||
assert "500" in action.action_log, action.action_log
|
||||
assert action.new_state == request.text, "a failed create must not fake a result"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_unreachable_server_fails_honestly():
|
||||
action, request, _engine = run(
|
||||
None, "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.new_state == request.text
|
||||
print(action.action_log)
|
||||
|
||||
|
||||
def main():
|
||||
test_example_creates_event_on_default_calendar()
|
||||
test_missing_time_asks_then_creates()
|
||||
test_missing_day_asks_then_creates()
|
||||
test_missing_title_asks()
|
||||
test_named_calendar_is_used()
|
||||
test_weak_winner_falls_back_to_default()
|
||||
test_unknown_default_uses_semif_decision()
|
||||
test_all_day_event()
|
||||
test_llm_bridge_failure_is_reported_honestly()
|
||||
test_llm_bridge_error_status_is_reported_honestly()
|
||||
test_server_error_is_reported_honestly()
|
||||
test_unreachable_server_fails_honestly()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"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 task lists and create the task.",
|
||||
"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 phrase the task 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."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Add a single task to a Nextcloud task list from a request such as \"add a task to eat more hot dogs\"."
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
"""Add a single task to a Nextcloud task list.
|
||||
|
||||
Real integration: the Nextcloud bridge over HTTP, which fronts the user's
|
||||
Nextcloud (CalDAV VTODO). The bridge URL/token and the LLM bridge URL/token are
|
||||
operational values supplied through `ctx.config` (declared in CONTRACT); the task
|
||||
summary and description are derived from `request.text`.
|
||||
|
||||
`GET /tasklists` returns only VTODO-capable task lists (the bridge excludes
|
||||
event-only calendars and Nextcloud Deck boards), so a task can never be written
|
||||
to a collection that rejects it. When the account has several task lists the
|
||||
target is resolved by a single SemIf choice over them; otherwise the sole list is
|
||||
used. The task is created for real with `POST /tasks` and the real outcome is
|
||||
reported — a failure is never dressed up as success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from semif_agent.decisions import DecisionRequest, Option
|
||||
from semif_agent.skills import ActionResult
|
||||
|
||||
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 task lists and create the task.",
|
||||
"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 phrase the task 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.",
|
||||
}
|
||||
|
||||
|
||||
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)}
|
||||
|
||||
|
||||
def _parse_json_object(text):
|
||||
"""Pull the first JSON object out of a model reply, or return None."""
|
||||
if not text:
|
||||
return None
|
||||
start = text.find("{")
|
||||
end = text.rfind("}")
|
||||
if start == -1 or end <= start:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(text[start : end + 1])
|
||||
except ValueError:
|
||||
return None
|
||||
return data if isinstance(data, dict) else None
|
||||
|
||||
|
||||
def _extract_task(ctx, request):
|
||||
"""Ask the LLM bridge for (summary, description) of the task; else an error."""
|
||||
llm_url = str(ctx.config.get("llm_bridge_url", "") or "").rstrip("/")
|
||||
headers = _headers(ctx.config.get("llm_bridge_token", ""))
|
||||
messages = [
|
||||
{
|
||||
"role": "system",
|
||||
"content": (
|
||||
"You turn a user's request into a single to-do task. Reply with "
|
||||
'only a JSON object: {"summary": "<short task title>", '
|
||||
'"description": "<extra detail, or an empty string>"}.'
|
||||
),
|
||||
},
|
||||
{"role": "user", "content": request.text or ""},
|
||||
]
|
||||
status, payload = _call(
|
||||
"POST",
|
||||
f"{llm_url}/chat",
|
||||
headers,
|
||||
{"messages": messages, "max_tokens": 200},
|
||||
)
|
||||
if status != 200:
|
||||
return (
|
||||
None,
|
||||
None,
|
||||
f"could not phrase the task via the LLM bridge at {llm_url}: "
|
||||
f"status {status}, {payload.get('error', payload)}",
|
||||
)
|
||||
data = _parse_json_object(payload.get("text") or "")
|
||||
if not data or not str(data.get("summary") or "").strip():
|
||||
return (
|
||||
None,
|
||||
None,
|
||||
f"LLM bridge at {llm_url} returned no usable task text: "
|
||||
f"{payload.get('text')!r}",
|
||||
)
|
||||
return (
|
||||
str(data["summary"]).strip(),
|
||||
str(data.get("description") or "").strip(),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def act(ctx, request) -> ActionResult:
|
||||
"""Add one task to the chosen Nextcloud task list and report the result."""
|
||||
decisions = []
|
||||
base_url = str(ctx.config.get("nextcloud_bridge_url", "") or "").rstrip("/")
|
||||
nc_headers = _headers(ctx.config.get("nextcloud_bridge_token", ""))
|
||||
|
||||
# 1. Phrase the task from the request via the LLM bridge.
|
||||
summary, description, llm_error = _extract_task(ctx, request)
|
||||
if llm_error:
|
||||
return ActionResult(
|
||||
action_log=llm_error,
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
# 2. Find the task list to write to (the bridge returns only VTODO-capable
|
||||
# task lists, so an event-only calendar can never be chosen).
|
||||
status, payload = _call("GET", f"{base_url}/tasklists", nc_headers)
|
||||
if status != 200:
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"could not list Nextcloud task lists from {base_url}: "
|
||||
f"status {status}, {payload.get('error', payload)}"
|
||||
),
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
task_lists = [c for c in (payload.get("tasklists") or []) if c.get("name")]
|
||||
if not task_lists:
|
||||
return ActionResult(
|
||||
action_log="no Nextcloud task lists are available to add a task to",
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
if len(task_lists) == 1:
|
||||
target = task_lists[0]["name"]
|
||||
else:
|
||||
decision = DecisionRequest(
|
||||
state=request.text,
|
||||
question="Which Nextcloud task list should the new task be added to?",
|
||||
options=[
|
||||
Option(c["name"], c.get("label") or c["name"]) for c in task_lists
|
||||
],
|
||||
)
|
||||
result = ctx.engine.call(decision)
|
||||
decisions.append((decision, result))
|
||||
target = result.selected
|
||||
target_label = next(
|
||||
(c.get("label") or c["name"] for c in task_lists if c["name"] == target),
|
||||
target,
|
||||
)
|
||||
|
||||
# 3. Create the task for real through the bridge.
|
||||
status, payload = _call(
|
||||
"POST",
|
||||
f"{base_url}/tasks",
|
||||
nc_headers,
|
||||
{"calendar": target, "summary": summary, "description": description},
|
||||
)
|
||||
if status != 200 or not payload.get("ok"):
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"failed to add task \"{summary}\" to Nextcloud task list "
|
||||
f"\"{target_label}\": status {status}, {payload.get('error', payload)}"
|
||||
),
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
uid = payload.get("uid", "")
|
||||
calendar = payload.get("calendar", target)
|
||||
report = (
|
||||
f'added task "{summary}" to Nextcloud task list "{target_label}" '
|
||||
f"(calendar={calendar}, uid={uid})"
|
||||
)
|
||||
return ActionResult(action_log=report, new_state=report, decisions=decisions)
|
||||
@@ -0,0 +1,345 @@
|
||||
"""Hermetic mechanics test for nextcloud.create_task.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the Nextcloud bridge (`GET /tasklists`, `POST /tasks`) and the
|
||||
LLM bridge's `POST /chat`. This proves the body phrases the task through the LLM
|
||||
bridge, picks a task list (the sole one, or a SemIf choice when there are
|
||||
several), creates the task through the bridge, and fails honestly when the LLM
|
||||
bridge or the Nextcloud bridge errors. It does NOT prove the live integration —
|
||||
only a real run against the user's Nextcloud does.
|
||||
"""
|
||||
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
import skill
|
||||
|
||||
|
||||
def make_handler(routes, seen):
|
||||
"""Build a request handler that records every request and replays `routes`."""
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def _respond(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(length) if length else b""
|
||||
try:
|
||||
body = json.loads(raw.decode("utf-8")) if raw else None
|
||||
except ValueError:
|
||||
body = raw.decode("utf-8", "replace")
|
||||
seen.append(
|
||||
{
|
||||
"method": self.command,
|
||||
"path": self.path,
|
||||
"headers": {k.lower(): v for k, v in self.headers.items()},
|
||||
"body": body,
|
||||
}
|
||||
)
|
||||
key = (self.command, self.path.split("?")[0])
|
||||
status, payload = routes.get(key, (404, {"error": "no route"}))
|
||||
data = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
do_GET = _respond
|
||||
do_POST = _respond
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
def start_server(routes):
|
||||
seen = []
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(routes, seen))
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
url = "http://127.0.0.1:%d" % server.server_address[1]
|
||||
return server, seen, url
|
||||
|
||||
|
||||
def stop(server):
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def closed_port_url():
|
||||
sock = socket.socket()
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
sock.close()
|
||||
return "http://127.0.0.1:%d" % port
|
||||
|
||||
|
||||
class FakeResult:
|
||||
"""Minimal stand-in for a DecisionResult: the body only reads `.selected`."""
|
||||
|
||||
def __init__(self, selected):
|
||||
self.selected = selected
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
"""Test-only decision engine; records the requests the body asked for."""
|
||||
|
||||
def __init__(self, choice=None):
|
||||
self.choice = choice
|
||||
self.calls = []
|
||||
|
||||
def call(self, decision):
|
||||
self.calls.append(decision)
|
||||
return FakeResult(self.choice)
|
||||
|
||||
|
||||
def test_happy_path_single_task_list():
|
||||
llm_routes = {
|
||||
("POST", "/chat"): (
|
||||
200,
|
||||
{
|
||||
"text": '{"summary": "Eat hot dogs", '
|
||||
'"description": "Buy and eat hot dogs"}'
|
||||
},
|
||||
)
|
||||
}
|
||||
nc_routes = {
|
||||
("GET", "/tasklists"): (
|
||||
200,
|
||||
{"tasklists": [{"name": "tasks", "label": "Tasks"}]},
|
||||
),
|
||||
("POST", "/tasks"): (
|
||||
200,
|
||||
{"ok": True, "uid": "uid-1", "calendar": "tasks"},
|
||||
),
|
||||
}
|
||||
llm_server, llm_seen, llm_url = start_server(llm_routes)
|
||||
nc_server, nc_seen, nc_url = start_server(nc_routes)
|
||||
try:
|
||||
engine = FakeEngine()
|
||||
ctx = ActionContext(
|
||||
engine=engine,
|
||||
config={
|
||||
"nextcloud_bridge_url": nc_url,
|
||||
"nextcloud_bridge_token": "nc-secret",
|
||||
"llm_bridge_url": llm_url,
|
||||
"llm_bridge_token": "llm-secret",
|
||||
},
|
||||
)
|
||||
request = Request("Add a task in next cloud for eating hot dogs.")
|
||||
result = skill.act(ctx, request)
|
||||
|
||||
assert not engine.calls, "a single task list must not need a decision"
|
||||
assert "Eat hot dogs" in result.action_log, result.action_log
|
||||
assert "Tasks" in result.action_log, result.action_log
|
||||
assert "uid-1" in result.action_log, result.action_log
|
||||
|
||||
assert len(llm_seen) == 1, llm_seen
|
||||
chat = llm_seen[0]
|
||||
assert chat["method"] == "POST", chat
|
||||
assert chat["path"] == "/chat", chat
|
||||
assert chat["headers"].get("x-semif-token") == "llm-secret", chat["headers"]
|
||||
assert chat["body"]["messages"][1]["content"] == request.text, chat["body"]
|
||||
assert "summary" in chat["body"]["messages"][0]["content"], chat["body"]
|
||||
|
||||
assert [r["path"] for r in nc_seen] == ["/tasklists", "/tasks"], nc_seen
|
||||
listing = nc_seen[0]
|
||||
assert listing["method"] == "GET", listing
|
||||
assert listing["headers"].get("x-semif-token") == "nc-secret", listing["headers"]
|
||||
create = nc_seen[1]
|
||||
assert create["method"] == "POST", create
|
||||
assert create["headers"].get("x-semif-token") == "nc-secret", create["headers"]
|
||||
assert create["body"] == {
|
||||
"calendar": "tasks",
|
||||
"summary": "Eat hot dogs",
|
||||
"description": "Buy and eat hot dogs",
|
||||
}, create["body"]
|
||||
print("happy path:", result.action_log)
|
||||
finally:
|
||||
stop(llm_server)
|
||||
stop(nc_server)
|
||||
|
||||
|
||||
def test_multiple_task_lists_asks_and_omits_token_header():
|
||||
llm_routes = {
|
||||
("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'})
|
||||
}
|
||||
nc_routes = {
|
||||
("GET", "/tasklists"): (
|
||||
200,
|
||||
{
|
||||
"tasklists": [
|
||||
{"name": "tasks", "label": "Tasks"},
|
||||
{"name": "work", "label": "Work"},
|
||||
]
|
||||
},
|
||||
),
|
||||
("POST", "/tasks"): (200, {"ok": True, "uid": "uid-2", "calendar": "work"}),
|
||||
}
|
||||
llm_server, llm_seen, llm_url = start_server(llm_routes)
|
||||
nc_server, nc_seen, nc_url = start_server(nc_routes)
|
||||
try:
|
||||
engine = FakeEngine(choice="work")
|
||||
ctx = ActionContext(
|
||||
engine=engine,
|
||||
config={
|
||||
"nextcloud_bridge_url": nc_url,
|
||||
"nextcloud_bridge_token": "",
|
||||
"llm_bridge_url": llm_url,
|
||||
"llm_bridge_token": "",
|
||||
},
|
||||
)
|
||||
result = skill.act(
|
||||
ctx, Request("Add a task in next cloud for eating hot dogs.")
|
||||
)
|
||||
|
||||
assert len(engine.calls) == 1, "two task lists must trigger one decision"
|
||||
decision = engine.calls[0]
|
||||
assert [o.id for o in decision.options] == ["tasks", "work"], decision.options
|
||||
assert result.decisions, "the decision must be recorded on the result"
|
||||
|
||||
assert "x-semif-token" not in llm_seen[0]["headers"], llm_seen[0]["headers"]
|
||||
create = nc_seen[-1]
|
||||
assert create["path"] == "/tasks", create
|
||||
assert create["body"]["calendar"] == "work", create["body"]
|
||||
assert create["body"]["description"] == "", create["body"]
|
||||
assert "x-semif-token" not in create["headers"], create["headers"]
|
||||
assert "Work" in result.action_log, result.action_log
|
||||
print("decision path:", result.action_log)
|
||||
finally:
|
||||
stop(llm_server)
|
||||
stop(nc_server)
|
||||
|
||||
|
||||
def test_llm_bridge_failure_leaves_nextcloud_untouched():
|
||||
llm_routes = {("POST", "/chat"): (502, {"error": "model down"})}
|
||||
nc_routes = {
|
||||
("GET", "/tasklists"): (200, {"tasklists": [{"name": "tasks"}]})
|
||||
}
|
||||
llm_server, _llm_seen, llm_url = start_server(llm_routes)
|
||||
nc_server, nc_seen, nc_url = start_server(nc_routes)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={
|
||||
"nextcloud_bridge_url": nc_url,
|
||||
"llm_bridge_url": llm_url,
|
||||
},
|
||||
)
|
||||
result = skill.act(ctx, Request("Add a task in next cloud for hot dogs."))
|
||||
assert "could not phrase the task" in result.action_log, result.action_log
|
||||
assert "model down" in result.action_log, result.action_log
|
||||
assert nc_seen == [], "Nextcloud must not be touched when phrasing fails"
|
||||
print("llm failure:", result.action_log)
|
||||
finally:
|
||||
stop(llm_server)
|
||||
stop(nc_server)
|
||||
|
||||
|
||||
def test_llm_reply_without_task_text():
|
||||
llm_routes = {("POST", "/chat"): (200, {"text": "I cannot help with that."})}
|
||||
nc_routes = {
|
||||
("GET", "/tasklists"): (200, {"tasklists": [{"name": "tasks"}]})
|
||||
}
|
||||
llm_server, _llm_seen, llm_url = start_server(llm_routes)
|
||||
nc_server, nc_seen, nc_url = start_server(nc_routes)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={"nextcloud_bridge_url": nc_url, "llm_bridge_url": llm_url},
|
||||
)
|
||||
result = skill.act(ctx, Request("do something vague"))
|
||||
assert "no usable task text" in result.action_log, result.action_log
|
||||
assert nc_seen == [], "Nextcloud must not be touched without a task title"
|
||||
print("unusable llm reply:", result.action_log)
|
||||
finally:
|
||||
stop(llm_server)
|
||||
stop(nc_server)
|
||||
|
||||
|
||||
def test_no_task_lists_available():
|
||||
llm_routes = {
|
||||
("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'})
|
||||
}
|
||||
nc_routes = {("GET", "/tasklists"): (200, {"tasklists": []})}
|
||||
llm_server, _llm_seen, llm_url = start_server(llm_routes)
|
||||
nc_server, nc_seen, nc_url = start_server(nc_routes)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={"nextcloud_bridge_url": nc_url, "llm_bridge_url": llm_url},
|
||||
)
|
||||
result = skill.act(ctx, Request("Add a task in next cloud for hot dogs."))
|
||||
assert "no Nextcloud task lists" in result.action_log, result.action_log
|
||||
assert [r["path"] for r in nc_seen] == ["/tasklists"], nc_seen
|
||||
print("no task lists:", result.action_log)
|
||||
finally:
|
||||
stop(llm_server)
|
||||
stop(nc_server)
|
||||
|
||||
|
||||
def test_unreachable_nextcloud_bridge():
|
||||
llm_routes = {
|
||||
("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'})
|
||||
}
|
||||
llm_server, _llm_seen, llm_url = start_server(llm_routes)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={
|
||||
"nextcloud_bridge_url": closed_port_url(),
|
||||
"llm_bridge_url": llm_url,
|
||||
},
|
||||
)
|
||||
result = skill.act(ctx, Request("Add a task in next cloud for hot dogs."))
|
||||
assert "could not list Nextcloud task lists" in result.action_log, result.action_log
|
||||
print("unreachable nextcloud:", result.action_log)
|
||||
finally:
|
||||
stop(llm_server)
|
||||
|
||||
|
||||
def test_task_creation_failure_is_reported():
|
||||
llm_routes = {
|
||||
("POST", "/chat"): (200, {"text": '{"summary": "Eat hot dogs"}'})
|
||||
}
|
||||
nc_routes = {
|
||||
("GET", "/tasklists"): (
|
||||
200,
|
||||
{"tasklists": [{"name": "tasks", "label": "Tasks"}]},
|
||||
),
|
||||
("POST", "/tasks"): (502, {"error": "CalDAV rejected the VTODO"}),
|
||||
}
|
||||
llm_server, _llm_seen, llm_url = start_server(llm_routes)
|
||||
nc_server, nc_seen, nc_url = start_server(nc_routes)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={"nextcloud_bridge_url": nc_url, "llm_bridge_url": llm_url},
|
||||
)
|
||||
result = skill.act(ctx, Request("Add a task in next cloud for hot dogs."))
|
||||
assert "failed to add task" in result.action_log, result.action_log
|
||||
assert "CalDAV rejected the VTODO" in result.action_log, result.action_log
|
||||
assert [r["path"] for r in nc_seen] == ["/tasklists", "/tasks"], nc_seen
|
||||
print("creation failure:", result.action_log)
|
||||
finally:
|
||||
stop(llm_server)
|
||||
stop(nc_server)
|
||||
|
||||
|
||||
def main():
|
||||
test_happy_path_single_task_list()
|
||||
test_multiple_task_lists_asks_and_omits_token_header()
|
||||
test_llm_bridge_failure_leaves_nextcloud_untouched()
|
||||
test_llm_reply_without_task_text()
|
||||
test_no_task_lists_available()
|
||||
test_unreachable_nextcloud_bridge()
|
||||
test_task_creation_failure_is_reported()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"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)."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Report the next upcoming event on the user's Nextcloud calendar."
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
"""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`).
|
||||
|
||||
`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.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import re
|
||||
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",
|
||||
"config_vars": [
|
||||
"nextcloud_url",
|
||||
"nextcloud_username",
|
||||
"nextcloud_app_password",
|
||||
"nextcloud_default_calendar",
|
||||
],
|
||||
}
|
||||
|
||||
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).",
|
||||
}
|
||||
|
||||
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`
|
||||
config value when set, else host local. A test seam; never freezes time."""
|
||||
return local_now(ctx.config)
|
||||
|
||||
|
||||
# ---- transport ----
|
||||
|
||||
|
||||
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",
|
||||
},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
|
||||
return response.read()
|
||||
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
|
||||
|
||||
|
||||
# ---- calendar resolution ----
|
||||
|
||||
|
||||
def _default_calendar(ctx, calendars):
|
||||
"""The configured default calendar, if it is one of the account's."""
|
||||
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
|
||||
for calendar in calendars:
|
||||
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()):
|
||||
return calendar
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_calendar(ctx, request, calendars, decisions):
|
||||
"""Resolve which calendar the request means, mirroring nextcloud.create_event.
|
||||
|
||||
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)
|
||||
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],
|
||||
)
|
||||
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
|
||||
|
||||
|
||||
# ---- iCalendar 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_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:
|
||||
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
|
||||
|
||||
|
||||
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
|
||||
if event.get("all_day"):
|
||||
return event["start"] + timedelta(days=1)
|
||||
return event["start"]
|
||||
|
||||
|
||||
def _pick_next(events, now):
|
||||
current_or_future = [event for event in events if _event_end(event) >= now]
|
||||
if not current_or_future:
|
||||
return None
|
||||
return min(current_or_future, key=lambda event: event["start"])
|
||||
|
||||
|
||||
def _format_when(event):
|
||||
start = event["start"]
|
||||
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):
|
||||
try:
|
||||
calendars = _discover_calendars(ctx)
|
||||
except CalDavError as exc:
|
||||
return ActionResult(
|
||||
action_log=f"calendar discovery failed: {exc}",
|
||||
new_state=request.text,
|
||||
)
|
||||
if not calendars:
|
||||
return ActionResult(
|
||||
action_log="calendar discovery failed: no calendars found",
|
||||
new_state=request.text,
|
||||
)
|
||||
|
||||
decisions = []
|
||||
calendar = _resolve_calendar(ctx, request, calendars, 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)
|
||||
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:
|
||||
return ActionResult(
|
||||
action_log=f"failed on {calendar!r}: {exc}",
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
next_event = _pick_next(events, now)
|
||||
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)
|
||||
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)
|
||||
@@ -0,0 +1,259 @@
|
||||
"""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.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import sys
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from semif_agent.decisions import DecisionResult, Request
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
import skill
|
||||
|
||||
CALENDARS = [("personal", "Personal"), ("work", "Work")]
|
||||
ICS = ""
|
||||
|
||||
|
||||
def build_ics():
|
||||
"""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")
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
"""Test-only engine.
|
||||
|
||||
By default it picks the requested option id (else the first) with full
|
||||
confidence. Pass `probs` (a mapping of option id -> probability) to script an
|
||||
arbitrary distribution, e.g. a near-tie that must fall back to the default.
|
||||
"""
|
||||
|
||||
def __init__(self, pick=None, probs=None):
|
||||
self.pick = pick
|
||||
self.probs = probs
|
||||
self.decisions = []
|
||||
|
||||
def call(self, decision):
|
||||
self.decisions.append(decision)
|
||||
option_ids = [option.id for option in decision.options]
|
||||
if self.probs is not None:
|
||||
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
|
||||
else:
|
||||
chosen = self.pick if self.pick in option_ids else option_ids[0]
|
||||
probabilities = [
|
||||
1.0 if option_id == chosen else 0.0 for option_id in option_ids
|
||||
]
|
||||
return DecisionResult(
|
||||
request=decision, option_ids=option_ids, probabilities=probabilities
|
||||
)
|
||||
|
||||
|
||||
class CalDavHandler(BaseHTTPRequestHandler):
|
||||
requests = []
|
||||
calendar_count = 2
|
||||
report_status = 207
|
||||
|
||||
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")
|
||||
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()
|
||||
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>"
|
||||
)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def start_server(**overrides):
|
||||
handler = type("Handler", (CalDavHandler,), {"requests": [], **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"):
|
||||
return {
|
||||
"nextcloud_url": url,
|
||||
"nextcloud_username": "testuser",
|
||||
"nextcloud_app_password": "app-pw",
|
||||
"nextcloud_default_calendar": default,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
global ICS
|
||||
ICS = build_ics()
|
||||
|
||||
# A strong winner is used even though a default is configured.
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
engine = FakeEngine(pick="work")
|
||||
ctx = ActionContext(engine=engine, config=fixture_config(url))
|
||||
request = Request("what is the next event on my work calendar?")
|
||||
action = skill.act(ctx, request)
|
||||
assert len(action.decisions) == 1, "act must log the calendar choice"
|
||||
assert len(engine.decisions) == 1
|
||||
assert [option.id for option in engine.decisions[0].options] == [
|
||||
"personal",
|
||||
"work",
|
||||
], engine.decisions[0].options
|
||||
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"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
# A weak winner falls back to the configured default calendar.
|
||||
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"))
|
||||
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 "Team sync" in action.action_log, action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
# A weak winner with no configured default stands.
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
|
||||
ctx = ActionContext(engine=engine, config=fixture_config(url, default=""))
|
||||
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"]
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
# A single calendar needs no SemIf decision.
|
||||
server, handler, url = start_server(calendar_count=1)
|
||||
try:
|
||||
engine = FakeEngine()
|
||||
ctx = ActionContext(engine=engine, config=fixture_config(url))
|
||||
request = Request("what is the next event on my calendar?")
|
||||
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/"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
# A failing REPORT is reported honestly.
|
||||
server, handler, url = start_server(report_status=500)
|
||||
try:
|
||||
engine = FakeEngine(pick="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 "failed" in action.action_log, action.action_log
|
||||
assert action.new_state == request.text, "a failed query must not fake a result"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
sys.exit(1)
|
||||
Reference in new issue
Block a user