llm bridge service

This commit is contained in:
gabby committed 2026-10-03 09:05:28 +00:00
1 parent f21baa7ebd
commit 63c5fc9903
20 files changed
+724 -171

No files matched your search

+37 -4
View File
@@ -182,7 +182,8 @@ gateway/ messenger COMMAND intake/reply — and nothing else. base.py:
`gateway.simplex`. The gateway MUST NOT read history, show/create `gateway.simplex`. The gateway MUST NOT read history, show/create
invite links, or compose messages — see "gateway isolation" invite links, or compose messages — see "gateway isolation"
below. below.
bridges/ standalone third-party API bridges (SimpleX first). base.py: bridges/ standalone third-party API bridges (SimpleX first, plus the
LLM bridge). base.py:
BridgeInfo + BridgeService (shared localhost JSON HTTP layer, BridgeInfo + BridgeService (shared localhost JSON HTTP layer,
`X-Semif-Token` guard). inbox.py: MessagingInbox (bounded FIFO + `X-Semif-Token` guard). inbox.py: MessagingInbox (bounded FIFO +
contacts learned from inbound DMs and the daemon contact list, contacts learned from inbound DMs and the daemon contact list,
@@ -191,8 +192,13 @@ bridges/ standalone third-party API bridges (SimpleX first). base.py:
gateway's), buffers every inbound DM, refreshes the daemon gateway's), buffers every inbound DM, refreshes the daemon
contact list on (re)connect + on demand, serves invite-link/ contact list on (re)connect + on demand, serves invite-link/
read/send plus daemon-backed unread + per-chat history. read/send plus daemon-backed unread + per-chat history.
llm.py: LLMBridge — a generic `POST /chat` in front of the
scheduler's configured `llm` client (reused, not re-configured),
so bodies get short generated text (e.g. an event title +
description) over HTTP.
registry.py: CATALOG, describe_bridges() (catalog injected registry.py: CATALOG, describe_bridges() (catalog injected
into the codegen prompts), run_bridges(). Run with `python -m into the codegen prompts), run_bridges() (threads the scheduler's
`llm` client into the LLM bridge). Run with `python -m
semif_agent.cli bridge [--name NAME]`; config under `bridges`. semif_agent.cli bridge [--name NAME]`; config under `bridges`.
simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway
adapter and the bridge (parse direct text across v7 shapes, adapter and the bridge (parse direct text across v7 shapes,
@@ -501,7 +507,9 @@ CLI, unit tests (24) + integration tests (2).
`codegen.timeout: 3600`, the SimpleX gateway enabled `codegen.timeout: 3600`, the SimpleX gateway enabled
(`gateway.simplex.enabled = true`, `ws_url` from `simplex_chat.port`) and the (`gateway.simplex.enabled = true`, `ws_url` from `simplex_chat.port`) and the
standalone forwarding bridge enabled (`bridges.simplex.enabled = true`, standalone forwarding bridge enabled (`bridges.simplex.enabled = true`,
`ws_url` from `simplex_chat.forward_port`, top-level `simplex_bridge_url`); `ws_url` from `simplex_chat.forward_port`, top-level `simplex_bridge_url`) and
the LLM bridge enabled (`bridges.llm.enabled = true`, top-level
`llm_bridge_url`; it reuses the `llm` model);
the operator sets `llm.model`/`llm.base_url` and `codegen.model`/ the operator sets `llm.model`/`llm.base_url` and `codegen.model`/
`codegen.base_url`. Bootstrap renders/enables four user services: `codegen.base_url`. Bootstrap renders/enables four user services:
`semif-simplex.service` (the command `simplex-chat` bot daemon, `semif-simplex.service` (the command `simplex-chat` bot daemon,
@@ -663,6 +671,11 @@ CLI, unit tests (24) + integration tests (2).
satisfy pause the run **before act** (`pre_act`), asking the human one at a satisfy pause the run **before act** (`pre_act`), asking the human one at a
time. Each answer gets a SemIf `record-as-config vs ask-again-each-fire` choice time. Each answer gets a SemIf `record-as-config vs ask-again-each-fire` choice
(phase `config:record`); recorded values persist to the skill `config.json`. (phase `config:record`); recorded values persist to the skill `config.json`.
**An empty answer (or the literal "skip") skips that variable for the run**: it
stays unset in `ctx.config` and is never re-asked, and the run proceeds (or
asks the next missing variable). An act-driven `needs_input` also accepts an
empty answer — it is forwarded to `act` as `user_input=""`; a body that then
fails for lack of the info is assessed/repair-offered normally.
- **Resolved-input observation.** The `assess:outcome` / `assess:requeue` state - **Resolved-input observation.** The `assess:outcome` / `assess:requeue` state
includes the resolved contract values (`resolved inputs:` block) so the includes the resolved contract values (`resolved inputs:` block) so the
decision sees the full query → resolution → action path; secret-named decision sees the full query → resolution → action path; secret-named
@@ -907,6 +920,21 @@ CLI, unit tests (24) + integration tests (2).
it in sync with the bridge port. Skills reach a bridge with the ordinary `http` it in sync with the bridge port. Skills reach a bridge with the ordinary `http`
transport, so their hermetic tests are loopback HTTP like any other HTTP body. transport, so their hermetic tests are loopback HTTP like any other HTTP body.
`simplex.next_message` and `simplex.connect_link` are the seeds. `simplex.next_message` and `simplex.connect_link` are the seeds.
- **LLM bridge** (`bridges/llm.py`). A generic `POST /chat`
`{"messages": [{"role","content"}, ...], "max_tokens"?: int}` ->
`{"text": "<model reply>"}` (plus `GET /health`, `400` bad body, `502` model
error) in front of the agent's language model, so a body can ask for short
generated text over HTTP instead of speaking the OpenAI-compatible protocol
itself. It does **not** own the model connection: `run_bridge` passes the
scheduler's already-configured `llm` client through `run_bridges`/`build_bridge`
into `LLMBridge`, so the endpoint/model/sampler stay configured once in the
top-level `llm` block; the `bridges.llm` block carries only the local listener
(`enabled`/`host`/`port`/`token`). Bodies reach it via the top-level
`llm_bridge_url` (+ optional `llm_bridge_token`). It runs inside the existing
`semif-bridge.service` process (all enabled bridges start together); with no
client it reports `502`, never a fabricated reply. `calendar.create_event` is
the first consumer (title + description extraction, cached in `request.meta`
across a `needs_input` resume).
## Bridge backlog (one session per item) ## Bridge backlog (one session per item)
@@ -939,7 +967,12 @@ The bridge read path (`simplex.next_message`) and contact-link lookup
outbound counterpart to `simplex.next_message`: resolve the recipient with a outbound counterpart to `simplex.next_message`: resolve the recipient with a
SemIf sub-decision over `/contacts`, send only on explicit user intent, and SemIf sub-decision over `/contacts`, send only on explicit user intent, and
report the bridge's `contact_id` / errors honestly. report the bridge's `contact_id` / errors honestly.
- [ ] **4. More bridges.** Each new third-party API gets its own `bridges/<name>.py` - [x] **4. LLM bridge** (`bridges/llm.py`). Shipped: `LLMBridge` exposes a
generic `POST /chat` in front of the scheduler's configured `llm` client
(threaded through `run_bridges`/`build_bridge`, never re-configured), registered
in `CATALOG` and seeded under `bridges.llm` + top-level `llm_bridge_url`.
`calendar.create_event` extracts its title + description through it.
- [ ] **5. More bridges.** Each new third-party API gets its own `bridges/<name>.py`
+ config block + `CATALOG` entry; the codegen prompts pick it up automatically + config block + `CATALOG` entry; the codegen prompts pick it up automatically
through `describe_bridges()`. through `describe_bridges()`.
+1 -3
View File
@@ -9,7 +9,7 @@ contract, `TESTGEN.md`. This file is about the runnable body only.
## What a skill is ## What a skill is
Semif-agent is an end-user application: an everyday person asks it to do a task, Semif-agent is an end-user application: an everyday person asks it to do a task,
and it does that task using a combination of user-provided data and a catalog of basic services known as bridges. A skill is the thing that performs one of those tasks: it is the leaf in the skill tree that the agent navigates to when it has resolved a request to a single, concrete action. and it does that task using a combination of user-provided data and a catalog of basic services known as bridges. A skill is the thing that performs one of those tasks: it is the leaf in the skill tree that the agent navigates to when it has resolved a request to a single, concrete action. Navigation is performed by an llm-based classification engine known as SemIf.
A skill is three things: A skill is three things:
@@ -59,8 +59,6 @@ def act(ctx, request) -> ActionResult:
during `act` so they are logged as training rows. `needs_input` carries a during `act` so they are logged as training rows. `needs_input` carries a
question for the human; see the rules below. question for the human; see the rules below.
There is no `predict` phase. Resolution and the action happen in `act`.
### Data contract ### Data contract
Every **required** operational value the body needs is declared in a Every **required** operational value the body needs is declared in a
+19 -1
View File
@@ -376,7 +376,7 @@ semif_agent/
static/ dashboard frontend (html/js/css) static/ dashboard frontend (html/js/css)
simplex_ws.py neutral SimpleX daemon protocol (shared by gateway + bridge) simplex_ws.py neutral SimpleX daemon protocol (shared by gateway + bridge)
gateway/ messenger COMMAND intake/reply (SimpleX first) gateway/ messenger COMMAND intake/reply (SimpleX first)
bridges/ standalone third-party API bridges (SimpleX first) bridges/ standalone third-party API bridges (SimpleX + the LLM bridge)
seeds/ committed starter skills (calendar, simplex) seeds/ committed starter skills (calendar, simplex)
scripts/ bootstrap.sh, simplex-address.py, systemd/*.in scripts/ bootstrap.sh, simplex-address.py, systemd/*.in
requirements/ staging.txt — the pinned engine deps requirements/ staging.txt — the pinned engine deps
@@ -496,6 +496,8 @@ Key blocks:
| `gateway.simplex` | command gateway: ws_url, allowlist, batching | | `gateway.simplex` | command gateway: ws_url, allowlist, batching |
| `bridges.simplex` | forwarding bridge: host/port/token/ws_url | | `bridges.simplex` | forwarding bridge: host/port/token/ws_url |
| `simplex_bridge_url` / `simplex_bridge_token` | what skill bodies call | | `simplex_bridge_url` / `simplex_bridge_token` | what skill bodies call |
| `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) |
| `llm_bridge_url` / `llm_bridge_token` | what skill bodies call for generation |
| `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) | | `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) |
| `dashboard` | bind host/port | | `dashboard` | bind host/port |
@@ -617,6 +619,22 @@ is injected into every codegen prompt via `describe_bridges()`, so it is the
single source of bridge specifics. Adding a bridge = a class + a config block + single source of bridge specifics. Adding a bridge = a class + a config block +
a `CATALOG` entry. a `CATALOG` entry.
The **LLM bridge** (`semif_agent/bridges/llm.py`) is the second: a generic
```
POST /chat {"messages": [{"role","content"}, ...], "max_tokens"?: int} -> {"text": "..."}
```
in front of the agent's language model, so a body can ask for short generated
text (e.g. extract an event title + description) over HTTP instead of speaking
the OpenAI-compatible protocol itself. It does not own the model connection:
`cli bridge` threads the scheduler's already-configured `llm` client into it, so
the endpoint/model/sampler live only in the top-level `llm` block; `bridges.llm`
carries just the local listener. Skills call it via `llm_bridge_url`
(+ optional `llm_bridge_token`); with no client it returns `502`, never a
fabricated reply. It starts in the same `semif-bridge.service` process as the
other enabled bridges.
### Dream report ### Dream report
```sh ```sh
+9
View File
@@ -94,6 +94,8 @@
"skill_seeds": "seeds", "skill_seeds": "seeds",
"simplex_bridge_url": "http://127.0.0.1:5227", "simplex_bridge_url": "http://127.0.0.1:5227",
"simplex_bridge_token": "", "simplex_bridge_token": "",
"llm_bridge_url": "http://127.0.0.1:5229",
"llm_bridge_token": "",
"log": "data/decisions.jsonl", "log": "data/decisions.jsonl",
"trace": "data/runs.jsonl", "trace": "data/runs.jsonl",
"category_registry": "data/categories.json", "category_registry": "data/categories.json",
@@ -117,6 +119,13 @@
"user_id": 1, "user_id": 1,
"auto_accept": true, "auto_accept": true,
"reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2} "reconnect": {"initial": 1.0, "max": 60.0, "jitter": 0.2}
},
"llm": {
"_comment": "LLM bridge: a generic `POST /chat` in front of the agent's configured `llm` model, so skill bodies can ask for short generated text (e.g. an event title + description) over HTTP instead of speaking the OpenAI-compatible protocol. It reuses the top-level `llm` client (endpoint/model/sampler configured once there); this block only carries the local listener. Skills use the top-level `llm_bridge_url`; keep it in sync with host/port. Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. It runs inside the same `semif-bridge.service` process as the other enabled bridges.",
"enabled": true,
"host": "127.0.0.1",
"port": 5229,
"token": ""
} }
}, },
"gateway": { "gateway": {
+5
View File
@@ -479,4 +479,9 @@ SimpleX forwarding bridge (messaging UX for skills):
- Skills reach it over HTTP via the top-level simplex_bridge_url - Skills reach it over HTTP via the top-level simplex_bridge_url
(default http://127.0.0.1:5227); simplex.connect_link shows its address and (default http://127.0.0.1:5227); simplex.connect_link shows its address and
simplex.next_message reads messages sent to it. simplex.next_message reads messages sent to it.
LLM bridge (generation for skills):
- Runs inside the same 'semif-bridge' process. It reuses the top-level `llm`
model (configured once) and serves a generic POST /chat; skills call it via
the top-level llm_bridge_url (default http://127.0.0.1:5229).
EOF EOF
+3 -1
View File
@@ -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_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_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_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."
} }
+110 -110
View File
@@ -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`, details and the default calendar come from `ctx.config` (`nextcloud_url`,
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`). `nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`).
`act` reads `request.text` and derives the event's per-request arguments — the `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. title and description are extracted by the local LLM bridge (`llm_bridge_url`,
Missing arguments are asked one at a time and the answer is stashed in `llm_bridge_token`) with one generic chat call, cached in `request.meta` so a
`request.meta`; because `act` is single-phase and re-runs from the top after a `needs_input` resume does not re-call it; the start date/time and duration are
`needs_input` pause, the body re-parses the query each pass and never re-asks a parsed deterministically. Missing arguments are asked one at a time and the
question it already has an answer for. Calendars are discovered over PROPFIND and answer is stashed in `request.meta`; because `act` is single-phase and re-runs
a named target is resolved with a SemIf sub-decision when more than one matches; from the top after a `needs_input` pause, the body never re-asks a question it
otherwise the configured default calendar is used. The event is created with a already has an answer for. Calendars are discovered over PROPFIND and the target
real CalDAV PUT (iCalendar, UTC timestamps, `If-None-Match: *`) and the real is resolved by a single SemIf choice over every owned calendar (state = the user
outcome is reported. 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 The date/time parse is deliberately bounded; the title/description come from the
to a skill body): when a required field cannot be derived confidently the body model. When the model bridge is unavailable the body reports the real failure
asks rather than guessing. rather than guessing.
""" """
from __future__ import annotations from __future__ import annotations
import base64 import base64
import json
import re import re
import urllib.error import urllib.error
import urllib.parse import urllib.parse
@@ -42,6 +46,8 @@ INTEGRATION = {
"nextcloud_username", "nextcloud_username",
"nextcloud_app_password", "nextcloud_app_password",
"nextcloud_default_calendar", "nextcloud_default_calendar",
"llm_bridge_url",
"llm_bridge_token",
], ],
} }
@@ -50,12 +56,17 @@ CONTRACT = {
"nextcloud_username": "The Nextcloud username whose calendars are used.", "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_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.",
} }
DAV = "DAV:" DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav" CALDAV = "urn:ietf:params:xml:ns:caldav"
TIMEOUT_SECONDS = 30 TIMEOUT_SECONDS = 30
DEFAULT_DURATION_MINUTES = 60 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 = ( PROPFIND_BODY = (
'<?xml version="1.0" encoding="utf-8"?>' '<?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)?" 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): class CalDavError(Exception):
"""A real failure talking to the calendar service.""" """A real failure talking to the calendar service."""
class BridgeError(Exception):
"""A real failure talking to the local LLM bridge."""
def _now(): def _now():
"""Current local time (aware). A test seam; the body never freezes time.""" """Current local time (aware). A test seam; the body never freezes time."""
return datetime.now().astimezone() return datetime.now().astimezone()
@@ -210,30 +210,65 @@ def _calendar_path(ctx, calendar):
) )
# ---- request -> arguments ---- # ---- LLM field extraction ----
def _remove_spans(text, spans): def _extract_fields(ctx, request):
for start, end in sorted(spans, reverse=True): """Ask the LLM bridge for the event title and description.
text = text[:start] + " " + text[end:]
return text 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): def _parse_fields(text):
text = re.sub(r"\s{2,}", " ", text).strip() """Pull the `{"title","description"}` object out of the model's reply."""
previous = None start, end = text.find("{"), text.rfind("}")
while previous != text: if start == -1 or end < start:
previous = text raise BridgeError("llm bridge returned no JSON object")
text = _LEADING_NOISE.sub("", text) try:
for pattern in _TITLE_NOISE: data = json.loads(text[start : end + 1])
text = pattern.sub(" ", text) except ValueError as exc:
text = _TRAILING_NOISE.sub("", text) raise BridgeError(f"llm bridge returned invalid JSON: {exc}") from exc
text = re.sub(r"\s{2,}", " ", text).strip() if not isinstance(data, dict):
return text.strip(" \t,;:-.") raise BridgeError("llm bridge returned JSON that is not an object")
return {
"title": str(data.get("title") or "").strip(),
def _extract_title(text, spans): "description": str(data.get("description") or "").strip(),
return _clean_title(_remove_spans(text or "", spans)) }
def _month_number(token): def _month_number(token):
@@ -261,8 +296,9 @@ def _parse_when(text, now):
"""Best-effort extraction of date/time/duration from free text. """Best-effort extraction of date/time/duration from free text.
Returns a dict with `date` (datetime.date | None), `time` (datetime.time | Returns a dict with `date` (datetime.date | None), `time` (datetime.time |
None), `all_day` (bool), `duration_minutes` (int | None), `from_weekday` None), `all_day` (bool), `duration_minutes` (int | None) and `from_weekday`
(bool) and `spans` (matched ranges, so the title can be cleaned). (bool). The title and description come from the LLM bridge, so no matched
spans are tracked here.
""" """
text = text or "" text = text or ""
result = { result = {
@@ -272,22 +308,18 @@ def _parse_when(text, now):
"duration_minutes": None, "duration_minutes": None,
"from_weekday": False, "from_weekday": False,
} }
spans = []
match = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", text, re.I) match = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", text, re.I)
if match: if match:
result["all_day"] = True result["all_day"] = True
spans.append(match.span())
match = re.search(r"\bfor\s+(\d+(?:\.\d+)?)\s*(hours?|hrs?|h)\b", text, re.I) match = re.search(r"\bfor\s+(\d+(?:\.\d+)?)\s*(hours?|hrs?|h)\b", text, re.I)
if match: if match:
result["duration_minutes"] = int(round(float(match.group(1)) * 60)) result["duration_minutes"] = int(round(float(match.group(1)) * 60))
spans.append(match.span())
else: else:
match = re.search(r"\bfor\s+(\d+)\s*(minutes?|mins?|m)\b", text, re.I) match = re.search(r"\bfor\s+(\d+)\s*(minutes?|mins?|m)\b", text, re.I)
if match: if match:
result["duration_minutes"] = int(match.group(1)) result["duration_minutes"] = int(match.group(1))
spans.append(match.span())
else: else:
for phrase, minutes in ( for phrase, minutes in (
(r"\bfor\s+half\s+an?\s+hour\b", 30), (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) match = re.search(phrase, text, re.I)
if match: if match:
result["duration_minutes"] = minutes result["duration_minutes"] = minutes
spans.append(match.span())
break break
date = None date = None
@@ -307,7 +338,6 @@ def _parse_when(text, now):
date = datetime( date = datetime(
int(match.group(1)), int(match.group(2)), int(match.group(3)) int(match.group(1)), int(match.group(2)), int(match.group(3))
).date() ).date()
spans.append(match.span())
except ValueError: except ValueError:
date = None date = None
@@ -321,8 +351,6 @@ def _parse_when(text, now):
month = _month_number(match.group(1)) month = _month_number(match.group(1))
year = int(match.group(3)) if match.group(3) else None year = int(match.group(3)) if match.group(3) else None
date = _resolve_month_day(month, int(match.group(2)), year, now) date = _resolve_month_day(month, int(match.group(2)), year, now)
if date is not None:
spans.append(match.span())
if date is None: if date is None:
match = re.search( match = re.search(
@@ -334,8 +362,6 @@ def _parse_when(text, now):
month = _month_number(match.group(2)) month = _month_number(match.group(2))
year = int(match.group(3)) if match.group(3) else None year = int(match.group(3)) if match.group(3) else None
date = _resolve_month_day(month, int(match.group(1)), year, now) date = _resolve_month_day(month, int(match.group(1)), year, now)
if date is not None:
spans.append(match.span())
if date is None: if date is None:
match = re.search(r"\b(\d{1,2})/(\d{1,2})(?:/(\d{2,4}))?\b", text) 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: if year is not None and year < 100:
year += 2000 year += 2000
date = _resolve_month_day(month, day, year, now) date = _resolve_month_day(month, day, year, now)
if date is not None:
spans.append(match.span())
if date is None: if date is None:
match = re.search( match = re.search(
@@ -361,7 +385,6 @@ def _parse_when(text, now):
date = now.date() + timedelta(days=1) date = now.date() + timedelta(days=1)
else: else:
date = now.date() + timedelta(days=7) date = now.date() + timedelta(days=7)
spans.append(match.span())
if date is None: if date is None:
match = _WEEKDAY_RE.search(text) match = _WEEKDAY_RE.search(text)
@@ -371,19 +394,14 @@ def _parse_when(text, now):
prefix = text[max(0, match.start() - 6):match.start()] prefix = text[max(0, match.start() - 6):match.start()]
if re.search(r"\bnext\s*$", prefix, re.I): if re.search(r"\bnext\s*$", prefix, re.I):
date += timedelta(days=7) date += timedelta(days=7)
spans.append((match.start() - len("next "), match.end()))
else:
spans.append(match.span())
result["from_weekday"] = True result["from_weekday"] = True
parsed_time = None parsed_time = None
match = re.search(r"\bnoon\b", text, re.I) match = re.search(r"\bnoon\b", text, re.I)
if match: if match:
parsed_time = time(12, 0) parsed_time = time(12, 0)
spans.append(match.span())
elif re.search(r"\bmidnight\b", text, re.I): elif re.search(r"\bmidnight\b", text, re.I):
parsed_time = time(0, 0) parsed_time = time(0, 0)
spans.append(re.search(r"\bmidnight\b", text, re.I).span())
else: else:
match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I) match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I)
if match: if match:
@@ -393,46 +411,25 @@ def _parse_when(text, now):
hour += 12 hour += 12
if hour < 24 and minute < 60: if hour < 24 and minute < 60:
parsed_time = time(hour, minute) parsed_time = time(hour, minute)
spans.append(match.span())
else: else:
match = re.search(r"\b(\d{1,2}):(\d{2})\b", text) match = re.search(r"\b(\d{1,2}):(\d{2})\b", text)
if match: if match:
hour, minute = int(match.group(1)), int(match.group(2)) hour, minute = int(match.group(1)), int(match.group(2))
if hour < 24 and minute < 60: if hour < 24 and minute < 60:
parsed_time = time(hour, minute) parsed_time = time(hour, minute)
spans.append(match.span())
else: else:
match = re.search(r"\bat\s+(\d{1,2})\b", text, re.I) match = re.search(r"\bat\s+(\d{1,2})\b", text, re.I)
if match and 13 <= int(match.group(1)) < 24: if match and 13 <= int(match.group(1)) < 24:
parsed_time = time(int(match.group(1)), 0) parsed_time = time(int(match.group(1)), 0)
spans.append(match.span())
result["date"] = date result["date"] = date
result["time"] = parsed_time result["time"] = parsed_time
result["spans"] = spans
return result return result
# ---- calendar resolution ---- # ---- 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): def _resolve_calendar(ctx, request, calendars, decisions):
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower() default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
default = None default = None
@@ -441,33 +438,22 @@ def _resolve_calendar(ctx, request, calendars, decisions):
default = calendar default = calendar
break 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: if len(calendars) == 1:
return calendars[0]["name"] 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( decision = DecisionRequest(
state=request.text, state=request.text,
question="Which calendar should the event go on?", question="Which calendar is referred to in the user query?",
options=options, options=[Option(c["name"], c["label"]) for c in calendars],
) )
result = ctx.engine.call(decision) result = ctx.engine.call(decision)
decisions.append((decision, result)) 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 ---- # ---- iCalendar ----
@@ -532,9 +518,21 @@ def act(ctx, request):
answers[awaiting] = request.user_input.strip() answers[awaiting] = request.user_input.strip()
request.meta.pop("create_event_awaiting", None) 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() now = _now()
parsed = _parse_when(request.text, now) parsed = _parse_when(request.text, now)
title = _extract_title(request.text, parsed["spans"])
if answers.get("title"): if answers.get("title"):
title = answers["title"].strip() title = answers["title"].strip()
@@ -589,7 +587,9 @@ def act(ctx, request):
calendar = _resolve_calendar(ctx, request, calendars, decisions) calendar = _resolve_calendar(ctx, request, calendars, decisions)
uid = f"{uuid.uuid4().hex}@semif-agent" 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" path = _calendar_path(ctx, calendar) + urllib.parse.quote(uid, safe="") + ".ics"
try: try:
_request( _request(
+162 -30
View File
@@ -1,12 +1,15 @@
"""Hermetic mechanics test for calendar.create_event. """Hermetic mechanics test for calendar.create_event.
Run from this folder: `python skill.test.py`. No external network: a loopback Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays a Nextcloud CalDAV endpoint (PROPFIND discovery + PUT create). 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 and the LLM bridge's `POST /chat`. This proves the body extracts the event title
a missing field and resumes, resolves the target calendar (default or named, with and description through the LLM bridge (caching the call across a `needs_input`
a SemIf sub-decision when ambiguous), writes a real iCalendar PUT, and fails resume), parses the date/time from the request, asks for a missing field and
honestly when the server errors. It does NOT prove the live integration — only a resumes, resolves the target calendar with a SemIf choice over the owned
real run against the user's Nextcloud does. 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 json
@@ -24,25 +27,36 @@ import skill
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc) FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
skill._now = lambda: FIXED_NOW skill._now = lambda: FIXED_NOW
DEFAULT_LLM_REPLY = {"title": "event", "description": ""}
def next_weekday(now, weekday): def next_weekday(now, weekday):
return now.date() + timedelta(days=(weekday - now.date().weekday()) % 7) return now.date() + timedelta(days=(weekday - now.date().weekday()) % 7)
class FakeEngine: 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.pick = pick
self.probs = probs
self.decisions = [] self.decisions = []
def call(self, decision): def call(self, decision):
self.decisions.append(decision) self.decisions.append(decision)
option_ids = [option.id for option in decision.options] option_ids = [option.id for option in decision.options]
chosen = self.pick if self.pick in option_ids else option_ids[0] if self.probs is not None:
probabilities = [ probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
1.0 if option_id == chosen else 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( return DecisionResult(
request=decision, option_ids=option_ids, probabilities=probabilities request=decision, option_ids=option_ids, probabilities=probabilities
) )
@@ -53,6 +67,9 @@ class CalDavHandler(BaseHTTPRequestHandler):
put_status = 201 put_status = 201
requests = [] requests = []
puts = [] puts = []
llm_reply = DEFAULT_LLM_REPLY
llm_status = 200
llm_requests = []
def _read_body(self): def _read_body(self):
length = int(self.headers.get("Content-Length") or 0) length = int(self.headers.get("Content-Length") or 0)
@@ -95,11 +112,26 @@ class CalDavHandler(BaseHTTPRequestHandler):
) )
self._send(b"", self.put_status, "text/plain") 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): def log_message(self, *args):
pass 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 = type(
"Handler", "Handler",
(CalDavHandler,), (CalDavHandler,),
@@ -113,6 +145,9 @@ def start_server(calendars=None, put_status=201):
"put_status": put_status, "put_status": put_status,
"requests": [], "requests": [],
"puts": [], "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) 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]}" 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 { return {
"nextcloud_url": url, "nextcloud_url": url,
"nextcloud_username": "alice", "nextcloud_username": "alice",
"nextcloud_app_password": "secret", "nextcloud_app_password": "secret",
"nextcloud_default_calendar": default, "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() 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) request = Request(text)
action = skill.act(ctx, request) action = skill.act(ctx, request)
return action, request, engine return action, request, engine
def test_example_creates_event_on_default_calendar(): 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: 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( 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 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 assert len(handler.puts) == 1, handler.puts
put = handler.puts[0] put = handler.puts[0]
assert put["path"].startswith("/remote.php/dav/calendars/alice/personal/"), put 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") == "*" assert put["headers"].get("If-None-Match") == "*"
body = put["body"].decode("utf-8") body = put["body"].decode("utf-8")
assert "SUMMARY:Ashley's dance recital" in body, body assert "SUMMARY:Ashley's dance recital" in body, body
assert "DESCRIPTION:Dance recital at 5pm." in body, body
tuesday = next_weekday(FIXED_NOW, 1) tuesday = next_weekday(FIXED_NOW, 1)
assert f"DTSTART:{tuesday.strftime('%Y%m%d')}T170000Z" in body, body 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 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(): def test_missing_time_asks_then_creates():
server, handler, url = start_server() server, handler, url = start_server(
llm_reply={"title": "dentist appointment", "description": ""}
)
try: try:
action, request, engine = run( action, request, engine = run(
handler, url, "add dentist appointment on 2026-11-10" 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 action.needs_input, "a missing start time must be asked"
assert "time" in action.needs_input.lower(), action.needs_input assert "time" in action.needs_input.lower(), action.needs_input
assert handler.puts == [] assert handler.puts == []
assert len(handler.llm_requests) == 1, "the LLM is called once, then cached"
request.user_input = "2pm" request.user_input = "2pm"
ctx = ActionContext(engine=engine, config=config(url)) ctx = ActionContext(engine=engine, config=config(url))
action = skill.act(ctx, request) action = skill.act(ctx, request)
assert action.needs_input is None, action.needs_input assert action.needs_input is None, action.needs_input
assert len(handler.puts) == 1, handler.puts 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") body = handler.puts[0]["body"].decode("utf-8")
assert "SUMMARY:dentist appointment" in body, body assert "SUMMARY:dentist appointment" in body, body
assert "DTSTART:20261110T140000Z" 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(): def test_missing_day_asks_then_creates():
server, handler, url = start_server() server, handler, url = start_server(
llm_reply={"title": "dentist appointment", "description": ""}
)
try: try:
action, request, engine = run(handler, url, "add dentist appointment at 2pm") action, request, engine = run(handler, url, "add dentist appointment at 2pm")
assert action.needs_input, "a missing day must be asked" 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(): def test_missing_title_asks():
server, handler, url = start_server() server, handler, url = start_server(llm_reply={"title": "", "description": ""})
try: try:
action, _request, _engine = run(handler, url, "schedule on 2026-11-10 at 2pm") action, _request, _engine = run(handler, url, "schedule on 2026-11-10 at 2pm")
assert action.needs_input, "a missing title must be asked" 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(): def test_named_calendar_is_used():
server, handler, url = start_server() server, handler, url = start_server(
llm_reply={"title": "team sync", "description": ""}
)
try: try:
engine = FakeEngine(pick="work")
action, _request, engine = run( 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 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( assert handler.puts[0]["path"].startswith(
"/remote.php/dav/calendars/alice/work/" "/remote.php/dav/calendars/alice/work/"
), handler.puts[0] ), handler.puts[0]
@@ -235,10 +304,35 @@ def test_named_calendar_is_used():
server.server_close() server.server_close()
def test_unknown_default_uses_semif_decision(): def test_weak_winner_falls_back_to_default():
server, handler, url = start_server() server, handler, url = start_server(llm_reply={"title": "standup", "description": ""})
try: 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( action, _request, engine = run(
handler, handler,
url, url,
@@ -259,7 +353,7 @@ def test_unknown_default_uses_semif_decision():
def test_all_day_event(): def test_all_day_event():
server, handler, url = start_server() server, handler, url = start_server(llm_reply={"title": "conference", "description": ""})
try: try:
action, _request, _engine = run( action, _request, _engine = run(
handler, url, "add conference all day on 2026-11-10" handler, url, "add conference all day on 2026-11-10"
@@ -275,8 +369,43 @@ def test_all_day_event():
server.server_close() 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(): 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: try:
action, request, _engine = run( action, request, _engine = run(
handler, url, "add standup on 2026-11-10 at 9am" handler, url, "add standup on 2026-11-10 at 9am"
@@ -304,8 +433,11 @@ def main():
test_missing_day_asks_then_creates() test_missing_day_asks_then_creates()
test_missing_title_asks() test_missing_title_asks()
test_named_calendar_is_used() test_named_calendar_is_used()
test_weak_winner_falls_back_to_default()
test_unknown_default_uses_semif_decision() test_unknown_default_uses_semif_decision()
test_all_day_event() 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_server_error_is_reported_honestly()
test_unreachable_server_fails_honestly() test_unreachable_server_fails_honestly()
print("ok") print("ok")
+6 -5
View File
@@ -1,11 +1,12 @@
"""Third-party API bridges: a secure local layer between skills and services. """Third-party API bridges: a secure local layer between skills and services.
A **bridge service** is a standalone process that exposes one third-party system A **bridge service** is a standalone process that exposes one third-party system
(SimpleX first, more later) to codegen-authored skill bodies over a local, (SimpleX, the local language model) to codegen-authored skill bodies over a
token-guarded HTTP API. It exists so a generated body never speaks a system's local, token-guarded HTTP API. It exists so a generated body never speaks a
native protocol (WebSocket, SMTP, CalDAV, a CLI's private flags) directly: it system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat
calls a small, documented, uniform HTTP surface instead, and the bridge owns the API, a CLI's private flags) directly: it calls a small, documented, uniform HTTP
messy integration details and credentials. surface instead, and the bridge owns the messy integration details and
credentials.
Two boundaries matter: Two boundaries matter:
+99
View File
@@ -0,0 +1,99 @@
"""LLM bridge: the agent's language model behind the standard bridge surface.
Skill bodies are stdlib-only and must not speak a model's native
OpenAI-compatible protocol directly. This bridge exposes one generic chat call
over the same local, token-guarded JSON surface every other bridge uses, so a
body can ask for short generated text (e.g. extract an event title and
description from a request) without importing a client or knowing the endpoint.
It does **not** own the model connection: it reuses the scheduler's already
configured `llm` client, passed in at construction, so the endpoint/model/
sampler live in one place (the top-level `llm` block). Constructed without a
client (tests, standalone) it has no model and every call reports 502 rather
than fabricating an answer.
"""
from __future__ import annotations
from .base import BridgeInfo, BridgeService
class LLMBridge(BridgeService):
name = "llm"
INFO = BridgeInfo(
name="llm",
service="llm",
description=(
"Generate short text with the agent's configured language model, "
"e.g. extract a title and a description from a user's request."
),
url_config_var="llm_bridge_url",
endpoints=(
'GET /health -> 200 {"ok": true, "platform": "llm"} — the bridge is up',
'POST /chat {"messages": [{"role", "content"}, ...], "max_tokens"?: int} '
'-> 200 {"text": "<model reply>"}; 400 {"error": "..."} on a '
'missing/invalid messages list; 502 {"error": "..."} when the model '
"call fails or no model is configured",
'any request -> 401 {"error": "unauthorized"} when the token is '
"configured and the auth header is missing or wrong",
),
config_vars=("llm_bridge_url", "llm_bridge_token"),
config_var_docs=(
(
"llm_bridge_url",
"Base URL of the local LLM bridge (e.g. http://127.0.0.1:5229); "
"never hardcode it in the body.",
),
(
"llm_bridge_token",
"Shared secret for the bridge, if one is configured; sent as the "
"X-Semif-Token header. Leave blank when the bridge requires no auth.",
),
),
auth_header="X-Semif-Token",
auth_config_var="llm_bridge_token",
)
def __init__(self, config: dict | None = None, trace=None, client=None):
super().__init__(config, trace)
#: The scheduler's configured `llm` client (or a test double). None when
#: the bridge is built without one; calls then report 502, never a guess.
self.client = client
# ---- lifecycle ----
def check_requirements(self) -> tuple[bool, str | None]:
# Stdlib only: no missing dependency can make the bridge unstartable. A
# missing model surfaces as a 502 on the call, not as a startup failure.
return True, None
# ---- routes ----
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
if path == "/health":
return 200, {"ok": True, "platform": self.name}
return 404, {"error": "not found"}
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
if path != "/chat":
return 404, {"error": "not found"}
messages = payload.get("messages")
if not isinstance(messages, list) or not messages:
return 400, {"error": "messages is required"}
if not all(
isinstance(message, dict)
and isinstance(message.get("role"), str)
and isinstance(message.get("content"), str)
for message in messages
):
return 400, {"error": "each message needs a string role and content"}
max_tokens = payload.get("max_tokens")
if max_tokens is not None and not isinstance(max_tokens, int):
return 400, {"error": "max_tokens must be an integer"}
if self.client is None:
return 502, {"error": "no language model is configured"}
try:
text = self.client.chat(messages, max_tokens=max_tokens)
except Exception as exc: # the model client's error type + anything it raises
return 502, {"error": f"llm call failed: {exc}"[:300]}
return 200, {"text": text}
+17 -5
View File
@@ -13,10 +13,11 @@ from __future__ import annotations
import threading import threading
from .base import BridgeInfo, BridgeService from .base import BridgeInfo, BridgeService
from .llm import LLMBridge
from .simplex import SimplexBridge from .simplex import SimplexBridge
#: Known bridge services. Order is presentation order. #: Known bridge services. Order is presentation order.
CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge,) CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge, LLMBridge)
def _class_for(name: str) -> type[BridgeService] | None: def _class_for(name: str) -> type[BridgeService] | None:
@@ -67,12 +68,21 @@ def describe_bridges() -> str:
return "\n".join(lines) + "\n" return "\n".join(lines) + "\n"
def build_bridge(config: dict, name: str, trace=None) -> BridgeService: def build_bridge(
"""Instantiate one bridge from the top-level `bridges.<name>` config block.""" config: dict, name: str, trace=None, llm=None
) -> BridgeService:
"""Instantiate one bridge from the top-level `bridges.<name>` config block.
`llm` is the scheduler's configured language-model client, handed to the LLM
bridge so it reuses the top-level `llm` endpoint/model instead of duplicating
that config. Other bridges ignore it.
"""
bridge_class = _class_for(name) bridge_class = _class_for(name)
if bridge_class is None: if bridge_class is None:
raise KeyError(f"unknown bridge: {name!r}") raise KeyError(f"unknown bridge: {name!r}")
block = (config.get("bridges", {}) or {}).get(name, {}) or {} block = (config.get("bridges", {}) or {}).get(name, {}) or {}
if bridge_class is LLMBridge:
return LLMBridge(block, trace=trace, client=llm)
return bridge_class(block, trace=trace) return bridge_class(block, trace=trace)
@@ -80,11 +90,13 @@ def run_bridges(
config: dict, config: dict,
names: list[str] | None = None, names: list[str] | None = None,
trace=None, trace=None,
llm=None,
) -> int: ) -> int:
"""Run the selected (+ enabled) bridges until interrupted. """Run the selected (+ enabled) bridges until interrupted.
With explicit `names`, a bridge runs even if disabled is not set; with no With explicit `names`, a bridge runs even if disabled is not set; with no
names, only `enabled` bridges run. Returns a process exit code. names, only `enabled` bridges run. Returns a process exit code. `llm` is the
scheduler's configured language-model client (see `build_bridge`).
""" """
blocks = config.get("bridges", {}) or {} blocks = config.get("bridges", {}) or {}
selected: list[BridgeService] = [] selected: list[BridgeService] = []
@@ -95,7 +107,7 @@ def run_bridges(
block = blocks.get(name, {}) or {} block = blocks.get(name, {}) or {}
if not names and not block.get("enabled", False): if not names and not block.get("enabled", False):
continue continue
bridge = bridge_class(block, trace=trace) bridge = build_bridge(config, name, trace=trace, llm=llm)
ok, hint = bridge.check_requirements() ok, hint = bridge.check_requirements()
if not ok: if not ok:
print(f"bridge {name} unavailable: {hint}") print(f"bridge {name} unavailable: {hint}")
+5 -2
View File
@@ -486,7 +486,8 @@ def repl(scheduler: Scheduler, config: dict) -> int:
if _fatal_exit(scheduler) is not None: if _fatal_exit(scheduler) is not None:
return 1 return 1
while scheduler.pending is not None: while scheduler.pending is not None:
answer = input(f"{scheduler.pending.question} ") hint = "" if scheduler.pending.pre_act else " [leave empty to skip]"
answer = input(f"{scheduler.pending.question}{hint} ")
status, detail = scheduler.answer(answer) status, detail = scheduler.answer(answer)
print(f"[{status}] {detail}") print(f"[{status}] {detail}")
if _fatal_exit(scheduler) is not None: if _fatal_exit(scheduler) is not None:
@@ -629,7 +630,9 @@ def run_bridge(scheduler: Scheduler, config: dict, name: str | None = None) -> i
from .bridges.registry import run_bridges from .bridges.registry import run_bridges
names = [name] if name else None names = [name] if name else None
return run_bridges(config, names=names, trace=scheduler.trace) return run_bridges(
config, names=names, trace=scheduler.trace, llm=scheduler.llm
)
def main(argv: list[str] | None = None) -> int: def main(argv: list[str] | None = None) -> int:
+10 -2
View File
@@ -572,7 +572,10 @@ class Scheduler:
"""Feed the human's answer to a run paused for input. """Feed the human's answer to a run paused for input.
Routed directly to the pending run — no gate, score, or navigation — Routed directly to the pending run — no gate, score, or navigation —
and the run resumes by re-invoking `act`. and the run resumes by re-invoking `act`. An empty answer is accepted:
a pre-act contract variable is left unset and marked skipped, and an
act-driven pause receives the empty string (the body may then fail,
which is assessed normally).
""" """
with self._lock: with self._lock:
if self.pending is None: if self.pending is None:
@@ -580,7 +583,12 @@ class Scheduler:
pending = self.pending pending = self.pending
self.pending = None self.pending = None
pending.request.user_input = text pending.request.user_input = text
self.trace.append("answered", pending.request.id, text=text) self.trace.append(
"answered",
pending.request.id,
text=text,
skipped=not (text or "").strip(),
)
outcome = self.runner.resume( outcome = self.runner.resume(
pending.skill, pending.request, pre_act=pending.pre_act pending.skill, pending.request, pre_act=pending.pre_act
) )
+14 -6
View File
@@ -125,17 +125,22 @@ class SkillRunner:
return [] return []
answered = request.meta.get("config_answers", {}) answered = request.meta.get("config_answers", {})
if self.store is not None: if self.store is not None:
return unresolved_variables(self.store, skill, self.ctx.config, answered) missing = unresolved_variables(self.store, skill, self.ctx.config, answered)
merged = {**self.ctx.config} else:
merged.update(skill.config or {}) merged = {**self.ctx.config}
merged.update(answered) merged.update(skill.config or {})
return [name for name in skill.contract if name not in merged] merged.update(answered)
missing = [name for name in skill.contract if name not in merged]
# A variable the human chose to skip (empty answer) stays unresolved but
# must never be re-asked: the run proceeds with it left unset.
skipped = request.meta.get("config_skipped", ())
return [name for name in missing if name not in skipped]
def _variable_question(self, skill: Skill, variable: str) -> str: def _variable_question(self, skill: Skill, variable: str) -> str:
desc = (skill.contract or {}).get(variable, "") desc = (skill.contract or {}).get(variable, "")
return ( return (
f"To run {skill.category}.{skill.name} I need `{variable}`. {desc}\n" f"To run {skill.category}.{skill.name} I need `{variable}`. {desc}\n"
"Reply with the value, or 'skip' to leave it empty." "Reply with the value, or leave it empty to skip."
) )
def _decide_record(self, skill: Skill, request: Request, variable: str, value: str) -> bool: def _decide_record(self, skill: Skill, request: Request, variable: str, value: str) -> bool:
@@ -172,6 +177,8 @@ class SkillRunner:
def _record_answer(self, skill: Skill, request: Request) -> None: def _record_answer(self, skill: Skill, request: Request) -> None:
"""Persist (or stash per-fire) the human's answer to the last question. """Persist (or stash per-fire) the human's answer to the last question.
An empty answer (or the literal "skip") leaves the variable unset and
marks it skipped for this run, so the run continues instead of re-asking.
`request.user_input` is cleared after consumption so a contract answer `request.user_input` is cleared after consumption so a contract answer
does not leak into a later act-driven pause or the skill's own does not leak into a later act-driven pause or the skill's own
user_input checks. user_input checks.
@@ -183,6 +190,7 @@ class SkillRunner:
return return
value = answer.strip() value = answer.strip()
if not value or value.lower() == "skip": if not value or value.lower() == "skip":
request.meta.setdefault("config_skipped", set()).add(variable)
return return
if self._decide_record(skill, request, variable, value): if self._decide_record(skill, request, variable, value):
skill.config = {**(skill.config or {}), variable: value} skill.config = {**(skill.config or {}), variable: value}
+1 -1
View File
@@ -699,7 +699,7 @@ function renderStatus() {
const pending = state.status.pending; const pending = state.status.pending;
$("#answer-form").classList.toggle("hidden", !pending); $("#answer-form").classList.toggle("hidden", !pending);
if (pending) { if (pending) {
$("#answer-input").placeholder = `${pending.skill}: ${pending.question}`; $("#answer-input").placeholder = `${pending.skill}: ${pending.question} (empty to skip)`;
const p = document.createElement("div"); const p = document.createElement("div");
p.className = "pending-line"; p.className = "pending-line";
p.textContent = `awaiting input (${pending.run_id || pending.skill}): ${pending.question}`; p.textContent = `awaiting input (${pending.run_id || pending.skill}): ${pending.question}`;
+1 -1
View File
@@ -20,7 +20,7 @@
</form> </form>
<form id="answer-form" class="hidden"> <form id="answer-form" class="hidden">
<input id="answer-input" type="text" autocomplete="off" spellcheck="false" <input id="answer-input" type="text" autocomplete="off" spellcheck="false"
placeholder="answer the pending question"> placeholder="answer the pending question (empty to skip)">
<button type="submit" id="answer-btn">answer</button> <button type="submit" id="answer-btn">answer</button>
</form> </form>
<div id="answer-feedback" class="hidden"></div> <div id="answer-feedback" class="hidden"></div>
+100
View File
@@ -14,6 +14,7 @@ import urllib.request
import pytest import pytest
from semif_agent.bridges.llm import LLMBridge
from semif_agent.bridges.registry import describe_bridges, known_infos from semif_agent.bridges.registry import describe_bridges, known_infos
from semif_agent.bridges.simplex import SimplexBridge from semif_agent.bridges.simplex import SimplexBridge
@@ -442,6 +443,94 @@ def test_history_lookup_failure_is_reported():
bridge.stop() bridge.stop()
# ---- LLM bridge ----
class FakeLLMClient:
"""Stands in for the scheduler's configured `llm` client."""
def __init__(self, reply="ok", error=None):
self.reply = reply
self.error = error
self.calls = []
def chat(self, messages, max_tokens=None):
self.calls.append((messages, max_tokens))
if self.error is not None:
raise self.error
return self.reply
def start_llm_bridge(client=None, **config):
bridge = LLMBridge(config, client=client)
port = bridge.start()
return bridge, f"http://127.0.0.1:{port}"
def test_llm_bridge_chat_returns_model_text():
client = FakeLLMClient(reply='{"title": "x", "description": ""}')
bridge, base = start_llm_bridge(client)
try:
messages = [{"role": "user", "content": "add lunch tomorrow"}]
assert post(f"{base}/chat", {"messages": messages}) == {
"text": client.reply
}
assert client.calls == [(messages, None)]
finally:
bridge.stop()
def test_llm_bridge_forwards_max_tokens():
client = FakeLLMClient()
bridge, base = start_llm_bridge(client)
try:
post(f"{base}/chat", {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 64})
assert client.calls[0][1] == 64
finally:
bridge.stop()
def test_llm_bridge_rejects_bad_body():
bridge, base = start_llm_bridge(FakeLLMClient())
try:
for payload in ({"messages": []}, {"messages": [{"role": "user"}]}, {}):
with pytest.raises(urllib.error.HTTPError) as exc:
post(f"{base}/chat", payload)
assert exc.value.code == 400
finally:
bridge.stop()
def test_llm_bridge_without_a_client_is_unavailable():
bridge, base = start_llm_bridge(None)
try:
with pytest.raises(urllib.error.HTTPError) as exc:
post(f"{base}/chat", {"messages": [{"role": "user", "content": "hi"}]})
assert exc.value.code == 502
finally:
bridge.stop()
def test_llm_bridge_maps_client_error_to_502():
bridge, base = start_llm_bridge(FakeLLMClient(error=RuntimeError("down")))
try:
with pytest.raises(urllib.error.HTTPError) as exc:
post(f"{base}/chat", {"messages": [{"role": "user", "content": "hi"}]})
assert exc.value.code == 502
finally:
bridge.stop()
def test_llm_bridge_health_and_token():
bridge, base = start_llm_bridge(FakeLLMClient(), token="sekret")
try:
with pytest.raises(urllib.error.HTTPError) as exc:
get(f"{base}/health")
assert exc.value.code == 401
assert get(f"{base}/health", token="sekret") == {"ok": True, "platform": "llm"}
finally:
bridge.stop()
# ---- catalog / codegen surface ---- # ---- catalog / codegen surface ----
def test_known_infos_include_simplex(): def test_known_infos_include_simplex():
@@ -454,6 +543,17 @@ def test_known_infos_include_simplex():
assert info.auth_config_var == "simplex_bridge_token" assert info.auth_config_var == "simplex_bridge_token"
def test_known_infos_include_llm():
infos = {info.name: info for info in known_infos()}
assert "llm" in infos
info = infos["llm"]
assert info.service == "llm"
assert info.url_config_var == "llm_bridge_url"
assert info.auth_header == "X-Semif-Token"
assert info.auth_config_var == "llm_bridge_token"
assert any("/chat" in endpoint for endpoint in info.endpoints)
def test_every_bridge_documents_its_config_vars_and_auth(): def test_every_bridge_documents_its_config_vars_and_auth():
for info in known_infos(): for info in known_infos():
docs = dict(info.config_var_docs) docs = dict(info.config_var_docs)
+24
View File
@@ -318,6 +318,30 @@ def test_answer_roundtrip_via_api(tmp_path):
finally: finally:
server.close() server.close()
def test_answer_accepts_empty_via_api(tmp_path):
scheduler = build_scheduler(tmp_path)
seen = []
def act(ctx, request):
seen.append(request.user_input)
if request.user_input is None:
return ActionResult(
action_log="ask", new_state=request.text, needs_input="Tracking number?"
)
return ActionResult(action_log="empty answer", new_state="unresolved")
skill = Skill(name="track.manual", category="tracking", description="", act=act)
scheduler._run_skill(skill, Request("track my package"))
server = Server(scheduler)
try:
status, payload = server.post("/api/answer", {"text": ""})
assert status == 200
assert payload["status"] == "ran"
assert seen == [None, ""], "empty answer must be forwarded to act"
finally:
server.close()
def test_questions_endpoint_roundtrip(tmp_path): def test_questions_endpoint_roundtrip(tmp_path):
scheduler = build_scheduler(tmp_path) scheduler = build_scheduler(tmp_path)
scheduler.questions.append( scheduler.questions.append(
+30
View File
@@ -173,3 +173,33 @@ def test_resume_can_ask_again(tmp_path):
assert status == "ran" assert status == "ran"
assert scheduler.pending is None assert scheduler.pending is None
assert scheduler.current is None assert scheduler.current is None
def test_empty_answer_is_accepted_and_forwarded(tmp_path):
"""An act-driven pause always accepts an empty answer: it is forwarded to
`act` as user_input='' (never rejected). A body that cannot proceed without
the info simply produces a failed run, which assessment handles."""
scheduler = build_scheduler(tmp_path)
seen = []
def act(ctx, request):
seen.append(request.user_input)
if request.user_input is None:
return ActionResult(
action_log="ask",
new_state=request.text,
needs_input="What's the tracking number?",
)
return ActionResult(action_log="empty answer", new_state="unresolved")
skill = Skill(name="track.manual", category="tracking", description="", act=act)
result = scheduler._run_skill(skill, Request("track my package"))
assert result.kind == "needs_input"
status, detail = scheduler.answer("")
assert status == "ran", detail
assert seen == [None, ""], "the empty answer must reach act"
assert scheduler.pending is None
assert scheduler.current is None
answered = [e for e in scheduler.trace.read() if e["kind"] == "answered"]
assert answered and answered[-1]["skipped"] is True
+71
View File
@@ -1318,6 +1318,77 @@ def test_skill_pre_act_contract_pause_and_resume(tmp_path):
assert scheduler.pending is None assert scheduler.pending is None
def test_pre_act_skip_leaves_variable_unset_and_does_not_reask(tmp_path):
"""An empty answer skips a contract variable: it is left unset, the run
proceeds, and the same variable is never re-asked (regression: the old
no-op skip re-asked the identical question forever)."""
scheduler = _scheduler(tmp_path)
scheduler.tree["tracking"] = []
scheduler.body_store.write_contract(
"tracking", "track_live", {"token": "The tracking token."}
)
seen = {}
def act(ctx, request):
seen.update(ctx.config)
return ActionResult(action_log="done", new_state="done")
skill = Skill(
name="track_live",
category="tracking",
description="Follow a package.",
act=act,
contract={"token": "The tracking token."},
)
result = scheduler._run_skill(skill, Request("track my package"))
assert result.kind == "needs_input"
assert scheduler.pending is not None and scheduler.pending.pre_act is True
status, detail = scheduler.answer("")
assert status == "ran", detail
assert scheduler.pending is None
assert "token" not in seen, "a skipped variable must stay unset"
def test_pre_act_skip_advances_to_next_missing_variable(tmp_path):
"""Skipping one contract variable leaves just that one empty and moves on to
the next missing variable, then runs."""
scheduler = _scheduler(tmp_path)
scheduler.tree["tracking"] = []
scheduler.body_store.write_contract(
"tracking", "probe", {"alpha": "first", "beta": "second"}
)
seen = {}
def act(ctx, request):
seen.update(ctx.config)
return ActionResult(action_log="done", new_state="done")
skill = Skill(
name="probe",
category="tracking",
description="Probe.",
act=act,
contract={"alpha": "first", "beta": "second"},
)
result = scheduler._run_skill(skill, Request("probe"))
assert result.kind == "needs_input"
assert "`alpha`" in result.summary
status, detail = scheduler.answer("")
assert status == "needs_input"
assert scheduler.pending is not None
assert "`beta`" in scheduler.pending.question
status, detail = scheduler.answer("")
assert status == "ran", detail
assert "alpha" not in seen and "beta" not in seen
def test_unresolved_variables_respects_tiered_config(tmp_path): def test_unresolved_variables_respects_tiered_config(tmp_path):
"""Contract vars are satisfied by global config, category config, skill """Contract vars are satisfied by global config, category config, skill
config, or per-fire answers — in that order of precedence.""" config, or per-fire answers — in that order of precedence."""