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
@@ -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)
|
||||
Reference in new issue
Block a user