Compare commits

...
3 Commits
Author SHA1 Message Date
gabby 8426b85ce0 codegen: share build_codegen_client and fix its integration test
Extract build_codegen_client() from build_scheduler so the codegen client
(provider class plus auth/User-Agent) is constructed in one place, and use it
in test_generate_skill_body_codegen, which previously hardcoded a plain
CodegenClient and 403'd against the Console provider.
2026-10-03 18:07:22 +00:00
gabby e81e6c3a6b seeds: make calendar.create_event the authoritative example
CODEGEN.md now points to seeds/calendar/create_event/ as the worked example,
and the other seeds mirror it: next_event and next_message gain the
configured-default contract var plus create_event's tau -> default ->
weak-winner candidate resolution, and the shared docstring/banner/_now style.
connect_link gets the style alignment only; create_event itself is unchanged.
2026-10-03 18:07:16 +00:00
gabby 63c5fc9903 llm bridge service 2026-10-03 09:05:28 +00:00
28 changed files with 1054 additions and 295 deletions

No files matched your search

+45 -12
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
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,
@@ -578,14 +586,14 @@ CLI, unit tests (24) + integration tests (2).
loads them into every tree at startup; recorded config (credentials collected
at first fire) is written to the runtime store `data/skills/`, so the committed
seed never holds secrets, and a generated body with the same name replaces the
seed. `calendar.next_event` (Nextcloud CalDAV, recurring events expanded
server-side) is the reference read seed and `calendar.create_event` (CalDAV
PUT; derives the title/date/time from the query, asks for missing fields and
resumes, resolves the target calendar against the configured default) is the
reference write seed; `simplex.next_message` (read via the
forwarding bridge) and `simplex.connect_link` (show/create the forwarding
bot's contact link) are the messenger seeds; `tests/test_seed_skills.py` keeps
them honest.
seed. `calendar.create_event` is the authoritative worked example (CalDAV PUT;
derives the title/date/time from the query, asks for missing fields and
resumes, resolves the target calendar with a SemIf choice over the owned
calendars — a strong winner is used, otherwise the configured default);
`calendar.next_event` is the read counterpart (Nextcloud CalDAV, recurring
events expanded server-side); `simplex.next_message` (read via the forwarding
bridge) and `simplex.connect_link` (show/create the forwarding bot's contact
link) are the messenger seeds; `tests/test_seed_skills.py` keeps them honest.
- **Contract provenance.** Each authored body records the CODEGEN.md revision it
was written against. `skill_contract_ref()` (`codegen.py`) returns
`{"ref", "dirty"}`: `ref` is the short git commit sha the contract was read
@@ -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()`.
+12 -6
View File
@@ -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:
@@ -21,6 +21,11 @@ A skill is three things:
talks to and how) and the `CONTRACT` constant (the values the runner must
provide).
The committed seed `seeds/calendar/create_event/` is the **authoritative worked
example** of all three. Read its `manifest.json`, its `skill.py` (which declares
`INTEGRATION` and `CONTRACT`), and its `skill.test.py` alongside this file; a new
body should look and behave like it.
## Manifest schema
Registered in `data/categories.json` (and mirrored in the running tree). Fields:
@@ -59,8 +64,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
@@ -183,6 +186,9 @@ return ActionResult(..., decisions=[(decision, result)])
`ActionResult.decisions` so the choice is logged with the run outcome.
- Include any configured default (a value read from `ctx.config`) as one of the
options, so the request can override the stored default.
- When the winner is weak (its probability is below the skill's confidence
threshold), fall back to the configured default; with no configured default,
keep the weak winner. See how `calendar.create_event` resolves its calendar.
### Producing the result (output)
@@ -304,7 +310,7 @@ Rules:
- **Resolve the recipient/target with a SemIf sub-decision.** When more than one
conversation or target is relevant, resolve which one with a
`ctx.engine.call(...)` sub-decision over the catalog's list endpoint (e.g.
contacts or buffered senders), mirroring how `calendar.next_event` picks a
contacts or buffered senders), mirroring how `calendar.create_event` picks a
calendar. Use the catalog's default config var as the configured option when
the request does not already make it clear.
- **Sending requires user intent.** Send only because the request (or the
@@ -323,8 +329,8 @@ Rules:
- Single purpose, single file, single module.
- Avoid duplicating an existing skill in the same category.
- `act` resolves ambiguity (arguments, recipients, targets) with SemIf
sub-decisions, mirroring how `calendar.next_event` resolves which calendar
to read.
sub-decisions, mirroring how `calendar.create_event` resolves which calendar
to write to.
- `act` performs the concrete real action and writes a human-readable
`action_log` that the SemIf assessment step can judge. Include what the
service actually returned.
+31 -5
View File
@@ -341,8 +341,9 @@ fine-tuning loop — it is not yet the fine-tune itself.
- **Messenger command gateway (SimpleX)** — take commands and reply over DM.
- **Standalone bridge services** — a token-guarded localhost HTTP layer in front
of third-party systems, so generated bodies never speak native protocols.
- **Seeds** — shipped real starter skills: `calendar.next_event` (Nextcloud
CalDAV) and `simplex.next_message` / `simplex.connect_link`.
- **Seeds** — shipped real starter skills: `calendar.create_event` (the
authoritative worked example), `calendar.next_event` (Nextcloud CalDAV), and
`simplex.next_message` / `simplex.connect_link`.
- **Fatal-on-engine-loss** — the engine is always real; its absence exits the app.
- **Stdlib-only core** — SemIf/llama.cpp are lazy imports, so the package stays
importable and testable without the heavy engine installed.
@@ -376,7 +377,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 +497,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 +620,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
@@ -657,11 +676,18 @@ folder format, plus a `manifest.json`. `merge_seed_store` loads them into every
tree at startup; recorded config is written to the runtime store, so the
committed seed never holds secrets.
- `calendar.create_event` — create an event on Nextcloud CalDAV (the
authoritative worked example); resolves the target calendar with a SemIf
choice over the owned calendars (strong winner, else the configured default);
config vars `nextcloud_url`, `nextcloud_username`, `nextcloud_app_password`,
`nextcloud_default_calendar`, plus the LLM bridge (`llm_bridge_url`,
`llm_bridge_token`).
- `calendar.next_event` — next upcoming event from Nextcloud CalDAV (recurring
events expanded server-side); config vars `nextcloud_url`,
`nextcloud_username`, `nextcloud_app_password`.
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`.
- `simplex.next_message` — read the next unread message via the forwarding
bridge.
bridge; config vars `simplex_bridge_url`, `simplex_bridge_token`,
`simplex_default_contact`.
- `simplex.connect_link` — show/create the forwarding bot's contact link.
---
+9
View File
@@ -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": {
+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
(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
+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_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."
}
+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`,
`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(
+158 -26
View File
@@ -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")
+2 -1
View File
@@ -1,5 +1,6 @@
{
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are read.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off."
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar)."
}
+67 -23
View File
@@ -1,15 +1,20 @@
"""Report the next upcoming event on the user's Nextcloud calendar.
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
details come from `ctx.config` (`nextcloud_url`, `nextcloud_username`,
`nextcloud_app_password`). `act` discovers the user's calendars over PROPFIND
and resolves which one the request means with a SemIf sub-decision when there
is more than one, then issues a `calendar-query` REPORT with server-side
recurrence expansion and reports the earliest instance that has not ended yet.
details and the default calendar come from `ctx.config` (`nextcloud_url`,
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`).
Recurring events are expanded by the server (`<c:expand>`), so no RRULE
engine lives here; a server that ignores expansion is reported honestly
rather than guessed at.
`act` discovers the user's calendars over PROPFIND and resolves which one the
request means with a single SemIf choice over every owned calendar (state = the
user query): a strong winner (probability >= `CALENDAR_WINNER_TAU`) is used,
otherwise the configured default calendar is used; with no configured default
the weak winner stands. It then issues a `calendar-query` REPORT with
server-side recurrence expansion and reports the earliest instance that has not
ended yet.
Recurring events are expanded by the server (`<c:expand>`), so no RRULE engine
lives here; a server that ignores expansion is reported honestly rather than
guessed at.
"""
from __future__ import annotations
@@ -33,6 +38,7 @@ INTEGRATION = {
"nextcloud_url",
"nextcloud_username",
"nextcloud_app_password",
"nextcloud_default_calendar",
],
}
@@ -40,12 +46,16 @@ CONTRACT = {
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
"nextcloud_username": "The Nextcloud username whose calendars are read.",
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar).",
}
DAV = "DAV:"
CALDAV = "urn:ietf:params:xml:ns:caldav"
LOOKAHEAD_DAYS = 60
TIMEOUT_SECONDS = 30
# A SemIf probability at or above this counts as a "strong winner" for the
# target calendar; below it the configured default calendar is used instead.
CALENDAR_WINNER_TAU = 0.6
PROPFIND_BODY = (
'<?xml version="1.0" encoding="utf-8"?>'
@@ -66,6 +76,11 @@ class CalDavError(Exception):
"""A real failure talking to the calendar service."""
def _now():
"""Current local time (aware). A test seam; the body never freezes time."""
return datetime.now().astimezone()
# ---- transport ----
@@ -182,6 +197,43 @@ def _calendar_payloads(body):
return payloads
# ---- calendar resolution ----
def _default_calendar(ctx, calendars):
"""The configured default calendar, if it is one of the account's."""
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
for calendar in calendars:
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()):
return calendar
return None
def _resolve_calendar(ctx, request, calendars, decisions):
"""Resolve which calendar the request means, mirroring calendar.create_event.
A strong SemIf winner is used; a weak winner falls back to the configured
default calendar, and with no configured default the weak winner stands.
"""
default = _default_calendar(ctx, calendars)
if len(calendars) == 1:
return calendars[0]["name"]
decision = DecisionRequest(
state=request.text,
question="Which calendar is referred to in the user query?",
options=[Option(c["name"], c["label"]) for c in calendars],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
winner = result.selected
if result.prob(winner) >= CALENDAR_WINNER_TAU:
return winner
if default is not None:
return default["name"]
return winner
# ---- iCalendar parsing ----
@@ -316,28 +368,18 @@ def act(ctx, request):
action_log="calendar.next_event: calendar discovery failed: no calendars found",
new_state=request.text,
)
decisions = []
if len(calendars) == 1:
calendar = calendars[0]["name"]
else:
decision = DecisionRequest(
state=request.text,
question="Which calendar is the intended one?",
options=[
Option(c["name"], c["label"]) for c in calendars
],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
calendar = result.selected
calendar = _resolve_calendar(ctx, request, calendars, decisions)
if not calendar:
return ActionResult(
action_log="calendar.next_event aborted: no calendar resolved.",
new_state=request.text,
decisions=decisions,
)
local_tz = datetime.now().astimezone().tzinfo or timezone.utc
now = datetime.now(local_tz)
now = _now()
local_tz = now.tzinfo or timezone.utc
window_start = now - timedelta(days=1)
window_end = now + timedelta(days=LOOKAHEAD_DAYS)
try:
@@ -355,6 +397,7 @@ def act(ctx, request):
new_state=request.text,
decisions=decisions,
)
next_event = _pick_next(events, now)
if next_event is None:
message = (
@@ -362,6 +405,7 @@ def act(ctx, request):
f"{window_end.strftime('%Y-%m-%d')}."
)
return ActionResult(action_log=message, new_state=message, decisions=decisions)
summary = next_event.get("summary") or "(no title)"
when = _format_when(next_event)
message = f"Next event on {calendar!r}: {summary} — {when}"
+53 -6
View File
@@ -3,9 +3,10 @@
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the Nextcloud CalDAV endpoint. This proves the body builds
real CalDAV requests, discovers calendars, resolves the calendar through a
SemIf sub-decision, parses expanded iCalendar events, and fails honestly when
the service errors. It does NOT prove the live integration — only a real run
against the user's Nextcloud does.
SemIf sub-decision (a strong winner is used, otherwise the configured default,
otherwise the weak winner), parses expanded iCalendar events, and fails honestly
when the service errors. It does NOT prove the live integration — only a real
run against the user's Nextcloud does.
"""
import base64
@@ -49,15 +50,24 @@ def build_ics():
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
@@ -137,11 +147,12 @@ def start_server(**overrides):
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
def fixture_config(url):
def fixture_config(url, default="personal"):
return {
"nextcloud_url": url,
"nextcloud_username": "testuser",
"nextcloud_app_password": "app-pw",
"nextcloud_default_calendar": default,
}
@@ -149,6 +160,7 @@ def main():
global ICS
ICS = build_ics()
# A strong winner is used even though a default is configured.
server, handler, url = start_server()
try:
engine = FakeEngine(pick="work")
@@ -157,6 +169,10 @@ def main():
action = skill.act(ctx, request)
assert len(action.decisions) == 1, "act must log the calendar choice"
assert len(engine.decisions) == 1
assert [option.id for option in engine.decisions[0].options] == [
"personal",
"work",
], engine.decisions[0].options
assert "Team sync" in action.action_log, action.action_log
assert action.new_state, "act must set a new state"
@@ -174,6 +190,36 @@ def main():
server.shutdown()
server.server_close()
# A weak winner falls back to the configured default calendar.
server, handler, url = start_server()
try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default="personal"))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/", handler.requests[1]["path"]
assert "Team sync" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A weak winner with no configured default stands.
server, handler, url = start_server()
try:
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
ctx = ActionContext(engine=engine, config=fixture_config(url, default=""))
request = Request("what is the next event on my calendar?")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/work/", handler.requests[1]["path"]
print(action.action_log)
finally:
server.shutdown()
server.server_close()
# A single calendar needs no SemIf decision.
server, handler, url = start_server(calendar_count=1)
try:
engine = FakeEngine()
@@ -188,6 +234,7 @@ def main():
server.shutdown()
server.server_close()
# A failing REPORT is reported honestly.
server, handler, url = start_server(report_status=500)
try:
engine = FakeEngine(pick="personal")
+13 -7
View File
@@ -1,14 +1,14 @@
"""Show the SimpleX contact link others use to connect to this agent.
Real integration: the standalone SimpleX forwarding bridge
(`simplex_bridge_url`). The bridge's own connection to the `simplex-chat`
daemon is the only thing that can read (or create) the forwarding bot's *user
contact address*; this body asks the bridge for it and reports the link
honestly. It never opens a WebSocket to the daemon and never invents a link: if
the bridge is not running or has no address, it says so.
(`simplex_bridge_url`, `simplex_bridge_token`). The bridge's own connection to
the `simplex-chat` daemon is the only thing that can read (or create) the
forwarding bot's *user contact address*; this body asks the bridge for it and
reports the link honestly. It never opens a WebSocket to the daemon and never
invents a link: if the bridge is not running or has no address, it says so.
`GET /address` shows the existing link and creates one on first call, returning
`{short_link, full_link, created}`.
`act` health-checks the bridge, then `GET /address` shows the existing link and
creates one on first call, returning `{short_link, full_link, created}`.
"""
from __future__ import annotations
@@ -37,6 +37,9 @@ class BridgeError(Exception):
"""The SimpleX forwarding bridge is unreachable or returned an error."""
# ---- transport ----
def _base(ctx):
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
if not url:
@@ -63,6 +66,9 @@ def _get(ctx, path):
raise BridgeError(f"GET {path}: {exc}") from exc
# ---- skill phases ----
def act(ctx, request):
try:
payload = _get(ctx, "/health")
+2 -1
View File
@@ -1,4 +1,5 @@
{
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_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."
"simplex_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.",
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate."
}
+53 -20
View File
@@ -3,9 +3,11 @@
Real integration: the standalone SimpleX forwarding bridge
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends.
`act` peeks that inbox, finds which conversations have unread messages, and
resolves which one to read with a SemIf sub-decision when more than one does
(honoring a configured default contact); it then pops and reports the oldest
unread message for that conversation.
resolves which one to read with a SemIf choice over them (state = the user
query): a strong winner (probability >= `CONTACT_WINNER_TAU`) is used, otherwise
the configured default contact is used; with no configured default (or a default
with no unread message) the weak winner stands. It then pops and reports the
oldest unread message for that conversation.
The bridge owns the read cursor, so this skill keeps no state of its own. It
never opens a WebSocket to the `simplex-chat` daemon — the bridge is the only
@@ -25,22 +27,32 @@ from semif_agent.skills import ActionResult
INTEGRATION = {
"service": "simplex",
"transport": "http",
"config_vars": ["simplex_bridge_url", "simplex_bridge_token"],
"config_vars": [
"simplex_bridge_url",
"simplex_bridge_token",
"simplex_default_contact",
],
}
CONTRACT = {
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
"simplex_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.",
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate.",
}
TIMEOUT_SECONDS = 20
# A SemIf probability at or above this counts as a "strong winner" for the
# conversation; below it the configured default contact is used instead.
CONTACT_WINNER_TAU = 0.6
class BridgeError(Exception):
"""The SimpleX forwarding bridge is unreachable or returned an error."""
# ---- transport ----
def _base(ctx):
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
if not url:
@@ -67,6 +79,9 @@ def _get(ctx, path):
raise BridgeError(f"GET {path}: {exc}") from exc
# ---- conversation resolution ----
def _senders(messages):
"""Distinct conversations with buffered messages, in arrival order."""
senders = []
@@ -82,16 +97,45 @@ def _senders(messages):
return senders
def _match_default(senders, default):
default = str(default or "").strip()
def _default_sender(ctx, senders):
"""The configured default contact, if it has unread messages."""
default = str(ctx.config.get("simplex_default_contact", "") or "").strip()
if not default:
return None
for sender in senders:
if sender["id"] == default or sender["display_name"] == default:
return sender["id"]
return sender
return None
def _resolve_contact(ctx, request, senders, decisions):
"""Resolve which conversation to read, mirroring calendar.create_event.
A strong SemIf winner is used; a weak winner falls back to the configured
default contact, and with no configured default the weak winner stands.
"""
default = _default_sender(ctx, senders)
if len(senders) == 1:
return senders[0]["id"]
decision = DecisionRequest(
state=request.text,
question="Which conversation should I read the next SimpleX message from?",
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
winner = result.selected
if result.prob(winner) >= CONTACT_WINNER_TAU:
return winner
if default is not None:
return default["id"]
return winner
# ---- skill phases ----
def act(ctx, request):
try:
payload = _get(ctx, "/inbox")
@@ -104,18 +148,7 @@ def act(ctx, request):
new_state="no unread SimpleX messages",
)
decisions = []
contact = _match_default(senders, ctx.config.get("simplex_default_contact", ""))
if contact is None and len(senders) > 1:
decision = DecisionRequest(
state=request.text,
question="Which conversation should I read the next SimpleX message from?",
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
)
result = ctx.engine.call(decision)
decisions.append((decision, result))
contact = result.selected
if contact is None:
contact = senders[0]["id"]
contact = _resolve_contact(ctx, request, senders, decisions)
try:
payload = _get(
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
+65 -11
View File
@@ -2,10 +2,11 @@
Run from this folder: `python skill.test.py`. No external network: a loopback
http.server plays the standalone SimpleX forwarding bridge. This proves the body
peeks the inbox, resolves the conversation through a SemIf sub-decision (or a
configured default), pops the real `next` message, and fails honestly when the
bridge is unreachable. It does NOT prove the live integration — only a real run
against the bridge and a real contact does.
peeks the inbox, resolves the conversation through a SemIf sub-decision (a
strong winner is used, otherwise the configured default, otherwise the weak
winner), pops the real `next` message, and fails honestly when the bridge is
unreachable. It does NOT prove the live integration — only a real run against
the bridge and a real contact does.
"""
import json
@@ -21,15 +22,24 @@ import skill
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
@@ -129,7 +139,7 @@ def test_multiple_senders_uses_semif_decision():
server.server_close()
def test_default_contact_skips_decision():
def test_strong_winner_overrides_default_contact():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
@@ -137,13 +147,55 @@ def test_default_contact_skips_decision():
]
)
try:
engine = FakeEngine()
engine = FakeEngine(probs={"4": 0.1, "7": 0.9})
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message from Bob")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1, "the conversation is chosen with one SemIf decision"
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_falls_back_to_default_contact():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
# Bob edges out Alice but stays below the strong-winner threshold, so the
# configured default ("Alice") is used instead.
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert engine.decisions == [], "a configured default needs no SemIf decision"
assert "Alice" in action.action_log, action.action_log
assert len(engine.decisions) == 1
assert handler.requests[1] == "/inbox/next?contact=4", handler.requests
assert "hello there" in action.action_log, action.action_log
print(action.action_log)
finally:
server.shutdown()
server.server_close()
def test_weak_winner_without_default_stands():
server, handler, url = start_server(
[
message("m1", "4", "Alice", "hello there"),
message("m2", "7", "Bob", "shipment arrived"),
]
)
try:
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
ctx = ActionContext(engine=engine, config=config(url))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert len(engine.decisions) == 1
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
print(action.action_log)
finally:
server.shutdown()
@@ -207,7 +259,9 @@ def test_auth_token_is_sent_when_configured():
def main():
test_multiple_senders_uses_semif_decision()
test_default_contact_skips_decision()
test_strong_winner_overrides_default_contact()
test_weak_winner_falls_back_to_default_contact()
test_weak_winner_without_default_stands()
test_single_sender_needs_no_decision()
test_empty_inbox_is_reported_honestly()
test_unreachable_bridge_fails_honestly()
+6 -5
View File
@@ -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:
+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
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}")
+50 -36
View File
@@ -177,6 +177,50 @@ def build_engine_config(config: dict, pins: dict | None = None) -> EngineConfig:
)
def build_codegen_client(config: dict) -> CodegenClient:
"""Build the codegen client from the `codegen` config block.
`provider` selects the class (`opencode` -> the Console client, which adds
bearer auth and a User-Agent) and the endpoint/auth come from
`_provider_endpoint`. Shared by `build_scheduler` and the integration tests
so both exercise the configured provider rather than assuming ollama.
"""
codegen_cfg = config.get("codegen", {}) or {}
deg_cfg = codegen_cfg.get("degeneration", {}) or {}
provider = str(codegen_cfg.get("provider", "ollama") or "ollama").lower()
client_cls = ConsoleCodegenClient if provider == "opencode" else CodegenClient
endpoint = _provider_endpoint(
codegen_cfg,
config.get("llm", {}).get("base_url", "http://localhost:11434/v1"),
)
return client_cls(
base_url=endpoint["base_url"],
model=_required_model(codegen_cfg, "codegen"),
timeout=float(codegen_cfg.get("timeout", 1200.0)),
stream=bool(codegen_cfg.get("stream", False)),
idle_warn=float(codegen_cfg.get("idle_warn", 60.0)),
idle_timeout=float(codegen_cfg.get("idle_timeout", 180.0)),
context_window=float(codegen_cfg.get("context_window", 0.0)),
smart_limit=int(codegen_cfg.get("smart_limit", 250000)),
warn_limit=int(codegen_cfg.get("warn_limit", 500000)),
max_fill_ratio=float(codegen_cfg.get("max_fill_ratio", 0.9)),
warn_fill_ratio=float(codegen_cfg.get("warn_fill_ratio", 0.7)),
max_output=float(codegen_cfg.get("max_output", 0.85)),
chars_per_token=float(codegen_cfg.get("chars_per_token", 4.0)),
degeneration_interval=int(deg_cfg.get("interval", 8000)),
degeneration_window=int(deg_cfg.get("window", 2000)),
degeneration_min_chars=int(deg_cfg.get("min_chars", 4000)),
temperature=_opt_float(codegen_cfg.get("temperature")),
top_p=_opt_float(codegen_cfg.get("top_p")),
presence_penalty=_opt_float(codegen_cfg.get("presence_penalty")),
frequency_penalty=_opt_float(codegen_cfg.get("frequency_penalty")),
max_attempts=int(codegen_cfg.get("max_attempts", 3)),
api_key=endpoint["api_key"],
extra_headers=endpoint["extra_headers"],
user_agent=endpoint["user_agent"],
)
def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
engine = SemIfEngine(build_engine_config(config))
llm_cfg = config.get("llm", {}) or {}
@@ -204,40 +248,7 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
trace = TraceLog(config.get("trace", "data/runs.jsonl"))
codegen_cfg = config.get("codegen", {})
deg_cfg = codegen_cfg.get("degeneration", {}) or {}
codegen_provider = str(codegen_cfg.get("provider", "ollama") or "ollama").lower()
codegen_cls = (
ConsoleCodegenClient if codegen_provider == "opencode" else CodegenClient
)
codegen_endpoint = _provider_endpoint(
codegen_cfg,
config.get("llm", {}).get("base_url", "http://localhost:11434/v1"),
)
codegen = codegen_cls(
base_url=codegen_endpoint["base_url"],
model=_required_model(codegen_cfg, "codegen"),
timeout=float(codegen_cfg.get("timeout", 1200.0)),
stream=bool(codegen_cfg.get("stream", False)),
idle_warn=float(codegen_cfg.get("idle_warn", 60.0)),
idle_timeout=float(codegen_cfg.get("idle_timeout", 180.0)),
context_window=float(codegen_cfg.get("context_window", 0.0)),
smart_limit=int(codegen_cfg.get("smart_limit", 250000)),
warn_limit=int(codegen_cfg.get("warn_limit", 500000)),
max_fill_ratio=float(codegen_cfg.get("max_fill_ratio", 0.9)),
warn_fill_ratio=float(codegen_cfg.get("warn_fill_ratio", 0.7)),
max_output=float(codegen_cfg.get("max_output", 0.85)),
chars_per_token=float(codegen_cfg.get("chars_per_token", 4.0)),
degeneration_interval=int(deg_cfg.get("interval", 8000)),
degeneration_window=int(deg_cfg.get("window", 2000)),
degeneration_min_chars=int(deg_cfg.get("min_chars", 4000)),
temperature=_opt_float(codegen_cfg.get("temperature")),
top_p=_opt_float(codegen_cfg.get("top_p")),
presence_penalty=_opt_float(codegen_cfg.get("presence_penalty")),
frequency_penalty=_opt_float(codegen_cfg.get("frequency_penalty")),
max_attempts=int(codegen_cfg.get("max_attempts", 3)),
api_key=codegen_endpoint["api_key"],
extra_headers=codegen_endpoint["extra_headers"],
user_agent=codegen_endpoint["user_agent"],
)
codegen = build_codegen_client(config)
def make_degeneration_check(run_id: str):
"""2-option SemIf decision (continue/stop) that aborts a degenerating
@@ -486,7 +497,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 +641,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:
+10 -2
View File
@@ -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
View File
@@ -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}
+1 -1
View File
@@ -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}`;
+1 -1
View File
@@ -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>
+6 -13
View File
@@ -13,8 +13,7 @@ import time
import pytest
from semif_agent.cli import (
_opt_float,
_required_model,
build_codegen_client,
build_engine_config,
build_scheduler,
load_config,
@@ -297,17 +296,11 @@ def test_generate_skill_body_codegen(tmp_path):
"""
config = load_config()
require_real(config)
codegen_cfg = config.get("codegen", {})
client = CodegenClient(
base_url=codegen_cfg.get("base_url", "http://localhost:11434/v1"),
model=_required_model(codegen_cfg, "codegen"),
timeout=float(codegen_cfg.get("timeout", 1200.0)),
stream=True,
temperature=_opt_float(codegen_cfg.get("temperature")),
top_p=_opt_float(codegen_cfg.get("top_p")),
presence_penalty=_opt_float(codegen_cfg.get("presence_penalty")),
frequency_penalty=_opt_float(codegen_cfg.get("frequency_penalty")),
)
# Build the client exactly as build_scheduler does, so the test exercises the
# configured provider (e.g. the hosted Console, which needs auth + a
# User-Agent) rather than assuming an unauthenticated ollama endpoint.
config["codegen"] = {**(config.get("codegen") or {}), "stream": True}
client = build_codegen_client(config)
tree = build_tree(build_skills({"skills": {}}))
draft = SkillDraft(
name="check_service",
+100
View File
@@ -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)
+24
View File
@@ -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(
+30
View File
@@ -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
+71
View File
@@ -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."""