diff --git a/AGENTS.md b/AGENTS.md index 70dcf42..8a7d82e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -67,13 +67,16 @@ scheduler.py gate -> choice(tau) -> score -> queue; preempt + requeue; failed real run triggers a logged SemIf repair choice (retry/repair_skill/ask_user/no_repair) surfaced to the user queue.py urgency max-heap (desc weight, FIFO seq), age pulls toward 1.0 -skills.py tree + registry (email.compose, response.reject, tracking.check), - navigation = SemIf choices per level (logged), create_category +skills.py tree + registry (hardcoded built-in: response.reject, service-free + behaviors only), navigation = SemIf choices per level (logged), + create_category and create_skill author + register stubs via the decision model in generation mode; SkillStore persists one folder per skill (skill.py, skill.test.py, contract.json, config.json) and materialize_skill / merge_skill_store hot-load runnable skills from data/skills/; + merge_seed_store loads committed starter skills from seeds/ with + their recorded config read from data/skills/; ActionResult.needs_input pauses a run for human input; Skill.integration / integration_source read the body's INTEGRATION declaration (or infer it); @@ -375,6 +378,15 @@ unit tests (24) + box integration tests (2). check** (inline fixtures, loopback `http.server` for HTTP bodies, no external network) that never certifies the live integration — only a real run does. The body owns no data; everything comes from the runner via `ctx.config`. +- **Seed skills.** `seeds///` ships a real starter integration in + the exact generated-skill folder format (`skill.py`, `contract.json`, + `skill.test.py`, plus `manifest.json` with the description). `merge_seed_store` + loads them into every tree at startup; recorded config (credentials collected + at first fire) is written to the runtime store `data/skills/`, so the committed + seed never holds secrets, and a generated body with the same name replaces the + seed. `calendar.next_event` (Nextcloud CalDAV, recurring events expanded + server-side) is the reference seed; `tests/test_seed_skills.py` keeps it + honest. - **Trust boundary**: generated skill code is executed locally (it is imported as a module and its `predict`/`act` run in-process; `skill.test.py` runs as a subprocess in the skill folder). The box is the intended target; treat the diff --git a/SKILL.md b/SKILL.md index 5dc1666..9abaad7 100644 --- a/SKILL.md +++ b/SKILL.md @@ -143,8 +143,9 @@ talk to. Declaring a transport the body does not use is a broken skill. called again with the *same* prediction — check `request.user_input` on the resume pass to finish the run. This refines the product goal and requirements only — never operational data (the runner supplies that). -- **Write files under configured data dirs only** (e.g. `ctx.config["drafts"]`), - never anywhere else on disk. +- **Write files under configured data dirs only** (e.g. the directory named by + a config variable such as `ctx.config["output_dir"]`), never anywhere else on + disk. - **Fail fast on budget.** Keep the work small; do not loop or retry in code. - **Names match the manifest.** The module is imported as its manifest name; the functions are `predict` and `act` exactly. @@ -154,7 +155,8 @@ talk to. Declaring a transport the body does not use is a broken skill. - Single purpose, single file, single module. - Avoid duplicating an existing skill in the same category. - `predict` resolves ambiguity (arguments, recipients, targets) with SemIf - sub-decisions, mirroring how `email.compose` resolves its recipient. + sub-decisions, mirroring how `calendar.next_event` resolves which calendar + to read. - `act` performs the concrete real action and writes a human-readable `action_log` that the self-assessment LLM can judge. Include what the service actually returned. diff --git a/config.example.json b/config.example.json index 2f22716..2e40e51 100644 --- a/config.example.json +++ b/config.example.json @@ -68,12 +68,7 @@ } }, "skill_bodies": "data/skills", - "skills": { - "email": {"cost_budget": 1.0}, - "contacts": "data/contacts.json", - "drafts": "data/drafts", - "packages": "data/packages.json" - }, + "skill_seeds": "seeds", "log": "data/decisions.jsonl", "trace": "data/runs.jsonl", "category_registry": "data/categories.json", diff --git a/data/contacts.json b/data/contacts.json deleted file mode 100644 index fa40c96..0000000 --- a/data/contacts.json +++ /dev/null @@ -1,5 +0,0 @@ -[ - {"name": "alice", "description": "Partner; usually home by six."}, - {"name": "bob", "description": "Work colleague on the ops team."}, - {"name": "carol", "description": "Landlord; prefers email."} -] \ No newline at end of file diff --git a/data/packages.json b/data/packages.json deleted file mode 100644 index 49efe47..0000000 --- a/data/packages.json +++ /dev/null @@ -1,5 +0,0 @@ -[ - {"id": "1Z999AA10123456784", "status": "out for delivery"}, - {"id": "1Z999BB10234567891", "status": "delivered"}, - {"id": "1Z999CC10345678908", "status": "at sorting facility"} -] \ No newline at end of file diff --git a/seeds/calendar/next_event/contract.json b/seeds/calendar/next_event/contract.json new file mode 100644 index 0000000..37a5ec7 --- /dev/null +++ b/seeds/calendar/next_event/contract.json @@ -0,0 +1,5 @@ +{ + "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." +} diff --git a/seeds/calendar/next_event/manifest.json b/seeds/calendar/next_event/manifest.json new file mode 100644 index 0000000..7022683 --- /dev/null +++ b/seeds/calendar/next_event/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Report the next upcoming event on the user's Nextcloud calendar." +} diff --git a/seeds/calendar/next_event/skill.py b/seeds/calendar/next_event/skill.py new file mode 100644 index 0000000..e27952f --- /dev/null +++ b/seeds/calendar/next_event/skill.py @@ -0,0 +1,367 @@ +"""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`). `predict` 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; `act` 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 (``), so no RRULE +engine lives here; a server that ignores expansion is reported honestly +rather than guessed at. +""" + +from __future__ import annotations + +import base64 +import re +import urllib.error +import urllib.parse +import urllib.request +import xml.etree.ElementTree as ET +from datetime import datetime, timedelta, timezone +from zoneinfo import ZoneInfo + +from semif_agent.decisions import DecisionRequest, Option +from semif_agent.skills import ActionResult, Prediction + +INTEGRATION = { + "service": "nextcloud_calendar", + "transport": "caldav", + "config_vars": [ + "nextcloud_url", + "nextcloud_username", + "nextcloud_app_password", + ], +} + +DAV = "DAV:" +CALDAV = "urn:ietf:params:xml:ns:caldav" +LOOKAHEAD_DAYS = 60 +TIMEOUT_SECONDS = 30 + +PROPFIND_BODY = ( + '' + '' + "" + "" +).encode("utf-8") + +PROPERTY_RE = re.compile(r"^(?P[A-Za-z-]+)(?P(?:;[^:]*)?):(?P.*)$") +DURATION_RE = re.compile( + r"^(?P[+-])?P" + r"(?:(?P\d+)W)?(?:(?P\d+)D)?" + r"(?:T(?:(?P\d+)H)?(?:(?P\d+)M)?(?:(?P\d+)S)?)?$" +) + + +class CalDavError(Exception): + """A real failure talking to the calendar service.""" + + +# ---- transport ---- + + +def _request(ctx, method, path, body=None, depth="0"): + username = str(ctx.config.get("nextcloud_username", "") or "").strip() + password = str(ctx.config.get("nextcloud_app_password", "") or "") + url = str(ctx.config.get("nextcloud_url", "") or "").strip().rstrip("/") + if not url: + raise CalDavError("nextcloud_url is not configured") + if not username or not password: + raise CalDavError("nextcloud_username and nextcloud_app_password are not configured") + token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii") + request = urllib.request.Request( + url + path, + data=body, + method=method, + headers={ + "Authorization": f"Basic {token}", + "Depth": depth, + "Content-Type": "application/xml; charset=utf-8", + }, + ) + try: + with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response: + return response.read() + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace").strip()[:200] + raise CalDavError(f"{method} {path}: HTTP {exc.code} {detail}") from exc + except (urllib.error.URLError, OSError) as exc: + raise CalDavError(f"{method} {path}: {exc}") from exc + + +# ---- CalDAV discovery + query ---- + + +def _multistatus(body): + try: + root = ET.fromstring(body) + except ET.ParseError as exc: + raise CalDavError(f"unparseable CalDAV XML: {exc}") from exc + if root.tag != f"{{{DAV}}}multistatus": + raise CalDavError(f"unexpected CalDAV response root {root.tag!r}") + return root + + +def _response_prop(response): + return response.find(f"{{{DAV}}}propstat/{{{DAV}}}prop") + + +def _discover_calendars(ctx): + username = str(ctx.config.get("nextcloud_username", "") or "").strip() + if not username: + raise CalDavError("nextcloud_username is not configured") + home = f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/" + root = _multistatus(_request(ctx, "PROPFIND", home, PROPFIND_BODY, depth="1")) + calendars = [] + for response in root.findall(f"{{{DAV}}}response"): + prop = _response_prop(response) + if prop is None: + continue + resourcetype = prop.find(f"{{{DAV}}}resourcetype") + if resourcetype is None or resourcetype.find(f"{{{CALDAV}}}calendar") is None: + continue + href = response.find(f"{{{DAV}}}href") + path = urllib.parse.urlparse((href.text if href is not None else "") or "").path + name = urllib.parse.unquote(path.rstrip("/").rsplit("/", 1)[-1]) + if not name: + continue + display = prop.find(f"{{{DAV}}}displayname") + label = (display.text or "").strip() if display is not None else "" + calendars.append({"name": name, "label": label or name}) + return calendars + + +def _calendar_path(ctx, calendar): + username = str(ctx.config.get("nextcloud_username", "") or "").strip() + return ( + f"/remote.php/dav/calendars/{urllib.parse.quote(username)}/" + f"{urllib.parse.quote(calendar)}/" + ) + + +def _report_body(start, end): + start_text = start.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + end_text = end.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + return ( + '' + '' + "" + f'' + "" + "" + "" + '' + '' + f'' + "" + "" + "" + "" + ).encode("utf-8") + + +def _calendar_payloads(body): + root = _multistatus(body) + payloads = [] + for response in root.findall(f"{{{DAV}}}response"): + prop = _response_prop(response) + if prop is None: + continue + for data in prop.findall(f"{{{CALDAV}}}calendar-data"): + if data.text: + payloads.append(data.text) + return payloads + + +# ---- iCalendar parsing ---- + + +def _unfold(text): + lines = [] + for raw in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"): + if raw[:1] in (" ", "\t") and lines: + lines[-1] += raw[1:] + else: + lines.append(raw) + return lines + + +def _parse_property(line): + match = PROPERTY_RE.match(line) + if match is None: + return "", {}, "" + name = match.group("name").upper() + params = {} + for chunk in match.group("params").strip(";").split(";"): + key, _, value = chunk.partition("=") + if key: + params[key.strip().upper()] = value.strip().strip('"') + return name, params, match.group("value") + + +def _parse_datetime(value, params, default_tz): + value = value.strip() + if params.get("VALUE") == "DATE" or (len(value) == 8 and value.isdigit()): + return datetime.strptime(value, "%Y%m%d").replace(tzinfo=default_tz), True + tz = default_tz + if value.endswith("Z"): + tz = timezone.utc + value = value[:-1] + elif params.get("TZID"): + try: + tz = ZoneInfo(params["TZID"]) + except Exception: + tz = default_tz + return datetime.strptime(value, "%Y%m%dT%H%M%S").replace(tzinfo=tz), False + + +def _parse_duration(value): + match = DURATION_RE.match(value.strip().upper()) + if match is None: + return None + total = timedelta( + weeks=int(match.group("weeks") or 0), + days=int(match.group("days") or 0), + hours=int(match.group("hours") or 0), + minutes=int(match.group("minutes") or 0), + seconds=int(match.group("seconds") or 0), + ) + return -total if match.group("sign") == "-" else total + + +def _parse_events(payloads, default_tz): + events = [] + for payload in payloads: + current = None + for line in _unfold(payload): + name, params, value = _parse_property(line) + if name == "BEGIN" and value.strip().upper() == "VEVENT": + current = {} + continue + if name == "END" and value.strip().upper() == "VEVENT": + if current is not None: + events.append(current) + current = None + continue + if current is None: + continue + if name == "DTSTART": + current["start"], current["all_day"] = _parse_datetime( + value, params, default_tz + ) + elif name == "DTEND": + current["end"] = _parse_datetime(value, params, default_tz)[0] + elif name == "DURATION": + current["duration"] = _parse_duration(value) + elif name == "SUMMARY": + current["summary"] = value.strip() + elif name == "LOCATION": + current["location"] = value.strip() + elif name == "STATUS" and value.strip().upper() == "CANCELLED": + current["cancelled"] = True + if current is not None: + events.append(current) + return [ + event for event in events if "start" in event and not event.get("cancelled") + ] + + +def _event_end(event): + if event.get("end") is not None: + return event["end"] + duration = event.get("duration") + if duration is not None: + return event["start"] + duration + if event.get("all_day"): + return event["start"] + timedelta(days=1) + return event["start"] + + +def _pick_next(events, now): + current_or_future = [event for event in events if _event_end(event) >= now] + if not current_or_future: + return None + return min(current_or_future, key=lambda event: event["start"]) + + +def _format_when(event): + start = event["start"] + if event.get("all_day"): + return start.strftime("%Y-%m-%d (all day)") + return start.strftime("%Y-%m-%d %H:%M %Z") + + +# ---- skill phases ---- + + +def predict(ctx, request): + try: + calendars = _discover_calendars(ctx) + except CalDavError as exc: + return Prediction(text=f"calendar discovery failed: {exc}") + if not calendars: + return Prediction(text="calendar discovery failed: no calendars found") + if len(calendars) == 1: + return Prediction(text=f"calendar: {calendars[0]['name']}") + decision = DecisionRequest( + state=request.text, + question="Which calendar is the intended one?", + options=[ + Option(calendar["name"], calendar["label"]) for calendar in calendars + ], + ) + result = ctx.engine.call(decision) + return Prediction( + text=f"calendar: {result.selected}", + decisions=[(decision, result)], + ) + + +def act(ctx, request, prediction): + text = prediction.text if prediction else "" + if text.startswith("calendar discovery failed:"): + return ActionResult(action_log=text, new_state=request.text) + calendar = text.removeprefix("calendar: ").strip() + if not calendar: + return ActionResult( + action_log=( + "calendar.next_event aborted: no calendar resolved " + f"({text or 'no prediction'})." + ), + new_state=request.text, + ) + local_tz = datetime.now().astimezone().tzinfo or timezone.utc + now = datetime.now(local_tz) + window_start = now - timedelta(days=1) + window_end = now + timedelta(days=LOOKAHEAD_DAYS) + try: + body = _request( + ctx, + "REPORT", + _calendar_path(ctx, calendar), + _report_body(window_start, window_end), + depth="1", + ) + events = _parse_events(_calendar_payloads(body), local_tz) + except CalDavError as exc: + return ActionResult( + action_log=f"calendar.next_event failed on {calendar!r}: {exc}", + new_state=request.text, + ) + next_event = _pick_next(events, now) + if next_event is None: + message = ( + f"No events on calendar {calendar!r} through " + f"{window_end.strftime('%Y-%m-%d')}." + ) + return ActionResult(action_log=message, new_state=message) + summary = next_event.get("summary") or "(no title)" + when = _format_when(next_event) + message = f"Next event on {calendar!r}: {summary} — {when}" + if next_event.get("location"): + message += f" at {next_event['location']}" + return ActionResult(action_log=message, new_state=message) diff --git a/seeds/calendar/next_event/skill.test.py b/seeds/calendar/next_event/skill.test.py new file mode 100644 index 0000000..bcc3f8d --- /dev/null +++ b/seeds/calendar/next_event/skill.test.py @@ -0,0 +1,218 @@ +"""Hermetic mechanics test for calendar.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 +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. +""" + +import base64 +import sys +import threading +from datetime import datetime, timedelta, timezone +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from semif_agent.decisions import DecisionResult, Request +from semif_agent.skills import ActionContext + +import skill + +CALENDARS = [("personal", "Personal"), ("work", "Work")] +ICS = "" + + +def build_ics(): + """Fixture events relative to now, so the test never rots.""" + now = datetime.now(timezone.utc) + past = now - timedelta(days=2) + soon = now + timedelta(hours=2) + all_day = (now + timedelta(days=2)).date() + + def stamp(value): + return value.strftime("%Y%m%dT%H%M%SZ") + + return ( + "BEGIN:VCALENDAR\nVERSION:2.0\n" + "BEGIN:VEVENT\nUID:past@example\n" + f"DTSTART:{stamp(past)}\nDTEND:{stamp(past + timedelta(hours=1))}\n" + "SUMMARY:Already happened\nEND:VEVENT\n" + "BEGIN:VEVENT\nUID:soon@example\n" + f"DTSTART:{stamp(soon)}\nDTEND:{stamp(soon + timedelta(hours=1))}\n" + "SUMMARY:Team sync\nLOCATION:Room 3\nEND:VEVENT\n" + "BEGIN:VEVENT\nUID:allday@example\n" + f"DTSTART;VALUE=DATE:{all_day.strftime('%Y%m%d')}\n" + "SUMMARY:Offsite\nEND:VEVENT\n" + "END:VCALENDAR" + ) + + +class FakeEngine: + """Test-only engine: picks the requested option id, else the first.""" + + def __init__(self, pick=None): + self.pick = pick + 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 + ] + return DecisionResult( + request=decision, option_ids=option_ids, probabilities=probabilities + ) + + +class CalDavHandler(BaseHTTPRequestHandler): + requests = [] + calendar_count = 2 + report_status = 207 + + def _record(self): + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length) if length else b"" + self.requests.append( + { + "command": self.command, + "path": self.path, + "depth": self.headers.get("Depth"), + "authorization": self.headers.get("Authorization"), + "body": body.decode("utf-8", "replace"), + } + ) + + def _multistatus(self, payload): + body = payload.encode("utf-8") + self.send_response(207) + self.send_header("Content-Type", "application/xml; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_PROPFIND(self): + self._record() + responses = "".join( + f"/remote.php/dav/calendars/testuser/{name}/" + "" + f"{label}" + "" + "HTTP/1.1 200 OK" + for name, label in CALENDARS[: self.calendar_count] + ) + self._multistatus( + '' + '' + f"{responses}" + ) + + def do_REPORT(self): + self._record() + if self.report_status != 207: + self.send_response(self.report_status) + self.end_headers() + return + self._multistatus( + '' + '' + "" + "/remote.php/dav/calendars/testuser/work/event.ics" + "" + f"{ICS}" + "HTTP/1.1 200 OK" + "" + ) + + def log_message(self, *args): + pass + + +def start_server(**overrides): + handler = type("Handler", (CalDavHandler,), {"requests": [], **overrides}) + server = ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, handler, f"http://127.0.0.1:{server.server_address[1]}" + + +def fixture_config(url): + return { + "nextcloud_url": url, + "nextcloud_username": "testuser", + "nextcloud_app_password": "app-pw", + } + + +def main(): + global ICS + ICS = build_ics() + + server, handler, url = start_server() + try: + engine = FakeEngine(pick="work") + ctx = ActionContext(engine=engine, config=fixture_config(url)) + request = Request("what is the next event on my work calendar?") + prediction = skill.predict(ctx, request) + assert prediction.text == "calendar: work", prediction.text + assert len(prediction.decisions) == 1, "predict must log the calendar choice" + assert len(engine.decisions) == 1 + + action = skill.act(ctx, request, prediction) + assert "Team sync" in action.action_log, action.action_log + assert action.new_state, "act must set a new state" + + commands = [entry["command"] for entry in handler.requests] + assert commands == ["PROPFIND", "REPORT"], commands + report = handler.requests[1] + assert report["path"] == "/remote.php/dav/calendars/testuser/work/", report["path"] + assert report["depth"] == "1", report["depth"] + expected_auth = "Basic " + base64.b64encode(b"testuser:app-pw").decode("ascii") + assert report["authorization"] == expected_auth, report["authorization"] + assert " dict: return self._read_json(category, name, "config.json") + def read_manifest(self, category: str, name: str) -> dict: + return self._read_json(category, name, "manifest.json") + def _read_json(self, category: str, name: str, filename: str): path = self.dir(category, name) / filename if not path.is_file(): @@ -377,6 +380,61 @@ def merge_skill_store( return upgraded +def merge_seed_store( + tree: dict[str, list[Skill]], + seed_store: SkillStore, + config_store: SkillStore | None = None, +) -> int: + """Load committed starter skills from a read-only seed store into the tree. + + A seed is a real skill in the same folder layout as a generated one + (`skill.py`, `contract.json`, `skill.test.py`, plus a `manifest.json` with + its description), so it is inspectable and testable exactly like a codegen + body. `config_store` is the runtime store (`data/skills`): recorded answers + — credentials collected at first fire — live there, never in the committed + seed folder. Returns the number of skills loaded. + """ + loaded = 0 + for category, name in seed_store.list_skills(): + directory = seed_store.dir(category, name) + try: + module = load_skill_module(category, name, seed_store.path) + except Exception: + continue + predict = getattr(module, "predict", None) + act = getattr(module, "act", None) + if not callable(predict) or not callable(act): + continue + try: + code = (directory / "skill.py").read_text() + except OSError: + continue + integration, integration_source = _extract_integration(code) + manifest = seed_store.read_manifest(category, name) + description = str(manifest.get("description") or name) + skill = Skill( + name=name, + category=category, + description=description, + predict=predict, + act=act, + config=(config_store or seed_store).read_config(category, name), + contract=seed_store.read_contract(category, name), + integration=integration, + integration_source=integration_source, + ) + skills = tree.setdefault(category, []) + for index, existing in enumerate(skills): + if existing.name == name: + skills[index] = skill + break + else: + skills.append(skill) + skills.sort(key=lambda s: s.name) + loaded += 1 + return loaded + + def resolve_skill_config( store: SkillStore, skill: Skill, global_config: dict, answered: dict | None = None ) -> dict: @@ -411,85 +469,27 @@ def compose_state(request: Request, current: str | None = None) -> str: return " ".join(parts) -def _contacts(ctx: ActionContext) -> list[dict]: - path = Path(ctx.config.get("contacts", "data/contacts.json")) - if not path.is_file(): - return [] - return json.loads(path.read_text()) - - -def _email_predict(ctx: ActionContext, request: Request) -> Prediction: - contacts = _contacts(ctx) - if not contacts: - return Prediction(text="no contacts available", decisions=[]) - decision = DecisionRequest( - state=compose_state(request), - question="Which contact is the intended recipient?", - options=[Option(c["name"], c.get("description", "")) for c in contacts] - + [Option("none", "None of the listed contacts.")], - ) - result = ctx.engine.call(decision) - return Prediction(text=f"recipient is {result.selected}", decisions=[(decision, result)]) - - -def _email_compose(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult: - recipient = prediction.text.removeprefix("recipient is ") - if recipient == "no contacts available" or recipient == "none": - return ActionResult( - action_log="email.compose aborted: recipient not resolved.", - new_state=request.text, - ) - drafts = Path(ctx.config.get("drafts", "data/drafts")) - drafts.mkdir(parents=True, exist_ok=True) - target = drafts / f"{request.id}.txt" - target.write_text(f"To: {recipient}\nBody: {request.text}\n") - return ActionResult( - action_log=f"email.compose: wrote draft {target} for {recipient!r}.", - new_state=f"Draft written to {target.name} for {recipient}.", - ) - - def _response_reject(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult: message = f"Rejected: I cannot act on this while busy ({request.text})." return ActionResult(action_log=f"response.reject: {message}", new_state=message) -def _tracking_check(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult: - path = Path(ctx.config.get("packages", "data/packages.json")) - if not path.is_file(): - return ActionResult( - action_log="tracking.check aborted: no packages file.", - new_state=request.text, - ) - packages = json.loads(path.read_text()) - lines = [f"{p.get('id')}: {p.get('status')}" for p in packages] - report = "Tracking statuses:\n" + "\n".join(lines) - return ActionResult(action_log="tracking.check: " + report, new_state=report) - - def build_skills(config: dict) -> list[Skill]: - skills = config.get("skills", {}) + """The hardcoded built-ins: internal behaviors only. + + Real integrations do not live here — they are authored by the codegen + pipeline into `data/skills/` or shipped as seed skill packages under + `seeds/`. A fabricated built-in here shadows the authoring path for a real + one (navigation routes to it), so keep this list to behaviors that need no + external service. + """ return [ - Skill( - name="email.compose", - category="email", - description="Compose and dispatch an email.", - predict=_email_predict, - act=_email_compose, - cost_budget=float(skills.get("email", {}).get("cost_budget", 1.0)), - ), Skill( name="response.reject", category="response", description="Politely reject a request because the agent is busy.", act=_response_reject, ), - Skill( - name="tracking.check", - category="tracking", - description="Check the delivery status of a package.", - act=_tracking_check, - ), ] diff --git a/semif_agent/static/index.html b/semif_agent/static/index.html index 02c3506..2c32f33 100644 --- a/semif_agent/static/index.html +++ b/semif_agent/static/index.html @@ -15,7 +15,7 @@
+ placeholder="type a request, e.g. 'what is the next event on my nextcloud calendar?'">