llm bridge service
This commit is contained in:
1 parent
f21baa7ebd
commit
63c5fc9903
20 files changed
+717
-164
No files matched your search
@@ -182,7 +182,8 @@ gateway/ messenger COMMAND intake/reply — and nothing else. base.py:
|
||||
`gateway.simplex`. The gateway MUST NOT read history, show/create
|
||||
invite links, or compose messages — see "gateway isolation"
|
||||
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,
|
||||
`X-Semif-Token` guard). inbox.py: MessagingInbox (bounded FIFO +
|
||||
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
|
||||
contact list on (re)connect + on demand, serves invite-link/
|
||||
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
|
||||
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`.
|
||||
simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway
|
||||
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
|
||||
(`gateway.simplex.enabled = true`, `ws_url` from `simplex_chat.port`) and the
|
||||
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`/
|
||||
`codegen.base_url`. Bootstrap renders/enables four user services:
|
||||
`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
|
||||
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`.
|
||||
**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
|
||||
includes the resolved contract values (`resolved inputs:` block) so the
|
||||
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`
|
||||
transport, so their hermetic tests are loopback HTTP like any other HTTP body.
|
||||
`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)
|
||||
|
||||
@@ -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
|
||||
SemIf sub-decision over `/contacts`, send only on explicit user intent, and
|
||||
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
|
||||
through `describe_bridges()`.
|
||||
|
||||
|
||||
+1
-3
@@ -9,7 +9,7 @@ contract, `TESTGEN.md`. This file is about the runnable body only.
|
||||
## What a skill is
|
||||
|
||||
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:
|
||||
|
||||
@@ -59,8 +59,6 @@ def act(ctx, request) -> ActionResult:
|
||||
during `act` so they are logged as training rows. `needs_input` carries a
|
||||
question for the human; see the rules below.
|
||||
|
||||
There is no `predict` phase. Resolution and the action happen in `act`.
|
||||
|
||||
### Data contract
|
||||
|
||||
Every **required** operational value the body needs is declared in a
|
||||
|
||||
@@ -376,7 +376,7 @@ semif_agent/
|
||||
static/ dashboard frontend (html/js/css)
|
||||
simplex_ws.py neutral SimpleX daemon protocol (shared by gateway + bridge)
|
||||
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)
|
||||
scripts/ bootstrap.sh, simplex-address.py, systemd/*.in
|
||||
requirements/ staging.txt — the pinned engine deps
|
||||
@@ -496,6 +496,8 @@ Key blocks:
|
||||
| `gateway.simplex` | command gateway: ws_url, allowlist, batching |
|
||||
| `bridges.simplex` | forwarding bridge: host/port/token/ws_url |
|
||||
| `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`) |
|
||||
| `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 +
|
||||
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
|
||||
|
||||
```sh
|
||||
|
||||
@@ -94,6 +94,8 @@
|
||||
"skill_seeds": "seeds",
|
||||
"simplex_bridge_url": "http://127.0.0.1:5227",
|
||||
"simplex_bridge_token": "",
|
||||
"llm_bridge_url": "http://127.0.0.1:5229",
|
||||
"llm_bridge_token": "",
|
||||
"log": "data/decisions.jsonl",
|
||||
"trace": "data/runs.jsonl",
|
||||
"category_registry": "data/categories.json",
|
||||
@@ -117,6 +119,13 @@
|
||||
"user_id": 1,
|
||||
"auto_accept": true,
|
||||
"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": {
|
||||
|
||||
@@ -479,4 +479,9 @@ SimpleX forwarding bridge (messaging UX for skills):
|
||||
- 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
|
||||
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
|
||||
@@ -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,21 +27,32 @@ 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]
|
||||
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
|
||||
@@ -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")
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""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
|
||||
(SimpleX first, more later) to codegen-authored skill bodies over a local,
|
||||
token-guarded HTTP API. It exists so a generated body never speaks a system's
|
||||
native protocol (WebSocket, SMTP, CalDAV, a CLI's private flags) directly: it
|
||||
calls a small, documented, uniform HTTP surface instead, and the bridge owns the
|
||||
messy integration details and credentials.
|
||||
(SimpleX, the local language model) to codegen-authored skill bodies over a
|
||||
local, token-guarded HTTP API. It exists so a generated body never speaks a
|
||||
system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat
|
||||
API, a CLI's private flags) directly: it calls a small, documented, uniform HTTP
|
||||
surface instead, and the bridge owns the messy integration details and
|
||||
credentials.
|
||||
|
||||
Two boundaries matter:
|
||||
|
||||
|
||||
@@ -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}
|
||||
@@ -13,10 +13,11 @@ from __future__ import annotations
|
||||
import threading
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .llm import LLMBridge
|
||||
from .simplex import SimplexBridge
|
||||
|
||||
#: 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:
|
||||
@@ -67,12 +68,21 @@ def describe_bridges() -> str:
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def build_bridge(config: dict, name: str, trace=None) -> BridgeService:
|
||||
"""Instantiate one bridge from the top-level `bridges.<name>` config block."""
|
||||
def build_bridge(
|
||||
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)
|
||||
if bridge_class is None:
|
||||
raise KeyError(f"unknown bridge: {name!r}")
|
||||
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)
|
||||
|
||||
|
||||
@@ -80,11 +90,13 @@ def run_bridges(
|
||||
config: dict,
|
||||
names: list[str] | None = None,
|
||||
trace=None,
|
||||
llm=None,
|
||||
) -> int:
|
||||
"""Run the selected (+ enabled) bridges until interrupted.
|
||||
|
||||
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 {}
|
||||
selected: list[BridgeService] = []
|
||||
@@ -95,7 +107,7 @@ def run_bridges(
|
||||
block = blocks.get(name, {}) or {}
|
||||
if not names and not block.get("enabled", False):
|
||||
continue
|
||||
bridge = bridge_class(block, trace=trace)
|
||||
bridge = build_bridge(config, name, trace=trace, llm=llm)
|
||||
ok, hint = bridge.check_requirements()
|
||||
if not ok:
|
||||
print(f"bridge {name} unavailable: {hint}")
|
||||
|
||||
+5
-2
@@ -486,7 +486,8 @@ def repl(scheduler: Scheduler, config: dict) -> int:
|
||||
if _fatal_exit(scheduler) is not None:
|
||||
return 1
|
||||
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)
|
||||
print(f"[{status}] {detail}")
|
||||
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
|
||||
|
||||
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:
|
||||
|
||||
@@ -572,7 +572,10 @@ class Scheduler:
|
||||
"""Feed the human's answer to a run paused for input.
|
||||
|
||||
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:
|
||||
if self.pending is None:
|
||||
@@ -580,7 +583,12 @@ class Scheduler:
|
||||
pending = self.pending
|
||||
self.pending = None
|
||||
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(
|
||||
pending.skill, pending.request, pre_act=pending.pre_act
|
||||
)
|
||||
|
||||
+11
-3
@@ -125,17 +125,22 @@ class SkillRunner:
|
||||
return []
|
||||
answered = request.meta.get("config_answers", {})
|
||||
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)
|
||||
else:
|
||||
merged = {**self.ctx.config}
|
||||
merged.update(skill.config or {})
|
||||
merged.update(answered)
|
||||
return [name for name in skill.contract if name not in merged]
|
||||
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:
|
||||
desc = (skill.contract or {}).get(variable, "")
|
||||
return (
|
||||
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:
|
||||
@@ -172,6 +177,8 @@ class SkillRunner:
|
||||
def _record_answer(self, skill: Skill, request: Request) -> None:
|
||||
"""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
|
||||
does not leak into a later act-driven pause or the skill's own
|
||||
user_input checks.
|
||||
@@ -183,6 +190,7 @@ class SkillRunner:
|
||||
return
|
||||
value = answer.strip()
|
||||
if not value or value.lower() == "skip":
|
||||
request.meta.setdefault("config_skipped", set()).add(variable)
|
||||
return
|
||||
if self._decide_record(skill, request, variable, value):
|
||||
skill.config = {**(skill.config or {}), variable: value}
|
||||
|
||||
@@ -699,7 +699,7 @@ function renderStatus() {
|
||||
const pending = state.status.pending;
|
||||
$("#answer-form").classList.toggle("hidden", !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");
|
||||
p.className = "pending-line";
|
||||
p.textContent = `awaiting input (${pending.run_id || pending.skill}): ${pending.question}`;
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
</form>
|
||||
<form id="answer-form" class="hidden">
|
||||
<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>
|
||||
</form>
|
||||
<div id="answer-feedback" class="hidden"></div>
|
||||
|
||||
@@ -14,6 +14,7 @@ import urllib.request
|
||||
|
||||
import pytest
|
||||
|
||||
from semif_agent.bridges.llm import LLMBridge
|
||||
from semif_agent.bridges.registry import describe_bridges, known_infos
|
||||
from semif_agent.bridges.simplex import SimplexBridge
|
||||
|
||||
@@ -442,6 +443,94 @@ def test_history_lookup_failure_is_reported():
|
||||
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 ----
|
||||
|
||||
def test_known_infos_include_simplex():
|
||||
@@ -454,6 +543,17 @@ def test_known_infos_include_simplex():
|
||||
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():
|
||||
for info in known_infos():
|
||||
docs = dict(info.config_var_docs)
|
||||
|
||||
@@ -318,6 +318,30 @@ def test_answer_roundtrip_via_api(tmp_path):
|
||||
finally:
|
||||
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):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
scheduler.questions.append(
|
||||
|
||||
@@ -173,3 +173,33 @@ def test_resume_can_ask_again(tmp_path):
|
||||
assert status == "ran"
|
||||
assert scheduler.pending 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
|
||||
@@ -1318,6 +1318,77 @@ def test_skill_pre_act_contract_pause_and_resume(tmp_path):
|
||||
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):
|
||||
"""Contract vars are satisfied by global config, category config, skill
|
||||
config, or per-fire answers — in that order of precedence."""
|
||||
|
||||
Reference in new issue
Block a user