llm bridge service
This commit is contained in:
1 parent
f21baa7ebd
commit
63c5fc9903
20 files changed
+725
-172
No files matched your search
@@ -2,5 +2,7 @@
|
||||
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
|
||||
"nextcloud_username": "The Nextcloud username whose calendars are used.",
|
||||
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
|
||||
"nextcloud_default_calendar": "Name of the calendar new events go to by default, e.g. personal (a request may still name another calendar)."
|
||||
"nextcloud_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."
|
||||
}
|
||||
@@ -4,25 +4,29 @@ 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, the start date/time, the duration, and (when named) the target calendar.
|
||||
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 re-parses the query each pass and never re-asks a
|
||||
question it already has an answer for. Calendars are discovered over PROPFIND and
|
||||
a named target is resolved with a SemIf sub-decision when more than one matches;
|
||||
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.
|
||||
`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.
|
||||
|
||||
Parsing is deliberately bounded and stdlib-only (no text generation is available
|
||||
to a skill body): when a required field cannot be derived confidently the body
|
||||
asks rather than guessing.
|
||||
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
|
||||
@@ -42,6 +46,8 @@ INTEGRATION = {
|
||||
"nextcloud_username",
|
||||
"nextcloud_app_password",
|
||||
"nextcloud_default_calendar",
|
||||
"llm_bridge_url",
|
||||
"llm_bridge_token",
|
||||
],
|
||||
}
|
||||
|
||||
@@ -50,12 +56,17 @@ CONTRACT = {
|
||||
"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"?>'
|
||||
@@ -106,25 +117,14 @@ _MONTH_ALT = (
|
||||
r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"
|
||||
)
|
||||
|
||||
_LEADING_NOISE = re.compile(
|
||||
r"^\s*(please\s+)?(add|create|schedule|put|make|set\s+up|new|insert|book|a|an|the)\b[\s:,-]*",
|
||||
re.I,
|
||||
)
|
||||
_TITLE_NOISE = [
|
||||
re.compile(r"\b(to|on|in)\s+(my|the)\s+[A-Za-z0-9_'-]+\s+calendar\b", re.I),
|
||||
re.compile(r"\b(to|on|in)\s+(my|the)\s+calendar\b", re.I),
|
||||
re.compile(r"\b(new\s+|calendar\s+)*event\b", re.I),
|
||||
re.compile(r"\b(called|titled|named)\b", re.I),
|
||||
]
|
||||
_TRAILING_NOISE = re.compile(
|
||||
r"[\s,;:-]*\b(for|on|at|to|the|my|a|an|in|of)\b[\s,;:-]*$", re.I
|
||||
)
|
||||
|
||||
|
||||
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():
|
||||
"""Current local time (aware). A test seam; the body never freezes time."""
|
||||
return datetime.now().astimezone()
|
||||
@@ -210,30 +210,65 @@ def _calendar_path(ctx, calendar):
|
||||
)
|
||||
|
||||
|
||||
# ---- request -> arguments ----
|
||||
# ---- LLM field extraction ----
|
||||
|
||||
|
||||
def _remove_spans(text, spans):
|
||||
for start, end in sorted(spans, reverse=True):
|
||||
text = text[:start] + " " + text[end:]
|
||||
return text
|
||||
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 _clean_title(text):
|
||||
text = re.sub(r"\s{2,}", " ", text).strip()
|
||||
previous = None
|
||||
while previous != text:
|
||||
previous = text
|
||||
text = _LEADING_NOISE.sub("", text)
|
||||
for pattern in _TITLE_NOISE:
|
||||
text = pattern.sub(" ", text)
|
||||
text = _TRAILING_NOISE.sub("", text)
|
||||
text = re.sub(r"\s{2,}", " ", text).strip()
|
||||
return text.strip(" \t,;:-.")
|
||||
|
||||
|
||||
def _extract_title(text, spans):
|
||||
return _clean_title(_remove_spans(text or "", spans))
|
||||
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):
|
||||
@@ -261,8 +296,9 @@ 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), `from_weekday`
|
||||
(bool) and `spans` (matched ranges, so the title can be cleaned).
|
||||
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 = {
|
||||
@@ -272,22 +308,18 @@ def _parse_when(text, now):
|
||||
"duration_minutes": None,
|
||||
"from_weekday": False,
|
||||
}
|
||||
spans = []
|
||||
|
||||
match = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", text, re.I)
|
||||
if match:
|
||||
result["all_day"] = True
|
||||
spans.append(match.span())
|
||||
|
||||
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))
|
||||
spans.append(match.span())
|
||||
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))
|
||||
spans.append(match.span())
|
||||
else:
|
||||
for phrase, minutes in (
|
||||
(r"\bfor\s+half\s+an?\s+hour\b", 30),
|
||||
@@ -297,7 +329,6 @@ def _parse_when(text, now):
|
||||
match = re.search(phrase, text, re.I)
|
||||
if match:
|
||||
result["duration_minutes"] = minutes
|
||||
spans.append(match.span())
|
||||
break
|
||||
|
||||
date = None
|
||||
@@ -307,7 +338,6 @@ def _parse_when(text, now):
|
||||
date = datetime(
|
||||
int(match.group(1)), int(match.group(2)), int(match.group(3))
|
||||
).date()
|
||||
spans.append(match.span())
|
||||
except ValueError:
|
||||
date = None
|
||||
|
||||
@@ -321,8 +351,6 @@ def _parse_when(text, now):
|
||||
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 not None:
|
||||
spans.append(match.span())
|
||||
|
||||
if date is None:
|
||||
match = re.search(
|
||||
@@ -334,8 +362,6 @@ def _parse_when(text, now):
|
||||
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 not None:
|
||||
spans.append(match.span())
|
||||
|
||||
if date is None:
|
||||
match = re.search(r"\b(\d{1,2})/(\d{1,2})(?:/(\d{2,4}))?\b", text)
|
||||
@@ -346,8 +372,6 @@ def _parse_when(text, now):
|
||||
if year is not None and year < 100:
|
||||
year += 2000
|
||||
date = _resolve_month_day(month, day, year, now)
|
||||
if date is not None:
|
||||
spans.append(match.span())
|
||||
|
||||
if date is None:
|
||||
match = re.search(
|
||||
@@ -361,7 +385,6 @@ def _parse_when(text, now):
|
||||
date = now.date() + timedelta(days=1)
|
||||
else:
|
||||
date = now.date() + timedelta(days=7)
|
||||
spans.append(match.span())
|
||||
|
||||
if date is None:
|
||||
match = _WEEKDAY_RE.search(text)
|
||||
@@ -371,19 +394,14 @@ def _parse_when(text, now):
|
||||
prefix = text[max(0, match.start() - 6):match.start()]
|
||||
if re.search(r"\bnext\s*$", prefix, re.I):
|
||||
date += timedelta(days=7)
|
||||
spans.append((match.start() - len("next "), match.end()))
|
||||
else:
|
||||
spans.append(match.span())
|
||||
result["from_weekday"] = True
|
||||
|
||||
parsed_time = None
|
||||
match = re.search(r"\bnoon\b", text, re.I)
|
||||
if match:
|
||||
parsed_time = time(12, 0)
|
||||
spans.append(match.span())
|
||||
elif re.search(r"\bmidnight\b", text, re.I):
|
||||
parsed_time = time(0, 0)
|
||||
spans.append(re.search(r"\bmidnight\b", text, re.I).span())
|
||||
else:
|
||||
match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I)
|
||||
if match:
|
||||
@@ -393,46 +411,25 @@ def _parse_when(text, now):
|
||||
hour += 12
|
||||
if hour < 24 and minute < 60:
|
||||
parsed_time = time(hour, minute)
|
||||
spans.append(match.span())
|
||||
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)
|
||||
spans.append(match.span())
|
||||
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)
|
||||
spans.append(match.span())
|
||||
|
||||
result["date"] = date
|
||||
result["time"] = parsed_time
|
||||
result["spans"] = spans
|
||||
return result
|
||||
|
||||
|
||||
# ---- calendar resolution ----
|
||||
|
||||
|
||||
def _mentioned_calendars(calendars, text):
|
||||
low = (text or "").lower()
|
||||
found = []
|
||||
for calendar in calendars:
|
||||
for token in {calendar["name"].lower(), calendar["label"].lower()}:
|
||||
if len(token) < 3:
|
||||
continue
|
||||
pattern = (
|
||||
rf"\b{re.escape(token)}\b\s+calendar\b"
|
||||
rf"|\bcalendar\b\s+\b{re.escape(token)}\b"
|
||||
)
|
||||
if re.search(pattern, low):
|
||||
found.append(calendar)
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def _resolve_calendar(ctx, request, calendars, decisions):
|
||||
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
|
||||
default = None
|
||||
@@ -441,33 +438,22 @@ def _resolve_calendar(ctx, request, calendars, decisions):
|
||||
default = calendar
|
||||
break
|
||||
|
||||
mentioned = _mentioned_calendars(calendars, request.text)
|
||||
if len(mentioned) == 1:
|
||||
return mentioned[0]["name"]
|
||||
if len(mentioned) > 1:
|
||||
return _choose_calendar(ctx, request, mentioned, default, decisions)
|
||||
if default is not None:
|
||||
return default["name"]
|
||||
if len(calendars) == 1:
|
||||
return calendars[0]["name"]
|
||||
return _choose_calendar(ctx, request, calendars, default, decisions)
|
||||
|
||||
|
||||
def _choose_calendar(ctx, request, candidates, default, decisions):
|
||||
options = []
|
||||
for calendar in candidates:
|
||||
label = calendar["label"]
|
||||
if default is not None and calendar["name"] == default["name"]:
|
||||
label = f"{label} (default)"
|
||||
options.append(Option(calendar["name"], label))
|
||||
decision = DecisionRequest(
|
||||
state=request.text,
|
||||
question="Which calendar should the event go on?",
|
||||
options=options,
|
||||
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))
|
||||
return result.selected
|
||||
winner = result.selected
|
||||
if result.prob(winner) >= CALENDAR_WINNER_TAU:
|
||||
return winner
|
||||
if default is not None:
|
||||
return default["name"]
|
||||
return winner
|
||||
|
||||
|
||||
# ---- iCalendar ----
|
||||
@@ -532,9 +518,21 @@ def act(ctx, request):
|
||||
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=f"calendar.create_event: {exc}",
|
||||
new_state=request.text,
|
||||
)
|
||||
request.meta["create_event_fields"] = fields
|
||||
title = fields["title"]
|
||||
description = fields["description"]
|
||||
|
||||
now = _now()
|
||||
parsed = _parse_when(request.text, now)
|
||||
title = _extract_title(request.text, parsed["spans"])
|
||||
|
||||
if answers.get("title"):
|
||||
title = answers["title"].strip()
|
||||
@@ -589,7 +587,9 @@ def act(ctx, request):
|
||||
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))
|
||||
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(
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""Hermetic mechanics test for calendar.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).
|
||||
This proves the body derives the event title/date/time from the request, asks for
|
||||
a missing field and resumes, resolves the target calendar (default or named, with
|
||||
a SemIf sub-decision when ambiguous), writes a real iCalendar PUT, and fails
|
||||
honestly when the server errors. It does NOT prove the live integration — only a
|
||||
real run against the user's Nextcloud does.
|
||||
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
|
||||
@@ -24,25 +27,36 @@ import skill
|
||||
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
|
||||
skill._now = lambda: 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: picks the requested option id, else the first."""
|
||||
"""Test-only engine.
|
||||
|
||||
def __init__(self, pick=None):
|
||||
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]
|
||||
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
|
||||
]
|
||||
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
|
||||
)
|
||||
@@ -53,6 +67,9 @@ class CalDavHandler(BaseHTTPRequestHandler):
|
||||
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)
|
||||
@@ -95,11 +112,26 @@ class CalDavHandler(BaseHTTPRequestHandler):
|
||||
)
|
||||
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):
|
||||
def start_server(calendars=None, put_status=201, llm_reply=None, llm_status=200):
|
||||
handler = type(
|
||||
"Handler",
|
||||
(CalDavHandler,),
|
||||
@@ -113,6 +145,9 @@ def start_server(calendars=None, put_status=201):
|
||||
"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)
|
||||
@@ -120,31 +155,48 @@ def start_server(calendars=None, put_status=201):
|
||||
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def config(url, default="personal", token=""):
|
||||
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):
|
||||
def run(handler, url, text, default="personal", engine=None, llm_url=None):
|
||||
engine = engine or FakeEngine()
|
||||
ctx = ActionContext(engine=engine, config=config(url, default))
|
||||
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()
|
||||
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"
|
||||
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 engine.decisions == [], "the default calendar needs no SemIf decision"
|
||||
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
|
||||
@@ -152,6 +204,7 @@ def test_example_creates_event_on_default_calendar():
|
||||
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
|
||||
@@ -163,7 +216,9 @@ def test_example_creates_event_on_default_calendar():
|
||||
|
||||
|
||||
def test_missing_time_asks_then_creates():
|
||||
server, handler, url = start_server()
|
||||
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"
|
||||
@@ -171,11 +226,13 @@ def test_missing_time_asks_then_creates():
|
||||
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
|
||||
@@ -186,7 +243,9 @@ def test_missing_time_asks_then_creates():
|
||||
|
||||
|
||||
def test_missing_day_asks_then_creates():
|
||||
server, handler, url = start_server()
|
||||
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"
|
||||
@@ -204,7 +263,7 @@ def test_missing_day_asks_then_creates():
|
||||
|
||||
|
||||
def test_missing_title_asks():
|
||||
server, handler, url = start_server()
|
||||
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"
|
||||
@@ -217,13 +276,23 @@ def test_missing_title_asks():
|
||||
|
||||
|
||||
def test_named_calendar_is_used():
|
||||
server, handler, url = start_server()
|
||||
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"
|
||||
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 engine.decisions == [], "a uniquely named calendar needs no decision"
|
||||
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]
|
||||
@@ -235,10 +304,35 @@ def test_named_calendar_is_used():
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_unknown_default_uses_semif_decision():
|
||||
server, handler, url = start_server()
|
||||
def test_weak_winner_falls_back_to_default():
|
||||
server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
|
||||
try:
|
||||
engine = FakeEngine(pick="work")
|
||||
# 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,
|
||||
@@ -259,7 +353,7 @@ def test_unknown_default_uses_semif_decision():
|
||||
|
||||
|
||||
def test_all_day_event():
|
||||
server, handler, url = start_server()
|
||||
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"
|
||||
@@ -275,8 +369,43 @@ def test_all_day_event():
|
||||
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)
|
||||
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"
|
||||
@@ -304,8 +433,11 @@ def main():
|
||||
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")
|
||||
|
||||
Reference in new issue
Block a user