bridges: add an Outlook (Microsoft Graph) bridge + seeds
A standalone Outlook bridge in front of Microsoft Graph — mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files — so skill bodies never speak Graph or OAuth directly. Stdlib-only, no daemon (like Nextcloud), and registered in CATALOG so describe_bridges() feeds it into every codegen prompt. Authorization is the OAuth2 device code flow: scripts/outlook-auth.py runs it once and stores the refresh token 0600 under .runtime/outlook/token.json; outlook_client.py refreshes on expiry/401, follows @odata.nextLink paging, and backs off on 429/Retry-After. An unauthenticated route is a 503 (run the helper), a real Graph failure a 502. Seven seeds/outlook/* starter skills (next_message, send_message — compose via the LLM bridge and confirm before sending — next_event, create_event, create_task, list_contacts, list_files), a bridges.outlook config block, and tests/test_outlook_bridge.py driving the real client over a loopback server faking the token endpoint and Graph shapes.
This commit is contained in:
1 parent
b7d405454a
commit
e434b9fbe5
37 files changed
+4505
-7
No files matched your search
@@ -263,6 +263,13 @@ bridges/ standalone third-party API bridges (SimpleX, the LLM bridge,
|
||||
DAV/OCS; no service daemon (stdlib-only), connection from
|
||||
`bridges.nextcloud` with a fallback to the top-level
|
||||
`nextcloud_*` values the calendar seeds use.
|
||||
outlook.py + outlook_client.py: OutlookBridge — the user's
|
||||
Microsoft account (Outlook / Microsoft 365) over Microsoft Graph:
|
||||
mail, calendar events, Microsoft To Do tasks, contacts, and
|
||||
OneDrive files, plus the OAuth2 device-code + refresh flow. No
|
||||
daemon (stdlib-only `urllib`); tokens stored under
|
||||
`.runtime/outlook/token.json` and seeded once with
|
||||
`scripts/outlook-auth.py`; connection from `bridges.outlook`.
|
||||
registry.py: CATALOG, describe_bridges() (catalog injected
|
||||
into the codegen prompts), run_bridges() (threads the scheduler's
|
||||
`llm` client into the LLM bridge). Run with `python -m
|
||||
@@ -1359,6 +1366,36 @@ CLI, unit tests (24) + integration tests (2).
|
||||
addressbook defaults resolve from config when a request names none and the
|
||||
account has several. `tests/test_nextcloud_bridge.py` drives the real client
|
||||
over a loopback `http.server` faking Nextcloud's DAV/OCS shapes.
|
||||
- **Outlook bridge** (`bridges/outlook.py` + `bridges/outlook_client.py`).
|
||||
Wraps the user's Microsoft account — Outlook / Microsoft 365 mail, calendar
|
||||
events, Microsoft To Do tasks, contacts, and OneDrive files — behind one
|
||||
uniform JSON surface over **Microsoft Graph**, so a body never speaks Graph or
|
||||
OAuth directly. Like Nextcloud it has **no service daemon** (Graph is plain
|
||||
HTTPS) and is stdlib-only (`urllib` + `json` + `ssl` + `base64`), so
|
||||
`check_requirements` is always `(True, None)` and it starts instantly inside
|
||||
`semif-bridge.service`. Authorization is the OAuth2 **device code flow** (a
|
||||
public client, no secret): `scripts/outlook-auth.py` runs it once and stores
|
||||
the access + refresh tokens 0600 under the checkout's
|
||||
`.runtime/outlook/token.json` (override with `bridges.outlook.token_path`); the
|
||||
client refreshes on expiry/401. The bridge starts without a token — an
|
||||
unauthenticated route returns `503` telling the operator to run the helper
|
||||
(`OutlookAuthRequired`), a real Graph failure is `502` (`OutlookError`), and a
|
||||
missing `client_id` is `503`. The connection is configured in
|
||||
`bridges.outlook` (`client_id`, `tenant` default `common`,
|
||||
`default_calendar`/`default_task_list`/`default_mail_folder`/`default_timezone`,
|
||||
`verify_tls`/`timeout`); it also accepts `graph`/`login` base URLs (a test
|
||||
seam/defaulting to the real hosts). Bodies reach it via the derived
|
||||
`outlook_bridge_url` (+ optional `outlook_bridge_token`). Routes (reads `GET`,
|
||||
mutations `POST`): `/user`, mail (`/mail/folders`, `/mail/messages` list +
|
||||
`/mail/messages/get`, `POST /mail/send` immediate + `/mail/draft`), calendar
|
||||
(`/calendars`, `/calendars/events` via `calendarView` so recurrences expand,
|
||||
`POST /calendars/events` + `/update` + `/delete`), To Do (`/tasklists`,
|
||||
`/tasks`, `POST /tasks` + `/update` + `/complete` + `/delete`), contacts
|
||||
(`/contacts` search), and OneDrive (`/files` list, `/files/read`
|
||||
text-or-base64, `POST /files/write`). Graph's `@odata.nextLink` paging and
|
||||
`429`/`Retry-After` backoff are handled in the client.
|
||||
`tests/test_outlook_bridge.py` drives the real client over a loopback
|
||||
`http.server` faking the token endpoint and Graph shapes.
|
||||
|
||||
## Bridge backlog (one session per item)
|
||||
|
||||
@@ -1402,6 +1439,15 @@ The bridge read path (`simplex.next_message`) and contact-link lookup
|
||||
`bridges/nextcloud_client.py`): files/calendars/tasks/contacts/notes over one
|
||||
JSON surface, no daemon, connection from `bridges.nextcloud` with a top-level
|
||||
`nextcloud_*` fallback. Future bridges follow the same shape.
|
||||
- [x] **6. Outlook / Microsoft Graph bridge** (`bridges/outlook.py` +
|
||||
`bridges/outlook_client.py`). Shipped: the `OutlookBridge` exposes mail,
|
||||
calendar, Microsoft To Do, contacts, and OneDrive over one JSON surface in
|
||||
front of Graph; OAuth2 device-code + refresh (`scripts/outlook-auth.py`, tokens
|
||||
under `.runtime/outlook/token.json`); seven `seeds/outlook/*` skills
|
||||
(`next_message`, `send_message` confirm-gated, `next_event`, `create_event`,
|
||||
`create_task`, `list_contacts`, `list_files`). Deferred: writing/reusing
|
||||
Outlook app-registration guidance in the docs, and a mail-send seed that
|
||||
attaches files.
|
||||
|
||||
### Code principles
|
||||
- **Contain installation artifacts in the repo.** Everything a machine installs
|
||||
|
||||
@@ -515,14 +515,16 @@ Key blocks:
|
||||
| `bridges.simplex` | forwarding bridge: host/port/token/ws_url |
|
||||
| `bridges.llm` | LLM bridge: host/port/token (model comes from `llm`) |
|
||||
| `bridges.nextcloud` | Nextcloud bridge: host/port/token + connection (url/username/app_password/defaults) |
|
||||
| `bridges.outlook` | Outlook bridge: host/port/token + Microsoft Graph connection (client_id/tenant/defaults) |
|
||||
| `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) |
|
||||
| `dashboard` | bind host/port |
|
||||
|
||||
Bridge skills read `simplex_bridge_url` / `llm_bridge_url` / `nextcloud_bridge_url`
|
||||
(+ their `_token`) from `ctx.config`; each is **derived** at startup from its
|
||||
`bridges.<name>` host/port/token, so there is no duplicate top-level key to keep
|
||||
in sync. A bridge with no block (or no port) leaves the variable unresolved and
|
||||
the operator is asked for it.
|
||||
Bridge skills read `simplex_bridge_url` / `llm_bridge_url` /
|
||||
`nextcloud_bridge_url` / `outlook_bridge_url` (+ their `_token`) from
|
||||
`ctx.config`; each is **derived** at startup from its `bridges.<name>`
|
||||
host/port/token, so there is no duplicate top-level key to keep in sync. A bridge
|
||||
with no block (or no port) leaves the variable unresolved and the operator is
|
||||
asked for it.
|
||||
|
||||
`llm.model` and `codegen.model` are **required** (no default): set each to a
|
||||
model its endpoint serves. A missing model fails fast at startup with a clear
|
||||
@@ -774,6 +776,46 @@ or a bad reply) is `502` — never a fabricated success. Calendar and addressboo
|
||||
defaults resolve from `bridges.nextcloud` when a request names none and the
|
||||
account has several.
|
||||
|
||||
The **Outlook bridge** (`semif_agent/bridges/outlook.py`) wraps the user's
|
||||
Microsoft account (Outlook / Microsoft 365) through **Microsoft Graph**: mail,
|
||||
calendar events, Microsoft To Do tasks, contacts, and OneDrive files. Like
|
||||
Nextcloud it has **no service daemon** (Graph is plain HTTPS) and is stdlib-only,
|
||||
so it starts instantly in the same `semif-bridge` process. Authorization is the
|
||||
OAuth2 **device code flow**: register an Entra ID public-client app, put its
|
||||
`client_id` in `bridges.outlook`, and run `scripts/outlook-auth.py` once — the
|
||||
tokens are stored (0600) under the checkout's `.runtime/outlook/token.json` and
|
||||
refreshed automatically. The bridge starts without a token; an unauthenticated
|
||||
route returns `503` telling the operator to run that helper. Skills call it at the
|
||||
address derived from `bridges.outlook` (`outlook_bridge_url`, + optional
|
||||
`outlook_bridge_token`). Its HTTP surface:
|
||||
|
||||
```
|
||||
GET /health
|
||||
GET /user # the signed-in account
|
||||
GET /mail/folders
|
||||
GET /mail/messages?folder=<name|id>&count=<n>&search=<text>&unread=<bool>
|
||||
GET /mail/messages/get?id=<id>
|
||||
POST /mail/send {"to":[...],"cc"?,"subject"?,"body"?,"content_type"?}
|
||||
POST /mail/draft {"to"?,"cc"?,"subject"?,"body"?,"content_type"?}
|
||||
GET /calendars
|
||||
GET /calendars/events?calendar=<name|id>&start=<iso>&end=<iso> # recurrences expand
|
||||
POST /calendars/events | /calendars/events/update | /calendars/events/delete
|
||||
GET /tasklists # Microsoft To Do
|
||||
GET /tasks?list=<name|id>
|
||||
POST /tasks | /tasks/update | /tasks/complete | /tasks/delete
|
||||
GET /contacts?query=<text>&count=<n>
|
||||
GET /files?path=<dir> # OneDrive
|
||||
GET /files/read?path=<path> # text, or base64 for binary
|
||||
POST /files/write {"path","content","encoding"?,"overwrite"?}
|
||||
```
|
||||
|
||||
A missing `client_id` or an unauthorized bridge is `503`; a real Graph failure
|
||||
(transport, HTTP error, or a bad reply) is `502` — never a fabricated success.
|
||||
Seven `seeds/outlook/*` skills ship (`next_message`, `send_message`,
|
||||
`next_event`, `create_event`, `create_task`, `list_contacts`, `list_files`);
|
||||
`send_message` composes the message through the LLM bridge and asks for
|
||||
confirmation before it sends.
|
||||
|
||||
### Dream report
|
||||
|
||||
```sh
|
||||
|
||||
@@ -162,6 +162,21 @@
|
||||
"default_addressbook": "",
|
||||
"verify_tls": true,
|
||||
"timeout": 30
|
||||
},
|
||||
"outlook": {
|
||||
"_comment": "Outlook bridge: the user's Microsoft account (Outlook / Microsoft 365) through Microsoft Graph — mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files — over one uniform local JSON API, so skill bodies never speak Graph or OAuth. No service daemon and no extra dependency (Graph is plain HTTPS); it runs inside the same `semif-bridge` process as the other enabled bridges. Authorization is the OAuth2 device code flow: register an Entra ID public-client app, put its `client_id` here, run `scripts/outlook-auth.py` once, and the tokens are stored (0600) under `.runtime/outlook/token.json` (override with `token_path`). `tenant` is usually `common` (personal + work accounts). `default_calendar`/`default_task_list`/`default_mail_folder` are used when a request names none; `default_timezone` (IANA name) labels created events/tasks whose start has no offset. `verify_tls` false skips certificate verification. Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set. Disabled by default because it needs a client id + an authorization run first.",
|
||||
"enabled": false,
|
||||
"host": "127.0.0.1",
|
||||
"port": 5231,
|
||||
"token": "",
|
||||
"client_id": "",
|
||||
"tenant": "common",
|
||||
"default_calendar": "",
|
||||
"default_task_list": "",
|
||||
"default_mail_folder": "inbox",
|
||||
"default_timezone": "UTC",
|
||||
"verify_tls": true,
|
||||
"timeout": 30
|
||||
}
|
||||
},
|
||||
"gateway": {
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Authorize the Outlook bridge with Microsoft (OAuth2 device code flow).
|
||||
|
||||
The bridge reads the user's Microsoft account through Microsoft Graph; that
|
||||
needs an access token, obtained once here with the **device code flow** (a public
|
||||
client, no secret):
|
||||
|
||||
1. register an Entra ID app (see below) and put its client id in
|
||||
`config.json` under `bridges.outlook.client_id`;
|
||||
2. run this script;
|
||||
3. open the printed URL on any device, enter the printed code, and sign in;
|
||||
4. the resulting tokens are saved (0600) to `.runtime/outlook/token.json`,
|
||||
which the bridge loads and refreshes automatically.
|
||||
|
||||
One-time app registration (Entra ID / Azure AD):
|
||||
|
||||
- "App registrations" -> "New registration".
|
||||
- Supported account types: include personal Microsoft accounts if the user
|
||||
has an @outlook.com/@hotmail.com account (e.g. "Accounts in any
|
||||
organizational directory and personal Microsoft accounts").
|
||||
- Authentication -> "Allow public client flows" = Yes (no redirect URI is
|
||||
needed for device code).
|
||||
- No API permissions need adding by hand: the script requests the delegated
|
||||
scopes it needs and the user consents during sign-in.
|
||||
|
||||
Usage (from the checkout):
|
||||
|
||||
.runtime/venv/bin/python scripts/outlook-auth.py [--config config.json]
|
||||
[--client-id ID]
|
||||
[--tenant common]
|
||||
[--token-path PATH]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
from semif_agent.bridges.outlook_client import ( # noqa: E402
|
||||
DEFAULT_TENANT,
|
||||
OutlookError,
|
||||
run_device_code_flow,
|
||||
save_token,
|
||||
)
|
||||
|
||||
DEFAULT_TOKEN_PATH = str(REPO_ROOT / ".runtime" / "outlook" / "token.json")
|
||||
|
||||
|
||||
def _block(config_path: str) -> dict:
|
||||
try:
|
||||
with open(config_path, encoding="utf-8") as handle:
|
||||
config = json.load(handle)
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
block = (config.get("bridges", {}) or {}).get("outlook", {}) or {}
|
||||
return block if isinstance(block, dict) else {}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", default="config.json")
|
||||
parser.add_argument("--client-id", default=None, help="override bridges.outlook.client_id")
|
||||
parser.add_argument("--tenant", default=None, help="override bridges.outlook.tenant (default common)")
|
||||
parser.add_argument("--token-path", default=None, help="where to save the tokens")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
block = _block(args.config)
|
||||
client_id = str(args.client_id or block.get("client_id") or "").strip()
|
||||
tenant = str(args.tenant or block.get("tenant") or DEFAULT_TENANT).strip() or DEFAULT_TENANT
|
||||
token_path = str(args.token_path or block.get("token_path") or DEFAULT_TOKEN_PATH)
|
||||
scopes = block.get("scopes") or None
|
||||
|
||||
if not client_id:
|
||||
print(
|
||||
"no Microsoft client id configured: set bridges.outlook.client_id in "
|
||||
f"{args.config} (or pass --client-id)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
|
||||
try:
|
||||
token = run_device_code_flow(client_id, tenant, scopes)
|
||||
except OutlookError as exc:
|
||||
print(f"authorization failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
except KeyboardInterrupt:
|
||||
print("\ncancelled", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
save_token(token_path, token)
|
||||
print(f"saved Outlook authorization to {token_path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Create an Outlook calendar event from a request such as \"add dentist appointment on 2026-11-10 at 2pm\"."
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
"""Create an event on the user's Outlook calendar from a request.
|
||||
|
||||
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
|
||||
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
|
||||
speaks Graph or OAuth directly. `act` derives the event's title, date, time and
|
||||
duration from `request.text`; missing pieces are asked one at a time and the
|
||||
answers are stashed in `request.meta` (act re-runs from the top after a
|
||||
`needs_input` pause, so a question is never asked twice). The event is created
|
||||
with a real `POST /calendars/events` and the real outcome reported. The user's
|
||||
IANA timezone (the top-level `timezone` config value, when set) labels the start.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime, time, timedelta
|
||||
|
||||
from semif_agent.skills import ActionResult
|
||||
from semif_agent.timers import local_now
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "outlook",
|
||||
"transport": "http",
|
||||
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
|
||||
}
|
||||
|
||||
CONTRACT = {
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
}
|
||||
|
||||
TIMEOUT_SECONDS = 30
|
||||
DEFAULT_DURATION_MINUTES = 60
|
||||
|
||||
_WEEKDAYS = {
|
||||
"monday": 0,
|
||||
"mon": 0,
|
||||
"tuesday": 1,
|
||||
"tue": 1,
|
||||
"tues": 1,
|
||||
"wednesday": 2,
|
||||
"wed": 2,
|
||||
"thursday": 3,
|
||||
"thu": 3,
|
||||
"thur": 3,
|
||||
"thurs": 3,
|
||||
"friday": 4,
|
||||
"fri": 4,
|
||||
"saturday": 5,
|
||||
"sat": 5,
|
||||
"sunday": 6,
|
||||
"sun": 6,
|
||||
}
|
||||
_WEEKDAY_RE = re.compile(
|
||||
r"\b(" + "|".join(sorted(_WEEKDAYS, key=len, reverse=True)) + r")\b", re.I
|
||||
)
|
||||
_MONTHS = {
|
||||
"jan": 1,
|
||||
"feb": 2,
|
||||
"mar": 3,
|
||||
"apr": 4,
|
||||
"may": 5,
|
||||
"jun": 6,
|
||||
"jul": 7,
|
||||
"aug": 8,
|
||||
"sep": 9,
|
||||
"oct": 10,
|
||||
"nov": 11,
|
||||
"dec": 12,
|
||||
}
|
||||
_MONTH_ALT = (
|
||||
r"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?"
|
||||
r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"
|
||||
)
|
||||
_COMMAND_WORDS = re.compile(
|
||||
r"\b(add|create|new|put|make|set\s*up|set|schedule|book|"
|
||||
r"i\s+need\s+to|i\s+have\s+to|calendar|"
|
||||
r"for|on|at|from|my|the|a|an|to)\b",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
class OutlookBridgeError(Exception):
|
||||
"""A real failure talking to the local Outlook bridge."""
|
||||
|
||||
|
||||
def _now(ctx):
|
||||
return local_now(ctx.config)
|
||||
|
||||
|
||||
def _post(ctx, path, payload):
|
||||
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
|
||||
if not base:
|
||||
raise OutlookBridgeError("outlook_bridge_url is not configured")
|
||||
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
|
||||
data = json.dumps(payload).encode("utf-8")
|
||||
headers = {"Content-Type": "application/json", "Accept": "application/json"}
|
||||
if token:
|
||||
headers["X-Semif-Token"] = token
|
||||
http_request = urllib.request.Request(base + path, data=data, method="POST", headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
|
||||
return json.loads(response.read().decode("utf-8") or "{}")
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
||||
raise OutlookBridgeError(f"POST {path}: HTTP {exc.code} {detail}") from exc
|
||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
||||
raise OutlookBridgeError(f"POST {path}: {exc}") from exc
|
||||
|
||||
|
||||
def _month_number(token):
|
||||
return _MONTHS.get(token.lower()[:3])
|
||||
|
||||
|
||||
def _resolve_month_day(month, day, year, now):
|
||||
if not (month and 1 <= day <= 31):
|
||||
return None
|
||||
given_year = year is not None
|
||||
year = year or now.year
|
||||
try:
|
||||
candidate = datetime(year, month, day).date()
|
||||
except ValueError:
|
||||
return None
|
||||
if not given_year and candidate < now.date():
|
||||
try:
|
||||
candidate = datetime(year + 1, month, day).date()
|
||||
except ValueError:
|
||||
return None
|
||||
return candidate
|
||||
|
||||
|
||||
def _parse_when(text, now):
|
||||
"""`{"date","date_span","time","time_span","all_day","duration_minutes","from_weekday"}`."""
|
||||
text = text or ""
|
||||
result = {
|
||||
"date": None,
|
||||
"date_span": None,
|
||||
"time": None,
|
||||
"time_span": None,
|
||||
"all_day": False,
|
||||
"duration_minutes": None,
|
||||
"from_weekday": False,
|
||||
}
|
||||
|
||||
match = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", text, re.I)
|
||||
if match:
|
||||
result["all_day"] = True
|
||||
|
||||
match = re.search(r"\bfor\s+(\d+(?:\.\d+)?)\s*(hours?|hrs?|h)\b", text, re.I)
|
||||
if match:
|
||||
result["duration_minutes"] = int(round(float(match.group(1)) * 60))
|
||||
else:
|
||||
match = re.search(r"\bfor\s+(\d+)\s*(minutes?|mins?|m)\b", text, re.I)
|
||||
if match:
|
||||
result["duration_minutes"] = int(match.group(1))
|
||||
else:
|
||||
for phrase, minutes in (
|
||||
(r"\bfor\s+half\s+an?\s+hour\b", 30),
|
||||
(r"\bfor\s+an?\s+hour\b", 60),
|
||||
):
|
||||
match = re.search(phrase, text, re.I)
|
||||
if match:
|
||||
result["duration_minutes"] = minutes
|
||||
break
|
||||
|
||||
date = None
|
||||
span = None
|
||||
match = re.search(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", text)
|
||||
if match:
|
||||
try:
|
||||
date = datetime(int(match.group(1)), int(match.group(2)), int(match.group(3))).date()
|
||||
span = match.span()
|
||||
except ValueError:
|
||||
date = None
|
||||
if date is None:
|
||||
match = re.search(
|
||||
r"\b(" + _MONTH_ALT + r")\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?\b", text, re.I
|
||||
)
|
||||
if match:
|
||||
month = _month_number(match.group(1))
|
||||
year = int(match.group(3)) if match.group(3) else None
|
||||
date = _resolve_month_day(month, int(match.group(2)), year, now)
|
||||
span = match.span() if date else None
|
||||
if date is None:
|
||||
match = re.search(
|
||||
r"\b(\d{1,2})(?:st|nd|rd|th)?\s+(?:of\s+)?(" + _MONTH_ALT + r")(?:,?\s*(\d{4}))?\b",
|
||||
text,
|
||||
re.I,
|
||||
)
|
||||
if match:
|
||||
month = _month_number(match.group(2))
|
||||
year = int(match.group(3)) if match.group(3) else None
|
||||
date = _resolve_month_day(month, int(match.group(1)), year, now)
|
||||
span = match.span() if date else None
|
||||
if date is None:
|
||||
match = re.search(r"\b(today|tonight|tomorrow|tmrw|tomorow|next\s+week)\b", text, re.I)
|
||||
if match:
|
||||
word = re.sub(r"\s+", " ", match.group(1).lower())
|
||||
if word in ("today", "tonight"):
|
||||
date = now.date()
|
||||
elif word in ("tomorrow", "tmrw", "tomorow"):
|
||||
date = now.date() + timedelta(days=1)
|
||||
else:
|
||||
date = now.date() + timedelta(days=7)
|
||||
span = match.span()
|
||||
if date is None:
|
||||
match = _WEEKDAY_RE.search(text)
|
||||
if match:
|
||||
target = _WEEKDAYS[match.group(1).lower()]
|
||||
date = now.date() + timedelta(days=(target - now.date().weekday()) % 7)
|
||||
prefix = text[max(0, match.start() - 6) : match.start()]
|
||||
if re.search(r"\bnext\s*$", prefix, re.I):
|
||||
date += timedelta(days=7)
|
||||
result["from_weekday"] = True
|
||||
span = match.span()
|
||||
|
||||
parsed_time = None
|
||||
time_span = None
|
||||
match = re.search(r"\bnoon\b", text, re.I)
|
||||
if match:
|
||||
parsed_time = time(12, 0)
|
||||
time_span = match.span()
|
||||
elif re.search(r"\bmidnight\b", text, re.I):
|
||||
parsed_time = time(0, 0)
|
||||
time_span = re.search(r"\bmidnight\b", text, re.I).span()
|
||||
else:
|
||||
match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I)
|
||||
if match:
|
||||
hour = int(match.group(1)) % 12
|
||||
minute = int(match.group(2) or 0)
|
||||
if match.group(3).lower() == "p":
|
||||
hour += 12
|
||||
if hour < 24 and minute < 60:
|
||||
parsed_time = time(hour, minute)
|
||||
time_span = match.span()
|
||||
else:
|
||||
match = re.search(r"\b(\d{1,2}):(\d{2})\b", text)
|
||||
if match:
|
||||
hour, minute = int(match.group(1)), int(match.group(2))
|
||||
if hour < 24 and minute < 60:
|
||||
parsed_time = time(hour, minute)
|
||||
time_span = match.span()
|
||||
|
||||
result["date"] = date
|
||||
result["date_span"] = span
|
||||
result["time"] = parsed_time
|
||||
result["time_span"] = time_span
|
||||
return result
|
||||
|
||||
|
||||
def _title(text, parsed):
|
||||
remove = [parsed.get("date_span"), parsed.get("time_span")]
|
||||
out = text
|
||||
for span in sorted((s for s in remove if s), key=lambda s: s[0], reverse=True):
|
||||
out = out[: span[0]] + " " + out[span[1] :]
|
||||
phrase = re.search(r"\ball[\s-]?day\b|\bwhole\s+day\b", out, re.I)
|
||||
if phrase:
|
||||
out = out[: phrase.start()] + " " + out[phrase.end() :]
|
||||
cleaned = re.sub(r"\s+", " ", _COMMAND_WORDS.sub(" ", out)).strip(" .,:;-")
|
||||
return cleaned
|
||||
|
||||
|
||||
def _ask(request, field, question):
|
||||
request.meta["create_event_awaiting"] = field
|
||||
return ActionResult(action_log=f"waiting for {field}", new_state=request.text, needs_input=question)
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
answers = request.meta.setdefault("create_event_answers", {})
|
||||
awaiting = request.meta.get("create_event_awaiting")
|
||||
if request.user_input is not None and awaiting:
|
||||
answers[awaiting] = request.user_input.strip()
|
||||
request.meta.pop("create_event_awaiting", None)
|
||||
|
||||
now = _now(ctx)
|
||||
parsed = _parse_when(request.text, now)
|
||||
title = _title(request.text, parsed)
|
||||
|
||||
if answers.get("title"):
|
||||
title = answers["title"].strip()
|
||||
for key in ("date", "time"):
|
||||
if answers.get(key):
|
||||
extra = _parse_when(answers[key], now)
|
||||
if extra["date"] is not None:
|
||||
parsed["date"] = extra["date"]
|
||||
if extra["time"] is not None:
|
||||
parsed["time"] = extra["time"]
|
||||
if extra["all_day"]:
|
||||
parsed["all_day"] = True
|
||||
if extra["duration_minutes"]:
|
||||
parsed["duration_minutes"] = extra["duration_minutes"]
|
||||
|
||||
if not title:
|
||||
return _ask(request, "title", "What should I call the event?")
|
||||
if parsed["date"] is None:
|
||||
return _ask(request, "date", f"What day should I schedule {title!r}?")
|
||||
if not parsed["all_day"] and parsed["time"] is None:
|
||||
return _ask(request, "time", f"What time should {title!r} start? (or say 'all day')")
|
||||
|
||||
all_day = bool(parsed["all_day"])
|
||||
if all_day:
|
||||
start = datetime.combine(parsed["date"], time(0, 0))
|
||||
else:
|
||||
start = datetime.combine(parsed["date"], parsed["time"])
|
||||
if start <= now.replace(tzinfo=None) and parsed.get("from_weekday"):
|
||||
start += timedelta(days=7)
|
||||
|
||||
timezone_name = str(ctx.config.get("timezone", "") or "").strip()
|
||||
payload = {
|
||||
"subject": title,
|
||||
"start": start.strftime("%Y-%m-%dT%H:%M:%S"),
|
||||
"all_day": all_day,
|
||||
}
|
||||
if not all_day:
|
||||
duration = timedelta(minutes=parsed["duration_minutes"] or DEFAULT_DURATION_MINUTES)
|
||||
payload["end"] = (start + duration).strftime("%Y-%m-%dT%H:%M:%S")
|
||||
if timezone_name:
|
||||
payload["timezone"] = timezone_name
|
||||
|
||||
try:
|
||||
data = _post(ctx, "/calendars/events", payload)
|
||||
except OutlookBridgeError as exc:
|
||||
return ActionResult(action_log=str(exc), new_state=request.text)
|
||||
|
||||
if all_day:
|
||||
when_text = f"{start.date().isoformat()} (all day)"
|
||||
else:
|
||||
when_text = start.strftime("%Y-%m-%d %H:%M")
|
||||
report = f"Created {title!r} on {when_text}."
|
||||
return ActionResult(action_log=report, new_state=report)
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Hermetic mechanics test for outlook.create_event.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the local Outlook bridge's `/calendars/events` route and records
|
||||
the payload. This proves the body derives the title/date/time, asks for a missing
|
||||
piece and resumes, creates the event with a real POST, and fails honestly when
|
||||
the bridge errors. It does NOT prove the live integration — only a real run
|
||||
against the user's Microsoft account does.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
import skill
|
||||
|
||||
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
|
||||
skill._now = lambda ctx: FIXED_NOW
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
def call(self, decision): # pragma: no cover - this skill makes no decision
|
||||
raise AssertionError("outlook.create_event must not ask the decision engine")
|
||||
|
||||
|
||||
class BridgeHandler(BaseHTTPRequestHandler):
|
||||
status = 200
|
||||
posts = []
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
body = self.rfile.read(length) if length else b""
|
||||
if self.path != "/calendars/events":
|
||||
self._send({"error": "not found"}, 404)
|
||||
return
|
||||
self.posts.append(json.loads(body.decode("utf-8")))
|
||||
if self.status != 200:
|
||||
self._send({"error": "boom"}, self.status)
|
||||
return
|
||||
self._send({"ok": True, "id": "e1", "subject": self.posts[-1].get("subject")}, 201)
|
||||
|
||||
def _send(self, payload, status):
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def start_server(status=200):
|
||||
handler = type("Handler", (BridgeHandler,), {"status": status, "posts": []})
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def context(url, tz=""):
|
||||
config = {"outlook_bridge_url": url, "outlook_bridge_token": ""}
|
||||
if tz:
|
||||
config["timezone"] = tz
|
||||
return ActionContext(engine=FakeEngine(), config=config)
|
||||
|
||||
|
||||
def test_explicit_datetime():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
action = skill.act(context(url), Request("add dentist appointment on 2026-11-10 at 2pm"))
|
||||
assert action.needs_input is None, action.needs_input
|
||||
post = handler.posts[0]
|
||||
assert post["subject"] == "dentist appointment", post
|
||||
assert post["start"] == "2026-11-10T14:00:00", post
|
||||
assert post["end"] == "2026-11-10T15:00:00", post
|
||||
assert post["all_day"] is False, post
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_timezone_is_sent():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
skill.act(
|
||||
context(url, tz="America/Chicago"),
|
||||
Request("add lunch on 2026-11-10 at noon"),
|
||||
)
|
||||
assert handler.posts[0]["timezone"] == "America/Chicago", handler.posts[0]
|
||||
print(handler.posts[0])
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_all_day_event():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
skill.act(context(url), Request("add conference all day on 2026-11-10"))
|
||||
post = handler.posts[0]
|
||||
assert post["all_day"] is True, post
|
||||
assert "end" not in post, post
|
||||
assert post["subject"] == "conference", post
|
||||
print(post)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_missing_time_asks_then_creates():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
ctx = context(url)
|
||||
request = Request("add dentist appointment on 2026-11-10")
|
||||
action = skill.act(ctx, request)
|
||||
assert action.needs_input, "a missing start time must be asked"
|
||||
assert handler.posts == []
|
||||
request.user_input = "2pm"
|
||||
action = skill.act(ctx, request)
|
||||
assert action.needs_input is None, action.needs_input
|
||||
assert handler.posts[0]["start"] == "2026-11-10T14:00:00", handler.posts[0]
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_bridge_error_is_reported_honestly():
|
||||
server, _handler, url = start_server(status=502)
|
||||
try:
|
||||
request = Request("add dentist appointment on 2026-11-10 at 2pm")
|
||||
action = skill.act(context(url), request)
|
||||
assert "502" in action.action_log, action.action_log
|
||||
assert action.new_state == request.text, "a failed create must not fake a result"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def main():
|
||||
test_explicit_datetime()
|
||||
test_timezone_is_sent()
|
||||
test_all_day_event()
|
||||
test_missing_time_asks_then_creates()
|
||||
test_bridge_error_is_reported_honestly()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Add a task to the user's Microsoft To Do list, e.g. \"remind me to call the dentist tomorrow\"."
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Add a task to the user's Microsoft To Do list.
|
||||
|
||||
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
|
||||
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
|
||||
speaks Graph or OAuth directly. `act` derives the task title and an optional due
|
||||
date from `request.text`; a missing title is asked one at a time and the answer
|
||||
is stashed in `request.meta` (act re-runs from the top after a `needs_input`
|
||||
pause, so a question is never asked twice). The task is created with a real
|
||||
`POST /tasks` and the real outcome reported.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from semif_agent.skills import ActionResult
|
||||
from semif_agent.timers import local_now
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "outlook",
|
||||
"transport": "http",
|
||||
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
|
||||
}
|
||||
|
||||
CONTRACT = {
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
}
|
||||
|
||||
TIMEOUT_SECONDS = 30
|
||||
|
||||
_WEEKDAYS = {
|
||||
"monday": 0,
|
||||
"mon": 0,
|
||||
"tuesday": 1,
|
||||
"tue": 1,
|
||||
"tues": 1,
|
||||
"wednesday": 2,
|
||||
"wed": 2,
|
||||
"thursday": 3,
|
||||
"thu": 3,
|
||||
"thur": 3,
|
||||
"thurs": 3,
|
||||
"friday": 4,
|
||||
"fri": 4,
|
||||
"saturday": 5,
|
||||
"sat": 5,
|
||||
"sunday": 6,
|
||||
"sun": 6,
|
||||
}
|
||||
_WEEKDAY_RE = re.compile(
|
||||
r"\b(" + "|".join(sorted(_WEEKDAYS, key=len, reverse=True)) + r")\b", re.I
|
||||
)
|
||||
_MONTHS = {
|
||||
"jan": 1,
|
||||
"feb": 2,
|
||||
"mar": 3,
|
||||
"apr": 4,
|
||||
"may": 5,
|
||||
"jun": 6,
|
||||
"jul": 7,
|
||||
"aug": 8,
|
||||
"sep": 9,
|
||||
"oct": 10,
|
||||
"nov": 11,
|
||||
"dec": 12,
|
||||
}
|
||||
_MONTH_ALT = (
|
||||
r"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?"
|
||||
r"|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"
|
||||
)
|
||||
_COMMAND_WORDS = re.compile(
|
||||
r"\b(add|create|new|put|make|set\s*up|set|schedule|remind\s+me(?:\s+to)?|"
|
||||
r"i\s+need\s+to|i\s+have\s+to|tasks|task|to-?dos|to-?do|todo|lists|list|for|by|due|on|"
|
||||
r"my|the|a|an|to)\b",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
class OutlookBridgeError(Exception):
|
||||
"""A real failure talking to the local Outlook bridge."""
|
||||
|
||||
|
||||
def _now(ctx):
|
||||
return local_now(ctx.config)
|
||||
|
||||
|
||||
def _post(ctx, path, payload):
|
||||
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
|
||||
if not base:
|
||||
raise OutlookBridgeError("outlook_bridge_url is not configured")
|
||||
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
|
||||
data = json.dumps(payload).encode("utf-8")
|
||||
headers = {"Content-Type": "application/json", "Accept": "application/json"}
|
||||
if token:
|
||||
headers["X-Semif-Token"] = token
|
||||
http_request = urllib.request.Request(base + path, data=data, method="POST", headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
|
||||
return json.loads(response.read().decode("utf-8") or "{}")
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
||||
raise OutlookBridgeError(f"POST {path}: HTTP {exc.code} {detail}") from exc
|
||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
||||
raise OutlookBridgeError(f"POST {path}: {exc}") from exc
|
||||
|
||||
|
||||
def _match_due(text, now):
|
||||
"""Return `(due_date | None, matched_span | None)` for the due date."""
|
||||
match = re.search(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", text)
|
||||
if match:
|
||||
try:
|
||||
return datetime(int(match.group(1)), int(match.group(2)), int(match.group(3))).date(), match.span()
|
||||
except ValueError:
|
||||
return None, None
|
||||
match = re.search(r"\b(" + _MONTH_ALT + r")\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?\b", text, re.I)
|
||||
if match:
|
||||
month = _MONTHS.get(match.group(1).lower()[:3])
|
||||
year = int(match.group(3)) if match.group(3) else now.year
|
||||
try:
|
||||
candidate = datetime(year, month, int(match.group(2))).date()
|
||||
except (TypeError, ValueError):
|
||||
return None, None
|
||||
if not match.group(3) and candidate < now.date():
|
||||
candidate = candidate.replace(year=year + 1)
|
||||
return candidate, match.span()
|
||||
match = re.search(r"\b(today|tonight|tomorrow|tmrw|next\s+week)\b", text, re.I)
|
||||
if match:
|
||||
word = re.sub(r"\s+", " ", match.group(1).lower())
|
||||
if word in ("today", "tonight"):
|
||||
return now.date(), match.span()
|
||||
if word in ("tomorrow", "tmrw"):
|
||||
return now.date() + timedelta(days=1), match.span()
|
||||
return now.date() + timedelta(days=7), match.span()
|
||||
match = _WEEKDAY_RE.search(text)
|
||||
if match:
|
||||
target = _WEEKDAYS[match.group(1).lower()]
|
||||
date = now.date() + timedelta(days=(target - now.date().weekday()) % 7)
|
||||
return date, match.span()
|
||||
return None, None
|
||||
|
||||
|
||||
def _title(text, span):
|
||||
stripped = text
|
||||
if span is not None:
|
||||
stripped = text[: span[0]] + " " + text[span[1] :]
|
||||
cleaned = re.sub(r"\s+", " ", _COMMAND_WORDS.sub(" ", stripped)).strip(" .,:;-")
|
||||
return cleaned
|
||||
|
||||
|
||||
def _ask(request, field, question):
|
||||
request.meta["create_task_awaiting"] = field
|
||||
return ActionResult(action_log=f"waiting for {field}", new_state=request.text, needs_input=question)
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
answers = request.meta.setdefault("create_task_answers", {})
|
||||
awaiting = request.meta.get("create_task_awaiting")
|
||||
if request.user_input is not None and awaiting:
|
||||
answers[awaiting] = request.user_input.strip()
|
||||
request.meta.pop("create_task_awaiting", None)
|
||||
|
||||
now = _now(ctx)
|
||||
due, span = _match_due(request.text, now)
|
||||
title = _title(request.text, span)
|
||||
|
||||
if answers.get("title"):
|
||||
title = answers["title"].strip()
|
||||
if answers.get("due"):
|
||||
extra_due, _ = _match_due(answers["due"], now)
|
||||
if extra_due is not None:
|
||||
due = extra_due
|
||||
|
||||
if not title:
|
||||
return _ask(request, "title", "What's the task?")
|
||||
|
||||
payload = {"title": title}
|
||||
if due is not None:
|
||||
payload["due"] = f"{due.isoformat()}T00:00:00"
|
||||
|
||||
try:
|
||||
data = _post(ctx, "/tasks", payload)
|
||||
except OutlookBridgeError as exc:
|
||||
return ActionResult(action_log=str(exc), new_state=request.text)
|
||||
|
||||
when = f" due {due.isoformat()}" if due is not None else ""
|
||||
report = f"Added task {title!r}{when}."
|
||||
return ActionResult(action_log=report, new_state=report)
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Hermetic mechanics test for outlook.create_task.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the local Outlook bridge's `/tasks` route and records the
|
||||
payload. This proves the body derives a title + due date, asks for a missing
|
||||
title and resumes, creates the task with a real POST, and fails honestly when the
|
||||
bridge errors. It does NOT prove the live integration — only a real run against
|
||||
the user's Microsoft account does.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
import skill
|
||||
|
||||
FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc)
|
||||
skill._now = lambda ctx: FIXED_NOW
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
def call(self, decision): # pragma: no cover - this skill makes no decision
|
||||
raise AssertionError("outlook.create_task must not ask the decision engine")
|
||||
|
||||
|
||||
class BridgeHandler(BaseHTTPRequestHandler):
|
||||
status = 200
|
||||
posts = []
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
body = self.rfile.read(length) if length else b""
|
||||
if self.path != "/tasks":
|
||||
self._send({"error": "not found"}, 404)
|
||||
return
|
||||
self.posts.append(json.loads(body.decode("utf-8")))
|
||||
if self.status != 200:
|
||||
self._send({"error": "boom"}, self.status)
|
||||
return
|
||||
self._send({"ok": True, "id": "t1", "title": self.posts[-1].get("title")}, 201)
|
||||
|
||||
def _send(self, payload, status):
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def start_server(status=200):
|
||||
handler = type("Handler", (BridgeHandler,), {"status": status, "posts": []})
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def config(url):
|
||||
return {"outlook_bridge_url": url, "outlook_bridge_token": ""}
|
||||
|
||||
|
||||
def test_plain_task():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
ctx = ActionContext(engine=FakeEngine(), config=config(url))
|
||||
action = skill.act(ctx, Request("add buy milk to my tasks"))
|
||||
assert action.needs_input is None, action.needs_input
|
||||
assert handler.posts[0]["title"] == "buy milk", handler.posts[0]
|
||||
assert "due" not in handler.posts[0], handler.posts[0]
|
||||
assert "buy milk" in action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_task_with_due_date():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
ctx = ActionContext(engine=FakeEngine(), config=config(url))
|
||||
action = skill.act(ctx, Request("remind me to call the dentist tomorrow"))
|
||||
assert action.needs_input is None, action.needs_input
|
||||
assert handler.posts[0]["title"] == "call dentist", handler.posts[0]
|
||||
assert handler.posts[0]["due"] == "2026-10-08T00:00:00", handler.posts[0]
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_missing_title_asks_then_creates():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
ctx = ActionContext(engine=FakeEngine(), config=config(url))
|
||||
request = Request("add a task")
|
||||
action = skill.act(ctx, request)
|
||||
assert action.needs_input, "a missing title must be asked"
|
||||
assert handler.posts == []
|
||||
request.user_input = "water the plants"
|
||||
action = skill.act(ctx, request)
|
||||
assert action.needs_input is None, action.needs_input
|
||||
assert handler.posts[0]["title"] == "water the plants", handler.posts[0]
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_bridge_error_is_reported_honestly():
|
||||
server, _handler, url = start_server(status=502)
|
||||
try:
|
||||
ctx = ActionContext(engine=FakeEngine(), config=config(url))
|
||||
request = Request("add buy milk to my tasks")
|
||||
action = skill.act(ctx, request)
|
||||
assert "502" in action.action_log, action.action_log
|
||||
assert action.new_state == request.text, "a failed create must not fake a result"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def main():
|
||||
test_plain_task()
|
||||
test_task_with_due_date()
|
||||
test_missing_title_asks_then_creates()
|
||||
test_bridge_error_is_reported_honestly()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Look up a person in the user's Outlook contacts by name, email, or company."
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Look up a person in the user's Outlook contacts.
|
||||
|
||||
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
|
||||
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
|
||||
speaks Graph or OAuth directly. It searches the contacts for the words in the
|
||||
request and reports the matches, or the real failure honestly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from semif_agent.skills import ActionResult
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "outlook",
|
||||
"transport": "http",
|
||||
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
|
||||
}
|
||||
|
||||
CONTRACT = {
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
}
|
||||
|
||||
TIMEOUT_SECONDS = 30
|
||||
_STOPWORDS = re.compile(
|
||||
r"\b(find|search|look\s*up|show|get|whats|what's|contact|contacts|email|e-?mail|"
|
||||
r"address|phone|number|details|for|my|me|the|of|a|an)\b",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
class OutlookBridgeError(Exception):
|
||||
"""A real failure talking to the local Outlook bridge."""
|
||||
|
||||
|
||||
def _get(ctx, path, params=None):
|
||||
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
|
||||
if not base:
|
||||
raise OutlookBridgeError("outlook_bridge_url is not configured")
|
||||
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
|
||||
url = base + path
|
||||
if params:
|
||||
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
|
||||
headers = {"Accept": "application/json"}
|
||||
if token:
|
||||
headers["X-Semif-Token"] = token
|
||||
http_request = urllib.request.Request(url, method="GET", headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
|
||||
return json.loads(response.read().decode("utf-8") or "{}")
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
||||
raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
|
||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
||||
raise OutlookBridgeError(f"GET {path}: {exc}") from exc
|
||||
|
||||
|
||||
def _query(text):
|
||||
return re.sub(r"\s+", " ", _STOPWORDS.sub(" ", text or "")).strip()
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
try:
|
||||
data = _get(ctx, "/contacts", {"query": _query(request.text)})
|
||||
except OutlookBridgeError as exc:
|
||||
return ActionResult(action_log=str(exc), new_state=request.text)
|
||||
|
||||
contacts = data.get("contacts") or []
|
||||
if not contacts:
|
||||
return ActionResult(action_log="No matching contacts.", new_state="No matching contacts.")
|
||||
|
||||
lines = []
|
||||
for contact in contacts[:5]:
|
||||
name = contact.get("display_name") or "(no name)"
|
||||
emails = ", ".join(contact.get("emails") or [])
|
||||
phones = ", ".join(contact.get("phones") or [])
|
||||
bits = " | ".join(part for part in (emails, phones) if part)
|
||||
lines.append(f"- {name}: {bits}" if bits else f"- {name}")
|
||||
report = "Contacts:\n" + "\n".join(lines)
|
||||
return ActionResult(action_log=report, new_state=report)
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Hermetic mechanics test for outlook.list_contacts.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the local Outlook bridge's `/contacts` route and records the
|
||||
query it received. This proves the body searches the contacts and reports the
|
||||
matches (and fails honestly when the bridge is unavailable). It does NOT prove
|
||||
the live integration — only a real run against the user's Microsoft account does.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
import skill
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
def call(self, decision): # pragma: no cover - this skill makes no decision
|
||||
raise AssertionError("outlook.list_contacts must not ask the decision engine")
|
||||
|
||||
|
||||
class BridgeHandler(BaseHTTPRequestHandler):
|
||||
contacts = []
|
||||
status = 200
|
||||
queries = []
|
||||
|
||||
def do_GET(self):
|
||||
if self.status != 200:
|
||||
self._send({"error": "boom"}, self.status)
|
||||
return
|
||||
parsed = urlparse(self.path)
|
||||
if parsed.path == "/contacts":
|
||||
self.queries.append(parse_qs(parsed.query).get("query", [""])[0])
|
||||
self._send({"contacts": self.contacts}, 200)
|
||||
return
|
||||
self._send({"error": "not found"}, 404)
|
||||
|
||||
def _send(self, payload, status):
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def start_server(contacts=None, status=200):
|
||||
handler = type(
|
||||
"Handler",
|
||||
(BridgeHandler,),
|
||||
{
|
||||
"contacts": contacts
|
||||
if contacts is not None
|
||||
else [
|
||||
{
|
||||
"id": "c1",
|
||||
"display_name": "Bob Smith",
|
||||
"emails": ["bob@example.com"],
|
||||
"phones": ["555-1234"],
|
||||
}
|
||||
],
|
||||
"status": status,
|
||||
"queries": [],
|
||||
},
|
||||
)
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def run(url, text="find Bob's email"):
|
||||
ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""})
|
||||
return skill.act(ctx, Request(text))
|
||||
|
||||
|
||||
def test_reports_matching_contacts():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
action = run(url)
|
||||
assert "Bob Smith" in action.action_log, action.action_log
|
||||
assert "bob@example.com" in action.action_log, action.action_log
|
||||
assert handler.queries and "Bob" in handler.queries[0], handler.queries
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_no_matches_is_reported():
|
||||
server, _handler, url = start_server(contacts=[])
|
||||
try:
|
||||
action = run(url)
|
||||
assert "no matching contacts" in action.action_log.lower(), action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_bridge_error_is_reported_honestly():
|
||||
server, _handler, url = start_server(status=502)
|
||||
try:
|
||||
action = run(url)
|
||||
assert "502" in action.action_log, action.action_log
|
||||
assert action.new_state == "find Bob's email"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def main():
|
||||
test_reports_matching_contacts()
|
||||
test_no_matches_is_reported()
|
||||
test_bridge_error_is_reported_honestly()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "List the user's OneDrive files, optionally in a named folder."
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
"""List the user's OneDrive files.
|
||||
|
||||
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
|
||||
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
|
||||
speaks Graph or OAuth directly. It lists a OneDrive folder (root by default) and
|
||||
reports the entries, or the real failure honestly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from semif_agent.skills import ActionResult
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "outlook",
|
||||
"transport": "http",
|
||||
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
|
||||
}
|
||||
|
||||
CONTRACT = {
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
}
|
||||
|
||||
TIMEOUT_SECONDS = 30
|
||||
_STOPWORDS = re.compile(
|
||||
r"\b(list|show|what'?s|whats|in|my|the|onedrive|files|file|folder|drive|of|me)\b",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
class OutlookBridgeError(Exception):
|
||||
"""A real failure talking to the local Outlook bridge."""
|
||||
|
||||
|
||||
def _get(ctx, path, params=None):
|
||||
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
|
||||
if not base:
|
||||
raise OutlookBridgeError("outlook_bridge_url is not configured")
|
||||
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
|
||||
url = base + path
|
||||
if params:
|
||||
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
|
||||
headers = {"Accept": "application/json"}
|
||||
if token:
|
||||
headers["X-Semif-Token"] = token
|
||||
http_request = urllib.request.Request(url, method="GET", headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
|
||||
return json.loads(response.read().decode("utf-8") or "{}")
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
||||
raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
|
||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
||||
raise OutlookBridgeError(f"GET {path}: {exc}") from exc
|
||||
|
||||
|
||||
def _folder(text):
|
||||
cleaned = re.sub(r"\s+", " ", _STOPWORDS.sub(" ", text or "")).strip()
|
||||
return cleaned or "/"
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
path = _folder(request.text)
|
||||
try:
|
||||
data = _get(ctx, "/files", {"path": path})
|
||||
except OutlookBridgeError as exc:
|
||||
return ActionResult(action_log=str(exc), new_state=request.text)
|
||||
|
||||
entries = data.get("entries") or []
|
||||
if not entries:
|
||||
return ActionResult(
|
||||
action_log=f"{data.get('path') or path} is empty.",
|
||||
new_state=f"{data.get('path') or path} is empty.",
|
||||
)
|
||||
|
||||
lines = []
|
||||
for entry in entries[:20]:
|
||||
name = entry.get("name") or "(unnamed)"
|
||||
kind = "folder" if entry.get("is_folder") else "file"
|
||||
size = entry.get("size")
|
||||
detail = f"{kind}"
|
||||
if kind == "file" and size is not None:
|
||||
detail += f", {size} bytes"
|
||||
lines.append(f"- {name} ({detail})")
|
||||
report = f"Files in {data.get('path') or path}:\n" + "\n".join(lines)
|
||||
return ActionResult(action_log=report, new_state=report)
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Hermetic mechanics test for outlook.list_files.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the local Outlook bridge's `/files` route and records the path
|
||||
it received. This proves the body lists OneDrive and reports the entries (and
|
||||
fails honestly when the bridge is unavailable). It does NOT prove the live
|
||||
integration — only a real run against the user's Microsoft account does.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
import skill
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
def call(self, decision): # pragma: no cover - this skill makes no decision
|
||||
raise AssertionError("outlook.list_files must not ask the decision engine")
|
||||
|
||||
|
||||
class BridgeHandler(BaseHTTPRequestHandler):
|
||||
entries = []
|
||||
status = 200
|
||||
paths = []
|
||||
|
||||
def do_GET(self):
|
||||
if self.status != 200:
|
||||
self._send({"error": "boom"}, self.status)
|
||||
return
|
||||
parsed = urlparse(self.path)
|
||||
if parsed.path == "/files":
|
||||
path = parse_qs(parsed.query).get("path", ["/"])[0]
|
||||
self.paths.append(path)
|
||||
self._send({"path": path, "entries": self.entries}, 200)
|
||||
return
|
||||
self._send({"error": "not found"}, 404)
|
||||
|
||||
def _send(self, payload, status):
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def start_server(entries=None, status=200):
|
||||
handler = type(
|
||||
"Handler",
|
||||
(BridgeHandler,),
|
||||
{
|
||||
"entries": entries
|
||||
if entries is not None
|
||||
else [
|
||||
{"id": "d1", "name": "Docs", "is_folder": True, "size": 0},
|
||||
{"id": "f1", "name": "notes.txt", "is_folder": False, "size": 5},
|
||||
],
|
||||
"status": status,
|
||||
"paths": [],
|
||||
},
|
||||
)
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def run(url, text="list my files"):
|
||||
ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""})
|
||||
return skill.act(ctx, Request(text))
|
||||
|
||||
|
||||
def test_lists_root_files():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
action = run(url)
|
||||
assert "Docs (folder)" in action.action_log, action.action_log
|
||||
assert "notes.txt (file, 5 bytes)" in action.action_log, action.action_log
|
||||
assert handler.paths and handler.paths[0] == "/", handler.paths
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_named_folder_is_requested():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
run(url, "list files in Documents")
|
||||
assert handler.paths and handler.paths[0] == "Documents", handler.paths
|
||||
print(handler.paths)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_empty_folder_is_reported():
|
||||
server, _handler, url = start_server(entries=[])
|
||||
try:
|
||||
action = run(url)
|
||||
assert "empty" in action.action_log.lower(), action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_bridge_error_is_reported_honestly():
|
||||
server, _handler, url = start_server(status=502)
|
||||
try:
|
||||
action = run(url)
|
||||
assert "502" in action.action_log, action.action_log
|
||||
assert action.new_state == "list my files"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def main():
|
||||
test_lists_root_files()
|
||||
test_named_folder_is_requested()
|
||||
test_empty_folder_is_reported()
|
||||
test_bridge_error_is_reported_honestly()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Read the user's upcoming Outlook calendar events."
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Read the user's upcoming Outlook calendar events.
|
||||
|
||||
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
|
||||
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
|
||||
speaks Graph or OAuth directly. It asks the bridge for the upcoming events and
|
||||
reports them, or reports the real failure honestly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from semif_agent.skills import ActionResult
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "outlook",
|
||||
"transport": "http",
|
||||
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
|
||||
}
|
||||
|
||||
CONTRACT = {
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
}
|
||||
|
||||
TIMEOUT_SECONDS = 30
|
||||
DEFAULT_COUNT = 5
|
||||
|
||||
|
||||
class OutlookBridgeError(Exception):
|
||||
"""A real failure talking to the local Outlook bridge."""
|
||||
|
||||
|
||||
def _get(ctx, path, params=None):
|
||||
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
|
||||
if not base:
|
||||
raise OutlookBridgeError("outlook_bridge_url is not configured")
|
||||
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
|
||||
url = base + path
|
||||
if params:
|
||||
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
|
||||
headers = {"Accept": "application/json"}
|
||||
if token:
|
||||
headers["X-Semif-Token"] = token
|
||||
http_request = urllib.request.Request(url, method="GET", headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
|
||||
return json.loads(response.read().decode("utf-8") or "{}")
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
||||
raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
|
||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
||||
raise OutlookBridgeError(f"GET {path}: {exc}") from exc
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
try:
|
||||
data = _get(ctx, "/calendars/events")
|
||||
except OutlookBridgeError as exc:
|
||||
return ActionResult(action_log=str(exc), new_state=request.text)
|
||||
|
||||
events = data.get("events") or []
|
||||
if not events:
|
||||
return ActionResult(action_log="There are no upcoming events.", new_state="No upcoming events.")
|
||||
|
||||
lines = []
|
||||
for event in events[:DEFAULT_COUNT]:
|
||||
subject = event.get("subject") or "(no subject)"
|
||||
start = event.get("start") or ""
|
||||
when = _describe_when(start, bool(event.get("all_day")))
|
||||
location = event.get("location") or ""
|
||||
where = f" at {location}" if location else ""
|
||||
lines.append(f"- {subject}{where} — {when}")
|
||||
report = "Upcoming events:\n" + "\n".join(lines)
|
||||
return ActionResult(action_log=report, new_state=report)
|
||||
|
||||
|
||||
def _describe_when(start, all_day):
|
||||
"""A short human time: the date (all-day) or date + time."""
|
||||
text = str(start or "").strip()
|
||||
if not text:
|
||||
return "time unknown"
|
||||
date, _, rest = text.partition("T")
|
||||
if all_day or not rest:
|
||||
return f"{date} (all day)" if all_day else date
|
||||
return f"{date} {rest[:5]}"
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Hermetic mechanics test for outlook.next_event.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the local Outlook bridge's `/calendars/events` route. This
|
||||
proves the body asks the bridge for upcoming events and reports them (and fails
|
||||
honestly when the bridge is unavailable). It does NOT prove the live
|
||||
integration — only a real run against the user's Microsoft account does.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
import skill
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
def call(self, decision): # pragma: no cover - this skill makes no decision
|
||||
raise AssertionError("outlook.next_event must not ask the decision engine")
|
||||
|
||||
|
||||
class BridgeHandler(BaseHTTPRequestHandler):
|
||||
events = []
|
||||
status = 200
|
||||
|
||||
def do_GET(self):
|
||||
if self.status != 200:
|
||||
self._send({"error": "boom"}, self.status)
|
||||
return
|
||||
if self.path.startswith("/calendars/events"):
|
||||
self._send({"calendar": "", "events": self.events}, 200)
|
||||
return
|
||||
self._send({"error": "not found"}, 404)
|
||||
|
||||
def _send(self, payload, status):
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def start_server(events=None, status=200):
|
||||
handler = type(
|
||||
"Handler",
|
||||
(BridgeHandler,),
|
||||
{
|
||||
"events": events
|
||||
if events is not None
|
||||
else [
|
||||
{
|
||||
"id": "e1",
|
||||
"subject": "Standup",
|
||||
"start": "2026-10-08T09:00:00.0000000",
|
||||
"end": "2026-10-08T09:30:00.0000000",
|
||||
"all_day": False,
|
||||
"location": "Room 1",
|
||||
}
|
||||
],
|
||||
"status": status,
|
||||
},
|
||||
)
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def run(url, text="what's on my calendar"):
|
||||
ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""})
|
||||
return skill.act(ctx, Request(text))
|
||||
|
||||
|
||||
def test_reports_upcoming_events():
|
||||
server, url = start_server()
|
||||
try:
|
||||
action = run(url)
|
||||
assert "Standup" in action.action_log, action.action_log
|
||||
assert "Room 1" in action.action_log, action.action_log
|
||||
assert "2026-10-08 09:00" in action.action_log, action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_no_events_is_reported():
|
||||
server, url = start_server(events=[])
|
||||
try:
|
||||
action = run(url)
|
||||
assert "no upcoming events" in action.action_log.lower(), action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_bridge_error_is_reported_honestly():
|
||||
server, url = start_server(status=502)
|
||||
try:
|
||||
action = run(url)
|
||||
assert "502" in action.action_log, action.action_log
|
||||
assert action.new_state == "what's on my calendar"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_unreachable_bridge_fails_honestly():
|
||||
action = run("http://127.0.0.1:1")
|
||||
assert action.new_state == "what's on my calendar"
|
||||
print(action.action_log)
|
||||
|
||||
|
||||
def main():
|
||||
test_reports_upcoming_events()
|
||||
test_no_events_is_reported()
|
||||
test_bridge_error_is_reported_honestly()
|
||||
test_unreachable_bridge_fails_honestly()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Read the latest messages from the user's Outlook inbox."
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Read the latest messages from the user's Outlook inbox.
|
||||
|
||||
Real integration: the local Outlook bridge (Microsoft Graph). Connection comes
|
||||
from `ctx.config` (`outlook_bridge_url`, `outlook_bridge_token`); the body never
|
||||
speaks Graph or OAuth directly. It asks the bridge for the newest inbox messages
|
||||
and reports them, or reports the real failure honestly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from semif_agent.skills import ActionResult
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "outlook",
|
||||
"transport": "http",
|
||||
"config_vars": ["outlook_bridge_url", "outlook_bridge_token"],
|
||||
}
|
||||
|
||||
CONTRACT = {
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
}
|
||||
|
||||
TIMEOUT_SECONDS = 30
|
||||
DEFAULT_COUNT = 5
|
||||
|
||||
|
||||
class OutlookBridgeError(Exception):
|
||||
"""A real failure talking to the local Outlook bridge."""
|
||||
|
||||
|
||||
def _get(ctx, path, params=None):
|
||||
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
|
||||
if not base:
|
||||
raise OutlookBridgeError("outlook_bridge_url is not configured")
|
||||
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
|
||||
url = base + path
|
||||
if params:
|
||||
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
|
||||
headers = {"Accept": "application/json"}
|
||||
if token:
|
||||
headers["X-Semif-Token"] = token
|
||||
http_request = urllib.request.Request(url, method="GET", headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
|
||||
return json.loads(response.read().decode("utf-8") or "{}")
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
||||
raise OutlookBridgeError(f"GET {path}: HTTP {exc.code} {detail}") from exc
|
||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
||||
raise OutlookBridgeError(f"GET {path}: {exc}") from exc
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
try:
|
||||
data = _get(ctx, "/mail/messages", {"folder": "inbox", "count": DEFAULT_COUNT})
|
||||
except OutlookBridgeError as exc:
|
||||
return ActionResult(action_log=str(exc), new_state=request.text)
|
||||
|
||||
messages = data.get("messages") or []
|
||||
if not messages:
|
||||
return ActionResult(action_log="The inbox is empty.", new_state="The inbox is empty.")
|
||||
|
||||
lines = []
|
||||
for message in messages[:DEFAULT_COUNT]:
|
||||
sender = message.get("from") or "unknown sender"
|
||||
subject = message.get("subject") or "(no subject)"
|
||||
received = message.get("received") or ""
|
||||
flag = " (unread)" if not message.get("is_read") else ""
|
||||
lines.append(f"- {sender}: {subject}{flag} [{received}]")
|
||||
report = "Recent inbox messages:\n" + "\n".join(lines)
|
||||
return ActionResult(action_log=report, new_state=report)
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Hermetic mechanics test for outlook.next_message.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the local Outlook bridge's `/mail/messages` route. This proves
|
||||
the body asks the bridge for the inbox and reports the messages (and fails
|
||||
honestly when the bridge is unavailable). It does NOT prove the live
|
||||
integration — only a real run against the user's Microsoft account does.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
import skill
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
def call(self, decision): # pragma: no cover - this skill makes no decision
|
||||
raise AssertionError("outlook.next_message must not ask the decision engine")
|
||||
|
||||
|
||||
class BridgeHandler(BaseHTTPRequestHandler):
|
||||
messages = []
|
||||
requests = []
|
||||
status = 200
|
||||
|
||||
def do_GET(self):
|
||||
self.requests.append(self.path)
|
||||
if self.status != 200:
|
||||
self._send({"error": "boom"}, self.status)
|
||||
return
|
||||
if self.path.startswith("/mail/messages"):
|
||||
self._send({"folder": "inbox", "messages": self.messages}, 200)
|
||||
return
|
||||
self._send({"error": "not found"}, 404)
|
||||
|
||||
def _send(self, payload, status):
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def start_server(messages=None, status=200):
|
||||
handler = type(
|
||||
"Handler",
|
||||
(BridgeHandler,),
|
||||
{
|
||||
"messages": messages
|
||||
if messages is not None
|
||||
else [
|
||||
{
|
||||
"id": "m1",
|
||||
"subject": "Lunch?",
|
||||
"from": "Sam <sam@example.com>",
|
||||
"received": "2026-10-08T12:00:00Z",
|
||||
"is_read": False,
|
||||
}
|
||||
],
|
||||
"requests": [],
|
||||
"status": status,
|
||||
},
|
||||
)
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def run(url, text="check my email"):
|
||||
ctx = ActionContext(engine=FakeEngine(), config={"outlook_bridge_url": url, "outlook_bridge_token": ""})
|
||||
return skill.act(ctx, Request(text))
|
||||
|
||||
|
||||
def test_reports_recent_messages():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
action = run(url)
|
||||
assert "Lunch?" in action.action_log, action.action_log
|
||||
assert "sam@example.com" in action.action_log, action.action_log
|
||||
assert action.new_state == action.action_log
|
||||
assert handler.requests, "the bridge must be called"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_empty_inbox_is_reported():
|
||||
server, _handler, url = start_server(messages=[])
|
||||
try:
|
||||
action = run(url)
|
||||
assert "empty" in action.action_log.lower(), action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_bridge_error_is_reported_honestly():
|
||||
server, _handler, url = start_server(status=502)
|
||||
try:
|
||||
action = run(url)
|
||||
assert "502" in action.action_log, action.action_log
|
||||
assert action.new_state == "check my email", "a failed read must not fake a result"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_unreachable_bridge_fails_honestly():
|
||||
action = run("http://127.0.0.1:1")
|
||||
assert "outlook.next_message" not in action.action_log, action.action_log
|
||||
assert action.new_state == "check my email"
|
||||
print(action.action_log)
|
||||
|
||||
|
||||
def main():
|
||||
test_reports_recent_messages()
|
||||
test_empty_inbox_is_reported()
|
||||
test_bridge_error_is_reported_honestly()
|
||||
test_unreachable_bridge_fails_honestly()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to compose the message.",
|
||||
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"description": "Compose and send an Outlook email, after confirming the message."
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Send an Outlook email on the user's behalf, after a confirmation.
|
||||
|
||||
Real integration: the local Outlook bridge (Microsoft Graph) to resolve the
|
||||
recipient and send, and the local LLM bridge to turn the request into a
|
||||
`{recipient, subject, body}` draft. Connection comes from `ctx.config`
|
||||
(`outlook_bridge_url`, `outlook_bridge_token`, `llm_bridge_url`,
|
||||
`llm_bridge_token`); the body never speaks Graph, OAuth, or the model's protocol
|
||||
directly.
|
||||
|
||||
Because sending is irreversible, the body **asks for confirmation before it
|
||||
sends**: it composes the message, resolves the recipient (an explicit address is
|
||||
used as-is; otherwise the contacts are searched and, when several match, a SemIf
|
||||
choice picks one), then pauses with "Send ...? (yes/no)". A `yes` sends for real;
|
||||
anything else cancels. A missing recipient is asked for.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from semif_agent.decisions import DecisionRequest, Option
|
||||
from semif_agent.skills import ActionResult
|
||||
|
||||
INTEGRATION = {
|
||||
"service": "outlook",
|
||||
"transport": "http",
|
||||
"config_vars": [
|
||||
"outlook_bridge_url",
|
||||
"outlook_bridge_token",
|
||||
"llm_bridge_url",
|
||||
"llm_bridge_token",
|
||||
],
|
||||
}
|
||||
|
||||
CONTRACT = {
|
||||
"outlook_bridge_url": "Base URL of the local Outlook bridge, e.g. http://127.0.0.1:5231 (no trailing slash needed).",
|
||||
"outlook_bridge_token": "Shared secret for the Outlook bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
"llm_bridge_url": "Base URL of the local LLM bridge, e.g. http://127.0.0.1:5229 (no trailing slash needed); used to compose the message.",
|
||||
"llm_bridge_token": "Shared secret for the LLM bridge, if one is configured; sent as the X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
}
|
||||
|
||||
TIMEOUT_SECONDS = 30
|
||||
_YES = {"y", "yes", "send", "ok", "okay", "sure", "confirm"}
|
||||
|
||||
|
||||
class OutlookBridgeError(Exception):
|
||||
"""A real failure talking to the local Outlook or LLM bridge."""
|
||||
|
||||
|
||||
def _request(ctx, service, path, *, method="GET", params=None, payload=None):
|
||||
if service == "llm":
|
||||
base = str(ctx.config.get("llm_bridge_url", "") or "").strip().rstrip("/")
|
||||
token = str(ctx.config.get("llm_bridge_token", "") or "").strip()
|
||||
else:
|
||||
base = str(ctx.config.get("outlook_bridge_url", "") or "").strip().rstrip("/")
|
||||
token = str(ctx.config.get("outlook_bridge_token", "") or "").strip()
|
||||
if not base:
|
||||
raise OutlookBridgeError(f"the {service} bridge URL is not configured")
|
||||
url = base + path
|
||||
if params:
|
||||
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
|
||||
data = json.dumps(payload).encode("utf-8") if payload is not None else None
|
||||
headers = {"Accept": "application/json"}
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
if token:
|
||||
headers["X-Semif-Token"] = token
|
||||
http_request = urllib.request.Request(url, data=data, method=method, headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response:
|
||||
return json.loads(response.read().decode("utf-8") or "{}")
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = exc.read().decode("utf-8", "replace").strip()[:200]
|
||||
raise OutlookBridgeError(f"{method} {path}: HTTP {exc.code} {detail}") from exc
|
||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
||||
raise OutlookBridgeError(f"{method} {path}: {exc}") from exc
|
||||
|
||||
|
||||
def _compose(ctx, request):
|
||||
"""Ask the LLM bridge for the recipient, subject, and body."""
|
||||
messages = [
|
||||
{
|
||||
"role": "system",
|
||||
"content": (
|
||||
"Turn the user's request into an email. Reply with ONLY a JSON "
|
||||
'object: {"recipient": "<name or email address>", '
|
||||
'"subject": "<short subject>", "body": "<the message>"}.'
|
||||
),
|
||||
},
|
||||
{"role": "user", "content": request.text},
|
||||
]
|
||||
data = _request(ctx, "llm", "/chat", method="POST", payload={"messages": messages})
|
||||
text = str(data.get("text") or "")
|
||||
start, end = text.find("{"), text.rfind("}")
|
||||
if start == -1 or end < start:
|
||||
raise OutlookBridgeError("the LLM bridge returned no JSON object")
|
||||
try:
|
||||
draft = json.loads(text[start : end + 1])
|
||||
except ValueError as exc:
|
||||
raise OutlookBridgeError(f"the LLM bridge returned invalid JSON: {exc}") from exc
|
||||
if not isinstance(draft, dict):
|
||||
raise OutlookBridgeError("the LLM bridge returned JSON that is not an object")
|
||||
return {
|
||||
"recipient": str(draft.get("recipient") or "").strip(),
|
||||
"subject": str(draft.get("subject") or "").strip(),
|
||||
"body": str(draft.get("body") or "").strip(),
|
||||
}
|
||||
|
||||
|
||||
def _resolve_address(ctx, decisions, recipient):
|
||||
"""An email address for `recipient`: used directly, or chosen from contacts."""
|
||||
if "@" in recipient:
|
||||
return recipient
|
||||
data = _request(ctx, "outlook", "/contacts", params={"query": recipient})
|
||||
contacts = [c for c in (data.get("contacts") or []) if c.get("emails")]
|
||||
if not contacts:
|
||||
return None
|
||||
if len(contacts) == 1:
|
||||
return str(contacts[0]["emails"][0])
|
||||
options = [
|
||||
Option(str(contact["emails"][0]), str(contact.get("display_name") or contact["emails"][0]))
|
||||
for contact in contacts
|
||||
]
|
||||
decision = DecisionRequest(
|
||||
state=recipient,
|
||||
question="Which contact should the message be sent to?",
|
||||
options=options,
|
||||
)
|
||||
result = ctx.engine.call(decision)
|
||||
decisions.append((decision, result))
|
||||
return str(result.selected)
|
||||
|
||||
|
||||
def _ask(request, question):
|
||||
return ActionResult(action_log="waiting for input", new_state=request.text, needs_input=question)
|
||||
|
||||
|
||||
def act(ctx, request):
|
||||
meta = request.meta
|
||||
awaiting = meta.get("send_message_awaiting")
|
||||
decisions = []
|
||||
|
||||
# Resume: the user answered the recipient/address/confirmation question.
|
||||
if request.user_input is not None and awaiting:
|
||||
if awaiting == "confirm":
|
||||
ready = meta.get("send_message_ready") or {}
|
||||
meta.pop("send_message_awaiting", None)
|
||||
if request.user_input.strip().lower() not in _YES:
|
||||
return ActionResult(
|
||||
action_log="Cancelled; the message was not sent.",
|
||||
new_state="cancelled",
|
||||
)
|
||||
try:
|
||||
result = _request(
|
||||
ctx,
|
||||
"outlook",
|
||||
"/mail/send",
|
||||
method="POST",
|
||||
payload={"to": [ready.get("to", "")], "subject": ready.get("subject", ""), "body": ready.get("body", "")},
|
||||
)
|
||||
except OutlookBridgeError as exc:
|
||||
return ActionResult(action_log=str(exc), new_state=request.text)
|
||||
report = f"Sent {ready.get('subject')!r} to {ready.get('to')}."
|
||||
meta.pop("send_message_ready", None)
|
||||
return ActionResult(action_log=report, new_state=report)
|
||||
meta.setdefault("send_message_answers", {})[awaiting] = request.user_input.strip()
|
||||
meta.pop("send_message_awaiting", None)
|
||||
|
||||
answers = meta.get("send_message_answers") or {}
|
||||
|
||||
draft = meta.get("send_message_composed")
|
||||
if draft is None:
|
||||
try:
|
||||
draft = _compose(ctx, request)
|
||||
except OutlookBridgeError as exc:
|
||||
return ActionResult(action_log=str(exc), new_state=request.text)
|
||||
meta["send_message_composed"] = draft
|
||||
|
||||
recipient = answers.get("recipient") or draft["recipient"]
|
||||
if not recipient:
|
||||
meta["send_message_awaiting"] = "recipient"
|
||||
return _ask(request, "Who should I send the message to?")
|
||||
|
||||
address = answers.get("address")
|
||||
if not address:
|
||||
try:
|
||||
address = _resolve_address(ctx, decisions, recipient)
|
||||
except OutlookBridgeError as exc:
|
||||
return ActionResult(action_log=str(exc), new_state=request.text)
|
||||
if not address:
|
||||
meta["send_message_awaiting"] = "address"
|
||||
return _ask(request, f"What's the email address for {recipient!r}?")
|
||||
|
||||
meta["send_message_ready"] = {"to": address, "subject": draft["subject"], "body": draft["body"]}
|
||||
meta["send_message_awaiting"] = "confirm"
|
||||
action = _ask(request, f"Send {draft['subject']!r} to {address}? (yes/no)")
|
||||
action.decisions = decisions
|
||||
return action
|
||||
@@ -0,0 +1,216 @@
|
||||
"""Hermetic mechanics test for outlook.send_message.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the local LLM bridge (`POST /chat`), the Outlook bridge's
|
||||
contact lookup, and `POST /mail/send`. This proves the body composes a draft,
|
||||
resolves the recipient, asks for confirmation BEFORE sending, sends for real on
|
||||
`yes`, cancels otherwise, and fails honestly when the LLM bridge is down. It does
|
||||
NOT prove the live integration — only a real run against the user's Microsoft
|
||||
account does.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from semif_agent.decisions import DecisionResult, Request
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
import skill
|
||||
|
||||
|
||||
class FakeEngine:
|
||||
"""Picks `pick` (else the first option) with full confidence."""
|
||||
|
||||
def __init__(self, pick=None):
|
||||
self.pick = pick
|
||||
self.decisions = []
|
||||
|
||||
def call(self, decision):
|
||||
self.decisions.append(decision)
|
||||
ids = [option.id for option in decision.options]
|
||||
chosen = self.pick if self.pick in ids else ids[0]
|
||||
probs = [1.0 if option_id == chosen else 0.0 for option_id in ids]
|
||||
return DecisionResult(request=decision, option_ids=ids, probabilities=probs)
|
||||
|
||||
|
||||
class BridgeHandler(BaseHTTPRequestHandler):
|
||||
draft = {"recipient": "Sam", "subject": "Lunch", "body": "Tomorrow?"}
|
||||
contacts = [{"id": "c1", "display_name": "Sam", "emails": ["sam@example.com"]}]
|
||||
llm_status = 200
|
||||
sends = []
|
||||
queries = []
|
||||
|
||||
def _read(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
return self.rfile.read(length) if length else b""
|
||||
|
||||
def do_POST(self):
|
||||
body = self._read()
|
||||
if self.path == "/chat":
|
||||
if self.llm_status != 200:
|
||||
self._send({"error": "boom"}, self.llm_status)
|
||||
return
|
||||
self._send({"text": json.dumps(self.draft)}, 200)
|
||||
return
|
||||
if self.path == "/mail/send":
|
||||
self.sends.append(json.loads(body.decode("utf-8")))
|
||||
self._send({"ok": True, "to": self.sends[-1].get("to")}, 200)
|
||||
return
|
||||
self._send({"error": "not found"}, 404)
|
||||
|
||||
def do_GET(self):
|
||||
parsed = urlparse(self.path)
|
||||
if parsed.path == "/contacts":
|
||||
self.queries.append(parse_qs(parsed.query).get("query", [""])[0])
|
||||
self._send({"contacts": self.contacts}, 200)
|
||||
return
|
||||
self._send({"error": "not found"}, 404)
|
||||
|
||||
def _send(self, payload, status):
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def start_server(**overrides):
|
||||
attrs = {
|
||||
"draft": {"recipient": "Sam", "subject": "Lunch", "body": "Tomorrow?"},
|
||||
"contacts": [{"id": "c1", "display_name": "Sam", "emails": ["sam@example.com"]}],
|
||||
"llm_status": 200,
|
||||
"sends": [],
|
||||
"queries": [],
|
||||
}
|
||||
attrs.update(overrides)
|
||||
handler = type("Handler", (BridgeHandler,), attrs)
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, handler, f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def context(url, engine):
|
||||
return ActionContext(
|
||||
engine=engine,
|
||||
config={
|
||||
"outlook_bridge_url": url,
|
||||
"outlook_bridge_token": "",
|
||||
"llm_bridge_url": url,
|
||||
"llm_bridge_token": "",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_confirms_then_sends():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
ctx = context(url, FakeEngine())
|
||||
request = Request("email Sam that lunch is tomorrow")
|
||||
action = skill.act(ctx, request)
|
||||
assert action.needs_input and "send" in action.needs_input.lower(), action.needs_input
|
||||
assert handler.sends == [], "nothing may be sent before confirmation"
|
||||
request.user_input = "yes"
|
||||
action = skill.act(ctx, request)
|
||||
assert action.needs_input is None, action.needs_input
|
||||
assert handler.sends[0]["to"] == ["sam@example.com"], handler.sends
|
||||
assert handler.sends[0]["subject"] == "Lunch", handler.sends
|
||||
assert "sent" in action.action_log.lower(), action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_cancel_does_not_send():
|
||||
server, handler, url = start_server()
|
||||
try:
|
||||
ctx = context(url, FakeEngine())
|
||||
request = Request("email Sam that lunch is tomorrow")
|
||||
skill.act(ctx, request)
|
||||
request.user_input = "no"
|
||||
action = skill.act(ctx, request)
|
||||
assert handler.sends == [], "a cancelled message must not be sent"
|
||||
assert "cancel" in action.action_log.lower(), action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_multiple_contacts_use_semif_choice():
|
||||
contacts = [
|
||||
{"id": "c1", "display_name": "Sam A", "emails": ["sam.a@example.com"]},
|
||||
{"id": "c2", "display_name": "Sam B", "emails": ["sam.b@example.com"]},
|
||||
]
|
||||
server, handler, url = start_server(contacts=contacts)
|
||||
try:
|
||||
engine = FakeEngine(pick="sam.b@example.com")
|
||||
ctx = context(url, engine)
|
||||
request = Request("email Sam that lunch is tomorrow")
|
||||
action = skill.act(ctx, request)
|
||||
assert len(engine.decisions) == 1, engine.decisions
|
||||
assert "sam.b@example.com" in action.needs_input, action.needs_input
|
||||
request.user_input = "yes"
|
||||
action = skill.act(ctx, request)
|
||||
assert handler.sends[0]["to"] == ["sam.b@example.com"], handler.sends
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_explicit_address_is_used():
|
||||
server, handler, url = start_server(
|
||||
draft={"recipient": "bob@example.com", "subject": "Late", "body": "I'll be late"}
|
||||
)
|
||||
try:
|
||||
ctx = context(url, FakeEngine(pick="sam@example.com"))
|
||||
request = Request("email bob@example.com that I'll be late")
|
||||
skill.act(ctx, request)
|
||||
request.user_input = "yes"
|
||||
skill.act(ctx, request)
|
||||
assert handler.sends[0]["to"] == ["bob@example.com"], handler.sends
|
||||
# No contact lookup is needed for an explicit address.
|
||||
assert handler.queries == [], handler.queries
|
||||
print(handler.sends[0])
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_llm_bridge_failure_is_reported_honestly():
|
||||
server, handler, url = start_server(llm_status=502)
|
||||
try:
|
||||
ctx = context(url, FakeEngine())
|
||||
request = Request("email Sam that lunch is tomorrow")
|
||||
action = skill.act(ctx, request)
|
||||
assert "502" in action.action_log, action.action_log
|
||||
assert handler.sends == []
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def main():
|
||||
test_confirms_then_sends()
|
||||
test_cancel_does_not_send()
|
||||
test_multiple_contacts_use_semif_choice()
|
||||
test_explicit_address_is_used()
|
||||
test_llm_bridge_failure_is_reported_honestly()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
sys.exit(1)
|
||||
@@ -1,7 +1,8 @@
|
||||
"""Third-party API bridges: a secure local layer between skills and services.
|
||||
|
||||
A **bridge service** is a standalone process that exposes one third-party system
|
||||
(SimpleX, the local language model, Nextcloud) to codegen-authored skill bodies
|
||||
(SimpleX, the local language model, Nextcloud, Microsoft Graph / Outlook) to
|
||||
codegen-authored skill bodies
|
||||
over a local, token-guarded HTTP API. It exists so a generated body never speaks
|
||||
a system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat
|
||||
API, a CLI's private flags) directly: it calls a small, documented, uniform HTTP
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
"""Outlook bridge: the user's Microsoft account (Graph) over HTTP.
|
||||
|
||||
Microsoft Graph is a plain HTTPS/JSON API, but a codegen-authored skill body
|
||||
must still never speak it (or OAuth) directly. This bridge owns the connection —
|
||||
the Entra ID client id, the tenant, and the stored refresh token — and exposes
|
||||
one uniform, token-guarded localhost JSON API for mail, calendar, Microsoft To Do
|
||||
tasks, contacts, and OneDrive files, so a body only reads `outlook_bridge_url`
|
||||
and `outlook_bridge_token` from `ctx.config` and calls a documented route.
|
||||
|
||||
There is no service daemon and no third-party dependency: Graph is plain HTTPS,
|
||||
so the bridge is stdlib-only (`urllib`) and starts instantly, like Nextcloud.
|
||||
Authorization is the OAuth2 device code flow, run once with
|
||||
`scripts/outlook-auth.py`; the resulting tokens are stored (0600) under the
|
||||
checkout's `.runtime/outlook/token.json`. The bridge starts without them and an
|
||||
unauthenticated route returns 503 telling the operator to run that helper.
|
||||
|
||||
The actual Graph work lives in `outlook_client.py`; the routes here validate
|
||||
input and map a real failure (`OutlookError`) to a 502 — or a missing
|
||||
authorization (`OutlookAuthRequired`) to a 503 — rather than a fabricated
|
||||
success.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .outlook_client import (
|
||||
DEFAULT_SCOPES,
|
||||
DEFAULT_TENANT,
|
||||
DEFAULT_TIMEOUT,
|
||||
OutlookAuthRequired,
|
||||
OutlookClient,
|
||||
OutlookError,
|
||||
)
|
||||
|
||||
#: The checkout root (`semif_agent/bridges/outlook.py` -> repo root), used to
|
||||
#: anchor the default token store under the gitignored `.runtime/` tree.
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
DEFAULT_TOKEN_PATH = str(_REPO_ROOT / ".runtime" / "outlook" / "token.json")
|
||||
|
||||
|
||||
class OutlookBridge(BridgeService):
|
||||
name = "outlook"
|
||||
INFO = BridgeInfo(
|
||||
name="outlook",
|
||||
service="outlook",
|
||||
description=(
|
||||
"Read and write the user's Microsoft account (Outlook / Microsoft "
|
||||
"365) through Microsoft Graph: mail, calendar events, Microsoft To "
|
||||
"Do tasks, contacts, and OneDrive files."
|
||||
),
|
||||
url_config_var="outlook_bridge_url",
|
||||
endpoints=(
|
||||
"GET /health -> 200 {\"ok\": true, \"platform\": \"outlook\"} — the "
|
||||
"bridge is up",
|
||||
"GET /user -> 200 {\"user\": {id, display_name, mail, "
|
||||
"user_principal_name}} — the signed-in account",
|
||||
"GET /mail/folders -> 200 {\"folders\": [{id, name, total, unread}]}",
|
||||
"GET /mail/messages?folder=<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 scripts/outlook-auth.py) or has no client id configured; 502 "
|
||||
"{\"error\": \"...\"} on a real Microsoft Graph failure (transport, "
|
||||
"HTTP error, or bad reply)",
|
||||
),
|
||||
config_vars=("outlook_bridge_url", "outlook_bridge_token"),
|
||||
config_var_docs=(
|
||||
(
|
||||
"outlook_bridge_url",
|
||||
"Base URL of the local Outlook bridge (e.g. "
|
||||
"http://127.0.0.1:5231); never hardcode it in the body.",
|
||||
),
|
||||
(
|
||||
"outlook_bridge_token",
|
||||
"Shared secret for the bridge, if one is configured; sent as the "
|
||||
"X-Semif-Token header. Leave blank when the bridge requires no auth.",
|
||||
),
|
||||
),
|
||||
auth_header="X-Semif-Token",
|
||||
auth_config_var="outlook_bridge_token",
|
||||
)
|
||||
|
||||
def __init__(self, config: dict | None = None, trace=None, client=None):
|
||||
super().__init__(config, trace)
|
||||
cfg = config or {}
|
||||
self.client_id = str(cfg.get("client_id", "") or "").strip()
|
||||
self.tenant = str(cfg.get("tenant", DEFAULT_TENANT) or DEFAULT_TENANT).strip() or DEFAULT_TENANT
|
||||
self.token_path = str(cfg.get("token_path") or DEFAULT_TOKEN_PATH)
|
||||
self.default_timezone = str(cfg.get("default_timezone", "UTC") or "UTC").strip() or "UTC"
|
||||
self.default_mail_folder = str(cfg.get("default_mail_folder", "inbox") or "inbox").strip() or "inbox"
|
||||
#: A test seam: inject a client double. Production builds the real one.
|
||||
self.client = client or OutlookClient(
|
||||
self.client_id,
|
||||
tenant=self.tenant,
|
||||
token_path=self.token_path,
|
||||
scopes=cfg.get("scopes") or DEFAULT_SCOPES,
|
||||
timeout=float(cfg.get("timeout", DEFAULT_TIMEOUT)),
|
||||
verify_tls=bool(cfg.get("verify_tls", True)),
|
||||
default_calendar=str(cfg.get("default_calendar", "") or "").strip(),
|
||||
default_task_list=str(cfg.get("default_task_list", "") or "").strip(),
|
||||
default_mail_folder=self.default_mail_folder,
|
||||
default_timezone=self.default_timezone,
|
||||
)
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def check_requirements(self) -> tuple[bool, str | None]:
|
||||
# Stdlib only: no missing dependency can make the bridge unstartable. A
|
||||
# missing authorization surfaces as a 503 on the call, not a startup failure.
|
||||
return True, None
|
||||
|
||||
# ---- routes ----
|
||||
|
||||
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/health":
|
||||
return 200, {"ok": True, "platform": self.name}
|
||||
if not self.client.configured:
|
||||
return self._unconfigured()
|
||||
try:
|
||||
return self._get(path, query)
|
||||
except OutlookAuthRequired as exc:
|
||||
return 503, {"error": str(exc)[:300]}
|
||||
except OutlookError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if not self.client.configured:
|
||||
return self._unconfigured()
|
||||
try:
|
||||
return self._post(path, payload)
|
||||
except OutlookAuthRequired as exc:
|
||||
return 503, {"error": str(exc)[:300]}
|
||||
except OutlookError as exc:
|
||||
return 502, {"error": str(exc)[:300]}
|
||||
except ValueError as exc:
|
||||
return 400, {"error": str(exc)[:300]}
|
||||
|
||||
def _unconfigured(self) -> tuple[int, dict]:
|
||||
return 503, {
|
||||
"error": (
|
||||
"the Outlook bridge has no connection configured (set "
|
||||
"bridges.outlook.client_id, then run scripts/outlook-auth.py)"
|
||||
)
|
||||
}
|
||||
|
||||
def _get(self, path: str, query: dict) -> tuple[int, dict]:
|
||||
if path == "/user":
|
||||
return 200, {"user": self.client.me()}
|
||||
if path == "/mail/folders":
|
||||
return 200, {"folders": self.client.list_mail_folders()}
|
||||
if path == "/mail/messages":
|
||||
folder = self._q(query, "folder", "") or ""
|
||||
return 200, {
|
||||
"folder": folder or self.default_mail_folder,
|
||||
"messages": self.client.list_messages(
|
||||
folder,
|
||||
self._int_query(query, "count", 25),
|
||||
self._q(query, "search", "") or "",
|
||||
self._bool_query(query, "unread", False),
|
||||
),
|
||||
}
|
||||
if path == "/mail/messages/get":
|
||||
return 200, {"message": self.client.get_message(self._required_query(query, "id"))}
|
||||
if path == "/calendars":
|
||||
return 200, {"calendars": self.client.list_calendars()}
|
||||
if path == "/calendars/events":
|
||||
return 200, {
|
||||
"calendar": self._q(query, "calendar", "") or "",
|
||||
"events": self.client.list_events(
|
||||
self._q(query, "calendar", "") or "",
|
||||
self._q(query, "start", "") or "",
|
||||
self._q(query, "end", "") or "",
|
||||
),
|
||||
}
|
||||
if path == "/tasklists":
|
||||
return 200, {"tasklists": self.client.list_task_lists()}
|
||||
if path == "/tasks":
|
||||
task_list = self._q(query, "list", "") or ""
|
||||
return 200, {"list": task_list, "tasks": self.client.list_tasks(task_list)}
|
||||
if path == "/contacts":
|
||||
return 200, {
|
||||
"contacts": self.client.list_contacts(
|
||||
self._q(query, "query", "") or "", self._int_query(query, "count", 50)
|
||||
)
|
||||
}
|
||||
if path == "/files":
|
||||
folder = self._q(query, "path", "/") or "/"
|
||||
return 200, {"path": folder, "entries": self.client.list_files(folder)}
|
||||
if path == "/files/read":
|
||||
return 200, self.client.read_file(self._required_query(query, "path"))
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
def _post(self, path: str, payload: dict) -> tuple[int, dict]:
|
||||
if path == "/mail/send":
|
||||
recipients = self._string_list(payload, "to")
|
||||
if not recipients:
|
||||
raise ValueError("to is required")
|
||||
return 200, self.client.send_mail(
|
||||
recipients,
|
||||
self._optional_str(payload, "subject"),
|
||||
self._optional_str(payload, "body"),
|
||||
self._string_list(payload, "cc"),
|
||||
self._optional_str(payload, "content_type", "text") or "text",
|
||||
)
|
||||
if path == "/mail/draft":
|
||||
return 200, self.client.create_draft(
|
||||
self._string_list(payload, "to"),
|
||||
self._optional_str(payload, "subject"),
|
||||
self._optional_str(payload, "body"),
|
||||
self._string_list(payload, "cc"),
|
||||
self._optional_str(payload, "content_type", "text") or "text",
|
||||
)
|
||||
if path == "/calendars/events":
|
||||
return 200, self.client.create_event(
|
||||
calendar=self._optional_str(payload, "calendar"),
|
||||
subject=self._required(payload, "subject"),
|
||||
start=self._required(payload, "start"),
|
||||
end=self._optional_str(payload, "end"),
|
||||
all_day=self._optional_bool(payload, "all_day", False),
|
||||
location=self._optional_str(payload, "location"),
|
||||
description=self._optional_str(payload, "description"),
|
||||
attendees=self._string_list(payload, "attendees"),
|
||||
timezone_name=self._optional_str(payload, "timezone"),
|
||||
)
|
||||
if path == "/calendars/events/update":
|
||||
event_id = self._required(payload, "id")
|
||||
changes = {
|
||||
key: payload[key]
|
||||
for key in ("subject", "start", "end", "location", "description")
|
||||
if key in payload
|
||||
}
|
||||
if "all_day" in payload:
|
||||
changes["all_day"] = self._optional_bool(payload, "all_day", False)
|
||||
return 200, self.client.update_event(
|
||||
event_id, timezone_name=self._optional_str(payload, "timezone"), **changes
|
||||
)
|
||||
if path == "/calendars/events/delete":
|
||||
return 200, self.client.delete_event(self._required(payload, "id"))
|
||||
if path == "/tasks":
|
||||
return 200, self.client.create_task(
|
||||
task_list=self._optional_str(payload, "list"),
|
||||
title=self._required(payload, "title"),
|
||||
due=self._optional_str(payload, "due"),
|
||||
importance=self._optional_str(payload, "importance"),
|
||||
description=self._optional_str(payload, "description"),
|
||||
)
|
||||
if path == "/tasks/update":
|
||||
task_id = self._required(payload, "id")
|
||||
changes = {
|
||||
key: payload[key]
|
||||
for key in ("title", "due", "importance", "status", "description")
|
||||
if key in payload
|
||||
}
|
||||
return 200, self.client.update_task(
|
||||
task_id, task_list=self._optional_str(payload, "list"), **changes
|
||||
)
|
||||
if path == "/tasks/complete":
|
||||
return 200, self.client.complete_task(
|
||||
self._required(payload, "id"), task_list=self._optional_str(payload, "list")
|
||||
)
|
||||
if path == "/tasks/delete":
|
||||
return 200, self.client.delete_task(
|
||||
self._required(payload, "id"), task_list=self._optional_str(payload, "list")
|
||||
)
|
||||
if path == "/files/write":
|
||||
return 200, self.client.write_file(
|
||||
self._required(payload, "path"),
|
||||
self._required(payload, "content", allow_empty=True),
|
||||
self._optional_str(payload, "encoding", "utf-8") or "utf-8",
|
||||
self._optional_bool(payload, "overwrite", True),
|
||||
)
|
||||
return 404, {"error": "not found"}
|
||||
|
||||
# ---- input helpers ----
|
||||
|
||||
@staticmethod
|
||||
def _q(query: dict, key: str, default=None):
|
||||
values = query.get(key)
|
||||
if not values:
|
||||
return default
|
||||
return values[0]
|
||||
|
||||
@staticmethod
|
||||
def _required_query(query: dict, key: str) -> str:
|
||||
value = OutlookBridge._q(query, key)
|
||||
if value is None or not str(value).strip():
|
||||
raise ValueError(f"{key} is required")
|
||||
return str(value).strip()
|
||||
|
||||
@staticmethod
|
||||
def _int_query(query: dict, key: str, default: int) -> int:
|
||||
value = OutlookBridge._q(query, key)
|
||||
if value is None or str(value).strip() == "":
|
||||
return default
|
||||
try:
|
||||
return int(str(value))
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"{key} must be an integer") from exc
|
||||
|
||||
@staticmethod
|
||||
def _bool_query(query: dict, key: str, default: bool) -> bool:
|
||||
value = OutlookBridge._q(query, key)
|
||||
if value is None or str(value).strip() == "":
|
||||
return default
|
||||
return str(value).strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
@staticmethod
|
||||
def _required(payload: dict, key: str, allow_empty: bool = False) -> str:
|
||||
value = payload.get(key)
|
||||
if not isinstance(value, str) or (not allow_empty and not value.strip()):
|
||||
raise ValueError(f"{key} is required")
|
||||
return value if allow_empty else value.strip()
|
||||
|
||||
@staticmethod
|
||||
def _optional_str(payload: dict, key: str, default: str = "") -> str:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"{key} must be a string")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _optional_bool(payload: dict, key: str, default: bool) -> bool:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError(f"{key} must be a boolean")
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _string_list(payload: dict, key: str) -> list[str]:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
||||
raise ValueError(f"{key} must be a list of strings")
|
||||
return value
|
||||
File diff suppressed because it is too large.
Load diff
@@ -15,10 +15,16 @@ import threading
|
||||
from .base import BridgeInfo, BridgeService
|
||||
from .llm import LLMBridge
|
||||
from .nextcloud import NextcloudBridge
|
||||
from .outlook import OutlookBridge
|
||||
from .simplex import SimplexBridge
|
||||
|
||||
#: Known bridge services. Order is presentation order.
|
||||
CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge, LLMBridge, NextcloudBridge)
|
||||
CATALOG: tuple[type[BridgeService], ...] = (
|
||||
SimplexBridge,
|
||||
LLMBridge,
|
||||
NextcloudBridge,
|
||||
OutlookBridge,
|
||||
)
|
||||
|
||||
|
||||
def _class_for(name: str) -> type[BridgeService] | None:
|
||||
|
||||
@@ -0,0 +1,646 @@
|
||||
"""Pure-stdlib tests for the Outlook (Microsoft Graph) bridge.
|
||||
|
||||
A loopback `http.server` plays Microsoft's token endpoint and Graph API so the
|
||||
bridge's own client is exercised over HTTP with no mocking of the transport. The
|
||||
decision engine and LLM are never involved. A few route tests inject a fake
|
||||
client to check wiring/validation without a server. Passing these proves
|
||||
mechanics only; a real run against the user's Microsoft account is the only proof
|
||||
the integration works.
|
||||
"""
|
||||
|
||||
import json
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import pytest
|
||||
|
||||
from semif_agent.bridges.outlook import OutlookBridge
|
||||
from semif_agent.bridges.outlook_client import (
|
||||
OutlookAuthRequired,
|
||||
OutlookClient,
|
||||
OutlookError,
|
||||
load_token,
|
||||
run_device_code_flow,
|
||||
save_token,
|
||||
)
|
||||
from semif_agent.bridges.registry import build_bridge, derived_config_vars, describe_bridges, known_infos
|
||||
|
||||
|
||||
class FakeGraph:
|
||||
"""A minimal but real Microsoft-shaped HTTP server (token + Graph)."""
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
self.refresh_calls = 0
|
||||
self.device_polls = 0
|
||||
self.token_status = 200
|
||||
self._server = None
|
||||
self._thread = None
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def start(self):
|
||||
fake = self
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def _read(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
return self.rfile.read(length) if length else b""
|
||||
|
||||
def _send(self, status, payload):
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _dispatch(self, method):
|
||||
body = self._read()
|
||||
fake.calls.append((method, self.path, dict(self.headers), body))
|
||||
status, payload = fake.handle(method, self.path, body)
|
||||
if status == 204:
|
||||
self.send_response(204)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
if isinstance(payload, bytes):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/octet-stream")
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
return
|
||||
self._send(status, payload)
|
||||
|
||||
def do_GET(self):
|
||||
self._dispatch("GET")
|
||||
|
||||
def do_POST(self):
|
||||
self._dispatch("POST")
|
||||
|
||||
def do_PUT(self):
|
||||
self._dispatch("PUT")
|
||||
|
||||
def do_PATCH(self):
|
||||
self._dispatch("PATCH")
|
||||
|
||||
def do_DELETE(self):
|
||||
self._dispatch("DELETE")
|
||||
|
||||
self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
|
||||
self._thread.start()
|
||||
return f"http://127.0.0.1:{self._server.server_address[1]}"
|
||||
|
||||
def stop(self):
|
||||
if self._server is not None:
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
self._server = None
|
||||
|
||||
# ---- routing ----
|
||||
|
||||
def handle(self, method, path, body):
|
||||
parsed = urlparse(path)
|
||||
route = parsed.path
|
||||
query = parse_qs(parsed.query)
|
||||
|
||||
# ---- OAuth token endpoint ----
|
||||
if route.endswith("/oauth2/v2.0/devicecode"):
|
||||
return 200, {
|
||||
"device_code": "dev-code",
|
||||
"user_code": "ABCD-EFGH",
|
||||
"verification_uri": "https://microsoft.com/devicelogin",
|
||||
"interval": 1,
|
||||
"expires_in": 900,
|
||||
"message": "go to https://microsoft.com/devicelogin and enter ABCD-EFGH",
|
||||
}
|
||||
if route.endswith("/oauth2/v2.0/token"):
|
||||
fields = parse_qs(body.decode("utf-8"))
|
||||
grant = (fields.get("grant_type") or [""])[0]
|
||||
if grant == "refresh_token":
|
||||
self.refresh_calls += 1
|
||||
return self.token_status, {
|
||||
"access_token": f"refreshed-{self.refresh_calls}",
|
||||
"refresh_token": f"rotated-{self.refresh_calls}",
|
||||
"expires_in": 3600,
|
||||
"token_type": "Bearer",
|
||||
"scope": "Mail.ReadWrite",
|
||||
}
|
||||
# device-code poll: pending once, then success
|
||||
self.device_polls += 1
|
||||
if self.device_polls < 2:
|
||||
return 400, {"error": "authorization_pending"}
|
||||
return 200, {
|
||||
"access_token": "device-access",
|
||||
"refresh_token": "device-refresh",
|
||||
"expires_in": 3600,
|
||||
"token_type": "Bearer",
|
||||
"scope": "Mail.ReadWrite",
|
||||
}
|
||||
|
||||
# ---- Graph ----
|
||||
if method == "GET" and route == "/v1.0/me":
|
||||
return 200, {
|
||||
"id": "user-1",
|
||||
"displayName": "Jane Doe",
|
||||
"mail": "jane@example.com",
|
||||
"userPrincipalName": "jane@example.com",
|
||||
}
|
||||
if method == "GET" and route == "/v1.0/me/mailFolders":
|
||||
return 200, {
|
||||
"value": [
|
||||
{"id": "inbox", "displayName": "Inbox", "totalItemCount": 3, "unreadItemCount": 1}
|
||||
]
|
||||
}
|
||||
if method == "GET" and route == "/v1.0/me/mailFolders/inbox/messages":
|
||||
return 200, {
|
||||
"value": [
|
||||
{
|
||||
"id": "m1",
|
||||
"subject": "Hello",
|
||||
"from": {"emailAddress": {"name": "Alice", "address": "alice@example.com"}},
|
||||
"toRecipients": [{"emailAddress": {"address": "jane@example.com"}}],
|
||||
"ccRecipients": [],
|
||||
"receivedDateTime": "2026-10-08T09:00:00Z",
|
||||
"isRead": False,
|
||||
"hasAttachments": False,
|
||||
"bodyPreview": "Hi there",
|
||||
"importance": "normal",
|
||||
"webLink": "https://outlook/m1",
|
||||
}
|
||||
]
|
||||
}
|
||||
if method == "GET" and route == "/v1.0/me/messages/m1":
|
||||
return 200, {
|
||||
"id": "m1",
|
||||
"subject": "Hello",
|
||||
"from": {"emailAddress": {"name": "Alice", "address": "alice@example.com"}},
|
||||
"toRecipients": [{"emailAddress": {"address": "jane@example.com"}}],
|
||||
"ccRecipients": [],
|
||||
"receivedDateTime": "2026-10-08T09:00:00Z",
|
||||
"isRead": False,
|
||||
"hasAttachments": False,
|
||||
"body": {"contentType": "text", "content": "Hi there"},
|
||||
"bodyPreview": "Hi there",
|
||||
"importance": "normal",
|
||||
"webLink": "https://outlook/m1",
|
||||
}
|
||||
if method == "POST" and route == "/v1.0/me/sendMail":
|
||||
self.sent = json.loads(body.decode("utf-8"))
|
||||
return 202, {}
|
||||
if method == "POST" and route == "/v1.0/me/messages":
|
||||
payload = json.loads(body.decode("utf-8"))
|
||||
return 201, {"id": "draft-1", "subject": payload.get("subject", "")}
|
||||
if method == "GET" and route == "/v1.0/me/calendars":
|
||||
return 200, {
|
||||
"value": [
|
||||
{"id": "cal1", "name": "Calendar", "color": "auto", "isDefaultCalendar": True, "canEdit": True}
|
||||
]
|
||||
}
|
||||
if method == "GET" and route == "/v1.0/me/calendarView":
|
||||
return 200, {
|
||||
"value": [
|
||||
{
|
||||
"id": "e1",
|
||||
"subject": "Standup",
|
||||
"start": {"dateTime": "2026-10-08T09:00:00.0000000", "timeZone": "UTC"},
|
||||
"end": {"dateTime": "2026-10-08T09:30:00.0000000", "timeZone": "UTC"},
|
||||
"isAllDay": False,
|
||||
"location": {"displayName": "Room 1"},
|
||||
"bodyPreview": "",
|
||||
"showAs": "busy",
|
||||
"isOnlineMeeting": False,
|
||||
"webLink": "https://outlook/e1",
|
||||
"organizer": {"emailAddress": {"address": "jane@example.com"}},
|
||||
}
|
||||
]
|
||||
}
|
||||
if method == "POST" and route == "/v1.0/me/events":
|
||||
payload = json.loads(body.decode("utf-8"))
|
||||
return 201, {
|
||||
"id": "new-event",
|
||||
"subject": payload.get("subject"),
|
||||
"webLink": "https://outlook/new-event",
|
||||
}
|
||||
if method == "PATCH" and route.startswith("/v1.0/me/events/"):
|
||||
payload = json.loads(body.decode("utf-8"))
|
||||
return 200, {"id": route.rsplit("/", 1)[-1], "subject": payload.get("subject", "")}
|
||||
if method == "DELETE" and route.startswith("/v1.0/me/events/"):
|
||||
return 204, {}
|
||||
if method == "GET" and route == "/v1.0/me/todo/lists":
|
||||
return 200, {
|
||||
"value": [
|
||||
{"id": "list1", "displayName": "Tasks", "isOwner": True, "wellknownListName": "defaultList"}
|
||||
]
|
||||
}
|
||||
if method == "GET" and route == "/v1.0/me/todo/lists/list1/tasks":
|
||||
return 200, {
|
||||
"value": [
|
||||
{
|
||||
"id": "t1",
|
||||
"title": "Buy milk",
|
||||
"status": "notStarted",
|
||||
"importance": "normal",
|
||||
"dueDateTime": {"dateTime": "2026-10-10T00:00:00", "timeZone": "UTC"},
|
||||
"completedDateTime": {},
|
||||
"body": {"content": ""},
|
||||
}
|
||||
]
|
||||
}
|
||||
if method == "POST" and route == "/v1.0/me/todo/lists/list1/tasks":
|
||||
payload = json.loads(body.decode("utf-8"))
|
||||
return 201, {"id": "t2", "title": payload.get("title")}
|
||||
if method == "PATCH" and route.startswith("/v1.0/me/todo/lists/list1/tasks/"):
|
||||
payload = json.loads(body.decode("utf-8"))
|
||||
return 200, {"id": route.rsplit("/", 1)[-1], "status": payload.get("status", "notStarted")}
|
||||
if method == "DELETE" and route.startswith("/v1.0/me/todo/lists/list1/tasks/"):
|
||||
return 204, {}
|
||||
if method == "GET" and route == "/v1.0/me/contacts":
|
||||
return 200, {
|
||||
"value": [
|
||||
{
|
||||
"id": "c1",
|
||||
"displayName": "Bob Smith",
|
||||
"givenName": "Bob",
|
||||
"surname": "Smith",
|
||||
"emailAddresses": [{"address": "bob@example.com"}],
|
||||
"businessPhones": ["555-1234"],
|
||||
"homePhones": [],
|
||||
"mobilePhone": None,
|
||||
"companyName": "Acme",
|
||||
"jobTitle": "Dev",
|
||||
}
|
||||
]
|
||||
}
|
||||
if method == "GET" and route == "/v1.0/me/drive/root/children":
|
||||
return 200, {
|
||||
"value": [
|
||||
{
|
||||
"id": "f1",
|
||||
"name": "notes.txt",
|
||||
"size": 5,
|
||||
"lastModifiedDateTime": "2026-10-08T08:00:00Z",
|
||||
"file": {"mimeType": "text/plain"},
|
||||
"parentReference": {"path": "/drive/root:"},
|
||||
"webUrl": "https://onedrive/f1",
|
||||
}
|
||||
]
|
||||
}
|
||||
if route.startswith("/v1.0/me/drive/root:/") and route.endswith(":"):
|
||||
return 200, {
|
||||
"id": "f1",
|
||||
"name": "notes.txt",
|
||||
"size": 5,
|
||||
"file": {"mimeType": "text/plain"},
|
||||
"lastModifiedDateTime": "2026-10-08T08:00:00Z",
|
||||
"webUrl": "https://onedrive/f1",
|
||||
}
|
||||
if route.startswith("/v1.0/me/drive/root:/") and route.endswith("/content"):
|
||||
if method == "GET":
|
||||
return 200, b"hello"
|
||||
return 201, {"id": "f2", "size": 5, "webUrl": "https://onedrive/f2"}
|
||||
|
||||
return 404, {"error": {"code": "notFound", "message": f"no fake route for {method} {route}"}}
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def fake():
|
||||
server = FakeGraph()
|
||||
base = server.start()
|
||||
try:
|
||||
yield server, base
|
||||
finally:
|
||||
server.stop()
|
||||
|
||||
|
||||
def make_client(fake, tmp_path, *, token="tok", expires_at=None, refresh="r1", graph_suffix="/v1.0"):
|
||||
server, base = fake
|
||||
token_path = tmp_path / "token.json"
|
||||
if token is not None:
|
||||
save_token(
|
||||
str(token_path),
|
||||
{
|
||||
"access_token": token,
|
||||
"refresh_token": refresh,
|
||||
"expires_at": 9999999999 if expires_at is None else expires_at,
|
||||
"token_type": "Bearer",
|
||||
},
|
||||
)
|
||||
return OutlookClient(
|
||||
"client-1",
|
||||
tenant="common",
|
||||
token_path=str(token_path),
|
||||
graph=base + graph_suffix,
|
||||
login=base,
|
||||
)
|
||||
|
||||
|
||||
# ---- OAuth ----
|
||||
|
||||
def test_device_code_flow_polls_until_success(fake):
|
||||
server, base = fake
|
||||
lines = []
|
||||
token = run_device_code_flow(
|
||||
"client-1", "common", out=lines.append, sleep=lambda _s: None, login=base
|
||||
)
|
||||
assert token["access_token"] == "device-access"
|
||||
assert token["refresh_token"] == "device-refresh"
|
||||
assert any("ABCD-EFGH" in line for line in lines)
|
||||
assert server.device_polls == 2
|
||||
|
||||
|
||||
def test_token_refresh_on_expiry(fake, tmp_path):
|
||||
server, base = fake
|
||||
client = make_client(fake, tmp_path, token="stale", expires_at=0)
|
||||
user = client.me()
|
||||
assert user["display_name"] == "Jane Doe"
|
||||
assert server.refresh_calls == 1
|
||||
stored = load_token(str(tmp_path / "token.json"))
|
||||
assert stored["access_token"] == "refreshed-1"
|
||||
assert stored["refresh_token"] == "rotated-1"
|
||||
|
||||
|
||||
def test_missing_token_raises_auth_required(tmp_path):
|
||||
client = OutlookClient(
|
||||
"client-1", token_path=str(tmp_path / "missing.json"), graph="http://127.0.0.1:1/v1.0"
|
||||
)
|
||||
with pytest.raises(OutlookAuthRequired):
|
||||
client.me()
|
||||
|
||||
|
||||
def test_not_configured_without_client_id(tmp_path):
|
||||
client = OutlookClient("", token_path=str(tmp_path / "t.json"))
|
||||
assert client.configured is False
|
||||
|
||||
|
||||
# ---- Graph client ----
|
||||
|
||||
def test_me_and_mail(fake, tmp_path):
|
||||
client = make_client(fake, tmp_path)
|
||||
assert client.me()["mail"] == "jane@example.com"
|
||||
folders = client.list_mail_folders()
|
||||
assert folders[0]["name"] == "Inbox"
|
||||
messages = client.list_messages("inbox")
|
||||
assert messages[0]["subject"] == "Hello"
|
||||
assert messages[0]["from"] == "Alice <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 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"
|
||||
Reference in new issue
Block a user