diff --git a/bridge/__init__.py b/bridge/__init__.py new file mode 100644 index 0000000..5b49c2f --- /dev/null +++ b/bridge/__init__.py @@ -0,0 +1,7 @@ +"""The outlook pack's bridge: a localhost HTTP surface in front of its service. + +The bridge implementation ships with the pack (see PACKGEN.md, "Authoring a +bridge"); the core imports it by convention from this package. It subclasses +`semif_agent.bridges.base.BridgeService` and declares a `BridgeInfo` catalog +entry that codegen reads via `describe_bridges()`. +""" diff --git a/bridge/outlook.py b/bridge/outlook.py new file mode 100644 index 0000000..1340db2 --- /dev/null +++ b/bridge/outlook.py @@ -0,0 +1,396 @@ +"""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 +`packs/outlook/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 semif_agent.bridges.base import BridgeInfo, BridgeService, checkout_root +from .outlook_client import ( + DEFAULT_SCOPES, + DEFAULT_TENANT, + DEFAULT_TIMEOUT, + OutlookAuthRequired, + OutlookClient, + OutlookError, +) + +#: The default token store is anchored under the checkout's gitignored +#: `.runtime/` tree; the bridge ships in its pack, so it asks the core for the +#: root rather than deriving it from its own (pack-relative) `__file__`. +DEFAULT_TOKEN_PATH = str(checkout_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 packs/outlook/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 packs/outlook/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/bridge/outlook_client.py b/bridge/outlook_client.py new file mode 100644 index 0000000..894f045 --- /dev/null +++ b/bridge/outlook_client.py @@ -0,0 +1,1044 @@ +"""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 `packs/outlook/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 packs/outlook/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]: + # No $select: Graph's To Do endpoints reject OData $select for personal + # (consumer) Microsoft accounts with RequestBroker--ParseUri, while $top + # is accepted. Fetch the full shape and read the fields we need. + items = self._paged("/me/todo/lists", {"$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) + # No $select here either: see list_task_lists (consumer To Do quirk). + items = self._paged( + f"/me/todo/lists/{urllib.parse.quote(list_id)}/tasks", {"$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/bridge/test_outlook_bridge.py b/bridge/test_outlook_bridge.py new file mode 100644 index 0000000..e494804 --- /dev/null +++ b/bridge/test_outlook_bridge.py @@ -0,0 +1,654 @@ +"""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 importlib +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse + +import pytest + +from semif_agent.bridges.registry import ( + build_bridge, + derived_config_vars, + describe_bridges, + known_infos, + load_pack_bridge_module, +) + +_outlook = load_pack_bridge_module("outlook", "outlook") +OutlookBridge = _outlook.OutlookBridge +_outlook_client = importlib.import_module(f"{_outlook.__package__}.outlook_client") +OutlookAuthRequired = _outlook_client.OutlookAuthRequired +OutlookClient = _outlook_client.OutlookClient +OutlookError = _outlook_client.OutlookError +load_token = _outlook_client.load_token +run_device_code_flow = _outlook_client.run_device_code_flow +save_token = _outlook_client.save_token + + +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 packs/outlook/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" diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..89c927a --- /dev/null +++ b/conftest.py @@ -0,0 +1,17 @@ +"""Make the agent checkout importable when running this pack's tests standalone. + +A pack's bridge test imports `semif_agent` (the shared bridge contract and the +discovery registry). The pack lives inside an agent checkout at `packs//`, +so this adds the checkout root to `sys.path` — running the tests through the +agent repo (`pytest tests/test_packs.py`) already provides it, but +`cd packs/ && pytest` needs this. +""" + +import sys +from pathlib import Path + +for _parent in Path(__file__).resolve().parents: + if (_parent / "semif_agent" / "__init__.py").is_file(): + if str(_parent) not in sys.path: + sys.path.insert(0, str(_parent)) + break diff --git a/scripts/outlook-auth.py b/scripts/outlook-auth.py index cac3f49..90838d6 100644 --- a/scripts/outlook-auth.py +++ b/scripts/outlook-auth.py @@ -51,12 +51,31 @@ _AGENT_ROOT = _agent_root() if _AGENT_ROOT is not None and str(_AGENT_ROOT) not in sys.path: sys.path.insert(0, str(_AGENT_ROOT)) -from semif_agent.bridges.outlook_client import ( # noqa: E402 - DEFAULT_TENANT, - OutlookError, - run_device_code_flow, - save_token, -) + +def _load_outlook_client(): + """The pack's own Graph client (`../bridge/outlook_client.py`). + + The bridge ships with the pack, so the script loads its sibling module by + path rather than importing a (removed) core module. + """ + import importlib.util + + bridge_dir = Path(__file__).resolve().parents[1] / "bridge" + spec = importlib.util.spec_from_file_location( + "outlook_client", bridge_dir / "outlook_client.py" + ) + if spec is None or spec.loader is None: + raise ImportError(f"cannot load {bridge_dir / 'outlook_client.py'}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +_outlook_client = _load_outlook_client() +DEFAULT_TENANT = _outlook_client.DEFAULT_TENANT +OutlookError = _outlook_client.OutlookError +run_device_code_flow = _outlook_client.run_device_code_flow +save_token = _outlook_client.save_token DEFAULT_TOKEN_PATH = str((_AGENT_ROOT or Path.cwd()) / ".runtime" / "outlook" / "token.json")