Ship the bridge with the pack (moved from the agent core)

The core now keeps only the shared bridge contract (semif_agent/bridges/base.py)
and the discovery registry (semif_agent/bridges/registry.py); a pack ships its
own bridge under bridge/<name>.py and the registry imports it by convention from
the pack's declared `bridges`. The bridge's hermetic test moves here too and
runs via the agent repo's tests/test_packs.py (or standalone with conftest.py).
This commit is contained in:
gabby committed 2026-10-13 23:52:52 +00:00
1 parent f0396edf16
commit dcc935f6b8
6 files changed
+2143 -6

No files matched your search

+7
View File
@@ -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()`.
"""
+396
View File
@@ -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=<name|id>&count=<n>&search=<text>&unread=<bool> "
"-> 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=<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=<name|id>&start=<iso>&end=<iso> -> "
"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=<name|id> -> 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=<text>&count=<n> -> 200 {\"contacts\": [{id, "
"display_name, given_name, surname, emails, phones, company, "
"job_title}]} — query filters by name/email/company",
"GET /files?path=<dir> -> 200 {\"path\", \"entries\": [{id, name, "
"path, size, modified, is_folder, content_type, web_url}]} — OneDrive "
"folder listing (default root)",
"GET /files/read?path=<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
File diff suppressed because it is too large. Load diff
+654
View File
@@ -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 <alice@example.com>"
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"
+17
View File
@@ -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/<name>/`,
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/<name> && 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
+25 -6
View File
@@ -51,12 +51,31 @@ _AGENT_ROOT = _agent_root()
if _AGENT_ROOT is not None and str(_AGENT_ROOT) not in sys.path: if _AGENT_ROOT is not None and str(_AGENT_ROOT) not in sys.path:
sys.path.insert(0, str(_AGENT_ROOT)) sys.path.insert(0, str(_AGENT_ROOT))
from semif_agent.bridges.outlook_client import ( # noqa: E402
DEFAULT_TENANT, def _load_outlook_client():
OutlookError, """The pack's own Graph client (`../bridge/outlook_client.py`).
run_device_code_flow,
save_token, 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") DEFAULT_TOKEN_PATH = str((_AGENT_ROOT or Path.cwd()) / ".runtime" / "outlook" / "token.json")