Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(microsoft): Microsoft 365 Graph mail + calendar nodes (#100)
José Tomás Guzmán1d97fa176929
diff --git a/cli/commands/build.py b/cli/commands/build.pyindex 0cff1f4f..3ebabe89 100644--- a/cli/commands/build.py+++ b/cli/commands/build.py@@ -247,7 +247,7 @@ def build_command() -> None:# python via pipx) and never shares this environment -- see# ``cli/platform_.py`` docstring for the rationale. ``uv sync``# is idempotent and creates the venv on first run.- run(["uv", "sync"], cwd=server_cwd)+ run(["uv", "sync", "--extra", "docs"], cwd=server_cwd)# Pre-compile our Python sources to plain .pyc. No `-O`: every# runtime (uvicorn via `uv run`, `company serve`'s venv python) runsdiff --git a/client/src/components/credentials/types.ts b/client/src/components/credentials/types.tsindex 129746dc..4d7ee506 100644--- a/client/src/components/credentials/types.ts+++ b/client/src/components/credentials/types.ts@@ -103,7 +103,7 @@ export interface ProviderConfig {/** WebSocket commands for OAuth flows. */ws?: { login: string; logout: string; status: string };/** Which status hook to read. */- statusHook?: 'whatsapp' | 'android' | 'twitter' | 'google' | 'telegram';+ statusHook?: 'whatsapp' | 'android' | 'twitter' | 'google' | 'telegram' | 'microsoft';/** Config-driven status rows (replaces per-provider conditionals). */statusRows?: StatusRowDef[];/** Config-driven actions (replaces per-provider handler code). */diff --git a/client/src/hooks/useCatalogueQuery.ts b/client/src/hooks/useCatalogueQuery.tsindex 5166cf70..48405540 100644--- a/client/src/hooks/useCatalogueQuery.ts+++ b/client/src/hooks/useCatalogueQuery.ts@@ -104,7 +104,7 @@ export interface ServerProviderConfig {icon_ref?: string;fields?: ServerFieldDef[];ws?: { login: string; logout: string; status: string };- status_hook?: 'whatsapp' | 'android' | 'twitter' | 'google' | 'telegram';+ status_hook?: 'whatsapp' | 'android' | 'twitter' | 'google' | 'telegram' | 'microsoft';status_rows?: ServerStatusRowDef[];actions?: ServerActionDef[];qr?: ServerQrDef;diff --git a/client/vite.config.js b/client/vite.config.jsindex b0651803..4fd4f612 100644--- a/client/vite.config.js+++ b/client/vite.config.js@@ -148,12 +148,20 @@ export default defineConfig(({ mode }) => {// uvicorn serves the SPA itself on 5678. Keeps OAuth callback// URLs (…:5678/api/...) valid in both modes and removes the// cross-origin dependence in dev.+ //+ // changeOrigin MUST stay false: the backend derives OAuth redirect+ // URIs from the incoming Host header (services/oauth_utils.get_base_url+ // -> websocket.base_url). changeOrigin:true would rewrite Host to the+ // proxy target (localhost:5679), so the derived redirect URI would be+ // :5679 — breaking the browser-facing :5678 callback the OAuth app is+ // registered with (e.g. Microsoft AADSTS50011 redirect-URI mismatch).+ // Preserving the original Host keeps the :5678 callback correct.proxy: Object.fromEntries(['/api', '/ws', '/webhook', '/health', '/mcp'].map((prefix) => [prefix,{target: `http://localhost:${requireEnv('PYTHON_BACKEND_PORT')}`,- changeOrigin: true,+ changeOrigin: false,ws: prefix === '/ws',},])diff --git a/server/config/credential_providers.json b/server/config/credential_providers.jsonindex 722af537..4dfe072c 100644--- a/server/config/credential_providers.json+++ b/server/config/credential_providers.json@@ -431,6 +431,40 @@"callback_url": "http://localhost:5678/api/google/callback","instructions": "Get credentials from Google Cloud Console. Enable Gmail, Calendar, Drive, Sheets, Tasks, and People APIs."},+ "microsoft": {+ "name": "Microsoft Graph",+ "category": "productivity",+ "category_label": "Productivity",+ "color": "theme.categoryAI",+ "kind": "oauth",+ "icon_ref": "/api/schemas/credentials/microsoft/icon",+ "status_hook": "microsoft",+ "usage_service": "microsoft_graph",+ "ws": {+ "login": "microsoft_oauth_login",+ "logout": "microsoft_logout",+ "status": "microsoft_oauth_status"+ },+ "fields": [+ {+ "key": "microsoft_client_id",+ "label": "Application (client) ID",+ "type": "string",+ "placeholder": "Client ID (from Azure Portal app registration)",+ "required": true+ },+ {+ "key": "microsoft_client_secret",+ "label": "Client Secret",+ "type": "password",+ "secret": true,+ "placeholder": "Client secret VALUE (from Certificates & secrets)",+ "required": true+ }+ ],+ "callback_url": "http://localhost:5678/api/microsoft/callback",+ "instructions": "Register an app in the Azure Portal (Microsoft Entra ID > App registrations). Set the account type to organizational (Work/School), add redirect URI http://localhost:5678/api/microsoft/callback (Web platform), and grant delegated Microsoft Graph permissions: User.Read, Mail.Send, Mail.ReadWrite, Calendars.ReadWrite, offline_access."+ },"email_himalaya": {"name": "Email (IMAP/SMTP)","category": "email",diff --git a/server/config/microsoft_apis.json b/server/config/microsoft_apis.jsonnew file mode 100644index 00000000..2b593c12--- /dev/null+++ b/server/config/microsoft_apis.json@@ -0,0 +1,50 @@+{+ "version": "2026.08",+ "last_updated": "2026-08-03",+ "_source": "https://learn.microsoft.com/en-us/graph/",+ "_note": "Work/School accounts only. Authority is /organizations (Azure AD org accounts). Personal Microsoft accounts are not supported by this integration.",++ "oauth": {+ "authority": "https://login.microsoftonline.com/organizations",+ "auth_uri": "https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize",+ "token_uri": "https://login.microsoftonline.com/organizations/oauth2/v2.0/token",+ "microsoft_callback_path": "/api/microsoft/callback"+ },++ "services": {+ "graph": {+ "name": "Microsoft Graph API",+ "version": "v1.0",+ "base_url": "https://graph.microsoft.com/v1.0",+ "documentation": "https://learn.microsoft.com/en-us/graph/api/overview"+ }+ },++ "scopes": {+ "userinfo": [+ "openid",+ "profile",+ "email",+ "offline_access",+ "User.Read"+ ],+ "mail": [+ "Mail.Send",+ "Mail.ReadWrite",+ "Mail.ReadWrite.Shared",+ "Mail.Send.Shared"+ ],+ "calendar": [+ "Calendars.ReadWrite",+ "Calendars.ReadWrite.Shared"+ ]+ },++ "rate_limits": {+ "_note": "Microsoft Graph is free; throttling is per-app/per-mailbox. See https://learn.microsoft.com/en-us/graph/throttling",+ "graph": {+ "requests_per_10_minutes_per_mailbox": 10000,+ "concurrent_requests_per_mailbox": 4+ }+ }+}diff --git a/server/config/pricing.json b/server/config/pricing.jsonindex c05e4bd0..1985c7b8 100644--- a/server/config/pricing.json+++ b/server/config/pricing.json@@ -202,6 +202,23 @@"contact_search": 0.0,"_default": 0.0},+ "microsoft_graph": {+ "_description": "Microsoft Graph API (Mail + Calendar) - free, throttled per mailbox",+ "_source": "https://learn.microsoft.com/en-us/graph/throttling",+ "_note": "Free API - costs are $0. Analytics bookkeeping only.",+ "mail_send": 0.0,+ "mail_read": 0.0,+ "mail_search": 0.0,+ "mail_reply": 0.0,+ "mail_list_attachments": 0.0,+ "mail_download_attachments": 0.0,+ "event_create": 0.0,+ "event_read": 0.0,+ "event_update": 0.0,+ "event_delete": 0.0,+ "event_list": 0.0,+ "_default": 0.0+ },"twitter": {"_description": "X/Twitter Pay-Per-Use API pricing (per resource/request)","_source": "https://developer.x.com/#pricing",@@ -388,6 +405,18 @@"list": "contact_list","search": "contact_search"},+ "microsoft_graph": {+ "send": "mail_send",+ "read": "mail_read",+ "search": "mail_search",+ "reply": "mail_reply",+ "list_attachments": "mail_list_attachments",+ "download_attachments": "mail_download_attachments",+ "create": "event_create",+ "update": "event_update",+ "delete": "event_delete",+ "list": "event_list"+ },"brave_search": {"web_search": "web_search"},diff --git a/server/constants.py b/server/constants.pyindex 044df4dd..c8713c2b 100644--- a/server/constants.py+++ b/server/constants.py@@ -376,6 +376,7 @@ POLLING_TRIGGER_TYPES: FrozenSet[str] = frozenset("googleGmailReceive","twitterReceive","emailReceive",+ "msMailReceive",])@@ -401,6 +402,7 @@ WORKFLOW_TRIGGER_TYPES: FrozenSet[str] = frozenset("googleGmailReceive","telegramReceive","emailReceive",+ "msMailReceive",])diff --git a/server/nodes/groups.py b/server/nodes/groups.pyindex 2ffda685..5f3ad309 100644--- a/server/nodes/groups.py+++ b/server/nodes/groups.py@@ -45,6 +45,7 @@ register_group(key="utility", metadata={"label": "Utilities", "icon": "🔧", "cregister_group(key="api", metadata={"label": "API & Scraping", "icon": "🕷️", "color": "#ffb86c", "visibility": "dev"})register_group(key="search", metadata={"label": "Search", "icon": "🔍", "color": "#8be9fd", "visibility": "dev"})register_group(key="google", metadata={"label": "Google Workspace", "icon": "asset:google", "color": "#4285F4", "visibility": "dev"})+register_group(key="microsoft", metadata={"label": "Microsoft Graph", "icon": "lobehub:Microsoft", "color": "#0078D4", "visibility": "dev"})register_group(key="scheduler", metadata={"label": "Schedulers", "icon": "📅", "color": "#ff79c6", "visibility": "dev"})register_group(key="proxy", metadata={"label": "Proxy", "icon": "🛡", "color": "#bd93f9", "visibility": "dev"})register_group(key="whatsapp", metadata={"label": "WhatsApp", "icon": "💬", "color": "#25D366", "visibility": "dev"})diff --git a/server/nodes/microsoft/__init__.py b/server/nodes/microsoft/__init__.pynew file mode 100644index 00000000..89b0d1f3--- /dev/null+++ b/server/nodes/microsoft/__init__.py@@ -0,0 +1,45 @@+"""Plugins for the 'microsoft' palette group (Microsoft Graph).++Self-contained plugin folder (Wave 11.H pattern). One folder owns the+Microsoft Graph Email + Calendar surface:++- 2 action plugins — ``mail/`` (``msMail``) and ``calendar/`` (``msCalendar``),+ both usable as AI tools.+- ``_credentials.py`` — :class:`MicrosoftCredential` (OAuth2). Both plugins+ reference this single credential class.+- ``_oauth.py`` — :class:`MicrosoftOAuth` (OAuth2 auth-code + PKCE,+ authority ``/organizations`` — Work/School accounts only).+- ``_auth_helper.py`` — proactive access-token refresh (Graph tokens+ expire ~1h and ``get_oauth_tokens`` does not refresh).+- ``_base.py`` — ``graph_request`` helper + usage tracking.+- ``_handlers.py`` — 3 WebSocket handlers+ (``microsoft_oauth_login`` / ``microsoft_oauth_status`` / ``microsoft_logout``).+- ``_router.py`` — HTTP OAuth callback (``/api/microsoft/callback``).++Self-registration below — the central WS dispatcher, the FastAPI app,+and the status broadcaster pick up the plugin's surface without ever+importing this module by name.+"""++from services.deployment.canary_registry import register_canary_trigger_type+from services.status_broadcaster import register_service_refresh+from services.ws_handler_registry import (+ register_oauth_callback_path,+ register_router,+ register_ws_handlers,+)++from . import _router+from ._handlers import WS_HANDLERS+from ._refresh import refresh_microsoft_status++register_ws_handlers(WS_HANDLERS)+register_router(_router.router, name="microsoft")+register_oauth_callback_path("microsoft", "/api/microsoft/callback")+register_service_refresh(refresh_microsoft_status)++# Opt msMailReceive into the PollingTriggerWorkflow consumer path. The+# per-cycle Temporal activity is emitted by MailReceiveNode.as_poll_activity()+# (auto-collected by the worker); the CloudEvents type must match the+# producer so DeploymentManager's EventType Search Attribute lines up.+register_canary_trigger_type("msMailReceive", "com.opencompany.msmail.message.received")diff --git a/server/nodes/microsoft/_auth_helper.py b/server/nodes/microsoft/_auth_helper.pynew file mode 100644index 00000000..b24d8f9d--- /dev/null+++ b/server/nodes/microsoft/_auth_helper.py@@ -0,0 +1,115 @@+"""Shared Microsoft Graph token helper.++Microsoft Graph access tokens expire in ~1 hour, and+``AuthService.get_oauth_tokens()`` returns the STORED (possibly expired)+access token without refreshing — the generic :class:`Connection` facade+only retries once on 401/403 with the *same* token, so a stale token+would fail twice. This helper proactively refreshes and persists the+access token before a node makes Graph calls (mirroring+``nodes.google._auth_helper.get_google_credentials``).++The AuthService storage layer does not plumb ``token_expiry``, so we+track expiry in-process (``_TOKEN_EXPIRY``). On an unknown / expired+entry (e.g. the first call after a server restart) we refresh once —+a cheap, safe over-refresh — then rely on the cached expiry to skip+refresh on subsequent calls within the token lifetime.+"""++from __future__ import annotations++import time+from typing import Dict, Optional++from core.logging import get_logger++logger = get_logger(__name__)++# user_id -> epoch seconds at which the currently-stored access token expires.+_TOKEN_EXPIRY: Dict[str, float] = {}++# Refresh this many seconds before actual expiry to avoid edge-of-expiry races.+_EXPIRY_MARGIN_SECONDS = 120+++def _needs_refresh(user_id: str) -> bool:+ expiry = _TOKEN_EXPIRY.get(user_id)+ if expiry is None:+ return True # unknown (fresh process / never refreshed here)+ return time.time() >= (expiry - _EXPIRY_MARGIN_SECONDS)+++async def ensure_fresh_microsoft_token(user_id: str = "owner") -> str:+ """Guarantee the stored Microsoft access token is fresh; return it.++ Raises:+ PermissionError: if Microsoft Graph is not connected (no tokens),+ annotated so ``BaseNode.execute`` surfaces the provider and+ emits a ``credential.oauth.runtime_failed`` event.+ """+ from services.plugin.deps import get_auth_service++ auth_service = get_auth_service()+ tokens = await auth_service.get_oauth_tokens("microsoft", customer_id=user_id)+ if not tokens or not tokens.get("access_token"):+ err = PermissionError("Microsoft Graph not connected. Connect via the Credentials modal.")+ err.provider = "microsoft"+ err.reason = "missing"+ err.auth = "oauth2"+ raise err++ if not _needs_refresh(user_id):+ return tokens["access_token"]++ refreshed = await _refresh_and_persist(user_id, tokens)+ return refreshed or tokens["access_token"]+++async def _refresh_and_persist(user_id: str, current_tokens: Dict) -> Optional[str]:+ """Attempt a token refresh; persist the new access + rotated refresh.++ Returns the new access token, or ``None`` if refresh was not possible+ (no refresh token / no client credentials / upstream failure) — the+ caller falls back to the existing (stored) access token in that case.+ """+ from services.plugin.deps import get_auth_service++ from ._oauth import MicrosoftOAuth++ auth_service = get_auth_service()++ refresh_token = await auth_service.get_oauth_refresh_token("microsoft", customer_id=user_id)+ if not refresh_token:+ return None++ client_id = await auth_service.get_api_key("microsoft_client_id") or ""+ client_secret = await auth_service.get_api_key("microsoft_client_secret") or ""+ if not client_id:+ return None++ oauth = MicrosoftOAuth(client_id=client_id, redirect_uri="", client_secret=client_secret or None)+ result = await oauth.refresh_access_token(refresh_token)+ if not result.get("success") or not result.get("access_token"):+ logger.debug(f"[microsoft] token refresh failed: {result.get('error')}")+ return None++ new_access = result["access_token"]+ new_refresh = result.get("refresh_token") or refresh_token+ await auth_service.store_oauth_tokens(+ provider="microsoft",+ access_token=new_access,+ refresh_token=new_refresh,+ email=current_tokens.get("email"),+ name=current_tokens.get("name"),+ scopes=current_tokens.get("scopes"),+ customer_id=user_id,+ )++ expires_in = result.get("expires_in")+ if isinstance(expires_in, (int, float)) and expires_in > 0:+ _TOKEN_EXPIRY[user_id] = time.time() + float(expires_in)+ else:+ # Microsoft access tokens default to ~3600s; assume that.+ _TOKEN_EXPIRY[user_id] = time.time() + 3600.0++ logger.debug("[microsoft] refreshed and persisted access token")+ return new_accessdiff --git a/server/nodes/microsoft/_base.py b/server/nodes/microsoft/_base.pynew file mode 100644index 00000000..f4ae15b1--- /dev/null+++ b/server/nodes/microsoft/_base.py@@ -0,0 +1,247 @@+"""Shared helpers for Microsoft Graph plugins.++Every Microsoft plugin follows the same pattern:++ ensure a fresh access token -> ctx.connection("microsoft").<verb>(url)+ -> response.json() -> track usage -> return Output++``graph_request`` captures the token-freshness + base-URL + error+handling so each ``@Operation`` shrinks to the Graph-specific call ++argument shaping. Graph is plain bearer REST, so — unlike Google — no+SDK object is built; the :class:`Connection` facade injects the token+and retries once on 401/403.+"""++from __future__ import annotations++from typing import Any, Dict, Optional++import httpx++from core.logging import get_logger+from services.plugin import NodeUserError+from services.pricing import get_pricing_service++from ._auth_helper import ensure_fresh_microsoft_token++logger = get_logger(__name__)++GRAPH_BASE_URL = "https://graph.microsoft.com/v1.0"+++def mailbox_base(mailbox: Optional[str] = None) -> str:+ """Return the Graph path prefix for the target mailbox.++ Empty / None -> ``/me`` (the signed-in user's own mailbox, unchanged+ behaviour). A shared/other mailbox address -> ``/users/{address}``.++ Accessing another mailbox over the delegated flow requires the caller+ to have been granted Full Access (and Send As, to send) on it, plus the+ ``.Shared`` OAuth scopes (Mail.ReadWrite.Shared / Mail.Send.Shared /+ Calendars.ReadWrite.Shared) — see microsoft_apis.json.+ """+ addr = (mailbox or "").strip()+ if not addr:+ return "/me"+ # Guard against a path-breaking value; the address becomes a URL segment.+ if "/" in addr or " " in addr:+ raise NodeUserError(f"Invalid mailbox address: {addr!r}")+ return f"/users/{addr}"+++async def graph_request(+ ctx,+ method: str,+ path: str,+ *,+ params: Optional[Dict[str, Any]] = None,+ json: Optional[Any] = None,+) -> Optional[Dict[str, Any]]:+ """Issue an authed Microsoft Graph request.++ Args:+ ctx: NodeContext (provides the Connection factory + user_id).+ method: HTTP verb.+ path: Graph path beginning with ``/`` (appended to ``GRAPH_BASE_URL``),+ or an absolute URL (used verbatim, e.g. an ``@odata.nextLink``).+ params: Query string params.+ json: JSON request body.++ Returns:+ Parsed JSON dict, or ``None`` for empty-body responses (e.g. 202+ from sendMail, 204 from delete).++ Raises:+ NodeUserError: on a non-2xx Graph response, carrying Graph's own+ error message so the user/LLM can correct the input.+ """+ # Guarantee the STORED access token is fresh before the Connection+ # facade resolves + injects it (get_oauth_tokens does not refresh).+ await ensure_fresh_microsoft_token(getattr(ctx, "user_id", "owner"))++ url = path if path.startswith("http") else f"{GRAPH_BASE_URL}{path}"++ async with ctx.connection("microsoft") as conn:+ response = await conn.request(method, url, params=params, json=json)++ if response.status_code >= 400:+ raise NodeUserError(_format_graph_error(response))++ if response.status_code == 204 or not response.content:+ return None+ try:+ return response.json()+ except (ValueError, httpx.DecodingError):+ return None+++async def graph_get_raw(+ path: str,+ *,+ params: Optional[Dict[str, Any]] = None,+ user_id: str = "owner",+) -> Dict[str, Any]:+ """Authed Graph GET for contexts without a NodeContext / Connection.++ The polling-trigger hooks (``fetch_ids`` / ``fetch_detail``) run inside+ the deployment loop and the Temporal poll activity — neither has a+ ``ctx`` to source the :class:`Connection` factory from. This helper+ resolves a fresh token via :func:`ensure_fresh_microsoft_token` and+ issues a plain httpx GET with the bearer header.++ Raises:+ NodeUserError: on a non-2xx Graph response.+ """+ token = await ensure_fresh_microsoft_token(user_id)+ url = path if path.startswith("http") else f"{GRAPH_BASE_URL}{path}"+ async with httpx.AsyncClient(timeout=30.0) as client:+ response = await client.get(url, params=params, headers={"Authorization": f"Bearer {token}"})+ if response.status_code >= 400:+ raise NodeUserError(_format_graph_error(response))+ if not response.content:+ return {}+ try:+ return response.json()+ except (ValueError, httpx.DecodingError):+ return {}+++async def mark_message_read_raw(message_id: str, *, mailbox: Optional[str] = None, user_id: str = "owner") -> None:+ """PATCH a message's ``isRead`` flag to true (ctx-free; best-effort caller).++ ``mailbox`` targets a shared/other mailbox (``/users/{addr}``); empty = ``/me``.+ """+ token = await ensure_fresh_microsoft_token(user_id)+ url = f"{GRAPH_BASE_URL}{mailbox_base(mailbox)}/messages/{message_id}"+ async with httpx.AsyncClient(timeout=30.0) as client:+ await client.patch(url, json={"isRead": True}, headers={"Authorization": f"Bearer {token}"})+++def _format_graph_error(response: httpx.Response) -> str:+ """Extract Microsoft Graph's structured error message for a user-facing warning."""+ try:+ body = response.json()+ except (ValueError, httpx.DecodingError):+ body = None+ if isinstance(body, dict):+ err = body.get("error")+ if isinstance(err, dict):+ code = err.get("code", "")+ message = err.get("message", "")+ detail = f"{code}: {message}".strip(": ") if (code or message) else ""+ if detail:+ return f"Microsoft Graph error ({response.status_code}): {detail}"+ return f"Microsoft Graph request failed with HTTP {response.status_code}"+++def write_attachment_bytes(payload, *, ctx, filename, mime_type=None):+ """Write attachment bytes into the workspace; return ``(FileRef, abs_path)``.++ Mirrors ``services.media.workspace.write_audio``'s proven pattern+ (workspace_root -> resolve_media -> atomic_write_bytes) but returns a+ plain ``kind="file"`` :class:`FileRef` rather than an ``AudioRef`` — a PDF+ is not audio and must never claim ``kind="audio"`` (that asserts an+ ``inspect_audio`` probe that never ran). Files land under+ ``<workspace>/attachments/`` with a random-suffixed name so retries and+ repeated runs never collide or overwrite.++ The absolute path is returned alongside the ref because the downstream+ ``documentParser`` node consumes a plain path string (``file_path`` /+ ``input_dir``), not a FileRef.++ Raises:+ NodeUserError: on empty payload.+ """+ import hashlib+ import mimetypes+ from uuid import uuid4++ from nodes.filesystem._backend import atomic_write_bytes+ from services.media.refs import FileRef+ from services.media.workspace import _slugify, resolve_media, workspace_file_url, workspace_root+ from services.plugin import NodeUserError++ if not payload:+ raise NodeUserError("Refusing to write an empty attachment file.")++ root = workspace_root(ctx)+ node_id = str(getattr(ctx, "node_id", "") or "node")+ workflow_id = getattr(ctx, "workflow_id", None)++ # Preserve the real extension (documentParser globs on *.pdf); slugify the stem.+ dot = filename.rfind(".") if filename else -1+ stem = filename[:dot] if dot > 0 else (filename or "attachment")+ ext = filename[dot + 1 :].lower() if dot > 0 else ""+ safe = f"{_slugify(stem)}-{node_id[:8]}-{uuid4().hex[:6]}"+ name = f"{safe}.{ext}" if ext else safe+ rel = f"attachments/{name}"++ target = resolve_media(rel, ctx=ctx)+ target.parent.mkdir(parents=True, exist_ok=True)+ atomic_write_bytes(target, payload, root_dir=root)++ ref = FileRef(+ kind="file",+ path=rel,+ workflow_id=workflow_id,+ filename=filename or name,+ mime_type=mime_type or mimetypes.guess_type(filename or name)[0] or "application/octet-stream",+ size_bytes=len(payload),+ sha256=hashlib.sha256(payload).hexdigest(),+ url=workspace_file_url(workflow_id, rel),+ )+ return ref, str(target)+++async def track_microsoft_usage(+ node_id: str,+ action: str,+ resource_count: int,+ context: Dict[str, Any],+) -> Dict[str, float]:+ """Record a Microsoft Graph call in ``api_usage_metrics``.++ ``action`` maps through ``pricing.json``'s ``microsoft_graph``+ operation_map (send / read / search / reply / create / update /+ delete / list). Graph is free at our tier — analytics bookkeeping,+ cost is $0.+ """+ from services.plugin.deps import get_database++ pricing = get_pricing_service()+ cost_data = pricing.calculate_api_cost("microsoft_graph", action, resource_count)++ db = get_database()+ await db.save_api_usage_metric(+ {+ "session_id": context.get("session_id", "default"),+ "node_id": node_id,+ "workflow_id": context.get("workflow_id"),+ "service": "microsoft_graph",+ "operation": cost_data.get("operation", action),+ "endpoint": action,+ "resource_count": resource_count,+ "cost": cost_data.get("total_cost", 0.0),+ }+ )+ return cost_datadiff --git a/server/nodes/microsoft/_credentials.py b/server/nodes/microsoft/_credentials.pynew file mode 100644index 00000000..759b6482--- /dev/null+++ b/server/nodes/microsoft/_credentials.py@@ -0,0 +1,52 @@+"""Microsoft Graph credential (OAuth2).++Shared by the Microsoft plugins in this folder — ``msMail`` and+``msCalendar``. Unlike Google (which needs a+``google.oauth2.credentials.Credentials`` object for the googleapiclient+SDK), Microsoft Graph is plain bearer REST, so these plugins use the+:class:`services.plugin.connection.Connection` facade and this credential+only needs the standard :meth:`OAuth2Credential.resolve` /+:meth:`OAuth2Credential.inject` (``Authorization: Bearer <token>``).++OAuth flow (authorization_url / token_url / scopes) is owned by+:mod:`nodes.microsoft._oauth`; this class is the plugin-facing interface++ Credentials-modal metadata + runtime token injection.+"""++from __future__ import annotations++from typing import ClassVar++from services.plugin.credential import OAuth2Credential++from ._oauth import get_oauth_endpoints++_ENDPOINTS = get_oauth_endpoints()+++class MicrosoftCredential(OAuth2Credential):+ id = "microsoft"+ display_name = "Microsoft Graph"+ category = "Productivity"+ authorization_url = _ENDPOINTS["auth_uri"]+ token_url = _ENDPOINTS["token_uri"]+ client_id_api_key = "microsoft_client_id"+ client_secret_api_key = "microsoft_client_secret"+ docs_url = "https://learn.microsoft.com/en-us/graph/overview"++ # Access token rides as a bearer header (OAuth2Credential defaults:+ # token_location="header", token_header="Authorization", prefix="Bearer ").++ # Scope union across the Microsoft plugins. Single source of truth:+ # :data:`nodes.microsoft._oauth.MICROSOFT_GRAPH_SCOPES`, exposed lazily+ # to avoid import-cycle risk during credential auto-discovery.+ scopes: ClassVar[tuple] = ()++ @classmethod+ def get_scopes(cls) -> tuple:+ """Return the live scope list (lazy import)."""+ if not cls.scopes:+ from nodes.microsoft._oauth import MICROSOFT_GRAPH_SCOPES++ cls.scopes = tuple(MICROSOFT_GRAPH_SCOPES)+ return cls.scopesdiff --git a/server/nodes/microsoft/_handlers.py b/server/nodes/microsoft/_handlers.pynew file mode 100644index 00000000..ad8393e9--- /dev/null+++ b/server/nodes/microsoft/_handlers.py@@ -0,0 +1,56 @@+"""Microsoft Graph WebSocket handlers — factory-built.++The 3 handlers (``microsoft_oauth_login`` / ``microsoft_oauth_status`` /+``microsoft_logout``) come from+:func:`services.events.oauth_lifecycle.make_oauth_lifecycle_handlers`.+No ``legacy_status_broadcast`` — Microsoft is a new provider with no+pre-existing frontend frame; the modal reads status via the unified+``credential_catalogue_updated`` envelope + ``config.stored``.++The factory pulls ``microsoft_client_id`` + ``microsoft_client_secret``+from ``auth_service`` inside :func:`_microsoft_oauth_factory` and+constructs a :class:`MicrosoftOAuth` per call.+"""++from __future__ import annotations++from typing import Any, Dict, Optional++from services.events.oauth_lifecycle import make_oauth_lifecycle_handlers++from ._oauth import MicrosoftOAuth+++async def _microsoft_oauth_factory(+ *,+ redirect_uri: Optional[str] = None,+ **_kwargs,+) -> MicrosoftOAuth:+ """Build a :class:`MicrosoftOAuth` from stored client credentials."""+ from services.plugin.deps import get_auth_service++ auth_service = get_auth_service()+ client_id = await auth_service.get_api_key("microsoft_client_id") or ""+ client_secret = await auth_service.get_api_key("microsoft_client_secret") or ""+ return MicrosoftOAuth(+ client_id=client_id,+ client_secret=client_secret or None,+ redirect_uri=redirect_uri or "",+ )+++def _user_info_to_email(info: Dict[str, Any]) -> str:+ return info.get("email", "Unknown") or "Unknown"+++WS_HANDLERS = make_oauth_lifecycle_handlers(+ provider="microsoft",+ oauth_factory=_microsoft_oauth_factory,+ user_info_to_subject=_user_info_to_email,+)+++# Module-level aliases so contract tests can import handlers by name.+handle_microsoft_oauth_login = WS_HANDLERS["microsoft_oauth_login"]+handle_microsoft_oauth_status = WS_HANDLERS["microsoft_oauth_status"]+handle_microsoft_logout = WS_HANDLERS["microsoft_logout"]diff --git a/server/nodes/microsoft/_oauth.py b/server/nodes/microsoft/_oauth.pynew file mode 100644index 00000000..b255060f--- /dev/null+++ b/server/nodes/microsoft/_oauth.py@@ -0,0 +1,171 @@+"""Microsoft Graph OAuth 2.0 client (Work/School accounts).++Subclasses :class:`services.plugin.oauth.OAuth2PKCEClient` (the Twitter+pattern) — the base owns the PKCE state store, code-verifier generation,+code exchange, token refresh, and revocation. This file declares the+Microsoft-specific endpoints, scopes, ``fetch_user_info`` translation,+and one override: the Microsoft identity platform token endpoint expects+``client_id`` + ``client_secret`` as form-body parameters, NOT HTTP Basic+auth (which the base uses by default for confidential clients).++Endpoints + scopes are read from ``server/config/microsoft_apis.json``+(authority ``/organizations`` — organizational Work/School accounts only).+A hardcoded fallback keeps the module importable if the config is absent.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any, ClassVar, Dict, List, Optional, Tuple++import httpx++from core.logging import get_logger+from services.plugin.oauth import OAuth2PKCEClient, OAuthStateStore++logger = get_logger(__name__)++# Microsoft Graph user-info endpoint (the profile of the signed-in user).+USER_INFO_URL = "https://graph.microsoft.com/v1.0/me"++# Hardcoded fallbacks (authority /organizations). Overridden by config.+_DEFAULT_AUTHORIZATION_URL = "https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize"+_DEFAULT_TOKEN_URL = "https://login.microsoftonline.com/organizations/oauth2/v2.0/token"++_DEFAULT_SCOPES = [+ "openid",+ "profile",+ "email",+ "offline_access", # enables refresh tokens+ "User.Read",+ "Mail.Send",+ "Mail.ReadWrite",+ "Calendars.ReadWrite",+]+++def _config_path() -> Path:+ # server/nodes/microsoft/_oauth.py -> parents[2] == server/+ return Path(__file__).resolve().parents[2] / "config" / "microsoft_apis.json"+++def _load_config() -> Dict[str, Any]:+ try:+ with _config_path().open("r", encoding="utf-8") as fh:+ return json.load(fh)+ except (OSError, ValueError) as exc:+ logger.debug(f"[microsoft] microsoft_apis.json unavailable, using defaults: {exc}")+ return {}+++def get_oauth_endpoints() -> Dict[str, str]:+ """Return ``{auth_uri, token_uri}`` from config (or defaults)."""+ oauth = _load_config().get("oauth", {})+ return {+ "auth_uri": oauth.get("auth_uri", _DEFAULT_AUTHORIZATION_URL),+ "token_uri": oauth.get("token_uri", _DEFAULT_TOKEN_URL),+ }+++def get_all_scopes() -> List[str]:+ """Flatten every scope block in config into one deduplicated list."""+ scopes_cfg = _load_config().get("scopes")+ if not scopes_cfg:+ return list(_DEFAULT_SCOPES)+ seen: Dict[str, None] = {}+ for block in scopes_cfg.values():+ for scope in block:+ seen.setdefault(scope, None)+ return list(seen.keys()) if seen else list(_DEFAULT_SCOPES)+++# Single source of truth for the credential scope union.+MICROSOFT_GRAPH_SCOPES: List[str] = get_all_scopes()++_ENDPOINTS = get_oauth_endpoints()+++class MicrosoftOAuth(OAuth2PKCEClient):+ """Microsoft Graph OAuth 2.0 client (authorization-code + PKCE)."""++ provider = "microsoft"+ authorization_endpoint = _ENDPOINTS["auth_uri"]+ token_endpoint = _ENDPOINTS["token_uri"]+ # Microsoft has no OAuth token-revocation endpoint; logout clears the+ # stored tokens locally. revoke_token() is a no-op (base handles the+ # empty ``revocation_endpoint`` by returning {"success": True, "skipped"}).+ revocation_endpoint = ""++ # Plugin-scoped state store — isolated from Google's / Twitter's.+ state_store = OAuthStateStore()++ DEFAULT_SCOPES: ClassVar[List[str]] = MICROSOFT_GRAPH_SCOPES++ def __init__(+ self,+ client_id: str,+ redirect_uri: str,+ client_secret: Optional[str] = None,+ scopes: Optional[List[str]] = None,+ ) -> None:+ super().__init__(+ client_id=client_id,+ redirect_uri=redirect_uri,+ client_secret=client_secret,+ scopes=scopes,+ )++ def _token_request_auth(self) -> Tuple[Dict[str, str], Dict[str, str]]:+ """Microsoft identity platform expects the client credentials in+ the request BODY, not HTTP Basic auth. Override the base (which+ would send ``Authorization: Basic``) to put ``client_id`` ++ ``client_secret`` in the form body — the documented shape for the+ v2.0 token endpoint.++ See: https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow#redeem-a-code-for-an-access-token+ """+ body = {"client_id": self.client_id}+ if self.client_secret:+ body["client_secret"] = self.client_secret+ return body, {}++ async def fetch_user_info(self, access_token: str) -> Dict[str, Any]:+ """Translate Graph ``/me`` into the unified user-info shape.++ Work/School accounts populate ``mail``; when null (some org+ mailboxes) fall back to ``userPrincipalName``.+ """+ try:+ async with httpx.AsyncClient(timeout=30.0) as client:+ response = await client.get(+ USER_INFO_URL,+ headers={"Authorization": f"Bearer {access_token}"},+ )+ except httpx.HTTPError as exc:+ logger.error(f"[microsoft] HTTP error getting user info: {exc}")+ return {"success": False, "error": str(exc)}++ if response.status_code != 200:+ error_data = response.json() if response.text else {}+ err = error_data.get("error", {})+ message = err.get("message") if isinstance(err, dict) else str(err)+ return {"success": False, "error": message or "Failed to get user info"}++ user = response.json()+ email = user.get("mail") or user.get("userPrincipalName") or "Unknown"+ return {+ "success": True,+ "id": user.get("id"),+ "email": email,+ "name": user.get("displayName", ""),+ }+++__all__ = [+ "MicrosoftOAuth",+ "MICROSOFT_GRAPH_SCOPES",+ "USER_INFO_URL",+ "get_oauth_endpoints",+ "get_all_scopes",+]diff --git a/server/nodes/microsoft/_refresh.py b/server/nodes/microsoft/_refresh.pynew file mode 100644index 00000000..8881ac0b--- /dev/null+++ b/server/nodes/microsoft/_refresh.py@@ -0,0 +1,46 @@+"""Microsoft Graph service-status refresh callback.++Registered via ``status_broadcaster.register_service_refresh``. Reads+OAuth tokens via ``auth_service.get_oauth_tokens("microsoft")`` and+mirrors the connected/disconnected state into the broadcaster cache so+a freshly-connected client reflects status on the next refresh cycle.+"""++from __future__ import annotations++import logging+from typing import TYPE_CHECKING++from opentelemetry import trace++if TYPE_CHECKING:+ from services.status_broadcaster import StatusBroadcaster++logger = logging.getLogger(__name__)+tracer = trace.get_tracer(__name__)+++async def refresh_microsoft_status(broadcaster: "StatusBroadcaster") -> None:+ """Refresh Microsoft cache. One pass per ``_refresh_all_services`` cycle."""+ with tracer.start_as_current_span("broadcaster.refresh_microsoft") as span:+ try:+ from services.plugin.deps import get_auth_service++ auth_service = get_auth_service()+ tokens = await auth_service.get_oauth_tokens("microsoft", customer_id="owner")+ if not tokens or not tokens.get("access_token"):+ broadcaster._status["microsoft"] = {+ "connected": False,+ "email": None,+ "name": None,+ }+ else:+ broadcaster._status["microsoft"] = {+ "connected": True,+ "email": tokens.get("email"),+ "name": tokens.get("name"),+ }+ span.set_attribute("connected", bool(broadcaster._status["microsoft"]["connected"]))+ except Exception as exc: # noqa: BLE001+ span.record_exception(exc)+ logger.debug("[StatusBroadcaster] Could not refresh Microsoft status: %s", exc)diff --git a/server/nodes/microsoft/_router.py b/server/nodes/microsoft/_router.pynew file mode 100644index 00000000..a2e9eb4f--- /dev/null+++ b/server/nodes/microsoft/_router.py@@ -0,0 +1,27 @@+"""Microsoft Graph OAuth callback router — factory-built.++Mounts ``GET /api/microsoft/callback`` via+:func:`services.events.oauth_lifecycle.make_oauth_callback_router`. The+factory owns the code exchange, token storage, XSS-safe success/error+page, and the ``credential.oauth.connected`` broadcast.+"""++from __future__ import annotations++from typing import Any, Dict++from services.events.oauth_lifecycle import make_oauth_callback_router++from ._handlers import _microsoft_oauth_factory+++def _user_info_to_email(info: Dict[str, Any]) -> str:+ return info.get("email", "Unknown") or "Unknown"+++router = make_oauth_callback_router(+ provider="microsoft",+ oauth_factory=_microsoft_oauth_factory,+ user_info_to_email=_user_info_to_email,+ color_hex="#0078D4",+)diff --git a/server/nodes/microsoft/calendar/__init__.py b/server/nodes/microsoft/calendar/__init__.pynew file mode 100644index 00000000..300d9c74--- /dev/null+++ b/server/nodes/microsoft/calendar/__init__.py@@ -0,0 +1,249 @@+"""Outlook Calendar via Microsoft Graph — multi-op ActionNode + AI tool.++Operations (dispatched off ``params.operation``):+- create -> POST /me/events+- list -> GET /me/calendarView?startDateTime=&endDateTime=+- update -> PATCH /me/events/{id}+- delete -> DELETE /me/events/{id}++Times are ISO 8601. ``list`` accepts ``today`` / ``today+Nd`` shortcuts+for the start/end window (mirrors the Google Calendar node).+"""++from __future__ import annotations++from datetime import datetime, timedelta+from typing import List, Literal, Optional++from pydantic import BaseModel, ConfigDict, Field++from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue++from .._base import graph_request, mailbox_base, track_microsoft_usage+from .._credentials import MicrosoftCredential++_CREATE = {"displayOptions": {"show": {"operation": ["create"]}}}+_LIST = {"displayOptions": {"show": {"operation": ["list"]}}}+_UPDATE = {"displayOptions": {"show": {"operation": ["update"]}}}+_UPDATE_OR_DELETE = {"displayOptions": {"show": {"operation": ["update", "delete"]}}}+++class CalendarParams(BaseModel):+ operation: Literal["create", "list", "update", "delete"] = "list"++ # Target mailbox calendar. Empty = your own; a shared mailbox address+ # (/users/{addr}) requires Full Access + Calendars.ReadWrite.Shared.+ mailbox: str = Field(default="", description="Shared mailbox address (empty = your own calendar).")++ event_id: str = Field(default="", json_schema_extra=_UPDATE_OR_DELETE)++ # Create+ title: str = Field(default="", json_schema_extra=_CREATE)+ body: str = Field(default="", json_schema_extra={"rows": 3, **_CREATE})+ start_time: str = Field(+ default="",+ json_schema_extra={"placeholder": "2026-08-10T14:00:00", **_CREATE},+ )+ end_time: str = Field(+ default="",+ json_schema_extra={"placeholder": "2026-08-10T15:00:00", **_CREATE},+ )+ location: str = Field(default="", json_schema_extra=_CREATE)+ attendees: str = Field(+ default="",+ json_schema_extra={"placeholder": "[email protected], [email protected]", **_CREATE},+ )+ timezone: str = Field(default="UTC", json_schema_extra=_CREATE)++ # List+ start_date: str = Field(default="", json_schema_extra={"placeholder": "today", **_LIST})+ end_date: str = Field(default="", json_schema_extra={"placeholder": "today+7d", **_LIST})+ max_results: int = Field(default=10, ge=1, le=250, json_schema_extra=_LIST)++ # Update+ update_title: str = Field(default="", json_schema_extra=_UPDATE)+ update_start_time: str = Field(default="", json_schema_extra=_UPDATE)+ update_end_time: str = Field(default="", json_schema_extra=_UPDATE)+ update_body: str = Field(default="", json_schema_extra={"rows": 3, **_UPDATE})+ update_location: str = Field(default="", json_schema_extra=_UPDATE)++ model_config = ConfigDict(extra="ignore")+++class CalendarOutput(BaseModel):+ operation: Optional[str] = None+ event_id: Optional[str] = None+ title: Optional[str] = None+ start: Optional[str] = None+ end: Optional[str] = None+ web_link: Optional[str] = None+ location: Optional[str] = None+ events: Optional[List[dict]] = None+ count: Optional[int] = None+ time_range: Optional[dict] = None+ deleted: Optional[bool] = None++ model_config = ConfigDict(extra="allow")+++def _iso_or_shortcut(value: str, default_offset_days: int = 0) -> str:+ """Resolve ISO datetime or ``today`` / ``today+Nd`` shortcut to ISO 8601."""+ now = datetime.utcnow()+ if not value or value.lower() == "today":+ base = now.replace(hour=0, minute=0, second=0, microsecond=0) if default_offset_days == 0 else now + timedelta(days=default_offset_days)+ return base.isoformat()+ if value.startswith("today+"):+ days = int(value.replace("today+", "").replace("d", ""))+ return (now + timedelta(days=days)).isoformat()+ return value+++def _attendees(raw: str) -> list:+ parts = [p.strip() for chunk in raw.split(",") for p in chunk.split(";")]+ return [{"emailAddress": {"address": addr}, "type": "required"} for addr in parts if addr]+++def _summarize(ev: dict) -> dict:+ return {+ "event_id": ev.get("id"),+ "title": ev.get("subject", "No Title"),+ "start": (ev.get("start") or {}).get("dateTime"),+ "end": (ev.get("end") or {}).get("dateTime"),+ "location": (ev.get("location") or {}).get("displayName", ""),+ "organizer": ((ev.get("organizer") or {}).get("emailAddress") or {}).get("address", ""),+ "web_link": ev.get("webLink"),+ "is_all_day": ev.get("isAllDay"),+ }+++class CalendarNode(ActionNode):+ type = "msCalendar"+ display_name = "Outlook Calendar"+ subtitle = "Event Management"+ group = ("microsoft", "tool")+ description = "Microsoft Outlook Calendar create / list / update / delete events via Graph (workflow + AI tool)"+ component_kind = "square"+ tool_name = "ms_calendar"+ tool_description = (+ "Manage Outlook Calendar events via Microsoft Graph. Operations: "+ "create (new event), list (events in a date range), update (modify event), delete (remove event)."+ )+ handles = (+ {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},+ )+ credentials = (MicrosoftCredential,)+ annotations = {"destructive": False, "readonly": False, "open_world": True}+ task_queue = TaskQueue.REST_API+ usable_as_tool = True++ Params = CalendarParams+ Output = CalendarOutput++ @Operation("dispatch")+ async def dispatch(self, ctx: NodeContext, params: CalendarParams) -> CalendarOutput:+ op = params.operation+ if op == "create":+ return await self._create(ctx, params)+ if op == "list":+ return await self._list(ctx, params)+ if op == "update":+ return await self._update(ctx, params)+ if op == "delete":+ return await self._delete(ctx, params)+ raise NodeUserError(f"Unknown Calendar operation: {op}")++ async def _create(self, ctx: NodeContext, params: CalendarParams) -> CalendarOutput:+ if not params.title:+ raise NodeUserError("Event title is required")+ if not params.start_time or not params.end_time:+ raise NodeUserError("Start time and end time are required")++ event = {+ "subject": params.title,+ "start": {"dateTime": params.start_time, "timeZone": params.timezone},+ "end": {"dateTime": params.end_time, "timeZone": params.timezone},+ }+ if params.body:+ event["body"] = {"contentType": "Text", "content": params.body}+ if params.location:+ event["location"] = {"displayName": params.location}+ if params.attendees:+ event["attendees"] = _attendees(params.attendees)++ result = await graph_request(ctx, "POST", f"{mailbox_base(params.mailbox)}/events", json=event)+ await track_microsoft_usage(ctx.node_id, "create", 1, ctx.raw)+ summary = _summarize(result or {})+ return CalendarOutput(+ operation="create",+ event_id=summary["event_id"],+ title=summary["title"],+ start=summary["start"],+ end=summary["end"],+ location=summary["location"],+ web_link=summary["web_link"],+ )++ async def _list(self, ctx: NodeContext, params: CalendarParams) -> CalendarOutput:+ start = _iso_or_shortcut(params.start_date)+ end = _iso_or_shortcut(params.end_date, default_offset_days=7)+ data = await graph_request(+ ctx,+ "GET",+ f"{mailbox_base(params.mailbox)}/calendarView",+ params={+ "startDateTime": start,+ "endDateTime": end,+ "$top": min(params.max_results, 250),+ "$orderby": "start/dateTime",+ "$select": "id,subject,start,end,location,organizer,webLink,isAllDay",+ },+ )+ items = (data or {}).get("value", [])+ formatted = [_summarize(e) for e in items]+ await track_microsoft_usage(ctx.node_id, "list", len(formatted), ctx.raw)+ return CalendarOutput(+ operation="list",+ events=formatted,+ count=len(formatted),+ time_range={"start": start, "end": end},+ )++ async def _update(self, ctx: NodeContext, params: CalendarParams) -> CalendarOutput:+ if not params.event_id:+ raise NodeUserError("Event ID is required")++ patch: dict = {}+ if params.update_title:+ patch["subject"] = params.update_title+ if params.update_start_time:+ patch["start"] = {"dateTime": params.update_start_time, "timeZone": params.timezone}+ if params.update_end_time:+ patch["end"] = {"dateTime": params.update_end_time, "timeZone": params.timezone}+ if params.update_body:+ patch["body"] = {"contentType": "Text", "content": params.update_body}+ if params.update_location:+ patch["location"] = {"displayName": params.update_location}++ if not patch:+ raise NodeUserError("No update fields provided")++ result = await graph_request(ctx, "PATCH", f"{mailbox_base(params.mailbox)}/events/{params.event_id}", json=patch)+ await track_microsoft_usage(ctx.node_id, "update", 1, ctx.raw)+ summary = _summarize(result or {})+ return CalendarOutput(+ operation="update",+ event_id=summary["event_id"] or params.event_id,+ title=summary["title"],+ start=summary["start"],+ end=summary["end"],+ location=summary["location"],+ web_link=summary["web_link"],+ )++ async def _delete(self, ctx: NodeContext, params: CalendarParams) -> CalendarOutput:+ if not params.event_id:+ raise NodeUserError("Event ID is required")+ await graph_request(ctx, "DELETE", f"{mailbox_base(params.mailbox)}/events/{params.event_id}")+ await track_microsoft_usage(ctx.node_id, "delete", 1, ctx.raw)+ return CalendarOutput(operation="delete", deleted=True, event_id=params.event_id)diff --git a/server/nodes/microsoft/calendar/icon.svg b/server/nodes/microsoft/calendar/icon.svgnew file mode 100644index 00000000..5b31d788--- /dev/null+++ b/server/nodes/microsoft/calendar/icon.svg@@ -0,0 +1,6 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="48" height="48">+ <path fill="#1a75d2" d="M8 10h32a2 2 0 0 1 2 2v28a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V12a2 2 0 0 1 2-2z"/>+ <path fill="#fff" d="M8 18h34v2H8z"/>+ <path fill="#fff" d="M14 8a2 2 0 0 1 2 2v4a2 2 0 0 1-4 0v-4a2 2 0 0 1 2-2zM34 8a2 2 0 0 1 2 2v4a2 2 0 0 1-4 0v-4a2 2 0 0 1 2-2z"/>+ <path fill="#fff" d="M13 24h6v6h-6zM21 24h6v6h-6zM29 24h6v6h-6zM13 32h6v6h-6zM21 32h6v6h-6z"/>+</svg>diff --git a/server/nodes/microsoft/calendar/meta.json b/server/nodes/microsoft/calendar/meta.jsonnew file mode 100644index 00000000..6fc307dd--- /dev/null+++ b/server/nodes/microsoft/calendar/meta.json@@ -0,0 +1 @@+{"color": "#0078D4"}diff --git a/server/nodes/microsoft/mail/__init__.py b/server/nodes/microsoft/mail/__init__.pynew file mode 100644index 00000000..5e816160--- /dev/null+++ b/server/nodes/microsoft/mail/__init__.py@@ -0,0 +1,411 @@+"""Outlook Mail via Microsoft Graph — multi-op ActionNode + AI tool.++Operations (dispatched off ``params.operation``):+- send -> POST /me/sendMail+- read -> GET /me/messages/{id} (or GET /me/messages?$top= when no id)+- search -> GET /me/messages?$search="..."+- reply -> POST /me/messages/{id}/reply+- list_attachments -> GET /me/messages/{id}/attachments?$select=... (metadata only)+- download_attachments -> GET /me/messages/{id}/attachments (base64 contentBytes ->+ workspace files); pairs with the documentParser node for text.++The optional ``mailbox`` param retargets every op to a shared/other mailbox+(``/users/{address}`` instead of ``/me``); empty keeps the signed-in user's+own mailbox. Requires Full Access (+ Send As to send) on that mailbox and the+.Shared OAuth scopes.+"""++from __future__ import annotations++import base64+from typing import List, Literal, Optional++from pydantic import BaseModel, ConfigDict, Field++from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue++from .._base import graph_request, mailbox_base, track_microsoft_usage, write_attachment_bytes+from .._credentials import MicrosoftCredential++_SEND = {"displayOptions": {"show": {"operation": ["send"]}}}+_READ = {"displayOptions": {"show": {"operation": ["read"]}}}+_SEARCH = {"displayOptions": {"show": {"operation": ["search"]}}}+_REPLY = {"displayOptions": {"show": {"operation": ["reply"]}}}+_ATTACH = {"displayOptions": {"show": {"operation": ["list_attachments", "download_attachments"]}}}++# Graph attachment @odata.type discriminators.+_FILE_ATTACHMENT = "#microsoft.graph.fileAttachment"+++class MailParams(BaseModel):+ operation: Literal["send", "read", "search", "reply", "list_attachments", "download_attachments"] = "send"++ # Target mailbox. Empty = the signed-in user's own mailbox. Set to a+ # shared/other mailbox address (e.g. [email protected]) to operate on+ # it — requires Full Access (+ Send As to send) on that mailbox and the+ # .Shared OAuth scopes.+ mailbox: str = Field(default="", description="Shared mailbox address (empty = your own mailbox).")++ # Send+ to: str = Field(+ default="",+ json_schema_extra={"placeholder": "[email protected], [email protected]", **_SEND},+ )+ cc: str = Field(default="", json_schema_extra=_SEND)+ bcc: str = Field(default="", json_schema_extra=_SEND)+ subject: str = Field(default="", json_schema_extra=_SEND)+ body: str = Field(+ default="",+ json_schema_extra={"rows": 4, "placeholder": "Write your message...", **_SEND},+ )+ body_type: Literal["text", "html"] = Field(default="text", json_schema_extra=_SEND)++ # Read (message_id optional: omit to list recent messages). message_id is+ # also the parent-message field for the attachment ops, so it shows there too.+ message_id: str = Field(+ default="",+ json_schema_extra={"displayOptions": {"show": {"operation": ["read", "list_attachments", "download_attachments"]}}},+ )+ max_results: int = Field(default=10, ge=1, le=100, json_schema_extra=_READ)++ # Search+ query: str = Field(+ default="",+ json_schema_extra={"placeholder": "from:jane subject:meeting", **_SEARCH},+ )+ search_max_results: int = Field(default=10, ge=1, le=100, json_schema_extra=_SEARCH)++ # Reply+ reply_message_id: str = Field(default="", json_schema_extra=_REPLY)+ comment: str = Field(+ default="",+ json_schema_extra={"rows": 4, "placeholder": "Your reply...", **_REPLY},+ )+ reply_all: bool = Field(default=False, json_schema_extra=_REPLY)++ # Attachments (list_attachments / download_attachments). Reuses message_id+ # above as the parent message. attachment_id downloads just one; empty = all.+ attachment_id: str = Field(default="", json_schema_extra=_ATTACH)+ include_inline: bool = Field(+ default=False,+ description="Include inline body images (e.g. signature logos). Off by default.",+ json_schema_extra=_ATTACH,+ )++ model_config = ConfigDict(extra="ignore")+++class MailOutput(BaseModel):+ operation: Optional[str] = None+ sent: Optional[bool] = None+ replied: Optional[bool] = None+ to: Optional[str] = None+ subject: Optional[str] = None+ message_id: Optional[str] = None+ from_: Optional[str] = Field(default=None)+ received: Optional[str] = None+ body_preview: Optional[str] = None+ body: Optional[str] = None+ web_link: Optional[str] = None+ has_attachments: Optional[bool] = None+ messages: Optional[List[dict]] = None+ count: Optional[int] = None+ query: Optional[str] = None+ # Attachment ops+ attachments: Optional[List[dict]] = None+ download_dir: Optional[str] = None+ skipped: Optional[List[dict]] = None++ model_config = ConfigDict(extra="allow")+++def _recipients(raw: str) -> list:+ """Comma/semicolon-separated addresses -> Graph recipient objects."""+ parts = [p.strip() for chunk in raw.split(",") for p in chunk.split(";")]+ return [{"emailAddress": {"address": addr}} for addr in parts if addr]+++def _summarize(msg: dict) -> dict:+ """Compact a Graph message resource into a flat summary dict."""+ sender = (msg.get("from") or {}).get("emailAddress") or {}+ return {+ "message_id": msg.get("id"),+ "subject": msg.get("subject", ""),+ "from": sender.get("address", ""),+ "from_name": sender.get("name", ""),+ "received": msg.get("receivedDateTime"),+ "body_preview": msg.get("bodyPreview", ""),+ "is_read": msg.get("isRead"),+ "has_attachments": msg.get("hasAttachments"),+ "web_link": msg.get("webLink"),+ }+++class MailNode(ActionNode):+ type = "msMail"+ display_name = "Outlook Mail"+ subtitle = "Email Operations"+ group = ("microsoft", "tool")+ description = "Microsoft Outlook Mail send / read / search / reply via Graph (workflow + AI tool)"+ component_kind = "square"+ tool_name = "ms_mail"+ tool_description = (+ "Send, read, search, reply to, and handle attachments of Outlook email via Microsoft Graph. "+ "Operations: send (compose), read (get message by ID or list recent), "+ "search (find messages by text), reply (respond to a message), "+ "list_attachments (metadata for a message's attachments), "+ "download_attachments (save file attachments to the workspace; returns paths "+ "for the document parser). read/search results include has_attachments. "+ "Set 'mailbox' to a shared mailbox address to operate on it instead of your own."+ )+ handles = (+ {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},+ )+ credentials = (MicrosoftCredential,)+ annotations = {"destructive": False, "readonly": False, "open_world": True}+ task_queue = TaskQueue.REST_API+ usable_as_tool = True++ Params = MailParams+ Output = MailOutput++ _SELECT = "id,subject,from,receivedDateTime,bodyPreview,isRead,hasAttachments,webLink"++ @Operation("dispatch")+ async def dispatch(self, ctx: NodeContext, params: MailParams) -> MailOutput:+ op = params.operation++ if op == "send":+ return await self._send(ctx, params)+ if op == "read":+ return await self._read(ctx, params)+ if op == "search":+ return await self._search(ctx, params)+ if op == "reply":+ return await self._reply(ctx, params)+ if op == "list_attachments":+ return await self._list_attachments(ctx, params)+ if op == "download_attachments":+ return await self._download_attachments(ctx, params)+ raise NodeUserError(f"Unknown Mail operation: {op}")++ async def _send(self, ctx: NodeContext, params: MailParams) -> MailOutput:+ if not params.to:+ raise NodeUserError("Recipient email address (to) is required")+ if not params.subject:+ raise NodeUserError("Email subject is required")+ if not params.body:+ raise NodeUserError("Email body is required")++ message = {+ "subject": params.subject,+ "body": {+ "contentType": "HTML" if params.body_type == "html" else "Text",+ "content": params.body,+ },+ "toRecipients": _recipients(params.to),+ }+ if params.cc:+ message["ccRecipients"] = _recipients(params.cc)+ if params.bcc:+ message["bccRecipients"] = _recipients(params.bcc)++ await graph_request(+ ctx,+ "POST",+ f"{mailbox_base(params.mailbox)}/sendMail",+ json={"message": message, "saveToSentItems": True},+ )+ await track_microsoft_usage(ctx.node_id, "send", 1, ctx.raw)+ return MailOutput(operation="send", sent=True, to=params.to, subject=params.subject)++ async def _read(self, ctx: NodeContext, params: MailParams) -> MailOutput:+ if params.message_id:+ msg = await graph_request(+ ctx,+ "GET",+ f"{mailbox_base(params.mailbox)}/messages/{params.message_id}",+ params={"$select": f"{self._SELECT},body"},+ )+ await track_microsoft_usage(ctx.node_id, "read", 1, ctx.raw)+ summary = _summarize(msg or {})+ body = ((msg or {}).get("body") or {}).get("content", "")+ return MailOutput(+ operation="read",+ message_id=summary["message_id"],+ subject=summary["subject"],+ from_=summary["from"],+ received=summary["received"],+ body_preview=summary["body_preview"],+ body=body,+ has_attachments=summary["has_attachments"],+ web_link=summary["web_link"],+ )++ # No id -> list most recent messages.+ data = await graph_request(+ ctx,+ "GET",+ f"{mailbox_base(params.mailbox)}/messages",+ params={+ "$top": min(params.max_results, 100),+ "$select": self._SELECT,+ "$orderby": "receivedDateTime desc",+ },+ )+ items = (data or {}).get("value", [])+ formatted = [_summarize(m) for m in items]+ await track_microsoft_usage(ctx.node_id, "read", len(formatted), ctx.raw)+ return MailOutput(operation="read", messages=formatted, count=len(formatted))++ async def _search(self, ctx: NodeContext, params: MailParams) -> MailOutput:+ if not params.query:+ raise NodeUserError("Search query is required")+ # Graph $search must be a quoted string; it cannot combine with $orderby.+ data = await graph_request(+ ctx,+ "GET",+ f"{mailbox_base(params.mailbox)}/messages",+ params={+ "$search": f'"{params.query}"',+ "$top": min(params.search_max_results, 100),+ "$select": self._SELECT,+ },+ )+ items = (data or {}).get("value", [])+ formatted = [_summarize(m) for m in items]+ await track_microsoft_usage(ctx.node_id, "search", len(formatted), ctx.raw)+ return MailOutput(+ operation="search",+ messages=formatted,+ count=len(formatted),+ query=params.query,+ )++ async def _reply(self, ctx: NodeContext, params: MailParams) -> MailOutput:+ if not params.reply_message_id:+ raise NodeUserError("reply_message_id is required")+ if not params.comment:+ raise NodeUserError("Reply comment is required")+ endpoint = "replyAll" if params.reply_all else "reply"+ await graph_request(+ ctx,+ "POST",+ f"{mailbox_base(params.mailbox)}/messages/{params.reply_message_id}/{endpoint}",+ json={"comment": params.comment},+ )+ await track_microsoft_usage(ctx.node_id, "reply", 1, ctx.raw)+ return MailOutput(operation="reply", replied=True, message_id=params.reply_message_id)++ async def _list_attachments(self, ctx: NodeContext, params: MailParams) -> MailOutput:+ if not params.message_id:+ raise NodeUserError("message_id is required to list attachments")+ # Metadata only — $select excludes contentBytes so no payload is fetched.+ data = await graph_request(+ ctx,+ "GET",+ f"{mailbox_base(params.mailbox)}/messages/{params.message_id}/attachments",+ params={"$select": "id,name,contentType,size,isInline"},+ )+ items = (data or {}).get("value", [])+ attachments = []+ for a in items:+ is_inline = bool(a.get("isInline"))+ if is_inline and not params.include_inline:+ continue+ odata = a.get("@odata.type", "")+ attachments.append(+ {+ "attachment_id": a.get("id"),+ "name": a.get("name"),+ "content_type": a.get("contentType"),+ "size": a.get("size"),+ "is_inline": is_inline,+ # "file" for downloadable fileAttachment; else the Graph+ # subtype (item / reference) so the caller sees why a+ # download op would skip it.+ "kind": "file" if odata == _FILE_ATTACHMENT else odata.split(".")[-1] or "unknown",+ }+ )+ await track_microsoft_usage(ctx.node_id, "list_attachments", len(attachments), ctx.raw)+ return MailOutput(operation="list_attachments", attachments=attachments, count=len(attachments))++ async def _download_attachments(self, ctx: NodeContext, params: MailParams) -> MailOutput:+ from services.media.limits import MEDIA_MAX_READ_BYTES++ if not params.message_id:+ raise NodeUserError("message_id is required to download attachments")++ # Full fetch — fileAttachments carry base64 contentBytes inline. For+ # attachments >3 MB Graph may omit contentBytes and require the+ # session upload/download API; that's out of scope (the >25 MiB guard+ # below skips oversize items rather than blowing the media read cap).+ base = mailbox_base(params.mailbox)+ if params.attachment_id:+ single = await graph_request(+ ctx,+ "GET",+ f"{base}/messages/{params.message_id}/attachments/{params.attachment_id}",+ )+ items = [single] if single else []+ else:+ data = await graph_request(+ ctx,+ "GET",+ f"{base}/messages/{params.message_id}/attachments",+ )+ items = (data or {}).get("value", [])++ downloaded = []+ skipped = []+ for a in items:+ name = a.get("name") or "attachment"+ odata = a.get("@odata.type", "")+ if odata != _FILE_ATTACHMENT:+ skipped.append({"name": name, "reason": f"unsupported type {odata.split('.')[-1] or 'unknown'}"})+ continue+ if a.get("isInline") and not params.include_inline:+ skipped.append({"name": name, "reason": "inline"})+ continue+ content_b64 = a.get("contentBytes")+ if not content_b64:+ skipped.append({"name": name, "reason": "no contentBytes (may exceed Graph inline size)"})+ continue+ payload = base64.b64decode(content_b64)+ if len(payload) > MEDIA_MAX_READ_BYTES:+ skipped.append({"name": name, "reason": f"exceeds {MEDIA_MAX_READ_BYTES} byte limit"})+ continue++ ref, abs_path = write_attachment_bytes(+ payload,+ ctx=ctx,+ filename=name,+ mime_type=a.get("contentType"),+ )+ downloaded.append(+ {+ "filename": name,+ "path": abs_path, # absolute — feeds documentParser.file_path+ "mime_type": a.get("contentType"),+ "size": len(payload),+ "ref": ref.model_dump(mode="json"),+ }+ )++ if not downloaded:+ detail = f" (skipped: {skipped})" if skipped else ""+ raise NodeUserError(f"No downloadable file attachments on message {params.message_id}{detail}")++ # download_dir (absolute workspace attachments/ dir) feeds documentParser.input_dir.+ from pathlib import Path as _Path++ download_dir = str(_Path(downloaded[0]["path"]).parent)+ await track_microsoft_usage(ctx.node_id, "download_attachments", len(downloaded), ctx.raw)+ return MailOutput(+ operation="download_attachments",+ attachments=downloaded,+ download_dir=download_dir,+ count=len(downloaded),+ skipped=skipped or None,+ )diff --git a/server/nodes/microsoft/mail/icon.svg b/server/nodes/microsoft/mail/icon.svgnew file mode 100644index 00000000..9cb444ff--- /dev/null+++ b/server/nodes/microsoft/mail/icon.svg@@ -0,0 +1,6 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="48" height="48">+ <path fill="#0072c6" d="M28 12h16a2 2 0 0 1 2 2v20a2 2 0 0 1-2 2H28V12z"/>+ <path fill="#fff" d="M30 17h13v2H30zM30 22h13v2H30zM30 27h13v2H30z"/>+ <path fill="#0072c6" d="M2 9.5 25 6v36L2 38.5z"/>+ <path fill="#fff" d="M13.5 18.2c3 0 5 2.4 5 5.8s-2 5.9-5.1 5.9-5-2.4-5-5.8 2.1-5.9 5.1-5.9zm0 2.3c-1.6 0-2.5 1.5-2.5 3.5s.9 3.5 2.5 3.5 2.5-1.5 2.5-3.5-.9-3.5-2.5-3.5z"/>+</svg>diff --git a/server/nodes/microsoft/mail/meta.json b/server/nodes/microsoft/mail/meta.jsonnew file mode 100644index 00000000..6fc307dd--- /dev/null+++ b/server/nodes/microsoft/mail/meta.json@@ -0,0 +1 @@+{"color": "#0078D4"}diff --git a/server/nodes/microsoft/mail_receive/__init__.py b/server/nodes/microsoft/mail_receive/__init__.pynew file mode 100644index 00000000..41748317--- /dev/null+++ b/server/nodes/microsoft/mail_receive/__init__.py@@ -0,0 +1,255 @@+"""Outlook Mail Receive — Microsoft Graph polling trigger.++Fires when a new message matching the filter arrives in the mailbox.+Mirrors ``googleGmailReceive``: the ``PollingTriggerNode`` base owns the+loop, seen-id baseline, and the per-cycle Temporal poll activity; this+class supplies the four Graph-specific hooks plus an ``execute()``+override for the inline canvas-Run path.++Because the polling hooks run without a ``NodeContext`` (deployment loop+and Temporal activity), they authenticate through the ctx-free+``graph_get_raw`` / ``mark_message_read_raw`` helpers in ``.._base``.+"""++from __future__ import annotations++import asyncio+import time+from datetime import datetime+from typing import Any, Dict, Optional, Set++from pydantic import BaseModel, ConfigDict, Field++from core.logging import get_logger+from services.plugin import NodeContext, Operation, PollingTriggerNode, TaskQueue++from .._base import graph_get_raw, mailbox_base, mark_message_read_raw, track_microsoft_usage+from .._credentials import MicrosoftCredential++logger = get_logger(__name__)++# Fields fetched per message. bodyPreview keeps the payload small; the+# full body is included so downstream nodes have it without a second call.+_SELECT = "id,subject,from,toRecipients,receivedDateTime,bodyPreview,body,isRead,hasAttachments,webLink,conversationId"+++class MailReceiveParams(BaseModel):+ mailbox: str = Field(+ default="",+ description="Shared mailbox address to watch (empty = your own mailbox). Requires Full Access + Mail.ReadWrite.Shared.",+ )+ only_unread: bool = Field(+ default=True,+ description="Only fire for unread messages (Graph $filter=isRead eq false).",+ )+ from_filter: str = Field(+ default="",+ description="Only fire for messages from this sender address (optional).",+ )+ folder: str = Field(+ default="inbox",+ description="Mail folder well-known name (e.g. inbox, sentitems) or folder id.",+ )+ mark_as_read: bool = Field(default=False, description="Mark the message read after firing.")+ poll_interval: int = Field(default=60, ge=10, le=3600)++ model_config = ConfigDict(extra="ignore")+++class MailReceiveOutput(BaseModel):+ message_id: Optional[str] = None+ conversation_id: Optional[str] = None+ from_: Optional[str] = Field(default=None)+ from_name: Optional[str] = None+ to: Optional[list] = None+ subject: Optional[str] = None+ body_preview: Optional[str] = None+ body: Optional[str] = None+ received: Optional[str] = None+ is_read: Optional[bool] = None+ has_attachments: Optional[bool] = None+ web_link: Optional[str] = None++ model_config = ConfigDict(extra="allow")+++def _summarize(msg: Dict[str, Any]) -> Dict[str, Any]:+ sender = (msg.get("from") or {}).get("emailAddress") or {}+ return {+ "message_id": msg.get("id"),+ "conversation_id": msg.get("conversationId"),+ "from": sender.get("address", ""),+ "from_name": sender.get("name", ""),+ "to": [(r.get("emailAddress") or {}).get("address", "") for r in msg.get("toRecipients", [])],+ "subject": msg.get("subject", ""),+ "body_preview": msg.get("bodyPreview", ""),+ "body": (msg.get("body") or {}).get("content", ""),+ "received": msg.get("receivedDateTime"),+ "is_read": msg.get("isRead"),+ "has_attachments": msg.get("hasAttachments"),+ "web_link": msg.get("webLink"),+ }+++def _list_path(params: Dict[str, Any]) -> str:+ folder = (params.get("folder") or "inbox").strip()+ # Well-known folder names and folder ids both slot into mailFolders/{id}.+ # mailbox_base() -> /me or /users/{shared-address}.+ return f"{mailbox_base(params.get('mailbox'))}/mailFolders/{folder}/messages"+++def _query(params: Dict[str, Any]) -> Dict[str, Any]:+ filters = []+ if params.get("only_unread", True):+ filters.append("isRead eq false")+ sender = (params.get("from_filter") or "").strip()+ if sender:+ # OData string literals use single quotes; double any embedded quote.+ safe = sender.replace("'", "''")+ filters.append(f"from/emailAddress/address eq '{safe}'")+ q: Dict[str, Any] = {+ "$select": _SELECT,+ "$top": 25,+ }+ if filters:+ # Graph rejects ($filter on isRead/from) + ($orderby on a DIFFERENT+ # property, receivedDateTime) with 400 InefficientFilter unless the+ # advanced-query header is set. The trigger dedups by seen-ids and+ # doesn't depend on ordering, so we simply drop $orderby whenever a+ # filter is present. Without a filter we keep newest-first ordering.+ q["$filter"] = " and ".join(filters)+ else:+ q["$orderby"] = "receivedDateTime desc"+ return q+++class MailReceiveNode(PollingTriggerNode):+ type = "msMailReceive"+ event_type = "ms_mail_received"+ display_name = "Outlook Mail Receive"+ subtitle = "Inbound Email"+ group = ("microsoft", "trigger")+ description = "Polling trigger for incoming Outlook mail via Microsoft Graph"+ component_kind = "trigger"+ handles = ({"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},)+ credentials = (MicrosoftCredential,)+ task_queue = TaskQueue.TRIGGERS_POLL+ default_poll_interval = 60++ Params = MailReceiveParams+ Output = MailReceiveOutput++ # ---- PollingTriggerNode hooks (deployment / Temporal poll) --------++ async def setup_service(self, params: Dict[str, Any]) -> Any:+ # No long-lived handle: Graph is stateless bearer REST and each+ # helper re-resolves a fresh token. Pass params through so the+ # other hooks can read filters without extra plumbing.+ return params++ async def fetch_ids(self, service: Any, params: Dict[str, Any]) -> Set[str]:+ data = await graph_get_raw(_list_path(params), params=_query(params))+ return {m.get("id") for m in data.get("value", []) if m.get("id")}++ async def fetch_detail(self, service: Any, msg_id: str, params: Dict[str, Any]) -> Dict[str, Any]:+ msg = await graph_get_raw(f"{mailbox_base(params.get('mailbox'))}/messages/{msg_id}", params={"$select": _SELECT})+ detail = _summarize(msg)+ detail["id"] = msg_id # stable cross-cycle dedup key for the workflow+ return detail++ async def post_emit(self, service: Any, msg_id: str, params: Dict[str, Any]) -> None:+ if params.get("mark_as_read"):+ try:+ await mark_message_read_raw(msg_id, mailbox=params.get("mailbox"))+ except Exception as exc: # noqa: BLE001+ logger.warning(f"[msMailReceive] Failed to mark as read: {exc}")++ # ---- inline canvas-Run path (mirrors gmail_receive.execute) -------++ async def execute(+ self,+ node_id: str,+ parameters: Dict[str, Any],+ context: NodeContext,+ ) -> Dict[str, Any]:+ from services.status_broadcaster import get_status_broadcaster++ start_time = time.time()+ try:+ poll_interval = self._clamp_interval(parameters.get("poll_interval"))++ await get_status_broadcaster().update_node_status(+ node_id,+ "waiting",+ {+ "message": f"Waiting for Outlook mail (polling every {poll_interval}s)...",+ "event_type": self.event_type,+ },+ workflow_id=context.workflow_id,+ )++ seen_ids: Set[str] = set()+ try:+ seen_ids = await self.fetch_ids(parameters, parameters)+ logger.info(f"[msMailReceive] Baseline: {len(seen_ids)} existing messages")+ except Exception as e: # noqa: BLE001+ logger.warning(f"[msMailReceive] Baseline fetch failed (treating all as new): {e}")++ while True:+ await asyncio.sleep(poll_interval)+ try:+ current_ids = await self.fetch_ids(parameters, parameters)+ new_ids = current_ids - seen_ids+ if not new_ids:+ seen_ids = set(current_ids)+ continue++ newest_id = next(iter(new_ids))+ seen_ids = set(current_ids)+ detail = await self.fetch_detail(parameters, newest_id, parameters)+ await self.post_emit(parameters, newest_id, parameters)++ await track_microsoft_usage(+ node_id,+ "read",+ 1,+ {"workflow_id": context.workflow_id, "session_id": context.session_id},+ )+ logger.info(f"[msMailReceive] New message: {detail.get('subject', 'no subject')}")+ return {+ "success": True,+ "node_id": node_id,+ "node_type": self.type,+ "result": detail,+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat(),+ }+ except asyncio.CancelledError:+ raise+ except Exception as e: # noqa: BLE001 -- per-cycle isolation+ logger.error(f"[msMailReceive] Poll error (will retry): {e}")++ except asyncio.CancelledError:+ logger.info(f"[msMailReceive] Cancelled by user: node_id={node_id}")+ return {+ "success": False,+ "node_id": node_id,+ "node_type": self.type,+ "error": "Cancelled by user",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat(),+ }+ except Exception as e: # noqa: BLE001+ logger.error(f"[msMailReceive] Error: {e}")+ return {+ "success": False,+ "node_id": node_id,+ "node_type": self.type,+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat(),+ }++ @Operation("wait")+ async def wait(self, ctx: NodeContext, params: MailReceiveParams) -> MailReceiveOutput:+ raise NotImplementedError("msMailReceive uses execute() override.")diff --git a/server/nodes/microsoft/mail_receive/icon.svg b/server/nodes/microsoft/mail_receive/icon.svgnew file mode 100644index 00000000..bbf062c1--- /dev/null+++ b/server/nodes/microsoft/mail_receive/icon.svg@@ -0,0 +1,7 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="48" height="48">+ <path fill="#0072c6" d="M28 12h16a2 2 0 0 1 2 2v20a2 2 0 0 1-2 2H28V12z"/>+ <path fill="#fff" d="M30 22h13v2H30zM30 27h13v2H30z"/>+ <path fill="#0072c6" d="M2 9.5 25 6v36L2 38.5z"/>+ <path fill="#fff" d="M13.5 18.2c3 0 5 2.4 5 5.8s-2 5.9-5.1 5.9-5-2.4-5-5.8 2.1-5.9 5.1-5.9zm0 2.3c-1.6 0-2.5 1.5-2.5 3.5s.9 3.5 2.5 3.5 2.5-1.5 2.5-3.5-.9-3.5-2.5-3.5z"/>+ <circle cx="40" cy="14" r="7" fill="#ea4335" stroke="#fff" stroke-width="2"/>+</svg>diff --git a/server/nodes/microsoft/mail_receive/meta.json b/server/nodes/microsoft/mail_receive/meta.jsonnew file mode 100644index 00000000..6fc307dd--- /dev/null+++ b/server/nodes/microsoft/mail_receive/meta.json@@ -0,0 +1 @@+{"color": "#0078D4"}diff --git a/server/nodes/microsoft/microsoft.svg b/server/nodes/microsoft/microsoft.svgnew file mode 100644index 00000000..7f0d198d--- /dev/null+++ b/server/nodes/microsoft/microsoft.svg@@ -0,0 +1,6 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 23 23" width="23" height="23">+ <rect x="1" y="1" width="10" height="10" fill="#F25022"/>+ <rect x="12" y="1" width="10" height="10" fill="#7FBA00"/>+ <rect x="1" y="12" width="10" height="10" fill="#00A4EF"/>+ <rect x="12" y="12" width="10" height="10" fill="#FFB900"/>+</svg>diff --git a/server/nodes/visuals.json b/server/nodes/visuals.jsonindex a3e88f6b..7e73ce43 100644--- a/server/nodes/visuals.json+++ b/server/nodes/visuals.json@@ -185,6 +185,12 @@"googleTasks": {"skill": "google-tasks-skill"},+ "msMail": {+ "skill": "ms-mail-skill"+ },+ "msCalendar": {+ "skill": "ms-calendar-skill"+ },"groqChatModel": {"icon": "lobehub:groq"},diff --git a/server/skills/productivity_agent/ms-calendar-skill/SKILL.md b/server/skills/productivity_agent/ms-calendar-skill/SKILL.mdnew file mode 100644index 00000000..cfd9581a--- /dev/null+++ b/server/skills/productivity_agent/ms-calendar-skill/SKILL.md@@ -0,0 +1,143 @@+---+name: ms-calendar-skill+description: Create, list, update, and delete Outlook Calendar events via Microsoft Graph. Supports attendees, locations, and date-range queries.+allowed-tools: "ms_calendar"+metadata:+ author: opencompany+ version: "1.0"+ category: productivity++---++# Outlook Calendar Skill++Manage Outlook Calendar events - create, list, update, and delete - using the Microsoft Graph API (Outlook / Microsoft 365).++## Tool: ms_calendar++Consolidated Outlook Calendar tool with an `operation` parameter.++### Operations++| Operation | Description | Required Fields |+|-----------|-------------|-----------------|+| `create` | Create a new event | title, start_time, end_time |+| `list` | List events in a date range | (none, defaults to the next 7 days) |+| `update` | Update an existing event | event_id |+| `delete` | Delete an event | event_id |++### create - Create a new event++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| operation | string | Yes | Must be `"create"` |+| title | string | Yes | Event title/subject |+| start_time | string | Yes | Start time in ISO 8601 format |+| end_time | string | Yes | End time in ISO 8601 format |+| body | string | No | Event description/notes |+| location | string | No | Event location |+| attendees | string | No | Comma-separated email addresses |+| timezone | string | No | IANA/Windows time zone (default: UTC) |++**Example - Simple event:**+```json+{+ "operation": "create",+ "title": "Team Meeting",+ "start_time": "2026-08-10T14:00:00",+ "end_time": "2026-08-10T15:00:00",+ "body": "Weekly team sync"+}+```++**Example - Event with attendees and location:**+```json+{+ "operation": "create",+ "title": "Project Review",+ "start_time": "2026-08-10T10:00:00",+ "end_time": "2026-08-10T11:30:00",+ "location": "Conference Room A",+ "attendees": "[email protected], [email protected]",+ "timezone": "Eastern Standard Time"+}+```++### list - List events in a date range++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| operation | string | Yes | Must be `"list"` |+| start_date | string | No | Start of window. ISO 8601, or `today` / `today+Nd` (default: today) |+| end_date | string | No | End of window. ISO 8601, or `today+Nd` (default: 7 days ahead) |+| max_results | integer | No | Maximum results (default: 10, max: 250) |++**Example:**+```json+{+ "operation": "list",+ "start_date": "today",+ "end_date": "today+7d",+ "max_results": 20+}+```++### update - Update an existing event++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| operation | string | Yes | Must be `"update"` |+| event_id | string | Yes | Event ID to update (from `create` / `list`) |+| update_title | string | No | New title |+| update_start_time | string | No | New start time (ISO 8601) |+| update_end_time | string | No | New end time (ISO 8601) |+| update_body | string | No | New description/notes |+| update_location | string | No | New location |+| timezone | string | No | Time zone applied to new start/end (default: UTC) |++At least one `update_*` field must be provided.++**Example:**+```json+{+ "operation": "update",+ "event_id": "AAMkAGI2...",+ "update_title": "Updated Team Meeting",+ "update_start_time": "2026-08-10T15:00:00",+ "update_end_time": "2026-08-10T16:00:00"+}+```++### delete - Delete an event++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| operation | string | Yes | Must be `"delete"` |+| event_id | string | Yes | Event ID to delete |++**Example:**+```json+{+ "operation": "delete",+ "event_id": "AAMkAGI2..."+}+```++## Date/Time Formats++- **ISO 8601**: `2026-08-10T14:00:00` (interpreted in the given `timezone`)+- **Shortcuts (list only)**: `today`, `today+7d`+- Times returned by `list` are the raw Graph `dateTime` values.++## Common Workflows++1. **Schedule a meeting**: `create` with attendees; they receive invites.+2. **Check availability**: `list` for a date range.+3. **Reschedule**: `update` with new `update_start_time` / `update_end_time`.+4. **Cancel meeting**: `delete` the event by `event_id`.++## Setup Requirements++1. Connect the Outlook Calendar node to an AI Agent's `input-tools` handle.+2. Authenticate with Microsoft Graph in the Credentials Modal (Work/School account).+3. Ensure the Calendars.ReadWrite scope is granted.diff --git a/server/skills/productivity_agent/ms-mail-skill/SKILL.md b/server/skills/productivity_agent/ms-mail-skill/SKILL.mdnew file mode 100644index 00000000..8b7cf47c--- /dev/null+++ b/server/skills/productivity_agent/ms-mail-skill/SKILL.md@@ -0,0 +1,240 @@+---+name: ms-mail-skill+description: Send, read, search, reply to, and handle attachments of Outlook email via Microsoft Graph — for your own mailbox or a shared mailbox. Compose messages, list recent mail, search by text, reply/reply-all, and list or download file attachments (e.g. PDFs) for parsing.+allowed-tools: "ms_mail"+metadata:+ author: opencompany+ version: "1.2"+ category: productivity++---++# Outlook Mail Skill++Send, read, search, reply to, and handle attachments of email using the Microsoft Graph API (Outlook / Microsoft 365).++## Tool: ms_mail++Consolidated Outlook Mail tool with an `operation` parameter.++### Operations++| Operation | Description | Required Fields |+|-----------|-------------|-----------------|+| `send` | Send an email | to, subject, body |+| `read` | Read a message by ID, or list recent mail when no ID is given | (message_id optional) |+| `search` | Search messages by text | query |+| `reply` | Reply to a message | reply_message_id, comment |+| `list_attachments` | List a message's attachments (metadata only, no download) | message_id |+| `download_attachments` | Download file attachments into the workspace | message_id |++Every `read`/`search` result includes a `has_attachments` boolean per message —+check it before calling `list_attachments` / `download_attachments`.++### send - Send an email++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| operation | string | Yes | Must be `"send"` |+| to | string | Yes | Recipient address(es), comma-separated |+| subject | string | Yes | Email subject line |+| body | string | Yes | Email body (plain text or HTML) |+| cc | string | No | CC recipients (comma-separated) |+| bcc | string | No | BCC recipients (comma-separated) |+| body_type | string | No | `"text"` or `"html"` (default: text) |++**Example - Send plain text email:**+```json+{+ "operation": "send",+ "to": "[email protected]",+ "subject": "Meeting Tomorrow",+ "body": "Hi,\n\nJust a reminder about our meeting tomorrow at 2pm.\n\nBest regards"+}+```++**Example - Send to multiple recipients with CC:**+```json+{+ "operation": "send",+ "to": "[email protected], [email protected]",+ "cc": "[email protected]",+ "subject": "Weekly Report",+ "body": "<h1>Weekly Report</h1><p>Highlights...</p>",+ "body_type": "html"+}+```++### read - Read a message or list recent mail++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| operation | string | Yes | Must be `"read"` |+| message_id | string | No | Message ID to fetch (with body). Omit to list recent messages. |+| max_results | integer | No | Max messages when listing (default: 10, max: 100) |++Each returned message includes `has_attachments` (boolean). When `true`, use+`list_attachments` / `download_attachments` with that `message_id`.++**Example - Read a specific message:**+```json+{+ "operation": "read",+ "message_id": "AAMkAGI2..."+}+```++**Example - List the 20 most recent messages:**+```json+{+ "operation": "read",+ "max_results": 20+}+```++### search - Search messages++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| operation | string | Yes | Must be `"search"` |+| query | string | Yes | Free-text search (Microsoft Graph `$search`) |+| search_max_results | integer | No | Max results (default: 10, max: 100) |++Microsoft Graph search matches across subject, body, sender, and recipients.+Use natural keywords (e.g. `invoice`, `from:jane quarterly plan`); it does not+use Gmail-style operators.++**Example:**+```json+{+ "operation": "search",+ "query": "quarterly plan",+ "search_max_results": 20+}+```++### reply - Reply to a message++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| operation | string | Yes | Must be `"reply"` |+| reply_message_id | string | Yes | ID of the message to reply to (from search/read) |+| comment | string | Yes | The reply text |+| reply_all | boolean | No | Reply to all recipients (default: false) |++**Example:**+```json+{+ "operation": "reply",+ "reply_message_id": "AAMkAGI2...",+ "comment": "Thanks - looks good to me.",+ "reply_all": true+}+```++### list_attachments - List a message's attachments (metadata only)++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| operation | string | Yes | Must be `"list_attachments"` |+| message_id | string | Yes | The message whose attachments to list |+| include_inline | boolean | No | Include inline body images (e.g. signature logos). Default false. |++Returns `attachments: [{attachment_id, name, content_type, size, is_inline, kind}]`+and `count`. `kind` is `"file"` for a downloadable file attachment; other values+(`itemAttachment`, `referenceAttachment`) are shown so you know they cannot be+downloaded as bytes. Inline images are excluded unless `include_inline: true`.+This op does NOT download bytes — it is a cheap metadata lookup.++**Example:**+```json+{+ "operation": "list_attachments",+ "message_id": "AAMkAGI2..."+}+```++### download_attachments - Download file attachments into the workspace++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| operation | string | Yes | Must be `"download_attachments"` |+| message_id | string | Yes | The message whose attachments to download |+| attachment_id | string | No | Download only this attachment. Omit to download all file attachments. |+| include_inline | boolean | No | Include inline body images. Default false. |++Saves each file attachment into the workflow workspace and returns:+- `attachments: [{filename, path, mime_type, size, ref}]` — `path` is the absolute+ file path on disk (feed it to the Document Parser's `file_path`).+- `download_dir` — the absolute directory the files landed in (feed it to the+ Document Parser's `input_dir` to parse all of them).+- `count`, and `skipped: [{name, reason}]` for anything not downloaded+ (inline images, item/reference attachments, or files over the size limit).++Only real file attachments are downloaded. Item/reference attachments and (by+default) inline images are skipped. Bytes are never returned inline — you get a+path/reference, not the file contents.++**Example - download all file attachments:**+```json+{+ "operation": "download_attachments",+ "message_id": "AAMkAGI2..."+}+```++**Example - download one specific attachment:**+```json+{+ "operation": "download_attachments",+ "message_id": "AAMkAGI2...",+ "attachment_id": "AAMkAGI2...=="+}+```++## Parsing an attachment (e.g. a PDF)++`ms_mail` downloads the file; it does NOT extract text. To read a PDF's contents,+pair it with the **Document Parser** node on the canvas:++1. `ms_mail` `download_attachments` → returns `download_dir` (and per-file `path`).+2. Document Parser with `input_dir = {{msMail.download_dir}}` and+ `file_pattern = *.pdf` (or `file_path = {{msMail.attachments[0].path}}` for one file).+3. Document Parser returns `documents[].content` — the extracted text.++## Common Workflows++1. **Triage recent mail**: `read` with no ID to list recent messages, then `read` a specific `message_id` for full content.+2. **Find a thread**: `search` by keyword, take the `message_id`, then `reply`.+3. **Send an update**: `send` to one or more recipients, optionally as HTML.+4. **Process an attachment**: on a message with `has_attachments: true`, call+ `download_attachments`, then run the Document Parser over `download_dir` to get the text.++## Shared mailboxes++Every operation accepts an optional `mailbox` field. Leave it empty to use the+signed-in user's own mailbox (default). Set it to a shared/other mailbox address+(e.g. `[email protected]`) to operate on that mailbox instead — the node then+calls `/users/{address}/…` rather than `/me/…`.++Requirements for a shared mailbox:+- The signed-in account must have **Full Access** on the mailbox (and **Send As**+ / **Send on Behalf** to send from it).+- The `Mail.ReadWrite.Shared` / `Mail.Send.Shared` scopes must be granted+ (reconnect in the Credentials Modal after these are added to re-consent).++**Example - read a shared mailbox:**+```json+{+ "operation": "read",+ "mailbox": "[email protected]",+ "max_results": 20+}+```++## Setup Requirements++1. Connect the Outlook Mail node to an AI Agent's `input-tools` handle.+2. Authenticate with Microsoft Graph in the Credentials Modal (Work/School account).+3. Ensure the Mail.Send and Mail.ReadWrite scopes are granted (plus the+ `.Shared` variants if you use the `mailbox` field for a shared mailbox).diff --git a/server/tests/fixtures/tool_names_snapshot.json b/server/tests/fixtures/tool_names_snapshot.jsonindex 920718f1..c2fd065f 100644--- a/server/tests/fixtures/tool_names_snapshot.json+++ b/server/tests/fixtures/tool_names_snapshot.json@@ -80,6 +80,8 @@"twitterSearch": "twitter_search","twitterUser": "twitter_user","httpRequest": "http_request",+ "msMail": "ms_mail",+ "msCalendar": "ms_calendar","anthropicChatModel": "anthropic_chat_model","openaiChatModel": "openai_chat_model","geminiChatModel": "gemini_chat_model"diff --git a/server/tests/nodes/test_microsoft.py b/server/tests/nodes/test_microsoft.pynew file mode 100644index 00000000..14b9d27f--- /dev/null+++ b/server/tests/nodes/test_microsoft.py@@ -0,0 +1,753 @@+"""Contract tests for the Microsoft Graph nodes: msMail, msCalendar.++Each node is driven through the full NodeExecutor dispatch via the shared+`harness` fixture. Microsoft Graph HTTP is mocked with respx so no network+is touched, and the outgoing request (method + path + body) is asserted —+not just the parsed result — because that is the real contract with Graph.++The proactive token-refresh helper (`ensure_fresh_microsoft_token`) is+patched to a no-op here; it is a pure token-freshness concern exercised in+isolation by `test_ensure_fresh_token_*` below. Credentials reach the+`Connection` facade via `patched_container(auth_oauth_tokens=...)`.+"""++from __future__ import annotations++from contextlib import contextmanager+from unittest.mock import AsyncMock, patch++import httpx+import pytest+import respx++from tests.nodes._mocks import patched_container, patched_pricing++pytestmark = pytest.mark.node_contract++GRAPH = "https://graph.microsoft.com/v1.0"++# An owner token so MicrosoftCredential.resolve() -> get_oauth_tokens returns+# a bearer the Connection facade can inject.+_OWNER_TOKENS = {"microsoft": {"access_token": "tok_ms", "email": "[email protected]", "name": "Me"}}+++@contextmanager+def _no_refresh():+ """Skip the proactive-refresh side trip so tests exercise the Graph call."""+ with patch("nodes.microsoft._base.ensure_fresh_microsoft_token", new=AsyncMock(return_value="tok_ms")):+ yield+++# ============================================================================+# msMail+# ============================================================================+++class TestMsMailSend:+ @respx.mock+ async def test_send_posts_sendmail(self, harness):+ route = respx.post(f"{GRAPH}/me/sendMail").mock(return_value=httpx.Response(202))+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msMail",+ {+ "operation": "send",+ "to": "[email protected], [email protected]",+ "subject": "Hi",+ "body": "Hello there",+ "body_type": "text",+ },+ )++ harness.assert_envelope(result, success=True)+ assert result["result"]["sent"] is True+ assert route.called+ sent = respx.calls.last.request+ assert sent.headers["Authorization"] == "Bearer tok_ms"+ import json as _json++ payload = _json.loads(sent.content)+ msg = payload["message"]+ assert msg["subject"] == "Hi"+ assert msg["body"]["contentType"] == "Text"+ assert [r["emailAddress"]["address"] for r in msg["toRecipients"]] == [+ "[email protected]",+ "[email protected]",+ ]++ async def test_send_missing_recipient_is_user_error(self, harness):+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute("msMail", {"operation": "send", "subject": "x", "body": "y"})+ harness.assert_envelope(result, success=False)+ assert "recipient" in result["error"].lower()+++class TestMsMailSearch:+ @respx.mock+ async def test_search_uses_search_param(self, harness):+ respx.get(f"{GRAPH}/me/messages").mock(+ return_value=httpx.Response(+ 200,+ json={+ "value": [+ {+ "id": "AAA",+ "subject": "Quarterly plan",+ "from": {"emailAddress": {"address": "[email protected]", "name": "Jane"}},+ "receivedDateTime": "2026-08-01T10:00:00Z",+ "bodyPreview": "hello",+ "isRead": False,+ "webLink": "https://outlook/AAA",+ }+ ]+ },+ )+ )+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute("msMail", {"operation": "search", "query": "plan", "search_max_results": 5})++ harness.assert_envelope(result, success=True)+ payload = result["result"]+ assert payload["count"] == 1+ assert payload["messages"][0]["message_id"] == "AAA"+ assert payload["messages"][0]["from"] == "[email protected]"+ sent = respx.calls.last.request+ assert sent.url.params["$search"] == '"plan"'+ assert sent.url.params["$top"] == "5"++ async def test_search_empty_query_is_user_error(self, harness):+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute("msMail", {"operation": "search", "query": ""})+ harness.assert_envelope(result, success=False)+ assert "query" in result["error"].lower()+++class TestMsMailReply:+ @respx.mock+ async def test_reply_posts_reply(self, harness):+ route = respx.post(f"{GRAPH}/me/messages/AAA/reply").mock(return_value=httpx.Response(202))+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msMail",+ {"operation": "reply", "reply_message_id": "AAA", "comment": "Thanks!"},+ )+ harness.assert_envelope(result, success=True)+ assert result["result"]["replied"] is True+ assert route.called++ @respx.mock+ async def test_reply_all_uses_replyall_endpoint(self, harness):+ route = respx.post(f"{GRAPH}/me/messages/AAA/replyAll").mock(return_value=httpx.Response(202))+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msMail",+ {"operation": "reply", "reply_message_id": "AAA", "comment": "Thanks all!", "reply_all": True},+ )+ harness.assert_envelope(result, success=True)+ assert route.called+++class TestMsMailGraphError:+ @respx.mock+ async def test_graph_error_becomes_user_error(self, harness):+ respx.post(f"{GRAPH}/me/sendMail").mock(+ return_value=httpx.Response(+ 403,+ json={"error": {"code": "ErrorAccessDenied", "message": "Access is denied."}},+ )+ )+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msMail",+ {"operation": "send", "to": "[email protected]", "subject": "s", "body": "b"},+ )+ harness.assert_envelope(result, success=False)+ assert "ErrorAccessDenied" in result["error"] or "Access is denied" in result["error"]+++# ============================================================================+# msCalendar+# ============================================================================+++class TestMsCalendarCreate:+ @respx.mock+ async def test_create_posts_event(self, harness):+ respx.post(f"{GRAPH}/me/events").mock(+ return_value=httpx.Response(+ 201,+ json={+ "id": "EV1",+ "subject": "Standup",+ "start": {"dateTime": "2026-08-10T14:00:00.0000000", "timeZone": "UTC"},+ "end": {"dateTime": "2026-08-10T14:30:00.0000000", "timeZone": "UTC"},+ "location": {"displayName": "Room 1"},+ "webLink": "https://outlook/EV1",+ },+ )+ )+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msCalendar",+ {+ "operation": "create",+ "title": "Standup",+ "start_time": "2026-08-10T14:00:00",+ "end_time": "2026-08-10T14:30:00",+ "location": "Room 1",+ "attendees": "[email protected]",+ },+ )+ harness.assert_envelope(result, success=True)+ payload = result["result"]+ assert payload["event_id"] == "EV1"+ assert payload["title"] == "Standup"+ sent = respx.calls.last.request+ import json as _json++ body = _json.loads(sent.content)+ assert body["subject"] == "Standup"+ assert body["start"]["dateTime"] == "2026-08-10T14:00:00"+ assert body["attendees"][0]["emailAddress"]["address"] == "[email protected]"++ async def test_create_missing_title_is_user_error(self, harness):+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msCalendar",+ {"operation": "create", "start_time": "x", "end_time": "y"},+ )+ harness.assert_envelope(result, success=False)+ assert "title" in result["error"].lower()+++class TestMsCalendarList:+ @respx.mock+ async def test_list_uses_calendarview(self, harness):+ route = respx.get(f"{GRAPH}/me/calendarView").mock(+ return_value=httpx.Response(+ 200,+ json={+ "value": [+ {+ "id": "EV1",+ "subject": "Standup",+ "start": {"dateTime": "2026-08-10T14:00:00.0000000"},+ "end": {"dateTime": "2026-08-10T14:30:00.0000000"},+ "location": {"displayName": "Room 1"},+ "organizer": {"emailAddress": {"address": "[email protected]"}},+ "webLink": "https://outlook/EV1",+ }+ ]+ },+ )+ )+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msCalendar",+ {"operation": "list", "start_date": "2026-08-01T00:00:00", "end_date": "2026-08-31T00:00:00"},+ )+ harness.assert_envelope(result, success=True)+ payload = result["result"]+ assert payload["count"] == 1+ assert payload["events"][0]["event_id"] == "EV1"+ assert route.called+ sent = respx.calls.last.request+ assert sent.url.params["startDateTime"] == "2026-08-01T00:00:00"+ assert sent.url.params["endDateTime"] == "2026-08-31T00:00:00"+++class TestMsCalendarDelete:+ @respx.mock+ async def test_delete_calls_delete(self, harness):+ route = respx.delete(f"{GRAPH}/me/events/EV1").mock(return_value=httpx.Response(204))+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute("msCalendar", {"operation": "delete", "event_id": "EV1"})+ harness.assert_envelope(result, success=True)+ assert result["result"]["deleted"] is True+ assert route.called++ async def test_delete_missing_id_is_user_error(self, harness):+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute("msCalendar", {"operation": "delete"})+ harness.assert_envelope(result, success=False)+ assert "event id" in result["error"].lower()+++class TestMsCalendarUpdate:+ @respx.mock+ async def test_update_patches_event(self, harness):+ route = respx.patch(f"{GRAPH}/me/events/EV1").mock(+ return_value=httpx.Response(+ 200,+ json={"id": "EV1", "subject": "Renamed", "start": {"dateTime": "x"}, "end": {"dateTime": "y"}},+ )+ )+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msCalendar",+ {"operation": "update", "event_id": "EV1", "update_title": "Renamed"},+ )+ harness.assert_envelope(result, success=True)+ assert result["result"]["title"] == "Renamed"+ assert route.called+ import json as _json++ body = _json.loads(respx.calls.last.request.content)+ assert body == {"subject": "Renamed"}++ async def test_update_no_fields_is_user_error(self, harness):+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute("msCalendar", {"operation": "update", "event_id": "EV1"})+ harness.assert_envelope(result, success=False)+ assert "no update fields" in result["error"].lower()+++# ============================================================================+# Params schema invariants (tool-facing flatness)+# ============================================================================+++class TestParamsSchemas:+ def test_params_are_flat_no_refs(self):+ from nodes.microsoft.calendar import CalendarParams+ from nodes.microsoft.mail import MailParams++ for model in (MailParams, CalendarParams):+ schema = model.model_json_schema()+ assert "$defs" not in schema, f"{model.__name__} leaked $defs"+ assert "definitions" not in schema, f"{model.__name__} leaked definitions"+++# ============================================================================+# Token freshness helper (unit)+# ============================================================================+++class TestEnsureFreshToken:+ async def test_missing_tokens_raises_permission_error(self):+ from nodes.microsoft import _auth_helper++ auth = AsyncMock()+ auth.get_oauth_tokens = AsyncMock(return_value=None)+ with patch("services.plugin.deps.get_auth_service", return_value=auth):+ with pytest.raises(PermissionError) as exc:+ await _auth_helper.ensure_fresh_microsoft_token("owner")+ assert getattr(exc.value, "provider", None) == "microsoft"++ async def test_refresh_persists_new_token(self):+ from nodes.microsoft import _auth_helper++ # Force a refresh: clear any cached expiry so _needs_refresh() is True.+ _auth_helper._TOKEN_EXPIRY.pop("owner", None)++ auth = AsyncMock()+ auth.get_oauth_tokens = AsyncMock(return_value={"access_token": "old", "email": "[email protected]", "name": "Me", "scopes": "User.Read"})+ auth.get_oauth_refresh_token = AsyncMock(return_value="rt")+ auth.get_api_key = AsyncMock(side_effect=lambda k, *a, **kw: {"microsoft_client_id": "cid", "microsoft_client_secret": "sec"}.get(k))+ auth.store_oauth_tokens = AsyncMock(return_value=True)++ refresh_result = {"success": True, "access_token": "new", "refresh_token": "rt2", "expires_in": 3600}++ with patch("services.plugin.deps.get_auth_service", return_value=auth), patch(+ "nodes.microsoft._oauth.MicrosoftOAuth.refresh_access_token",+ new=AsyncMock(return_value=refresh_result),+ ):+ token = await _auth_helper.ensure_fresh_microsoft_token("owner")++ assert token == "new"+ auth.store_oauth_tokens.assert_awaited_once()+ _, kwargs = auth.store_oauth_tokens.call_args+ assert kwargs["access_token"] == "new"+ assert kwargs["refresh_token"] == "rt2"+++# ============================================================================+# msMailReceive (polling trigger)+# ============================================================================+++@contextmanager+def _fresh_token():+ """Skip the token-freshness resolve so ctx-free Graph helpers just run."""+ with patch("nodes.microsoft._base.ensure_fresh_microsoft_token", new=AsyncMock(return_value="tok_ms")):+ yield+++class TestMsMailReceive:+ def test_registration(self):+ from services.node_registry import get_node_class++ cls = get_node_class("msMailReceive")+ assert cls is not None+ assert cls.mode == "polling"+ assert cls.event_type == "ms_mail_received"+ assert cls.task_queue == "triggers-poll"+ # Trigger nodes are not AI tools.+ assert getattr(cls, "usable_as_tool", False) is False++ def test_query_defaults_to_unread(self):+ from nodes.microsoft.mail_receive import _list_path, _query++ q = _query({"only_unread": True})+ assert q["$filter"] == "isRead eq false"+ assert _list_path({}) == "/me/mailFolders/inbox/messages"++ def test_query_with_filter_omits_orderby(self):+ # Graph rejects $filter (isRead/from) + $orderby (receivedDateTime)+ # with 400 InefficientFilter. When a filter is present, no $orderby.+ from nodes.microsoft.mail_receive import _query++ q = _query({"only_unread": True})+ assert "$orderby" not in q+ q2 = _query({"only_unread": True, "from_filter": "[email protected]"})+ assert "$orderby" not in q2++ def test_query_without_filter_keeps_orderby(self):+ from nodes.microsoft.mail_receive import _query++ q = _query({"only_unread": False})+ assert "$filter" not in q+ assert q["$orderby"] == "receivedDateTime desc"++ def test_query_from_filter_and_folder(self):+ from nodes.microsoft.mail_receive import _list_path, _query++ q = _query({"only_unread": True, "from_filter": "[email protected]"})+ assert "isRead eq false" in q["$filter"]+ assert "from/emailAddress/address eq '[email protected]'" in q["$filter"]+ assert _list_path({"folder": "sentitems"}) == "/me/mailFolders/sentitems/messages"++ def test_query_from_filter_escapes_single_quote(self):+ from nodes.microsoft.mail_receive import _query++ q = _query({"only_unread": False, "from_filter": "o'[email protected]"})+ assert "from/emailAddress/address eq 'o''[email protected]'" == q["$filter"]++ @respx.mock+ async def test_fetch_ids_hits_mailfolder_messages(self):+ from nodes.microsoft.mail_receive import MailReceiveNode++ route = respx.get(f"{GRAPH}/me/mailFolders/inbox/messages").mock(+ return_value=httpx.Response(200, json={"value": [{"id": "M1"}, {"id": "M2"}]})+ )+ node = MailReceiveNode()+ params = {"only_unread": True}+ with _fresh_token():+ ids = await node.fetch_ids(await node.setup_service(params), params)+ assert ids == {"M1", "M2"}+ assert route.called+ assert respx.calls.last.request.url.params["$filter"] == "isRead eq false"++ @respx.mock+ async def test_fetch_detail_summarizes(self):+ from nodes.microsoft.mail_receive import MailReceiveNode++ respx.get(f"{GRAPH}/me/messages/M1").mock(+ return_value=httpx.Response(+ 200,+ json={+ "id": "M1",+ "subject": "Hello",+ "from": {"emailAddress": {"address": "[email protected]", "name": "Jane"}},+ "toRecipients": [{"emailAddress": {"address": "[email protected]"}}],+ "receivedDateTime": "2026-08-01T10:00:00Z",+ "bodyPreview": "hi",+ "body": {"content": "<p>hi</p>"},+ "isRead": False,+ "webLink": "https://outlook/M1",+ "conversationId": "C1",+ },+ )+ )+ node = MailReceiveNode()+ with _fresh_token():+ detail = await node.fetch_detail(None, "M1", {})+ assert detail["id"] == "M1"+ assert detail["from"] == "[email protected]"+ assert detail["subject"] == "Hello"+ assert detail["conversation_id"] == "C1"++ @respx.mock+ async def test_post_emit_marks_read_when_enabled(self):+ from nodes.microsoft.mail_receive import MailReceiveNode++ route = respx.patch(f"{GRAPH}/me/messages/M1").mock(return_value=httpx.Response(200, json={"id": "M1"}))+ node = MailReceiveNode()+ with _fresh_token():+ await node.post_emit(None, "M1", {"mark_as_read": True})+ assert route.called++ @respx.mock+ async def test_post_emit_noop_when_disabled(self):+ from nodes.microsoft.mail_receive import MailReceiveNode++ route = respx.patch(f"{GRAPH}/me/messages/M1").mock(return_value=httpx.Response(200))+ node = MailReceiveNode()+ with _fresh_token():+ await node.post_emit(None, "M1", {"mark_as_read": False})+ assert not route.called++ def test_output_params_flat(self):+ from nodes.microsoft.mail_receive import MailReceiveParams++ schema = MailReceiveParams.model_json_schema()+ assert "$defs" not in schema and "definitions" not in schema+++# ============================================================================+# msMail attachments (list + download)+# ============================================================================++import base64 # noqa: E402++_FILE_ODATA = "#microsoft.graph.fileAttachment"+_ITEM_ODATA = "#microsoft.graph.itemAttachment"+++def _attachment(name, *, odata=_FILE_ODATA, inline=False, content=b"", ctype="application/pdf", aid="A1"):+ a = {+ "@odata.type": odata,+ "id": aid,+ "name": name,+ "contentType": ctype,+ "size": len(content),+ "isInline": inline,+ }+ if content:+ a["contentBytes"] = base64.b64encode(content).decode()+ return a+++class TestMsMailHasAttachments:+ def test_select_includes_hasattachments(self):+ from nodes.microsoft.mail import MailNode++ assert "hasAttachments" in MailNode._SELECT++ def test_receive_select_includes_hasattachments(self):+ from nodes.microsoft.mail_receive import _SELECT++ assert "hasAttachments" in _SELECT++ def test_summarize_surfaces_has_attachments(self):+ from nodes.microsoft.mail import _summarize++ out = _summarize({"id": "M1", "hasAttachments": True})+ assert out["has_attachments"] is True+++class TestMsMailListAttachments:+ @respx.mock+ async def test_list_excludes_inline_by_default(self, harness):+ respx.get(f"{GRAPH}/me/messages/M1/attachments").mock(+ return_value=httpx.Response(+ 200,+ json={+ "value": [+ _attachment("quote.pdf", aid="A1"),+ _attachment("logo.png", inline=True, ctype="image/png", aid="A2"),+ {"@odata.type": _ITEM_ODATA, "id": "A3", "name": "embedded.eml", "size": 10, "isInline": False},+ ]+ },+ )+ )+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute("msMail", {"operation": "list_attachments", "message_id": "M1"})++ harness.assert_envelope(result, success=True)+ names = [a["name"] for a in result["result"]["attachments"]]+ assert "quote.pdf" in names+ assert "logo.png" not in names # inline excluded by default+ # item attachment surfaces in listing but tagged non-file+ item = next(a for a in result["result"]["attachments"] if a["name"] == "embedded.eml")+ assert item["kind"] == "itemAttachment"+ pdf = next(a for a in result["result"]["attachments"] if a["name"] == "quote.pdf")+ assert pdf["kind"] == "file"+ # metadata-only fetch+ assert respx.calls.last.request.url.params["$select"] == "id,name,contentType,size,isInline"++ @respx.mock+ async def test_list_includes_inline_when_requested(self, harness):+ respx.get(f"{GRAPH}/me/messages/M1/attachments").mock(+ return_value=httpx.Response(200, json={"value": [_attachment("logo.png", inline=True, ctype="image/png")]})+ )+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msMail",+ {"operation": "list_attachments", "message_id": "M1", "include_inline": True},+ )+ assert result["result"]["count"] == 1++ async def test_list_requires_message_id(self, harness):+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute("msMail", {"operation": "list_attachments"})+ harness.assert_envelope(result, success=False)+ assert "message_id" in result["error"].lower()+++class TestMsMailDownloadAttachments:+ @respx.mock+ async def test_download_writes_file_and_returns_path(self, harness, tmp_path):+ pdf_bytes = b"%PDF-1.4 fake pdf body"+ respx.get(f"{GRAPH}/me/messages/M1/attachments").mock(+ return_value=httpx.Response(+ 200,+ json={+ "value": [+ _attachment("quote.pdf", content=pdf_bytes, aid="A1"),+ _attachment("logo.png", inline=True, content=b"img", ctype="image/png", aid="A2"),+ ]+ },+ )+ )+ ctx = harness.build_context(workspace_dir=str(tmp_path))+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msMail",+ {"operation": "download_attachments", "message_id": "M1"},+ context=ctx,+ )++ harness.assert_envelope(result, success=True)+ payload = result["result"]+ assert payload["count"] == 1 # inline logo skipped+ att = payload["attachments"][0]+ assert att["filename"] == "quote.pdf"+ # file actually written under attachments/ with real bytes+ from pathlib import Path++ written = Path(att["path"])+ assert written.is_absolute() and written.exists()+ assert written.read_bytes() == pdf_bytes+ assert written.parent.name == "attachments"+ assert payload["download_dir"] == str(written.parent)+ # FileRef is kind=file (never audio), and NO raw bytes leak into output+ assert att["ref"]["kind"] == "file"+ assert "contentBytes" not in att and "data" not in att+ assert "contentBytes" not in str(payload)+ # inline recorded in skipped+ assert any(s["reason"] == "inline" for s in (payload.get("skipped") or []))++ @respx.mock+ async def test_download_single_attachment_by_id(self, harness, tmp_path):+ route = respx.get(f"{GRAPH}/me/messages/M1/attachments/A1").mock(+ return_value=httpx.Response(200, json=_attachment("quote.pdf", content=b"%PDF-1.4 x", aid="A1"))+ )+ ctx = harness.build_context(workspace_dir=str(tmp_path))+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msMail",+ {"operation": "download_attachments", "message_id": "M1", "attachment_id": "A1"},+ context=ctx,+ )+ harness.assert_envelope(result, success=True)+ assert route.called+ assert result["result"]["count"] == 1++ @respx.mock+ async def test_download_no_file_attachments_is_user_error(self, harness, tmp_path):+ respx.get(f"{GRAPH}/me/messages/M1/attachments").mock(+ return_value=httpx.Response(+ 200,+ json={"value": [{"@odata.type": _ITEM_ODATA, "id": "A3", "name": "embedded.eml", "size": 10}]},+ )+ )+ ctx = harness.build_context(workspace_dir=str(tmp_path))+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msMail",+ {"operation": "download_attachments", "message_id": "M1"},+ context=ctx,+ )+ harness.assert_envelope(result, success=False)+ assert "no downloadable file attachments" in result["error"].lower()++ async def test_download_requires_message_id(self, harness, tmp_path):+ ctx = harness.build_context(workspace_dir=str(tmp_path))+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute("msMail", {"operation": "download_attachments"}, context=ctx)+ harness.assert_envelope(result, success=False)+ assert "message_id" in result["error"].lower()+++# ============================================================================+# Shared mailbox (/users/{address}) routing+# ============================================================================++SHARED = "[email protected]"+++class TestMailboxBaseHelper:+ def test_empty_is_me(self):+ from nodes.microsoft._base import mailbox_base++ assert mailbox_base("") == "/me"+ assert mailbox_base(None) == "/me"++ def test_address_is_users_path(self):+ from nodes.microsoft._base import mailbox_base++ assert mailbox_base(SHARED) == f"/users/{SHARED}"+ assert mailbox_base(" [email protected] ") == "/users/[email protected]"++ def test_invalid_address_raises(self):+ from nodes.microsoft._base import mailbox_base+ from services.plugin import NodeUserError++ for bad in ("a/b", "has space"):+ with pytest.raises(NodeUserError):+ mailbox_base(bad)+++class TestMsMailSharedMailbox:+ @respx.mock+ async def test_read_list_targets_shared_mailbox(self, harness):+ route = respx.get(f"{GRAPH}/users/{SHARED}/messages").mock(+ return_value=httpx.Response(200, json={"value": []})+ )+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute("msMail", {"operation": "read", "mailbox": SHARED})+ harness.assert_envelope(result, success=True)+ assert route.called++ @respx.mock+ async def test_send_from_shared_mailbox(self, harness):+ route = respx.post(f"{GRAPH}/users/{SHARED}/sendMail").mock(return_value=httpx.Response(202))+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msMail",+ {"operation": "send", "mailbox": SHARED, "to": "[email protected]", "subject": "s", "body": "b"},+ )+ harness.assert_envelope(result, success=True)+ assert route.called++ @respx.mock+ async def test_empty_mailbox_still_uses_me(self, harness):+ route = respx.get(f"{GRAPH}/me/messages").mock(return_value=httpx.Response(200, json={"value": []}))+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute("msMail", {"operation": "read"})+ harness.assert_envelope(result, success=True)+ assert route.called+++class TestMsMailReceiveSharedMailbox:+ def test_list_path_shared(self):+ from nodes.microsoft.mail_receive import _list_path++ assert _list_path({"mailbox": SHARED, "folder": "inbox"}) == f"/users/{SHARED}/mailFolders/inbox/messages"+ assert _list_path({"folder": "inbox"}) == "/me/mailFolders/inbox/messages"+++class TestMsCalendarSharedMailbox:+ @respx.mock+ async def test_list_targets_shared_calendar(self, harness):+ route = respx.get(f"{GRAPH}/users/{SHARED}/calendarView").mock(+ return_value=httpx.Response(200, json={"value": []})+ )+ with _no_refresh(), patched_container(auth_oauth_tokens=_OWNER_TOKENS), patched_pricing():+ result = await harness.execute(+ "msCalendar",+ {"operation": "list", "mailbox": SHARED, "start_date": "2026-08-01T00:00:00", "end_date": "2026-08-31T00:00:00"},+ )+ harness.assert_envelope(result, success=True)+ assert route.calleddiff --git a/server/tests/test_plugin_self_containment.py b/server/tests/test_plugin_self_containment.pyindex 548791e9..99a32fb2 100644--- a/server/tests/test_plugin_self_containment.py+++ b/server/tests/test_plugin_self_containment.py@@ -65,6 +65,7 @@ _MIGRATED_PLUGINS = ("gcloud","github","google",+ "microsoft","stripe","telegram","twitter",@@ -80,6 +81,7 @@ _PLUGINS_WITH_HANDLERS = ("gcloud","github","google",+ "microsoft","stripe","telegram","twitter",@@ -92,6 +94,7 @@ _PLUGINS_WITH_HANDLERS = (_PLUGINS_WITH_ROUTERS = ("android","google",+ "microsoft","twitter",)