diff --git a/AGENTS.md b/AGENTS.md index ddec187..fe73ed2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -263,6 +263,13 @@ bridges/ standalone third-party API bridges (SimpleX, the LLM bridge, DAV/OCS; no service daemon (stdlib-only), connection from `bridges.nextcloud` with a fallback to the top-level `nextcloud_*` values the calendar seeds use. + outlook.py + outlook_client.py: OutlookBridge — the user's + Microsoft account (Outlook / Microsoft 365) over Microsoft Graph: + mail, calendar events, Microsoft To Do tasks, contacts, and + OneDrive files, plus the OAuth2 device-code + refresh flow. No + daemon (stdlib-only `urllib`); tokens stored under + `.runtime/outlook/token.json` and seeded once with + `scripts/outlook-auth.py`; connection from `bridges.outlook`. registry.py: CATALOG, describe_bridges() (catalog injected into the codegen prompts), run_bridges() (threads the scheduler's `llm` client into the LLM bridge). Run with `python -m @@ -1359,6 +1366,36 @@ CLI, unit tests (24) + integration tests (2). addressbook defaults resolve from config when a request names none and the account has several. `tests/test_nextcloud_bridge.py` drives the real client over a loopback `http.server` faking Nextcloud's DAV/OCS shapes. +- **Outlook bridge** (`bridges/outlook.py` + `bridges/outlook_client.py`). + Wraps the user's Microsoft account — Outlook / Microsoft 365 mail, calendar + events, Microsoft To Do tasks, contacts, and OneDrive files — behind one + uniform JSON surface over **Microsoft Graph**, so a body never speaks Graph or + OAuth directly. Like Nextcloud it has **no service daemon** (Graph is plain + HTTPS) and is stdlib-only (`urllib` + `json` + `ssl` + `base64`), so + `check_requirements` is always `(True, None)` and it starts instantly inside + `semif-bridge.service`. Authorization is the OAuth2 **device code flow** (a + public client, no secret): `scripts/outlook-auth.py` runs it once and stores + the access + refresh tokens 0600 under the checkout's + `.runtime/outlook/token.json` (override with `bridges.outlook.token_path`); the + client refreshes on expiry/401. The bridge starts without a token — an + unauthenticated route returns `503` telling the operator to run the helper + (`OutlookAuthRequired`), a real Graph failure is `502` (`OutlookError`), and a + missing `client_id` is `503`. The connection is configured in + `bridges.outlook` (`client_id`, `tenant` default `common`, + `default_calendar`/`default_task_list`/`default_mail_folder`/`default_timezone`, + `verify_tls`/`timeout`); it also accepts `graph`/`login` base URLs (a test + seam/defaulting to the real hosts). Bodies reach it via the derived + `outlook_bridge_url` (+ optional `outlook_bridge_token`). Routes (reads `GET`, + mutations `POST`): `/user`, mail (`/mail/folders`, `/mail/messages` list + + `/mail/messages/get`, `POST /mail/send` immediate + `/mail/draft`), calendar + (`/calendars`, `/calendars/events` via `calendarView` so recurrences expand, + `POST /calendars/events` + `/update` + `/delete`), To Do (`/tasklists`, + `/tasks`, `POST /tasks` + `/update` + `/complete` + `/delete`), contacts + (`/contacts` search), and OneDrive (`/files` list, `/files/read` + text-or-base64, `POST /files/write`). Graph's `@odata.nextLink` paging and + `429`/`Retry-After` backoff are handled in the client. + `tests/test_outlook_bridge.py` drives the real client over a loopback + `http.server` faking the token endpoint and Graph shapes. ## Bridge backlog (one session per item) @@ -1402,6 +1439,15 @@ The bridge read path (`simplex.next_message`) and contact-link lookup `bridges/nextcloud_client.py`): files/calendars/tasks/contacts/notes over one JSON surface, no daemon, connection from `bridges.nextcloud` with a top-level `nextcloud_*` fallback. Future bridges follow the same shape. +- [x] **6. Outlook / Microsoft Graph bridge** (`bridges/outlook.py` + + `bridges/outlook_client.py`). Shipped: the `OutlookBridge` exposes mail, + calendar, Microsoft To Do, contacts, and OneDrive over one JSON surface in + front of Graph; OAuth2 device-code + refresh (`scripts/outlook-auth.py`, tokens + under `.runtime/outlook/token.json`); seven `seeds/outlook/*` skills + (`next_message`, `send_message` confirm-gated, `next_event`, `create_event`, + `create_task`, `list_contacts`, `list_files`). Deferred: writing/reusing + Outlook app-registration guidance in the docs, and a mail-send seed that + attaches files. ### Code principles - **Contain installation artifacts in the repo.** Everything a machine installs diff --git a/README.md b/README.md index 7724345..7b56b67 100644 --- a/README.md +++ b/README.md @@ -515,14 +515,16 @@ Key blocks: | `bridges.simplex` | forwarding bridge: host/port/token/ws_url | | `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) | | `bridges.nextcloud` | Nextcloud bridge: host/port/token + connection (url/username/app_password/defaults) | +| `bridges.outlook` | Outlook bridge: host/port/token + Microsoft Graph connection (client_id/tenant/defaults) | | `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) | | `dashboard` | bind host/port | -Bridge skills read `simplex_bridge_url` / `llm_bridge_url` / `nextcloud_bridge_url` -(+ their `_token`) from `ctx.config`; each is **derived** at startup from its -`bridges.` host/port/token, so there is no duplicate top-level key to keep -in sync. A bridge with no block (or no port) leaves the variable unresolved and -the operator is asked for it. +Bridge skills read `simplex_bridge_url` / `llm_bridge_url` / +`nextcloud_bridge_url` / `outlook_bridge_url` (+ their `_token`) from +`ctx.config`; each is **derived** at startup from its `bridges.` +host/port/token, so there is no duplicate top-level key to keep in sync. A bridge +with no block (or no port) leaves the variable unresolved and the operator is +asked for it. `llm.model` and `codegen.model` are **required** (no default): set each to a model its endpoint serves. A missing model fails fast at startup with a clear @@ -774,6 +776,46 @@ or a bad reply) is `502` — never a fabricated success. Calendar and addressboo defaults resolve from `bridges.nextcloud` when a request names none and the account has several. +The **Outlook bridge** (`semif_agent/bridges/outlook.py`) wraps the user's +Microsoft account (Outlook / Microsoft 365) through **Microsoft Graph**: mail, +calendar events, Microsoft To Do tasks, contacts, and OneDrive files. Like +Nextcloud it has **no service daemon** (Graph is plain HTTPS) and is stdlib-only, +so it starts instantly in the same `semif-bridge` process. Authorization is the +OAuth2 **device code flow**: register an Entra ID public-client app, put its +`client_id` in `bridges.outlook`, and run `scripts/outlook-auth.py` once — the +tokens are stored (0600) under the checkout's `.runtime/outlook/token.json` and +refreshed automatically. The bridge starts without a token; an unauthenticated +route returns `503` telling the operator to run that helper. Skills call it at the +address derived from `bridges.outlook` (`outlook_bridge_url`, + optional +`outlook_bridge_token`). Its HTTP surface: + +``` +GET /health +GET /user # the signed-in account +GET /mail/folders +GET /mail/messages?folder=&count=&search=&unread= +GET /mail/messages/get?id= +POST /mail/send {"to":[...],"cc"?,"subject"?,"body"?,"content_type"?} +POST /mail/draft {"to"?,"cc"?,"subject"?,"body"?,"content_type"?} +GET /calendars +GET /calendars/events?calendar=&start=&end= # recurrences expand +POST /calendars/events | /calendars/events/update | /calendars/events/delete +GET /tasklists # Microsoft To Do +GET /tasks?list= +POST /tasks | /tasks/update | /tasks/complete | /tasks/delete +GET /contacts?query=&count= +GET /files?path= # OneDrive +GET /files/read?path= # text, or base64 for binary +POST /files/write {"path","content","encoding"?,"overwrite"?} +``` + +A missing `client_id` or an unauthorized bridge is `503`; a real Graph failure +(transport, HTTP error, or a bad reply) is `502` — never a fabricated success. +Seven `seeds/outlook/*` skills ship (`next_message`, `send_message`, +`next_event`, `create_event`, `create_task`, `list_contacts`, `list_files`); +`send_message` composes the message through the LLM bridge and asks for +confirmation before it sends. + ### Dream report ```sh diff --git a/config.example.json b/config.example.json index 5f37e74..6e26d08 100644 --- a/config.example.json +++ b/config.example.json @@ -162,6 +162,21 @@ "default_addressbook": "", "verify_tls": true, "timeout": 30 + }, + "outlook": { + "_comment": "Outlook bridge: the user's Microsoft account (Outlook / Microsoft 365) through Microsoft Graph — mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files — over one uniform local JSON API, so skill bodies never speak Graph or OAuth. No service daemon and no extra dependency (Graph is plain HTTPS); it runs inside the same `semif-bridge` process as the other enabled bridges. Authorization is the OAuth2 device code flow: register an Entra ID public-client app, put its `client_id` here, run `scripts/outlook-auth.py` once, and the tokens are stored (0600) under `.runtime/outlook/token.json` (override with `token_path`). `tenant` is usually `common` (personal + work accounts). `default_calendar`/`default_task_list`/`default_mail_folder` are used when a request names none; `default_timezone` (IANA name) labels created events/tasks whose start has no offset. `verify_tls` false skips certificate verification. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. Disabled by default because it needs a client id + an authorization run first.", + "enabled": false, + "host": "127.0.0.1", + "port": 5231, + "token": "", + "client_id": "", + "tenant": "common", + "default_calendar": "", + "default_task_list": "", + "default_mail_folder": "inbox", + "default_timezone": "UTC", + "verify_tls": true, + "timeout": 30 } }, "gateway": { diff --git a/scripts/outlook-auth.py b/scripts/outlook-auth.py new file mode 100644 index 0000000..258b61b --- /dev/null +++ b/scripts/outlook-auth.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Authorize the Outlook bridge with Microsoft (OAuth2 device code flow). + +The bridge reads the user's Microsoft account through Microsoft Graph; that +needs an access token, obtained once here with the **device code flow** (a public +client, no secret): + + 1. register an Entra ID app (see below) and put its client id in + `config.json` under `bridges.outlook.client_id`; + 2. run this script; + 3. open the printed URL on any device, enter the printed code, and sign in; + 4. the resulting tokens are saved (0600) to `.runtime/outlook/token.json`, + which the bridge loads and refreshes automatically. + +One-time app registration (Entra ID / Azure AD): + + - "App registrations" -> "New registration". + - Supported account types: include personal Microsoft accounts if the user + has an @outlook.com/@hotmail.com account (e.g. "Accounts in any + organizational directory and personal Microsoft accounts"). + - Authentication -> "Allow public client flows" = Yes (no redirect URI is + needed for device code). + - No API permissions need adding by hand: the script requests the delegated + scopes it needs and the user consents during sign-in. + +Usage (from the checkout): + + .runtime/venv/bin/python scripts/outlook-auth.py [--config config.json] + [--client-id ID] + [--tenant common] + [--token-path PATH] +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO_ROOT)) + +from semif_agent.bridges.outlook_client import ( # noqa: E402 + DEFAULT_TENANT, + OutlookError, + run_device_code_flow, + save_token, +) + +DEFAULT_TOKEN_PATH = str(REPO_ROOT / ".runtime" / "outlook" / "token.json") + + +def _block(config_path: str) -> dict: + try: + with open(config_path, encoding="utf-8") as handle: + config = json.load(handle) + except (OSError, ValueError): + return {} + block = (config.get("bridges", {}) or {}).get("outlook", {}) or {} + return block if isinstance(block, dict) else {} + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", default="config.json") + parser.add_argument("--client-id", default=None, help="override bridges.outlook.client_id") + parser.add_argument("--tenant", default=None, help="override bridges.outlook.tenant (default common)") + parser.add_argument("--token-path", default=None, help="where to save the tokens") + args = parser.parse_args(argv) + + block = _block(args.config) + client_id = str(args.client_id or block.get("client_id") or "").strip() + tenant = str(args.tenant or block.get("tenant") or DEFAULT_TENANT).strip() or DEFAULT_TENANT + token_path = str(args.token_path or block.get("token_path") or DEFAULT_TOKEN_PATH) + scopes = block.get("scopes") or None + + if not client_id: + print( + "no Microsoft client id configured: set bridges.outlook.client_id in " + f"{args.config} (or pass --client-id)", + file=sys.stderr, + ) + return 1 + + try: + token = run_device_code_flow(client_id, tenant, scopes) + except OutlookError as exc: + print(f"authorization failed: {exc}", file=sys.stderr) + return 1 + except KeyboardInterrupt: + print("\ncancelled", file=sys.stderr) + return 1 + + save_token(token_path, token) + print(f"saved Outlook authorization to {token_path}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/seeds/outlook/create_event/contract.json b/seeds/outlook/create_event/contract.json new file mode 100644 index 0000000..ce8daaf --- /dev/null +++ b/seeds/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/seeds/outlook/create_event/manifest.json b/seeds/outlook/create_event/manifest.json new file mode 100644 index 0000000..84d4dff --- /dev/null +++ b/seeds/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/seeds/outlook/create_event/skill.py b/seeds/outlook/create_event/skill.py new file mode 100644 index 0000000..1c5fc4c --- /dev/null +++ b/seeds/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/seeds/outlook/create_event/skill.test.py b/seeds/outlook/create_event/skill.test.py new file mode 100644 index 0000000..7205386 --- /dev/null +++ b/seeds/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/seeds/outlook/create_task/contract.json b/seeds/outlook/create_task/contract.json new file mode 100644 index 0000000..ce8daaf --- /dev/null +++ b/seeds/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/seeds/outlook/create_task/manifest.json b/seeds/outlook/create_task/manifest.json new file mode 100644 index 0000000..0fb7c2f --- /dev/null +++ b/seeds/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/seeds/outlook/create_task/skill.py b/seeds/outlook/create_task/skill.py new file mode 100644 index 0000000..d83c129 --- /dev/null +++ b/seeds/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/seeds/outlook/create_task/skill.test.py b/seeds/outlook/create_task/skill.test.py new file mode 100644 index 0000000..dacd8a8 --- /dev/null +++ b/seeds/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/seeds/outlook/list_contacts/contract.json b/seeds/outlook/list_contacts/contract.json new file mode 100644 index 0000000..ce8daaf --- /dev/null +++ b/seeds/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/seeds/outlook/list_contacts/manifest.json b/seeds/outlook/list_contacts/manifest.json new file mode 100644 index 0000000..7d322dd --- /dev/null +++ b/seeds/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/seeds/outlook/list_contacts/skill.py b/seeds/outlook/list_contacts/skill.py new file mode 100644 index 0000000..8d42bc5 --- /dev/null +++ b/seeds/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/seeds/outlook/list_contacts/skill.test.py b/seeds/outlook/list_contacts/skill.test.py new file mode 100644 index 0000000..63d153c --- /dev/null +++ b/seeds/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/seeds/outlook/list_files/contract.json b/seeds/outlook/list_files/contract.json new file mode 100644 index 0000000..ce8daaf --- /dev/null +++ b/seeds/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/seeds/outlook/list_files/manifest.json b/seeds/outlook/list_files/manifest.json new file mode 100644 index 0000000..68bf1a6 --- /dev/null +++ b/seeds/outlook/list_files/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "List the user's OneDrive files, optionally in a named folder." +} diff --git a/seeds/outlook/list_files/skill.py b/seeds/outlook/list_files/skill.py new file mode 100644 index 0000000..9c60fbb --- /dev/null +++ b/seeds/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/seeds/outlook/list_files/skill.test.py b/seeds/outlook/list_files/skill.test.py new file mode 100644 index 0000000..1ae7c0f --- /dev/null +++ b/seeds/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/seeds/outlook/next_event/contract.json b/seeds/outlook/next_event/contract.json new file mode 100644 index 0000000..ce8daaf --- /dev/null +++ b/seeds/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/seeds/outlook/next_event/manifest.json b/seeds/outlook/next_event/manifest.json new file mode 100644 index 0000000..1f4279e --- /dev/null +++ b/seeds/outlook/next_event/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Read the user's upcoming Outlook calendar events." +} diff --git a/seeds/outlook/next_event/skill.py b/seeds/outlook/next_event/skill.py new file mode 100644 index 0000000..7dc6453 --- /dev/null +++ b/seeds/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/seeds/outlook/next_event/skill.test.py b/seeds/outlook/next_event/skill.test.py new file mode 100644 index 0000000..65d0f99 --- /dev/null +++ b/seeds/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/seeds/outlook/next_message/contract.json b/seeds/outlook/next_message/contract.json new file mode 100644 index 0000000..ce8daaf --- /dev/null +++ b/seeds/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/seeds/outlook/next_message/manifest.json b/seeds/outlook/next_message/manifest.json new file mode 100644 index 0000000..ea81f7b --- /dev/null +++ b/seeds/outlook/next_message/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Read the latest messages from the user's Outlook inbox." +} diff --git a/seeds/outlook/next_message/skill.py b/seeds/outlook/next_message/skill.py new file mode 100644 index 0000000..eefccbc --- /dev/null +++ b/seeds/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/seeds/outlook/next_message/skill.test.py b/seeds/outlook/next_message/skill.test.py new file mode 100644 index 0000000..f1adca6 --- /dev/null +++ b/seeds/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/seeds/outlook/send_message/contract.json b/seeds/outlook/send_message/contract.json new file mode 100644 index 0000000..0da6abf --- /dev/null +++ b/seeds/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/seeds/outlook/send_message/manifest.json b/seeds/outlook/send_message/manifest.json new file mode 100644 index 0000000..88473f7 --- /dev/null +++ b/seeds/outlook/send_message/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Compose and send an Outlook email, after confirming the message." +} diff --git a/seeds/outlook/send_message/skill.py b/seeds/outlook/send_message/skill.py new file mode 100644 index 0000000..227790d --- /dev/null +++ b/seeds/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/seeds/outlook/send_message/skill.test.py b/seeds/outlook/send_message/skill.test.py new file mode 100644 index 0000000..377a015 --- /dev/null +++ b/seeds/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) diff --git a/semif_agent/bridges/__init__.py b/semif_agent/bridges/__init__.py index 78285b9..207d200 100644 --- a/semif_agent/bridges/__init__.py +++ b/semif_agent/bridges/__init__.py @@ -1,7 +1,8 @@ """Third-party API bridges: a secure local layer between skills and services. A **bridge service** is a standalone process that exposes one third-party system -(SimpleX, the local language model, Nextcloud) to codegen-authored skill bodies +(SimpleX, the local language model, Nextcloud, Microsoft Graph / Outlook) to +codegen-authored skill bodies over a local, token-guarded HTTP API. It exists so a generated body never speaks a system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat API, a CLI's private flags) directly: it calls a small, documented, uniform HTTP diff --git a/semif_agent/bridges/outlook.py b/semif_agent/bridges/outlook.py new file mode 100644 index 0000000..11573d5 --- /dev/null +++ b/semif_agent/bridges/outlook.py @@ -0,0 +1,398 @@ +"""Outlook bridge: the user's Microsoft account (Graph) over HTTP. + +Microsoft Graph is a plain HTTPS/JSON API, but a codegen-authored skill body +must still never speak it (or OAuth) directly. This bridge owns the connection — +the Entra ID client id, the tenant, and the stored refresh token — and exposes +one uniform, token-guarded localhost JSON API for mail, calendar, Microsoft To Do +tasks, contacts, and OneDrive files, so a body only reads `outlook_bridge_url` +and `outlook_bridge_token` from `ctx.config` and calls a documented route. + +There is no service daemon and no third-party dependency: Graph is plain HTTPS, +so the bridge is stdlib-only (`urllib`) and starts instantly, like Nextcloud. +Authorization is the OAuth2 device code flow, run once with +`scripts/outlook-auth.py`; the resulting tokens are stored (0600) under the +checkout's `.runtime/outlook/token.json`. The bridge starts without them and an +unauthenticated route returns 503 telling the operator to run that helper. + +The actual Graph work lives in `outlook_client.py`; the routes here validate +input and map a real failure (`OutlookError`) to a 502 — or a missing +authorization (`OutlookAuthRequired`) to a 503 — rather than a fabricated +success. +""" + +from __future__ import annotations + +from pathlib import Path + +from .base import BridgeInfo, BridgeService +from .outlook_client import ( + DEFAULT_SCOPES, + DEFAULT_TENANT, + DEFAULT_TIMEOUT, + OutlookAuthRequired, + OutlookClient, + OutlookError, +) + +#: The checkout root (`semif_agent/bridges/outlook.py` -> repo root), used to +#: anchor the default token store under the gitignored `.runtime/` tree. +_REPO_ROOT = Path(__file__).resolve().parents[2] +DEFAULT_TOKEN_PATH = str(_REPO_ROOT / ".runtime" / "outlook" / "token.json") + + +class OutlookBridge(BridgeService): + name = "outlook" + INFO = BridgeInfo( + name="outlook", + service="outlook", + description=( + "Read and write the user's Microsoft account (Outlook / Microsoft " + "365) through Microsoft Graph: mail, calendar events, Microsoft To " + "Do tasks, contacts, and OneDrive files." + ), + url_config_var="outlook_bridge_url", + endpoints=( + "GET /health -> 200 {\"ok\": true, \"platform\": \"outlook\"} — the " + "bridge is up", + "GET /user -> 200 {\"user\": {id, display_name, mail, " + "user_principal_name}} — the signed-in account", + "GET /mail/folders -> 200 {\"folders\": [{id, name, total, unread}]}", + "GET /mail/messages?folder=&count=&search=&unread= " + "-> 200 {\"folder\", \"messages\": [{id, subject, from, to, cc, " + "received, is_read, has_attachments, importance, preview, web_link}]} " + "— newest first; folder defaults to inbox (a well-known name like " + "sentitems/drafts/archive or a folder display name/id)", + "GET /mail/messages/get?id= -> 200 {\"message\": {..., body, " + "body_type}} — the full message", + "POST /mail/send {\"to\": [addr, ...], \"cc\"?: [addr, ...], " + "\"subject\"?, \"body\"?, \"content_type\"?: text|html} -> 200 " + "{\"ok\": true, \"to\", \"cc\", \"subject\"} — sends immediately", + "POST /mail/draft {\"to\"?, \"cc\"?, \"subject\"?, \"body\"?, " + "\"content_type\"?} -> 200 {\"ok\": true, \"id\", \"subject\"} — " + "saves a draft in the Drafts folder", + "GET /calendars -> 200 {\"calendars\": [{id, name, color, " + "is_default, can_edit}]}", + "GET /calendars/events?calendar=&start=&end= -> " + "200 {\"calendar\", \"events\": [{id, subject, start, end, timezone, " + "all_day, location, preview, show_as, is_online_meeting, web_link, " + "organizer}]} — start/end are ISO 8601 (default: now to +30 days); " + "recurring events are expanded, calendar defaults to the configured " + "or primary calendar", + "POST /calendars/events {\"calendar\"?, \"subject\", \"start\", " + "\"end\"?, \"all_day\"?, \"location\"?, \"description\"?, " + "\"attendees\"?: [addr, ...], \"timezone\"?} -> 200 {\"ok\": true, " + "\"id\", \"subject\", \"calendar\", \"web_link\"} — start/end are " + "local ISO 8601 in the named timezone (default UTC when absent); end " + "defaults to +1h (+1 day when all_day)", + "POST /calendars/events/update {\"id\", \"subject\"?, \"start\"?, " + "\"end\"?, \"all_day\"?, \"location\"?, \"description\"?, " + "\"timezone\"?} -> 200 {ok, id, subject} — only the named fields change", + "POST /calendars/events/delete {\"id\"} -> 200 {\"ok\": true, \"id\"}", + "GET /tasklists -> 200 {\"tasklists\": [{id, name, is_owner, " + "is_default}]} — Microsoft To Do lists", + "GET /tasks?list= -> 200 {\"list\", \"tasks\": [{id, title, " + "status, importance, due, completed, description, list_id}]} — list " + "defaults to the configured or default list", + "POST /tasks {\"list\"?, \"title\", \"due\"?, \"importance\"?, " + "\"description\"?} -> 200 {\"ok\": true, \"id\", \"title\", " + "\"list_id\"} — importance is low|normal|high; due is ISO 8601", + "POST /tasks/update {\"id\", \"list\"?, \"title\"?, \"due\"?, " + "\"importance\"?, \"status\"?, \"description\"?} -> 200 {ok, id, status}", + "POST /tasks/complete {\"id\", \"list\"?} -> 200 {ok, id, status} — " + "marks the task completed", + "POST /tasks/delete {\"id\", \"list\"?} -> 200 {\"ok\": true, \"id\"}", + "GET /contacts?query=&count= -> 200 {\"contacts\": [{id, " + "display_name, given_name, surname, emails, phones, company, " + "job_title}]} — query filters by name/email/company", + "GET /files?path= -> 200 {\"path\", \"entries\": [{id, name, " + "path, size, modified, is_folder, content_type, web_url}]} — OneDrive " + "folder listing (default root)", + "GET /files/read?path= -> 200 {\"path\", \"name\", \"content\", " + "\"encoding\" (utf-8|base64), \"size\", \"content_type\", \"modified\"} " + "— file contents; binary is base64", + "POST /files/write {\"path\", \"content\", \"encoding\"?: " + "utf-8|base64, \"overwrite\"?: bool} -> 200 {\"ok\": true, \"path\", " + "\"id\", \"size\", \"web_url\"}", + "any request -> 401 {\"error\": \"unauthorized\"} when the token is " + "configured and the auth header is missing or wrong", + "503 {\"error\": \"...\"} when the bridge is not authenticated " + "(run scripts/outlook-auth.py) or has no client id configured; 502 " + "{\"error\": \"...\"} on a real Microsoft Graph failure (transport, " + "HTTP error, or bad reply)", + ), + config_vars=("outlook_bridge_url", "outlook_bridge_token"), + config_var_docs=( + ( + "outlook_bridge_url", + "Base URL of the local Outlook bridge (e.g. " + "http://127.0.0.1:5231); never hardcode it in the body.", + ), + ( + "outlook_bridge_token", + "Shared secret for the bridge, if one is configured; sent as the " + "X-Semif-Token header. Leave blank when the bridge requires no auth.", + ), + ), + auth_header="X-Semif-Token", + auth_config_var="outlook_bridge_token", + ) + + def __init__(self, config: dict | None = None, trace=None, client=None): + super().__init__(config, trace) + cfg = config or {} + self.client_id = str(cfg.get("client_id", "") or "").strip() + self.tenant = str(cfg.get("tenant", DEFAULT_TENANT) or DEFAULT_TENANT).strip() or DEFAULT_TENANT + self.token_path = str(cfg.get("token_path") or DEFAULT_TOKEN_PATH) + self.default_timezone = str(cfg.get("default_timezone", "UTC") or "UTC").strip() or "UTC" + self.default_mail_folder = str(cfg.get("default_mail_folder", "inbox") or "inbox").strip() or "inbox" + #: A test seam: inject a client double. Production builds the real one. + self.client = client or OutlookClient( + self.client_id, + tenant=self.tenant, + token_path=self.token_path, + scopes=cfg.get("scopes") or DEFAULT_SCOPES, + timeout=float(cfg.get("timeout", DEFAULT_TIMEOUT)), + verify_tls=bool(cfg.get("verify_tls", True)), + default_calendar=str(cfg.get("default_calendar", "") or "").strip(), + default_task_list=str(cfg.get("default_task_list", "") or "").strip(), + default_mail_folder=self.default_mail_folder, + default_timezone=self.default_timezone, + ) + + # ---- lifecycle ---- + + def check_requirements(self) -> tuple[bool, str | None]: + # Stdlib only: no missing dependency can make the bridge unstartable. A + # missing authorization surfaces as a 503 on the call, not a startup failure. + return True, None + + # ---- routes ---- + + def handle_get(self, path: str, query: dict) -> tuple[int, dict]: + if path == "/health": + return 200, {"ok": True, "platform": self.name} + if not self.client.configured: + return self._unconfigured() + try: + return self._get(path, query) + except OutlookAuthRequired as exc: + return 503, {"error": str(exc)[:300]} + except OutlookError as exc: + return 502, {"error": str(exc)[:300]} + except ValueError as exc: + return 400, {"error": str(exc)[:300]} + + def handle_post(self, path: str, payload: dict) -> tuple[int, dict]: + if not self.client.configured: + return self._unconfigured() + try: + return self._post(path, payload) + except OutlookAuthRequired as exc: + return 503, {"error": str(exc)[:300]} + except OutlookError as exc: + return 502, {"error": str(exc)[:300]} + except ValueError as exc: + return 400, {"error": str(exc)[:300]} + + def _unconfigured(self) -> tuple[int, dict]: + return 503, { + "error": ( + "the Outlook bridge has no connection configured (set " + "bridges.outlook.client_id, then run scripts/outlook-auth.py)" + ) + } + + def _get(self, path: str, query: dict) -> tuple[int, dict]: + if path == "/user": + return 200, {"user": self.client.me()} + if path == "/mail/folders": + return 200, {"folders": self.client.list_mail_folders()} + if path == "/mail/messages": + folder = self._q(query, "folder", "") or "" + return 200, { + "folder": folder or self.default_mail_folder, + "messages": self.client.list_messages( + folder, + self._int_query(query, "count", 25), + self._q(query, "search", "") or "", + self._bool_query(query, "unread", False), + ), + } + if path == "/mail/messages/get": + return 200, {"message": self.client.get_message(self._required_query(query, "id"))} + if path == "/calendars": + return 200, {"calendars": self.client.list_calendars()} + if path == "/calendars/events": + return 200, { + "calendar": self._q(query, "calendar", "") or "", + "events": self.client.list_events( + self._q(query, "calendar", "") or "", + self._q(query, "start", "") or "", + self._q(query, "end", "") or "", + ), + } + if path == "/tasklists": + return 200, {"tasklists": self.client.list_task_lists()} + if path == "/tasks": + task_list = self._q(query, "list", "") or "" + return 200, {"list": task_list, "tasks": self.client.list_tasks(task_list)} + if path == "/contacts": + return 200, { + "contacts": self.client.list_contacts( + self._q(query, "query", "") or "", self._int_query(query, "count", 50) + ) + } + if path == "/files": + folder = self._q(query, "path", "/") or "/" + return 200, {"path": folder, "entries": self.client.list_files(folder)} + if path == "/files/read": + return 200, self.client.read_file(self._required_query(query, "path")) + return 404, {"error": "not found"} + + def _post(self, path: str, payload: dict) -> tuple[int, dict]: + if path == "/mail/send": + recipients = self._string_list(payload, "to") + if not recipients: + raise ValueError("to is required") + return 200, self.client.send_mail( + recipients, + self._optional_str(payload, "subject"), + self._optional_str(payload, "body"), + self._string_list(payload, "cc"), + self._optional_str(payload, "content_type", "text") or "text", + ) + if path == "/mail/draft": + return 200, self.client.create_draft( + self._string_list(payload, "to"), + self._optional_str(payload, "subject"), + self._optional_str(payload, "body"), + self._string_list(payload, "cc"), + self._optional_str(payload, "content_type", "text") or "text", + ) + if path == "/calendars/events": + return 200, self.client.create_event( + calendar=self._optional_str(payload, "calendar"), + subject=self._required(payload, "subject"), + start=self._required(payload, "start"), + end=self._optional_str(payload, "end"), + all_day=self._optional_bool(payload, "all_day", False), + location=self._optional_str(payload, "location"), + description=self._optional_str(payload, "description"), + attendees=self._string_list(payload, "attendees"), + timezone_name=self._optional_str(payload, "timezone"), + ) + if path == "/calendars/events/update": + event_id = self._required(payload, "id") + changes = { + key: payload[key] + for key in ("subject", "start", "end", "location", "description") + if key in payload + } + if "all_day" in payload: + changes["all_day"] = self._optional_bool(payload, "all_day", False) + return 200, self.client.update_event( + event_id, timezone_name=self._optional_str(payload, "timezone"), **changes + ) + if path == "/calendars/events/delete": + return 200, self.client.delete_event(self._required(payload, "id")) + if path == "/tasks": + return 200, self.client.create_task( + task_list=self._optional_str(payload, "list"), + title=self._required(payload, "title"), + due=self._optional_str(payload, "due"), + importance=self._optional_str(payload, "importance"), + description=self._optional_str(payload, "description"), + ) + if path == "/tasks/update": + task_id = self._required(payload, "id") + changes = { + key: payload[key] + for key in ("title", "due", "importance", "status", "description") + if key in payload + } + return 200, self.client.update_task( + task_id, task_list=self._optional_str(payload, "list"), **changes + ) + if path == "/tasks/complete": + return 200, self.client.complete_task( + self._required(payload, "id"), task_list=self._optional_str(payload, "list") + ) + if path == "/tasks/delete": + return 200, self.client.delete_task( + self._required(payload, "id"), task_list=self._optional_str(payload, "list") + ) + if path == "/files/write": + return 200, self.client.write_file( + self._required(payload, "path"), + self._required(payload, "content", allow_empty=True), + self._optional_str(payload, "encoding", "utf-8") or "utf-8", + self._optional_bool(payload, "overwrite", True), + ) + return 404, {"error": "not found"} + + # ---- input helpers ---- + + @staticmethod + def _q(query: dict, key: str, default=None): + values = query.get(key) + if not values: + return default + return values[0] + + @staticmethod + def _required_query(query: dict, key: str) -> str: + value = OutlookBridge._q(query, key) + if value is None or not str(value).strip(): + raise ValueError(f"{key} is required") + return str(value).strip() + + @staticmethod + def _int_query(query: dict, key: str, default: int) -> int: + value = OutlookBridge._q(query, key) + if value is None or str(value).strip() == "": + return default + try: + return int(str(value)) + except ValueError as exc: + raise ValueError(f"{key} must be an integer") from exc + + @staticmethod + def _bool_query(query: dict, key: str, default: bool) -> bool: + value = OutlookBridge._q(query, key) + if value is None or str(value).strip() == "": + return default + return str(value).strip().lower() in ("1", "true", "yes", "on") + + @staticmethod + def _required(payload: dict, key: str, allow_empty: bool = False) -> str: + value = payload.get(key) + if not isinstance(value, str) or (not allow_empty and not value.strip()): + raise ValueError(f"{key} is required") + return value if allow_empty else value.strip() + + @staticmethod + def _optional_str(payload: dict, key: str, default: str = "") -> str: + value = payload.get(key) + if value is None: + return default + if not isinstance(value, str): + raise ValueError(f"{key} must be a string") + return value + + @staticmethod + def _optional_bool(payload: dict, key: str, default: bool) -> bool: + value = payload.get(key) + if value is None: + return default + if not isinstance(value, bool): + raise ValueError(f"{key} must be a boolean") + return value + + @staticmethod + def _string_list(payload: dict, key: str) -> list[str]: + value = payload.get(key) + if value is None: + return [] + if not isinstance(value, list) or not all(isinstance(item, str) for item in value): + raise ValueError(f"{key} must be a list of strings") + return value diff --git a/semif_agent/bridges/outlook_client.py b/semif_agent/bridges/outlook_client.py new file mode 100644 index 0000000..3deed7e --- /dev/null +++ b/semif_agent/bridges/outlook_client.py @@ -0,0 +1,1049 @@ +"""A small, real Microsoft Graph client for Outlook over stdlib. + +The Outlook bridge calls this instead of a skill body speaking Graph or OAuth +directly. It owns the connection (an Entra ID client id, tenant, and the stored +refresh token), the bearer-token lifecycle, Graph's paging/throttling, and the +JSON shapes, and returns plain dicts. Mail, calendar, To Do tasks, contacts, and +OneDrive files all go through the one Graph REST surface. + +Authorization is the OAuth2 **device code flow** (a public client: no secret): +`run_device_code_flow` prints a code the user enters at a Microsoft URL, then +stores the resulting access + refresh tokens. The bridge starts without a token; +the first authenticated call raises `OutlookAuthRequired`, which the bridge maps +to a 503 telling the operator to run `scripts/outlook-auth.py`. Every other +failure is an `OutlookError` carrying the HTTP status when there was one, so the +bridge maps it to a 502 (a real Graph failure) rather than a fabricated success. + +Only the stdlib is used: `urllib.request`, `json`, `ssl`, `os`, `time`, +`base64`, and `datetime`. +""" + +from __future__ import annotations + +import base64 +import json +import os +import ssl +import time +import urllib.error +import urllib.parse +import urllib.request +from datetime import datetime, timedelta, timezone + +GRAPH = "https://graph.microsoft.com/v1.0" +LOGIN = "https://login.microsoftonline.com" +DEFAULT_TENANT = "common" +DEFAULT_TIMEOUT = 30.0 +#: Delegated scopes the bridge needs. `offline_access` yields the refresh token. +DEFAULT_SCOPES = ( + "offline_access", + "User.Read", + "Mail.ReadWrite", + "Mail.Send", + "Calendars.ReadWrite", + "Contacts.ReadWrite", + "Tasks.ReadWrite", + "Files.ReadWrite", +) +#: Refresh the access token this many seconds before Graph would reject it. +TOKEN_REFRESH_SKEW = 120.0 +MAX_PAGES = 20 +MAX_RETRIES = 3 +AUTH_HINT = "run scripts/outlook-auth.py to authorize Outlook" + + +class OutlookError(Exception): + """A real failure talking to Microsoft Graph (transport, HTTP, or a bad reply).""" + + def __init__(self, message: str, status: int | None = None): + super().__init__(message) + self.status = status + + +class OutlookAuthRequired(OutlookError): + """No usable stored authorization; the operator must (re-)run the auth helper.""" + + +# ---- small helpers ---------------------------------------------------------- + + +def _ssl_context(verify_tls: bool): + if verify_tls: + return None + context = ssl.create_default_context() + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + return context + + +def _graph_error(detail: str) -> str: + """Pull the human message out of a Graph error body, else the raw text.""" + try: + data = json.loads(detail or "{}") + except ValueError: + return detail[:200] + error = data.get("error") + if isinstance(error, dict): + message = error.get("message") or error.get("code") or "" + return str(message)[:200] + if isinstance(error, str): + return error[:200] + return detail[:200] + + +def _retry_after(headers, attempt: int) -> float: + """Seconds to wait before a throttled retry: Graph's Retry-After or backoff.""" + value = None + if headers is not None: + try: + value = headers.get("Retry-After") + except Exception: # pragma: no cover - header objects vary + value = None + try: + return max(0.0, float(str(value))) + except (TypeError, ValueError): + return float(2 ** attempt) + + +def normalize_scopes(scopes) -> tuple[str, ...]: + """Accept a space string or a list; always a non-empty tuple.""" + if not scopes: + return DEFAULT_SCOPES + if isinstance(scopes, str): + parts = scopes.replace(",", " ").split() + else: + parts = [str(part) for part in scopes] + return tuple(parts) or DEFAULT_SCOPES + + +# ---- OAuth2 (device code, refresh) ------------------------------------------ + + +def _oauth_post(url: str, fields: dict, timeout: float, verify_tls: bool) -> tuple[int, dict]: + """POST an x-www-form-urlencoded form; return `(status, body)`. + + The Microsoft token endpoint reports pending/declined device codes as HTTP + 400 with a JSON `error`, so the body is parsed and returned rather than + raised: the caller decides if it is retryable. + """ + data = urllib.parse.urlencode(fields).encode("utf-8") + request = urllib.request.Request( + url, + data=data, + method="POST", + headers={ + "Content-Type": "application/x-www-form-urlencoded", + "Accept": "application/json", + }, + ) + try: + with urllib.request.urlopen( + request, timeout=timeout, context=_ssl_context(verify_tls) + ) as response: + raw = response.read().decode("utf-8", "replace") + return response.status, json.loads(raw or "{}") + except urllib.error.HTTPError as exc: + raw = exc.read().decode("utf-8", "replace") + try: + body = json.loads(raw or "{}") + except ValueError: + body = {"error": "http_error", "error_description": raw[:300]} + return exc.code, body + except (urllib.error.URLError, OSError, TimeoutError) as exc: + raise OutlookError(f"cannot reach Microsoft sign-in: {exc}") from exc + + +def request_device_code( + client_id: str, + tenant: str = DEFAULT_TENANT, + scopes=DEFAULT_SCOPES, + *, + timeout: float = DEFAULT_TIMEOUT, + verify_tls: bool = True, + login: str = LOGIN, +) -> dict: + """Start a device-code flow: returns `user_code`, `verification_uri`, ...""" + if not client_id: + raise OutlookError("a Microsoft client id is required") + url = f"{login}/{tenant or DEFAULT_TENANT}/oauth2/v2.0/devicecode" + status, data = _oauth_post( + url, + {"client_id": client_id, "scope": " ".join(normalize_scopes(scopes))}, + timeout, + verify_tls, + ) + if status != 200 or "device_code" not in data: + raise OutlookError( + f"could not start Microsoft device authorization " + f"({data.get('error', status)}): {data.get('error_description', '')}".strip() + ) + return data + + +def refresh_access_token( + client_id: str, + tenant: str, + refresh_token: str, + scopes=DEFAULT_SCOPES, + *, + timeout: float = DEFAULT_TIMEOUT, + verify_tls: bool = True, + login: str = LOGIN, +) -> tuple[int, dict]: + """Exchange a refresh token for a new access token. Returns `(status, body)`.""" + url = f"{login}/{tenant or DEFAULT_TENANT}/oauth2/v2.0/token" + return _oauth_post( + url, + { + "client_id": client_id, + "grant_type": "refresh_token", + "refresh_token": refresh_token, + "scope": " ".join(normalize_scopes(scopes)), + }, + timeout, + verify_tls, + ) + + +def token_from_response(data: dict, *, tenant: str, client_id: str, fallback_refresh: str = "") -> dict: + """Normalize a token-endpoint response into the stored token dict.""" + token = { + "access_token": data.get("access_token", ""), + "refresh_token": data.get("refresh_token") or fallback_refresh, + "token_type": data.get("token_type", "Bearer"), + "scope": data.get("scope", ""), + "expires_at": time.time() + float(data.get("expires_in") or 3600), + "tenant": tenant, + "client_id": client_id, + } + return token + + +def poll_device_code( + client_id: str, + tenant: str, + device_code: str, + *, + interval: float = 5.0, + expires_in: float = 900.0, + scopes=DEFAULT_SCOPES, + timeout: float = DEFAULT_TIMEOUT, + verify_tls: bool = True, + sleep=time.sleep, + login: str = LOGIN, +) -> dict: + """Poll the token endpoint until the user completes the device-code flow. + + Handles the OAuth pending/slow-down/expiry error codes; any terminal error + is a real `OutlookError`. Returns the normalized stored token dict. + """ + url = f"{login}/{tenant or DEFAULT_TENANT}/oauth2/v2.0/token" + deadline = time.time() + float(expires_in or 900.0) + wait = max(1.0, float(interval or 5.0)) + while time.time() < deadline: + sleep(wait) + status, data = _oauth_post( + url, + { + "client_id": client_id, + "grant_type": "urn:ietf:params:oauth:grant-type:device_code", + "device_code": device_code, + "scope": " ".join(normalize_scopes(scopes)), + }, + timeout, + verify_tls, + ) + if status == 200 and "access_token" in data: + return token_from_response(data, tenant=tenant, client_id=client_id) + error = str(data.get("error") or "") + if error == "authorization_pending": + continue + if error == "slow_down": + wait += 5.0 + continue + if error in ("expired_token", "bad_verification_code"): + raise OutlookError("the Microsoft device code expired; start over") + if error in ("authorization_declined", "access_denied"): + raise OutlookError("the Microsoft authorization request was declined") + raise OutlookError( + f"Microsoft authorization failed ({error or status}): " + f"{data.get('error_description', '')}".strip() + ) + raise OutlookError("the Microsoft device code expired; start over") + + +def run_device_code_flow( + client_id: str, + tenant: str = DEFAULT_TENANT, + scopes=DEFAULT_SCOPES, + *, + timeout: float = DEFAULT_TIMEOUT, + verify_tls: bool = True, + out=print, + sleep=time.sleep, + login: str = LOGIN, +) -> dict: + """Run the whole flow: start, show instructions, poll, return the token dict.""" + device = request_device_code( + client_id, tenant, scopes, timeout=timeout, verify_tls=verify_tls, login=login + ) + message = device.get("message") or ( + f"To authorize Outlook, visit {device.get('verification_uri')} and enter " + f"the code {device.get('user_code')}." + ) + out(message) + return poll_device_code( + client_id, + tenant, + device.get("device_code", ""), + interval=float(device.get("interval") or 5.0), + expires_in=float(device.get("expires_in") or 900.0), + scopes=scopes, + timeout=timeout, + verify_tls=verify_tls, + sleep=sleep, + login=login, + ) + + +# ---- token storage ---------------------------------------------------------- + + +def load_token(path: str) -> dict: + """Read the stored token dict; raises `OutlookAuthRequired` when absent.""" + if not path or not os.path.exists(path): + raise OutlookAuthRequired(f"Outlook is not authorized ({AUTH_HINT})") + try: + with open(path, encoding="utf-8") as handle: + data = json.load(handle) + except (OSError, ValueError) as exc: + raise OutlookAuthRequired(f"the stored Outlook authorization is unreadable ({AUTH_HINT})") from exc + if not isinstance(data, dict) or not data.get("refresh_token"): + raise OutlookAuthRequired(f"the stored Outlook authorization is incomplete ({AUTH_HINT})") + return data + + +def save_token(path: str, token: dict) -> None: + """Write the token dict 0600 (it holds the refresh token, a real secret).""" + directory = os.path.dirname(os.path.abspath(path)) + if directory: + os.makedirs(directory, exist_ok=True) + tmp = f"{path}.tmp" + with open(tmp, "w", encoding="utf-8") as handle: + json.dump(token, handle, indent=2, sort_keys=True) + os.chmod(tmp, 0o600) + os.replace(tmp, path) + + +# ---- Graph normalizers ------------------------------------------------------ + + +def _address(recipient: dict) -> str: + email = (recipient or {}).get("emailAddress") or {} + name = str(email.get("name") or "").strip() + address = str(email.get("address") or "").strip() + if name and address: + return f"{name} <{address}>" + return address or name + + +def _addresses(recipients) -> list[str]: + return [_address(item) for item in (recipients or []) if isinstance(item, dict)] + + +def _message(data: dict, full: bool = False) -> dict: + result = { + "id": data.get("id"), + "subject": data.get("subject") or "", + "from": _address(data.get("from") or {}), + "to": _addresses(data.get("toRecipients")), + "cc": _addresses(data.get("ccRecipients")), + "received": data.get("receivedDateTime") or "", + "sent": data.get("sentDateTime") or "", + "is_read": bool(data.get("isRead")), + "has_attachments": bool(data.get("hasAttachments")), + "importance": data.get("importance") or "normal", + "preview": data.get("bodyPreview") or "", + "web_link": data.get("webLink") or "", + } + if full: + body = data.get("body") or {} + result["body"] = body.get("content") or "" + result["body_type"] = body.get("contentType") or "text" + return result + + +def _event(data: dict) -> dict: + start = data.get("start") or {} + end = data.get("end") or {} + location = data.get("location") or {} + return { + "id": data.get("id"), + "subject": data.get("subject") or "", + "start": start.get("dateTime") or "", + "end": end.get("dateTime") or "", + "timezone": start.get("timeZone") or "", + "all_day": bool(data.get("isAllDay")), + "location": location.get("displayName") or "", + "preview": data.get("bodyPreview") or "", + "show_as": data.get("showAs") or "", + "is_online_meeting": bool(data.get("isOnlineMeeting")), + "web_link": data.get("webLink") or "", + "organizer": _address(data.get("organizer") or {}), + } + + +def _task(data: dict, list_id: str) -> dict: + due = data.get("dueDateTime") or {} + completed = data.get("completedDateTime") or {} + body = data.get("body") or {} + return { + "id": data.get("id"), + "title": data.get("title") or "", + "status": data.get("status") or "notStarted", + "importance": data.get("importance") or "normal", + "due": due.get("dateTime") or "", + "completed": completed.get("dateTime") or "", + "description": body.get("content") or "", + "list_id": list_id, + } + + +def _contact(data: dict) -> dict: + emails = [str(item.get("address") or "") for item in (data.get("emailAddresses") or [])] + phones = list(data.get("businessPhones") or []) + list(data.get("homePhones") or []) + mobile = data.get("mobilePhone") + if mobile: + phones.append(mobile) + return { + "id": data.get("id"), + "display_name": data.get("displayName") or "", + "given_name": data.get("givenName") or "", + "surname": data.get("surname") or "", + "emails": [email for email in emails if email], + "phones": [phone for phone in phones if phone], + "company": data.get("companyName") or "", + "job_title": data.get("jobTitle") or "", + } + + +def _file(data: dict) -> dict: + folder = data.get("folder") or {} + file_info = data.get("file") or {} + parent = (data.get("parentReference") or {}).get("path") or "" + return { + "id": data.get("id"), + "name": data.get("name") or "", + "path": parent, + "size": data.get("size"), + "modified": data.get("lastModifiedDateTime") or "", + "is_folder": bool(folder) or "childCount" in folder, + "content_type": file_info.get("mimeType") or "", + "web_url": data.get("webUrl") or "", + } + + +def _graph_datetime(value, timezone_name: str) -> dict: + """A Graph `dateTimeTimeZone` from an ISO string (offset-aware -> UTC).""" + text = str(value or "").strip() + if not text: + return {"dateTime": text, "timeZone": timezone_name} + try: + moment = datetime.fromisoformat(text.replace("Z", "+00:00")) + except ValueError: + return {"dateTime": text, "timeZone": timezone_name} + if moment.tzinfo is not None: + moment = moment.astimezone(timezone.utc) + return {"dateTime": moment.strftime("%Y-%m-%dT%H:%M:%S"), "timeZone": "UTC"} + return {"dateTime": moment.strftime("%Y-%m-%dT%H:%M:%S"), "timeZone": timezone_name} + + +def _parse_naive(value): + text = str(value or "").strip() + if not text: + return None + try: + moment = datetime.fromisoformat(text.replace("Z", "+00:00")) + except ValueError: + return None + if moment.tzinfo is not None: + moment = moment.astimezone(timezone.utc).replace(tzinfo=None) + return moment + + +def _quote_path(path: str) -> str: + return urllib.parse.quote(str(path or "").strip("/"), safe="/") + + +_MAIL_WELL_KNOWN = { + "inbox", + "sentitems", + "drafts", + "deleteditems", + "archive", + "junkemail", + "outbox", + "conversationhistory", +} + + +class OutlookClient: + """A configured connection to one Microsoft account via Graph.""" + + def __init__( + self, + client_id: str, + *, + tenant: str = DEFAULT_TENANT, + token_path: str = "", + scopes=DEFAULT_SCOPES, + timeout: float = DEFAULT_TIMEOUT, + verify_tls: bool = True, + default_calendar: str = "", + default_task_list: str = "", + default_mail_folder: str = "inbox", + default_timezone: str = "UTC", + graph: str = GRAPH, + login: str = LOGIN, + ): + self.client_id = str(client_id or "").strip() + self.tenant = str(tenant or DEFAULT_TENANT).strip() or DEFAULT_TENANT + self.token_path = str(token_path or "") + self.scopes = normalize_scopes(scopes) + self.timeout = float(timeout or DEFAULT_TIMEOUT) + self.verify_tls = bool(verify_tls) + self.default_calendar = str(default_calendar or "").strip() + self.default_task_list = str(default_task_list or "").strip() + self.default_mail_folder = str(default_mail_folder or "inbox").strip() or "inbox" + self.default_timezone = str(default_timezone or "UTC").strip() or "UTC" + self.graph = str(graph or GRAPH).rstrip("/") + self.login = str(login or LOGIN).rstrip("/") + + @property + def configured(self) -> bool: + return bool(self.client_id and self.token_path) + + # ---- token lifecycle ---- + + def _access_token(self, force_refresh: bool = False) -> str: + token = load_token(self.token_path) + access = token.get("access_token") + expires_at = float(token.get("expires_at") or 0) + if access and not force_refresh and expires_at - time.time() > TOKEN_REFRESH_SKEW: + return str(access) + refresh = token.get("refresh_token") + if not refresh: + raise OutlookAuthRequired(f"the stored Outlook authorization has no refresh token ({AUTH_HINT})") + status, data = refresh_access_token( + self.client_id, + self.tenant, + refresh, + self.scopes, + timeout=self.timeout, + verify_tls=self.verify_tls, + login=self.login, + ) + if status != 200 or "access_token" not in data: + raise OutlookAuthRequired( + f"could not refresh Microsoft authorization " + f"({data.get('error', status)}); {AUTH_HINT}" + ) + updated = token_from_response( + data, tenant=self.tenant, client_id=self.client_id, fallback_refresh=refresh + ) + save_token(self.token_path, updated) + return str(updated["access_token"]) + + # ---- transport ---- + + def _request( + self, + method: str, + path: str, + *, + params: dict | None = None, + body=None, + headers: dict | None = None, + raw_body: bool = False, + raw: bool = False, + ): + """One Graph call with bearer auth, a 401 refresh-retry, and 429 backoff.""" + url = path if str(path).startswith("http") else self.graph + path + if params: + clean = {k: v for k, v in params.items() if v is not None} + if clean: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(clean) + attempt = 0 + refreshed = False + while True: + token = self._access_token(force_refresh=refreshed) + request_headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"} + data = None + if body is not None: + if raw_body: + data = body if isinstance(body, (bytes, bytearray)) else str(body).encode("utf-8") + else: + data = json.dumps(body).encode("utf-8") + request_headers["Content-Type"] = "application/json" + if headers: + request_headers.update(headers) + request = urllib.request.Request(url, data=data, method=method, headers=request_headers) + try: + with urllib.request.urlopen( + request, timeout=self.timeout, context=_ssl_context(self.verify_tls) + ) as response: + payload = response.read() + if raw: + return payload, response.headers + return json.loads(payload.decode("utf-8") or "{}"), response.headers + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace").strip() + if exc.code == 401 and not refreshed: + refreshed = True + continue + if exc.code in (429, 503) and attempt < MAX_RETRIES: + time.sleep(_retry_after(exc.headers, attempt)) + attempt += 1 + continue + message = f"{method} {path}: HTTP {exc.code}" + detail_text = _graph_error(detail) + if detail_text: + message += f" {detail_text}" + raise OutlookError(message, status=exc.code) from exc + except (urllib.error.URLError, OSError, TimeoutError) as exc: + raise OutlookError(f"{method} {path}: {exc}") from exc + + def _paged(self, path: str, params: dict | None = None, key: str = "value", limit: int = MAX_PAGES) -> list: + items: list = [] + data, _headers = self._request("GET", path, params=params) + for _ in range(max(1, limit)): + if isinstance(data, dict): + values = data.get(key) + if isinstance(values, list): + items.extend(values) + next_link = data.get("@odata.nextLink") + else: + next_link = None + if not next_link: + break + data, _headers = self._request("GET", next_link) + return items + + # ---- account ---- + + def me(self) -> dict: + data, _ = self._request( + "GET", "/me", params={"$select": "id,displayName,mail,userPrincipalName"} + ) + return { + "id": data.get("id"), + "display_name": data.get("displayName") or "", + "mail": data.get("mail") or data.get("userPrincipalName") or "", + "user_principal_name": data.get("userPrincipalName") or "", + } + + # ---- mail ---- + + def list_mail_folders(self) -> list[dict]: + items = self._paged( + "/me/mailFolders", + {"$select": "id,displayName,totalItemCount,unreadItemCount", "$top": 100}, + ) + return [ + { + "id": item.get("id"), + "name": item.get("displayName") or "", + "total": item.get("totalItemCount"), + "unread": item.get("unreadItemCount"), + } + for item in items + ] + + def _resolve_mail_folder(self, folder) -> str: + name = str(folder or self.default_mail_folder or "inbox").strip() + if not name: + name = "inbox" + if name.lower() in _MAIL_WELL_KNOWN: + return name.lower() + for candidate in self.list_mail_folders(): + if name.lower() in (str(candidate["id"]).lower(), str(candidate["name"]).lower()): + return str(candidate["id"]) + raise OutlookError(f"mail folder {name!r} not found") + + def list_messages(self, folder="", count=25, search="", unread_only=False) -> list[dict]: + params = { + "$top": max(1, min(int(count or 25), 100)), + "$orderby": "receivedDateTime desc", + "$select": ( + "id,subject,from,toRecipients,ccRecipients,receivedDateTime,isRead," + "hasAttachments,bodyPreview,importance,webLink" + ), + } + if search: + params["$search"] = '"' + str(search).replace('"', "") + '"' + elif unread_only: + params["$filter"] = "isRead eq false" + folder_id = self._resolve_mail_folder(folder) + items = self._paged( + f"/me/mailFolders/{urllib.parse.quote(folder_id)}/messages", params, limit=1 + ) + return [_message(item) for item in items] + + def get_message(self, message_id: str) -> dict: + data, _ = self._request( + "GET", + f"/me/messages/{urllib.parse.quote(message_id)}", + params={ + "$select": ( + "id,subject,from,toRecipients,ccRecipients,receivedDateTime," + "sentDateTime,isRead,hasAttachments,body,bodyPreview,importance,webLink" + ) + }, + ) + return _message(data, full=True) + + def send_mail(self, to, subject, body, cc=(), content_type="text", save_to_sent=True) -> dict: + recipients = [str(item) for item in (to or []) if str(item).strip()] + if not recipients: + raise ValueError("to is required") + message = { + "subject": str(subject or ""), + "body": { + "contentType": "HTML" if str(content_type).lower() == "html" else "Text", + "content": str(body or ""), + }, + "toRecipients": [{"emailAddress": {"address": address}} for address in recipients], + "ccRecipients": [ + {"emailAddress": {"address": str(item)}} + for item in (cc or []) + if str(item).strip() + ], + } + self._request( + "POST", "/me/sendMail", body={"message": message, "saveToSentItems": bool(save_to_sent)} + ) + return {"ok": True, "to": recipients, "cc": list(cc or []), "subject": message["subject"]} + + def create_draft(self, to, subject, body, cc=(), content_type="text") -> dict: + message = { + "subject": str(subject or ""), + "body": { + "contentType": "HTML" if str(content_type).lower() == "html" else "Text", + "content": str(body or ""), + }, + "toRecipients": [ + {"emailAddress": {"address": str(item)}} + for item in (to or []) + if str(item).strip() + ], + "ccRecipients": [ + {"emailAddress": {"address": str(item)}} + for item in (cc or []) + if str(item).strip() + ], + } + data, _ = self._request("POST", "/me/messages", body=message) + return {"ok": True, "id": data.get("id"), "subject": message["subject"]} + + # ---- calendar ---- + + def list_calendars(self) -> list[dict]: + items = self._paged( + "/me/calendars", + {"$select": "id,name,color,isDefaultCalendar,canEdit", "$top": 100}, + ) + return [ + { + "id": item.get("id"), + "name": item.get("name") or "", + "color": item.get("color") or "", + "is_default": bool(item.get("isDefaultCalendar")), + "can_edit": bool(item.get("canEdit")), + } + for item in items + ] + + def _resolve_calendar(self, calendar) -> str: + requested = str(calendar or self.default_calendar or "").strip() + if not requested: + return "" + lowered = requested.lower() + for candidate in self.list_calendars(): + if lowered in (str(candidate["id"]).lower(), str(candidate["name"]).lower()): + return str(candidate["id"]) + # Not a known name; let Graph reject an id it does not own (mapped to 502). + return requested + + def _calendar_view_path(self, calendar_id: str) -> str: + if calendar_id: + return f"/me/calendars/{urllib.parse.quote(calendar_id)}/calendarView" + return "/me/calendarView" + + def list_events(self, calendar="", start="", end="") -> list[dict]: + calendar_id = self._resolve_calendar(calendar) + now = datetime.now(timezone.utc) + window_start = start or now.strftime("%Y-%m-%dT%H:%M:%S") + window_end = end or (now + timedelta(days=30)).strftime("%Y-%m-%dT%H:%M:%S") + params = { + "startDateTime": window_start, + "endDateTime": window_end, + "$select": ( + "id,subject,start,end,isAllDay,location,bodyPreview,showAs," + "isOnlineMeeting,webLink,organizer" + ), + "$orderby": "start/dateTime", + "$top": 50, + } + items = self._paged(self._calendar_view_path(calendar_id), params, limit=4) + return [_event(item) for item in items] + + def create_event( + self, + calendar="", + subject="", + start="", + end="", + all_day=False, + location="", + description="", + attendees=(), + timezone_name="", + ) -> dict: + calendar_id = self._resolve_calendar(calendar) + tz = str(timezone_name or self.default_timezone or "UTC").strip() or "UTC" + if not end: + parsed = _parse_naive(start) + if parsed is not None: + delta = timedelta(days=1) if all_day else timedelta(hours=1) + end = (parsed + delta).strftime("%Y-%m-%dT%H:%M:%S") + event = { + "subject": str(subject or ""), + "start": _graph_datetime(start, tz), + "end": _graph_datetime(end or start, tz), + "isAllDay": bool(all_day), + } + if location: + event["location"] = {"displayName": str(location)} + if description: + event["body"] = {"contentType": "Text", "content": str(description)} + attendee_list = [str(item) for item in (attendees or []) if str(item).strip()] + if attendee_list: + event["attendees"] = [ + {"emailAddress": {"address": address}, "type": "required"} + for address in attendee_list + ] + path = ( + f"/me/calendars/{urllib.parse.quote(calendar_id)}/events" + if calendar_id + else "/me/events" + ) + data, _ = self._request("POST", path, body=event) + return { + "ok": True, + "id": data.get("id"), + "subject": data.get("subject") or event["subject"], + "calendar": calendar_id, + "web_link": data.get("webLink") or "", + } + + def update_event(self, event_id: str, *, timezone_name: str = "", **fields) -> dict: + patch: dict = {} + if "subject" in fields and fields["subject"] is not None: + patch["subject"] = str(fields["subject"]) + tz = str(timezone_name or self.default_timezone or "UTC").strip() or "UTC" + if fields.get("start"): + patch["start"] = _graph_datetime(fields["start"], tz) + if fields.get("end"): + patch["end"] = _graph_datetime(fields["end"], tz) + if "all_day" in fields and fields["all_day"] is not None: + patch["isAllDay"] = bool(fields["all_day"]) + if fields.get("location") is not None: + patch["location"] = {"displayName": str(fields.get("location") or "")} + if fields.get("description") is not None: + patch["body"] = {"contentType": "Text", "content": str(fields.get("description") or "")} + data, _ = self._request( + "PATCH", f"/me/events/{urllib.parse.quote(event_id)}", body=patch + ) + return {"ok": True, "id": data.get("id") or event_id, "subject": data.get("subject") or ""} + + def delete_event(self, event_id: str) -> dict: + self._request("DELETE", f"/me/events/{urllib.parse.quote(event_id)}") + return {"ok": True, "id": event_id} + + # ---- To Do tasks ---- + + def list_task_lists(self) -> list[dict]: + items = self._paged( + "/me/todo/lists", + {"$select": "id,displayName,isOwner,wellknownListName", "$top": 100}, + ) + return [ + { + "id": item.get("id"), + "name": item.get("displayName") or "", + "is_owner": bool(item.get("isOwner")), + "is_default": str(item.get("wellknownListName") or "") == "defaultList", + } + for item in items + ] + + def _resolve_task_list(self, task_list) -> str: + requested = str(task_list or self.default_task_list or "").strip() + lists = self.list_task_lists() + if requested: + lowered = requested.lower() + for candidate in lists: + if lowered in (str(candidate["id"]).lower(), str(candidate["name"]).lower()): + return str(candidate["id"]) + return requested + for candidate in lists: + if candidate.get("is_default"): + return str(candidate["id"]) + if lists: + return str(lists[0]["id"]) + raise OutlookError("no Microsoft To Do task lists are available") + + def list_tasks(self, task_list="") -> list[dict]: + list_id = self._resolve_task_list(task_list) + items = self._paged( + f"/me/todo/lists/{urllib.parse.quote(list_id)}/tasks", + { + "$select": ( + "id,title,status,importance,dueDateTime,completedDateTime,body,createdDateTime" + ), + "$top": 100, + }, + ) + return [_task(item, list_id) for item in items] + + def create_task(self, task_list="", title="", due="", importance="", description="") -> dict: + list_id = self._resolve_task_list(task_list) + task: dict = {"title": str(title or "")} + if due: + task["dueDateTime"] = _graph_datetime(due, self.default_timezone) + if importance: + task["importance"] = str(importance) + if description: + task["body"] = {"contentType": "Text", "content": str(description)} + data, _ = self._request( + "POST", f"/me/todo/lists/{urllib.parse.quote(list_id)}/tasks", body=task + ) + return {"ok": True, "id": data.get("id"), "title": data.get("title") or task["title"], "list_id": list_id} + + def update_task(self, task_id: str, *, task_list="", **fields) -> dict: + list_id = self._resolve_task_list(task_list) + patch: dict = {} + for key in ("title", "importance", "status"): + if fields.get(key) is not None: + patch[key] = str(fields[key]) + if fields.get("due"): + patch["dueDateTime"] = _graph_datetime(fields["due"], self.default_timezone) + if fields.get("description") is not None: + patch["body"] = {"contentType": "Text", "content": str(fields.get("description") or "")} + data, _ = self._request( + "PATCH", + f"/me/todo/lists/{urllib.parse.quote(list_id)}/tasks/{urllib.parse.quote(task_id)}", + body=patch, + ) + return {"ok": True, "id": data.get("id") or task_id, "status": data.get("status") or ""} + + def complete_task(self, task_id: str, task_list="") -> dict: + return self.update_task(task_id, task_list=task_list, status="completed") + + def delete_task(self, task_id: str, task_list="") -> dict: + list_id = self._resolve_task_list(task_list) + self._request( + "DELETE", + f"/me/todo/lists/{urllib.parse.quote(list_id)}/tasks/{urllib.parse.quote(task_id)}", + ) + return {"ok": True, "id": task_id} + + # ---- contacts ---- + + def list_contacts(self, query="", count=50) -> list[dict]: + params = { + "$select": ( + "id,displayName,givenName,surname,emailAddresses,businessPhones," + "homePhones,mobilePhone,companyName,jobTitle" + ), + "$top": max(1, min(int(count or 50), 100)), + } + if query: + params["$search"] = '"' + str(query).replace('"', "") + '"' + items = self._paged("/me/contacts", params, limit=1) + return [_contact(item) for item in items] + + # ---- OneDrive files ---- + + def list_files(self, path="/") -> list[dict]: + clean = str(path or "/").strip("/") + if clean: + endpoint = f"/me/drive/root:/{_quote_path(clean)}:/children" + else: + endpoint = "/me/drive/root/children" + items = self._paged( + endpoint, + { + "$select": ( + "id,name,size,lastModifiedDateTime,folder,file,webUrl,parentReference" + ), + "$top": 200, + }, + limit=2, + ) + return [_file(item) for item in items] + + def read_file(self, path: str) -> dict: + clean = str(path or "").strip("/") + if not clean: + raise ValueError("path is required") + meta, _ = self._request( + "GET", + f"/me/drive/root:/{_quote_path(clean)}:", + params={"$select": "id,name,size,file,lastModifiedDateTime,webUrl"}, + ) + payload, _ = self._request( + "GET", f"/me/drive/root:/{_quote_path(clean)}:/content", raw=True + ) + content_type = ((meta.get("file") or {}).get("mimeType")) or "" + try: + text = payload.decode("utf-8") + encoding = "utf-8" + except UnicodeDecodeError: + text = base64.b64encode(payload).decode("ascii") + encoding = "base64" + return { + "path": clean, + "name": meta.get("name") or clean.rsplit("/", 1)[-1], + "content": text, + "encoding": encoding, + "size": meta.get("size"), + "content_type": content_type, + "modified": meta.get("lastModifiedDateTime") or "", + } + + def write_file(self, path: str, content: str, encoding: str = "utf-8", overwrite: bool = True) -> dict: + clean = str(path or "").strip("/") + if not clean: + raise ValueError("path is required") + if str(encoding).lower() == "base64": + payload = base64.b64decode(content or "") + else: + payload = str(content or "").encode("utf-8") + headers = {"Content-Type": "application/octet-stream"} + if not overwrite: + headers["If-None-Match"] = "*" + data, _ = self._request( + "PUT", + f"/me/drive/root:/{_quote_path(clean)}:/content", + body=payload, + raw_body=True, + headers=headers, + ) + return { + "ok": True, + "path": clean, + "id": data.get("id"), + "size": data.get("size"), + "web_url": data.get("webUrl") or "", + } diff --git a/semif_agent/bridges/registry.py b/semif_agent/bridges/registry.py index b1e71bf..2725ee0 100644 --- a/semif_agent/bridges/registry.py +++ b/semif_agent/bridges/registry.py @@ -15,10 +15,16 @@ import threading from .base import BridgeInfo, BridgeService from .llm import LLMBridge from .nextcloud import NextcloudBridge +from .outlook import OutlookBridge from .simplex import SimplexBridge #: Known bridge services. Order is presentation order. -CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge, LLMBridge, NextcloudBridge) +CATALOG: tuple[type[BridgeService], ...] = ( + SimplexBridge, + LLMBridge, + NextcloudBridge, + OutlookBridge, +) def _class_for(name: str) -> type[BridgeService] | None: diff --git a/tests/test_outlook_bridge.py b/tests/test_outlook_bridge.py new file mode 100644 index 0000000..3921817 --- /dev/null +++ b/tests/test_outlook_bridge.py @@ -0,0 +1,646 @@ +"""Pure-stdlib tests for the Outlook (Microsoft Graph) bridge. + +A loopback `http.server` plays Microsoft's token endpoint and Graph API so the +bridge's own client is exercised over HTTP with no mocking of the transport. The +decision engine and LLM are never involved. A few route tests inject a fake +client to check wiring/validation without a server. Passing these proves +mechanics only; a real run against the user's Microsoft account is the only proof +the integration works. +""" + +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse + +import pytest + +from semif_agent.bridges.outlook import OutlookBridge +from semif_agent.bridges.outlook_client import ( + OutlookAuthRequired, + OutlookClient, + OutlookError, + load_token, + run_device_code_flow, + save_token, +) +from semif_agent.bridges.registry import build_bridge, derived_config_vars, describe_bridges, known_infos + + +class FakeGraph: + """A minimal but real Microsoft-shaped HTTP server (token + Graph).""" + + def __init__(self): + self.calls = [] + self.refresh_calls = 0 + self.device_polls = 0 + self.token_status = 200 + self._server = None + self._thread = None + + # ---- lifecycle ---- + + def start(self): + fake = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def _read(self): + length = int(self.headers.get("Content-Length") or 0) + return self.rfile.read(length) if length else b"" + + def _send(self, status, payload): + 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 _dispatch(self, method): + body = self._read() + fake.calls.append((method, self.path, dict(self.headers), body)) + status, payload = fake.handle(method, self.path, body) + if status == 204: + self.send_response(204) + self.send_header("Content-Length", "0") + self.end_headers() + return + if isinstance(payload, bytes): + self.send_response(status) + self.send_header("Content-Type", "application/octet-stream") + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + return + self._send(status, payload) + + def do_GET(self): + self._dispatch("GET") + + def do_POST(self): + self._dispatch("POST") + + def do_PUT(self): + self._dispatch("PUT") + + def do_PATCH(self): + self._dispatch("PATCH") + + def do_DELETE(self): + self._dispatch("DELETE") + + self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self._thread = threading.Thread(target=self._server.serve_forever, daemon=True) + self._thread.start() + return f"http://127.0.0.1:{self._server.server_address[1]}" + + def stop(self): + if self._server is not None: + self._server.shutdown() + self._server.server_close() + self._server = None + + # ---- routing ---- + + def handle(self, method, path, body): + parsed = urlparse(path) + route = parsed.path + query = parse_qs(parsed.query) + + # ---- OAuth token endpoint ---- + if route.endswith("/oauth2/v2.0/devicecode"): + return 200, { + "device_code": "dev-code", + "user_code": "ABCD-EFGH", + "verification_uri": "https://microsoft.com/devicelogin", + "interval": 1, + "expires_in": 900, + "message": "go to https://microsoft.com/devicelogin and enter ABCD-EFGH", + } + if route.endswith("/oauth2/v2.0/token"): + fields = parse_qs(body.decode("utf-8")) + grant = (fields.get("grant_type") or [""])[0] + if grant == "refresh_token": + self.refresh_calls += 1 + return self.token_status, { + "access_token": f"refreshed-{self.refresh_calls}", + "refresh_token": f"rotated-{self.refresh_calls}", + "expires_in": 3600, + "token_type": "Bearer", + "scope": "Mail.ReadWrite", + } + # device-code poll: pending once, then success + self.device_polls += 1 + if self.device_polls < 2: + return 400, {"error": "authorization_pending"} + return 200, { + "access_token": "device-access", + "refresh_token": "device-refresh", + "expires_in": 3600, + "token_type": "Bearer", + "scope": "Mail.ReadWrite", + } + + # ---- Graph ---- + if method == "GET" and route == "/v1.0/me": + return 200, { + "id": "user-1", + "displayName": "Jane Doe", + "mail": "jane@example.com", + "userPrincipalName": "jane@example.com", + } + if method == "GET" and route == "/v1.0/me/mailFolders": + return 200, { + "value": [ + {"id": "inbox", "displayName": "Inbox", "totalItemCount": 3, "unreadItemCount": 1} + ] + } + if method == "GET" and route == "/v1.0/me/mailFolders/inbox/messages": + return 200, { + "value": [ + { + "id": "m1", + "subject": "Hello", + "from": {"emailAddress": {"name": "Alice", "address": "alice@example.com"}}, + "toRecipients": [{"emailAddress": {"address": "jane@example.com"}}], + "ccRecipients": [], + "receivedDateTime": "2026-10-08T09:00:00Z", + "isRead": False, + "hasAttachments": False, + "bodyPreview": "Hi there", + "importance": "normal", + "webLink": "https://outlook/m1", + } + ] + } + if method == "GET" and route == "/v1.0/me/messages/m1": + return 200, { + "id": "m1", + "subject": "Hello", + "from": {"emailAddress": {"name": "Alice", "address": "alice@example.com"}}, + "toRecipients": [{"emailAddress": {"address": "jane@example.com"}}], + "ccRecipients": [], + "receivedDateTime": "2026-10-08T09:00:00Z", + "isRead": False, + "hasAttachments": False, + "body": {"contentType": "text", "content": "Hi there"}, + "bodyPreview": "Hi there", + "importance": "normal", + "webLink": "https://outlook/m1", + } + if method == "POST" and route == "/v1.0/me/sendMail": + self.sent = json.loads(body.decode("utf-8")) + return 202, {} + if method == "POST" and route == "/v1.0/me/messages": + payload = json.loads(body.decode("utf-8")) + return 201, {"id": "draft-1", "subject": payload.get("subject", "")} + if method == "GET" and route == "/v1.0/me/calendars": + return 200, { + "value": [ + {"id": "cal1", "name": "Calendar", "color": "auto", "isDefaultCalendar": True, "canEdit": True} + ] + } + if method == "GET" and route == "/v1.0/me/calendarView": + return 200, { + "value": [ + { + "id": "e1", + "subject": "Standup", + "start": {"dateTime": "2026-10-08T09:00:00.0000000", "timeZone": "UTC"}, + "end": {"dateTime": "2026-10-08T09:30:00.0000000", "timeZone": "UTC"}, + "isAllDay": False, + "location": {"displayName": "Room 1"}, + "bodyPreview": "", + "showAs": "busy", + "isOnlineMeeting": False, + "webLink": "https://outlook/e1", + "organizer": {"emailAddress": {"address": "jane@example.com"}}, + } + ] + } + if method == "POST" and route == "/v1.0/me/events": + payload = json.loads(body.decode("utf-8")) + return 201, { + "id": "new-event", + "subject": payload.get("subject"), + "webLink": "https://outlook/new-event", + } + if method == "PATCH" and route.startswith("/v1.0/me/events/"): + payload = json.loads(body.decode("utf-8")) + return 200, {"id": route.rsplit("/", 1)[-1], "subject": payload.get("subject", "")} + if method == "DELETE" and route.startswith("/v1.0/me/events/"): + return 204, {} + if method == "GET" and route == "/v1.0/me/todo/lists": + return 200, { + "value": [ + {"id": "list1", "displayName": "Tasks", "isOwner": True, "wellknownListName": "defaultList"} + ] + } + if method == "GET" and route == "/v1.0/me/todo/lists/list1/tasks": + return 200, { + "value": [ + { + "id": "t1", + "title": "Buy milk", + "status": "notStarted", + "importance": "normal", + "dueDateTime": {"dateTime": "2026-10-10T00:00:00", "timeZone": "UTC"}, + "completedDateTime": {}, + "body": {"content": ""}, + } + ] + } + if method == "POST" and route == "/v1.0/me/todo/lists/list1/tasks": + payload = json.loads(body.decode("utf-8")) + return 201, {"id": "t2", "title": payload.get("title")} + if method == "PATCH" and route.startswith("/v1.0/me/todo/lists/list1/tasks/"): + payload = json.loads(body.decode("utf-8")) + return 200, {"id": route.rsplit("/", 1)[-1], "status": payload.get("status", "notStarted")} + if method == "DELETE" and route.startswith("/v1.0/me/todo/lists/list1/tasks/"): + return 204, {} + if method == "GET" and route == "/v1.0/me/contacts": + return 200, { + "value": [ + { + "id": "c1", + "displayName": "Bob Smith", + "givenName": "Bob", + "surname": "Smith", + "emailAddresses": [{"address": "bob@example.com"}], + "businessPhones": ["555-1234"], + "homePhones": [], + "mobilePhone": None, + "companyName": "Acme", + "jobTitle": "Dev", + } + ] + } + if method == "GET" and route == "/v1.0/me/drive/root/children": + return 200, { + "value": [ + { + "id": "f1", + "name": "notes.txt", + "size": 5, + "lastModifiedDateTime": "2026-10-08T08:00:00Z", + "file": {"mimeType": "text/plain"}, + "parentReference": {"path": "/drive/root:"}, + "webUrl": "https://onedrive/f1", + } + ] + } + if route.startswith("/v1.0/me/drive/root:/") and route.endswith(":"): + return 200, { + "id": "f1", + "name": "notes.txt", + "size": 5, + "file": {"mimeType": "text/plain"}, + "lastModifiedDateTime": "2026-10-08T08:00:00Z", + "webUrl": "https://onedrive/f1", + } + if route.startswith("/v1.0/me/drive/root:/") and route.endswith("/content"): + if method == "GET": + return 200, b"hello" + return 201, {"id": "f2", "size": 5, "webUrl": "https://onedrive/f2"} + + return 404, {"error": {"code": "notFound", "message": f"no fake route for {method} {route}"}} + + +@pytest.fixture() +def fake(): + server = FakeGraph() + base = server.start() + try: + yield server, base + finally: + server.stop() + + +def make_client(fake, tmp_path, *, token="tok", expires_at=None, refresh="r1", graph_suffix="/v1.0"): + server, base = fake + token_path = tmp_path / "token.json" + if token is not None: + save_token( + str(token_path), + { + "access_token": token, + "refresh_token": refresh, + "expires_at": 9999999999 if expires_at is None else expires_at, + "token_type": "Bearer", + }, + ) + return OutlookClient( + "client-1", + tenant="common", + token_path=str(token_path), + graph=base + graph_suffix, + login=base, + ) + + +# ---- OAuth ---- + +def test_device_code_flow_polls_until_success(fake): + server, base = fake + lines = [] + token = run_device_code_flow( + "client-1", "common", out=lines.append, sleep=lambda _s: None, login=base + ) + assert token["access_token"] == "device-access" + assert token["refresh_token"] == "device-refresh" + assert any("ABCD-EFGH" in line for line in lines) + assert server.device_polls == 2 + + +def test_token_refresh_on_expiry(fake, tmp_path): + server, base = fake + client = make_client(fake, tmp_path, token="stale", expires_at=0) + user = client.me() + assert user["display_name"] == "Jane Doe" + assert server.refresh_calls == 1 + stored = load_token(str(tmp_path / "token.json")) + assert stored["access_token"] == "refreshed-1" + assert stored["refresh_token"] == "rotated-1" + + +def test_missing_token_raises_auth_required(tmp_path): + client = OutlookClient( + "client-1", token_path=str(tmp_path / "missing.json"), graph="http://127.0.0.1:1/v1.0" + ) + with pytest.raises(OutlookAuthRequired): + client.me() + + +def test_not_configured_without_client_id(tmp_path): + client = OutlookClient("", token_path=str(tmp_path / "t.json")) + assert client.configured is False + + +# ---- Graph client ---- + +def test_me_and_mail(fake, tmp_path): + client = make_client(fake, tmp_path) + assert client.me()["mail"] == "jane@example.com" + folders = client.list_mail_folders() + assert folders[0]["name"] == "Inbox" + messages = client.list_messages("inbox") + assert messages[0]["subject"] == "Hello" + assert messages[0]["from"] == "Alice " + assert messages[0]["to"] == ["jane@example.com"] + full = client.get_message("m1") + assert full["body"] == "Hi there" + assert full["body_type"] == "text" + + +def test_send_mail(fake, tmp_path): + server, _base = fake + client = make_client(fake, tmp_path) + result = client.send_mail(["sam@example.com"], "Lunch", "Tomorrow?", cc=["bob@example.com"]) + assert result["ok"] is True + sent = server.sent + assert sent["message"]["subject"] == "Lunch" + assert sent["message"]["toRecipients"][0]["emailAddress"]["address"] == "sam@example.com" + assert sent["message"]["ccRecipients"][0]["emailAddress"]["address"] == "bob@example.com" + assert sent["saveToSentItems"] is True + + +def test_create_draft(fake, tmp_path): + client = make_client(fake, tmp_path) + result = client.create_draft(["sam@example.com"], "Draft", "body") + assert result["id"] == "draft-1" + assert result["subject"] == "Draft" + + +def test_list_events(fake, tmp_path): + client = make_client(fake, tmp_path) + events = client.list_events() + assert events[0]["subject"] == "Standup" + assert events[0]["start"] == "2026-10-08T09:00:00.0000000" + assert events[0]["location"] == "Room 1" + assert events[0]["organizer"] == "jane@example.com" + + +def test_create_event_builds_graph_body(fake, tmp_path): + server, _base = fake + client = make_client(fake, tmp_path) + result = client.create_event( + subject="Dentist", + start="2026-11-10T14:00:00", + all_day=False, + location="Clinic", + timezone_name="America/Chicago", + ) + assert result["ok"] is True + assert result["id"] == "new-event" + call = next(c for c in server.calls if c[0] == "POST" and c[1] == "/v1.0/me/events") + body = json.loads(call[3].decode("utf-8")) + assert body["subject"] == "Dentist" + assert body["start"] == {"dateTime": "2026-11-10T14:00:00", "timeZone": "America/Chicago"} + # end defaults to one hour after start + assert body["end"]["dateTime"] == "2026-11-10T15:00:00" + assert body["isAllDay"] is False + assert body["location"] == {"displayName": "Clinic"} + + +def test_create_event_all_day_defaults_end_next_day(fake, tmp_path): + server, _base = fake + client = make_client(fake, tmp_path) + client.create_event(subject="Conference", start="2026-11-10T00:00:00", all_day=True) + call = next(c for c in server.calls if c[0] == "POST" and c[1] == "/v1.0/me/events") + body = json.loads(call[3].decode("utf-8")) + assert body["isAllDay"] is True + assert body["end"]["dateTime"].startswith("2026-11-11") + + +def test_tasks_flow(fake, tmp_path): + client = make_client(fake, tmp_path) + lists = client.list_task_lists() + assert lists[0]["is_default"] is True + tasks = client.list_tasks() + assert tasks[0]["title"] == "Buy milk" + created = client.create_task(title="Call mom", due="2026-10-12T09:00:00") + assert created["id"] == "t2" + completed = client.complete_task("t1") + assert completed["status"] == "completed" + + +def test_contacts(fake, tmp_path): + client = make_client(fake, tmp_path) + contacts = client.list_contacts("bob") + assert contacts[0]["display_name"] == "Bob Smith" + assert contacts[0]["emails"] == ["bob@example.com"] + assert "555-1234" in contacts[0]["phones"] + + +def test_files_read_and_write(fake, tmp_path): + client = make_client(fake, tmp_path) + entries = client.list_files("/") + assert entries[0]["name"] == "notes.txt" + read = client.read_file("notes.txt") + assert read["content"] == "hello" + assert read["encoding"] == "utf-8" + written = client.write_file("notes.txt", "hello", overwrite=True) + assert written["ok"] is True + assert written["path"] == "notes.txt" + + +def test_unreachable_graph_is_an_outlook_error(tmp_path): + client = OutlookClient( + "client-1", token_path=str(tmp_path / "t.json"), graph="http://127.0.0.1:1/v1.0" + ) + save_token(str(tmp_path / "t.json"), {"access_token": "x", "refresh_token": "r", "expires_at": 9999999999}) + with pytest.raises(OutlookError): + client.me() + + +# ---- bridge routes ---- + +class StubClient: + configured = True + + def __init__(self): + self.calls = [] + + def me(self): + return {"display_name": "Jane"} + + def list_mail_folders(self): + return [{"id": "inbox", "name": "Inbox"}] + + def list_messages(self, folder="", count=25, search="", unread_only=False): + self.calls.append(("list_messages", folder, count, search, unread_only)) + return [{"id": "m1", "subject": "Hello"}] + + def get_message(self, message_id): + return {"id": message_id, "body": "hi"} + + def send_mail(self, to, subject, body, cc=(), content_type="text", save_to_sent=True): + self.calls.append(("send_mail", to, subject, body, cc)) + return {"ok": True, "to": to} + + def create_event(self, **kwargs): + self.calls.append(("create_event", kwargs)) + return {"ok": True, "id": "e1"} + + def list_events(self, calendar="", start="", end=""): + return [{"id": "e1", "subject": "Standup"}] + + def create_task(self, **kwargs): + self.calls.append(("create_task", kwargs)) + return {"ok": True, "id": "t1"} + + def list_files(self, path="/"): + return [{"name": "notes.txt"}] + + def write_file(self, path, content, encoding="utf-8", overwrite=True): + return {"ok": True, "path": path} + + def list_calendars(self): + return [] + + def list_task_lists(self): + return [] + + def list_tasks(self, task_list=""): + return [] + + def list_contacts(self, query="", count=50): + return [] + + +def test_bridge_routes_wire_to_client(): + stub = StubClient() + bridge = OutlookBridge({"client_id": "c", "token_path": "/tmp/x"}, client=stub) + assert bridge.handle_get("/health", {}) == (200, {"ok": True, "platform": "outlook"}) + status, payload = bridge.handle_get("/mail/messages", {"folder": ["inbox"], "count": ["10"]}) + assert status == 200 and payload["messages"][0]["subject"] == "Hello" + assert stub.calls[-1] == ("list_messages", "inbox", 10, "", False) + status, payload = bridge.handle_post( + "/mail/send", {"to": ["sam@example.com"], "subject": "Hi", "body": "there"} + ) + assert status == 200 and payload["ok"] is True + assert stub.calls[-1] == ("send_mail", ["sam@example.com"], "Hi", "there", []) + status, _payload = bridge.handle_post("/calendars/events", {"subject": "Standup", "start": "2026-01-01T09:00:00"}) + assert status == 200 + assert stub.calls[-1][0] == "create_event" + + +def test_bridge_validation_errors(): + bridge = OutlookBridge({"client_id": "c"}, client=StubClient()) + status, payload = bridge.handle_post("/calendars/events", {"start": "2026-01-01T09:00:00"}) + assert status == 400 and "subject" in payload["error"] + status, payload = bridge.handle_post("/mail/send", {"subject": "no recipient"}) + assert status == 400 and "to" in payload["error"] + status, _ = bridge.handle_post("/nope", {}) + assert status == 404 + + +def test_bridge_unconfigured_is_503(): + bridge = OutlookBridge({}, client=StubClient()) + bridge.client = type("C", (), {"configured": False})() + assert bridge.handle_get("/mail/messages", {})[0] == 503 + assert bridge.handle_post("/mail/send", {"to": ["a@b.c"]})[0] == 503 + + +def test_bridge_auth_required_is_503(): + class Unauthorized: + configured = True + + def list_messages(self, *args, **kwargs): + raise OutlookAuthRequired("run scripts/outlook-auth.py") + + bridge = OutlookBridge({"client_id": "c"}, client=Unauthorized()) + status, payload = bridge.handle_get("/mail/messages", {}) + assert status == 503 + assert "outlook-auth" in payload["error"] + + +def test_bridge_maps_real_failure_to_502(): + class Broken: + configured = True + + def list_messages(self, *args, **kwargs): + raise OutlookError("boom") + + bridge = OutlookBridge({"client_id": "c"}, client=Broken()) + assert bridge.handle_get("/mail/messages", {})[0] == 502 + + +def test_check_requirements_is_stdlib_only(): + assert OutlookBridge({}).check_requirements() == (True, None) + + +# ---- catalog ---- + +def test_known_infos_include_outlook(): + infos = {info.name: info for info in known_infos()} + assert "outlook" in infos + info = infos["outlook"] + assert info.service == "outlook" + assert info.url_config_var == "outlook_bridge_url" + assert info.auth_header == "X-Semif-Token" + assert info.auth_config_var == "outlook_bridge_token" + + +def test_describe_bridges_covers_outlook(): + text = describe_bridges() + assert "outlook" in text + assert "outlook_bridge_url" in text + assert "Microsoft To Do" in text + + +def test_derived_config_vars_for_outlook(): + derived = derived_config_vars( + {"bridges": {"outlook": {"host": "127.0.0.1", "port": 5231, "token": "o"}}} + ) + assert derived["outlook_bridge_url"] == "http://127.0.0.1:5231" + assert derived["outlook_bridge_token"] == "o" + + +def test_build_bridge_returns_outlook(): + bridge = build_bridge({"bridges": {"outlook": {"client_id": "c"}}}, "outlook") + assert isinstance(bridge, OutlookBridge) + assert bridge.client_id == "c"