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.
This commit is contained in:
1 parent
63c5fc9903
commit
e81e6c3a6b
10 files changed
+286
-84
No files matched your search
@@ -586,14 +586,14 @@ CLI, unit tests (24) + integration tests (2).
|
|||||||
loads them into every tree at startup; recorded config (credentials collected
|
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
|
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 never holds secrets, and a generated body with the same name replaces the
|
||||||
seed. `calendar.next_event` (Nextcloud CalDAV, recurring events expanded
|
seed. `calendar.create_event` is the authoritative worked example (CalDAV PUT;
|
||||||
server-side) is the reference read seed and `calendar.create_event` (CalDAV
|
derives the title/date/time from the query, asks for missing fields and
|
||||||
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
|
||||||
resumes, resolves the target calendar against the configured default) is the
|
calendars — a strong winner is used, otherwise the configured default);
|
||||||
reference write seed; `simplex.next_message` (read via the
|
`calendar.next_event` is the read counterpart (Nextcloud CalDAV, recurring
|
||||||
forwarding bridge) and `simplex.connect_link` (show/create the forwarding
|
events expanded server-side); `simplex.next_message` (read via the forwarding
|
||||||
bot's contact link) are the messenger seeds; `tests/test_seed_skills.py` keeps
|
bridge) and `simplex.connect_link` (show/create the forwarding bot's contact
|
||||||
them honest.
|
link) are the messenger seeds; `tests/test_seed_skills.py` keeps them honest.
|
||||||
- **Contract provenance.** Each authored body records the CODEGEN.md revision it
|
- **Contract provenance.** Each authored body records the CODEGEN.md revision it
|
||||||
was written against. `skill_contract_ref()` (`codegen.py`) returns
|
was written against. `skill_contract_ref()` (`codegen.py`) returns
|
||||||
`{"ref", "dirty"}`: `ref` is the short git commit sha the contract was read
|
`{"ref", "dirty"}`: `ref` is the short git commit sha the contract was read
|
||||||
|
|||||||
+11
-3
@@ -21,6 +21,11 @@ A skill is three things:
|
|||||||
talks to and how) and the `CONTRACT` constant (the values the runner must
|
talks to and how) and the `CONTRACT` constant (the values the runner must
|
||||||
provide).
|
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
|
## Manifest schema
|
||||||
|
|
||||||
Registered in `data/categories.json` (and mirrored in the running tree). Fields:
|
Registered in `data/categories.json` (and mirrored in the running tree). Fields:
|
||||||
@@ -181,6 +186,9 @@ return ActionResult(..., decisions=[(decision, result)])
|
|||||||
`ActionResult.decisions` so the choice is logged with the run outcome.
|
`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
|
- Include any configured default (a value read from `ctx.config`) as one of the
|
||||||
options, so the request can override the stored default.
|
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)
|
### Producing the result (output)
|
||||||
|
|
||||||
@@ -302,7 +310,7 @@ Rules:
|
|||||||
- **Resolve the recipient/target with a SemIf sub-decision.** When more than one
|
- **Resolve the recipient/target with a SemIf sub-decision.** When more than one
|
||||||
conversation or target is relevant, resolve which one with a
|
conversation or target is relevant, resolve which one with a
|
||||||
`ctx.engine.call(...)` sub-decision over the catalog's list endpoint (e.g.
|
`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
|
calendar. Use the catalog's default config var as the configured option when
|
||||||
the request does not already make it clear.
|
the request does not already make it clear.
|
||||||
- **Sending requires user intent.** Send only because the request (or the
|
- **Sending requires user intent.** Send only because the request (or the
|
||||||
@@ -321,8 +329,8 @@ Rules:
|
|||||||
- Single purpose, single file, single module.
|
- Single purpose, single file, single module.
|
||||||
- Avoid duplicating an existing skill in the same category.
|
- Avoid duplicating an existing skill in the same category.
|
||||||
- `act` resolves ambiguity (arguments, recipients, targets) with SemIf
|
- `act` resolves ambiguity (arguments, recipients, targets) with SemIf
|
||||||
sub-decisions, mirroring how `calendar.next_event` resolves which calendar
|
sub-decisions, mirroring how `calendar.create_event` resolves which calendar
|
||||||
to read.
|
to write to.
|
||||||
- `act` performs the concrete real action and writes a human-readable
|
- `act` performs the concrete real action and writes a human-readable
|
||||||
`action_log` that the SemIf assessment step can judge. Include what the
|
`action_log` that the SemIf assessment step can judge. Include what the
|
||||||
service actually returned.
|
service actually returned.
|
||||||
|
|||||||
@@ -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.
|
- **Messenger command gateway (SimpleX)** — take commands and reply over DM.
|
||||||
- **Standalone bridge services** — a token-guarded localhost HTTP layer in front
|
- **Standalone bridge services** — a token-guarded localhost HTTP layer in front
|
||||||
of third-party systems, so generated bodies never speak native protocols.
|
of third-party systems, so generated bodies never speak native protocols.
|
||||||
- **Seeds** — shipped real starter skills: `calendar.next_event` (Nextcloud
|
- **Seeds** — shipped real starter skills: `calendar.create_event` (the
|
||||||
CalDAV) and `simplex.next_message` / `simplex.connect_link`.
|
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.
|
- **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
|
- **Stdlib-only core** — SemIf/llama.cpp are lazy imports, so the package stays
|
||||||
importable and testable without the heavy engine installed.
|
importable and testable without the heavy engine installed.
|
||||||
@@ -675,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
|
tree at startup; recorded config is written to the runtime store, so the
|
||||||
committed seed never holds secrets.
|
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
|
- `calendar.next_event` — next upcoming event from Nextcloud CalDAV (recurring
|
||||||
events expanded server-side); config vars `nextcloud_url`,
|
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
|
- `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.
|
- `simplex.connect_link` — show/create the forwarding bot's contact link.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -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_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_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)."
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,20 @@
|
|||||||
"""Report the next upcoming event on the user's Nextcloud calendar.
|
"""Report the next upcoming event on the user's Nextcloud calendar.
|
||||||
|
|
||||||
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
|
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
|
||||||
details come from `ctx.config` (`nextcloud_url`, `nextcloud_username`,
|
details and the default calendar come from `ctx.config` (`nextcloud_url`,
|
||||||
`nextcloud_app_password`). `act` discovers the user's calendars over PROPFIND
|
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`).
|
||||||
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.
|
|
||||||
|
|
||||||
Recurring events are expanded by the server (`<c:expand>`), so no RRULE
|
`act` discovers the user's calendars over PROPFIND and resolves which one the
|
||||||
engine lives here; a server that ignores expansion is reported honestly
|
request means with a single SemIf choice over every owned calendar (state = the
|
||||||
rather than guessed at.
|
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
|
from __future__ import annotations
|
||||||
@@ -33,6 +38,7 @@ INTEGRATION = {
|
|||||||
"nextcloud_url",
|
"nextcloud_url",
|
||||||
"nextcloud_username",
|
"nextcloud_username",
|
||||||
"nextcloud_app_password",
|
"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_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_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).",
|
||||||
}
|
}
|
||||||
|
|
||||||
DAV = "DAV:"
|
DAV = "DAV:"
|
||||||
CALDAV = "urn:ietf:params:xml:ns:caldav"
|
CALDAV = "urn:ietf:params:xml:ns:caldav"
|
||||||
LOOKAHEAD_DAYS = 60
|
LOOKAHEAD_DAYS = 60
|
||||||
TIMEOUT_SECONDS = 30
|
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 = (
|
PROPFIND_BODY = (
|
||||||
'<?xml version="1.0" encoding="utf-8"?>'
|
'<?xml version="1.0" encoding="utf-8"?>'
|
||||||
@@ -66,6 +76,11 @@ class CalDavError(Exception):
|
|||||||
"""A real failure talking to the calendar service."""
|
"""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 ----
|
# ---- transport ----
|
||||||
|
|
||||||
|
|
||||||
@@ -182,6 +197,43 @@ def _calendar_payloads(body):
|
|||||||
return payloads
|
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 ----
|
# ---- iCalendar parsing ----
|
||||||
|
|
||||||
|
|
||||||
@@ -316,28 +368,18 @@ def act(ctx, request):
|
|||||||
action_log="calendar.next_event: calendar discovery failed: no calendars found",
|
action_log="calendar.next_event: calendar discovery failed: no calendars found",
|
||||||
new_state=request.text,
|
new_state=request.text,
|
||||||
)
|
)
|
||||||
|
|
||||||
decisions = []
|
decisions = []
|
||||||
if len(calendars) == 1:
|
calendar = _resolve_calendar(ctx, request, calendars, decisions)
|
||||||
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
|
|
||||||
if not calendar:
|
if not calendar:
|
||||||
return ActionResult(
|
return ActionResult(
|
||||||
action_log="calendar.next_event aborted: no calendar resolved.",
|
action_log="calendar.next_event aborted: no calendar resolved.",
|
||||||
new_state=request.text,
|
new_state=request.text,
|
||||||
decisions=decisions,
|
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_start = now - timedelta(days=1)
|
||||||
window_end = now + timedelta(days=LOOKAHEAD_DAYS)
|
window_end = now + timedelta(days=LOOKAHEAD_DAYS)
|
||||||
try:
|
try:
|
||||||
@@ -355,6 +397,7 @@ def act(ctx, request):
|
|||||||
new_state=request.text,
|
new_state=request.text,
|
||||||
decisions=decisions,
|
decisions=decisions,
|
||||||
)
|
)
|
||||||
|
|
||||||
next_event = _pick_next(events, now)
|
next_event = _pick_next(events, now)
|
||||||
if next_event is None:
|
if next_event is None:
|
||||||
message = (
|
message = (
|
||||||
@@ -362,6 +405,7 @@ def act(ctx, request):
|
|||||||
f"{window_end.strftime('%Y-%m-%d')}."
|
f"{window_end.strftime('%Y-%m-%d')}."
|
||||||
)
|
)
|
||||||
return ActionResult(action_log=message, new_state=message, decisions=decisions)
|
return ActionResult(action_log=message, new_state=message, decisions=decisions)
|
||||||
|
|
||||||
summary = next_event.get("summary") or "(no title)"
|
summary = next_event.get("summary") or "(no title)"
|
||||||
when = _format_when(next_event)
|
when = _format_when(next_event)
|
||||||
message = f"Next event on {calendar!r}: {summary} — {when}"
|
message = f"Next event on {calendar!r}: {summary} — {when}"
|
||||||
|
|||||||
@@ -3,9 +3,10 @@
|
|||||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||||
http.server plays the Nextcloud CalDAV endpoint. This proves the body builds
|
http.server plays the Nextcloud CalDAV endpoint. This proves the body builds
|
||||||
real CalDAV requests, discovers calendars, resolves the calendar through a
|
real CalDAV requests, discovers calendars, resolves the calendar through a
|
||||||
SemIf sub-decision, parses expanded iCalendar events, and fails honestly when
|
SemIf sub-decision (a strong winner is used, otherwise the configured default,
|
||||||
the service errors. It does NOT prove the live integration — only a real run
|
otherwise the weak winner), parses expanded iCalendar events, and fails honestly
|
||||||
against the user's Nextcloud does.
|
when the service errors. It does NOT prove the live integration — only a real
|
||||||
|
run against the user's Nextcloud does.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
@@ -49,15 +50,24 @@ def build_ics():
|
|||||||
|
|
||||||
|
|
||||||
class FakeEngine:
|
class FakeEngine:
|
||||||
"""Test-only engine: picks the requested option id, else the first."""
|
"""Test-only engine.
|
||||||
|
|
||||||
def __init__(self, pick=None):
|
By default it picks the requested option id (else the first) with full
|
||||||
|
confidence. Pass `probs` (a mapping of option id -> probability) to script an
|
||||||
|
arbitrary distribution, e.g. a near-tie that must fall back to the default.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, pick=None, probs=None):
|
||||||
self.pick = pick
|
self.pick = pick
|
||||||
|
self.probs = probs
|
||||||
self.decisions = []
|
self.decisions = []
|
||||||
|
|
||||||
def call(self, decision):
|
def call(self, decision):
|
||||||
self.decisions.append(decision)
|
self.decisions.append(decision)
|
||||||
option_ids = [option.id for option in decision.options]
|
option_ids = [option.id for option in decision.options]
|
||||||
|
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]
|
chosen = self.pick if self.pick in option_ids else option_ids[0]
|
||||||
probabilities = [
|
probabilities = [
|
||||||
1.0 if option_id == chosen else 0.0 for option_id in option_ids
|
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]}"
|
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
||||||
|
|
||||||
|
|
||||||
def fixture_config(url):
|
def fixture_config(url, default="personal"):
|
||||||
return {
|
return {
|
||||||
"nextcloud_url": url,
|
"nextcloud_url": url,
|
||||||
"nextcloud_username": "testuser",
|
"nextcloud_username": "testuser",
|
||||||
"nextcloud_app_password": "app-pw",
|
"nextcloud_app_password": "app-pw",
|
||||||
|
"nextcloud_default_calendar": default,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -149,6 +160,7 @@ def main():
|
|||||||
global ICS
|
global ICS
|
||||||
ICS = build_ics()
|
ICS = build_ics()
|
||||||
|
|
||||||
|
# A strong winner is used even though a default is configured.
|
||||||
server, handler, url = start_server()
|
server, handler, url = start_server()
|
||||||
try:
|
try:
|
||||||
engine = FakeEngine(pick="work")
|
engine = FakeEngine(pick="work")
|
||||||
@@ -157,6 +169,10 @@ def main():
|
|||||||
action = skill.act(ctx, request)
|
action = skill.act(ctx, request)
|
||||||
assert len(action.decisions) == 1, "act must log the calendar choice"
|
assert len(action.decisions) == 1, "act must log the calendar choice"
|
||||||
assert len(engine.decisions) == 1
|
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 "Team sync" in action.action_log, action.action_log
|
||||||
assert action.new_state, "act must set a new state"
|
assert action.new_state, "act must set a new state"
|
||||||
|
|
||||||
@@ -174,6 +190,36 @@ def main():
|
|||||||
server.shutdown()
|
server.shutdown()
|
||||||
server.server_close()
|
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)
|
server, handler, url = start_server(calendar_count=1)
|
||||||
try:
|
try:
|
||||||
engine = FakeEngine()
|
engine = FakeEngine()
|
||||||
@@ -188,6 +234,7 @@ def main():
|
|||||||
server.shutdown()
|
server.shutdown()
|
||||||
server.server_close()
|
server.server_close()
|
||||||
|
|
||||||
|
# A failing REPORT is reported honestly.
|
||||||
server, handler, url = start_server(report_status=500)
|
server, handler, url = start_server(report_status=500)
|
||||||
try:
|
try:
|
||||||
engine = FakeEngine(pick="personal")
|
engine = FakeEngine(pick="personal")
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
"""Show the SimpleX contact link others use to connect to this agent.
|
"""Show the SimpleX contact link others use to connect to this agent.
|
||||||
|
|
||||||
Real integration: the standalone SimpleX forwarding bridge
|
Real integration: the standalone SimpleX forwarding bridge
|
||||||
(`simplex_bridge_url`). The bridge's own connection to the `simplex-chat`
|
(`simplex_bridge_url`, `simplex_bridge_token`). The bridge's own connection to
|
||||||
daemon is the only thing that can read (or create) the forwarding bot's *user
|
the `simplex-chat` daemon is the only thing that can read (or create) the
|
||||||
contact address*; this body asks the bridge for it and reports the link
|
forwarding bot's *user contact address*; this body asks the bridge for it and
|
||||||
honestly. It never opens a WebSocket to the daemon and never invents a link: if
|
reports the link honestly. It never opens a WebSocket to the daemon and never
|
||||||
the bridge is not running or has no address, it says so.
|
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
|
`act` health-checks the bridge, then `GET /address` shows the existing link and
|
||||||
`{short_link, full_link, created}`.
|
creates one on first call, returning `{short_link, full_link, created}`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -37,6 +37,9 @@ class BridgeError(Exception):
|
|||||||
"""The SimpleX forwarding bridge is unreachable or returned an error."""
|
"""The SimpleX forwarding bridge is unreachable or returned an error."""
|
||||||
|
|
||||||
|
|
||||||
|
# ---- transport ----
|
||||||
|
|
||||||
|
|
||||||
def _base(ctx):
|
def _base(ctx):
|
||||||
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
|
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
|
||||||
if not url:
|
if not url:
|
||||||
@@ -63,6 +66,9 @@ def _get(ctx, path):
|
|||||||
raise BridgeError(f"GET {path}: {exc}") from exc
|
raise BridgeError(f"GET {path}: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
# ---- skill phases ----
|
||||||
|
|
||||||
|
|
||||||
def act(ctx, request):
|
def act(ctx, request):
|
||||||
try:
|
try:
|
||||||
payload = _get(ctx, "/health")
|
payload = _get(ctx, "/health")
|
||||||
|
|||||||
@@ -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_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."
|
||||||
}
|
}
|
||||||
@@ -3,9 +3,11 @@
|
|||||||
Real integration: the standalone SimpleX forwarding bridge
|
Real integration: the standalone SimpleX forwarding bridge
|
||||||
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends.
|
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends.
|
||||||
`act` peeks that inbox, finds which conversations have unread messages, and
|
`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
|
resolves which one to read with a SemIf choice over them (state = the user
|
||||||
(honoring a configured default contact); it then pops and reports the oldest
|
query): a strong winner (probability >= `CONTACT_WINNER_TAU`) is used, otherwise
|
||||||
unread message for that conversation.
|
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
|
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
|
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 = {
|
INTEGRATION = {
|
||||||
"service": "simplex",
|
"service": "simplex",
|
||||||
"transport": "http",
|
"transport": "http",
|
||||||
"config_vars": ["simplex_bridge_url", "simplex_bridge_token"],
|
"config_vars": [
|
||||||
|
"simplex_bridge_url",
|
||||||
|
"simplex_bridge_token",
|
||||||
|
"simplex_default_contact",
|
||||||
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
CONTRACT = {
|
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_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.",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
TIMEOUT_SECONDS = 20
|
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):
|
class BridgeError(Exception):
|
||||||
"""The SimpleX forwarding bridge is unreachable or returned an error."""
|
"""The SimpleX forwarding bridge is unreachable or returned an error."""
|
||||||
|
|
||||||
|
|
||||||
|
# ---- transport ----
|
||||||
|
|
||||||
|
|
||||||
def _base(ctx):
|
def _base(ctx):
|
||||||
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
|
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
|
||||||
if not url:
|
if not url:
|
||||||
@@ -67,6 +79,9 @@ def _get(ctx, path):
|
|||||||
raise BridgeError(f"GET {path}: {exc}") from exc
|
raise BridgeError(f"GET {path}: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
# ---- conversation resolution ----
|
||||||
|
|
||||||
|
|
||||||
def _senders(messages):
|
def _senders(messages):
|
||||||
"""Distinct conversations with buffered messages, in arrival order."""
|
"""Distinct conversations with buffered messages, in arrival order."""
|
||||||
senders = []
|
senders = []
|
||||||
@@ -82,16 +97,45 @@ def _senders(messages):
|
|||||||
return senders
|
return senders
|
||||||
|
|
||||||
|
|
||||||
def _match_default(senders, default):
|
def _default_sender(ctx, senders):
|
||||||
default = str(default or "").strip()
|
"""The configured default contact, if it has unread messages."""
|
||||||
|
default = str(ctx.config.get("simplex_default_contact", "") or "").strip()
|
||||||
if not default:
|
if not default:
|
||||||
return None
|
return None
|
||||||
for sender in senders:
|
for sender in senders:
|
||||||
if sender["id"] == default or sender["display_name"] == default:
|
if sender["id"] == default or sender["display_name"] == default:
|
||||||
return sender["id"]
|
return sender
|
||||||
return None
|
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):
|
def act(ctx, request):
|
||||||
try:
|
try:
|
||||||
payload = _get(ctx, "/inbox")
|
payload = _get(ctx, "/inbox")
|
||||||
@@ -104,18 +148,7 @@ def act(ctx, request):
|
|||||||
new_state="no unread SimpleX messages",
|
new_state="no unread SimpleX messages",
|
||||||
)
|
)
|
||||||
decisions = []
|
decisions = []
|
||||||
contact = _match_default(senders, ctx.config.get("simplex_default_contact", ""))
|
contact = _resolve_contact(ctx, request, senders, decisions)
|
||||||
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"]
|
|
||||||
try:
|
try:
|
||||||
payload = _get(
|
payload = _get(
|
||||||
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
|
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
|
||||||
|
|||||||
@@ -2,10 +2,11 @@
|
|||||||
|
|
||||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||||
http.server plays the standalone SimpleX forwarding bridge. This proves the body
|
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
|
peeks the inbox, resolves the conversation through a SemIf sub-decision (a
|
||||||
configured default), pops the real `next` message, and fails honestly when the
|
strong winner is used, otherwise the configured default, otherwise the weak
|
||||||
bridge is unreachable. It does NOT prove the live integration — only a real run
|
winner), pops the real `next` message, and fails honestly when the bridge is
|
||||||
against the bridge and a real contact does.
|
unreachable. It does NOT prove the live integration — only a real run against
|
||||||
|
the bridge and a real contact does.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
@@ -21,15 +22,24 @@ import skill
|
|||||||
|
|
||||||
|
|
||||||
class FakeEngine:
|
class FakeEngine:
|
||||||
"""Test-only engine: picks the requested option id, else the first."""
|
"""Test-only engine.
|
||||||
|
|
||||||
def __init__(self, pick=None):
|
By default it picks the requested option id (else the first) with full
|
||||||
|
confidence. Pass `probs` (a mapping of option id -> probability) to script an
|
||||||
|
arbitrary distribution, e.g. a near-tie that must fall back to the default.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, pick=None, probs=None):
|
||||||
self.pick = pick
|
self.pick = pick
|
||||||
|
self.probs = probs
|
||||||
self.decisions = []
|
self.decisions = []
|
||||||
|
|
||||||
def call(self, decision):
|
def call(self, decision):
|
||||||
self.decisions.append(decision)
|
self.decisions.append(decision)
|
||||||
option_ids = [option.id for option in decision.options]
|
option_ids = [option.id for option in decision.options]
|
||||||
|
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]
|
chosen = self.pick if self.pick in option_ids else option_ids[0]
|
||||||
probabilities = [
|
probabilities = [
|
||||||
1.0 if option_id == chosen else 0.0 for option_id in option_ids
|
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()
|
server.server_close()
|
||||||
|
|
||||||
|
|
||||||
def test_default_contact_skips_decision():
|
def test_strong_winner_overrides_default_contact():
|
||||||
server, handler, url = start_server(
|
server, handler, url = start_server(
|
||||||
[
|
[
|
||||||
message("m1", "4", "Alice", "hello there"),
|
message("m1", "4", "Alice", "hello there"),
|
||||||
@@ -137,13 +147,55 @@ def test_default_contact_skips_decision():
|
|||||||
]
|
]
|
||||||
)
|
)
|
||||||
try:
|
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"))
|
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
|
||||||
request = Request("read my next simplex message")
|
request = Request("read my next simplex message")
|
||||||
action = skill.act(ctx, request)
|
action = skill.act(ctx, request)
|
||||||
assert engine.decisions == [], "a configured default needs no SemIf decision"
|
assert len(engine.decisions) == 1
|
||||||
assert "Alice" in action.action_log, action.action_log
|
|
||||||
assert handler.requests[1] == "/inbox/next?contact=4", handler.requests
|
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)
|
print(action.action_log)
|
||||||
finally:
|
finally:
|
||||||
server.shutdown()
|
server.shutdown()
|
||||||
@@ -207,7 +259,9 @@ def test_auth_token_is_sent_when_configured():
|
|||||||
|
|
||||||
def main():
|
def main():
|
||||||
test_multiple_senders_uses_semif_decision()
|
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_single_sender_needs_no_decision()
|
||||||
test_empty_inbox_is_reported_honestly()
|
test_empty_inbox_is_reported_honestly()
|
||||||
test_unreachable_bridge_fails_honestly()
|
test_unreachable_bridge_fails_honestly()
|
||||||
|
|||||||
Reference in new issue
Block a user