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