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
+294
-92
No files matched your search
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
|
||||
"nextcloud_username": "The Nextcloud username whose calendars are read.",
|
||||
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off."
|
||||
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
|
||||
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar)."
|
||||
}
|
||||
@@ -1,15 +1,20 @@
|
||||
"""Report the next upcoming event on the user's Nextcloud calendar.
|
||||
|
||||
Real integration: CalDAV against the user's Nextcloud (SabreDAV). Connection
|
||||
details come from `ctx.config` (`nextcloud_url`, `nextcloud_username`,
|
||||
`nextcloud_app_password`). `act` discovers the user's calendars over PROPFIND
|
||||
and resolves which one the request means with a SemIf sub-decision when there
|
||||
is more than one, then issues a `calendar-query` REPORT with server-side
|
||||
recurrence expansion and reports the earliest instance that has not ended yet.
|
||||
details and the default calendar come from `ctx.config` (`nextcloud_url`,
|
||||
`nextcloud_username`, `nextcloud_app_password`, `nextcloud_default_calendar`).
|
||||
|
||||
Recurring events are expanded by the server (`<c:expand>`), so no RRULE
|
||||
engine lives here; a server that ignores expansion is reported honestly
|
||||
rather than guessed at.
|
||||
`act` discovers the user's calendars over PROPFIND and resolves which one the
|
||||
request means with a single SemIf choice over every owned calendar (state = the
|
||||
user query): a strong winner (probability >= `CALENDAR_WINNER_TAU`) is used,
|
||||
otherwise the configured default calendar is used; with no configured default
|
||||
the weak winner stands. It then issues a `calendar-query` REPORT with
|
||||
server-side recurrence expansion and reports the earliest instance that has not
|
||||
ended yet.
|
||||
|
||||
Recurring events are expanded by the server (`<c:expand>`), so no RRULE engine
|
||||
lives here; a server that ignores expansion is reported honestly rather than
|
||||
guessed at.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -33,6 +38,7 @@ INTEGRATION = {
|
||||
"nextcloud_url",
|
||||
"nextcloud_username",
|
||||
"nextcloud_app_password",
|
||||
"nextcloud_default_calendar",
|
||||
],
|
||||
}
|
||||
|
||||
@@ -40,12 +46,16 @@ CONTRACT = {
|
||||
"nextcloud_url": "Base URL of the Nextcloud instance, e.g. https://cloud.example.com (no path, no trailing slash needed).",
|
||||
"nextcloud_username": "The Nextcloud username whose calendars are read.",
|
||||
"nextcloud_app_password": "A Nextcloud app password (Settings > Security > Devices & sessions) used for CalDAV Basic auth; the account password only works when two-factor auth is off.",
|
||||
"nextcloud_default_calendar": "Name of the calendar read by default when the request names none, e.g. personal (a request may still name another calendar).",
|
||||
}
|
||||
|
||||
DAV = "DAV:"
|
||||
CALDAV = "urn:ietf:params:xml:ns:caldav"
|
||||
LOOKAHEAD_DAYS = 60
|
||||
TIMEOUT_SECONDS = 30
|
||||
# A SemIf probability at or above this counts as a "strong winner" for the
|
||||
# target calendar; below it the configured default calendar is used instead.
|
||||
CALENDAR_WINNER_TAU = 0.6
|
||||
|
||||
PROPFIND_BODY = (
|
||||
'<?xml version="1.0" encoding="utf-8"?>'
|
||||
@@ -66,6 +76,11 @@ class CalDavError(Exception):
|
||||
"""A real failure talking to the calendar service."""
|
||||
|
||||
|
||||
def _now():
|
||||
"""Current local time (aware). A test seam; the body never freezes time."""
|
||||
return datetime.now().astimezone()
|
||||
|
||||
|
||||
# ---- transport ----
|
||||
|
||||
|
||||
@@ -182,6 +197,43 @@ def _calendar_payloads(body):
|
||||
return payloads
|
||||
|
||||
|
||||
# ---- calendar resolution ----
|
||||
|
||||
|
||||
def _default_calendar(ctx, calendars):
|
||||
"""The configured default calendar, if it is one of the account's."""
|
||||
default_name = str(ctx.config.get("nextcloud_default_calendar", "") or "").strip().lower()
|
||||
for calendar in calendars:
|
||||
if default_name and default_name in (calendar["name"].lower(), calendar["label"].lower()):
|
||||
return calendar
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_calendar(ctx, request, calendars, decisions):
|
||||
"""Resolve which calendar the request means, mirroring calendar.create_event.
|
||||
|
||||
A strong SemIf winner is used; a weak winner falls back to the configured
|
||||
default calendar, and with no configured default the weak winner stands.
|
||||
"""
|
||||
default = _default_calendar(ctx, calendars)
|
||||
if len(calendars) == 1:
|
||||
return calendars[0]["name"]
|
||||
|
||||
decision = DecisionRequest(
|
||||
state=request.text,
|
||||
question="Which calendar is referred to in the user query?",
|
||||
options=[Option(c["name"], c["label"]) for c in calendars],
|
||||
)
|
||||
result = ctx.engine.call(decision)
|
||||
decisions.append((decision, result))
|
||||
winner = result.selected
|
||||
if result.prob(winner) >= CALENDAR_WINNER_TAU:
|
||||
return winner
|
||||
if default is not None:
|
||||
return default["name"]
|
||||
return winner
|
||||
|
||||
|
||||
# ---- iCalendar parsing ----
|
||||
|
||||
|
||||
@@ -316,28 +368,18 @@ def act(ctx, request):
|
||||
action_log="calendar.next_event: calendar discovery failed: no calendars found",
|
||||
new_state=request.text,
|
||||
)
|
||||
|
||||
decisions = []
|
||||
if len(calendars) == 1:
|
||||
calendar = calendars[0]["name"]
|
||||
else:
|
||||
decision = DecisionRequest(
|
||||
state=request.text,
|
||||
question="Which calendar is the intended one?",
|
||||
options=[
|
||||
Option(c["name"], c["label"]) for c in calendars
|
||||
],
|
||||
)
|
||||
result = ctx.engine.call(decision)
|
||||
decisions.append((decision, result))
|
||||
calendar = result.selected
|
||||
calendar = _resolve_calendar(ctx, request, calendars, decisions)
|
||||
if not calendar:
|
||||
return ActionResult(
|
||||
action_log="calendar.next_event aborted: no calendar resolved.",
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
local_tz = datetime.now().astimezone().tzinfo or timezone.utc
|
||||
now = datetime.now(local_tz)
|
||||
|
||||
now = _now()
|
||||
local_tz = now.tzinfo or timezone.utc
|
||||
window_start = now - timedelta(days=1)
|
||||
window_end = now + timedelta(days=LOOKAHEAD_DAYS)
|
||||
try:
|
||||
@@ -355,6 +397,7 @@ def act(ctx, request):
|
||||
new_state=request.text,
|
||||
decisions=decisions,
|
||||
)
|
||||
|
||||
next_event = _pick_next(events, now)
|
||||
if next_event is None:
|
||||
message = (
|
||||
@@ -362,6 +405,7 @@ def act(ctx, request):
|
||||
f"{window_end.strftime('%Y-%m-%d')}."
|
||||
)
|
||||
return ActionResult(action_log=message, new_state=message, decisions=decisions)
|
||||
|
||||
summary = next_event.get("summary") or "(no title)"
|
||||
when = _format_when(next_event)
|
||||
message = f"Next event on {calendar!r}: {summary} — {when}"
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the Nextcloud CalDAV endpoint. This proves the body builds
|
||||
real CalDAV requests, discovers calendars, resolves the calendar through a
|
||||
SemIf sub-decision, parses expanded iCalendar events, and fails honestly when
|
||||
the service errors. It does NOT prove the live integration — only a real run
|
||||
against the user's Nextcloud does.
|
||||
SemIf sub-decision (a strong winner is used, otherwise the configured default,
|
||||
otherwise the weak winner), parses expanded iCalendar events, and fails honestly
|
||||
when the service errors. It does NOT prove the live integration — only a real
|
||||
run against the user's Nextcloud does.
|
||||
"""
|
||||
|
||||
import base64
|
||||
@@ -49,19 +50,28 @@ def build_ics():
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
"""Test-only engine: picks the requested option id, else the first."""
|
||||
"""Test-only engine.
|
||||
|
||||
def __init__(self, pick=None):
|
||||
By default it picks the requested option id (else the first) with full
|
||||
confidence. Pass `probs` (a mapping of option id -> probability) to script an
|
||||
arbitrary distribution, e.g. a near-tie that must fall back to the default.
|
||||
"""
|
||||
|
||||
def __init__(self, pick=None, probs=None):
|
||||
self.pick = pick
|
||||
self.probs = probs
|
||||
self.decisions = []
|
||||
|
||||
def call(self, decision):
|
||||
self.decisions.append(decision)
|
||||
option_ids = [option.id for option in decision.options]
|
||||
chosen = self.pick if self.pick in option_ids else option_ids[0]
|
||||
probabilities = [
|
||||
1.0 if option_id == chosen else 0.0 for option_id in option_ids
|
||||
]
|
||||
if self.probs is not None:
|
||||
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
|
||||
else:
|
||||
chosen = self.pick if self.pick in option_ids else option_ids[0]
|
||||
probabilities = [
|
||||
1.0 if option_id == chosen else 0.0 for option_id in option_ids
|
||||
]
|
||||
return DecisionResult(
|
||||
request=decision, option_ids=option_ids, probabilities=probabilities
|
||||
)
|
||||
@@ -137,11 +147,12 @@ def start_server(**overrides):
|
||||
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def fixture_config(url):
|
||||
def fixture_config(url, default="personal"):
|
||||
return {
|
||||
"nextcloud_url": url,
|
||||
"nextcloud_username": "testuser",
|
||||
"nextcloud_app_password": "app-pw",
|
||||
"nextcloud_default_calendar": default,
|
||||
}
|
||||
|
||||
|
||||
@@ -149,6 +160,7 @@ def main():
|
||||
global ICS
|
||||
ICS = build_ics()
|
||||
|
||||
# A strong winner is used even though a default is configured.
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
engine = FakeEngine(pick="work")
|
||||
@@ -157,6 +169,10 @@ def main():
|
||||
action = skill.act(ctx, request)
|
||||
assert len(action.decisions) == 1, "act must log the calendar choice"
|
||||
assert len(engine.decisions) == 1
|
||||
assert [option.id for option in engine.decisions[0].options] == [
|
||||
"personal",
|
||||
"work",
|
||||
], engine.decisions[0].options
|
||||
assert "Team sync" in action.action_log, action.action_log
|
||||
assert action.new_state, "act must set a new state"
|
||||
|
||||
@@ -174,6 +190,36 @@ def main():
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
# A weak winner falls back to the configured default calendar.
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
|
||||
ctx = ActionContext(engine=engine, config=fixture_config(url, default="personal"))
|
||||
request = Request("what is the next event on my calendar?")
|
||||
action = skill.act(ctx, request)
|
||||
assert len(engine.decisions) == 1
|
||||
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/personal/", handler.requests[1]["path"]
|
||||
assert "Team sync" in action.action_log, action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
# A weak winner with no configured default stands.
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
engine = FakeEngine(probs={"personal": 0.45, "work": 0.5})
|
||||
ctx = ActionContext(engine=engine, config=fixture_config(url, default=""))
|
||||
request = Request("what is the next event on my calendar?")
|
||||
action = skill.act(ctx, request)
|
||||
assert len(engine.decisions) == 1
|
||||
assert handler.requests[1]["path"] == "/remote.php/dav/calendars/testuser/work/", handler.requests[1]["path"]
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
# A single calendar needs no SemIf decision.
|
||||
server, handler, url = start_server(calendar_count=1)
|
||||
try:
|
||||
engine = FakeEngine()
|
||||
@@ -188,6 +234,7 @@ def main():
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
# A failing REPORT is reported honestly.
|
||||
server, handler, url = start_server(report_status=500)
|
||||
try:
|
||||
engine = FakeEngine(pick="personal")
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
"""Show the SimpleX contact link others use to connect to this agent.
|
||||
|
||||
Real integration: the standalone SimpleX forwarding bridge
|
||||
(`simplex_bridge_url`). The bridge's own connection to the `simplex-chat`
|
||||
daemon is the only thing that can read (or create) the forwarding bot's *user
|
||||
contact address*; this body asks the bridge for it and reports the link
|
||||
honestly. It never opens a WebSocket to the daemon and never invents a link: if
|
||||
the bridge is not running or has no address, it says so.
|
||||
(`simplex_bridge_url`, `simplex_bridge_token`). The bridge's own connection to
|
||||
the `simplex-chat` daemon is the only thing that can read (or create) the
|
||||
forwarding bot's *user contact address*; this body asks the bridge for it and
|
||||
reports the link honestly. It never opens a WebSocket to the daemon and never
|
||||
invents a link: if the bridge is not running or has no address, it says so.
|
||||
|
||||
`GET /address` shows the existing link and creates one on first call, returning
|
||||
`{short_link, full_link, created}`.
|
||||
`act` health-checks the bridge, then `GET /address` shows the existing link and
|
||||
creates one on first call, returning `{short_link, full_link, created}`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,6 +37,9 @@ class BridgeError(Exception):
|
||||
"""The SimpleX forwarding bridge is unreachable or returned an error."""
|
||||
|
||||
|
||||
# ---- transport ----
|
||||
|
||||
|
||||
def _base(ctx):
|
||||
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
|
||||
if not url:
|
||||
@@ -63,6 +66,9 @@ def _get(ctx, path):
|
||||
raise BridgeError(f"GET {path}: {exc}") from exc
|
||||
|
||||
|
||||
# ---- skill phases ----
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
try:
|
||||
payload = _get(ctx, "/health")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
||||
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
||||
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate."
|
||||
}
|
||||
@@ -3,9 +3,11 @@
|
||||
Real integration: the standalone SimpleX forwarding bridge
|
||||
(`simplex_bridge_url`) buffers every inbound DM and forwards outbound sends.
|
||||
`act` peeks that inbox, finds which conversations have unread messages, and
|
||||
resolves which one to read with a SemIf sub-decision when more than one does
|
||||
(honoring a configured default contact); it then pops and reports the oldest
|
||||
unread message for that conversation.
|
||||
resolves which one to read with a SemIf choice over them (state = the user
|
||||
query): a strong winner (probability >= `CONTACT_WINNER_TAU`) is used, otherwise
|
||||
the configured default contact is used; with no configured default (or a default
|
||||
with no unread message) the weak winner stands. It then pops and reports the
|
||||
oldest unread message for that conversation.
|
||||
|
||||
The bridge owns the read cursor, so this skill keeps no state of its own. It
|
||||
never opens a WebSocket to the `simplex-chat` daemon — the bridge is the only
|
||||
@@ -25,22 +27,32 @@ from semif_agent.skills import ActionResult
|
||||
INTEGRATION = {
|
||||
"service": "simplex",
|
||||
"transport": "http",
|
||||
"config_vars": ["simplex_bridge_url", "simplex_bridge_token"],
|
||||
"config_vars": [
|
||||
"simplex_bridge_url",
|
||||
"simplex_bridge_token",
|
||||
"simplex_default_contact",
|
||||
],
|
||||
}
|
||||
|
||||
CONTRACT = {
|
||||
"simplex_bridge_url": "Base URL of the standalone SimpleX forwarding bridge, e.g. http://127.0.0.1:5227 (no trailing slash needed).",
|
||||
"simplex_bridge_token": "Shared secret for the bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
"simplex_default_contact": "Default SimpleX contact (contact id or display name) used when the request does not strongly point at a conversation; leave blank to always use the strongest candidate.",
|
||||
}
|
||||
|
||||
|
||||
TIMEOUT_SECONDS = 20
|
||||
# A SemIf probability at or above this counts as a "strong winner" for the
|
||||
# conversation; below it the configured default contact is used instead.
|
||||
CONTACT_WINNER_TAU = 0.6
|
||||
|
||||
|
||||
class BridgeError(Exception):
|
||||
"""The SimpleX forwarding bridge is unreachable or returned an error."""
|
||||
|
||||
|
||||
# ---- transport ----
|
||||
|
||||
|
||||
def _base(ctx):
|
||||
url = str(ctx.config.get("simplex_bridge_url", "") or "").strip().rstrip("/")
|
||||
if not url:
|
||||
@@ -67,6 +79,9 @@ def _get(ctx, path):
|
||||
raise BridgeError(f"GET {path}: {exc}") from exc
|
||||
|
||||
|
||||
# ---- conversation resolution ----
|
||||
|
||||
|
||||
def _senders(messages):
|
||||
"""Distinct conversations with buffered messages, in arrival order."""
|
||||
senders = []
|
||||
@@ -82,16 +97,45 @@ def _senders(messages):
|
||||
return senders
|
||||
|
||||
|
||||
def _match_default(senders, default):
|
||||
default = str(default or "").strip()
|
||||
def _default_sender(ctx, senders):
|
||||
"""The configured default contact, if it has unread messages."""
|
||||
default = str(ctx.config.get("simplex_default_contact", "") or "").strip()
|
||||
if not default:
|
||||
return None
|
||||
for sender in senders:
|
||||
if sender["id"] == default or sender["display_name"] == default:
|
||||
return sender["id"]
|
||||
return sender
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_contact(ctx, request, senders, decisions):
|
||||
"""Resolve which conversation to read, mirroring calendar.create_event.
|
||||
|
||||
A strong SemIf winner is used; a weak winner falls back to the configured
|
||||
default contact, and with no configured default the weak winner stands.
|
||||
"""
|
||||
default = _default_sender(ctx, senders)
|
||||
if len(senders) == 1:
|
||||
return senders[0]["id"]
|
||||
|
||||
decision = DecisionRequest(
|
||||
state=request.text,
|
||||
question="Which conversation should I read the next SimpleX message from?",
|
||||
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
|
||||
)
|
||||
result = ctx.engine.call(decision)
|
||||
decisions.append((decision, result))
|
||||
winner = result.selected
|
||||
if result.prob(winner) >= CONTACT_WINNER_TAU:
|
||||
return winner
|
||||
if default is not None:
|
||||
return default["id"]
|
||||
return winner
|
||||
|
||||
|
||||
# ---- skill phases ----
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
try:
|
||||
payload = _get(ctx, "/inbox")
|
||||
@@ -104,18 +148,7 @@ def act(ctx, request):
|
||||
new_state="no unread SimpleX messages",
|
||||
)
|
||||
decisions = []
|
||||
contact = _match_default(senders, ctx.config.get("simplex_default_contact", ""))
|
||||
if contact is None and len(senders) > 1:
|
||||
decision = DecisionRequest(
|
||||
state=request.text,
|
||||
question="Which conversation should I read the next SimpleX message from?",
|
||||
options=[Option(sender["id"], sender["display_name"]) for sender in senders],
|
||||
)
|
||||
result = ctx.engine.call(decision)
|
||||
decisions.append((decision, result))
|
||||
contact = result.selected
|
||||
if contact is None:
|
||||
contact = senders[0]["id"]
|
||||
contact = _resolve_contact(ctx, request, senders, decisions)
|
||||
try:
|
||||
payload = _get(
|
||||
ctx, f"/inbox/next?contact={urllib.parse.quote(contact)}"
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the standalone SimpleX forwarding bridge. This proves the body
|
||||
peeks the inbox, resolves the conversation through a SemIf sub-decision (or a
|
||||
configured default), pops the real `next` message, and fails honestly when the
|
||||
bridge is unreachable. It does NOT prove the live integration — only a real run
|
||||
against the bridge and a real contact does.
|
||||
peeks the inbox, resolves the conversation through a SemIf sub-decision (a
|
||||
strong winner is used, otherwise the configured default, otherwise the weak
|
||||
winner), pops the real `next` message, and fails honestly when the bridge is
|
||||
unreachable. It does NOT prove the live integration — only a real run against
|
||||
the bridge and a real contact does.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -21,19 +22,28 @@ import skill
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
"""Test-only engine: picks the requested option id, else the first."""
|
||||
"""Test-only engine.
|
||||
|
||||
def __init__(self, pick=None):
|
||||
By default it picks the requested option id (else the first) with full
|
||||
confidence. Pass `probs` (a mapping of option id -> probability) to script an
|
||||
arbitrary distribution, e.g. a near-tie that must fall back to the default.
|
||||
"""
|
||||
|
||||
def __init__(self, pick=None, probs=None):
|
||||
self.pick = pick
|
||||
self.probs = probs
|
||||
self.decisions = []
|
||||
|
||||
def call(self, decision):
|
||||
self.decisions.append(decision)
|
||||
option_ids = [option.id for option in decision.options]
|
||||
chosen = self.pick if self.pick in option_ids else option_ids[0]
|
||||
probabilities = [
|
||||
1.0 if option_id == chosen else 0.0 for option_id in option_ids
|
||||
]
|
||||
if self.probs is not None:
|
||||
probabilities = [float(self.probs.get(option_id, 0.0)) for option_id in option_ids]
|
||||
else:
|
||||
chosen = self.pick if self.pick in option_ids else option_ids[0]
|
||||
probabilities = [
|
||||
1.0 if option_id == chosen else 0.0 for option_id in option_ids
|
||||
]
|
||||
return DecisionResult(
|
||||
request=decision, option_ids=option_ids, probabilities=probabilities
|
||||
)
|
||||
@@ -129,7 +139,7 @@ def test_multiple_senders_uses_semif_decision():
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_default_contact_skips_decision():
|
||||
def test_strong_winner_overrides_default_contact():
|
||||
server, handler, url = start_server(
|
||||
[
|
||||
message("m1", "4", "Alice", "hello there"),
|
||||
@@ -137,13 +147,55 @@ def test_default_contact_skips_decision():
|
||||
]
|
||||
)
|
||||
try:
|
||||
engine = FakeEngine()
|
||||
engine = FakeEngine(probs={"4": 0.1, "7": 0.9})
|
||||
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
|
||||
request = Request("read my next simplex message from Bob")
|
||||
action = skill.act(ctx, request)
|
||||
assert len(engine.decisions) == 1, "the conversation is chosen with one SemIf decision"
|
||||
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_weak_winner_falls_back_to_default_contact():
|
||||
server, handler, url = start_server(
|
||||
[
|
||||
message("m1", "4", "Alice", "hello there"),
|
||||
message("m2", "7", "Bob", "shipment arrived"),
|
||||
]
|
||||
)
|
||||
try:
|
||||
# Bob edges out Alice but stays below the strong-winner threshold, so the
|
||||
# configured default ("Alice") is used instead.
|
||||
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
|
||||
ctx = ActionContext(engine=engine, config=config(url, default="Alice"))
|
||||
request = Request("read my next simplex message")
|
||||
action = skill.act(ctx, request)
|
||||
assert engine.decisions == [], "a configured default needs no SemIf decision"
|
||||
assert "Alice" in action.action_log, action.action_log
|
||||
assert len(engine.decisions) == 1
|
||||
assert handler.requests[1] == "/inbox/next?contact=4", handler.requests
|
||||
assert "hello there" in action.action_log, action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_weak_winner_without_default_stands():
|
||||
server, handler, url = start_server(
|
||||
[
|
||||
message("m1", "4", "Alice", "hello there"),
|
||||
message("m2", "7", "Bob", "shipment arrived"),
|
||||
]
|
||||
)
|
||||
try:
|
||||
engine = FakeEngine(probs={"4": 0.45, "7": 0.5})
|
||||
ctx = ActionContext(engine=engine, config=config(url))
|
||||
request = Request("read my next simplex message")
|
||||
action = skill.act(ctx, request)
|
||||
assert len(engine.decisions) == 1
|
||||
assert handler.requests[1] == "/inbox/next?contact=7", handler.requests
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
@@ -207,7 +259,9 @@ def test_auth_token_is_sent_when_configured():
|
||||
|
||||
def main():
|
||||
test_multiple_senders_uses_semif_decision()
|
||||
test_default_contact_skips_decision()
|
||||
test_strong_winner_overrides_default_contact()
|
||||
test_weak_winner_falls_back_to_default_contact()
|
||||
test_weak_winner_without_default_stands()
|
||||
test_single_sender_needs_no_decision()
|
||||
test_empty_inbox_is_reported_honestly()
|
||||
test_unreachable_bridge_fails_honestly()
|
||||
|
||||
Reference in new issue
Block a user