commit 7442f5bd5f71220e1b062e534ee2f046b5564d94 Author: Gabby Morgan Date: Tue Oct 13 14:20:35 2026 +0000 Abstract seeds into modular skill packs + split config Group committed starter skills into packs (semif_agent/packs.py) that bind a concern to its categories, bridge(s), requirements, and config schema: - seeds/ -> packs// with a pack.json manifest + skills///. Shipped: nextcloud, simplex, outlook, browser (each owning its bridge) and essentials (time + calculator, no bridge). - PackRegistry discovers packs (a root with no manifest is one implicit pack); merge_packs loads every enabled pack. Pack enable is one switch (packs..enabled -> bridges..enabled -> enabled_by_default); disabling a pack drops its categories (incl. generated bodies) and its bridge. - CATEGORY_DESCRIPTIONS now comes from the pack manifests (built-ins stay). Adopt a Home-Assistant-style layered config (semif_agent/config.py): - config.json is a thin index ({"include": [...]}) over config/core.json, config/gateway.json, config/bridges.json, config/packs/*.json, deep-merged. - Secrets live in the gitignored secrets.json, referenced as "!secret "; api_key_env is removed. - CORE_SCHEMA + each pack's config schema own defaults and GENERATE the committed config.example.json; new `check-config` (validate + --write-example) and `config-init` (seed the split layout) commands. - scripts/config_merge.py (stdlib) lets bootstrap read the merged config. Tests: tests/test_packs.py (renamed from test_seed_skills, +enable/merge), new tests/test_config.py. All unit tests pass (772). diff --git a/pack.json b/pack.json new file mode 100644 index 0000000..96c91bb --- /dev/null +++ b/pack.json @@ -0,0 +1,26 @@ +{ + "name": "outlook", + "title": "Outlook", + "concern": "The user's Microsoft account (Outlook / Microsoft 365) through Microsoft Graph: mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files.", + "categories": { + "outlook": "Outlook / Microsoft 365: the user's mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files." + }, + "bridges": ["outlook"], + "requires": [], + "enabled_by_default": false, + "config": { + "enabled": {"type": "bool", "default": false, "doc": "Load this pack's skills and run its bridge. Disabled by default: it needs an Entra ID client id and an authorization run first."}, + "host": {"type": "str", "default": "127.0.0.1", "doc": "Bridge bind address (localhost only)."}, + "port": {"type": "int", "default": 5231, "doc": "Bridge listen port."}, + "token": {"type": "str", "default": "", "secret": true, "doc": "Shared secret required in the X-Semif-Token header when set."}, + "client_id": {"type": "str", "default": "", "doc": "Entra ID public-client app id (not a secret)."}, + "tenant": {"type": "str", "default": "common", "doc": "Entra tenant: common | organizations | consumers | a tenant id."}, + "token_path": {"type": "str", "default": ".runtime/outlook/token.json", "doc": "Where scripts/outlook-auth.py stores the tokens (0600)."}, + "default_calendar": {"type": "str", "default": "", "doc": "Calendar used when a request names none."}, + "default_task_list": {"type": "str", "default": "", "doc": "Microsoft To Do list used when a request names none."}, + "default_mail_folder": {"type": "str", "default": "inbox", "doc": "Mail folder read by default."}, + "default_timezone": {"type": "str", "default": "UTC", "doc": "IANA zone for created events/tasks whose start has no offset."}, + "verify_tls": {"type": "bool", "default": true, "doc": "false skips certificate verification."}, + "timeout": {"type": "int", "default": 30, "doc": "Per-request timeout in seconds."} + } +} diff --git a/skills/outlook/create_event/contract.json b/skills/outlook/create_event/contract.json new file mode 100644 index 0000000..ce8daaf --- /dev/null +++ b/skills/outlook/create_event/contract.json @@ -0,0 +1,4 @@ +{ + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth." +} diff --git a/skills/outlook/create_event/manifest.json b/skills/outlook/create_event/manifest.json new file mode 100644 index 0000000..84d4dff --- /dev/null +++ b/skills/outlook/create_event/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Create an Outlook calendar event from a request such as \"add dentist appointment on 2026-11-10 at 2pm\"." +} diff --git a/skills/outlook/create_event/skill.py b/skills/outlook/create_event/skill.py new file mode 100644 index 0000000..1c5fc4c --- /dev/null +++ b/skills/outlook/create_event/skill.py @@ -0,0 +1,334 @@ +"""Create an event on the user's Outlook calendar from a request. + +Real integration: the local Outlook bridge (Microsoft Graph). Connection comes +from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never +speaks Graph or OAuth directly. `act` derives the event's title, date, time and +duration from `request.text`; missing pieces are asked one at a time and the +answers are stashed in `request.meta` (act re-runs from the top after a +`needs_input` pause, so a question is never asked twice). The event is created +with a real `POST /calendars/events` and the real outcome reported. The user's +IANA timezone (the top-level `timezone` config value, when set) labels the start. +""" + +from __future__ import annotations + +import json +import re +import urllib.error +import urllib.parse +import urllib.request +from datetime import datetime, time, timedelta + +from semif_agent.skills import ActionResult +from semif_agent.timers import local_now + +INTEGRATION = { + "service": "outlook", + "transport": "http", + "config_vars": ["outlook_bridge_url", "outlook_bridge_token"], +} + +CONTRACT = { + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.", +} + +TIMEOUT_SECONDS = 30 +DEFAULT_DURATION_MINUTES = 60 + +_WEEKDAYS = { + "monday": 0, + "mon": 0, + "tuesday": 1, + "tue": 1, + "tues": 1, + "wednesday": 2, + "wed": 2, + "thursday": 3, + "thu": 3, + "thur": 3, + "thurs": 3, + "friday": 4, + "fri": 4, + "saturday": 5, + "sat": 5, + "sunday": 6, + "sun": 6, +} +_WEEKDAY_RE = re.compile( + r"\b(" + "|".join(sorted(_WEEKDAYS, key=len, reverse=True)) + r")\b", re.I +) +_MONTHS = { + "jan": 1, + "feb": 2, + "mar": 3, + "apr": 4, + "may": 5, + "jun": 6, + "jul": 7, + "aug": 8, + "sep": 9, + "oct": 10, + "nov": 11, + "dec": 12, +} +_MONTH_ALT = ( + r"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?" + r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?" +) +_COMMAND_WORDS = re.compile( + r"\b(add|create|new|put|make|set\s*up|set|schedule|book|" + r"i\s+need\s+to|i\s+have\s+to|calendar|" + r"for|on|at|from|my|the|a|an|to)\b", + re.I, +) + + +class OutlookBridgeError(Exception): + """A real failure talking to the local Outlook bridge.""" + + +def _now(ctx): + return local_now(ctx.config) + + +def _post(ctx, path, payload): + base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/") + if not base: + raise OutlookBridgeError("outlook_bridge_url is not configured") + token = str(ctx.config.get("outlook_bridge_token", "") or "").strip() + data = json.dumps(payload).encode("utf-8") + headers = {"Content-Type": "application/json", "Accept": "application/json"} + if token: + headers["X-Semif-Token"] = token + http_request = urllib.request.Request(base + path, data=data, method="POST", headers=headers) + try: + with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response: + return json.loads(response.read().decode("utf-8") or "{}") + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace").strip()[:200] + raise OutlookBridgeError(f"POST {path}: HTTP {exc.code} {detail}") from exc + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + raise OutlookBridgeError(f"POST {path}: {exc}") from exc + + +def _month_number(token): + return _MONTHS.get(token.lower()[:3]) + + +def _resolve_month_day(month, day, year, now): + if not (month and 1 <= day <= 31): + return None + given_year = year is not None + year = year or now.year + try: + candidate = datetime(year, month, day).date() + except ValueError: + return None + if not given_year and candidate < now.date(): + try: + candidate = datetime(year + 1, month, day).date() + except ValueError: + return None + return candidate + + +def _parse_when(text, now): + """`{"date","date_span","time","time_span","all_day","duration_minutes","from_weekday"}`.""" + text = text or "" + result = { + "date": None, + "date_span": None, + "time": None, + "time_span": None, + "all_day": False, + "duration_minutes": None, + "from_weekday": False, + } + + match = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", text, re.I) + if match: + result["all_day"] = True + + match = re.search(r"\bfor\s+(\d+(?:\.\d+)?)\s*(hours?|hrs?|h)\b", text, re.I) + if match: + result["duration_minutes"] = int(round(float(match.group(1)) * 60)) + else: + match = re.search(r"\bfor\s+(\d+)\s*(minutes?|mins?|m)\b", text, re.I) + if match: + result["duration_minutes"] = int(match.group(1)) + else: + for phrase, minutes in ( + (r"\bfor\s+half\s+an?\s+hour\b", 30), + (r"\bfor\s+an?\s+hour\b", 60), + ): + match = re.search(phrase, text, re.I) + if match: + result["duration_minutes"] = minutes + break + + date = None + span = None + match = re.search(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", text) + if match: + try: + date = datetime(int(match.group(1)), int(match.group(2)), int(match.group(3))).date() + span = match.span() + except ValueError: + date = None + if date is None: + match = re.search( + r"\b(" + _MONTH_ALT + r")\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?\b", text, re.I + ) + if match: + month = _month_number(match.group(1)) + year = int(match.group(3)) if match.group(3) else None + date = _resolve_month_day(month, int(match.group(2)), year, now) + span = match.span() if date else None + if date is None: + match = re.search( + r"\b(\d{1,2})(?:st|nd|rd|th)?\s+(?:of\s+)?(" + _MONTH_ALT + r")(?:,?\s*(\d{4}))?\b", + text, + re.I, + ) + if match: + month = _month_number(match.group(2)) + year = int(match.group(3)) if match.group(3) else None + date = _resolve_month_day(month, int(match.group(1)), year, now) + span = match.span() if date else None + if date is None: + match = re.search(r"\b(today|tonight|tomorrow|tmrw|tomorow|next\s+week)\b", text, re.I) + if match: + word = re.sub(r"\s+", " ", match.group(1).lower()) + if word in ("today", "tonight"): + date = now.date() + elif word in ("tomorrow", "tmrw", "tomorow"): + date = now.date() + timedelta(days=1) + else: + date = now.date() + timedelta(days=7) + span = match.span() + if date is None: + match = _WEEKDAY_RE.search(text) + if match: + target = _WEEKDAYS[match.group(1).lower()] + date = now.date() + timedelta(days=(target - now.date().weekday()) % 7) + prefix = text[max(0, match.start() - 6) : match.start()] + if re.search(r"\bnext\s*$", prefix, re.I): + date += timedelta(days=7) + result["from_weekday"] = True + span = match.span() + + parsed_time = None + time_span = None + match = re.search(r"\bnoon\b", text, re.I) + if match: + parsed_time = time(12, 0) + time_span = match.span() + elif re.search(r"\bmidnight\b", text, re.I): + parsed_time = time(0, 0) + time_span = re.search(r"\bmidnight\b", text, re.I).span() + else: + match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I) + if match: + hour = int(match.group(1)) % 12 + minute = int(match.group(2) or 0) + if match.group(3).lower() == "p": + hour += 12 + if hour < 24 and minute < 60: + parsed_time = time(hour, minute) + time_span = match.span() + else: + match = re.search(r"\b(\d{1,2}):(\d{2})\b", text) + if match: + hour, minute = int(match.group(1)), int(match.group(2)) + if hour < 24 and minute < 60: + parsed_time = time(hour, minute) + time_span = match.span() + + result["date"] = date + result["date_span"] = span + result["time"] = parsed_time + result["time_span"] = time_span + return result + + +def _title(text, parsed): + remove = [parsed.get("date_span"), parsed.get("time_span")] + out = text + for span in sorted((s for s in remove if s), key=lambda s: s[0], reverse=True): + out = out[: span[0]] + " " + out[span[1] :] + phrase = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", out, re.I) + if phrase: + out = out[: phrase.start()] + " " + out[phrase.end() :] + cleaned = re.sub(r"\s+", " ", _COMMAND_WORDS.sub(" ", out)).strip(" .,:;-") + return cleaned + + +def _ask(request, field, question): + request.meta["create_event_awaiting"] = field + return ActionResult(action_log=f"waiting for {field}", new_state=request.text, needs_input=question) + + +def act(ctx, request): + answers = request.meta.setdefault("create_event_answers", {}) + awaiting = request.meta.get("create_event_awaiting") + if request.user_input is not None and awaiting: + answers[awaiting] = request.user_input.strip() + request.meta.pop("create_event_awaiting", None) + + now = _now(ctx) + parsed = _parse_when(request.text, now) + title = _title(request.text, parsed) + + if answers.get("title"): + title = answers["title"].strip() + for key in ("date", "time"): + if answers.get(key): + extra = _parse_when(answers[key], now) + if extra["date"] is not None: + parsed["date"] = extra["date"] + if extra["time"] is not None: + parsed["time"] = extra["time"] + if extra["all_day"]: + parsed["all_day"] = True + if extra["duration_minutes"]: + parsed["duration_minutes"] = extra["duration_minutes"] + + if not title: + return _ask(request, "title", "What should I call the event?") + if parsed["date"] is None: + return _ask(request, "date", f"What day should I schedule {title!r}?") + if not parsed["all_day"] and parsed["time"] is None: + return _ask(request, "time", f"What time should {title!r} start? (or say 'all day')") + + all_day = bool(parsed["all_day"]) + if all_day: + start = datetime.combine(parsed["date"], time(0, 0)) + else: + start = datetime.combine(parsed["date"], parsed["time"]) + if start <= now.replace(tzinfo=None) and parsed.get("from_weekday"): + start += timedelta(days=7) + + timezone_name = str(ctx.config.get("timezone", "") or "").strip() + payload = { + "subject": title, + "start": start.strftime("%Y-%m-%dT%H:%M:%S"), + "all_day": all_day, + } + if not all_day: + duration = timedelta(minutes=parsed["duration_minutes"] or DEFAULT_DURATION_MINUTES) + payload["end"] = (start + duration).strftime("%Y-%m-%dT%H:%M:%S") + if timezone_name: + payload["timezone"] = timezone_name + + try: + data = _post(ctx, "/calendars/events", payload) + except OutlookBridgeError as exc: + return ActionResult(action_log=str(exc), new_state=request.text) + + if all_day: + when_text = f"{start.date().isoformat()} (all day)" + else: + when_text = start.strftime("%Y-%m-%d %H:%M") + report = f"Created {title!r} on {when_text}." + return ActionResult(action_log=report, new_state=report) diff --git a/skills/outlook/create_event/skill.test.py b/skills/outlook/create_event/skill.test.py new file mode 100644 index 0000000..7205386 --- /dev/null +++ b/skills/outlook/create_event/skill.test.py @@ -0,0 +1,162 @@ +"""Hermetic mechanics test for outlook.create_event. + +Run from this folder: `python skill.test.py`. No external network: a loopback +http.server plays the local Outlook bridge's `/calendars/events` route and records +the payload. This proves the body derives the title/date/time, asks for a missing +piece and resumes, creates the event with a real POST, and fails honestly when +the bridge errors. It does NOT prove the live integration — only a real run +against the user's Microsoft account does. +""" + +import json +import sys +import threading +from datetime import datetime, timezone +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from semif_agent.decisions import Request +from semif_agent.skills import ActionContext + +import skill + +FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc) +skill._now = lambda ctx: FIXED_NOW + + +class FakeEngine: + def call(self, decision): # pragma: no cover - this skill makes no decision + raise AssertionError("outlook.create_event must not ask the decision engine") + + +class BridgeHandler(BaseHTTPRequestHandler): + status = 200 + posts = [] + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length) if length else b"" + if self.path != "/calendars/events": + self._send({"error": "not found"}, 404) + return + self.posts.append(json.loads(body.decode("utf-8"))) + if self.status != 200: + self._send({"error": "boom"}, self.status) + return + self._send({"ok": True, "id": "e1", "subject": self.posts[-1].get("subject")}, 201) + + def _send(self, payload, status): + body = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +def start_server(status=200): + handler = type("Handler", (BridgeHandler,), {"status": status, "posts": []}) + 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 context(url, tz=""): + config = {"outlook_bridge_url": url, "outlook_bridge_token": ""} + if tz: + config["timezone"] = tz + return ActionContext(engine=FakeEngine(), config=config) + + +def test_explicit_datetime(): + server, handler, url = start_server() + try: + action = skill.act(context(url), Request("add dentist appointment on 2026-11-10 at 2pm")) + assert action.needs_input is None, action.needs_input + post = handler.posts[0] + assert post["subject"] == "dentist appointment", post + assert post["start"] == "2026-11-10T14:00:00", post + assert post["end"] == "2026-11-10T15:00:00", post + assert post["all_day"] is False, post + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_timezone_is_sent(): + server, handler, url = start_server() + try: + skill.act( + context(url, tz="America/Chicago"), + Request("add lunch on 2026-11-10 at noon"), + ) + assert handler.posts[0]["timezone"] == "America/Chicago", handler.posts[0] + print(handler.posts[0]) + finally: + server.shutdown() + server.server_close() + + +def test_all_day_event(): + server, handler, url = start_server() + try: + skill.act(context(url), Request("add conference all day on 2026-11-10")) + post = handler.posts[0] + assert post["all_day"] is True, post + assert "end" not in post, post + assert post["subject"] == "conference", post + print(post) + finally: + server.shutdown() + server.server_close() + + +def test_missing_time_asks_then_creates(): + server, handler, url = start_server() + try: + ctx = context(url) + request = Request("add dentist appointment on 2026-11-10") + action = skill.act(ctx, request) + assert action.needs_input, "a missing start time must be asked" + assert handler.posts == [] + request.user_input = "2pm" + action = skill.act(ctx, request) + assert action.needs_input is None, action.needs_input + assert handler.posts[0]["start"] == "2026-11-10T14:00:00", handler.posts[0] + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_bridge_error_is_reported_honestly(): + server, _handler, url = start_server(status=502) + try: + request = Request("add dentist appointment on 2026-11-10 at 2pm") + action = skill.act(context(url), request) + assert "502" in action.action_log, action.action_log + assert action.new_state == request.text, "a failed create must not fake a result" + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def main(): + test_explicit_datetime() + test_timezone_is_sent() + test_all_day_event() + test_missing_time_asks_then_creates() + test_bridge_error_is_reported_honestly() + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1) diff --git a/skills/outlook/create_task/contract.json b/skills/outlook/create_task/contract.json new file mode 100644 index 0000000..ce8daaf --- /dev/null +++ b/skills/outlook/create_task/contract.json @@ -0,0 +1,4 @@ +{ + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth." +} diff --git a/skills/outlook/create_task/manifest.json b/skills/outlook/create_task/manifest.json new file mode 100644 index 0000000..0fb7c2f --- /dev/null +++ b/skills/outlook/create_task/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Add a task to the user's Microsoft To Do list, e.g. \"remind me to call the dentist tomorrow\"." +} diff --git a/skills/outlook/create_task/skill.py b/skills/outlook/create_task/skill.py new file mode 100644 index 0000000..d83c129 --- /dev/null +++ b/skills/outlook/create_task/skill.py @@ -0,0 +1,193 @@ +"""Add a task to the user's Microsoft To Do list. + +Real integration: the local Outlook bridge (Microsoft Graph). Connection comes +from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never +speaks Graph or OAuth directly. `act` derives the task title and an optional due +date from `request.text`; a missing title is asked one at a time and the answer +is stashed in `request.meta` (act re-runs from the top after a `needs_input` +pause, so a question is never asked twice). The task is created with a real +`POST /tasks` and the real outcome reported. +""" + +from __future__ import annotations + +import json +import re +import urllib.error +import urllib.parse +import urllib.request +from datetime import datetime, timedelta + +from semif_agent.skills import ActionResult +from semif_agent.timers import local_now + +INTEGRATION = { + "service": "outlook", + "transport": "http", + "config_vars": ["outlook_bridge_url", "outlook_bridge_token"], +} + +CONTRACT = { + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.", +} + +TIMEOUT_SECONDS = 30 + +_WEEKDAYS = { + "monday": 0, + "mon": 0, + "tuesday": 1, + "tue": 1, + "tues": 1, + "wednesday": 2, + "wed": 2, + "thursday": 3, + "thu": 3, + "thur": 3, + "thurs": 3, + "friday": 4, + "fri": 4, + "saturday": 5, + "sat": 5, + "sunday": 6, + "sun": 6, +} +_WEEKDAY_RE = re.compile( + r"\b(" + "|".join(sorted(_WEEKDAYS, key=len, reverse=True)) + r")\b", re.I +) +_MONTHS = { + "jan": 1, + "feb": 2, + "mar": 3, + "apr": 4, + "may": 5, + "jun": 6, + "jul": 7, + "aug": 8, + "sep": 9, + "oct": 10, + "nov": 11, + "dec": 12, +} +_MONTH_ALT = ( + r"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?" + r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?" +) +_COMMAND_WORDS = re.compile( + r"\b(add|create|new|put|make|set\s*up|set|schedule|remind\s+me(?:\s+to)?|" + r"i\s+need\s+to|i\s+have\s+to|tasks|task|to-?dos|to-?do|todo|lists|list|for|by|due|on|" + r"my|the|a|an|to)\b", + re.I, +) + + +class OutlookBridgeError(Exception): + """A real failure talking to the local Outlook bridge.""" + + +def _now(ctx): + return local_now(ctx.config) + + +def _post(ctx, path, payload): + base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/") + if not base: + raise OutlookBridgeError("outlook_bridge_url is not configured") + token = str(ctx.config.get("outlook_bridge_token", "") or "").strip() + data = json.dumps(payload).encode("utf-8") + headers = {"Content-Type": "application/json", "Accept": "application/json"} + if token: + headers["X-Semif-Token"] = token + http_request = urllib.request.Request(base + path, data=data, method="POST", headers=headers) + try: + with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response: + return json.loads(response.read().decode("utf-8") or "{}") + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace").strip()[:200] + raise OutlookBridgeError(f"POST {path}: HTTP {exc.code} {detail}") from exc + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + raise OutlookBridgeError(f"POST {path}: {exc}") from exc + + +def _match_due(text, now): + """Return `(due_date | None, matched_span | None)` for the due date.""" + match = re.search(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", text) + if match: + try: + return datetime(int(match.group(1)), int(match.group(2)), int(match.group(3))).date(), match.span() + except ValueError: + return None, None + match = re.search(r"\b(" + _MONTH_ALT + r")\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?\b", text, re.I) + if match: + month = _MONTHS.get(match.group(1).lower()[:3]) + year = int(match.group(3)) if match.group(3) else now.year + try: + candidate = datetime(year, month, int(match.group(2))).date() + except (TypeError, ValueError): + return None, None + if not match.group(3) and candidate < now.date(): + candidate = candidate.replace(year=year + 1) + return candidate, match.span() + match = re.search(r"\b(today|tonight|tomorrow|tmrw|next\s+week)\b", text, re.I) + if match: + word = re.sub(r"\s+", " ", match.group(1).lower()) + if word in ("today", "tonight"): + return now.date(), match.span() + if word in ("tomorrow", "tmrw"): + return now.date() + timedelta(days=1), match.span() + return now.date() + timedelta(days=7), match.span() + match = _WEEKDAY_RE.search(text) + if match: + target = _WEEKDAYS[match.group(1).lower()] + date = now.date() + timedelta(days=(target - now.date().weekday()) % 7) + return date, match.span() + return None, None + + +def _title(text, span): + stripped = text + if span is not None: + stripped = text[: span[0]] + " " + text[span[1] :] + cleaned = re.sub(r"\s+", " ", _COMMAND_WORDS.sub(" ", stripped)).strip(" .,:;-") + return cleaned + + +def _ask(request, field, question): + request.meta["create_task_awaiting"] = field + return ActionResult(action_log=f"waiting for {field}", new_state=request.text, needs_input=question) + + +def act(ctx, request): + answers = request.meta.setdefault("create_task_answers", {}) + awaiting = request.meta.get("create_task_awaiting") + if request.user_input is not None and awaiting: + answers[awaiting] = request.user_input.strip() + request.meta.pop("create_task_awaiting", None) + + now = _now(ctx) + due, span = _match_due(request.text, now) + title = _title(request.text, span) + + if answers.get("title"): + title = answers["title"].strip() + if answers.get("due"): + extra_due, _ = _match_due(answers["due"], now) + if extra_due is not None: + due = extra_due + + if not title: + return _ask(request, "title", "What's the task?") + + payload = {"title": title} + if due is not None: + payload["due"] = f"{due.isoformat()}T00:00:00" + + try: + data = _post(ctx, "/tasks", payload) + except OutlookBridgeError as exc: + return ActionResult(action_log=str(exc), new_state=request.text) + + when = f" due {due.isoformat()}" if due is not None else "" + report = f"Added task {title!r}{when}." + return ActionResult(action_log=report, new_state=report) diff --git a/skills/outlook/create_task/skill.test.py b/skills/outlook/create_task/skill.test.py new file mode 100644 index 0000000..dacd8a8 --- /dev/null +++ b/skills/outlook/create_task/skill.test.py @@ -0,0 +1,144 @@ +"""Hermetic mechanics test for outlook.create_task. + +Run from this folder: `python skill.test.py`. No external network: a loopback +http.server plays the local Outlook bridge's `/tasks` route and records the +payload. This proves the body derives a title + due date, asks for a missing +title and resumes, creates the task with a real POST, and fails honestly when the +bridge errors. It does NOT prove the live integration — only a real run against +the user's Microsoft account does. +""" + +import json +import sys +import threading +from datetime import datetime, timezone +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from semif_agent.decisions import Request +from semif_agent.skills import ActionContext + +import skill + +FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc) +skill._now = lambda ctx: FIXED_NOW + + +class FakeEngine: + def call(self, decision): # pragma: no cover - this skill makes no decision + raise AssertionError("outlook.create_task must not ask the decision engine") + + +class BridgeHandler(BaseHTTPRequestHandler): + status = 200 + posts = [] + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length) if length else b"" + if self.path != "/tasks": + self._send({"error": "not found"}, 404) + return + self.posts.append(json.loads(body.decode("utf-8"))) + if self.status != 200: + self._send({"error": "boom"}, self.status) + return + self._send({"ok": True, "id": "t1", "title": self.posts[-1].get("title")}, 201) + + def _send(self, payload, status): + body = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +def start_server(status=200): + handler = type("Handler", (BridgeHandler,), {"status": status, "posts": []}) + 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 config(url): + return {"outlook_bridge_url": url, "outlook_bridge_token": ""} + + +def test_plain_task(): + server, handler, url = start_server() + try: + ctx = ActionContext(engine=FakeEngine(), config=config(url)) + action = skill.act(ctx, Request("add buy milk to my tasks")) + assert action.needs_input is None, action.needs_input + assert handler.posts[0]["title"] == "buy milk", handler.posts[0] + assert "due" not in handler.posts[0], handler.posts[0] + assert "buy milk" in action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_task_with_due_date(): + server, handler, url = start_server() + try: + ctx = ActionContext(engine=FakeEngine(), config=config(url)) + action = skill.act(ctx, Request("remind me to call the dentist tomorrow")) + assert action.needs_input is None, action.needs_input + assert handler.posts[0]["title"] == "call dentist", handler.posts[0] + assert handler.posts[0]["due"] == "2026-10-08T00:00:00", handler.posts[0] + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_missing_title_asks_then_creates(): + server, handler, url = start_server() + try: + ctx = ActionContext(engine=FakeEngine(), config=config(url)) + request = Request("add a task") + action = skill.act(ctx, request) + assert action.needs_input, "a missing title must be asked" + assert handler.posts == [] + request.user_input = "water the plants" + action = skill.act(ctx, request) + assert action.needs_input is None, action.needs_input + assert handler.posts[0]["title"] == "water the plants", handler.posts[0] + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_bridge_error_is_reported_honestly(): + server, _handler, url = start_server(status=502) + try: + ctx = ActionContext(engine=FakeEngine(), config=config(url)) + request = Request("add buy milk to my tasks") + action = skill.act(ctx, request) + assert "502" in action.action_log, action.action_log + assert action.new_state == request.text, "a failed create must not fake a result" + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def main(): + test_plain_task() + test_task_with_due_date() + test_missing_title_asks_then_creates() + test_bridge_error_is_reported_honestly() + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1) diff --git a/skills/outlook/list_contacts/contract.json b/skills/outlook/list_contacts/contract.json new file mode 100644 index 0000000..ce8daaf --- /dev/null +++ b/skills/outlook/list_contacts/contract.json @@ -0,0 +1,4 @@ +{ + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth." +} diff --git a/skills/outlook/list_contacts/manifest.json b/skills/outlook/list_contacts/manifest.json new file mode 100644 index 0000000..7d322dd --- /dev/null +++ b/skills/outlook/list_contacts/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Look up a person in the user's Outlook contacts by name, email, or company." +} diff --git a/skills/outlook/list_contacts/skill.py b/skills/outlook/list_contacts/skill.py new file mode 100644 index 0000000..8d42bc5 --- /dev/null +++ b/skills/outlook/list_contacts/skill.py @@ -0,0 +1,86 @@ +"""Look up a person in the user's Outlook contacts. + +Real integration: the local Outlook bridge (Microsoft Graph). Connection comes +from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never +speaks Graph or OAuth directly. It searches the contacts for the words in the +request and reports the matches, or the real failure honestly. +""" + +from __future__ import annotations + +import json +import re +import urllib.error +import urllib.parse +import urllib.request + +from semif_agent.skills import ActionResult + +INTEGRATION = { + "service": "outlook", + "transport": "http", + "config_vars": ["outlook_bridge_url", "outlook_bridge_token"], +} + +CONTRACT = { + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.", +} + +TIMEOUT_SECONDS = 30 +_STOPWORDS = re.compile( + r"\b(find|search|look\s*up|show|get|whats|what's|contact|contacts|email|e-?mail|" + r"address|phone|number|details|for|my|me|the|of|a|an)\b", + re.I, +) + + +class OutlookBridgeError(Exception): + """A real failure talking to the local Outlook bridge.""" + + +def _get(ctx, path, params=None): + base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/") + if not base: + raise OutlookBridgeError("outlook_bridge_url is not configured") + token = str(ctx.config.get("outlook_bridge_token", "") or "").strip() + url = base + path + if params: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params) + headers = {"Accept": "application/json"} + if token: + headers["X-Semif-Token"] = token + http_request = urllib.request.Request(url, method="GET", headers=headers) + try: + with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response: + return json.loads(response.read().decode("utf-8") or "{}") + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace").strip()[:200] + raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + raise OutlookBridgeError(f"GET {path}: {exc}") from exc + + +def _query(text): + return re.sub(r"\s+", " ", _STOPWORDS.sub(" ", text or "")).strip() + + +def act(ctx, request): + try: + data = _get(ctx, "/contacts", {"query": _query(request.text)}) + except OutlookBridgeError as exc: + return ActionResult(action_log=str(exc), new_state=request.text) + + contacts = data.get("contacts") or [] + if not contacts: + return ActionResult(action_log="No matching contacts.", new_state="No matching contacts.") + + lines = [] + for contact in contacts[:5]: + name = contact.get("display_name") or "(no name)" + emails = ", ".join(contact.get("emails") or []) + phones = ", ".join(contact.get("phones") or []) + bits = " | ".join(part for part in (emails, phones) if part) + lines.append(f"- {name}: {bits}" if bits else f"- {name}") + report = "Contacts:\n" + "\n".join(lines) + return ActionResult(action_log=report, new_state=report) diff --git a/skills/outlook/list_contacts/skill.test.py b/skills/outlook/list_contacts/skill.test.py new file mode 100644 index 0000000..63d153c --- /dev/null +++ b/skills/outlook/list_contacts/skill.test.py @@ -0,0 +1,132 @@ +"""Hermetic mechanics test for outlook.list_contacts. + +Run from this folder: `python skill.test.py`. No external network: a loopback +http.server plays the local Outlook bridge's `/contacts` route and records the +query it received. This proves the body searches the contacts and reports the +matches (and fails honestly when the bridge is unavailable). It does NOT prove +the live integration — only a real run against the user's Microsoft account does. +""" + +import json +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse + +from semif_agent.decisions import Request +from semif_agent.skills import ActionContext + +import skill + + +class FakeEngine: + def call(self, decision): # pragma: no cover - this skill makes no decision + raise AssertionError("outlook.list_contacts must not ask the decision engine") + + +class BridgeHandler(BaseHTTPRequestHandler): + contacts = [] + status = 200 + queries = [] + + def do_GET(self): + if self.status != 200: + self._send({"error": "boom"}, self.status) + return + parsed = urlparse(self.path) + if parsed.path == "/contacts": + self.queries.append(parse_qs(parsed.query).get("query", [""])[0]) + self._send({"contacts": self.contacts}, 200) + return + self._send({"error": "not found"}, 404) + + def _send(self, payload, status): + body = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +def start_server(contacts=None, status=200): + handler = type( + "Handler", + (BridgeHandler,), + { + "contacts": contacts + if contacts is not None + else [ + { + "id": "c1", + "display_name": "Bob Smith", + "emails": ["bob@example.com"], + "phones": ["555-1234"], + } + ], + "status": status, + "queries": [], + }, + ) + 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 run(url, text="find Bob's email"): + ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""}) + return skill.act(ctx, Request(text)) + + +def test_reports_matching_contacts(): + server, handler, url = start_server() + try: + action = run(url) + assert "Bob Smith" in action.action_log, action.action_log + assert "bob@example.com" in action.action_log, action.action_log + assert handler.queries and "Bob" in handler.queries[0], handler.queries + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_no_matches_is_reported(): + server, _handler, url = start_server(contacts=[]) + try: + action = run(url) + assert "no matching contacts" in action.action_log.lower(), action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_bridge_error_is_reported_honestly(): + server, _handler, url = start_server(status=502) + try: + action = run(url) + assert "502" in action.action_log, action.action_log + assert action.new_state == "find Bob's email" + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def main(): + test_reports_matching_contacts() + test_no_matches_is_reported() + test_bridge_error_is_reported_honestly() + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1) diff --git a/skills/outlook/list_files/contract.json b/skills/outlook/list_files/contract.json new file mode 100644 index 0000000..ce8daaf --- /dev/null +++ b/skills/outlook/list_files/contract.json @@ -0,0 +1,4 @@ +{ + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth." +} diff --git a/skills/outlook/list_files/manifest.json b/skills/outlook/list_files/manifest.json new file mode 100644 index 0000000..68bf1a6 --- /dev/null +++ b/skills/outlook/list_files/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "List the user's OneDrive files, optionally in a named folder." +} diff --git a/skills/outlook/list_files/skill.py b/skills/outlook/list_files/skill.py new file mode 100644 index 0000000..9c60fbb --- /dev/null +++ b/skills/outlook/list_files/skill.py @@ -0,0 +1,92 @@ +"""List the user's OneDrive files. + +Real integration: the local Outlook bridge (Microsoft Graph). Connection comes +from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never +speaks Graph or OAuth directly. It lists a OneDrive folder (root by default) and +reports the entries, or the real failure honestly. +""" + +from __future__ import annotations + +import json +import re +import urllib.error +import urllib.parse +import urllib.request + +from semif_agent.skills import ActionResult + +INTEGRATION = { + "service": "outlook", + "transport": "http", + "config_vars": ["outlook_bridge_url", "outlook_bridge_token"], +} + +CONTRACT = { + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.", +} + +TIMEOUT_SECONDS = 30 +_STOPWORDS = re.compile( + r"\b(list|show|what'?s|whats|in|my|the|onedrive|files|file|folder|drive|of|me)\b", + re.I, +) + + +class OutlookBridgeError(Exception): + """A real failure talking to the local Outlook bridge.""" + + +def _get(ctx, path, params=None): + base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/") + if not base: + raise OutlookBridgeError("outlook_bridge_url is not configured") + token = str(ctx.config.get("outlook_bridge_token", "") or "").strip() + url = base + path + if params: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params) + headers = {"Accept": "application/json"} + if token: + headers["X-Semif-Token"] = token + http_request = urllib.request.Request(url, method="GET", headers=headers) + try: + with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response: + return json.loads(response.read().decode("utf-8") or "{}") + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace").strip()[:200] + raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + raise OutlookBridgeError(f"GET {path}: {exc}") from exc + + +def _folder(text): + cleaned = re.sub(r"\s+", " ", _STOPWORDS.sub(" ", text or "")).strip() + return cleaned or "/" + + +def act(ctx, request): + path = _folder(request.text) + try: + data = _get(ctx, "/files", {"path": path}) + except OutlookBridgeError as exc: + return ActionResult(action_log=str(exc), new_state=request.text) + + entries = data.get("entries") or [] + if not entries: + return ActionResult( + action_log=f"{data.get('path') or path} is empty.", + new_state=f"{data.get('path') or path} is empty.", + ) + + lines = [] + for entry in entries[:20]: + name = entry.get("name") or "(unnamed)" + kind = "folder" if entry.get("is_folder") else "file" + size = entry.get("size") + detail = f"{kind}" + if kind == "file" and size is not None: + detail += f", {size} bytes" + lines.append(f"- {name} ({detail})") + report = f"Files in {data.get('path') or path}:\n" + "\n".join(lines) + return ActionResult(action_log=report, new_state=report) diff --git a/skills/outlook/list_files/skill.test.py b/skills/outlook/list_files/skill.test.py new file mode 100644 index 0000000..1ae7c0f --- /dev/null +++ b/skills/outlook/list_files/skill.test.py @@ -0,0 +1,141 @@ +"""Hermetic mechanics test for outlook.list_files. + +Run from this folder: `python skill.test.py`. No external network: a loopback +http.server plays the local Outlook bridge's `/files` route and records the path +it received. This proves the body lists OneDrive and reports the entries (and +fails honestly when the bridge is unavailable). It does NOT prove the live +integration — only a real run against the user's Microsoft account does. +""" + +import json +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse + +from semif_agent.decisions import Request +from semif_agent.skills import ActionContext + +import skill + + +class FakeEngine: + def call(self, decision): # pragma: no cover - this skill makes no decision + raise AssertionError("outlook.list_files must not ask the decision engine") + + +class BridgeHandler(BaseHTTPRequestHandler): + entries = [] + status = 200 + paths = [] + + def do_GET(self): + if self.status != 200: + self._send({"error": "boom"}, self.status) + return + parsed = urlparse(self.path) + if parsed.path == "/files": + path = parse_qs(parsed.query).get("path", ["/"])[0] + self.paths.append(path) + self._send({"path": path, "entries": self.entries}, 200) + return + self._send({"error": "not found"}, 404) + + def _send(self, payload, status): + body = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +def start_server(entries=None, status=200): + handler = type( + "Handler", + (BridgeHandler,), + { + "entries": entries + if entries is not None + else [ + {"id": "d1", "name": "Docs", "is_folder": True, "size": 0}, + {"id": "f1", "name": "notes.txt", "is_folder": False, "size": 5}, + ], + "status": status, + "paths": [], + }, + ) + 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 run(url, text="list my files"): + ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""}) + return skill.act(ctx, Request(text)) + + +def test_lists_root_files(): + server, handler, url = start_server() + try: + action = run(url) + assert "Docs (folder)" in action.action_log, action.action_log + assert "notes.txt (file, 5 bytes)" in action.action_log, action.action_log + assert handler.paths and handler.paths[0] == "/", handler.paths + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_named_folder_is_requested(): + server, handler, url = start_server() + try: + run(url, "list files in Documents") + assert handler.paths and handler.paths[0] == "Documents", handler.paths + print(handler.paths) + finally: + server.shutdown() + server.server_close() + + +def test_empty_folder_is_reported(): + server, _handler, url = start_server(entries=[]) + try: + action = run(url) + assert "empty" in action.action_log.lower(), action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_bridge_error_is_reported_honestly(): + server, _handler, url = start_server(status=502) + try: + action = run(url) + assert "502" in action.action_log, action.action_log + assert action.new_state == "list my files" + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def main(): + test_lists_root_files() + test_named_folder_is_requested() + test_empty_folder_is_reported() + test_bridge_error_is_reported_honestly() + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1) diff --git a/skills/outlook/next_event/contract.json b/skills/outlook/next_event/contract.json new file mode 100644 index 0000000..ce8daaf --- /dev/null +++ b/skills/outlook/next_event/contract.json @@ -0,0 +1,4 @@ +{ + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth." +} diff --git a/skills/outlook/next_event/manifest.json b/skills/outlook/next_event/manifest.json new file mode 100644 index 0000000..1f4279e --- /dev/null +++ b/skills/outlook/next_event/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Read the user's upcoming Outlook calendar events." +} diff --git a/skills/outlook/next_event/skill.py b/skills/outlook/next_event/skill.py new file mode 100644 index 0000000..7dc6453 --- /dev/null +++ b/skills/outlook/next_event/skill.py @@ -0,0 +1,89 @@ +"""Read the user's upcoming Outlook calendar events. + +Real integration: the local Outlook bridge (Microsoft Graph). Connection comes +from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never +speaks Graph or OAuth directly. It asks the bridge for the upcoming events and +reports them, or reports the real failure honestly. +""" + +from __future__ import annotations + +import json +import urllib.error +import urllib.parse +import urllib.request + +from semif_agent.skills import ActionResult + +INTEGRATION = { + "service": "outlook", + "transport": "http", + "config_vars": ["outlook_bridge_url", "outlook_bridge_token"], +} + +CONTRACT = { + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.", +} + +TIMEOUT_SECONDS = 30 +DEFAULT_COUNT = 5 + + +class OutlookBridgeError(Exception): + """A real failure talking to the local Outlook bridge.""" + + +def _get(ctx, path, params=None): + base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/") + if not base: + raise OutlookBridgeError("outlook_bridge_url is not configured") + token = str(ctx.config.get("outlook_bridge_token", "") or "").strip() + url = base + path + if params: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params) + headers = {"Accept": "application/json"} + if token: + headers["X-Semif-Token"] = token + http_request = urllib.request.Request(url, method="GET", headers=headers) + try: + with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response: + return json.loads(response.read().decode("utf-8") or "{}") + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace").strip()[:200] + raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + raise OutlookBridgeError(f"GET {path}: {exc}") from exc + + +def act(ctx, request): + try: + data = _get(ctx, "/calendars/events") + except OutlookBridgeError as exc: + return ActionResult(action_log=str(exc), new_state=request.text) + + events = data.get("events") or [] + if not events: + return ActionResult(action_log="There are no upcoming events.", new_state="No upcoming events.") + + lines = [] + for event in events[:DEFAULT_COUNT]: + subject = event.get("subject") or "(no subject)" + start = event.get("start") or "" + when = _describe_when(start, bool(event.get("all_day"))) + location = event.get("location") or "" + where = f" at {location}" if location else "" + lines.append(f"- {subject}{where} — {when}") + report = "Upcoming events:\n" + "\n".join(lines) + return ActionResult(action_log=report, new_state=report) + + +def _describe_when(start, all_day): + """A short human time: the date (all-day) or date + time.""" + text = str(start or "").strip() + if not text: + return "time unknown" + date, _, rest = text.partition("T") + if all_day or not rest: + return f"{date} (all day)" if all_day else date + return f"{date} {rest[:5]}" diff --git a/skills/outlook/next_event/skill.test.py b/skills/outlook/next_event/skill.test.py new file mode 100644 index 0000000..65d0f99 --- /dev/null +++ b/skills/outlook/next_event/skill.test.py @@ -0,0 +1,136 @@ +"""Hermetic mechanics test for outlook.next_event. + +Run from this folder: `python skill.test.py`. No external network: a loopback +http.server plays the local Outlook bridge's `/calendars/events` route. This +proves the body asks the bridge for upcoming events and reports them (and fails +honestly when the bridge is unavailable). It does NOT prove the live +integration — only a real run against the user's Microsoft account does. +""" + +import json +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from semif_agent.decisions import Request +from semif_agent.skills import ActionContext + +import skill + + +class FakeEngine: + def call(self, decision): # pragma: no cover - this skill makes no decision + raise AssertionError("outlook.next_event must not ask the decision engine") + + +class BridgeHandler(BaseHTTPRequestHandler): + events = [] + status = 200 + + def do_GET(self): + if self.status != 200: + self._send({"error": "boom"}, self.status) + return + if self.path.startswith("/calendars/events"): + self._send({"calendar": "", "events": self.events}, 200) + return + self._send({"error": "not found"}, 404) + + def _send(self, payload, status): + body = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +def start_server(events=None, status=200): + handler = type( + "Handler", + (BridgeHandler,), + { + "events": events + if events is not None + else [ + { + "id": "e1", + "subject": "Standup", + "start": "2026-10-08T09:00:00.0000000", + "end": "2026-10-08T09:30:00.0000000", + "all_day": False, + "location": "Room 1", + } + ], + "status": status, + }, + ) + server = ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, f"http://127.0.0.1:{server.server_address[1]}" + + +def run(url, text="what's on my calendar"): + ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""}) + return skill.act(ctx, Request(text)) + + +def test_reports_upcoming_events(): + server, url = start_server() + try: + action = run(url) + assert "Standup" in action.action_log, action.action_log + assert "Room 1" in action.action_log, action.action_log + assert "2026-10-08 09:00" in action.action_log, action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_no_events_is_reported(): + server, url = start_server(events=[]) + try: + action = run(url) + assert "no upcoming events" in action.action_log.lower(), action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_bridge_error_is_reported_honestly(): + server, url = start_server(status=502) + try: + action = run(url) + assert "502" in action.action_log, action.action_log + assert action.new_state == "what's on my calendar" + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_unreachable_bridge_fails_honestly(): + action = run("http://127.0.0.1:1") + assert action.new_state == "what's on my calendar" + print(action.action_log) + + +def main(): + test_reports_upcoming_events() + test_no_events_is_reported() + test_bridge_error_is_reported_honestly() + test_unreachable_bridge_fails_honestly() + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1) diff --git a/skills/outlook/next_message/contract.json b/skills/outlook/next_message/contract.json new file mode 100644 index 0000000..ce8daaf --- /dev/null +++ b/skills/outlook/next_message/contract.json @@ -0,0 +1,4 @@ +{ + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth." +} diff --git a/skills/outlook/next_message/manifest.json b/skills/outlook/next_message/manifest.json new file mode 100644 index 0000000..ea81f7b --- /dev/null +++ b/skills/outlook/next_message/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Read the latest messages from the user's Outlook inbox." +} diff --git a/skills/outlook/next_message/skill.py b/skills/outlook/next_message/skill.py new file mode 100644 index 0000000..eefccbc --- /dev/null +++ b/skills/outlook/next_message/skill.py @@ -0,0 +1,77 @@ +"""Read the latest messages from the user's Outlook inbox. + +Real integration: the local Outlook bridge (Microsoft Graph). Connection comes +from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never +speaks Graph or OAuth directly. It asks the bridge for the newest inbox messages +and reports them, or reports the real failure honestly. +""" + +from __future__ import annotations + +import json +import urllib.error +import urllib.parse +import urllib.request + +from semif_agent.skills import ActionResult + +INTEGRATION = { + "service": "outlook", + "transport": "http", + "config_vars": ["outlook_bridge_url", "outlook_bridge_token"], +} + +CONTRACT = { + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.", +} + +TIMEOUT_SECONDS = 30 +DEFAULT_COUNT = 5 + + +class OutlookBridgeError(Exception): + """A real failure talking to the local Outlook bridge.""" + + +def _get(ctx, path, params=None): + base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/") + if not base: + raise OutlookBridgeError("outlook_bridge_url is not configured") + token = str(ctx.config.get("outlook_bridge_token", "") or "").strip() + url = base + path + if params: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params) + headers = {"Accept": "application/json"} + if token: + headers["X-Semif-Token"] = token + http_request = urllib.request.Request(url, method="GET", headers=headers) + try: + with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response: + return json.loads(response.read().decode("utf-8") or "{}") + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace").strip()[:200] + raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + raise OutlookBridgeError(f"GET {path}: {exc}") from exc + + +def act(ctx, request): + try: + data = _get(ctx, "/mail/messages", {"folder": "inbox", "count": DEFAULT_COUNT}) + except OutlookBridgeError as exc: + return ActionResult(action_log=str(exc), new_state=request.text) + + messages = data.get("messages") or [] + if not messages: + return ActionResult(action_log="The inbox is empty.", new_state="The inbox is empty.") + + lines = [] + for message in messages[:DEFAULT_COUNT]: + sender = message.get("from") or "unknown sender" + subject = message.get("subject") or "(no subject)" + received = message.get("received") or "" + flag = " (unread)" if not message.get("is_read") else "" + lines.append(f"- {sender}: {subject}{flag} [{received}]") + report = "Recent inbox messages:\n" + "\n".join(lines) + return ActionResult(action_log=report, new_state=report) diff --git a/skills/outlook/next_message/skill.test.py b/skills/outlook/next_message/skill.test.py new file mode 100644 index 0000000..f1adca6 --- /dev/null +++ b/skills/outlook/next_message/skill.test.py @@ -0,0 +1,140 @@ +"""Hermetic mechanics test for outlook.next_message. + +Run from this folder: `python skill.test.py`. No external network: a loopback +http.server plays the local Outlook bridge's `/mail/messages` route. This proves +the body asks the bridge for the inbox and reports the messages (and fails +honestly when the bridge is unavailable). It does NOT prove the live +integration — only a real run against the user's Microsoft account does. +""" + +import json +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from semif_agent.decisions import Request +from semif_agent.skills import ActionContext + +import skill + + +class FakeEngine: + def call(self, decision): # pragma: no cover - this skill makes no decision + raise AssertionError("outlook.next_message must not ask the decision engine") + + +class BridgeHandler(BaseHTTPRequestHandler): + messages = [] + requests = [] + status = 200 + + def do_GET(self): + self.requests.append(self.path) + if self.status != 200: + self._send({"error": "boom"}, self.status) + return + if self.path.startswith("/mail/messages"): + self._send({"folder": "inbox", "messages": self.messages}, 200) + return + self._send({"error": "not found"}, 404) + + def _send(self, payload, status): + body = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +def start_server(messages=None, status=200): + handler = type( + "Handler", + (BridgeHandler,), + { + "messages": messages + if messages is not None + else [ + { + "id": "m1", + "subject": "Lunch?", + "from": "Sam ", + "received": "2026-10-08T12:00:00Z", + "is_read": False, + } + ], + "requests": [], + "status": status, + }, + ) + 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 run(url, text="check my email"): + ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""}) + return skill.act(ctx, Request(text)) + + +def test_reports_recent_messages(): + server, handler, url = start_server() + try: + action = run(url) + assert "Lunch?" in action.action_log, action.action_log + assert "sam@example.com" in action.action_log, action.action_log + assert action.new_state == action.action_log + assert handler.requests, "the bridge must be called" + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_empty_inbox_is_reported(): + server, _handler, url = start_server(messages=[]) + try: + action = run(url) + assert "empty" in action.action_log.lower(), action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_bridge_error_is_reported_honestly(): + server, _handler, url = start_server(status=502) + try: + action = run(url) + assert "502" in action.action_log, action.action_log + assert action.new_state == "check my email", "a failed read must not fake a result" + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_unreachable_bridge_fails_honestly(): + action = run("http://127.0.0.1:1") + assert "outlook.next_message" not in action.action_log, action.action_log + assert action.new_state == "check my email" + print(action.action_log) + + +def main(): + test_reports_recent_messages() + test_empty_inbox_is_reported() + test_bridge_error_is_reported_honestly() + test_unreachable_bridge_fails_honestly() + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1) diff --git a/skills/outlook/send_message/contract.json b/skills/outlook/send_message/contract.json new file mode 100644 index 0000000..0da6abf --- /dev/null +++ b/skills/outlook/send_message/contract.json @@ -0,0 +1,6 @@ +{ + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.", + "llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to compose the message.", + "llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth." +} diff --git a/skills/outlook/send_message/manifest.json b/skills/outlook/send_message/manifest.json new file mode 100644 index 0000000..88473f7 --- /dev/null +++ b/skills/outlook/send_message/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Compose and send an Outlook email, after confirming the message." +} diff --git a/skills/outlook/send_message/skill.py b/skills/outlook/send_message/skill.py new file mode 100644 index 0000000..227790d --- /dev/null +++ b/skills/outlook/send_message/skill.py @@ -0,0 +1,201 @@ +"""Send an Outlook email on the user's behalf, after a confirmation. + +Real integration: the local Outlook bridge (Microsoft Graph) to resolve the +recipient and send, and the local LLM bridge to turn the request into a +`{recipient, subject, body}` draft. Connection comes from `ctx.config` +(`outlook_bridge_url`, `outlook_bridge_token`, `llm_bridge_url`, +`llm_bridge_token`); the body never speaks Graph, OAuth, or the model's protocol +directly. + +Because sending is irreversible, the body **asks for confirmation before it +sends**: it composes the message, resolves the recipient (an explicit address is +used as-is; otherwise the contacts are searched and, when several match, a SemIf +choice picks one), then pauses with "Send ...? (yes/no)". A `yes` sends for real; +anything else cancels. A missing recipient is asked for. +""" + +from __future__ import annotations + +import json +import urllib.error +import urllib.parse +import urllib.request + +from semif_agent.decisions import DecisionRequest, Option +from semif_agent.skills import ActionResult + +INTEGRATION = { + "service": "outlook", + "transport": "http", + "config_vars": [ + "outlook_bridge_url", + "outlook_bridge_token", + "llm_bridge_url", + "llm_bridge_token", + ], +} + +CONTRACT = { + "outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).", + "outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.", + "llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to compose the message.", + "llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.", +} + +TIMEOUT_SECONDS = 30 +_YES = {"y", "yes", "send", "ok", "okay", "sure", "confirm"} + + +class OutlookBridgeError(Exception): + """A real failure talking to the local Outlook or LLM bridge.""" + + +def _request(ctx, service, path, *, method="GET", params=None, payload=None): + if service == "llm": + base = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/") + token = str(ctx.config.get("llm_bridge_token", "") or "").strip() + else: + base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/") + token = str(ctx.config.get("outlook_bridge_token", "") or "").strip() + if not base: + raise OutlookBridgeError(f"the {service} bridge URL is not configured") + url = base + path + if params: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params) + data = json.dumps(payload).encode("utf-8") if payload is not None else None + headers = {"Accept": "application/json"} + if data is not None: + headers["Content-Type"] = "application/json" + if token: + headers["X-Semif-Token"] = token + http_request = urllib.request.Request(url, data=data, method=method, headers=headers) + try: + with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response: + return json.loads(response.read().decode("utf-8") or "{}") + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace").strip()[:200] + raise OutlookBridgeError(f"{method} {path}: HTTP {exc.code} {detail}") from exc + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + raise OutlookBridgeError(f"{method} {path}: {exc}") from exc + + +def _compose(ctx, request): + """Ask the LLM bridge for the recipient, subject, and body.""" + messages = [ + { + "role": "system", + "content": ( + "Turn the user's request into an email. Reply with ONLY a JSON " + 'object: {"recipient": "", ' + '"subject": "", "body": ""}.' + ), + }, + {"role": "user", "content": request.text}, + ] + data = _request(ctx, "llm", "/chat", method="POST", payload={"messages": messages}) + text = str(data.get("text") or "") + start, end = text.find("{"), text.rfind("}") + if start == -1 or end < start: + raise OutlookBridgeError("the LLM bridge returned no JSON object") + try: + draft = json.loads(text[start : end + 1]) + except ValueError as exc: + raise OutlookBridgeError(f"the LLM bridge returned invalid JSON: {exc}") from exc + if not isinstance(draft, dict): + raise OutlookBridgeError("the LLM bridge returned JSON that is not an object") + return { + "recipient": str(draft.get("recipient") or "").strip(), + "subject": str(draft.get("subject") or "").strip(), + "body": str(draft.get("body") or "").strip(), + } + + +def _resolve_address(ctx, decisions, recipient): + """An email address for `recipient`: used directly, or chosen from contacts.""" + if "@" in recipient: + return recipient + data = _request(ctx, "outlook", "/contacts", params={"query": recipient}) + contacts = [c for c in (data.get("contacts") or []) if c.get("emails")] + if not contacts: + return None + if len(contacts) == 1: + return str(contacts[0]["emails"][0]) + options = [ + Option(str(contact["emails"][0]), str(contact.get("display_name") or contact["emails"][0])) + for contact in contacts + ] + decision = DecisionRequest( + state=recipient, + question="Which contact should the message be sent to?", + options=options, + ) + result = ctx.engine.call(decision) + decisions.append((decision, result)) + return str(result.selected) + + +def _ask(request, question): + return ActionResult(action_log="waiting for input", new_state=request.text, needs_input=question) + + +def act(ctx, request): + meta = request.meta + awaiting = meta.get("send_message_awaiting") + decisions = [] + + # Resume: the user answered the recipient/address/confirmation question. + if request.user_input is not None and awaiting: + if awaiting == "confirm": + ready = meta.get("send_message_ready") or {} + meta.pop("send_message_awaiting", None) + if request.user_input.strip().lower() not in _YES: + return ActionResult( + action_log="Cancelled; the message was not sent.", + new_state="cancelled", + ) + try: + result = _request( + ctx, + "outlook", + "/mail/send", + method="POST", + payload={"to": [ready.get("to", "")], "subject": ready.get("subject", ""), "body": ready.get("body", "")}, + ) + except OutlookBridgeError as exc: + return ActionResult(action_log=str(exc), new_state=request.text) + report = f"Sent {ready.get('subject')!r} to {ready.get('to')}." + meta.pop("send_message_ready", None) + return ActionResult(action_log=report, new_state=report) + meta.setdefault("send_message_answers", {})[awaiting] = request.user_input.strip() + meta.pop("send_message_awaiting", None) + + answers = meta.get("send_message_answers") or {} + + draft = meta.get("send_message_composed") + if draft is None: + try: + draft = _compose(ctx, request) + except OutlookBridgeError as exc: + return ActionResult(action_log=str(exc), new_state=request.text) + meta["send_message_composed"] = draft + + recipient = answers.get("recipient") or draft["recipient"] + if not recipient: + meta["send_message_awaiting"] = "recipient" + return _ask(request, "Who should I send the message to?") + + address = answers.get("address") + if not address: + try: + address = _resolve_address(ctx, decisions, recipient) + except OutlookBridgeError as exc: + return ActionResult(action_log=str(exc), new_state=request.text) + if not address: + meta["send_message_awaiting"] = "address" + return _ask(request, f"What's the email address for {recipient!r}?") + + meta["send_message_ready"] = {"to": address, "subject": draft["subject"], "body": draft["body"]} + meta["send_message_awaiting"] = "confirm" + action = _ask(request, f"Send {draft['subject']!r} to {address}? (yes/no)") + action.decisions = decisions + return action diff --git a/skills/outlook/send_message/skill.test.py b/skills/outlook/send_message/skill.test.py new file mode 100644 index 0000000..377a015 --- /dev/null +++ b/skills/outlook/send_message/skill.test.py @@ -0,0 +1,216 @@ +"""Hermetic mechanics test for outlook.send_message. + +Run from this folder: `python skill.test.py`. No external network: a loopback +http.server plays the local LLM bridge (`POST /chat`), the Outlook bridge's +contact lookup, and `POST /mail/send`. This proves the body composes a draft, +resolves the recipient, asks for confirmation BEFORE sending, sends for real on +`yes`, cancels otherwise, and fails honestly when the LLM bridge is down. It does +NOT prove the live integration — only a real run against the user's Microsoft +account does. +""" + +import json +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse + +from semif_agent.decisions import DecisionResult, Request +from semif_agent.skills import ActionContext + +import skill + + +class FakeEngine: + """Picks `pick` (else the first option) with full confidence.""" + + def __init__(self, pick=None): + self.pick = pick + self.decisions = [] + + def call(self, decision): + self.decisions.append(decision) + ids = [option.id for option in decision.options] + chosen = self.pick if self.pick in ids else ids[0] + probs = [1.0 if option_id == chosen else 0.0 for option_id in ids] + return DecisionResult(request=decision, option_ids=ids, probabilities=probs) + + +class BridgeHandler(BaseHTTPRequestHandler): + draft = {"recipient": "Sam", "subject": "Lunch", "body": "Tomorrow?"} + contacts = [{"id": "c1", "display_name": "Sam", "emails": ["sam@example.com"]}] + llm_status = 200 + sends = [] + queries = [] + + def _read(self): + length = int(self.headers.get("Content-Length") or 0) + return self.rfile.read(length) if length else b"" + + def do_POST(self): + body = self._read() + if self.path == "/chat": + if self.llm_status != 200: + self._send({"error": "boom"}, self.llm_status) + return + self._send({"text": json.dumps(self.draft)}, 200) + return + if self.path == "/mail/send": + self.sends.append(json.loads(body.decode("utf-8"))) + self._send({"ok": True, "to": self.sends[-1].get("to")}, 200) + return + self._send({"error": "not found"}, 404) + + def do_GET(self): + parsed = urlparse(self.path) + if parsed.path == "/contacts": + self.queries.append(parse_qs(parsed.query).get("query", [""])[0]) + self._send({"contacts": self.contacts}, 200) + return + self._send({"error": "not found"}, 404) + + def _send(self, payload, status): + body = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +def start_server(**overrides): + attrs = { + "draft": {"recipient": "Sam", "subject": "Lunch", "body": "Tomorrow?"}, + "contacts": [{"id": "c1", "display_name": "Sam", "emails": ["sam@example.com"]}], + "llm_status": 200, + "sends": [], + "queries": [], + } + attrs.update(overrides) + handler = type("Handler", (BridgeHandler,), attrs) + 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 context(url, engine): + return ActionContext( + engine=engine, + config={ + "outlook_bridge_url": url, + "outlook_bridge_token": "", + "llm_bridge_url": url, + "llm_bridge_token": "", + }, + ) + + +def test_confirms_then_sends(): + server, handler, url = start_server() + try: + ctx = context(url, FakeEngine()) + request = Request("email Sam that lunch is tomorrow") + action = skill.act(ctx, request) + assert action.needs_input and "send" in action.needs_input.lower(), action.needs_input + assert handler.sends == [], "nothing may be sent before confirmation" + request.user_input = "yes" + action = skill.act(ctx, request) + assert action.needs_input is None, action.needs_input + assert handler.sends[0]["to"] == ["sam@example.com"], handler.sends + assert handler.sends[0]["subject"] == "Lunch", handler.sends + assert "sent" in action.action_log.lower(), action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_cancel_does_not_send(): + server, handler, url = start_server() + try: + ctx = context(url, FakeEngine()) + request = Request("email Sam that lunch is tomorrow") + skill.act(ctx, request) + request.user_input = "no" + action = skill.act(ctx, request) + assert handler.sends == [], "a cancelled message must not be sent" + assert "cancel" in action.action_log.lower(), action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_multiple_contacts_use_semif_choice(): + contacts = [ + {"id": "c1", "display_name": "Sam A", "emails": ["sam.a@example.com"]}, + {"id": "c2", "display_name": "Sam B", "emails": ["sam.b@example.com"]}, + ] + server, handler, url = start_server(contacts=contacts) + try: + engine = FakeEngine(pick="sam.b@example.com") + ctx = context(url, engine) + request = Request("email Sam that lunch is tomorrow") + action = skill.act(ctx, request) + assert len(engine.decisions) == 1, engine.decisions + assert "sam.b@example.com" in action.needs_input, action.needs_input + request.user_input = "yes" + action = skill.act(ctx, request) + assert handler.sends[0]["to"] == ["sam.b@example.com"], handler.sends + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_explicit_address_is_used(): + server, handler, url = start_server( + draft={"recipient": "bob@example.com", "subject": "Late", "body": "I'll be late"} + ) + try: + ctx = context(url, FakeEngine(pick="sam@example.com")) + request = Request("email bob@example.com that I'll be late") + skill.act(ctx, request) + request.user_input = "yes" + skill.act(ctx, request) + assert handler.sends[0]["to"] == ["bob@example.com"], handler.sends + # No contact lookup is needed for an explicit address. + assert handler.queries == [], handler.queries + print(handler.sends[0]) + finally: + server.shutdown() + server.server_close() + + +def test_llm_bridge_failure_is_reported_honestly(): + server, handler, url = start_server(llm_status=502) + try: + ctx = context(url, FakeEngine()) + request = Request("email Sam that lunch is tomorrow") + action = skill.act(ctx, request) + assert "502" in action.action_log, action.action_log + assert handler.sends == [] + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def main(): + test_confirms_then_sends() + test_cancel_does_not_send() + test_multiple_contacts_use_semif_choice() + test_explicit_address_is_used() + test_llm_bridge_failure_is_reported_honestly() + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1)