Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1ea9f0c2c | ||
|
|
b8f86849ea |
No files matched your search
@@ -262,7 +262,7 @@ bridges/ standalone third-party API bridges (SimpleX, the LLM bridge,
|
||||
and Notes (OCS) behind one JSON surface, so bodies never speak
|
||||
DAV/OCS; no service daemon (stdlib-only), connection from
|
||||
`bridges.nextcloud` with a fallback to the top-level
|
||||
`nextcloud_*` values the calendar seeds use.
|
||||
`nextcloud_*` values the nextcloud seeds use.
|
||||
outlook.py + outlook_client.py: OutlookBridge — the user's
|
||||
Microsoft account (Outlook / Microsoft 365) over Microsoft Graph:
|
||||
mail, calendar events, Microsoft To Do tasks, contacts, and
|
||||
@@ -383,7 +383,7 @@ CLI, unit tests (24) + integration tests (2).
|
||||
model sent "book a flight to japan" to `simplex` (0.49 vs create_category
|
||||
0.12); with descriptions it picks `create_category` 0.87. `Skill` carries
|
||||
`category_description`, seeded by `CATEGORY_DESCRIPTIONS` for the built-ins
|
||||
(response/calendar/simplex) and read from the registry for authored
|
||||
(response/nextcloud/simplex) and read from the registry for authored
|
||||
categories; `category_descriptions(tree)` collapses it per category so an
|
||||
empty bucket is never offered bare. The old category threshold gate
|
||||
(`create_tau`/`create_margin`) is **retired**. Leaf level: the softmax
|
||||
@@ -460,13 +460,13 @@ CLI, unit tests (24) + integration tests (2).
|
||||
path with `reason_kind="manual"`), and `cancel_build` (confirm, then discard a
|
||||
queued/in-flight write and delete the half-built leaf). The target skill is an
|
||||
**input variable**: the skill resolves it from the request if named
|
||||
("delete skill calendar.foo") and otherwise **asks** for it ("delete skill" →
|
||||
("delete skill nextcloud.foo") and otherwise **asks** for it ("delete skill" →
|
||||
"Which skill?"), so the routed request never has to carry a task-like skill
|
||||
name. Explicit command forms ("delete skill", "clear config variables for X",
|
||||
"regen skill X", "cancel skill build") are recognized deterministically by
|
||||
`parse_meta_command` and routed straight to the housekeeping leaf (trace
|
||||
`meta_command`): the pinned 4B decision model reads a task-like name
|
||||
(`calendar.create_event`) as the task itself and misroutes the generic guards,
|
||||
(`nextcloud.create_event`) as the task itself and misroutes the generic guards,
|
||||
so the explicit command is deterministic while natural-language phrasings
|
||||
still go through navigation (the actionability guard's `action` option now
|
||||
names skill-management commands). They are built-ins
|
||||
@@ -860,23 +860,24 @@ 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.create_event` is the authoritative worked example (CalDAV PUT;
|
||||
seed. `nextcloud.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); `productivity_management.create_nextcloud_task`
|
||||
`nextcloud.next_event` is the read counterpart (Nextcloud CalDAV, recurring
|
||||
events expanded server-side); `nextcloud.create_task`
|
||||
adds a task to a Nextcloud task list through the Nextcloud bridge (`GET
|
||||
/tasklists` for a VTODO-capable target, `POST /tasks` to create it, the LLM
|
||||
bridge to phrase the summary/description); `simplex.next_message` (read via the
|
||||
forwarding bridge) and `simplex.connect_link` (show/create the forwarding bot's
|
||||
contact link) are the messenger seeds; `time.now`, `time.date`, `time.set_timer`, and
|
||||
forwarding bridge), `simplex.send_message` (send to a contact resolved over the
|
||||
bridge's contact list), and `simplex.connect_link` (show/create the forwarding
|
||||
bot's contact link) are the messenger seeds; `time.now`, `time.date`, `time.set_timer`, and
|
||||
`time.set_alarm` are the local time utilities (`compute` transport, empty
|
||||
contract) — they read the host clock and schedule on `ctx.timers`. Local time
|
||||
is the top-level `timezone` config value (an IANA name such as
|
||||
`America/Chicago`; `timers.local_now`/`resolve_timezone` resolve it via
|
||||
`zoneinfo`), falling back to the host's own timezone when it is empty or
|
||||
unknown; `TimerService` formats due/fired times in that zone too. The calendar
|
||||
unknown; `TimerService` formats due/fired times in that zone too. The nextcloud
|
||||
seeds derive "now" the same way, so a request time is parsed in the user's
|
||||
zone rather than the host's;
|
||||
`tests/test_seed_skills.py` keeps them honest.
|
||||
@@ -1248,7 +1249,8 @@ CLI, unit tests (24) + integration tests (2).
|
||||
resolution, outbound routing, token/body validation, `/address` success/503/502,
|
||||
daemon close on stop, catalog/`describe_bridges()`).
|
||||
`tests/test_seed_skills.py` hermetically tests every
|
||||
`seeds/<category>/<name>/` package, including `simplex.next_message` and
|
||||
`seeds/<category>/<name>/` package, including `simplex.next_message`,
|
||||
`simplex.send_message`, and
|
||||
`simplex.connect_link`. `tests/test_voice_gateway.py` drives the voice loop
|
||||
with injected fake engines (wake gating, endpointing, half-duplex,
|
||||
follow-up window, `speak` truncation/failure, adapter + CLI wiring) — no
|
||||
@@ -1319,7 +1321,8 @@ CLI, unit tests (24) + integration tests (2).
|
||||
keep in sync and the data-contract config search finds it and auto-populates the
|
||||
skill config. 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.
|
||||
`simplex.next_message`, `simplex.send_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
|
||||
@@ -1332,7 +1335,7 @@ CLI, unit tests (24) + integration tests (2).
|
||||
(`enabled`/`host`/`port`/`token`). Bodies reach it via the derived
|
||||
`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
|
||||
client it reports `502`, never a fabricated reply. `nextcloud.create_event` is
|
||||
the first consumer (title + description extraction, cached in `request.meta`
|
||||
across a `needs_input` resume).
|
||||
- **Nextcloud bridge** (`bridges/nextcloud.py` + `bridges/nextcloud_client.py`).
|
||||
@@ -1347,7 +1350,7 @@ CLI, unit tests (24) + integration tests (2).
|
||||
and `verify_tls`/`timeout`); `build_bridge` passes the top-level
|
||||
`nextcloud_url`/`nextcloud_username`/`nextcloud_app_password`/
|
||||
`nextcloud_default_calendar`/`nextcloud_default_addressbook` as a fallback, so
|
||||
the same account the calendar seeds collect is configured once and a block value
|
||||
the same account the nextcloud seeds collect is configured once and a block value
|
||||
wins. Bodies reach it via the derived `nextcloud_bridge_url` (+ optional
|
||||
`nextcloud_bridge_token`); the `BridgeInfo` declares only those two config vars.
|
||||
Routes (reads `GET`, mutations `POST`): files (`/files`, `/files/stat`,
|
||||
@@ -1399,8 +1402,9 @@ CLI, unit tests (24) + integration tests (2).
|
||||
|
||||
## Bridge backlog (one session per item)
|
||||
|
||||
The bridge read path (`simplex.next_message`) and contact-link lookup
|
||||
(`simplex.connect_link`) are covered. Deferred follow-ups:
|
||||
The bridge read path (`simplex.next_message`), outbound send
|
||||
(`simplex.send_message`), and contact-link lookup (`simplex.connect_link`) are
|
||||
covered. Deferred follow-ups:
|
||||
|
||||
- [x] **1. Contact-list refresh from the daemon** (`bridges/simplex.py`,
|
||||
`simplex_ws.py`). Shipped: `SimplexDaemon.contacts()` /
|
||||
@@ -1424,15 +1428,17 @@ The bridge read path (`simplex.next_message`) and contact-link lookup
|
||||
`/address` (503 not connected / 502 lookup failure; `/history` 400 without a
|
||||
contact). The live `/inbox` buffer is unchanged. Note: v7 has **no mark-read
|
||||
command**, so acking is via read receipts, not an API call.
|
||||
- [ ] **3. `simplex.send_message` seed** (`seeds/simplex/send_message/`). The
|
||||
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.
|
||||
- [x] **3. `simplex.send_message` seed** (`seeds/simplex/send_message/`). The
|
||||
outbound counterpart to `simplex.next_message`: resolves the recipient with a
|
||||
SemIf sub-decision over the bridge's `/contacts` (falling back to the
|
||||
configured default contact), writes the message from the request or the LLM
|
||||
bridge when no literal text is given, sends via `POST /send`, and reports the
|
||||
bridge's `contact_id` / errors honestly.
|
||||
- [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` (its URL is derived from that block).
|
||||
`calendar.create_event` extracts its title + description through it.
|
||||
`nextcloud.create_event` extracts its title + description through it.
|
||||
- [x] **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()`. Nextcloud shipped (`bridges/nextcloud.py` +
|
||||
|
||||
+7
-7
@@ -21,7 +21,7 @@ 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
|
||||
The committed seed `seeds/nextcloud/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.
|
||||
@@ -162,12 +162,12 @@ Rules:
|
||||
real candidate set (fetched from the service), include any configured default as
|
||||
one of the options, and threshold the winner: use it when its probability clears
|
||||
the skill's confidence threshold, otherwise fall back to the configured default
|
||||
(see `calendar.create_event` and `simplex.next_message`).
|
||||
(see `nextcloud.create_event` and `simplex.next_message`).
|
||||
- **Use the LLM bridge for text, not for routing or assessment.** Generated text
|
||||
goes through the LLM bridge — a generic `POST /chat` whose base URL, token,
|
||||
and endpoint shapes are in the bridge catalog injected below — never by
|
||||
speaking a model's protocol directly. Keep the model extractive and bounded
|
||||
(see how `calendar.create_event` asks only for a title and description), and
|
||||
(see how `nextcloud.create_event` asks only for a title and description), and
|
||||
report a real failure when the bridge is down rather than guessing the text.
|
||||
- **Never blur the boundaries.** SemIf never generates; an LLM never routes,
|
||||
selects, or assesses; deterministic code never invents a value it cannot
|
||||
@@ -422,7 +422,7 @@ return ActionResult(..., decisions=[(decision, result)])
|
||||
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.
|
||||
keep the weak winner. See how `nextcloud.create_event` resolves its calendar.
|
||||
|
||||
### Producing the result (output)
|
||||
|
||||
@@ -515,7 +515,7 @@ Rules:
|
||||
for. `request.meta` is a scratch dict carried on the same request across the
|
||||
pause, so a body can cache a computed value or an already-collected answer
|
||||
there and reuse it on the resume pass instead of recomputing or re-asking —
|
||||
see how `calendar.create_event` caches the extracted title/description and the
|
||||
see how `nextcloud.create_event` caches the extracted title/description and the
|
||||
answers it collected.
|
||||
- **Fail fast on budget.** Keep the work small; do not loop or retry in code.
|
||||
- **The function is `act` exactly.** The module is imported under its registered
|
||||
@@ -557,7 +557,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.create_event` picks a
|
||||
contacts or buffered senders), mirroring how `nextcloud.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
|
||||
@@ -576,7 +576,7 @@ 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.create_event` resolves which calendar
|
||||
sub-decisions, mirroring how `nextcloud.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
|
||||
|
||||
@@ -343,9 +343,10 @@ fine-tuning loop — it is not yet the fine-tune itself.
|
||||
text-to-speech, all local (openWakeWord / faster-whisper / Piper).
|
||||
- **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.create_event` (the
|
||||
authoritative worked example), `calendar.next_event` (Nextcloud CalDAV), and
|
||||
`simplex.next_message` / `simplex.connect_link`.
|
||||
- **Seeds** — shipped real starter skills: `nextcloud.create_event` (the
|
||||
authoritative worked example), `nextcloud.next_event` (Nextcloud CalDAV),
|
||||
`nextcloud.create_task` (Nextcloud task list), and
|
||||
`simplex.next_message` / `simplex.send_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.
|
||||
@@ -385,7 +386,7 @@ semif_agent/
|
||||
speech-to-text (faster-whisper), text-to-speech (Piper)
|
||||
gateway/ messenger COMMAND intake/reply (SimpleX, LXMF, voice)
|
||||
bridges/ standalone third-party API bridges (SimpleX, LLM, Nextcloud)
|
||||
seeds/ committed starter skills (calendar, simplex)
|
||||
seeds/ committed starter skills (nextcloud, simplex)
|
||||
scripts/ bootstrap.sh, simplex-address.py, systemd/*.in
|
||||
requirements/ staging.txt — the pinned engine deps
|
||||
tests/ stdlib unit tests + tests/integration (real engine + LLM)
|
||||
@@ -745,7 +746,7 @@ plain HTTPS) and is stdlib-only (`urllib` + `xml.etree`), so it starts instantly
|
||||
in the same `semif-bridge` process. The connection (base URL, username, app
|
||||
password) is configured in `bridges.nextcloud` and falls back to the top-level
|
||||
`nextcloud_url` / `nextcloud_username` / `nextcloud_app_password` /
|
||||
`nextcloud_default_calendar` the calendar seeds use, so the account is
|
||||
`nextcloud_default_calendar` the nextcloud seeds use, so the account is
|
||||
configured once. Skills call it at the address derived from `bridges.nextcloud`
|
||||
(`nextcloud_bridge_url`, + optional `nextcloud_bridge_token`). Its HTTP surface:
|
||||
|
||||
@@ -856,18 +857,27 @@ 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
|
||||
- `nextcloud.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
|
||||
- `nextcloud.next_event` — next upcoming event from Nextcloud CalDAV (recurring
|
||||
events expanded server-side); config vars `nextcloud_url`,
|
||||
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`.
|
||||
- `nextcloud.create_task` — add a task to a Nextcloud task list through the
|
||||
Nextcloud bridge (`GET /tasklists`, `POST /tasks`); config vars
|
||||
`nextcloud_bridge_url`, `nextcloud_bridge_token`, `llm_bridge_url`,
|
||||
`llm_bridge_token`.
|
||||
- `simplex.next_message` — read the next unread message via the forwarding
|
||||
bridge; config vars `simplex_bridge_url`, `simplex_bridge_token`,
|
||||
`simplex_default_contact`.
|
||||
- `simplex.send_message` — send a message to a contact resolved over the
|
||||
bridge's contact list (a SemIf choice, defaulting to the configured contact);
|
||||
config vars `simplex_bridge_url`, `simplex_bridge_token`,
|
||||
`simplex_default_contact`, plus the LLM bridge (`llm_bridge_url`,
|
||||
`llm_bridge_token`) to write the text when the request states none.
|
||||
- `simplex.connect_link` — show/create the forwarding bot's contact link.
|
||||
|
||||
---
|
||||
|
||||
+1
-1
@@ -149,7 +149,7 @@
|
||||
"token": ""
|
||||
},
|
||||
"nextcloud": {
|
||||
"_comment": "Nextcloud bridge: files (WebDAV), calendar events and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app) over one uniform local JSON API, so skill bodies never speak the native DAV/OCS protocols. It has no service daemon (Nextcloud is plain HTTPS) and runs inside the same `semif-bridge` process as the other enabled bridges. The connection is configured HERE (url/username/app_password); when a value is blank the bridge falls back to the top-level nextcloud_url/nextcloud_username/nextcloud_app_password/nextcloud_default_calendar the calendar seeds already use, so the account is configured once. `app_password` is a Nextcloud app password (Settings > Security > Devices & sessions), not the account password. `default_calendar`/`default_task_calendar`/`default_addressbook` are used when a request names none and the account has several; task operations only ever target a VTODO-capable task list (GET /tasklists), never an event-only calendar. `verify_tls` false skips certificate verification (self-signed hosts). Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
|
||||
"_comment": "Nextcloud bridge: files (WebDAV), calendar events and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app) over one uniform local JSON API, so skill bodies never speak the native DAV/OCS protocols. It has no service daemon (Nextcloud is plain HTTPS) and runs inside the same `semif-bridge` process as the other enabled bridges. The connection is configured HERE (url/username/app_password); when a value is blank the bridge falls back to the top-level nextcloud_url/nextcloud_username/nextcloud_app_password/nextcloud_default_calendar the nextcloud seeds already use, so the account is configured once. `app_password` is a Nextcloud app password (Settings > Security > Devices & sessions), not the account password. `default_calendar`/`default_task_calendar`/`default_addressbook` are used when a request names none and the account has several; task operations only ever target a VTODO-capable task list (GET /tasklists), never an event-only calendar. `verify_tls` false skips certificate verification (self-signed hosts). Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.",
|
||||
"enabled": true,
|
||||
"host": "127.0.0.1",
|
||||
"port": 5230,
|
||||
|
||||
@@ -629,7 +629,7 @@ Nextcloud bridge (files/calendar/tasks/contacts/notes for skills):
|
||||
- Runs inside the same 'semif-bridge' process (Nextcloud is plain HTTPS, so
|
||||
there is no separate daemon). Configure the account once in config.json under
|
||||
bridges.nextcloud (url/username/app_password) — or reuse the top-level
|
||||
nextcloud_* values the calendar seeds collect. Skills call it at the address
|
||||
nextcloud_* values the nextcloud seeds collect. Skills call it at the address
|
||||
derived from bridges.nextcloud (default http://127.0.0.1:5230).
|
||||
EOF
|
||||
|
||||
|
||||
@@ -58,11 +58,11 @@ LEAF_EVAL: list[tuple[str, str]] = [
|
||||
("check my next message on simplex", "simplex.next_message"),
|
||||
("read the next simplex message", "simplex.next_message"),
|
||||
("show me my simplex messages", "simplex.next_message"),
|
||||
('send a message on simplex to pepper: "hey!"', "simplex.send_simplex_message"),
|
||||
("send a simplex message to pepper saying hi", "simplex.send_simplex_message"),
|
||||
('send a message on simplex to pepper: "hey!"', "simplex.send_message"),
|
||||
("send a simplex message to pepper saying hi", "simplex.send_message"),
|
||||
("what is my simplex connection link?", "simplex.connect_link"),
|
||||
("give me my simplex contact link", "simplex.connect_link"),
|
||||
("tell me the next event in my nextcloud calendar", "calendar.next_event"),
|
||||
("tell me the next event in my nextcloud calendar", "nextcloud.next_event"),
|
||||
("translate my last simplex message to French", "create"),
|
||||
("delete my next simplex message", "create"),
|
||||
("book a flight to japan", "create"),
|
||||
@@ -73,7 +73,7 @@ CATEGORY_EVAL: list[tuple[str, str]] = [
|
||||
("what is my next message on simplex?", "simplex"),
|
||||
("send a simplex message to pepper saying hi", "simplex"),
|
||||
("what is my simplex connection link?", "simplex"),
|
||||
("tell me the next event in my nextcloud calendar", "calendar"),
|
||||
("tell me the next event in my nextcloud calendar", "nextcloud"),
|
||||
("hello there", "response"),
|
||||
("thanks!", "response"),
|
||||
("what", "response"),
|
||||
|
||||
File renamed without changes.
File renamed without changes.
@@ -481,7 +481,7 @@ def _build_ics(uid, summary, start, end, all_day, stamp, description=""):
|
||||
lines = [
|
||||
"BEGIN:VCALENDAR",
|
||||
"VERSION:2.0",
|
||||
"PRODID:-//semif-agent//calendar.create_event//EN",
|
||||
"PRODID:-//semif-agent//nextcloud.create_event//EN",
|
||||
"CALSCALE:GREGORIAN",
|
||||
"BEGIN:VEVENT",
|
||||
f"UID:{uid}",
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
"""Hermetic mechanics test for calendar.create_event.
|
||||
"""Hermetic mechanics test for nextcloud.create_event.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays a Nextcloud CalDAV endpoint (PROPFIND discovery + PUT create)
|
||||
@@ -422,7 +422,7 @@ def test_unreachable_server_fails_honestly():
|
||||
action, request, _engine = run(
|
||||
None, "http://127.0.0.1:1", "add standup on 2026-11-10 at 9am"
|
||||
)
|
||||
assert action.action_log and "calendar.create_event" not in action.action_log, action.action_log
|
||||
assert action.action_log and "nextcloud.create_event" not in action.action_log, action.action_log
|
||||
assert action.new_state == request.text
|
||||
print(action.action_log)
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
+1
-1
@@ -1,4 +1,4 @@
|
||||
"""Hermetic mechanics test for productivity_management.create_nextcloud_task.
|
||||
"""Hermetic mechanics test for nextcloud.create_task.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the Nextcloud bridge (`GET /tasklists`, `POST /tasks`) and the
|
||||
File renamed without changes.
File renamed without changes.
@@ -212,7 +212,7 @@ def _default_calendar(ctx, calendars):
|
||||
|
||||
|
||||
def _resolve_calendar(ctx, request, calendars, decisions):
|
||||
"""Resolve which calendar the request means, mirroring calendar.create_event.
|
||||
"""Resolve which calendar the request means, mirroring nextcloud.create_event.
|
||||
|
||||
A strong SemIf winner is used; a weak winner falls back to the configured
|
||||
default calendar, and with no configured default the weak winner stands.
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Hermetic mechanics test for calendar.next_event.
|
||||
"""Hermetic mechanics test for nextcloud.next_event.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the Nextcloud CalDAV endpoint. This proves the body builds
|
||||
@@ -128,7 +128,7 @@ def _default_sender(ctx, senders):
|
||||
|
||||
|
||||
def _resolve_contact(ctx, request, senders, decisions):
|
||||
"""Resolve which conversation to read, mirroring calendar.create_event.
|
||||
"""Resolve which conversation to read, mirroring nextcloud.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.
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"simplex_bridge_url": "Base URL of the local SimpleX forwarding bridge that fronts the user's simplex daemon, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
||||
"simplex_bridge_token": "Shared secret for the SimpleX 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 clearly name a recipient; leave blank to always use the strongest candidate.",
|
||||
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to write the message text when the request does not state it.",
|
||||
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Send a SimpleX message to a contact through the forwarding bridge."
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
"""Send a text message to a SimpleX contact through the local SimpleX bridge.
|
||||
|
||||
Real integration: the simplex bridge over HTTP. The bridge owns the SimpleX
|
||||
daemon connection and its credentials; this body only calls the bridge's HTTP
|
||||
API with the base URL and token resolved from `ctx.config`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from semif_agent.decisions import DecisionRequest, Option
|
||||
from semif_agent.skills import ActionResult
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "simplex",
|
||||
"transport": "http",
|
||||
"config_vars": [
|
||||
"simplex_bridge_url",
|
||||
"simplex_bridge_token",
|
||||
"simplex_default_contact",
|
||||
"llm_bridge_url",
|
||||
"llm_bridge_token",
|
||||
],
|
||||
}
|
||||
|
||||
CONTRACT = {
|
||||
"simplex_bridge_url": (
|
||||
"Base URL of the local SimpleX forwarding bridge that fronts the "
|
||||
"user's simplex daemon, e.g. http://127.0.0.1:5227 (no trailing slash "
|
||||
"needed)."
|
||||
),
|
||||
"simplex_bridge_token": (
|
||||
"Shared secret for the SimpleX 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 clearly name a recipient; leave blank to always use "
|
||||
"the strongest candidate."
|
||||
),
|
||||
"llm_bridge_url": (
|
||||
"Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no "
|
||||
"trailing slash needed); used to write the message text when the "
|
||||
"request does not state it."
|
||||
),
|
||||
"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."
|
||||
),
|
||||
}
|
||||
|
||||
# A contact sub-decision winner is used only when its conditional probability
|
||||
# clears this bar; otherwise the configured default contact wins.
|
||||
CONFIDENCE_THRESHOLD = 0.5
|
||||
|
||||
_HTTP_TIMEOUT = 20
|
||||
|
||||
# Ordered: the literal message text the user dictated wins over anything else.
|
||||
_MESSAGE_PATTERNS = (
|
||||
r"\b(?:saying|say|that says|which says|that reads|reads)\b\s*[:\-]?\s*(.+)$",
|
||||
r'["\u201c](.+?)["\u201d]',
|
||||
r"\b(?:message|text)\s*(?:is|:)\s*(.+)$",
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# bridge transport
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _headers(token: str, has_body: bool) -> dict:
|
||||
headers = {"Accept": "application/json"}
|
||||
if has_body:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if token:
|
||||
headers["X-Semif-Token"] = token
|
||||
return headers
|
||||
|
||||
|
||||
def _http_json(url: str, token: str, payload=None):
|
||||
"""GET the url, or POST the payload as JSON, and decode the JSON reply."""
|
||||
data = None
|
||||
if payload is not None:
|
||||
data = json.dumps(payload).encode("utf-8")
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers=_headers(token, data is not None),
|
||||
method="POST" if data is not None else "GET",
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=_HTTP_TIMEOUT) as response:
|
||||
raw = response.read().decode("utf-8")
|
||||
if not raw.strip():
|
||||
return {}
|
||||
return json.loads(raw)
|
||||
|
||||
|
||||
def _error_detail(exc) -> str:
|
||||
"""Best-effort human-readable detail from an HTTP error response."""
|
||||
try:
|
||||
raw = exc.read().decode("utf-8", "replace")
|
||||
except Exception:
|
||||
raw = ""
|
||||
if raw:
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
except ValueError:
|
||||
parsed = None
|
||||
if isinstance(parsed, dict) and parsed.get("error"):
|
||||
return str(parsed["error"])
|
||||
return raw.strip()
|
||||
return str(getattr(exc, "reason", "") or exc)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# contacts
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _contact_id(contact) -> str:
|
||||
return str(contact.get("id") or contact.get("display_name") or "").strip()
|
||||
|
||||
|
||||
def _display(contact) -> str:
|
||||
return str(contact.get("display_name") or contact.get("id") or "").strip()
|
||||
|
||||
|
||||
def _label(contact) -> str:
|
||||
"""The unique name for a contact: the daemon's local name when known.
|
||||
|
||||
Two peers can share a profile display name; the local name is unique, so it
|
||||
is the right label for a SemIf option and the right thing to match on.
|
||||
"""
|
||||
return str(
|
||||
contact.get("local_name") or _display(contact) or contact.get("id") or ""
|
||||
).strip()
|
||||
|
||||
|
||||
def _is_healthy(contact) -> bool:
|
||||
"""A contact is healthy when its connection is not known-bad.
|
||||
|
||||
`connected` is absent when the source did not report it (treat as unknown,
|
||||
i.e. not disqualifying); `auth_errors` counts failed sends on the connection
|
||||
and marks a stale/duplicate peer.
|
||||
"""
|
||||
if contact.get("connected") is False:
|
||||
return False
|
||||
try:
|
||||
return int(contact.get("auth_errors") or 0) == 0
|
||||
except (TypeError, ValueError):
|
||||
return True
|
||||
|
||||
|
||||
def _mentions(query: str, name: str) -> bool:
|
||||
if not name:
|
||||
return False
|
||||
pattern = r"(?<!\w)" + re.escape(name.lower()) + r"(?!\w)"
|
||||
return re.search(pattern, query.lower()) is not None
|
||||
|
||||
|
||||
def _match_contact(contacts, ref: str):
|
||||
"""Resolve an id or display name against the bridge's contact list."""
|
||||
ref = (ref or "").strip()
|
||||
if not ref:
|
||||
return None
|
||||
lowered = ref.lower()
|
||||
for contact in contacts:
|
||||
if _contact_id(contact).lower() == lowered:
|
||||
return contact
|
||||
exact = [
|
||||
c
|
||||
for c in contacts
|
||||
if _label(c).lower() == lowered or _display(c).lower() == lowered
|
||||
]
|
||||
if exact:
|
||||
return _preferred(exact)
|
||||
matches = [
|
||||
c
|
||||
for c in contacts
|
||||
if lowered in _display(c).lower() or lowered in _label(c).lower()
|
||||
]
|
||||
if len(matches) == 1:
|
||||
return matches[0]
|
||||
if matches:
|
||||
return _preferred(matches)
|
||||
return None
|
||||
|
||||
|
||||
def _preferred(candidates):
|
||||
"""Prefer a healthy candidate (the others are likely stale duplicates)."""
|
||||
healthy = [c for c in candidates if _is_healthy(c)]
|
||||
return (healthy or candidates)[0]
|
||||
|
||||
|
||||
def _find_by_id(contacts, contact_id):
|
||||
wanted = str(contact_id or "")
|
||||
for contact in contacts:
|
||||
if _contact_id(contact) == wanted:
|
||||
return contact
|
||||
return None
|
||||
|
||||
|
||||
def _confidence(result, option_id) -> float:
|
||||
prob = getattr(result, "prob", None)
|
||||
if callable(prob):
|
||||
try:
|
||||
return float(prob(option_id))
|
||||
except Exception:
|
||||
return 0.0
|
||||
probs = getattr(result, "probs", None)
|
||||
if isinstance(probs, dict):
|
||||
try:
|
||||
return float(probs.get(option_id, 0.0))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
return 0.0
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# message text
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _message_from_query(query: str) -> str:
|
||||
"""Pull the literal message text out of the user's request, if stated."""
|
||||
for pattern in _MESSAGE_PATTERNS:
|
||||
match = re.search(pattern, query, flags=re.IGNORECASE | re.DOTALL)
|
||||
if match:
|
||||
text = match.group(1).strip().strip("\"'\u201c\u201d").strip()
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
|
||||
|
||||
def _llm_message_text(ctx, query: str):
|
||||
"""Ask the LLM bridge to write the message body. Returns (text, reason)."""
|
||||
base_url = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
|
||||
if not base_url:
|
||||
return None, "no llm bridge is configured"
|
||||
token = str(ctx.config.get("llm_bridge_token", "") or "")
|
||||
payload = {
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"content": (
|
||||
"You write the exact text of a chat message a user wants to "
|
||||
"send. Reply with the message text only: no quotes, no "
|
||||
"preamble, no explanation."
|
||||
),
|
||||
},
|
||||
{"role": "user", "content": query},
|
||||
],
|
||||
"max_tokens": 256,
|
||||
}
|
||||
try:
|
||||
reply = _http_json(f"{base_url}/chat", token, payload)
|
||||
except urllib.error.HTTPError as exc:
|
||||
return None, f"the llm bridge returned HTTP {exc.code} {_error_detail(exc)}"
|
||||
except (urllib.error.URLError, ValueError, OSError) as exc:
|
||||
return None, f"could not reach the llm bridge: {exc}"
|
||||
if not isinstance(reply, dict):
|
||||
return None, "the llm bridge returned an unexpected reply"
|
||||
text = str(reply.get("text", "")).strip().strip('"').strip()
|
||||
if not text:
|
||||
return None, "the llm bridge returned no text"
|
||||
return text, ""
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# action
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def act(ctx, request) -> ActionResult:
|
||||
"""Send the requested message to the requested SimpleX contact."""
|
||||
base_url = str(ctx.config["simplex_bridge_url"]).strip().rstrip("/")
|
||||
token = str(ctx.config.get("simplex_bridge_token", "") or "")
|
||||
default_ref = str(ctx.config.get("simplex_default_contact", "") or "").strip()
|
||||
|
||||
query = (request.text or "").strip()
|
||||
user_input = str(getattr(request, "user_input", "") or "").strip()
|
||||
decisions = []
|
||||
|
||||
# --- the bridge's real contact list ------------------------------------
|
||||
try:
|
||||
payload = _http_json(f"{base_url}/contacts", token)
|
||||
except urllib.error.HTTPError as exc:
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"the simplex bridge at {base_url} returned HTTP {exc.code} "
|
||||
f"while listing contacts: {_error_detail(exc)}"
|
||||
),
|
||||
new_state=request.text,
|
||||
)
|
||||
except (urllib.error.URLError, ValueError, OSError) as exc:
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"could not reach the simplex bridge at {base_url} to list "
|
||||
f"contacts: {exc}"
|
||||
),
|
||||
new_state=request.text,
|
||||
)
|
||||
|
||||
raw_contacts = payload.get("contacts") if isinstance(payload, dict) else None
|
||||
contacts = (
|
||||
[c for c in raw_contacts if isinstance(c, dict)]
|
||||
if isinstance(raw_contacts, list)
|
||||
else []
|
||||
)
|
||||
|
||||
# --- resolve the recipient --------------------------------------------
|
||||
default_contact = _match_contact(contacts, default_ref)
|
||||
named = [
|
||||
c
|
||||
for c in contacts
|
||||
if _mentions(query, _display(c)) or _mentions(query, _label(c))
|
||||
]
|
||||
|
||||
chosen = None
|
||||
used_input_for_contact = False
|
||||
|
||||
if named or default_contact is not None:
|
||||
candidates = list(named)
|
||||
if default_contact is not None and all(
|
||||
_contact_id(c) != _contact_id(default_contact) for c in candidates
|
||||
):
|
||||
candidates.append(default_contact)
|
||||
|
||||
healthy = [c for c in candidates if _is_healthy(c)]
|
||||
if len(candidates) == 1:
|
||||
chosen = candidates[0]
|
||||
elif len(healthy) == 1:
|
||||
# Exactly one candidate's connection is healthy (the rest are stale
|
||||
# duplicates): pick it deterministically rather than coin-flipping.
|
||||
chosen = healthy[0]
|
||||
else:
|
||||
decision = DecisionRequest(
|
||||
state=query,
|
||||
question="Which SimpleX contact should the message be sent to?",
|
||||
options=[
|
||||
Option(_contact_id(c), _label(c) or _contact_id(c))
|
||||
for c in candidates
|
||||
],
|
||||
)
|
||||
result = ctx.engine.call(decision)
|
||||
decisions.append((decision, result))
|
||||
selected_id = getattr(result, "selected", None)
|
||||
selected = _find_by_id(candidates, selected_id)
|
||||
if (
|
||||
selected is not None
|
||||
and _confidence(result, selected_id) >= CONFIDENCE_THRESHOLD
|
||||
):
|
||||
chosen = selected
|
||||
elif default_contact is not None:
|
||||
chosen = default_contact
|
||||
else:
|
||||
chosen = selected if selected is not None else candidates[0]
|
||||
elif user_input:
|
||||
# The human answered the question asked on the previous pass.
|
||||
chosen = _match_contact(contacts, user_input) or {
|
||||
"id": user_input,
|
||||
"display_name": user_input,
|
||||
}
|
||||
used_input_for_contact = True
|
||||
|
||||
if chosen is None:
|
||||
known = ", ".join(_display(c) for c in contacts if _display(c)) or "none"
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
"the request does not identify a SimpleX contact to message; "
|
||||
f"the bridge knows these contacts: {known}"
|
||||
),
|
||||
new_state=request.text,
|
||||
needs_input="Which SimpleX contact should I message?",
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
recipient = _contact_id(chosen) or _display(chosen)
|
||||
display_name = _display(chosen) or recipient
|
||||
|
||||
# --- resolve the message text -----------------------------------------
|
||||
message_text = _message_from_query(query)
|
||||
if not message_text and user_input and not used_input_for_contact:
|
||||
message_text = user_input
|
||||
if not message_text:
|
||||
written, reason = _llm_message_text(ctx, query)
|
||||
if written:
|
||||
message_text = written
|
||||
else:
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"the request does not state what the message to "
|
||||
f"{display_name} should say and no message text could be "
|
||||
f"written ({reason})"
|
||||
),
|
||||
new_state=request.text,
|
||||
needs_input=f"What should the message to {display_name} say?",
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
# --- send it through the bridge ---------------------------------------
|
||||
try:
|
||||
response = _http_json(
|
||||
f"{base_url}/send", token, {"recipient": recipient, "text": message_text}
|
||||
)
|
||||
except urllib.error.HTTPError as exc:
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"the simplex bridge refused to send to {display_name}: "
|
||||
f"HTTP {exc.code} {_error_detail(exc)}"
|
||||
),
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
except (urllib.error.URLError, ValueError, OSError) as exc:
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"could not reach the simplex bridge at {base_url} to send the "
|
||||
f"message to {display_name}: {exc}"
|
||||
),
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
if not isinstance(response, dict):
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"the simplex bridge returned an unexpected reply while sending "
|
||||
f"to {display_name}"
|
||||
),
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
contact_id = str(response.get("contact_id") or recipient)
|
||||
status = str(response.get("status") or "")
|
||||
if not response.get("ok"):
|
||||
detail = str(response.get("error") or "").strip() or json.dumps(response)
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"the message to {display_name} (contact {contact_id}) did not "
|
||||
f"send (status {status or 'unknown'}: {detail})"
|
||||
),
|
||||
new_state=json.dumps(
|
||||
{
|
||||
"sent": False,
|
||||
"contact_id": contact_id,
|
||||
"display_name": display_name,
|
||||
"status": status,
|
||||
"error": detail,
|
||||
"text": message_text,
|
||||
}
|
||||
),
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
return ActionResult(
|
||||
action_log=(
|
||||
f"sent the message {message_text!r} to {display_name} "
|
||||
f"(contact {contact_id}, status {status or 'ok'}) through the "
|
||||
f"simplex bridge"
|
||||
),
|
||||
new_state=json.dumps(
|
||||
{
|
||||
"sent": True,
|
||||
"contact_id": contact_id,
|
||||
"display_name": display_name,
|
||||
"status": status,
|
||||
"text": message_text,
|
||||
}
|
||||
),
|
||||
decisions=decisions,
|
||||
)
|
||||
@@ -0,0 +1,371 @@
|
||||
"""Hermetic mechanics test for simplex.send_message.
|
||||
|
||||
Stands up loopback HTTP servers that imitate the simplex and llm bridges,
|
||||
points the fixture config at them, and drives the body's real `act` so the
|
||||
request construction, recipient/message resolution and error paths are
|
||||
exercised without leaving the machine.
|
||||
"""
|
||||
|
||||
import json
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import skill
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# inline fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
CONTACTS = [
|
||||
{"id": "c-pepper", "display_name": "pepper"},
|
||||
{"id": "c-salt", "display_name": "salt"},
|
||||
]
|
||||
|
||||
SIMPLEX_TOKEN = "s3cret-simplex-token"
|
||||
LLM_TOKEN = "s3cret-llm-token"
|
||||
LLM_REPLY = "a friendly hello"
|
||||
|
||||
|
||||
class FakeRequest:
|
||||
"""Minimal stand-in for the agent's Request object (test-only)."""
|
||||
|
||||
def __init__(self, text, user_input=""):
|
||||
self.text = text
|
||||
self.user_input = user_input
|
||||
|
||||
|
||||
class FakeResult:
|
||||
"""Stand-in for a decision result: exposes `selected` and `prob(id)`."""
|
||||
|
||||
def __init__(self, selected, confidence):
|
||||
self.selected = selected
|
||||
self._confidence = confidence
|
||||
|
||||
def prob(self, option_id):
|
||||
return float(self._confidence) if option_id == self.selected else 0.0
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
"""Test-only decision engine."""
|
||||
|
||||
def __init__(self, selected=None, confidence=1.0):
|
||||
self.selected = selected
|
||||
self.confidence = confidence
|
||||
self.calls = []
|
||||
|
||||
def call(self, decision):
|
||||
self.calls.append(decision)
|
||||
selected = self.selected
|
||||
if selected is None:
|
||||
options = list(decision.options)
|
||||
selected = options[0].id if options else None
|
||||
return FakeResult(selected, self.confidence)
|
||||
|
||||
|
||||
class _BaseHandler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def _send_json(self, code, obj):
|
||||
body = json.dumps(obj).encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _read_body(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(length) if length else b""
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return json.loads(raw.decode("utf-8"))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
class SimplexHandler(_BaseHandler):
|
||||
contacts = []
|
||||
send_error = False
|
||||
seen = []
|
||||
|
||||
def do_GET(self):
|
||||
SimplexHandler.seen.append(
|
||||
{
|
||||
"method": "GET",
|
||||
"path": self.path,
|
||||
"token": self.headers.get("X-Semif-Token"),
|
||||
}
|
||||
)
|
||||
if self.path == "/contacts":
|
||||
self._send_json(200, {"contacts": SimplexHandler.contacts})
|
||||
else:
|
||||
self._send_json(404, {"error": "not found"})
|
||||
|
||||
def do_POST(self):
|
||||
body = self._read_body()
|
||||
SimplexHandler.seen.append(
|
||||
{
|
||||
"method": "POST",
|
||||
"path": self.path,
|
||||
"token": self.headers.get("X-Semif-Token"),
|
||||
"body": body,
|
||||
}
|
||||
)
|
||||
if self.path != "/send":
|
||||
self._send_json(404, {"error": "not found"})
|
||||
return
|
||||
if SimplexHandler.send_error:
|
||||
self._send_json(400, {"error": "unknown recipient"})
|
||||
return
|
||||
recipient = (body or {}).get("recipient", "")
|
||||
self._send_json(200, {"ok": True, "contact_id": recipient})
|
||||
|
||||
|
||||
class LlmHandler(_BaseHandler):
|
||||
reply = LLM_REPLY
|
||||
seen = []
|
||||
|
||||
def do_POST(self):
|
||||
body = self._read_body()
|
||||
LlmHandler.seen.append(
|
||||
{
|
||||
"path": self.path,
|
||||
"token": self.headers.get("X-Semif-Token"),
|
||||
"body": body,
|
||||
}
|
||||
)
|
||||
if self.path == "/chat":
|
||||
self._send_json(200, {"text": LlmHandler.reply})
|
||||
else:
|
||||
self._send_json(404, {"error": "not found"})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def start_server(handler):
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server
|
||||
|
||||
|
||||
def base_url(server):
|
||||
return f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def reset(contacts=None, send_error=False):
|
||||
SimplexHandler.contacts = [dict(c) for c in (contacts if contacts is not None else CONTACTS)]
|
||||
SimplexHandler.send_error = send_error
|
||||
SimplexHandler.seen = []
|
||||
LlmHandler.seen = []
|
||||
LlmHandler.reply = LLM_REPLY
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_happy_path():
|
||||
"""A named contact plus an explicit message: GET /contacts then POST /send."""
|
||||
reset()
|
||||
server = start_server(SimplexHandler)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={
|
||||
"simplex_bridge_url": base_url(server),
|
||||
"simplex_bridge_token": SIMPLEX_TOKEN,
|
||||
},
|
||||
)
|
||||
result = skill.act(
|
||||
ctx, FakeRequest("send a message to pepper on simplex saying hey")
|
||||
)
|
||||
|
||||
assert result.action_log, "act must log what it did"
|
||||
assert not result.needs_input, result.action_log
|
||||
assert "sent" in result.action_log.lower(), result.action_log
|
||||
|
||||
gets = [r for r in SimplexHandler.seen if r["method"] == "GET"]
|
||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
||||
assert any(r["path"] == "/contacts" for r in gets), SimplexHandler.seen
|
||||
assert len(posts) == 1, SimplexHandler.seen
|
||||
assert posts[0]["path"] == "/send", SimplexHandler.seen
|
||||
assert posts[0]["body"] == {"recipient": "c-pepper", "text": "hey"}, posts[0]
|
||||
|
||||
for seen in SimplexHandler.seen:
|
||||
assert seen["token"] == SIMPLEX_TOKEN, seen
|
||||
|
||||
state = json.loads(result.new_state)
|
||||
assert state["sent"] is True, state
|
||||
assert state["contact_id"] == "c-pepper", state
|
||||
assert state["text"] == "hey", state
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_ambiguous_contact_uses_engine():
|
||||
"""Two named contacts: the body must ask the engine and honour the pick."""
|
||||
reset()
|
||||
server = start_server(SimplexHandler)
|
||||
try:
|
||||
engine = FakeEngine(selected="c-salt", confidence=0.9)
|
||||
ctx = ActionContext(
|
||||
engine=engine,
|
||||
config={"simplex_bridge_url": base_url(server)},
|
||||
)
|
||||
result = skill.act(
|
||||
ctx, FakeRequest("send a message to pepper and salt saying hi")
|
||||
)
|
||||
|
||||
assert not result.needs_input, result.action_log
|
||||
assert len(engine.calls) == 1, engine.calls
|
||||
option_ids = [o.id for o in engine.calls[0].options]
|
||||
assert set(option_ids) == {"c-pepper", "c-salt"}, option_ids
|
||||
|
||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
||||
assert len(posts) == 1, SimplexHandler.seen
|
||||
assert posts[0]["body"] == {"recipient": "c-salt", "text": "hi"}, posts[0]
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_message_written_by_llm_bridge():
|
||||
"""No literal text: the body must ask the llm bridge, then send its reply."""
|
||||
reset()
|
||||
simplex = start_server(SimplexHandler)
|
||||
llm = start_server(LlmHandler)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={
|
||||
"simplex_bridge_url": base_url(simplex),
|
||||
"simplex_bridge_token": SIMPLEX_TOKEN,
|
||||
"llm_bridge_url": base_url(llm),
|
||||
"llm_bridge_token": LLM_TOKEN,
|
||||
},
|
||||
)
|
||||
result = skill.act(ctx, FakeRequest("tell pepper something nice"))
|
||||
|
||||
assert not result.needs_input, result.action_log
|
||||
assert len(LlmHandler.seen) == 1, LlmHandler.seen
|
||||
chat = LlmHandler.seen[0]
|
||||
assert chat["path"] == "/chat", chat
|
||||
assert chat["token"] == LLM_TOKEN, chat
|
||||
assert chat["body"]["messages"], chat
|
||||
|
||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
||||
assert len(posts) == 1, SimplexHandler.seen
|
||||
assert posts[0]["body"] == {"recipient": "c-pepper", "text": LLM_REPLY}, posts[0]
|
||||
finally:
|
||||
simplex.shutdown()
|
||||
simplex.server_close()
|
||||
llm.shutdown()
|
||||
llm.server_close()
|
||||
|
||||
|
||||
def test_missing_text_without_llm_asks():
|
||||
"""A clear recipient but no message text and no llm bridge: ask the user."""
|
||||
reset()
|
||||
server = start_server(SimplexHandler)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={"simplex_bridge_url": base_url(server)},
|
||||
)
|
||||
result = skill.act(ctx, FakeRequest("tell pepper something nice"))
|
||||
|
||||
assert result.needs_input, result.action_log
|
||||
assert "say" in result.needs_input.lower(), result.needs_input
|
||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
||||
assert posts == [], SimplexHandler.seen
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_unknown_contact_asks():
|
||||
"""No matching contact in the bridge list: ask which contact to message."""
|
||||
reset(contacts=[])
|
||||
server = start_server(SimplexHandler)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={"simplex_bridge_url": base_url(server)},
|
||||
)
|
||||
result = skill.act(
|
||||
ctx, FakeRequest("send a message to pepper on simplex saying hey")
|
||||
)
|
||||
|
||||
assert result.needs_input, result.action_log
|
||||
assert "contact" in result.needs_input.lower(), result.needs_input
|
||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
||||
assert posts == [], SimplexHandler.seen
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_send_refused_is_reported():
|
||||
"""A 400 from POST /send must be surfaced, not silently swallowed."""
|
||||
reset(send_error=True)
|
||||
server = start_server(SimplexHandler)
|
||||
try:
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={"simplex_bridge_url": base_url(server)},
|
||||
)
|
||||
result = skill.act(
|
||||
ctx, FakeRequest("send a message to pepper on simplex saying hey")
|
||||
)
|
||||
|
||||
assert not result.needs_input, result.action_log
|
||||
assert "refused" in result.action_log.lower(), result.action_log
|
||||
assert "400" in result.action_log, result.action_log
|
||||
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
|
||||
assert len(posts) == 1, SimplexHandler.seen
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_unreachable_bridge_is_reported():
|
||||
"""A dead bridge must produce a plain failure log, not an exception."""
|
||||
reset()
|
||||
server = start_server(SimplexHandler)
|
||||
url = base_url(server)
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
ctx = ActionContext(
|
||||
engine=FakeEngine(),
|
||||
config={"simplex_bridge_url": url},
|
||||
)
|
||||
result = skill.act(
|
||||
ctx, FakeRequest("send a message to pepper on simplex saying hey")
|
||||
)
|
||||
assert not result.needs_input, result.action_log
|
||||
assert "could not reach" in result.action_log.lower(), result.action_log
|
||||
|
||||
|
||||
def main():
|
||||
test_happy_path()
|
||||
test_ambiguous_contact_uses_engine()
|
||||
test_message_written_by_llm_bridge()
|
||||
test_missing_text_without_llm_asks()
|
||||
test_unknown_contact_asks()
|
||||
test_send_refused_is_reported()
|
||||
test_unreachable_bridge_is_reported()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -11,7 +11,7 @@ There is no service daemon: Nextcloud is plain HTTPS, so the bridge is stdlib-on
|
||||
(`urllib` + `xml.etree`) and starts instantly. The connection comes from
|
||||
`bridges.nextcloud` (url/username/app_password/default_calendar/default_addressbook),
|
||||
falling back to the top-level `nextcloud_url`/`nextcloud_username`/
|
||||
`nextcloud_app_password`/`nextcloud_default_calendar` values the calendar seeds
|
||||
`nextcloud_app_password`/`nextcloud_default_calendar` values the nextcloud seeds
|
||||
already use, so the same account is configured in one place.
|
||||
|
||||
The actual DAV/OCS work lives in `nextcloud_client.py`; the routes here validate
|
||||
|
||||
@@ -112,7 +112,7 @@ def build_bridge(
|
||||
`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. The Nextcloud bridge gets the top-level `nextcloud_*` values as a
|
||||
fallback, so the same account the calendar seeds use is configured once. Other
|
||||
fallback, so the same account the nextcloud seeds use is configured once. Other
|
||||
bridges ignore both.
|
||||
"""
|
||||
bridge_class = _class_for(name)
|
||||
|
||||
+7
-10
@@ -656,9 +656,10 @@ CATEGORY_DESCRIPTIONS: dict[str, str] = {
|
||||
"Anything that is not a request to perform an action or produce a result: "
|
||||
"greetings, thanks, acknowledgements, chit-chat, and off-topic statements."
|
||||
),
|
||||
"calendar": (
|
||||
"Calendar and scheduling: reading or changing the user's calendar "
|
||||
"events and reminders."
|
||||
"nextcloud": (
|
||||
"Nextcloud productivity: the user's calendar events and scheduling "
|
||||
"(reading or changing events and reminders) and the user's to-do tasks "
|
||||
"and task lists."
|
||||
),
|
||||
"simplex": (
|
||||
"SimpleX messaging: reading incoming messages, sending messages to "
|
||||
@@ -668,10 +669,6 @@ CATEGORY_DESCRIPTIONS: dict[str, str] = {
|
||||
"Time and date utilities: telling the current time or date, setting "
|
||||
"countdown timers, and setting alarms."
|
||||
),
|
||||
"productivity_management": (
|
||||
"Personal productivity: creating and managing the user's to-do tasks "
|
||||
"and task lists."
|
||||
),
|
||||
"housekeeping": (
|
||||
"Agent self-maintenance: deleting, reconfiguring, regenerating, and "
|
||||
"cancelling the agent's own skills."
|
||||
@@ -724,7 +721,7 @@ _TARGET_QUESTION = (
|
||||
# Explicit housekeeping command forms. They are routed deterministically to the
|
||||
# housekeeping skill (see parse_meta_command) because the generic SemIf guards
|
||||
# read a task-like skill name in the request as the task itself (e.g.
|
||||
# "regen skill calendar.create_event" scores as a calendar task). The skill name
|
||||
# "regen skill nextcloud.create_event" scores as a nextcloud task). The skill name
|
||||
# is just a variable the skill resolves — or asks for.
|
||||
_META_PATTERNS: list[tuple[str, "re.Pattern[str]"]] = [
|
||||
(
|
||||
@@ -785,10 +782,10 @@ def parse_meta_command(text: str) -> str | None:
|
||||
def _resolve_target(admin, request: Request):
|
||||
"""Resolve the skill a housekeeping request targets.
|
||||
|
||||
The target may be named in the request ("delete skill calendar.foo") or
|
||||
The target may be named in the request ("delete skill nextcloud.foo") or
|
||||
supplied as an input variable when the request is name-free ("delete
|
||||
skill") — in which case the skill asks for it. Keeping the name out of the
|
||||
routed request is deliberate: a skill name like `calendar.create_event`
|
||||
routed request is deliberate: a skill name like `nextcloud.create_event`
|
||||
reads as a task and pulls navigation to the wrong category. Returns a
|
||||
`(category, name)` tuple, or an `ActionResult` (needs_input / not-found /
|
||||
ambiguous) to return as-is.
|
||||
|
||||
@@ -215,7 +215,7 @@ def test_navigation_routes_noise_into_the_response_tree(tmp_path):
|
||||
scheduler.engine, scheduler.log, scheduler.trace, Request(text), scheduler.tree
|
||||
)
|
||||
print(f"[lookup] {text!r} -> {result!r}")
|
||||
assert getattr(result, "category", None) == "calendar", f"lookup misrouted: {text!r}"
|
||||
assert getattr(result, "category", None) == "nextcloud", f"lookup misrouted: {text!r}"
|
||||
for text in noise:
|
||||
result = navigate(
|
||||
scheduler.engine, scheduler.log, scheduler.trace, Request(text), scheduler.tree
|
||||
@@ -583,7 +583,7 @@ def test_create_simplex_send_skill(tmp_path):
|
||||
scheduler, config = build_scheduler(config)
|
||||
|
||||
seeded = {s.name for s in scheduler.tree.get("simplex", [])}
|
||||
assert {"next_message", "connect_link"} <= seeded, (
|
||||
assert {"next_message", "send_message", "connect_link"} <= seeded, (
|
||||
f"the simplex seeds must be loaded, got {seeded}"
|
||||
)
|
||||
|
||||
|
||||
+63
-63
@@ -110,15 +110,15 @@ def test_build_housekeeping_skills():
|
||||
|
||||
def test_parse_meta_command_forms():
|
||||
assert parse_meta_command("delete skill") == "delete_skill"
|
||||
assert parse_meta_command("delete skill calendar.foo") == "delete_skill"
|
||||
assert parse_meta_command("delete skill nextcloud.foo") == "delete_skill"
|
||||
assert parse_meta_command("remove skill simplex.next_message") == "delete_skill"
|
||||
assert parse_meta_command("clear config variables") == "clear_config"
|
||||
assert parse_meta_command("clear the config variables for calendar.foo") == "clear_config"
|
||||
assert parse_meta_command("clear the config variables for nextcloud.foo") == "clear_config"
|
||||
assert parse_meta_command("clear the settings for simplex.next_message") == "clear_config"
|
||||
assert parse_meta_command("reset a skill's settings") == "clear_config"
|
||||
assert parse_meta_command("regen skill") == "regen_skill"
|
||||
assert parse_meta_command("regenerate the simplex skill") == "regen_skill"
|
||||
assert parse_meta_command("rewrite the code for calendar.foo") == "regen_skill"
|
||||
assert parse_meta_command("rewrite the code for nextcloud.foo") == "regen_skill"
|
||||
assert parse_meta_command("cancel skill build") == "cancel_build"
|
||||
assert parse_meta_command("cancel the skill build") == "cancel_build"
|
||||
assert parse_meta_command("abort the build") == "cancel_build"
|
||||
@@ -141,19 +141,19 @@ def test_parse_meta_command_leaves_normal_requests_alone():
|
||||
|
||||
def test_dispatch_routes_meta_command_deterministically(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
_add_skill(scheduler, "calendar", "foo")
|
||||
_add_skill(scheduler, "nextcloud", "foo")
|
||||
|
||||
# clear config runs immediately (no confirmation).
|
||||
result = scheduler._dispatch(Request("clear config variables for calendar.foo"))
|
||||
result = scheduler._dispatch(Request("clear config variables for nextcloud.foo"))
|
||||
assert result.kind == "ran"
|
||||
assert result.skill == "clear_config"
|
||||
|
||||
# delete routes to the meta skill and pauses for confirmation.
|
||||
delete = scheduler._dispatch(Request("delete skill calendar.foo"))
|
||||
delete = scheduler._dispatch(Request("delete skill nextcloud.foo"))
|
||||
assert delete.kind == "needs_input"
|
||||
assert delete.skill == "delete_skill"
|
||||
assert any(e["kind"] == "meta_command" for e in scheduler.trace.read())
|
||||
assert any(s.name == "foo" for s in scheduler.tree["calendar"])
|
||||
assert any(s.name == "foo" for s in scheduler.tree["nextcloud"])
|
||||
|
||||
|
||||
# ---- name resolution ----
|
||||
@@ -161,8 +161,8 @@ def test_dispatch_routes_meta_command_deterministically(tmp_path):
|
||||
|
||||
def _tree():
|
||||
return {
|
||||
"calendar": [
|
||||
Skill(name="next_event", category="calendar", description="d"),
|
||||
"nextcloud": [
|
||||
Skill(name="next_event", category="nextcloud", description="d"),
|
||||
],
|
||||
"simplex": [
|
||||
Skill(name="next_message", category="simplex", description="d"),
|
||||
@@ -172,8 +172,8 @@ def _tree():
|
||||
|
||||
def test_resolve_skill_ref_dotted_and_bare():
|
||||
tree = _tree()
|
||||
assert resolve_skill_ref(tree, "delete skill calendar.next_event") == (
|
||||
"calendar",
|
||||
assert resolve_skill_ref(tree, "delete skill nextcloud.next_event") == (
|
||||
"nextcloud",
|
||||
"next_event",
|
||||
)
|
||||
assert resolve_skill_ref(tree, "delete skill next_message") == (
|
||||
@@ -208,9 +208,9 @@ def test_registry_unregister_skill(tmp_path):
|
||||
|
||||
def test_skill_store_delete_and_path_guard(tmp_path):
|
||||
store = SkillStore(str(tmp_path / "skills"))
|
||||
store.write_body("calendar", "foo", "x = 1\n")
|
||||
assert store.delete("calendar", "foo") is True
|
||||
assert not store.dir("calendar", "foo").exists()
|
||||
store.write_body("nextcloud", "foo", "x = 1\n")
|
||||
assert store.delete("nextcloud", "foo") is True
|
||||
assert not store.dir("nextcloud", "foo").exists()
|
||||
with pytest.raises(ValueError):
|
||||
store.delete("..", "escape")
|
||||
|
||||
@@ -218,36 +218,36 @@ def test_skill_store_delete_and_path_guard(tmp_path):
|
||||
def test_deleted_skills_roundtrip(tmp_path):
|
||||
deleted = DeletedSkills(str(tmp_path / "deleted.json"))
|
||||
assert deleted.read() == set()
|
||||
deleted.add("calendar", "foo")
|
||||
assert deleted.contains("calendar", "foo")
|
||||
deleted.remove("calendar", "foo")
|
||||
deleted.add("nextcloud", "foo")
|
||||
assert deleted.contains("nextcloud", "foo")
|
||||
deleted.remove("nextcloud", "foo")
|
||||
assert deleted.read() == set()
|
||||
|
||||
|
||||
def test_apply_tombstones():
|
||||
tree = {
|
||||
"calendar": [Skill(name="foo", category="calendar", description="d")],
|
||||
"nextcloud": [Skill(name="foo", category="nextcloud", description="d")],
|
||||
"simplex": [Skill(name="bar", category="simplex", description="d")],
|
||||
}
|
||||
deleted = DeletedSkills("/nonexistent/deleted.json")
|
||||
deleted.read = lambda: {"calendar.foo"} # type: ignore[assignment]
|
||||
deleted.read = lambda: {"nextcloud.foo"} # type: ignore[assignment]
|
||||
removed = apply_tombstones(tree, deleted)
|
||||
assert removed == 1
|
||||
assert tree["calendar"] == []
|
||||
assert tree["nextcloud"] == []
|
||||
assert [s.name for s in tree["simplex"]] == ["bar"]
|
||||
|
||||
|
||||
def test_delete_seed_is_durable(tmp_path):
|
||||
_write_seed(tmp_path / "seeds", "calendar", "probe")
|
||||
_write_seed(tmp_path / "seeds", "nextcloud", "probe")
|
||||
scheduler = _scheduler(tmp_path)
|
||||
assert any(s.name == "probe" for s in scheduler.tree["calendar"])
|
||||
assert scheduler.tree["calendar"][0].origin == "seed"
|
||||
assert any(s.name == "probe" for s in scheduler.tree["nextcloud"])
|
||||
assert scheduler.tree["nextcloud"][0].origin == "seed"
|
||||
|
||||
status, _ = scheduler.delete_skill("calendar", "probe")
|
||||
status, _ = scheduler.delete_skill("nextcloud", "probe")
|
||||
assert status == "ok"
|
||||
|
||||
reloaded = _scheduler(tmp_path)
|
||||
assert all(s.name != "probe" for s in reloaded.tree.get("calendar", []))
|
||||
assert all(s.name != "probe" for s in reloaded.tree.get("nextcloud", []))
|
||||
|
||||
|
||||
# ---- locks ----
|
||||
@@ -304,17 +304,17 @@ def test_restart_skill_blocked_when_locked(tmp_path):
|
||||
|
||||
def test_delete_skill_removes_tree_registry_and_folder(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
_add_skill(scheduler, "calendar", "foo")
|
||||
status, detail = scheduler.delete_skill("calendar", "foo")
|
||||
_add_skill(scheduler, "nextcloud", "foo")
|
||||
status, detail = scheduler.delete_skill("nextcloud", "foo")
|
||||
assert status == "ok"
|
||||
assert all(s.name != "foo" for s in scheduler.tree["calendar"])
|
||||
assert scheduler.body_store.read_contract("calendar", "foo") == {}
|
||||
assert not scheduler.body_store.dir("calendar", "foo").exists()
|
||||
assert all(s.name != "foo" for s in scheduler.tree["nextcloud"])
|
||||
assert scheduler.body_store.read_contract("nextcloud", "foo") == {}
|
||||
assert not scheduler.body_store.dir("nextcloud", "foo").exists()
|
||||
assert all(
|
||||
s.get("name") != "foo"
|
||||
for s in scheduler.registry.read()["calendar"]["skills"]
|
||||
for s in scheduler.registry.read()["nextcloud"]["skills"]
|
||||
)
|
||||
assert scheduler.deleted.contains("calendar", "foo")
|
||||
assert scheduler.deleted.contains("nextcloud", "foo")
|
||||
assert any(e["kind"] == "skill_deleted" for e in scheduler.trace.read())
|
||||
|
||||
|
||||
@@ -328,14 +328,14 @@ def test_delete_refuses_builtin(tmp_path):
|
||||
|
||||
def test_clear_skill_config(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
skill = _add_skill(scheduler, "calendar", "foo")
|
||||
skill = _add_skill(scheduler, "nextcloud", "foo")
|
||||
skill.config = {"api_key": "x"}
|
||||
scheduler.body_store.write_config("calendar", "foo", {"api_key": "x"})
|
||||
scheduler.body_store.write_config("nextcloud", "foo", {"api_key": "x"})
|
||||
|
||||
status, detail = scheduler.clear_skill_config("calendar", "foo")
|
||||
status, detail = scheduler.clear_skill_config("nextcloud", "foo")
|
||||
assert status == "ok"
|
||||
assert "api_key" in detail
|
||||
assert scheduler.body_store.read_config("calendar", "foo") == {}
|
||||
assert scheduler.body_store.read_config("nextcloud", "foo") == {}
|
||||
assert skill.config == {}
|
||||
assert any(e["kind"] == "config_cleared" for e in scheduler.trace.read())
|
||||
|
||||
@@ -343,7 +343,7 @@ def test_clear_skill_config(tmp_path):
|
||||
def test_regen_skill_rewrites_existing_body(tmp_path, monkeypatch):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.codegen = object()
|
||||
_add_skill(scheduler, "calendar", "foo")
|
||||
_add_skill(scheduler, "nextcloud", "foo")
|
||||
captured = {}
|
||||
|
||||
def fake_start(request, category, draft, repair_evidence=None, reason_kind="run_failure"):
|
||||
@@ -354,7 +354,7 @@ def test_regen_skill_rewrites_existing_body(tmp_path, monkeypatch):
|
||||
)
|
||||
|
||||
monkeypatch.setattr(scheduler, "_start_skill_write", fake_start)
|
||||
status, _ = scheduler.regen_skill("calendar", "foo", "it crashes")
|
||||
status, _ = scheduler.regen_skill("nextcloud", "foo", "it crashes")
|
||||
assert status == "running"
|
||||
assert captured["reason_kind"] == "manual"
|
||||
assert captured["repair_evidence"]["guidance"] == "it crashes"
|
||||
@@ -366,8 +366,8 @@ def test_regen_skill_rewrites_existing_body(tmp_path, monkeypatch):
|
||||
def test_regen_skill_stub_has_no_evidence(tmp_path, monkeypatch):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.codegen = object()
|
||||
scheduler.tree["calendar"] = [
|
||||
Skill(name="stub", category="calendar", description="d")
|
||||
scheduler.tree["nextcloud"] = [
|
||||
Skill(name="stub", category="nextcloud", description="d")
|
||||
]
|
||||
captured = {}
|
||||
|
||||
@@ -375,30 +375,30 @@ def test_regen_skill_stub_has_no_evidence(tmp_path, monkeypatch):
|
||||
captured.update(repair_evidence=repair_evidence, reason_kind=reason_kind)
|
||||
|
||||
monkeypatch.setattr(scheduler, "_start_skill_write", fake_start)
|
||||
status, _ = scheduler.regen_skill("calendar", "stub", "make it work")
|
||||
status, _ = scheduler.regen_skill("nextcloud", "stub", "make it work")
|
||||
assert status == "running"
|
||||
assert captured["repair_evidence"] is None
|
||||
|
||||
|
||||
def test_cancel_skill_build_discards_and_deletes(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
skill = _add_skill(scheduler, "calendar", "foo")
|
||||
skill = _add_skill(scheduler, "nextcloud", "foo")
|
||||
skill.writing = True
|
||||
scheduler._writes.append(
|
||||
SkillWrite(
|
||||
request=Request("build foo"),
|
||||
category="calendar",
|
||||
category="nextcloud",
|
||||
draft=SkillDraft(name="foo", description="d"),
|
||||
)
|
||||
)
|
||||
|
||||
status, detail = scheduler.cancel_skill_build("calendar", "foo")
|
||||
status, detail = scheduler.cancel_skill_build("nextcloud", "foo")
|
||||
assert status == "ok"
|
||||
assert "cancelled" in detail
|
||||
assert ("calendar", "foo") in scheduler._cancelled
|
||||
assert ("nextcloud", "foo") in scheduler._cancelled
|
||||
assert not any(w.draft.name == "foo" for w in scheduler._writes)
|
||||
assert all(s.name != "foo" for s in scheduler.tree["calendar"])
|
||||
assert not scheduler.body_store.dir("calendar", "foo").exists()
|
||||
assert all(s.name != "foo" for s in scheduler.tree["nextcloud"])
|
||||
assert not scheduler.body_store.dir("nextcloud", "foo").exists()
|
||||
assert any(
|
||||
e["kind"] == "skill_build_cancelled" for e in scheduler.trace.read()
|
||||
)
|
||||
@@ -408,12 +408,12 @@ def test_consume_cancelled_discards_queued_write(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
job = SkillWrite(
|
||||
request=Request("build foo"),
|
||||
category="calendar",
|
||||
category="nextcloud",
|
||||
draft=SkillDraft(name="foo", description="d"),
|
||||
)
|
||||
scheduler._cancelled.add(("calendar", "foo"))
|
||||
scheduler._cancelled.add(("nextcloud", "foo"))
|
||||
assert scheduler._consume_cancelled(job) is True
|
||||
assert ("calendar", "foo") not in scheduler._cancelled
|
||||
assert ("nextcloud", "foo") not in scheduler._cancelled
|
||||
assert any(
|
||||
e["kind"] == "skill_write_cancelled" for e in scheduler.trace.read()
|
||||
)
|
||||
@@ -424,57 +424,57 @@ def test_consume_cancelled_discards_queued_write(tmp_path):
|
||||
|
||||
def test_delete_skill_act_confirms_then_deletes(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
_add_skill(scheduler, "calendar", "foo")
|
||||
_add_skill(scheduler, "nextcloud", "foo")
|
||||
ctx = ActionContext(engine=None, config={}, admin=scheduler)
|
||||
request = Request("delete skill calendar.foo")
|
||||
request = Request("delete skill nextcloud.foo")
|
||||
|
||||
first = _delete_skill_act(ctx, request)
|
||||
assert first.needs_input and "confirm" in first.needs_input.lower()
|
||||
assert any(s.name == "foo" for s in scheduler.tree["calendar"])
|
||||
assert any(s.name == "foo" for s in scheduler.tree["nextcloud"])
|
||||
|
||||
request.user_input = "yes"
|
||||
second = _delete_skill_act(ctx, request)
|
||||
assert second.needs_input is None
|
||||
assert all(s.name != "foo" for s in scheduler.tree["calendar"])
|
||||
assert all(s.name != "foo" for s in scheduler.tree["nextcloud"])
|
||||
|
||||
|
||||
def test_delete_skill_act_asks_for_target_when_absent(tmp_path):
|
||||
"""A name-free request ("delete skill") asks for the target as an input
|
||||
variable, then confirms, then deletes."""
|
||||
scheduler = _scheduler(tmp_path)
|
||||
_add_skill(scheduler, "calendar", "foo")
|
||||
_add_skill(scheduler, "nextcloud", "foo")
|
||||
ctx = ActionContext(engine=None, config={}, admin=scheduler)
|
||||
request = Request("delete skill")
|
||||
|
||||
first = _delete_skill_act(ctx, request)
|
||||
assert first.needs_input and "which skill" in first.needs_input.lower()
|
||||
|
||||
request.user_input = "calendar.foo"
|
||||
request.user_input = "nextcloud.foo"
|
||||
second = _delete_skill_act(ctx, request)
|
||||
assert second.needs_input and "confirm" in second.needs_input.lower()
|
||||
|
||||
request.user_input = "yes"
|
||||
third = _delete_skill_act(ctx, request)
|
||||
assert third.needs_input is None
|
||||
assert all(s.name != "foo" for s in scheduler.tree["calendar"])
|
||||
assert all(s.name != "foo" for s in scheduler.tree["nextcloud"])
|
||||
|
||||
|
||||
def test_delete_skill_act_declined_keeps_skill(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
_add_skill(scheduler, "calendar", "foo")
|
||||
_add_skill(scheduler, "nextcloud", "foo")
|
||||
ctx = ActionContext(engine=None, config={}, admin=scheduler)
|
||||
request = Request("delete skill calendar.foo")
|
||||
request = Request("delete skill nextcloud.foo")
|
||||
_delete_skill_act(ctx, request)
|
||||
request.user_input = "no"
|
||||
result = _delete_skill_act(ctx, request)
|
||||
assert result.needs_input is None
|
||||
assert "cancelled" in result.action_log
|
||||
assert any(s.name == "foo" for s in scheduler.tree["calendar"])
|
||||
assert any(s.name == "foo" for s in scheduler.tree["nextcloud"])
|
||||
|
||||
|
||||
def test_cancel_build_act_targets_writing_skill(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
skill = _add_skill(scheduler, "calendar", "foo")
|
||||
skill = _add_skill(scheduler, "nextcloud", "foo")
|
||||
skill.writing = True
|
||||
ctx = ActionContext(engine=None, config={}, admin=scheduler)
|
||||
|
||||
@@ -484,12 +484,12 @@ def test_cancel_build_act_targets_writing_skill(tmp_path):
|
||||
request.user_input = "yes"
|
||||
second = _cancel_build_act(ctx, request)
|
||||
assert second.needs_input is None
|
||||
assert all(s.name != "foo" for s in scheduler.tree["calendar"])
|
||||
assert all(s.name != "foo" for s in scheduler.tree["nextcloud"])
|
||||
|
||||
|
||||
def test_cancel_build_act_reports_when_nothing_writing(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
_add_skill(scheduler, "calendar", "foo")
|
||||
_add_skill(scheduler, "nextcloud", "foo")
|
||||
ctx = ActionContext(engine=None, config={}, admin=scheduler)
|
||||
result = _cancel_build_act(ctx, Request("cancel the skill build"))
|
||||
assert result.needs_input is None
|
||||
|
||||
@@ -30,15 +30,16 @@ def seed_id(seed: Path) -> str:
|
||||
|
||||
def test_expected_seeds_exist():
|
||||
ids = {seed_id(seed) for seed in SEED_DIRS}
|
||||
assert "calendar.next_event" in ids
|
||||
assert "calendar.create_event" in ids
|
||||
assert "nextcloud.next_event" in ids
|
||||
assert "nextcloud.create_event" in ids
|
||||
assert "simplex.next_message" in ids
|
||||
assert "simplex.send_message" in ids
|
||||
assert "simplex.connect_link" in ids
|
||||
assert "time.now" in ids
|
||||
assert "time.date" in ids
|
||||
assert "time.set_timer" in ids
|
||||
assert "time.set_alarm" in ids
|
||||
assert "productivity_management.create_nextcloud_task" in ids
|
||||
assert "nextcloud.create_task" in ids
|
||||
|
||||
|
||||
@pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS])
|
||||
|
||||
+19
-17
@@ -168,7 +168,7 @@ def test_run_summary_is_deterministic_and_surfaces_action_log(tmp_path):
|
||||
|
||||
skill = Skill(
|
||||
name="next_event",
|
||||
category="calendar",
|
||||
category="nextcloud",
|
||||
description="Report the next event.",
|
||||
act=act,
|
||||
)
|
||||
@@ -177,7 +177,7 @@ def test_run_summary_is_deterministic_and_surfaces_action_log(tmp_path):
|
||||
assert result.kind == "ran"
|
||||
|
||||
expected = (
|
||||
"calendar.next_event: ok — Next event on 'personal': Team sync — 2026-09-27 10:00 CEST"
|
||||
"nextcloud.next_event: ok — Next event on 'personal': Team sync — 2026-09-27 10:00 CEST"
|
||||
)
|
||||
assessed = [e for e in scheduler.trace.read() if e["kind"] == "assessed"]
|
||||
assert assessed, "the run must be traced"
|
||||
@@ -433,13 +433,13 @@ def test_merge_seed_store_loads_skill_with_runtime_config(tmp_path):
|
||||
the runtime store, never in the seed folder."""
|
||||
seed_store = SkillStore(str(tmp_path / "seeds"))
|
||||
config_store = SkillStore(str(tmp_path / "skills"))
|
||||
_write_seed(seed_store, "calendar", "probe", description="Probe a service.")
|
||||
config_store.write_config("calendar", "probe", {"probe_url": "https://example.test"})
|
||||
_write_seed(seed_store, "nextcloud", "probe", description="Probe a service.")
|
||||
config_store.write_config("nextcloud", "probe", {"probe_url": "https://example.test"})
|
||||
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
loaded = merge_seed_store(tree, seed_store, config_store)
|
||||
assert loaded == 1
|
||||
skill = tree["calendar"][0]
|
||||
skill = tree["nextcloud"][0]
|
||||
assert skill.status == "ready"
|
||||
assert skill.description == "Probe a service."
|
||||
assert skill.contract == {"probe_url": "Where to probe."}
|
||||
@@ -450,16 +450,16 @@ def test_merge_seed_store_loads_skill_with_runtime_config(tmp_path):
|
||||
def test_merge_seed_store_falls_back_to_name_and_body_store_wins(tmp_path):
|
||||
seed_store = SkillStore(str(tmp_path / "seeds"))
|
||||
body_store = SkillStore(str(tmp_path / "skills"))
|
||||
_write_seed(seed_store, "calendar", "probe")
|
||||
_write_seed(seed_store, "nextcloud", "probe")
|
||||
|
||||
tree = build_tree(build_skills({"skills": {}}))
|
||||
merge_seed_store(tree, seed_store, body_store)
|
||||
assert tree["calendar"][0].description == "probe"
|
||||
assert tree["nextcloud"][0].description == "probe"
|
||||
|
||||
body_store.write_body("calendar", "probe", GOOD_BODY)
|
||||
body_store.write_body("nextcloud", "probe", GOOD_BODY)
|
||||
merge_skill_store(tree, body_store, {})
|
||||
assert tree["calendar"][0].description == "probe", "the generated body replaces the seed"
|
||||
assert len(tree["calendar"]) == 1
|
||||
assert tree["nextcloud"][0].description == "probe", "the generated body replaces the seed"
|
||||
assert len(tree["nextcloud"]) == 1
|
||||
|
||||
|
||||
def test_scheduler_loads_committed_seed_skills(tmp_path):
|
||||
@@ -477,13 +477,13 @@ def test_scheduler_loads_committed_seed_skills(tmp_path):
|
||||
},
|
||||
trace=TraceLog(str(tmp_path / "runs.jsonl")),
|
||||
)
|
||||
calendar = scheduler.tree["calendar"]
|
||||
assert [s.name for s in calendar] == ["create_event", "next_event"]
|
||||
next_event = next(s for s in calendar if s.name == "next_event")
|
||||
nextcloud = scheduler.tree["nextcloud"]
|
||||
assert [s.name for s in nextcloud] == ["create_event", "create_task", "next_event"]
|
||||
next_event = next(s for s in nextcloud if s.name == "next_event")
|
||||
assert next_event.description.startswith("Report the next")
|
||||
assert next_event.status == "ready"
|
||||
assert next_event.integration["transport"] == "caldav"
|
||||
create_event = next(s for s in calendar if s.name == "create_event")
|
||||
create_event = next(s for s in nextcloud if s.name == "create_event")
|
||||
assert create_event.description.startswith("Create a calendar event")
|
||||
assert create_event.integration["transport"] == "caldav"
|
||||
|
||||
@@ -539,9 +539,11 @@ def test_committed_seeds_load_from_a_foreign_cwd(tmp_path, monkeypatch):
|
||||
assert [s.name for s in scheduler.tree["simplex"]] == [
|
||||
"connect_link",
|
||||
"next_message",
|
||||
"send_message",
|
||||
]
|
||||
assert [s.name for s in scheduler.tree["calendar"]] == [
|
||||
assert [s.name for s in scheduler.tree["nextcloud"]] == [
|
||||
"create_event",
|
||||
"create_task",
|
||||
"next_event",
|
||||
]
|
||||
|
||||
@@ -828,7 +830,7 @@ def test_confirm_category_fit_threshold(tmp_path):
|
||||
engine = ScriptedEngine(choices={"Does the scope": "covers"})
|
||||
assert (
|
||||
confirm_category_fit(
|
||||
engine, log, trace, Request("check my calendar"), "calendar", "Calendars.", tau=0.5
|
||||
engine, log, trace, Request("check my calendar"), "nextcloud", "Nextcloud.", tau=0.5
|
||||
)
|
||||
is True
|
||||
)
|
||||
@@ -837,7 +839,7 @@ def test_confirm_category_fit_threshold(tmp_path):
|
||||
engine = ScriptedEngine(choices={"Does the scope": "none"})
|
||||
assert (
|
||||
confirm_category_fit(
|
||||
engine, log, trace, Request("order pizza"), "calendar", "Calendars.", tau=0.5
|
||||
engine, log, trace, Request("order pizza"), "nextcloud", "Nextcloud.", tau=0.5
|
||||
)
|
||||
is False
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user