Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(teams): Microsoft Teams collaboration bridge (CHOO-1281) (#7)

Christian McDermott5647b18de696
diff --git a/.env.example b/.env.example
index 8e3a78c83..2c2fed003 100644
--- a/.env.example
+++ b/.env.example
@@ -53,6 +53,10 @@ MATTERMOST_TEAM_NAME=switch
MATTERMOST_USER=user
MATTERMOST_USER_PASSWORD=user1234
+# Teams has no local-dev env vars: a Teams workspace is connected per-bridge
+# through the gateway (all Azure app credentials live in the bridge's stored
+# connection_config), never in global config.
+
# ── OIDC (optional — MCP OAuth token validation; bring your own IdP) ─────────
# Enable OAuth/OIDC token auth on the MCP server by pointing at any standards
# compliant IdP. Leave unset to use API-token (bearer) auth only, which is the
diff --git a/core/pyproject.toml b/core/pyproject.toml
index b3ce70b24..49ee5190c 100644
--- a/core/pyproject.toml
+++ b/core/pyproject.toml
@@ -31,6 +31,8 @@ dependencies = [
"Markdown>=3,<4",
"slack-sdk>=3.41.0",
"mattermostdriver>=7.3.2",
+ "aiohttp>=3.10,<4",
+ "cryptography>=43,<47",
"fastmcp>=3.2.0,<4",
"bcrypt>=4.0,<5",
"PyJWT>=2.9,<3",
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index 7d8d3b538..ed6188aeb 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -265,3 +265,27 @@ class CollaborationAdapter(ABC):
@abstractmethod
def translate_inbound(self, raw_message: str) -> str: ...
+
+ async def ensure_channel_subscriptions(
+ self, channels: list[tuple[str, str]]
+ ) -> None:
+ """(Re)establish any server-side message capture for the given
+ ``(channel_id, channel_type)`` pairs.
+
+ Called on bridge startup with the bridge's known channels. Default is a
+ no-op; adapters that rely on expiring server-side subscriptions (Teams,
+ via Microsoft Graph) override this so channel capture self-heals after a
+ restart or a notification-URL change (e.g. a rotated tunnel), without the
+ bot having to be re-added to each channel."""
+ return None
+
+ def set_service_url_persister(
+ self, persist: Callable[[str], Awaitable[None]]
+ ) -> None:
+ """Install a callback the adapter uses to persist an outbound endpoint
+ it learns from inbound traffic, so outbound survives a restart.
+
+ Default is a no-op; adapters whose outbound endpoint is only discovered
+ from inbound activities (Teams, whose Bot Connector ``serviceUrl`` is
+ carried on inbound activities) override this to persist it."""
+ return None
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.py
index a89205beb..164765712 100644
--- a/core/switch_core/bridges/collaboration/bridge_core.py
+++ b/core/switch_core/bridges/collaboration/bridge_core.py
@@ -14,6 +14,7 @@ from nio import (
)
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+from switch_core.aliases import AliasError, validate_alias_format
from switch_core.bridges.collaboration.adapter import CollaborationAdapter
from switch_core.bridges.collaboration.models import (
ChannelType,
@@ -25,6 +26,7 @@ from switch_core.bridges.collaboration.models import (
)
from switch_core.clients.admin_messages import ADMIN_MARKER, AdminMessageType
from switch_core.clients.client_base import ClientBase, ClientConfig
+from switch_core.clients.mentions import mention_regex, strip_emphasis
from switch_core.db.models import BridgeMessageMap, ExternalUser
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.bridge_message_map_store import BridgeMessageMapStore
@@ -117,6 +119,7 @@ class BridgeCore:
on_user_joined=self._handle_user_joined_channel,
on_app_joined=self._handle_app_joined_channel,
)
+ await self._ensure_channel_captures()
await self._create_agent_identities()
async def stop(self) -> None:
@@ -173,6 +176,20 @@ class BridgeCore:
"Created %s identities for %d agents", self._bridge_type, len(agents)
)
+ async def _ensure_channel_captures(self) -> None:
+ """Ask the adapter to (re)establish server-side message capture for this
+ bridge's channels. Runs on startup so capture self-heals after a restart
+ or a notification-URL change (e.g. a rotated tunnel). A no-op for
+ adapters that don't use expiring subscriptions."""
+ async with self._session_factory() as session:
+ rooms = await self._room_store.get_by_bridge(session, self._bridge_id)
+ channels: list[tuple[str, str]] = []
+ for room in rooms:
+ if room.external_channel_id and room.channel_type:
+ channels.append((room.external_channel_id, room.channel_type))
+ if channels:
+ await self._adapter.ensure_channel_subscriptions(channels)
+
# ── Inbound (platform → room) ───────────────────────────────────────────
async def _is_registered_agent(self, name: str) -> bool:
@@ -214,11 +231,22 @@ class BridgeCore:
content = (
f"👋 You tagged {app_mention} directly — I'm not linked to an agent "
"in this channel yet.\n\n"
- f"*Agents you can tag directly:*\n{agent_list}\n\n"
- "*To make me an agent's entry point*, copy the line below and swap "
- "in the agent's name — after that, tagging me here routes to that "
- f"agent:\n!set-alias @agent_name {app_mention}"
+ f"*Agents you can tag directly:*\n{agent_list}"
)
+ # The `!set-alias` shortcut only makes sense when the bot handle is a
+ # valid alias token. Some platforms (e.g. Teams) use a bot id containing
+ # characters an alias can't hold (a `:`), so we omit the line there —
+ # tagging an agent by name (above) works regardless.
+ try:
+ validate_alias_format(token)
+ except AliasError:
+ pass
+ else:
+ content += (
+ "\n\n*To make me an agent's entry point*, copy the line below and "
+ "swap in the agent's name — after that, tagging me here routes to "
+ f"that agent:\n!set-alias @agent_name {app_mention}"
+ )
thread_root_id = msg.root_id or msg.message_ref
await self._adapter.admin_message(
msg.channel_id,
@@ -227,6 +255,32 @@ class BridgeCore:
message_type=AdminMessageType.SELF_MENTION_UNALIASED.value,
)
+ async def _resolve_self_mention_target(
+ self, msg: InboundMessage, room_id: str
+ ) -> str | None:
+ """The agent a bot @mention should address, or None.
+
+ A bot mention resolves to an agent when the bot handle is that agent's
+ room alias (matching Slack's behaviour), or — the common single-agent
+ case — when the room holds exactly one agent. Zero or several unaliased
+ agents are ambiguous, so we return None and let the caller post guidance.
+ """
+ token = msg.self_mention_token
+ if token is None:
+ return None
+ async with self._session_factory() as session:
+ agent_id = await self._room_store.get_agent_id_by_alias(
+ session, room_id, token
+ )
+ if agent_id is None:
+ agent_ids = await self._room_store.get_agent_ids(session, room_id)
+ if len(agent_ids) == 1:
+ agent_id = agent_ids[0]
+ if agent_id is None:
+ return None
+ agent = await self._agent_store.get(session, agent_id)
+ return agent.name if agent is not None else None
+
async def _handle_lobby_message(self, msg: InboundMessage) -> None:
"""The Slack app's DM ("lobby") is deprecated for talking to agents.
Reply with a pointer to the onboarding docs instead of routing."""
@@ -277,7 +331,15 @@ class BridgeCore:
room_id, matrix_room_id = room_ids
- await self._maybe_guide_self_mention(msg, room_id)
+ # A bot @mention carries no agent name in its text (the platform tags the
+ # bot, not the agent). Resolve which agent it addresses so we can inject
+ # an `@<agent>` the addressing layer matches on; if it can't be resolved,
+ # fall back to guidance.
+ mention_target: str | None = None
+ if msg.self_mention_token is not None:
+ mention_target = await self._resolve_self_mention_target(msg, room_id)
+ if mention_target is None:
+ await self._maybe_guide_self_mention(msg, room_id)
puppet = await self._ensure_user_in_matrix_room(
external_user_id=msg.sender_id,
@@ -288,6 +350,10 @@ class BridgeCore:
return
content = self._adapter.translate_inbound(msg.content)
+ if mention_target is not None and (
+ mention_regex(mention_target).search(strip_emphasis(content)) is None
+ ):
+ content = f"@{mention_target} {content}"
logger.debug(
"[BRIDGE-IN] sending to matrix room=%s via puppet=%s attachments=%d",
matrix_room_id,
diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.py
index 0986b5cbf..c1f0d7fe3 100644
--- a/core/switch_core/bridges/collaboration/lifecycle_service.py
+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py
@@ -153,6 +153,9 @@ class CollaborationBridgeLifecycleService:
typed_config = config_cls.model_validate(bridge.connection_config or {})
adapter = adapter_cls(config=typed_config) # type: ignore[call-arg]
+ adapter.set_service_url_persister(
+ lambda service_url: self._persist_service_url(bridge_id, service_url)
+ )
async with self._session_factory() as session:
bridge_client_record = await self._client_store.get(
@@ -203,6 +206,13 @@ class CollaborationBridgeLifecycleService:
logger.info("Started collaboration bridge %s (%s)", bridge_id, bridge.type)
+ async def _persist_service_url(self, bridge_id: str, service_url: str) -> None:
+ """Persist an outbound serviceUrl an adapter learned from inbound traffic
+ so outbound survives a restart (used by the Teams adapter)."""
+ async with self._session_factory() as session:
+ await self._bridge_store.set_service_url(session, bridge_id, service_url)
+ await session.commit()
+
async def _run_bridge(
self,
bridge_id: str,
diff --git a/core/switch_core/bridges/collaboration/teams/README.md b/core/switch_core/bridges/collaboration/teams/README.md
new file mode 100644
index 000000000..a8ec3fa7a
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/teams/README.md
@@ -0,0 +1,97 @@
+# Microsoft Teams collaboration bridge
+
+Integrates Switch with Microsoft Teams alongside Slack and Mattermost, following
+the same adapter contract (`../adapter.py`). This note covers the Teams-specific
+architecture, the ops prerequisites, and the per-bridge configuration. A Teams
+workspace is connected **per bridge through the gateway** — all credentials live
+in the bridge's stored `connection_config`, never in global/env config.
+
+## Architecture
+
+Teams has no persistent bot socket (unlike Slack Socket Mode / Mattermost
+WebSocket), so the adapter uses two Microsoft APIs and hosts its own HTTP
+listener:
+
+- **Bot Framework** (outbound + partial inbound). Outbound messages post via the
+ Bot Connector REST API at the per-tenant `serviceUrl`. Inbound activities (1:1
+ and group chats in full; channel messages only when the bot is @mentioned;
+ conversation/member updates) arrive at `POST /api/messages`, where the JWT the
+ Bot Connector attaches is verified before the activity is trusted.
+- **Microsoft Graph change notifications** (full channel capture). To see *every*
+ channel message — not just @mentions — the adapter subscribes to
+ `teams/{team}/channels/{channel}/messages` per channel. Graph delivers
+ encrypted resource data to `POST /api/teams/notifications`; the adapter
+ verifies `clientState`, decrypts, and renews subscriptions before their
+ ~60-minute expiry.
+
+**Identity model:** a single Azure bot backs every Switch agent (like Slack).
+Each agent's messages render as an **Adaptive Card** headed with the agent's name
+and avatar. Human users map to Matrix puppets keyed on their AAD object id. Both
+inbound paths funnel through one delivery + de-duplication path (keyed on the
+Teams message id); the bot's own posts are dropped to prevent loops.
+
+## Security note
+
+Graph resource-data encryption proves message **integrity, not origin** (the
+wrapping key is the public certificate, which anyone can encrypt to). The
+`clientState` shared secret is therefore the only control that authenticates a
+notification's origin, so it is **required** and validated on every notification —
+data and lifecycle events alike. Inbound Bot Framework activities are separately
+authenticated by verifying the Bot Connector JWT.
+
+## Ops prerequisites (must exist before onboarding)
+
+Environment/tenant setup owned by an administrator — track as a separate ops task.
+
+1. **Azure AD app registration** providing the bot's `app_id` (client id), a
+ client secret (`app_password`), and the `tenant_id`.
+2. **Azure Bot resource** against that app, with the **messaging endpoint** set
+ to `https://<public-host>/api/messages` and the **Microsoft Teams channel**
+ enabled.
+3. **Teams app package** (manifest) including the bot, installed into the target
+ team so it can be added to channels and post proactively.
+4. **Graph API permissions** with admin consent, for channel capture +
+ provisioning: `ChannelMessage.Read.Group` (RSC, preferred) *or* tenant-wide
+ `ChannelMessage.Read.All`; plus `Channel.Create` and
+ `TeamMember.ReadWrite.All` / `ChannelMember.ReadWrite.All`. Resource-data
+ subscriptions count against a shared per-tenant Teams subscription quota.
+5. **Encryption certificate** for Graph resource data: an X.509 cert whose public
+ certificate is handed to Graph and whose private key the bridge holds to
+ decrypt message bodies. Give it a stable id.
+6. **Public HTTPS ingress** routing `https://<public-host>/api/messages` and
+ `/api/teams/notifications` to the bridge's listener. Graph requires valid TLS
+ and a response to its validation handshake within 10 seconds.
+
+## Per-bridge configuration (`TeamsConnectionConfig`)
+
+Onboard through the gateway (collaboration bridge create). Admin-supplied fields:
+
+- **`app_id`**, **`app_password`**, **`tenant_id`** — Azure AD app registration.
+- **`team_id`** — the AAD team (group) id outbound-created channels go into.
+- **`public_base_url`** — the public HTTPS base the listener is reachable at (used
+ to build the `/api/teams/notifications` URL given to Graph).
+- **`client_state`** — required shared secret (see Security note).
+- **`encryption_certificate_id`**, **`encryption_public_certificate`** (PEM),
+ **`encryption_private_key`** (PEM) — required for channel-message capture.
+
+Switch-internal fields are **not** admin inputs and are hidden from the gateway
+form: the listener bind (`listen_host`/`listen_port`, default `0.0.0.0:3978`) is a
+deployment detail Switch owns, and `service_url` is learned at runtime and
+persisted automatically. An operator can still override the bind via the stored
+`connection_config` when running more than one Teams bridge on a host.
+
+Without the encryption fields the bridge still runs (outbound, chats, and
+@mention capture work), but per-channel Graph subscriptions are skipped and an
+error is logged — full channel capture is disabled until they are supplied.
+
+## Known limitations / follow-ups
+
+- **Switch-initiated DM rooms** are user-initiated (as on Mattermost);
+ bootstrapping one bot-side needs proactive app installation via Graph.
+- **Attachments** (inbound media and outbound files) are currently **disclosed,
+ not relayed**: the message text bridges and a note names the un-relayed media.
+ Native relay is a tenant-validated follow-up.
+- **Real outbound @mentions** are not yet emitted (needs a display-name → AAD id
+ directory); mention text bridges as plain `@name`.
+- **One Teams bridge per listener port** — run multiple Teams bridges on distinct
+ ports (and ingress routes) if needed.
diff --git a/core/switch_core/bridges/collaboration/teams/__init__.py b/core/switch_core/bridges/collaboration/teams/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.py
new file mode 100644
index 000000000..8c9fb3b04
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/teams/adapter.py
@@ -0,0 +1,1254 @@
+from __future__ import annotations
+
+import asyncio
+import html
+import logging
+import re
+from collections import OrderedDict
+from collections.abc import Awaitable, Callable
+from datetime import UTC, datetime, timedelta
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+from aiohttp import web
+from pydantic.json_schema import SkipJsonSchema
+
+from switch_core.bridges.collaboration.adapter import CollaborationAdapter
+from switch_core.bridges.collaboration.models import (
+ BridgeConnectionConfig,
+ ChannelType,
+ InboundAgentJoin,
+ InboundAppJoin,
+ InboundCommand,
+ InboundMessage,
+ InboundUserJoin,
+)
+from switch_core.bridges.collaboration.teams.auth import (
+ InboundActivityValidator,
+ TeamsTokenProvider,
+)
+from switch_core.bridges.collaboration.teams.cards import (
+ agent_message_card,
+ card_attachment,
+)
+from switch_core.bridges.collaboration.teams.connector import BotConnectorClient
+from switch_core.bridges.collaboration.teams.crypto import (
+ decrypt_resource_data,
+ load_certificate_der_b64,
+)
+from switch_core.bridges.collaboration.teams.graph import GraphClient
+
+logger = logging.getLogger(__name__)
+
+_MENTION_TAG = re.compile(r"<at\b[^>]*>(.*?)</at>", re.IGNORECASE | re.DOTALL)
+_HTML_TAG = re.compile(r"<[^>]+>")
+_BR_TAG = re.compile(r"<br\s*/?>", re.IGNORECASE)
+
+
+def _render_mentions(text: str) -> str:
+ """Rewrite Teams ``<at>Display</at>`` mention markup to ``@Display``.
+
+ Teams sends an @mention as ``<at>Name</at>`` markup, with the addressable id
+ carried separately in the activity ``entities`` / Graph ``mentions``.
+ Deleting the markup would drop the ``@name`` the addressing layer matches on,
+ so we keep the display text as a plain ``@name`` token instead."""
+
+ def _sub(match: re.Match[str]) -> str:
+ inner = html.unescape(match.group(1)).strip()
+ return f"@{inner}" if inner else ""
+
+ return _MENTION_TAG.sub(_sub, text)
+
+
+_LEADING_MENTION_TAG = re.compile(
+ r"^\s*(?:<(?:p|div|span)\b[^>]*>\s*)?<at\b[^>]*>.*?</at>\s*",
+ re.IGNORECASE | re.DOTALL,
+)
+
+
+def _strip_leading_mention(text: str) -> str:
+ """Drop a single leading ``<at>…</at>`` mention (optionally inside one wrapper
+ tag) from Teams message markup.
+
+ In a Teams channel the Bot Framework only delivers a message when the bot is
+ @mentioned, so a command typed in a channel always arrives as
+ ``@Bot !command``. Removing the leading bot mention lets the shared
+ ``!``-command detection in ``_deliver`` see the ``!`` marker."""
+ return _LEADING_MENTION_TAG.sub("", text, count=1)
+
+
+# Channel-message subscriptions with resource data live at most 60 minutes; we
+# request 55 and proactively renew well before expiry.
+_SUBSCRIPTION_TTL = timedelta(minutes=55)
+_RENEWAL_INTERVAL_SECONDS = 40 * 60
+
+
+class TeamsConnectionConfig(BridgeConnectionConfig):
+ """Per-bridge Microsoft Teams credentials and endpoints.
+
+ Teams integration uses an Azure AD app registration that backs both a Bot
+ Framework bot (outbound messaging, proactive messages) and Microsoft Graph
+ access (channel-message capture, provisioning). Secrets live per-bridge in
+ the ``connection_config`` JSONB column, like every other collaboration
+ bridge — nothing here belongs in global config.
+ """
+
+ # Azure AD app registration (bot client id + secret + tenant).
+ app_id: str
+ app_password: str
+ tenant_id: str
+
+ # AAD team (group) id that outbound-created channels are provisioned into.
+ team_id: str
+
+ # Public HTTPS base URL where this adapter's inbound listener is reachable.
+ # Teams and Graph are HTTP-push, so the adapter hosts its own listener:
+ # Bot Framework activities at ``/api/messages`` and Graph change
+ # notifications at ``/api/teams/notifications``, both under this base.
+ public_base_url: str
+
+ # Local bind for the inbound listener. This is a Switch-internal deployment
+ # detail, not an admin concern, so it is hidden from the gateway config form
+ # (SkipJsonSchema) and defaults are used; an operator can still override it
+ # via the stored connection_config when running more than one Teams bridge on
+ # a host (one bridge per listener port).
+ listen_host: SkipJsonSchema[str] = "0.0.0.0"
+ listen_port: SkipJsonSchema[int] = 3978
+
+ # Graph change-notification resource-data encryption. Graph encrypts message
+ # bodies with the public certificate; the private key decrypts them on
+ # delivery. Required once channel-message subscriptions are enabled.
+ encryption_certificate_id: str | None = None
+ encryption_public_certificate: str | None = None
+ encryption_private_key: str | None = None
+
+ # Shared secret echoed back in every change notification and validated on
+ # receipt. Required, and the ONLY control that authenticates a notification's
+ # origin: Graph resource-data encryption proves integrity but NOT origin (the
+ # wrapping key is the public certificate, which anyone can encrypt to), so
+ # without clientState the notification endpoint is spoofable.
+ client_state: str
+
+ # Bot Connector serviceUrl (the per-tenant outbound endpoint). It is learned
+ # from inbound Bot Framework activities and persisted here so outbound
+ # survives a process restart — otherwise, until the bot next receives a
+ # (mention-triggered) activity, no serviceUrl is known and every outbound
+ # message fails. The Graph channel-capture path never carries a serviceUrl,
+ # so a busy channel whose traffic arrives only via capture would never
+ # re-learn it. Refreshed automatically whenever a newer value is observed.
+ # Learned at runtime and persisted here — never an admin input, so it is
+ # hidden from the gateway config form (SkipJsonSchema).
+ service_url: SkipJsonSchema[str | None] = None
+
+
+class TeamsAdapter(CollaborationAdapter):
+ """Microsoft Teams collaboration adapter.
+
+ Single-bot identity model (like Slack): one Azure bot app backs every Switch
+ agent, and per-agent presentation is done with Adaptive Card sender labels
+ rather than a bot account per agent. Outbound messages are delivered through
+ the Bot Framework connector; inbound activities arrive at a self-hosted
+ aiohttp listener. Full (non-@mention) channel-message capture via Microsoft
+ Graph subscriptions is layered on in a later phase.
+ """
+
+ def __init__(self, *, config: TeamsConnectionConfig) -> None:
+ super().__init__()
+ self._config = config
+
+ self._http: httpx.AsyncClient | None = None
+ self._tokens: TeamsTokenProvider | None = None
+ self._connector: BotConnectorClient | None = None
+ self._graph: GraphClient | None = None
+ self._validator: InboundActivityValidator | None = None
+ self._runner: web.AppRunner | None = None
+
+ # Per-tenant Bot Connector endpoint, captured from inbound activities and
+ # seeded from persisted config so outbound works right after a restart,
+ # before the bot next receives a Bot Framework activity.
+ self._service_url: dict[str, str] = {}
+ self._default_service_url: str | None = config.service_url
+ # Installed by the bridge to persist a newly-learned serviceUrl so it
+ # survives a restart. No-op until set.
+ self._persist_service_url: Callable[[str], Awaitable[None]] | None = None
+ # channel/chat id -> ChannelType, learned from inbound activities.
+ self._channel_type: dict[str, ChannelType] = {}
+ # message id -> (service_url, conversation_id) for later edit/delete.
+ self._sent: dict[str, tuple[str, str]] = {}
+ # Inbound de-duplication — the Bot Framework and Graph capture paths can
+ # both deliver the same channel message, keyed on the Teams message id.
+ self._seen: OrderedDict[str, None] = OrderedDict()
+ self._seen_max = 2000
+
+ # channel id -> Graph subscription id, for channels we capture.
+ self._subscriptions: dict[str, str] = {}
+ # channel id -> AAD team id, learned from bot-join activities so a
+ # channel-message subscription can be created for it.
+ self._team_of_channel: dict[str, str] = {}
+ self._sub_lock = asyncio.Lock()
+ self._renewal_task: asyncio.Task[None] | None = None
+
+ # (channel_id, agent_name) -> live "working on it…" message ref.
+ self._working_msg: dict[tuple[str, str], str] = {}
+ # (channel_id, agent_name) -> live "needs your input" ping refs.
+ self._input_pings: dict[tuple[str, str], list[str]] = {}
+
+ # ── Lifecycle ────────────────────────────────────────────────────────────
+
+ async def start(
+ self,
+ on_message: Callable[[InboundMessage], Awaitable[None]],
+ on_command: Callable[[InboundCommand], Awaitable[None]],
+ on_agent_joined: Callable[[InboundAgentJoin], Awaitable[None]],
+ on_user_joined: Callable[[InboundUserJoin], Awaitable[None]],
+ on_app_joined: Callable[[InboundAppJoin], Awaitable[None]],
+ ) -> None:
+ self._on_message = on_message
+ self._on_command = on_command
+ self._on_agent_joined = on_agent_joined
+ self._on_user_joined = on_user_joined
+ self._on_app_joined = on_app_joined
+
+ self._http = httpx.AsyncClient(timeout=30)
+ self._tokens = TeamsTokenProvider(
+ tenant_id=self._config.tenant_id,
+ app_id=self._config.app_id,
+ app_password=self._config.app_password,
+ http=self._http,
+ )
+ self._connector = BotConnectorClient(tokens=self._tokens, http=self._http)
+ self._graph = GraphClient(tokens=self._tokens, http=self._http)
+ self._validator = InboundActivityValidator(app_id=self._config.app_id)
+
+ app = web.Application()
+ app.router.add_post("/api/messages", self._handle_http_messages)
+ app.router.add_post("/api/teams/notifications", self._handle_http_notifications)
+ app.router.add_get("/api/teams/notifications", self._handle_http_notifications)
+ self._runner = web.AppRunner(app)
+ await self._runner.setup()
+ site = web.TCPSite(
+ self._runner, self._config.listen_host, self._config.listen_port
+ )
+ await site.start()
+ logger.info(
+ "Teams adapter listening on %s:%d (app %s)",
+ self._config.listen_host,
+ self._config.listen_port,
+ self._config.app_id,
+ )
+ await self._adopt_existing_subscriptions()
+ self._renewal_task = asyncio.create_task(self._renewal_loop())
+
+ @property
+ def _notification_url(self) -> str:
+ base = self._config.public_base_url.rstrip("/")
+ return f"{base}/api/teams/notifications"
+
+ async def _adopt_existing_subscriptions(self) -> None:
+ """Re-attach to subscriptions this bridge already owns after a restart,
+ and delete stale ones left by a previous notification URL.
+
+ Graph subscriptions outlive the process, so on start we reclaim any that
+ point at our current notification URL rather than blindly creating
+ duplicates. Subscriptions for our channels that point at a *different*
+ URL (e.g. a rotated tunnel) can never deliver here, so we delete them;
+ ``ensure_channel_subscriptions`` then recreates them against the current
+ URL."""
+ if self._graph is None:
+ return
+ try:
+ existing = await self._graph.list_subscriptions()
+ except Exception:
+ logger.warning("Could not list existing Graph subscriptions on start")
+ return
+ for sub in existing:
+ resource = str(sub.get("resource", ""))
+ channel_id = self._channel_from_resource(resource)
+ if not channel_id:
+ continue
+ if sub.get("notificationUrl") == self._notification_url:
+ self._subscriptions[channel_id] = str(sub.get("id", ""))
+ continue
+ stale_id = str(sub.get("id", ""))
+ if not stale_id:
+ continue
+ try:
+ await self._graph.delete_subscription(subscription_id=stale_id)
+ logger.info(
+ "Deleted stale Teams subscription %s for channel %s "
+ "(notification URL changed)",
+ stale_id,
+ channel_id,
+ )
+ except Exception:
+ logger.warning("Failed to delete stale Teams subscription %s", stale_id)
+ if self._subscriptions:
+ logger.info(
+ "Re-attached to %d existing Teams subscriptions",
+ len(self._subscriptions),
+ )
+
+ async def ensure_channel_subscriptions(
+ self, channels: list[tuple[str, str]]
+ ) -> None:
+ """Recreate Graph subscriptions for known channels that lack a live one.
+
+ Called on startup with the bridge's channels so capture self-heals after
+ a restart or notification-URL change: ``_adopt_existing_subscriptions``
+ keeps still-valid subscriptions and clears stale ones, then this creates
+ any that are missing. ``_ensure_channel_subscription`` skips channels
+ already subscribed and logs (does not raise) on failure, so one bad
+ channel does not block the rest."""
+ for channel_id, channel_type in channels:
+ if channel_type in ("channel_public", "channel_private"):
+ await self._ensure_channel_subscription(channel_id)
+
+ async def _renewal_loop(self) -> None:
+ """Proactively renew channel-message subscriptions before they expire.
+
+ Complements the reactive ``reauthorizationRequired`` lifecycle handler:
+ even if a lifecycle notification is missed, subscriptions are refreshed
+ on this cadence so capture never silently lapses."""
+ while True:
+ await asyncio.sleep(_RENEWAL_INTERVAL_SECONDS)
+ await self._renew_all_subscriptions()
+
+ async def _renew_all_subscriptions(self) -> None:
+ if self._graph is None:
+ return
+ for channel_id, subscription_id in list(self._subscriptions.items()):
+ try:
+ await self._graph.renew_subscription(
+ subscription_id=subscription_id,
+ expiration_iso=self._expiration_iso(),
+ )
+ except Exception:
+ logger.exception(
+ "Failed to renew subscription %s for channel %s",
+ subscription_id,
+ channel_id,
+ )
+
+ async def stop(self) -> None:
+ if self._renewal_task is not None:
+ self._renewal_task.cancel()
+ try:
+ await self._renewal_task
+ except asyncio.CancelledError:
+ pass
+ self._renewal_task = None
+ if self._runner is not None:
+ await self._runner.cleanup()
+ self._runner = None
+ if self._validator is not None:
+ self._validator.close()
+ self._validator = None
+ if self._http is not None:
+ await self._http.aclose()
+ self._http = None
+ logger.info("Teams adapter stopped")
+
+ # ── Outbound helpers ─────────────────────────────────────────────────────
+
+ def _service_url_for(self, channel_id: str) -> str:
+ url = self._service_url.get(channel_id) or self._default_service_url
+ if not url:
+ raise RuntimeError(
+ f"no Bot Connector serviceUrl known for channel {channel_id} — "
+ "the bot has not yet received an activity from this tenant"
+ )
+ return url
+
+ def set_service_url_persister(
+ self, persist: Callable[[str], Awaitable[None]]
+ ) -> None:
+ self._persist_service_url = persist
+
+ async def _learn_service_url(self, service_url: str) -> None:
+ """Record a serviceUrl observed on an inbound activity, persisting it
+ when it is new or changed so outbound survives the next restart."""
+ if service_url == self._default_service_url:
+ return
+ self._default_service_url = service_url
+ if self._persist_service_url is None:
+ return
+ try:
+ await self._persist_service_url(service_url)
+ except Exception:
+ logger.warning("Failed to persist Teams serviceUrl", exc_info=True)
+
+ def _is_channel(self, channel_id: str) -> bool:
+ """Whether ``channel_id`` is a Teams channel (threaded) vs a flat chat.
+
+ Learned type wins; otherwise fall back to the id shape (channels use
+ ``@thread.tacv2``). Switch-created channels default to channel."""
+ known = self._channel_type.get(channel_id)
+ if known is not None:
+ return known in ("channel_public", "channel_private")
+ return "@thread.tacv2" in channel_id or channel_id not in self._channel_type
+
+ @staticmethod
+ def _thread_conversation(channel_id: str, root_id: str) -> str:
+ return f"{channel_id};messageid={root_id}"
+
+ def _message_activity(self, sender_name: str, body: str) -> dict[str, Any]:
+ return {
+ "type": "message",
+ # Notification/preview text; without it Teams renders a
+ # "cards.unsupported" placeholder in toasts, mobile, and link previews.
+ "summary": f"{sender_name}: {body}",
+ "attachments": [card_attachment(agent_message_card(sender_name, body))],
+ }
+
+ # ── Messaging ────────────────────────────────────────────────────────────
+
+ async def send_message(
+ self,
+ channel_id: str,
+ sender_name: str,
+ content: str,
+ thread_root_id: str | None = None,
+ ) -> str | None:
+ if self._connector is None:
+ raise RuntimeError("Cannot send message: Teams adapter not started")
+
+ service_url = self._service_url_for(channel_id)
+ activity = self._message_activity(sender_name, self.translate_outbound(content))
+
+ if self._is_channel(channel_id) and thread_root_id is None:
+ conversation_id, msg_id = await self._connector.create_channel_thread(
+ service_url=service_url, channel_id=channel_id, activity=activity
+ )
+ else:
+ conversation_id = (
+ self._thread_conversation(channel_id, thread_root_id)
+ if thread_root_id and self._is_channel(channel_id)
+ else channel_id
+ )
+ msg_id = await self._connector.send_to_conversation(
+ service_url=service_url,
+ conversation_id=conversation_id,
+ activity=activity,
+ )
+
+ if msg_id:
+ self._sent[msg_id] = (service_url, conversation_id)
+ return msg_id
+ return None
+
+ async def admin_message(
+ self,
+ channel_id: str,
+ content: str,
+ thread_root_id: str | None = None,
+ *,
+ message_type: str | None = None,
+ ) -> str | None:
+ # Admin/system messages render as the Switch bot itself — a plain text
+ # activity, no per-agent Adaptive Card — so they read as the platform
+ # speaking rather than an agent.
+ if self._connector is None:
+ raise RuntimeError("Cannot post admin message: Teams adapter not started")
+
+ service_url = self._service_url_for(channel_id)
+ activity = {"type": "message", "text": self.translate_outbound(content)}
+
+ if self._is_channel(channel_id) and thread_root_id is None:
+ conversation_id, msg_id = await self._connector.create_channel_thread(
+ service_url=service_url, channel_id=channel_id, activity=activity
+ )
+ else:
+ conversation_id = (
+ self._thread_conversation(channel_id, thread_root_id)
+ if thread_root_id and self._is_channel(channel_id)
+ else channel_id
+ )
+ msg_id = await self._connector.send_to_conversation(
+ service_url=service_url,
+ conversation_id=conversation_id,
+ activity=activity,
+ )
+
+ if msg_id:
+ self._sent[msg_id] = (service_url, conversation_id)
+ return msg_id
+ return None
+
+ def _locate(self, channel_id: str, message_ref: str) -> tuple[str, str]:
+ """Resolve ``(service_url, conversation_id)`` for a previously sent
+ message so it can be edited or deleted. Falls back to treating the
+ message as its own thread root when it wasn't sent in this session."""
+ located = self._sent.get(message_ref)
+ if located is not None:
+ return located
+ logger.warning(
+ "No tracked conversation for Teams message %s; reconstructing", message_ref
+ )
+ return (
+ self._service_url_for(channel_id),
+ self._thread_conversation(channel_id, message_ref),
+ )
+
+ async def update_message(
+ self, channel_id: str, message_ref: str, new_content: str
+ ) -> None:
+ if self._connector is None:
+ raise RuntimeError("Cannot update message: Teams adapter not started")
+ service_url, conversation_id = self._locate(channel_id, message_ref)
+ await self._connector.update_activity(
+ service_url=service_url,
+ conversation_id=conversation_id,
+ activity_id=message_ref,
+ activity={"type": "message", "text": self.translate_outbound(new_content)},
+ )
+
+ async def delete_message(self, channel_id: str, message_ref: str) -> None:
+ if self._connector is None:
+ raise RuntimeError("Cannot delete message: Teams adapter not started")
+ service_url, conversation_id = self._locate(channel_id, message_ref)
+ await self._connector.delete_activity(
+ service_url=service_url,
+ conversation_id=conversation_id,
+ activity_id=message_ref,
+ )
+ self._sent.pop(message_ref, None)
+
+ async def send_typing(
+ self, channel_id: str, sender_name: str, is_typing: bool
+ ) -> None:
+ # Teams typing indicators auto-expire and are best-effort cosmetics; a
+ # failure to show one must not break the turn.
+ if not is_typing or self._connector is None:
+ return
+ try:
+ await self._connector.send_to_conversation(
+ service_url=self._service_url_for(channel_id),
+ conversation_id=channel_id,
+ activity={"type": "typing"},
+ )
+ except Exception:
+ logger.warning("Failed to send typing indicator to %s", channel_id)
+
+ # ── Runtime state ──────────────────────────────────────────────────────────
+
+ async def apply_runtime_state(
+ self,
+ channel_id: str,
+ agent_name: str,
+ state: str,
+ *,
+ notify_user: str | None,
+ thread_root_id: str | None,
+ deeplink_url: str | None = None,
+ detail: str | None = None,
+ ) -> None:
+ """Persistent status messages, mirroring Slack.
+
+ A "working on it…" card is posted (as the agent) while the agent works
+ and edited in place as the activity detail changes; it stays up through
+ ``awaiting-input`` — where a "needs your input" ping is added — and both
+ are removed when the turn goes ``idle`` (or resumes to ``working``,
+ since the requested input was provided). Teams messages are truly
+ deletable, so no tombstone is left behind.
+ """
+ key = (channel_id, agent_name)
+ if state == "working":
+ await self._clear_input_pings(channel_id, agent_name)
+ body = self._working_body(detail, deeplink_url)
+ existing = self._working_msg.get(key)
+ if existing is not None:
+ await self._refresh_card(channel_id, existing, agent_name, body)
+ return
+ ref = await self.send_message(channel_id, agent_name, body, thread_root_id)
+ if ref is not None:
+ self._working_msg[key] = ref
+ elif state == "awaiting-input":
+ ref = await self._ping_operator(
+ channel_id, agent_name, notify_user, thread_root_id, deeplink_url
+ )
+ if ref is not None:
+ self._input_pings.setdefault(key, []).append(ref)
+ else:
+ await self._clear_working(channel_id, agent_name)
+ await self._clear_input_pings(channel_id, agent_name)
+
+ async def _refresh_card(
+ self, channel_id: str, message_ref: str, agent_name: str, body: str
+ ) -> None:
+ if self._connector is None:
+ return
+ service_url, conversation_id = self._locate(channel_id, message_ref)
+ await self._connector.update_activity(
+ service_url=service_url,
+ conversation_id=conversation_id,
+ activity_id=message_ref,
+ activity=self._message_activity(agent_name, body),
+ )
+
+ async def _clear_working(self, channel_id: str, agent_name: str) -> None:
+ ref = self._working_msg.pop((channel_id, agent_name), None)
+ if ref is not None:
+ await self.delete_message(channel_id, ref)
+
+ async def _clear_input_pings(self, channel_id: str, agent_name: str) -> None:
+ refs = self._input_pings.pop((channel_id, agent_name), [])
+ for ref in refs:
+ await self.delete_message(channel_id, ref)
+
+ # ── Channels ─────────────────────────────────────────────────────────────
+
+ @staticmethod
+ def _sanitize_channel_name(name: str) -> str:
+ """Teams channel display names disallow several characters and cap at
+ 50 chars. Replace the reserved set and trim."""
+ cleaned = re.sub(r'[~#%&*{}+/\\:<>?|\'"]', "-", name).strip(" .-")
+ return (cleaned or "switch")[:50]
+
+ async def create_channel(
+ self,
+ name: str,
+ topic: str,
+ *,
+ channel_type: ChannelType = "channel_public",
+ ) -> str:
+ if self._graph is None:
+ raise RuntimeError("Teams adapter not started")
+ if channel_type in ("group", "direct"):
+ raise ValueError(
+ f"Cannot create {channel_type} channels — they are initiated "
+ "from the messaging platform"
+ )
+
+ membership_type = "private" if channel_type == "channel_private" else "standard"
+ channel = await self._graph.create_channel(
+ team_id=self._config.team_id,
+ display_name=self._sanitize_channel_name(name),
+ description=topic,
+ membership_type=membership_type,
+ )
+ channel_id = str(channel.get("id", ""))
+ if not channel_id:
+ raise RuntimeError(f"Teams channel creation returned no id for '{name}'")
+
+ self._channel_type[channel_id] = channel_type
+ self._team_of_channel[channel_id] = self._config.team_id
+ # Capture the new channel's messages right away.
+ await self._ensure_channel_subscription(channel_id)
+ return channel_id
+
+ async def get_channel_type(self, channel_id: str) -> ChannelType:
+ known = self._channel_type.get(channel_id)
+ if known is not None:
+ return known
+ if self._graph is None:
+ raise RuntimeError("Teams adapter not started")
+ team_id = self._team_of_channel.get(channel_id, self._config.team_id)
+ channel = await self._graph.get_channel(team_id=team_id, channel_id=channel_id)
+ resolved: ChannelType = (
+ "channel_private"
+ if channel.get("membershipType") == "private"
+ else "channel_public"
+ )
+ self._channel_type[channel_id] = resolved
+ return resolved
+
+ async def channel_deeplink(self, external_channel_id: str) -> str | None:
+ """`https://teams.microsoft.com/l/channel/...` opening the channel in the
+ Teams client. Built from the channel id, its team, and the tenant."""
+ if not external_channel_id:
+ return None
+ team_id = self._team_of_channel.get(external_channel_id, self._config.team_id)
+ encoded = quote(external_channel_id, safe="")
+ return (
+ f"https://teams.microsoft.com/l/channel/{encoded}/channel"
+ f"?groupId={team_id}&tenantId={self._config.tenant_id}"
+ )
+
+ async def add_agents_to_channel(
+ self, channel_id: str, agent_names: list[str]
+ ) -> None:
+ # Single-bot identity model: agents share one Teams bot, so there is no
+ # per-agent membership to manage (mirrors Slack).
+ pass
+
+ async def add_users_to_channel(
+ self,
+ channel_id: str,
+ user_names: list[str],
+ user_external_ids: list[str],
+ ) -> None:
+ if self._graph is None:
+ raise RuntimeError("Teams adapter not started")
+ team_id = self._team_of_channel.get(channel_id, self._config.team_id)
+ # Private channels have their own membership; standard channels inherit
+ # the team's, so a user is added to the team instead.
+ is_private = self._channel_type.get(channel_id) == "channel_private"
+ failed: list[str] = []
+ for user_id in user_external_ids:
+ try:
+ if is_private:
+ await self._graph.add_channel_member(
+ team_id=team_id, channel_id=channel_id, user_aad_id=user_id
+ )
+ else:
+ await self._graph.add_team_member(
+ team_id=team_id, user_aad_id=user_id
+ )
+ except Exception:
+ logger.exception(
+ "Failed to add user %s to Teams channel %s", user_id, channel_id
+ )
+ failed.append(user_id)
+ if failed:
+ raise RuntimeError(
+ f"Failed to add {len(failed)} user(s) to Teams channel "
+ f"{channel_id}: {', '.join(failed)}"
+ )
+
+ # ── Agent identity ───────────────────────────────────────────────────────
+
+ async def create_agent_identity(
+ self, agent_name: str, agent_description: str
+ ) -> None:
+ # Single-bot model: no per-agent platform account is created.
+ pass
+
+ async def remove_agent_identity(self, agent_name: str) -> None:
+ pass
+
+ async def get_channel_agent_names(self, channel_id: str) -> list[str]:
+ # Single shared bot cannot enumerate per-agent membership (mirrors Slack).
+ return []
+
+ # ── Translation ──────────────────────────────────────────────────────────
+
+ def translate_outbound(self, content: str) -> str:
+ return content
+
+ def translate_inbound(self, raw_message: str) -> str:
+ return raw_message
+
+ # ── Inbound listener ─────────────────────────────────────────────────────
+
+ async def _handle_http_messages(self, request: web.Request) -> web.Response:
+ auth_header = request.headers.get("Authorization")
+ if self._validator is not None:
+ try:
+ await asyncio.get_running_loop().run_in_executor(
+ None, self._validator.validate, auth_header
+ )
+ except Exception as e:
+ logger.warning("Rejected inbound Teams activity: %s", e)
+ return web.Response(status=401, text="unauthorized")
+
+ try:
+ activity = await request.json()
+ except Exception:
+ return web.Response(status=400, text="invalid json")
+
+ try:
+ await self._dispatch_activity(activity)
+ except Exception:
+ logger.exception("Failed to handle inbound Teams activity")
+
+ return web.Response(status=200)
+
+ async def _dispatch_activity(self, activity: dict[str, Any]) -> None:
+ service_url = str(activity.get("serviceUrl", "")).strip()
+ activity_type = activity.get("type")
+
+ channel_id, channel_type = self._channel_from_activity(activity)
+ if service_url and channel_id:
+ self._service_url[channel_id] = service_url
+ await self._learn_service_url(service_url)
+ self._channel_type[channel_id] = channel_type
+
+ team = (activity.get("channelData") or {}).get("team") or {}
+ # Graph channel subscriptions key on the team's AAD group GUID, which
+ # Teams sends as ``aadGroupId``. ``team.id`` is the non-GUID channel
+ # thread id and Graph rejects it ("TeamGroupId must be ... a valid
+ # GUID"). Fall back to the configured team_id, which is also that GUID.
+ group_id = team.get("aadGroupId") or self._config.team_id
+ if group_id and channel_id:
+ self._team_of_channel[channel_id] = str(group_id)
+
+ if activity_type == "message":
+ await self._dispatch_message(activity, channel_id, channel_type)
+ elif activity_type == "conversationUpdate":
+ await self._dispatch_conversation_update(activity, channel_id, channel_type)
+
+ @staticmethod
+ def _channel_from_activity(
+ activity: dict[str, Any],
+ ) -> tuple[str, ChannelType]:
+ conversation = activity.get("conversation") or {}
+ conv_id = str(conversation.get("id", ""))
+ conv_type = conversation.get("conversationType", "")
+ channel_data = activity.get("channelData") or {}
+ channel = channel_data.get("channel") or {}
+
+ if conv_type == "channel" or "@thread.tacv2" in conv_id:
+ channel_id = str(channel.get("id") or conv_id.split(";", 1)[0])
+ return channel_id, "channel_public"
+ if conv_type == "personal":
+ return conv_id, "direct"
+ if conv_type == "groupChat":
+ return conv_id, "group"
+ return conv_id.split(";", 1)[0], "channel_public"
+
+ def _seen_activity(self, activity_id: str) -> bool:
+ if not activity_id:
+ return False
+ if activity_id in self._seen:
+ return True
+ self._seen[activity_id] = None
+ if len(self._seen) > self._seen_max:
+ self._seen.popitem(last=False)
+ return False
+
+ async def _dispatch_message(
+ self, activity: dict[str, Any], channel_id: str, channel_type: ChannelType
+ ) -> None:
+ activity_id = str(activity.get("id", ""))
+ if self._seen_activity(activity_id):
+ return
+
+ sender = activity.get("from") or {}
+ sender_id = str(sender.get("aadObjectId") or sender.get("id") or "")
+ sender_name = str(sender.get("name") or sender_id)
+
+ raw_text = str(activity.get("text", ""))
+ text = self._clean_text(raw_text)
+ text += self._disclosed_attachment_note(
+ self._activity_attachment_descriptors(activity)
+ )
+ self_mention_token = self._self_mention_token(activity)
+ command_text = (
+ self._clean_text(_strip_leading_mention(raw_text))
+ if self_mention_token is not None
+ else text
+ )
+
+ conversation = activity.get("conversation") or {}
+ conv_id = str(conversation.get("id", ""))
+ root_id: str | None = None
+ if ";messageid=" in conv_id:
+ thread_root = conv_id.split(";messageid=", 1)[1]
+ if thread_root and thread_root != activity_id:
+ root_id = thread_root
+
+ channel_name = self._channel_name(activity)
+
+ await self._deliver(
+ channel_id=channel_id,
+ channel_type=channel_type,
+ sender_id=sender_id,
+ sender_name=sender_name,
+ text=text,
+ message_ref=activity_id,
+ root_id=root_id,
+ channel_name=channel_name,
+ self_mention_token=self_mention_token,
+ command_text=command_text,
+ )
+
+ async def _deliver(
+ self,
+ *,
+ channel_id: str,
+ channel_type: ChannelType,
+ sender_id: str,
+ sender_name: str,
+ text: str,
+ message_ref: str,
+ root_id: str | None,
+ channel_name: str | None,
+ self_mention_token: str | None = None,
+ command_text: str | None = None,
+ ) -> None:
+ """Route a parsed inbound message to the command or message callback.
+
+ Shared by the Bot Framework activity path and the Graph capture path so
+ both apply the same ``!``-command detection and translation.
+
+ ``command_text`` is the message with a leading bot @mention removed; it is
+ used only to detect and parse ``!``-commands (a channel command arrives as
+ ``@Bot !cmd``), while ``text`` — mention intact — is what a plain message
+ is bridged as. Defaults to ``text`` when the caller has nothing to strip."""
+ command_probe = (command_text if command_text is not None else text).strip()
+ if command_probe.startswith("!") and self._on_command is not None:
+ parts = command_probe.split(None, 1)
+ await self._on_command(
+ InboundCommand(
+ channel_id=channel_id,
+ channel_type=channel_type,
+ sender_id=sender_id,
+ sender_name=sender_name,
+ command=parts[0].lstrip("!"),
+ args=parts[1].strip() if len(parts) > 1 else "",
+ message_ref=message_ref,
+ root_id=root_id,
+ channel_name=channel_name,
+ )
+ )
+ return
+
+ if self._on_message is not None:
+ await self._on_message(
+ InboundMessage(
+ channel_id=channel_id,
+ channel_type=channel_type,
+ sender_id=sender_id,
+ sender_name=sender_name,
+ content=self.translate_inbound(text),
+ message_ref=message_ref,
+ root_id=root_id,
+ channel_name=channel_name,
+ self_mention_token=self_mention_token,
+ )
+ )
+
+ async def _dispatch_conversation_update(
+ self, activity: dict[str, Any], channel_id: str, channel_type: ChannelType
+ ) -> None:
+ members_added = activity.get("membersAdded") or []
+ recipient = activity.get("recipient") or {}
+ bot_id = str(recipient.get("id", ""))
+ channel_name = self._channel_name(activity)
+
+ for member in members_added:
+ member_id = str(member.get("id", ""))
+ if member_id == bot_id:
+ # The bot was added to a channel/team → start capturing all of
+ # its messages via a Graph subscription (channels only; chats are
+ # captured through the Bot Framework path).
+ if channel_type in ("channel_public", "channel_private"):
+ await self._ensure_channel_subscription(channel_id)
+ if self._on_app_joined is not None:
+ await self._on_app_joined(
+ InboundAppJoin(
+ channel_id=channel_id,
+ channel_type=channel_type,
+ channel_name=channel_name,
+ )
+ )
+ elif self._on_user_joined is not None:
+ await self._on_user_joined(
+ InboundUserJoin(
+ channel_id=channel_id,
+ channel_type=channel_type,
+ external_user_id=str(member.get("aadObjectId") or member_id),
+ external_username=str(member.get("name") or member_id),
+ channel_name=channel_name,
+ )
+ )
+
+ @staticmethod
+ def _channel_name(activity: dict[str, Any]) -> str | None:
+ channel_data = activity.get("channelData") or {}
+ team = channel_data.get("team") or {}
+ name = team.get("name")
+ return str(name) if name else None
+
+ def _self_mention_token(self, activity: dict[str, Any]) -> str | None:
+ recipient = activity.get("recipient") or {}
+ bot_id = str(recipient.get("id", ""))
+ for entity in activity.get("entities") or []:
+ if entity.get("type") == "mention":
+ mentioned = entity.get("mentioned") or {}
+ if str(mentioned.get("id", "")) == bot_id:
+ return bot_id
+ return None
+
+ @staticmethod
+ def _clean_text(text: str) -> str:
+ """Rewrite Teams ``<at>…</at>`` mention markup to ``@<name>`` text."""
+ return _render_mentions(text).strip()
+
+ @staticmethod
+ def _disclosed_attachment_note(descriptors: list[str]) -> str:
+ """A visible note naming inbound attachments that were not relayed.
+
+ Teams inbound file/image relay is not yet implemented; rather than drop
+ media silently (which would violate the fail-loud rule and mislead the
+ agent), we bridge the text and append this disclosure. Empty when there
+ is nothing to disclose."""
+ if not descriptors:
+ return ""
+ if len(descriptors) == 1:
+ return f"\n\n_📎 an attachment was not relayed: {descriptors[0]}_"
+ joined = ", ".join(descriptors)
+ return f"\n\n_📎 {len(descriptors)} attachments were not relayed: {joined}_"
+
+ @staticmethod
+ def _activity_attachment_descriptors(activity: dict[str, Any]) -> list[str]:
+ """Names of real file/image attachments on a Bot Framework activity.
+
+ Excludes ``text/*`` attachments, which carry the message's own HTML/text
+ body rather than a user-supplied file."""
+ out: list[str] = []
+ for att in activity.get("attachments") or []:
+ content_type = str(att.get("contentType", ""))
+ if content_type.startswith("text/"):
+ continue
+ name = str(att.get("name") or "").strip()
+ out.append(name or content_type or "attachment")
+ return out
+
+ @staticmethod
+ def _graph_attachment_descriptors(chat_message: dict[str, Any]) -> list[str]:
+ """Names of attachments + inline hosted images on a Graph chat message."""
+ out: list[str] = []
+ for att in chat_message.get("attachments") or []:
+ name = str(att.get("name") or "").strip()
+ content_type = str(att.get("contentType", ""))
+ out.append(name or content_type or "attachment")
+ hosted = chat_message.get("hostedContents") or []
+ if hosted:
+ out.append(f"{len(hosted)} inline image(s)")
+ return out
+
+ # ── Graph capture (subscriptions + notifications) ────────────────────────
+
+ @staticmethod
+ def _expiration_iso() -> str:
+ expiry = datetime.now(UTC) + _SUBSCRIPTION_TTL
+ return expiry.replace(microsecond=0).isoformat().replace("+00:00", "Z")
+
+ @staticmethod
+ def _channel_from_resource(resource: str) -> str:
+ """Extract the channel id from a subscription's ``resource`` string
+ (``teams/{team}/channels/{channel}/messages``)."""
+ match = re.search(r"channels/([^/]+)/messages", resource)
+ return match.group(1) if match else ""
+
+ async def _ensure_channel_subscription(self, channel_id: str) -> None:
+ """Create a Graph change-notification subscription for a channel's
+ messages, so the bridge captures every post — not just @mentions.
+
+ Requires the encryption certificate + private key (Graph encrypts the
+ message body) and the channel's team id. A missing prerequisite is a
+ loud log, not a crash: the bot still joins, capture is simply degraded.
+ """
+ if channel_id in self._subscriptions or self._graph is None:
+ return
+ if not (
+ self._config.encryption_public_certificate
+ and self._config.encryption_certificate_id
+ ):
+ logger.error(
+ "Cannot subscribe to channel %s messages: encryption certificate "
+ "not configured on the Teams bridge",
+ channel_id,
+ )
+ return
+ team_id = self._team_of_channel.get(channel_id) or self._config.team_id
+ if not team_id:
+ logger.warning(
+ "Cannot subscribe to channel %s: team id unknown", channel_id
+ )
+ return
+
+ async with self._sub_lock:
+ if channel_id in self._subscriptions:
+ return
+ try:
+ cert_der = load_certificate_der_b64(
+ self._config.encryption_public_certificate
+ )
+ sub = await self._graph.create_subscription(
+ resource=f"teams/{team_id}/channels/{channel_id}/messages",
+ notification_url=self._notification_url,
+ lifecycle_notification_url=self._notification_url,
+ client_state=self._config.client_state,
+ expiration_iso=self._expiration_iso(),
+ encryption_certificate=cert_der,
+ encryption_certificate_id=self._config.encryption_certificate_id,
+ )
+ except Exception:
+ logger.exception(
+ "Failed to create Graph subscription for channel %s", channel_id
+ )
+ return
+ self._subscriptions[channel_id] = str(sub.get("id", ""))
+ logger.info(
+ "Subscribed to Teams channel %s messages (subscription %s)",
+ channel_id,
+ self._subscriptions[channel_id],
+ )
+
+ async def _handle_http_notifications(self, request: web.Request) -> web.Response:
+ # Subscription-creation handshake: Graph calls the endpoint with a
+ # ``validationToken`` that must be echoed back verbatim as text/plain.
+ validation_token = request.query.get("validationToken")
+ if validation_token is not None:
+ return web.Response(
+ status=200, text=validation_token, content_type="text/plain"
+ )
+
+ try:
+ payload = await request.json()
+ except Exception:
+ return web.Response(status=400, text="invalid json")
+
+ for item in payload.get("value", []):
+ try:
+ await self._dispatch_graph_notification(item)
+ except Exception:
+ logger.exception("Failed to handle Graph change notification")
+
+ return web.Response(status=202)
+
+ async def _dispatch_graph_notification(self, item: dict[str, Any]) -> None:
+ # Authenticate origin BEFORE acting on anything — data notifications and
+ # lifecycle events alike. clientState is the only origin control (the
+ # encryption proves integrity, not origin), so an unverified lifecycle
+ # event (e.g. a forged reauthorizationRequired) must not be honoured.
+ if item.get("clientState") != self._config.client_state:
+ logger.warning("Rejected Graph notification: clientState mismatch")
+ return
+
+ if item.get("lifecycleEvent"):
+ await self._handle_lifecycle_event(item)
+ return
+
+ encrypted = item.get("encryptedContent")
+ if not encrypted:
+ return
+ if not self._config.encryption_private_key:
+ logger.error(
+ "Received encrypted Graph notification but no private key is "
+ "configured to decrypt it"
+ )
+ return
+
+ chat_message = decrypt_resource_data(
+ encrypted, self._config.encryption_private_key
+ )
+ await self._deliver_graph_message(chat_message)
+
+ async def _handle_lifecycle_event(self, item: dict[str, Any]) -> None:
+ event = item.get("lifecycleEvent")
+ subscription_id = str(item.get("subscriptionId", ""))
+ if event == "reauthorizationRequired" and self._graph is not None:
+ try:
+ await self._graph.renew_subscription(
+ subscription_id=subscription_id,
+ expiration_iso=self._expiration_iso(),
+ )
+ logger.info("Renewed Teams subscription %s", subscription_id)
+ except Exception:
+ logger.exception(
+ "Failed to renew Teams subscription %s", subscription_id
+ )
+ elif event == "subscriptionRemoved":
+ # Graph dropped the subscription (e.g. a transient permission/quota
+ # issue). Recreate it rather than only logging — otherwise channel
+ # capture silently lapses until the next full restart.
+ await self._recreate_removed_subscription(subscription_id)
+ else:
+ logger.info(
+ "Teams subscription %s lifecycle event: %s",
+ subscription_id,
+ event,
+ )
+
+ async def _recreate_removed_subscription(self, subscription_id: str) -> None:
+ channel_id = next(
+ (c for c, s in self._subscriptions.items() if s == subscription_id),
+ None,
+ )
+ if channel_id is None:
+ logger.info(
+ "Teams subscriptionRemoved for unknown subscription %s; ignoring",
+ subscription_id,
+ )
+ return
+ logger.warning(
+ "Teams subscription %s for channel %s was removed; recreating",
+ subscription_id,
+ channel_id,
+ )
+ # Drop the dead mapping so _ensure_channel_subscription rebuilds it.
+ self._subscriptions.pop(channel_id, None)
+ await self._ensure_channel_subscription(channel_id)
+
+ async def _deliver_graph_message(self, chat_message: dict[str, Any]) -> None:
+ if chat_message.get("messageType", "message") != "message":
+ return
+
+ message_id = str(chat_message.get("id", ""))
+ if self._seen_activity(message_id):
+ return
+
+ sender = chat_message.get("from") or {}
+ application = sender.get("application") or {}
+ if application:
+ # Drop our own bot's posts (they are captured too) to avoid a loop.
+ if str(application.get("id", "")) == self._config.app_id:
+ return
+ sender_id = str(application.get("id", ""))
+ sender_name = str(application.get("displayName") or sender_id)
+ else:
+ user = sender.get("user") or {}
+ sender_id = str(user.get("id", ""))
+ sender_name = str(user.get("displayName") or sender_id)
+
+ identity = chat_message.get("channelIdentity") or {}
+ channel_id = str(identity.get("channelId", ""))
+ if not channel_id:
+ return
+
+ body = chat_message.get("body") or {}
+ raw_content = str(body.get("content", ""))
+ is_html = str(body.get("contentType", "")).lower() == "html"
+ content = self._graph_text(raw_content) if is_html else raw_content
+ content += self._disclosed_attachment_note(
+ self._graph_attachment_descriptors(chat_message)
+ )
+
+ self_mention_token = self._graph_self_mention_token(chat_message)
+ if self_mention_token is not None:
+ stripped = _strip_leading_mention(raw_content)
+ command_text = self._graph_text(stripped) if is_html else stripped
+ else:
+ command_text = content
+
+ reply_to = chat_message.get("replyToId")
+ root_id = str(reply_to) if reply_to and str(reply_to) != message_id else None
+
+ await self._deliver(
+ channel_id=channel_id,
+ channel_type=self._channel_type.get(channel_id, "channel_public"),
+ sender_id=sender_id,
+ sender_name=sender_name,
+ text=content,
+ message_ref=message_id,
+ root_id=root_id,
+ channel_name=None,
+ self_mention_token=self_mention_token,
+ command_text=command_text,
+ )
+
+ def _graph_self_mention_token(self, chat_message: dict[str, Any]) -> str | None:
+ """Return a truthy token when a Graph channel message @mentions our bot.
+
+ Graph carries mentions in ``chat_message["mentions"]``; a bot mention is
+ one whose ``mentioned.application.id`` matches our app id. Mirrors the
+ Bot Framework path's ``_self_mention_token`` so both capture paths flag a
+ bot mention identically."""
+ for mention in chat_message.get("mentions") or []:
+ mentioned = mention.get("mentioned") or {}
+ application = mentioned.get("application") or {}
+ if str(application.get("id", "")) == self._config.app_id:
+ return self._config.app_id
+ return None
+
+ @staticmethod
+ def _graph_text(content: str) -> str:
+ """Flatten a Graph channel message's HTML body to plain text."""
+ text = _BR_TAG.sub("\n", content)
+ text = _render_mentions(text)
+ text = _HTML_TAG.sub("", text)
+ return html.unescape(text).strip()
diff --git a/core/switch_core/bridges/collaboration/teams/auth.py b/core/switch_core/bridges/collaboration/teams/auth.py
new file mode 100644
index 000000000..d5b9b8bc5
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/teams/auth.py
@@ -0,0 +1,124 @@
+from __future__ import annotations
+
+import logging
+import time
+
+import httpx
+import jwt
+from jwt import PyJWKClient
+
+logger = logging.getLogger(__name__)
+
+# Scope for the Bot Connector service (outbound activities via serviceUrl).
+BOT_CONNECTOR_SCOPE = "https://api.botframework.com/.default"
+# Scope for Microsoft Graph (channel-message capture + provisioning).
+GRAPH_SCOPE = "https://graph.microsoft.com/.default"
+
+# OpenID metadata for tokens the Bot Connector attaches to inbound activities.
+_BOTFRAMEWORK_OPENID = (
+ "https://login.botframework.com/v1/.well-known/openidconfiguration"
+)
+# Expected issuer of Bot Connector tokens (public Azure cloud).
+_BOTFRAMEWORK_ISSUER = "https://api.botframework.com"
+
+
+class TeamsTokenProvider:
+ """Acquires and caches AAD app-only (client-credentials) access tokens.
+
+ One provider per bridge, shared by the Bot Connector (outbound) and Graph
+ (capture/provisioning) call paths — each scope is cached independently with
+ its own expiry. Tokens are refreshed a minute before expiry so an in-flight
+ request never carries a just-expired token.
+ """
+
+ def __init__(
+ self,
+ *,
+ tenant_id: str,
+ app_id: str,
+ app_password: str,
+ http: httpx.AsyncClient,
+ ) -> None:
+ self._token_url = (
+ f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
+ )
+ self._app_id = app_id
+ self._app_password = app_password
+ self._http = http
+ # scope -> (access_token, expires_at_epoch)
+ self._cache: dict[str, tuple[str, float]] = {}
+
+ async def token(self, scope: str) -> str:
+ cached = self._cache.get(scope)
+ now = time.time()
+ if cached and cached[1] - 60 > now:
+ return cached[0]
+
+ resp = await self._http.post(
+ self._token_url,
+ data={
+ "grant_type": "client_credentials",
+ "client_id": self._app_id,
+ "client_secret": self._app_password,
+ "scope": scope,
+ },
+ )
+ if resp.status_code != 200:
+ raise RuntimeError(
+ f"AAD token request for scope {scope} failed "
+ f"({resp.status_code}): {resp.text}"
+ )
+ payload = resp.json()
+ access_token = str(payload["access_token"])
+ expires_in = float(payload.get("expires_in", 3600))
+ self._cache[scope] = (access_token, now + expires_in)
+ return access_token
+
+ async def bot_token(self) -> str:
+ return await self.token(BOT_CONNECTOR_SCOPE)
+
+ async def graph_token(self) -> str:
+ return await self.token(GRAPH_SCOPE)
+
+
+class InboundActivityValidator:
+ """Validates the JWT the Bot Connector attaches to inbound activities.
+
+ Bot Framework signs each inbound call with a token issued by
+ ``https://api.botframework.com``; the bot must verify the signature against
+ the published JWKS and confirm the audience is its own app id before
+ trusting the activity. This rejects forged POSTs to the messaging endpoint.
+ """
+
+ def __init__(self, *, app_id: str) -> None:
+ self._app_id = app_id
+ self._jwks: PyJWKClient | None = None
+ self._jwks_uri: str | None = None
+ self._http = httpx.Client(timeout=10)
+
+ def _ensure_jwks(self) -> PyJWKClient:
+ if self._jwks is not None:
+ return self._jwks
+ meta = self._http.get(_BOTFRAMEWORK_OPENID)
+ meta.raise_for_status()
+ self._jwks_uri = meta.json()["jwks_uri"]
+ self._jwks = PyJWKClient(self._jwks_uri)
+ return self._jwks
+
+ def validate(self, auth_header: str | None) -> None:
+ """Raise if the Authorization header is missing or the token is invalid."""
+ if not auth_header or not auth_header.lower().startswith("bearer "):
+ raise PermissionError("missing bearer token on inbound Teams activity")
+ token = auth_header.split(" ", 1)[1].strip()
+ signing_key = self._ensure_jwks().get_signing_key_from_jwt(token)
+ jwt.decode(
+ token,
+ signing_key.key,
+ algorithms=["RS256"],
+ audience=self._app_id,
+ issuer=_BOTFRAMEWORK_ISSUER,
+ options={"require": ["exp", "iss", "aud"]},
+ )
+
+ def close(self) -> None:
+ self._http.close()
diff --git a/core/switch_core/bridges/collaboration/teams/cards.py b/core/switch_core/bridges/collaboration/teams/cards.py
new file mode 100644
index 000000000..95e70a1e5
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/teams/cards.py
@@ -0,0 +1,76 @@
+from __future__ import annotations
+
+from typing import Any
+from urllib.parse import quote
+
+ADAPTIVE_CARD_CONTENT_TYPE = "application/vnd.microsoft.card.adaptive"
+
+
+def agent_icon_url(agent_name: str) -> str:
+ """A stable generated avatar for an agent, matching the Slack adapter's
+ scheme so the same agent looks the same across bridged platforms."""
+ name = quote(agent_name.replace("_", "+"))
+ return f"https://ui-avatars.com/api/?name={name}&background=random&size=128"
+
+
+def agent_message_card(agent_name: str, body: str) -> dict[str, Any]:
+ """An Adaptive Card that labels a message with the sending agent's identity.
+
+ Teams has a single bot identity and no per-message username override (unlike
+ Slack), so each Switch agent is presented as a card whose header carries the
+ agent's avatar + name, with the message body beneath. ``body`` should already
+ be run through ``translate_outbound`` (Adaptive Card TextBlocks render a
+ markdown subset: bold, italic, links, lists)."""
+ return {
+ "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
+ "type": "AdaptiveCard",
+ "version": "1.4",
+ # Plain-text representation for surfaces that can't render the card
+ # inline (mobile, notification toasts, copy-link/search previews); its
+ # absence is what makes Teams show the "cards.unsupported" placeholder.
+ "fallbackText": f"{agent_name}: {body}",
+ "body": [
+ {
+ "type": "ColumnSet",
+ "columns": [
+ {
+ "type": "Column",
+ "width": "auto",
+ "items": [
+ {
+ "type": "Image",
+ "url": agent_icon_url(agent_name),
+ "size": "Small",
+ "style": "Person",
+ "altText": agent_name,
+ }
+ ],
+ },
+ {
+ "type": "Column",
+ "width": "stretch",
+ "verticalContentAlignment": "Center",
+ "items": [
+ {
+ "type": "TextBlock",
+ "text": agent_name,
+ "weight": "Bolder",
+ "wrap": True,
+ "spacing": "None",
+ }
+ ],
+ },
+ ],
+ },
+ {
+ "type": "TextBlock",
+ "text": body,
+ "wrap": True,
+ },
+ ],
+ }
+
+
+def card_attachment(card: dict[str, Any]) -> dict[str, Any]:
+ """Wrap an Adaptive Card as a Bot Framework activity attachment."""
+ return {"contentType": ADAPTIVE_CARD_CONTENT_TYPE, "content": card}
diff --git a/core/switch_core/bridges/collaboration/teams/connector.py b/core/switch_core/bridges/collaboration/teams/connector.py
new file mode 100644
index 000000000..1ccfdac91
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/teams/connector.py
@@ -0,0 +1,107 @@
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+import httpx
+
+from switch_core.bridges.collaboration.teams.auth import TeamsTokenProvider
+
+logger = logging.getLogger(__name__)
+
+
+class BotConnectorError(RuntimeError):
+ """A Bot Connector REST call returned a non-success status."""
+
+
+class BotConnectorClient:
+ """Thin async client over the Bot Framework Connector REST API.
+
+ The connector is reached at the per-tenant ``serviceUrl`` carried on inbound
+ activities (regional, e.g. ``https://smba.trafficmanager.net/amer/``). Every
+ call is authorised with an app-only Bot Connector token from the shared
+ token provider.
+ """
+
+ def __init__(self, *, tokens: TeamsTokenProvider, http: httpx.AsyncClient) -> None:
+ self._tokens = tokens
+ self._http = http
+
+ async def _headers(self) -> dict[str, str]:
+ token = await self._tokens.bot_token()
+ return {"Authorization": f"Bearer {token}"}
+
+ @staticmethod
+ def _base(service_url: str) -> str:
+ return service_url if service_url.endswith("/") else service_url + "/"
+
+ async def create_channel_thread(
+ self, *, service_url: str, channel_id: str, activity: dict[str, Any]
+ ) -> tuple[str, str]:
+ """Start a new thread in a Teams channel with ``activity``.
+
+ Returns ``(conversation_id, activity_id)`` — the new thread's
+ conversation id and the posted message's id (its thread root).
+ """
+ url = f"{self._base(service_url)}v3/conversations"
+ body = {
+ "isGroup": True,
+ "channelData": {"channel": {"id": channel_id}},
+ "activity": activity,
+ }
+ resp = await self._http.post(url, json=body, headers=await self._headers())
+ if resp.status_code >= 300:
+ raise BotConnectorError(
+ f"create conversation in {channel_id} failed "
+ f"({resp.status_code}): {resp.text}"
+ )
+ data = resp.json()
+ conversation_id = str(data.get("id") or channel_id)
+ activity_id = str(data.get("activityId") or data.get("id") or "")
+ return conversation_id, activity_id
+
+ async def send_to_conversation(
+ self, *, service_url: str, conversation_id: str, activity: dict[str, Any]
+ ) -> str:
+ """Post ``activity`` to an existing conversation; return its message id."""
+ url = f"{self._base(service_url)}v3/conversations/{conversation_id}/activities"
+ resp = await self._http.post(url, json=activity, headers=await self._headers())
+ if resp.status_code >= 300:
+ raise BotConnectorError(
+ f"send to conversation {conversation_id} failed "
+ f"({resp.status_code}): {resp.text}"
+ )
+ return str(resp.json().get("id", ""))
+
+ async def update_activity(
+ self,
+ *,
+ service_url: str,
+ conversation_id: str,
+ activity_id: str,
+ activity: dict[str, Any],
+ ) -> None:
+ url = (
+ f"{self._base(service_url)}v3/conversations/"
+ f"{conversation_id}/activities/{activity_id}"
+ )
+ resp = await self._http.put(url, json=activity, headers=await self._headers())
+ if resp.status_code >= 300:
+ raise BotConnectorError(
+ f"update activity {activity_id} failed "
+ f"({resp.status_code}): {resp.text}"
+ )
+
+ async def delete_activity(
+ self, *, service_url: str, conversation_id: str, activity_id: str
+ ) -> None:
+ url = (
+ f"{self._base(service_url)}v3/conversations/"
+ f"{conversation_id}/activities/{activity_id}"
+ )
+ resp = await self._http.delete(url, headers=await self._headers())
+ if resp.status_code >= 300:
+ raise BotConnectorError(
+ f"delete activity {activity_id} failed "
+ f"({resp.status_code}): {resp.text}"
+ )
diff --git a/core/switch_core/bridges/collaboration/teams/crypto.py b/core/switch_core/bridges/collaboration/teams/crypto.py
new file mode 100644
index 000000000..30f765668
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/teams/crypto.py
@@ -0,0 +1,94 @@
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+from typing import Any
+
+from cryptography import x509
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import padding as asym_padding
+from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
+from cryptography.hazmat.primitives.hashes import SHA1
+from cryptography.hazmat.primitives.padding import PKCS7
+from cryptography.hazmat.primitives.serialization import load_pem_private_key
+
+
+class ResourceDataError(RuntimeError):
+ """A Graph change-notification resource payload failed to decrypt/verify."""
+
+
+def _load_private_key(pem: str) -> Any:
+ key = load_pem_private_key(pem.encode("utf-8"), password=None)
+ return key
+
+
+def decrypt_resource_data(
+ encrypted_content: dict[str, Any], private_key_pem: str
+) -> dict[str, Any]:
+ """Decrypt and verify the ``encryptedContent`` of a Graph change notification.
+
+ Microsoft Graph encrypts included resource data with a one-time symmetric
+ key, itself RSA-OAEP-encrypted to the subscription's public certificate. The
+ steps (per the Graph "change notifications with resource data" spec):
+
+ 1. RSA-OAEP-decrypt ``dataKey`` with our private key to recover the
+ symmetric key.
+ 2. HMAC-SHA256 the encrypted ``data`` with that key and constant-time
+ compare against ``dataSignature`` — a mismatch means tampering.
+ 3. AES-256-CBC-decrypt ``data`` (IV = first 16 bytes of the symmetric key)
+ and strip PKCS7 padding.
+
+ Returns the decoded resource (a ``chatMessage`` JSON object).
+ """
+ try:
+ data = base64.b64decode(encrypted_content["data"])
+ data_signature = encrypted_content["dataSignature"]
+ data_key = base64.b64decode(encrypted_content["dataKey"])
+ except (KeyError, ValueError, TypeError) as e:
+ raise ResourceDataError(f"malformed encryptedContent: {e}") from e
+
+ private_key = _load_private_key(private_key_pem)
+ symmetric_key = private_key.decrypt(
+ data_key,
+ asym_padding.OAEP(
+ mgf=asym_padding.MGF1(algorithm=SHA1()),
+ algorithm=SHA1(),
+ label=None,
+ ),
+ )
+
+ expected_sig = base64.b64encode(
+ hmac.new(symmetric_key, data, hashlib.sha256).digest()
+ ).decode("utf-8")
+ if not hmac.compare_digest(expected_sig, data_signature):
+ raise ResourceDataError("resource data signature mismatch")
+
+ # AES-CBC is Microsoft Graph's fixed resource-data encryption format, so it
+ # cannot be swapped for an AEAD mode. Integrity is provided by the
+ # encrypt-then-MAC HMAC-SHA256 verification above (constant-time), which is
+ # checked before any decryption happens — so CBC is safe here.
+ iv = symmetric_key[:16]
+ cipher = Cipher(algorithms.AES(symmetric_key), modes.CBC(iv)) # nosemgrep
+ decryptor = cipher.decryptor()
+ padded = decryptor.update(data) + decryptor.finalize()
+ unpadder = PKCS7(algorithms.AES.block_size).unpadder()
+ plaintext = unpadder.update(padded) + unpadder.finalize()
+
+ try:
+ result: dict[str, Any] = json.loads(plaintext)
+ except json.JSONDecodeError as e:
+ raise ResourceDataError(f"decrypted resource is not valid JSON: {e}") from e
+ return result
+
+
+def load_certificate_der_b64(cert_pem: str) -> str:
+ """Validate the PEM certificate and return its base64 DER body.
+
+ Graph expects ``encryptionCertificate`` to be the base64-encoded DER of the
+ X.509 certificate. We re-encode from the parsed cert rather than trusting
+ hand-stripped PEM, so a malformed certificate fails loudly here."""
+ cert = x509.load_pem_x509_certificate(cert_pem.encode("utf-8"))
+ der = cert.public_bytes(serialization.Encoding.DER)
+ return base64.b64encode(der).decode("utf-8")
diff --git a/core/switch_core/bridges/collaboration/teams/graph.py b/core/switch_core/bridges/collaboration/teams/graph.py
new file mode 100644
index 000000000..cf81c070a
--- /dev/null
+++ b/core/switch_core/bridges/collaboration/teams/graph.py
@@ -0,0 +1,185 @@
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+import httpx
+
+from switch_core.bridges.collaboration.teams.auth import TeamsTokenProvider
+
+logger = logging.getLogger(__name__)
+
+GRAPH_BASE = "https://graph.microsoft.com/v1.0"
+
+
+class GraphError(RuntimeError):
+ """A Microsoft Graph REST call returned a non-success status."""
+
+
+class GraphClient:
+ """Async client for the Microsoft Graph endpoints the Teams bridge needs:
+ change-notification subscriptions (this phase) and, later, channel/user
+ provisioning. Every call carries an app-only Graph token."""
+
+ def __init__(self, *, tokens: TeamsTokenProvider, http: httpx.AsyncClient) -> None:
+ self._tokens = tokens
+ self._http = http
+
+ async def _headers(self) -> dict[str, str]:
+ token = await self._tokens.graph_token()
+ return {"Authorization": f"Bearer {token}"}
+
+ async def create_subscription(
+ self,
+ *,
+ resource: str,
+ notification_url: str,
+ lifecycle_notification_url: str,
+ client_state: str,
+ expiration_iso: str,
+ encryption_certificate: str,
+ encryption_certificate_id: str,
+ ) -> dict[str, Any]:
+ """Create a change-notification subscription with resource data.
+
+ Channel-message subscriptions must include an encryption certificate
+ (Graph encrypts the message body) and, because their lifetime exceeds an
+ hour's worth of renewals, a lifecycle notification URL.
+ """
+ body = {
+ "changeType": "created,updated",
+ "notificationUrl": notification_url,
+ "lifecycleNotificationUrl": lifecycle_notification_url,
+ "resource": resource,
+ "includeResourceData": True,
+ "encryptionCertificate": encryption_certificate,
+ "encryptionCertificateId": encryption_certificate_id,
+ "clientState": client_state,
+ "expirationDateTime": expiration_iso,
+ }
+ resp = await self._http.post(
+ f"{GRAPH_BASE}/subscriptions", json=body, headers=await self._headers()
+ )
+ if resp.status_code >= 300:
+ raise GraphError(
+ f"create subscription for {resource} failed "
+ f"({resp.status_code}): {resp.text}"
+ )
+ result: dict[str, Any] = resp.json()
+ return result
+
+ async def renew_subscription(
+ self, *, subscription_id: str, expiration_iso: str
+ ) -> None:
+ resp = await self._http.patch(
+ f"{GRAPH_BASE}/subscriptions/{subscription_id}",
+ json={"expirationDateTime": expiration_iso},
+ headers=await self._headers(),
+ )
+ if resp.status_code >= 300:
+ raise GraphError(
+ f"renew subscription {subscription_id} failed "
+ f"({resp.status_code}): {resp.text}"
+ )
+
+ async def delete_subscription(self, *, subscription_id: str) -> None:
+ resp = await self._http.delete(
+ f"{GRAPH_BASE}/subscriptions/{subscription_id}",
+ headers=await self._headers(),
+ )
+ if resp.status_code >= 300 and resp.status_code != 404:
+ raise GraphError(
+ f"delete subscription {subscription_id} failed "
+ f"({resp.status_code}): {resp.text}"
+ )
+
+ async def list_subscriptions(self) -> list[dict[str, Any]]:
+ resp = await self._http.get(
+ f"{GRAPH_BASE}/subscriptions", headers=await self._headers()
+ )
+ if resp.status_code >= 300:
+ raise GraphError(
+ f"list subscriptions failed ({resp.status_code}): {resp.text}"
+ )
+ value: list[dict[str, Any]] = resp.json().get("value", [])
+ return value
+
+ # ── Provisioning ─────────────────────────────────────────────────────────
+
+ async def create_channel(
+ self,
+ *,
+ team_id: str,
+ display_name: str,
+ description: str,
+ membership_type: str,
+ ) -> dict[str, Any]:
+ """Create a channel in a team. ``membership_type`` is ``standard`` or
+ ``private``. Returns the created channel (with its ``id``)."""
+ body = {
+ "displayName": display_name,
+ "description": description,
+ "membershipType": membership_type,
+ }
+ resp = await self._http.post(
+ f"{GRAPH_BASE}/teams/{team_id}/channels",
+ json=body,
+ headers=await self._headers(),
+ )
+ if resp.status_code >= 300:
+ raise GraphError(
+ f"create channel '{display_name}' in team {team_id} failed "
+ f"({resp.status_code}): {resp.text}"
+ )
+ result: dict[str, Any] = resp.json()
+ return result
+
+ async def get_channel(self, *, team_id: str, channel_id: str) -> dict[str, Any]:
+ resp = await self._http.get(
+ f"{GRAPH_BASE}/teams/{team_id}/channels/{channel_id}",
+ headers=await self._headers(),
+ )
+ if resp.status_code >= 300:
+ raise GraphError(
+ f"get channel {channel_id} failed ({resp.status_code}): {resp.text}"
+ )
+ result: dict[str, Any] = resp.json()
+ return result
+
+ async def add_channel_member(
+ self, *, team_id: str, channel_id: str, user_aad_id: str
+ ) -> None:
+ """Add an AAD user to a private channel's membership."""
+ body = {
+ "@odata.type": "#microsoft.graph.aadUserConversationMember",
+ "roles": [],
+ "[email protected]": (f"{GRAPH_BASE}/users('{user_aad_id}')"),
+ }
+ resp = await self._http.post(
+ f"{GRAPH_BASE}/teams/{team_id}/channels/{channel_id}/members",
+ json=body,
+ headers=await self._headers(),
+ )
+ if resp.status_code >= 300 and resp.status_code != 409:
+ raise GraphError(
+ f"add member {user_aad_id} to channel {channel_id} failed "
+ f"({resp.status_code}): {resp.text}"
+ )
+
+ async def add_team_member(self, *, team_id: str, user_aad_id: str) -> None:
+ """Add an AAD user to a team (so they can see its standard channels)."""
+ body = {
+ "@odata.type": "#microsoft.graph.aadUserConversationMember",
+ "roles": [],
+ "[email protected]": (f"{GRAPH_BASE}/users('{user_aad_id}')"),
+ }
+ resp = await self._http.post(
+ f"{GRAPH_BASE}/teams/{team_id}/members",
+ json=body,
+ headers=await self._headers(),
+ )
+ if resp.status_code >= 300 and resp.status_code != 409:
+ raise GraphError(
+ f"add member {user_aad_id} to team {team_id} failed "
+ f"({resp.status_code}): {resp.text}"
+ )
diff --git a/core/switch_core/db/stores/collaboration_bridge_store.py b/core/switch_core/db/stores/collaboration_bridge_store.py
index 63bc2c238..4094b2c6a 100644
--- a/core/switch_core/db/stores/collaboration_bridge_store.py
+++ b/core/switch_core/db/stores/collaboration_bridge_store.py
@@ -46,6 +46,20 @@ class CollaborationBridgeStore:
await session.flush()
return bridge
+ async def set_service_url(
+ self, session: AsyncSession, bridge_id: str, service_url: str
+ ) -> None:
+ """Persist a learned outbound serviceUrl into ``connection_config`` so it
+ survives a restart. Reassigns the dict so SQLAlchemy tracks the change."""
+ bridge = await session.get(CollaborationBridge, bridge_id)
+ if bridge is None:
+ raise ValueError(f"Bridge not found: {bridge_id}")
+ bridge.connection_config = {
+ **(bridge.connection_config or {}),
+ "service_url": service_url,
+ }
+ await session.flush()
+
async def delete(self, session: AsyncSession, bridge_id: str) -> None:
bridge = await session.get(CollaborationBridge, bridge_id)
if bridge:
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index f72e4af4e..5dc7be891 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -7,6 +7,7 @@ import os
import signal
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
+from pathlib import Path
import uvicorn
from alembic import command as alembic_command
@@ -40,6 +41,10 @@ from switch_core.bridges.collaboration.slack.adapter import (
SlackAdapter,
SlackConnectionConfig,
)
+from switch_core.bridges.collaboration.teams.adapter import (
+ TeamsAdapter,
+ TeamsConnectionConfig,
+)
from switch_core.bridges.resource.service import ResourceService
from switch_core.bridges.resource.tracker import ResourceRequestTracker
from switch_core.clients.admin_client import AdminClient
@@ -322,6 +327,7 @@ async def run() -> None:
"mattermost", MattermostAdapter, MattermostConnectionConfig
)
collab_lifecycle.register_adapter("slack", SlackAdapter, SlackConnectionConfig)
+ collab_lifecycle.register_adapter("teams", TeamsAdapter, TeamsConnectionConfig)
collab_lifecycle.register_adapter(
"discord", DiscordAdapter, DiscordConnectionConfig
)
@@ -471,7 +477,8 @@ async def _shutdown(
def main() -> None:
- alembic_cfg = AlembicConfig("alembic.ini")
+ alembic_ini = Path(__file__).resolve().parent.parent / "alembic.ini"
+ alembic_cfg = AlembicConfig(str(alembic_ini))
alembic_command.upgrade(alembic_cfg, "head")
log_level = os.environ.get("LOG_LEVEL", "INFO").upper()
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_capture.py b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_capture.py
new file mode 100644
index 000000000..2443c6bd5
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_capture.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+from switch_core.bridges.collaboration.bridge_core import BridgeCore
+
+# On startup BridgeCore hands the adapter the bridge's channels so channel
+# capture can self-heal (Teams recreates Graph subscriptions; other adapters
+# no-op). Only rows with both an external channel id and a channel type are
+# forwarded.
+
+
+class _FakeSession:
+ async def __aenter__(self) -> _FakeSession:
+ return self
+
+ async def __aexit__(self, *exc: Any) -> bool:
+ return False
+
+
+def _room(external_channel_id: str | None, channel_type: str | None) -> SimpleNamespace:
+ return SimpleNamespace(
+ external_channel_id=external_channel_id, channel_type=channel_type
+ )
+
+
+async def test_ensure_channel_captures_forwards_valid_channels() -> None:
+ passed: list[list[tuple[str, str]]] = []
+
+ class _RoomStore:
+ async def get_by_bridge(self, session: Any, bridge_id: str) -> list[Any]:
+ assert bridge_id == "bridge-1"
+ return [
+ _room("19:[email protected]", "channel_public"),
+ _room("19:[email protected]", "channel_private"),
+ _room(None, "channel_public"), # no channel id -> skipped
+ _room("19:[email protected]", None), # no channel type -> skipped
+ ]
+
+ class _Adapter:
+ async def ensure_channel_subscriptions(
+ self, channels: list[tuple[str, str]]
+ ) -> None:
+ passed.append(channels)
+
+ bridge = SimpleNamespace(
+ _session_factory=_FakeSession,
+ _room_store=_RoomStore(),
+ _adapter=_Adapter(),
+ _bridge_id="bridge-1",
+ )
+
+ await BridgeCore._ensure_channel_captures(bridge)
+
+ assert passed == [
+ [
+ ("19:[email protected]", "channel_public"),
+ ("19:[email protected]", "channel_private"),
+ ]
+ ]
+
+
+async def test_ensure_channel_captures_noop_without_channels() -> None:
+ calls: list[Any] = []
+
+ class _RoomStore:
+ async def get_by_bridge(self, session: Any, bridge_id: str) -> list[Any]:
+ return [_room(None, None)]
+
+ class _Adapter:
+ async def ensure_channel_subscriptions(
+ self, channels: list[tuple[str, str]]
+ ) -> None:
+ calls.append(channels)
+
+ bridge = SimpleNamespace(
+ _session_factory=_FakeSession,
+ _room_store=_RoomStore(),
+ _adapter=_Adapter(),
+ _bridge_id="bridge-1",
+ )
+
+ await BridgeCore._ensure_channel_captures(bridge)
+
+ assert calls == []
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_self_mention_guidance.py b/core/tests/switch_core/bridges/collaboration/test_bridge_self_mention_guidance.py
index 4e9fd9a64..1acaf053e 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_self_mention_guidance.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_self_mention_guidance.py
@@ -130,3 +130,67 @@ async def test_self_mention_threads_under_existing_thread_root() -> None:
)
assert bridge.notices[0][2] == "C123:100.1"
+
+
+async def test_guidance_omits_set_alias_for_non_alias_safe_token() -> None:
+ # A Teams bot id ("28:<guid>") can't be an alias (aliases forbid ':'), so the
+ # !set-alias shortcut is omitted — but the agent list (tag by name) stays.
+ bridge = _fake_bridge(
+ alias_agent=None,
+ agents={"a1": _agent("agent-a"), "a2": _agent("agent-b")},
+ )
+
+ await BridgeCore._maybe_guide_self_mention(
+ bridge, _msg(self_mention_token="28:app-123"), "room-uuid"
+ )
+
+ assert len(bridge.notices) == 1
+ _, content, _ = bridge.notices[0]
+ assert "!set-alias" not in content
+ assert "• @agent-a — agent-a does things" in content
+
+
+async def test_resolve_target_single_agent_unaliased() -> None:
+ bridge = _fake_bridge(alias_agent=None, agents={"a1": _agent("agent-a")})
+
+ target = await BridgeCore._resolve_self_mention_target(
+ bridge, _msg(self_mention_token="28:app-123"), "room-uuid"
+ )
+
+ assert target == "agent-a"
+
+
+async def test_resolve_target_uses_alias_even_with_many_agents() -> None:
+ bridge = _fake_bridge(
+ alias_agent="a2",
+ agents={"a1": _agent("agent-a"), "a2": _agent("agent-b")},
+ )
+
+ target = await BridgeCore._resolve_self_mention_target(
+ bridge, _msg(self_mention_token="UBOT"), "room-uuid"
+ )
+
+ assert target == "agent-b"
+
+
+async def test_resolve_target_ambiguous_returns_none() -> None:
+ bridge = _fake_bridge(
+ alias_agent=None,
+ agents={"a1": _agent("agent-a"), "a2": _agent("agent-b")},
+ )
+
+ target = await BridgeCore._resolve_self_mention_target(
+ bridge, _msg(self_mention_token="28:app-123"), "room-uuid"
+ )
+
+ assert target is None
+
+
+async def test_resolve_target_no_token_returns_none() -> None:
+ bridge = _fake_bridge(alias_agent=None, agents={"a1": _agent("agent-a")})
+
+ target = await BridgeCore._resolve_self_mention_target(
+ bridge, _msg(self_mention_token=None), "room-uuid"
+ )
+
+ assert target is None
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py
index 5ef752ada..38745266e 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py
@@ -17,6 +17,10 @@ from switch_core.bridges.collaboration.slack.adapter import (
SlackAdapter,
SlackConnectionConfig,
)
+from switch_core.bridges.collaboration.teams.adapter import (
+ TeamsAdapter,
+ TeamsConnectionConfig,
+)
def _service() -> CollaborationBridgeLifecycleService:
@@ -75,3 +79,40 @@ def test_get_config_schema_unknown_type_raises() -> None:
service = _service()
with pytest.raises(ValueError, match="Unknown bridge type"):
service.get_config_schema("does-not-exist")
+
+
+def test_teams_adapter_registers_with_expected_required_fields() -> None:
+ service = _service()
+ service.register_adapter("teams", TeamsAdapter, TeamsConnectionConfig)
+
+ assert "teams" in service.get_registered_types()
+
+ schema = service.get_config_schema("teams")
+ # The credentials + endpoint fields with no default are required; the
+ # subscription/encryption fields are optional. client_state is required —
+ # it is the only control that authenticates a notification's origin.
+ assert set(schema["required"]) == {
+ "app_id",
+ "app_password",
+ "tenant_id",
+ "team_id",
+ "public_base_url",
+ "client_state",
+ }
+ # Switch-internal fields (the listener bind, the runtime-learned serviceUrl)
+ # are hidden from the admin config form — the admin only supplies genuine
+ # Teams/Azure credentials + endpoint.
+ assert set(schema["properties"]) == {
+ "app_id",
+ "app_password",
+ "tenant_id",
+ "team_id",
+ "public_base_url",
+ "client_state",
+ "encryption_certificate_id",
+ "encryption_public_certificate",
+ "encryption_private_key",
+ }
+ assert "listen_host" not in schema["properties"]
+ assert "listen_port" not in schema["properties"]
+ assert "service_url" not in schema["properties"]
diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
new file mode 100644
index 000000000..8b516479b
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
@@ -0,0 +1,1014 @@
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+from switch_core.bridges.collaboration.models import InboundCommand, InboundMessage
+from switch_core.bridges.collaboration.teams.adapter import (
+ TeamsAdapter,
+ TeamsConnectionConfig,
+)
+from switch_core.bridges.collaboration.teams.cards import (
+ ADAPTIVE_CARD_CONTENT_TYPE,
+ agent_message_card,
+)
+
+
+def _config() -> TeamsConnectionConfig:
+ return TeamsConnectionConfig(
+ app_id="app-123",
+ app_password="secret",
+ tenant_id="tenant-1",
+ team_id="team-1",
+ public_base_url="https://switch.example",
+ client_state="s3cr3t",
+ )
+
+
+def _adapter() -> TeamsAdapter:
+ return TeamsAdapter(config=_config())
+
+
+def _run(coro: Any) -> Any:
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+class _FakeConnector:
+ """Records connector calls and returns canned ids."""
+
+ def __init__(self, *, raise_on_send: bool = False) -> None:
+ self.threads: list[dict[str, Any]] = []
+ self.sends: list[dict[str, Any]] = []
+ self.updates: list[dict[str, Any]] = []
+ self.deletes: list[dict[str, Any]] = []
+ self._raise_on_send = raise_on_send
+
+ async def create_channel_thread(
+ self, *, service_url: str, channel_id: str, activity: dict[str, Any]
+ ) -> tuple[str, str]:
+ self.threads.append(
+ {"service_url": service_url, "channel_id": channel_id, "activity": activity}
+ )
+ return f"{channel_id};messageid=ROOT1", "ROOT1"
+
+ async def send_to_conversation(
+ self, *, service_url: str, conversation_id: str, activity: dict[str, Any]
+ ) -> str:
+ if self._raise_on_send:
+ raise RuntimeError("boom")
+ self.sends.append(
+ {
+ "service_url": service_url,
+ "conversation_id": conversation_id,
+ "activity": activity,
+ }
+ )
+ return "MSG1"
+
+ async def update_activity(
+ self,
+ *,
+ service_url: str,
+ conversation_id: str,
+ activity_id: str,
+ activity: dict[str, Any],
+ ) -> None:
+ self.updates.append(
+ {"conversation_id": conversation_id, "activity_id": activity_id}
+ )
+
+ async def delete_activity(
+ self, *, service_url: str, conversation_id: str, activity_id: str
+ ) -> None:
+ self.deletes.append(
+ {"conversation_id": conversation_id, "activity_id": activity_id}
+ )
+
+
+def _capture_messages(adapter: TeamsAdapter) -> list[InboundMessage]:
+ captured: list[InboundMessage] = []
+
+ async def on_message(msg: InboundMessage) -> None:
+ captured.append(msg)
+
+ adapter._on_message = on_message
+ return captured
+
+
+def _capture_commands(adapter: TeamsAdapter) -> list[InboundCommand]:
+ captured: list[InboundCommand] = []
+
+ async def on_command(cmd: InboundCommand) -> None:
+ captured.append(cmd)
+
+ adapter._on_command = on_command
+ return captured
+
+
+# ── Channel resolution from activity ─────────────────────────────────────────
+
+
+def test_channel_from_channel_activity_uses_channel_data_id() -> None:
+ activity = {
+ "conversation": {
+ "id": "19:[email protected];messageid=100",
+ "conversationType": "channel",
+ },
+ "channelData": {"channel": {"id": "19:[email protected]"}},
+ }
+ channel_id, channel_type = TeamsAdapter._channel_from_activity(activity)
+ assert channel_id == "19:[email protected]"
+ assert channel_type == "channel_public"
+
+
+def test_channel_from_personal_activity_is_direct() -> None:
+ activity = {"conversation": {"id": "a:1xyz", "conversationType": "personal"}}
+ channel_id, channel_type = TeamsAdapter._channel_from_activity(activity)
+ assert channel_id == "a:1xyz"
+ assert channel_type == "direct"
+
+
+def test_channel_from_group_chat_activity_is_group() -> None:
+ activity = {
+ "conversation": {"id": "19:[email protected]", "conversationType": "groupChat"}
+ }
+ channel_id, channel_type = TeamsAdapter._channel_from_activity(activity)
+ assert channel_id == "19:[email protected]"
+ assert channel_type == "group"
+
+
+# ── Text cleaning + self-mention ─────────────────────────────────────────────
+
+
+def test_clean_text_renders_mention_markup() -> None:
+ # The mention display text is kept as an `@name` token (not deleted) so the
+ # addressing layer can still see it downstream.
+ assert (
+ TeamsAdapter._clean_text("<at>Switch Bot</at> hello there")
+ == "@Switch Bot hello there"
+ )
+
+
+def test_self_mention_token_set_when_bot_mentioned() -> None:
+ adapter = _adapter()
+ activity = {
+ "recipient": {"id": "28:app-123"},
+ "entities": [
+ {"type": "mention", "mentioned": {"id": "28:app-123"}},
+ ],
+ }
+ assert adapter._self_mention_token(activity) == "28:app-123"
+
+
+def test_self_mention_token_none_when_not_mentioned() -> None:
+ adapter = _adapter()
+ activity = {
+ "recipient": {"id": "28:app-123"},
+ "entities": [{"type": "mention", "mentioned": {"id": "29:someone"}}],
+ }
+ assert adapter._self_mention_token(activity) is None
+
+
+def test_inbound_bot_mention_carries_self_mention_token() -> None:
+ adapter = _adapter()
+ captured = _capture_messages(adapter)
+
+ activity = {
+ "type": "message",
+ "id": "300",
+ "serviceUrl": "https://smba.example/amer/",
+ "text": "<at>Switch Bot</at> please help",
+ "from": {"aadObjectId": "aad-1", "name": "Alice"},
+ "recipient": {"id": "28:app-123"},
+ "entities": [{"type": "mention", "mentioned": {"id": "28:app-123"}}],
+ "conversation": {
+ "id": "19:[email protected];messageid=300",
+ "conversationType": "channel",
+ },
+ "channelData": {"channel": {"id": "19:[email protected]"}},
+ }
+ _run(adapter._dispatch_activity(activity))
+
+ assert len(captured) == 1
+ assert captured[0].content == "@Switch Bot please help"
+ assert captured[0].self_mention_token == "28:app-123"
+
+
+# ── Inbound dispatch ─────────────────────────────────────────────────────────
+
+
+def test_inbound_attachment_is_disclosed_not_dropped() -> None:
+ # Inbound file/image relay is not implemented yet; the message text must
+ # still bridge and the dropped attachment must be disclosed (fail-loud), and
+ # the text/html body attachment must NOT be counted as a dropped file.
+ adapter = _adapter()
+ captured = _capture_messages(adapter)
+
+ activity = {
+ "type": "message",
+ "id": "att-1",
+ "serviceUrl": "https://smba.example/amer/",
+ "text": "look at this",
+ "from": {"aadObjectId": "aad-1", "name": "Alice"},
+ "conversation": {
+ "id": "19:[email protected];messageid=att-1",
+ "conversationType": "channel",
+ },
+ "channelData": {"channel": {"id": "19:[email protected]"}},
+ "attachments": [
+ {"contentType": "text/html", "content": "<p>look at this</p>"},
+ {"contentType": "image/png", "name": "diagram.png"},
+ ],
+ }
+ _run(adapter._dispatch_activity(activity))
+
+ assert len(captured) == 1
+ content = captured[0].content
+ assert content.startswith("look at this")
+ assert "diagram.png" in content
+ assert "not relayed" in content
+
+
+class _FakeHttpRequest:
+ def __init__(
+ self,
+ *,
+ headers: dict[str, str] | None = None,
+ body: Any = None,
+ json_error: bool = False,
+ ) -> None:
+ self.headers = headers or {}
+ self._body = body
+ self._json_error = json_error
+ self.query: dict[str, str] = {}
+
+ async def json(self) -> Any:
+ if self._json_error:
+ raise ValueError("bad json")
+ return self._body
+
+
+class _RaisingValidator:
+ def validate(self, auth_header: str | None) -> None:
+ raise PermissionError("forged")
+
+
+class _PassValidator:
+ def validate(self, auth_header: str | None) -> None:
+ return None
+
+
+def test_http_messages_rejects_unauthenticated_activity() -> None:
+ adapter = _adapter()
+ adapter._validator = _RaisingValidator() # type: ignore[assignment]
+
+ resp = _run(
+ adapter._handle_http_messages(
+ _FakeHttpRequest( # type: ignore[arg-type]
+ headers={"Authorization": "Bearer forged"},
+ body={"type": "message"},
+ )
+ )
+ )
+
+ assert resp.status == 401
+
+
+def test_http_messages_rejects_invalid_json() -> None:
+ adapter = _adapter()
+ adapter._validator = _PassValidator() # type: ignore[assignment]
+
+ resp = _run(
+ adapter._handle_http_messages(
+ _FakeHttpRequest( # type: ignore[arg-type]
+ headers={"Authorization": "Bearer ok"}, json_error=True
+ )
+ )
+ )
+
+ assert resp.status == 400
+
+
+def test_http_messages_dispatches_authenticated_activity() -> None:
+ adapter = _adapter()
+ adapter._validator = _PassValidator() # type: ignore[assignment]
+ captured = _capture_messages(adapter)
+
+ activity = {
+ "type": "message",
+ "id": "ok-1",
+ "serviceUrl": "https://smba.example/amer/",
+ "text": "hi",
+ "from": {"aadObjectId": "aad-1", "name": "Alice"},
+ "conversation": {
+ "id": "19:[email protected];messageid=ok-1",
+ "conversationType": "channel",
+ },
+ "channelData": {"channel": {"id": "19:[email protected]"}},
+ }
+ resp = _run(
+ adapter._handle_http_messages(
+ _FakeHttpRequest( # type: ignore[arg-type]
+ headers={"Authorization": "Bearer ok"}, body=activity
+ )
+ )
+ )
+
+ assert resp.status == 200
+ assert len(captured) == 1
+ assert captured[0].content == "hi"
+
+
+def test_inbound_channel_message_top_level_has_no_root() -> None:
+ adapter = _adapter()
+ captured = _capture_messages(adapter)
+
+ activity = {
+ "type": "message",
+ "id": "100",
+ "serviceUrl": "https://smba.example/amer/",
+ "text": "<at>Switch</at> hello",
+ "from": {"aadObjectId": "aad-1", "name": "Alice"},
+ "conversation": {
+ "id": "19:[email protected];messageid=100",
+ "conversationType": "channel",
+ },
+ "channelData": {"channel": {"id": "19:[email protected]"}},
+ }
+ _run(adapter._dispatch_activity(activity))
+
+ assert len(captured) == 1
+ msg = captured[0]
+ assert msg.channel_id == "19:[email protected]"
+ assert msg.channel_type == "channel_public"
+ assert msg.sender_id == "aad-1"
+ assert msg.sender_name == "Alice"
+ assert msg.content == "@Switch hello"
+ assert msg.message_ref == "100"
+ assert msg.root_id is None
+ # serviceUrl + type are learned for later outbound use.
+ assert adapter._service_url["19:[email protected]"] == "https://smba.example/amer/"
+
+
+def test_inbound_channel_reply_sets_root_id() -> None:
+ adapter = _adapter()
+ captured = _capture_messages(adapter)
+
+ activity = {
+ "type": "message",
+ "id": "200",
+ "serviceUrl": "https://smba.example/amer/",
+ "text": "a reply",
+ "from": {"aadObjectId": "aad-2", "name": "Bob"},
+ "conversation": {
+ "id": "19:[email protected];messageid=100",
+ "conversationType": "channel",
+ },
+ "channelData": {"channel": {"id": "19:[email protected]"}},
+ }
+ _run(adapter._dispatch_activity(activity))
+
+ assert captured[0].root_id == "100"
+ assert captured[0].message_ref == "200"
+
+
+def test_inbound_channel_learns_team_group_guid() -> None:
+ # Graph channel subscriptions require the team's AAD group GUID; the adapter
+ # must learn it from channelData.team.aadGroupId, not the non-GUID thread id.
+ adapter = _adapter()
+ _capture_messages(adapter)
+ activity = {
+ "type": "message",
+ "id": "500",
+ "serviceUrl": "https://smba.example/amer/",
+ "text": "<at>Switch</at> hi",
+ "from": {"aadObjectId": "aad-1", "name": "Alice"},
+ "conversation": {
+ "id": "19:[email protected];messageid=500",
+ "conversationType": "channel",
+ },
+ "channelData": {
+ "channel": {"id": "19:[email protected]"},
+ "team": {
+ "id": "19:[email protected]",
+ "aadGroupId": "40013d55-9d89-4e09-b993-4c56dbe8269f",
+ },
+ },
+ }
+ _run(adapter._dispatch_activity(activity))
+ assert (
+ adapter._team_of_channel["19:[email protected]"]
+ == "40013d55-9d89-4e09-b993-4c56dbe8269f"
+ )
+
+
+def test_inbound_channel_without_aad_group_falls_back_to_config_team_id() -> None:
+ # No aadGroupId in the payload -> use the configured team_id (also a GUID),
+ # never the non-GUID team thread id.
+ adapter = _adapter() # config team_id == "team-1"
+ _capture_messages(adapter)
+ activity = {
+ "type": "message",
+ "id": "501",
+ "serviceUrl": "https://smba.example/amer/",
+ "text": "hi",
+ "from": {"aadObjectId": "aad-1", "name": "Alice"},
+ "conversation": {
+ "id": "19:[email protected]",
+ "conversationType": "channel",
+ },
+ "channelData": {
+ "channel": {"id": "19:[email protected]"},
+ "team": {"id": "19:[email protected]"},
+ },
+ }
+ _run(adapter._dispatch_activity(activity))
+ assert adapter._team_of_channel["19:[email protected]"] == "team-1"
+
+
+def test_inbound_command_routes_to_on_command() -> None:
+ adapter = _adapter()
+ commands = _capture_commands(adapter)
+
+ activity = {
+ "type": "message",
+ "id": "300",
+ "serviceUrl": "https://smba.example/amer/",
+ "text": "!reset worker",
+ "from": {"aadObjectId": "aad-3", "name": "Carol"},
+ "conversation": {"id": "a:1chat", "conversationType": "personal"},
+ }
+ _run(adapter._dispatch_activity(activity))
+
+ assert len(commands) == 1
+ assert commands[0].command == "reset"
+ assert commands[0].args == "worker"
+ assert commands[0].channel_type == "direct"
+
+
+def test_inbound_channel_command_after_bot_mention_routes_to_on_command() -> None:
+ # In a Teams channel the Bot Framework only delivers messages that @mention
+ # the bot, so a channel command always arrives as "@Bot !cmd". The leading
+ # bot mention must not hide the "!" command marker.
+ adapter = _adapter()
+ commands = _capture_commands(adapter)
+ messages = _capture_messages(adapter)
+
+ activity = {
+ "type": "message",
+ "id": "301",
+ "serviceUrl": "https://smba.example/amer/",
+ "text": "<at>Switch Bot</at> !reset worker",
+ "from": {"aadObjectId": "aad-1", "name": "Alice"},
+ "recipient": {"id": "28:app-123"},
+ "entities": [{"type": "mention", "mentioned": {"id": "28:app-123"}}],
+ "conversation": {
+ "id": "19:[email protected];messageid=301",
+ "conversationType": "channel",
+ },
+ "channelData": {"channel": {"id": "19:[email protected]"}},
+ }
+ _run(adapter._dispatch_activity(activity))
+
+ assert len(commands) == 1
+ assert commands[0].command == "reset"
+ assert commands[0].args == "worker"
+ assert commands[0].channel_type == "channel_public"
+ # The command must not also be bridged as a normal message.
+ assert messages == []
+
+
+def test_graph_channel_command_after_bot_mention_routes_to_on_command() -> None:
+ # Same rule on the Graph capture path: strip the bot's leading <at> mention
+ # (here wrapped in a <p>) before detecting the "!" command.
+ adapter = _adapter()
+ commands = _capture_commands(adapter)
+
+ chat_message = {
+ "id": "700",
+ "messageType": "message",
+ "from": {"user": {"id": "user-1", "displayName": "Dave"}},
+ "channelIdentity": {"channelId": "19:[email protected]"},
+ "body": {
+ "contentType": "html",
+ "content": '<p><at id="0">Switch Bot</at> !help now</p>',
+ },
+ "mentions": [{"id": 0, "mentioned": {"application": {"id": "app-123"}}}],
+ }
+ _run(adapter._deliver_graph_message(chat_message))
+
+ assert len(commands) == 1
+ assert commands[0].command == "help"
+ assert commands[0].args == "now"
+
+
+def test_inbound_duplicate_activity_is_ignored() -> None:
+ adapter = _adapter()
+ captured = _capture_messages(adapter)
+
+ activity = {
+ "type": "message",
+ "id": "400",
+ "serviceUrl": "https://smba.example/amer/",
+ "text": "hi",
+ "from": {"aadObjectId": "aad-4", "name": "Dan"},
+ "conversation": {"id": "a:1chat", "conversationType": "personal"},
+ }
+ _run(adapter._dispatch_activity(activity))
+ _run(adapter._dispatch_activity(activity))
+
+ assert len(captured) == 1
+
+
+def test_conversation_update_bot_added_fires_app_joined() -> None:
+ from switch_core.bridges.collaboration.models import InboundAppJoin
+
+ adapter = _adapter()
+ joins: list[InboundAppJoin] = []
+
+ async def on_app_joined(join: InboundAppJoin) -> None:
+ joins.append(join)
+
+ adapter._on_app_joined = on_app_joined
+
+ activity = {
+ "type": "conversationUpdate",
+ "serviceUrl": "https://smba.example/amer/",
+ "recipient": {"id": "28:app-123"},
+ "membersAdded": [{"id": "28:app-123"}],
+ "conversation": {
+ "id": "19:[email protected]",
+ "conversationType": "channel",
+ },
+ "channelData": {
+ "channel": {"id": "19:[email protected]"},
+ "team": {"name": "Engineering"},
+ },
+ }
+ _run(adapter._dispatch_activity(activity))
+
+ assert len(joins) == 1
+ assert joins[0].channel_id == "19:[email protected]"
+ assert joins[0].channel_name == "Engineering"
+
+
+def test_conversation_update_user_added_fires_user_joined() -> None:
+ from switch_core.bridges.collaboration.models import InboundUserJoin
+
+ adapter = _adapter()
+ joins: list[InboundUserJoin] = []
+
+ async def on_user_joined(join: InboundUserJoin) -> None:
+ joins.append(join)
+
+ adapter._on_user_joined = on_user_joined
+
+ activity = {
+ "type": "conversationUpdate",
+ "serviceUrl": "https://smba.example/amer/",
+ "recipient": {"id": "28:app-123"},
+ "membersAdded": [{"id": "29:user", "aadObjectId": "aad-9", "name": "Erin"}],
+ "conversation": {
+ "id": "19:[email protected]",
+ "conversationType": "channel",
+ },
+ "channelData": {"channel": {"id": "19:[email protected]"}},
+ }
+ _run(adapter._dispatch_activity(activity))
+
+ assert len(joins) == 1
+ assert joins[0].external_user_id == "aad-9"
+ assert joins[0].external_username == "Erin"
+
+
+# ── Outbound send ────────────────────────────────────────────────────────────
+
+
+def _wire_outbound(adapter: TeamsAdapter, connector: _FakeConnector) -> None:
+ adapter._connector = connector # type: ignore[assignment]
+ adapter._default_service_url = "https://smba.example/amer/"
+
+
+def test_send_channel_top_level_creates_thread_with_card() -> None:
+ adapter = _adapter()
+ fake = _FakeConnector()
+ _wire_outbound(adapter, fake)
+ adapter._channel_type["19:[email protected]"] = "channel_public"
+
+ ref = _run(adapter.send_message("19:[email protected]", "worker", "hi there"))
+
+ assert ref == "ROOT1"
+ assert len(fake.threads) == 1
+ activity = fake.threads[0]["activity"]
+ assert activity["attachments"][0]["contentType"] == ADAPTIVE_CARD_CONTENT_TYPE
+ # The sent message is tracked for later edit/delete.
+ assert adapter._sent["ROOT1"][1] == "19:[email protected];messageid=ROOT1"
+
+
+def test_send_channel_reply_targets_thread_conversation() -> None:
+ adapter = _adapter()
+ fake = _FakeConnector()
+ _wire_outbound(adapter, fake)
+ adapter._channel_type["19:[email protected]"] = "channel_public"
+
+ ref = _run(
+ adapter.send_message(
+ "19:[email protected]", "worker", "a reply", thread_root_id="100"
+ )
+ )
+
+ assert ref == "MSG1"
+ assert len(fake.sends) == 1
+ assert fake.sends[0]["conversation_id"] == "19:[email protected];messageid=100"
+
+
+def test_send_to_chat_is_flat() -> None:
+ adapter = _adapter()
+ fake = _FakeConnector()
+ _wire_outbound(adapter, fake)
+ adapter._channel_type["a:1chat"] = "direct"
+
+ _run(adapter.send_message("a:1chat", "worker", "hello"))
+
+ assert fake.threads == []
+ assert len(fake.sends) == 1
+ assert fake.sends[0]["conversation_id"] == "a:1chat"
+
+
+def test_admin_message_is_plain_text_no_card() -> None:
+ adapter = _adapter()
+ fake = _FakeConnector()
+ _wire_outbound(adapter, fake)
+ adapter._channel_type["a:1chat"] = "direct"
+
+ _run(adapter.admin_message("a:1chat", "system notice"))
+
+ assert len(fake.sends) == 1
+ activity = fake.sends[0]["activity"]
+ assert activity["text"] == "system notice"
+ assert "attachments" not in activity
+
+
+def test_send_to_chat_with_thread_root_stays_flat() -> None:
+ # Flat chats (1:1/group) have no channel-style threading: appending
+ # ";messageid=" yields a conversation id Teams cannot decrypt (403), so a
+ # thread root must be ignored for a flat chat.
+ adapter = _adapter()
+ fake = _FakeConnector()
+ _wire_outbound(adapter, fake)
+ adapter._channel_type["a:1chat"] = "direct"
+
+ _run(adapter.send_message("a:1chat", "worker", "hi", thread_root_id="500"))
+
+ assert len(fake.sends) == 1
+ assert fake.sends[0]["conversation_id"] == "a:1chat"
+
+
+def test_admin_message_to_chat_with_thread_root_stays_flat() -> None:
+ # Same invariant for admin/system messages: a no-agents notice threaded under
+ # the triggering message in a 1:1 chat must not become "a:1chat;messageid=…".
+ adapter = _adapter()
+ fake = _FakeConnector()
+ _wire_outbound(adapter, fake)
+ adapter._channel_type["a:1chat"] = "direct"
+
+ _run(adapter.admin_message("a:1chat", "system notice", thread_root_id="500"))
+
+ assert len(fake.sends) == 1
+ assert fake.sends[0]["conversation_id"] == "a:1chat"
+
+
+def test_send_without_known_service_url_raises() -> None:
+ adapter = _adapter()
+ fake = _FakeConnector()
+ adapter._connector = fake # type: ignore[assignment]
+ # No default service url learned yet.
+ try:
+ _run(adapter.send_message("19:[email protected]", "worker", "hi"))
+ raised = False
+ except RuntimeError:
+ raised = True
+ assert raised
+
+
+def test_configured_service_url_seeds_outbound_after_restart() -> None:
+ # A serviceUrl persisted in config must let outbound work immediately, before
+ # any inbound activity is received (the post-restart case).
+ config = _config()
+ config.service_url = "https://smba.example/amer/"
+ adapter = TeamsAdapter(config=config)
+ fake = _FakeConnector()
+ adapter._connector = fake # type: ignore[assignment]
+
+ _run(adapter.send_message("19:[email protected]", "worker", "hi"))
+
+ assert fake.threads[0]["service_url"] == "https://smba.example/amer/"
+
+
+def test_learned_service_url_is_persisted_once_per_change() -> None:
+ # A newly-learned serviceUrl is persisted so it survives a restart; an
+ # unchanged one is not re-persisted on every subsequent activity.
+ adapter = _adapter()
+ _capture_messages(adapter)
+ persisted: list[str] = []
+
+ async def _persist(url: str) -> None:
+ persisted.append(url)
+
+ adapter.set_service_url_persister(_persist)
+
+ def _activity(msg_id: str, service_url: str) -> dict[str, Any]:
+ return {
+ "type": "message",
+ "id": msg_id,
+ "serviceUrl": service_url,
+ "text": "hi",
+ "from": {"aadObjectId": "aad-1", "name": "Alice"},
+ "conversation": {
+ "id": "19:[email protected];messageid=" + msg_id,
+ "conversationType": "channel",
+ },
+ "channelData": {"channel": {"id": "19:[email protected]"}},
+ }
+
+ _run(adapter._dispatch_activity(_activity("1", "https://smba.example/amer/")))
+ _run(adapter._dispatch_activity(_activity("2", "https://smba.example/amer/")))
+ _run(adapter._dispatch_activity(_activity("3", "https://smba.example/emea/")))
+
+ assert persisted == ["https://smba.example/amer/", "https://smba.example/emea/"]
+ assert adapter._default_service_url == "https://smba.example/emea/"
+
+
+# ── Edit / delete ────────────────────────────────────────────────────────────
+
+
+def test_delete_uses_tracked_conversation() -> None:
+ adapter = _adapter()
+ fake = _FakeConnector()
+ _wire_outbound(adapter, fake)
+ adapter._sent["MSG1"] = ("https://smba.example/amer/", "conv-xyz")
+
+ _run(adapter.delete_message("19:[email protected]", "MSG1"))
+
+ assert fake.deletes == [{"conversation_id": "conv-xyz", "activity_id": "MSG1"}]
+ assert "MSG1" not in adapter._sent
+
+
+def test_update_reconstructs_conversation_when_untracked() -> None:
+ adapter = _adapter()
+ fake = _FakeConnector()
+ _wire_outbound(adapter, fake)
+
+ _run(adapter.update_message("19:[email protected]", "OLD", "new text"))
+
+ assert fake.updates == [
+ {
+ "conversation_id": "19:[email protected];messageid=OLD",
+ "activity_id": "OLD",
+ }
+ ]
+
+
+# ── Typing (best-effort) ─────────────────────────────────────────────────────
+
+
+class _RecordThenRaiseConnector(_FakeConnector):
+ """Records the attempted activity, then raises — so a test can assert the
+ call was really attempted before its failure was swallowed."""
+
+ async def send_to_conversation(
+ self, *, service_url: str, conversation_id: str, activity: dict[str, Any]
+ ) -> str:
+ self.sends.append(
+ {
+ "service_url": service_url,
+ "conversation_id": conversation_id,
+ "activity": activity,
+ }
+ )
+ raise RuntimeError("boom")
+
+
+def test_typing_failure_is_swallowed() -> None:
+ adapter = _adapter()
+ fake = _RecordThenRaiseConnector()
+ _wire_outbound(adapter, fake)
+
+ # Must not raise even though the connector errors...
+ _run(adapter.send_typing("a:1chat", "worker", True))
+
+ # ...and the typing activity WAS attempted (not silently skipped).
+ assert len(fake.sends) == 1
+ assert fake.sends[0]["activity"]["type"] == "typing"
+
+
+def test_typing_false_is_noop() -> None:
+ adapter = _adapter()
+ fake = _FakeConnector()
+ _wire_outbound(adapter, fake)
+
+ _run(adapter.send_typing("a:1chat", "worker", False))
+
+ assert fake.sends == []
+
+
+# ── Adaptive card ────────────────────────────────────────────────────────────
+
+
+def test_agent_card_carries_name_and_body() -> None:
+ card = agent_message_card("worker", "the message body")
+ # Name appears in the header column; body appears as its own TextBlock.
+ header = card["body"][0]["columns"][1]["items"][0]
+ assert header["text"] == "worker"
+ assert card["body"][1]["text"] == "the message body"
+
+
+def test_message_activity_carries_notification_summary_and_fallback() -> None:
+ # Without a plain-text summary on the activity and a fallbackText on the card,
+ # Teams renders a "cards.unsupported" placeholder in notifications, mobile, and
+ # link/search previews.
+ adapter = _adapter()
+ activity = adapter._message_activity("worker", "hello world")
+ assert activity["summary"] == "worker: hello world"
+ assert (
+ activity["attachments"][0]["content"]["fallbackText"] == "worker: hello world"
+ )
+
+
+# ── Runtime state ────────────────────────────────────────────────────────────
+
+
+class _CountingConnector:
+ """Connector fake that returns a distinct id per posted message."""
+
+ def __init__(self) -> None:
+ self.threads: list[dict[str, Any]] = []
+ self.sends: list[dict[str, Any]] = []
+ self.updates: list[dict[str, Any]] = []
+ self.deletes: list[str] = []
+ self._n = 0
+
+ def _next(self) -> str:
+ self._n += 1
+ return f"M{self._n}"
+
+ async def create_channel_thread(
+ self, *, service_url: str, channel_id: str, activity: dict[str, Any]
+ ) -> tuple[str, str]:
+ self.threads.append(activity)
+ mid = self._next()
+ return f"{channel_id};messageid={mid}", mid
+
+ async def send_to_conversation(
+ self, *, service_url: str, conversation_id: str, activity: dict[str, Any]
+ ) -> str:
+ self.sends.append({"conversation_id": conversation_id, "activity": activity})
+ return self._next()
+
+ async def update_activity(
+ self,
+ *,
+ service_url: str,
+ conversation_id: str,
+ activity_id: str,
+ activity: dict[str, Any],
+ ) -> None:
+ self.updates.append({"activity_id": activity_id, "activity": activity})
+
+ async def delete_activity(
+ self, *, service_url: str, conversation_id: str, activity_id: str
+ ) -> None:
+ self.deletes.append(activity_id)
+
+
+def _wire_counting(adapter: TeamsAdapter, connector: _CountingConnector) -> None:
+ adapter._connector = connector # type: ignore[assignment]
+ adapter._default_service_url = "https://smba.example/amer/"
+ adapter._channel_type["19:[email protected]"] = "channel_public"
+
+
+def test_working_posts_status_card() -> None:
+ adapter = _adapter()
+ fake = _CountingConnector()
+ _wire_counting(adapter, fake)
+
+ _run(
+ adapter.apply_runtime_state(
+ "worker",
+ "working",
+ notify_user=None,
+ thread_root_id=None,
+ )
+ )
+
+ assert len(fake.threads) == 1
+ assert adapter._working_msg[("19:[email protected]", "worker")] == "M1"
+
+
+def test_working_detail_refreshes_in_place() -> None:
+ adapter = _adapter()
+ fake = _CountingConnector()
+ _wire_counting(adapter, fake)
+
+ _run(
+ adapter.apply_runtime_state(
+ "worker",
+ "working",
+ notify_user=None,
+ thread_root_id=None,
+ )
+ )
+ _run(
+ adapter.apply_runtime_state(
+ "worker",
+ "working",
+ notify_user=None,
+ thread_root_id=None,
+ detail="Editing adapter.py",
+ )
+ )
+
+ # One post, one in-place edit; the tracked ref is unchanged.
+ assert len(fake.threads) == 1
+ assert len(fake.updates) == 1
+ assert fake.updates[0]["activity_id"] == "M1"
+ assert adapter._working_msg[("19:[email protected]", "worker")] == "M1"
+
+
+def test_idle_clears_working_message() -> None:
+ adapter = _adapter()
+ fake = _CountingConnector()
+ _wire_counting(adapter, fake)
+
+ _run(
+ adapter.apply_runtime_state(
+ "worker",
+ "working",
+ notify_user=None,
+ thread_root_id=None,
+ )
+ )
+ _run(
+ adapter.apply_runtime_state(
+ "worker",
+ "idle",
+ notify_user=None,
+ thread_root_id=None,
+ )
+ )
+
+ assert fake.deletes == ["M1"]
+ assert ("19:[email protected]", "worker") not in adapter._working_msg
+
+
+def test_awaiting_input_keeps_working_and_pings() -> None:
+ adapter = _adapter()
+ fake = _CountingConnector()
+ _wire_counting(adapter, fake)
+ key = ("19:[email protected]", "worker")
+
+ _run(
+ adapter.apply_runtime_state(
+ "worker",
+ "working",
+ notify_user=None,
+ thread_root_id=None,
+ )
+ )
+ _run(
+ adapter.apply_runtime_state(
+ "worker",
+ "awaiting-input",
+ notify_user="louis",
+ thread_root_id=None,
+ )
+ )
+
+ # Working indicator stays up; a ping is tracked separately.
+ assert adapter._working_msg[key] == "M1"
+ assert adapter._input_pings[key] == ["M2"]
+
+ _run(
+ adapter.apply_runtime_state(
+ "worker",
+ "idle",
+ notify_user=None,
+ thread_root_id=None,
+ )
+ )
+ # Both the working message and the ping are removed on idle.
+ assert set(fake.deletes) == {"M1", "M2"}
+ assert key not in adapter._working_msg
+ assert key not in adapter._input_pings
diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_auth.py b/core/tests/switch_core/bridges/collaboration/test_teams_auth.py
new file mode 100644
index 000000000..6c0bf794c
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_teams_auth.py
@@ -0,0 +1,208 @@
+from __future__ import annotations
+
+import asyncio
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import jwt
+import pytest
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import rsa
+
+from switch_core.bridges.collaboration.teams.auth import (
+ BOT_CONNECTOR_SCOPE,
+ InboundActivityValidator,
+ TeamsTokenProvider,
+)
+
+_ISSUER = "https://api.botframework.com"
+
+
+def _run(coro: Any) -> Any:
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+class _FakeResp:
+ def __init__(self, status_code: int, payload: dict[str, Any]) -> None:
+ self.status_code = status_code
+ self._payload = payload
+ self.text = str(payload)
+
+ def json(self) -> dict[str, Any]:
+ return self._payload
+
+
+class _FakeHttp:
+ def __init__(self, resp: _FakeResp) -> None:
+ self._resp = resp
+ self.calls: list[dict[str, Any]] = []
+
+ async def post(self, url: str, data: dict[str, Any]) -> _FakeResp:
+ self.calls.append({"url": url, "data": data})
+ return self._resp
+
+
+def _provider(http: _FakeHttp) -> TeamsTokenProvider:
+ return TeamsTokenProvider(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ app_password="secret",
+ http=http, # type: ignore[arg-type]
+ )
+
+
+def test_token_is_fetched_and_returned() -> None:
+ http = _FakeHttp(_FakeResp(200, {"access_token": "tok-1", "expires_in": 3600}))
+ provider = _provider(http)
+
+ token = _run(provider.token(BOT_CONNECTOR_SCOPE))
+
+ assert token == "tok-1"
+ assert len(http.calls) == 1
+ assert http.calls[0]["data"]["scope"] == BOT_CONNECTOR_SCOPE
+ assert http.calls[0]["data"]["grant_type"] == "client_credentials"
+
+
+def test_token_is_cached_until_expiry() -> None:
+ http = _FakeHttp(_FakeResp(200, {"access_token": "tok-1", "expires_in": 3600}))
+ provider = _provider(http)
+
+ first = _run(provider.token(BOT_CONNECTOR_SCOPE))
+ second = _run(provider.token(BOT_CONNECTOR_SCOPE))
+
+ assert first == second == "tok-1"
+ # Only one network round-trip — the second call is served from cache.
+ assert len(http.calls) == 1
+
+
+def test_token_error_raises() -> None:
+ http = _FakeHttp(_FakeResp(401, {"error": "invalid_client"}))
+ provider = _provider(http)
+
+ try:
+ _run(provider.token(BOT_CONNECTOR_SCOPE))
+ raised = False
+ except RuntimeError:
+ raised = True
+ assert raised
+
+
+# ── InboundActivityValidator (Bot Framework JWT verification) ─────────────────
+
+
+def _keypair() -> tuple[str, str]:
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ priv_pem = key.private_bytes(
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption(),
+ ).decode()
+ pub_pem = (
+ key.public_key()
+ .public_bytes(
+ serialization.Encoding.PEM,
+ serialization.PublicFormat.SubjectPublicKeyInfo,
+ )
+ .decode()
+ )
+ return priv_pem, pub_pem
+
+
+class _FakeSigningKey:
+ def __init__(self, public_pem: str) -> None:
+ self.key = public_pem
+
+
+class _FakeJwks:
+ """Stands in for the network-backed PyJWKClient so decode uses our key."""
+
+ def __init__(self, public_pem: str) -> None:
+ self._public_pem = public_pem
+
+ def get_signing_key_from_jwt(self, token: str) -> _FakeSigningKey:
+ return _FakeSigningKey(self._public_pem)
+
+
+def _validator(public_pem: str, *, app_id: str = "app-1") -> InboundActivityValidator:
+ validator = InboundActivityValidator(app_id=app_id)
+ # Bypass the network JWKS fetch by pre-seeding the signing-key source.
+ validator._jwks = _FakeJwks(public_pem) # type: ignore[assignment]
+ return validator
+
+
+def _token(
+ priv_pem: str,
+ *,
+ aud: str = "app-1",
+ iss: str = _ISSUER,
+ expired: bool = False,
+) -> str:
+ now = datetime.now(UTC)
+ exp = now - timedelta(minutes=5) if expired else now + timedelta(hours=1)
+ return jwt.encode(
+ {"aud": aud, "iss": iss, "exp": exp},
+ priv_pem,
+ algorithm="RS256",
+ )
+
+
+def test_validator_accepts_valid_token() -> None:
+ priv, pub = _keypair()
+ validator = _validator(pub)
+
+ # No raise = accepted.
+ validator.validate(f"Bearer {_token(priv)}")
+
+
+def test_validator_rejects_missing_header() -> None:
+ _, pub = _keypair()
+ validator = _validator(pub)
+
+ with pytest.raises(PermissionError):
+ validator.validate(None)
+
+
+def test_validator_rejects_non_bearer_header() -> None:
+ _, pub = _keypair()
+ validator = _validator(pub)
+
+ with pytest.raises(PermissionError):
+ validator.validate("Basic Zm9vOmJhcg==")
+
+
+def test_validator_rejects_wrong_audience() -> None:
+ priv, pub = _keypair()
+ validator = _validator(pub, app_id="app-1")
+
+ with pytest.raises(jwt.InvalidAudienceError):
+ validator.validate(f"Bearer {_token(priv, aud='someone-else')}")
+
+
+def test_validator_rejects_expired_token() -> None:
+ priv, pub = _keypair()
+ validator = _validator(pub)
+
+ with pytest.raises(jwt.ExpiredSignatureError):
+ validator.validate(f"Bearer {_token(priv, expired=True)}")
+
+
+def test_validator_rejects_wrong_issuer() -> None:
+ priv, pub = _keypair()
+ validator = _validator(pub)
+
+ with pytest.raises(jwt.InvalidIssuerError):
+ validator.validate(f"Bearer {_token(priv, iss='https://evil.example')}")
+
+
+def test_validator_rejects_bad_signature() -> None:
+ priv_signing, _ = _keypair()
+ _, pub_other = _keypair()
+ # Verify with a public key that does NOT match the signing key.
+ validator = _validator(pub_other)
+
+ with pytest.raises(jwt.InvalidSignatureError):
+ validator.validate(f"Bearer {_token(priv_signing)}")
diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_capture.py b/core/tests/switch_core/bridges/collaboration/test_teams_capture.py
new file mode 100644
index 000000000..394ac9567
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_teams_capture.py
@@ -0,0 +1,623 @@
+from __future__ import annotations
+
+import asyncio
+import base64
+import datetime
+import hashlib
+import hmac
+import json
+import os
+from typing import Any
+
+from cryptography import x509
+from cryptography.hazmat.primitives import hashes, serialization
+from cryptography.hazmat.primitives.asymmetric import padding as asym_padding
+from cryptography.hazmat.primitives.asymmetric import rsa
+from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
+from cryptography.hazmat.primitives.hashes import SHA1
+from cryptography.hazmat.primitives.padding import PKCS7
+from cryptography.x509.oid import NameOID
+
+from switch_core.bridges.collaboration.models import InboundMessage
+from switch_core.bridges.collaboration.teams.adapter import (
+ TeamsAdapter,
+ TeamsConnectionConfig,
+)
+from switch_core.bridges.collaboration.teams.crypto import (
+ ResourceDataError,
+ decrypt_resource_data,
+ load_certificate_der_b64,
+)
+
+
+def _run(coro: Any) -> Any:
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+def _make_key_and_cert() -> tuple[str, str, x509.Certificate]:
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "switch-teams-test")])
+ cert = (
+ x509.CertificateBuilder()
+ .subject_name(name)
+ .issuer_name(name)
+ .public_key(key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(datetime.datetime(2020, 1, 1, tzinfo=datetime.UTC))
+ .not_valid_after(datetime.datetime(2035, 1, 1, tzinfo=datetime.UTC))
+ .sign(key, hashes.SHA256())
+ )
+ key_pem = key.private_bytes(
+ serialization.Encoding.PEM,
+ serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption(),
+ ).decode()
+ cert_pem = cert.public_bytes(serialization.Encoding.PEM).decode()
+ return key_pem, cert_pem, cert
+
+
+def _encrypt_like_graph(
+ payload: dict[str, Any], cert: x509.Certificate
+) -> dict[str, str]:
+ """Encrypt a resource payload exactly as Microsoft Graph does, so the
+ adapter's decryption can be verified end-to-end."""
+ symmetric_key = os.urandom(32)
+ raw = json.dumps(payload).encode("utf-8")
+
+ padder = PKCS7(algorithms.AES.block_size).padder()
+ padded = padder.update(raw) + padder.finalize()
+ encryptor = Cipher(
+ algorithms.AES(symmetric_key), modes.CBC(symmetric_key[:16])
+ ).encryptor()
+ data = encryptor.update(padded) + encryptor.finalize()
+
+ data_key = cert.public_key().encrypt( # type: ignore[union-attr]
+ symmetric_key,
+ asym_padding.OAEP(
+ mgf=asym_padding.MGF1(algorithm=SHA1()), algorithm=SHA1(), label=None
+ ),
+ )
+ signature = hmac.new(symmetric_key, data, hashlib.sha256).digest()
+ return {
+ "data": base64.b64encode(data).decode(),
+ "dataKey": base64.b64encode(data_key).decode(),
+ "dataSignature": base64.b64encode(signature).decode(),
+ }
+
+
+def _config(key_pem: str, cert_pem: str) -> TeamsConnectionConfig:
+ return TeamsConnectionConfig(
+ app_id="app-123",
+ app_password="secret",
+ tenant_id="tenant-1",
+ team_id="team-1",
+ public_base_url="https://switch.example",
+ encryption_certificate_id="cert-1",
+ encryption_public_certificate=cert_pem,
+ encryption_private_key=key_pem,
+ client_state="s3cr3t",
+ )
+
+
+# ── Crypto round-trip ────────────────────────────────────────────────────────
+
+
+def test_decrypt_resource_data_round_trip() -> None:
+ key_pem, cert_pem, cert = _make_key_and_cert()
+ payload = {"id": "m1", "body": {"content": "hello world"}}
+
+ encrypted = _encrypt_like_graph(payload, cert)
+ decrypted = decrypt_resource_data(encrypted, key_pem)
+
+ assert decrypted == payload
+
+
+def test_decrypt_rejects_tampered_signature() -> None:
+ key_pem, cert_pem, cert = _make_key_and_cert()
+ encrypted = _encrypt_like_graph({"id": "x"}, cert)
+ encrypted["dataSignature"] = base64.b64encode(b"not-the-signature").decode()
+
+ try:
+ decrypt_resource_data(encrypted, key_pem)
+ raised = False
+ except ResourceDataError:
+ raised = True
+ assert raised
+
+
+def test_load_certificate_der_b64_round_trips_to_der() -> None:
+ _, cert_pem, cert = _make_key_and_cert()
+ der_b64 = load_certificate_der_b64(cert_pem)
+ # It decodes back to the certificate's DER encoding.
+ assert base64.b64decode(der_b64) == cert.public_bytes(serialization.Encoding.DER)
+
+
+# ── Notification handling ────────────────────────────────────────────────────
+
+
+class _FakeRequest:
+ def __init__(
+ self, *, query: dict[str, str] | None = None, body: Any = None
+ ) -> None:
+ self.query = query or {}
+ self._body = body
+
+ async def json(self) -> Any:
+ if self._body is None:
+ raise ValueError("no body")
+ return self._body
+
+
+def _adapter(key_pem: str, cert_pem: str) -> TeamsAdapter:
+ return TeamsAdapter(config=_config(key_pem, cert_pem))
+
+
+def _capture(adapter: TeamsAdapter) -> list[InboundMessage]:
+ captured: list[InboundMessage] = []
+
+ async def on_message(msg: InboundMessage) -> None:
+ captured.append(msg)
+
+ adapter._on_message = on_message
+ return captured
+
+
+def test_validation_handshake_echoes_token() -> None:
+ key_pem, cert_pem, _ = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+
+ resp = _run(
+ adapter._handle_http_notifications(
+ _FakeRequest(query={"validationToken": "tok-xyz"}) # type: ignore[arg-type]
+ )
+ )
+
+ assert resp.status == 200
+ assert resp.text == "tok-xyz"
+
+
+def test_notification_decrypts_and_delivers_message() -> None:
+ key_pem, cert_pem, cert = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ captured = _capture(adapter)
+ adapter._channel_type["19:[email protected]"] = "channel_public"
+
+ chat_message = {
+ "id": "m100",
+ "messageType": "message",
+ "from": {"user": {"id": "aad-u", "displayName": "Alice"}},
+ "channelIdentity": {"teamId": "t1", "channelId": "19:[email protected]"},
+ "body": {"contentType": "html", "content": "<p>hello <at>Bot</at> team</p>"},
+ }
+ item = {
+ "clientState": "s3cr3t",
+ "encryptedContent": _encrypt_like_graph(chat_message, cert),
+ }
+
+ _run(adapter._dispatch_graph_notification(item))
+
+ assert len(captured) == 1
+ msg = captured[0]
+ assert msg.channel_id == "19:[email protected]"
+ assert msg.sender_id == "aad-u"
+ assert msg.sender_name == "Alice"
+ # The `<at>Bot</at>` mention is kept as an `@name` token, not deleted.
+ assert msg.content == "hello @Bot team"
+ assert msg.message_ref == "m100"
+ assert msg.self_mention_token is None
+
+
+def test_notification_sets_self_mention_token_for_bot_mention() -> None:
+ key_pem, cert_pem, cert = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ captured = _capture(adapter)
+ adapter._channel_type["19:[email protected]"] = "channel_public"
+
+ chat_message = {
+ "id": "m300",
+ "messageType": "message",
+ "from": {"user": {"id": "aad-u", "displayName": "Alice"}},
+ "channelIdentity": {"teamId": "t1", "channelId": "19:[email protected]"},
+ "body": {"contentType": "html", "content": '<p><at id="0">Bot</at> hi</p>'},
+ "mentions": [
+ {
+ "id": 0,
+ "mentionText": "Bot",
+ "mentioned": {"application": {"id": "app-123", "displayName": "Bot"}},
+ }
+ ],
+ }
+ item = {
+ "clientState": "s3cr3t",
+ "encryptedContent": _encrypt_like_graph(chat_message, cert),
+ }
+ _run(adapter._dispatch_graph_notification(item))
+
+ assert len(captured) == 1
+ assert captured[0].content == "@Bot hi"
+ assert captured[0].self_mention_token == "app-123"
+
+
+def test_notification_no_self_mention_token_for_human_mention() -> None:
+ key_pem, cert_pem, cert = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ captured = _capture(adapter)
+ adapter._channel_type["19:[email protected]"] = "channel_public"
+
+ chat_message = {
+ "id": "m400",
+ "messageType": "message",
+ "from": {"user": {"id": "aad-u", "displayName": "Alice"}},
+ "channelIdentity": {"teamId": "t1", "channelId": "19:[email protected]"},
+ "body": {"contentType": "html", "content": '<p><at id="0">Bob</at> hi</p>'},
+ "mentions": [
+ {
+ "id": 0,
+ "mentionText": "Bob",
+ "mentioned": {"user": {"id": "aad-bob", "displayName": "Bob"}},
+ }
+ ],
+ }
+ item = {
+ "clientState": "s3cr3t",
+ "encryptedContent": _encrypt_like_graph(chat_message, cert),
+ }
+ _run(adapter._dispatch_graph_notification(item))
+
+ assert len(captured) == 1
+ assert captured[0].content == "@Bob hi"
+ assert captured[0].self_mention_token is None
+
+
+def test_graph_message_attachment_is_disclosed() -> None:
+ # A captured channel message carrying an attachment / inline image must
+ # bridge its text and disclose the media rather than dropping it silently.
+ key_pem, cert_pem, cert = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ captured = _capture(adapter)
+ adapter._channel_type["19:[email protected]"] = "channel_public"
+
+ chat_message = {
+ "id": "m-att",
+ "messageType": "message",
+ "from": {"user": {"id": "aad-u", "displayName": "Alice"}},
+ "channelIdentity": {"teamId": "t1", "channelId": "19:[email protected]"},
+ "body": {"contentType": "html", "content": "<p>see attached</p>"},
+ "attachments": [{"contentType": "reference", "name": "report.pdf"}],
+ "hostedContents": [{"id": "h1"}],
+ }
+ item = {
+ "clientState": "s3cr3t",
+ "encryptedContent": _encrypt_like_graph(chat_message, cert),
+ }
+
+ _run(adapter._dispatch_graph_notification(item))
+
+ assert len(captured) == 1
+ content = captured[0].content
+ assert content.startswith("see attached")
+ assert "report.pdf" in content
+ assert "not relayed" in content
+
+
+def test_notification_rejects_bad_client_state() -> None:
+ key_pem, cert_pem, cert = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ captured = _capture(adapter)
+
+ item = {
+ "clientState": "WRONG",
+ "encryptedContent": _encrypt_like_graph({"id": "m1"}, cert),
+ }
+ _run(adapter._dispatch_graph_notification(item))
+
+ assert captured == []
+
+
+def test_own_bot_message_is_not_delivered() -> None:
+ key_pem, cert_pem, cert = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ captured = _capture(adapter)
+
+ chat_message = {
+ "id": "m200",
+ "messageType": "message",
+ # Authored by our own bot app → must be dropped (loop prevention).
+ "from": {"application": {"id": "app-123", "displayName": "Switch"}},
+ "channelIdentity": {"teamId": "t1", "channelId": "19:[email protected]"},
+ "body": {"contentType": "text", "content": "echo"},
+ }
+ item = {
+ "clientState": "s3cr3t",
+ "encryptedContent": _encrypt_like_graph(chat_message, cert),
+ }
+ _run(adapter._dispatch_graph_notification(item))
+
+ assert captured == []
+
+
+def test_graph_capture_dedupes_with_bot_framework_path() -> None:
+ key_pem, cert_pem, cert = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ captured = _capture(adapter)
+ adapter._channel_type["19:[email protected]"] = "channel_public"
+
+ chat_message = {
+ "id": "dup-1",
+ "messageType": "message",
+ "from": {"user": {"id": "aad-u", "displayName": "Alice"}},
+ "channelIdentity": {"teamId": "t1", "channelId": "19:[email protected]"},
+ "body": {"contentType": "text", "content": "hi"},
+ }
+ item = {
+ "clientState": "s3cr3t",
+ "encryptedContent": _encrypt_like_graph(chat_message, cert),
+ }
+ _run(adapter._dispatch_graph_notification(item))
+ # The same message id already seen via one path is ignored on the other.
+ _run(adapter._dispatch_graph_notification(item))
+
+ assert len(captured) == 1
+
+
+def test_reply_sets_root_id_from_reply_to_id() -> None:
+ key_pem, cert_pem, cert = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ captured = _capture(adapter)
+ adapter._channel_type["19:[email protected]"] = "channel_public"
+
+ chat_message = {
+ "id": "reply-1",
+ "messageType": "message",
+ "replyToId": "root-1",
+ "from": {"user": {"id": "aad-u", "displayName": "Alice"}},
+ "channelIdentity": {"teamId": "t1", "channelId": "19:[email protected]"},
+ "body": {"contentType": "text", "content": "a reply"},
+ }
+ item = {
+ "clientState": "s3cr3t",
+ "encryptedContent": _encrypt_like_graph(chat_message, cert),
+ }
+ _run(adapter._dispatch_graph_notification(item))
+
+ assert captured[0].root_id == "root-1"
+
+
+def test_system_event_message_is_ignored() -> None:
+ key_pem, cert_pem, cert = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ captured = _capture(adapter)
+
+ chat_message = {
+ "id": "sys-1",
+ "messageType": "systemEventMessage",
+ "channelIdentity": {"teamId": "t1", "channelId": "19:[email protected]"},
+ "body": {"contentType": "text", "content": ""},
+ }
+ item = {
+ "clientState": "s3cr3t",
+ "encryptedContent": _encrypt_like_graph(chat_message, cert),
+ }
+ _run(adapter._dispatch_graph_notification(item))
+
+ assert captured == []
+
+
+# ── Subscription lifecycle ───────────────────────────────────────────────────
+
+
+class _FakeGraph:
+ def __init__(self, existing: list[dict[str, Any]] | None = None) -> None:
+ self.created: list[dict[str, Any]] = []
+ self.renewed: list[dict[str, Any]] = []
+ self.deleted: list[str] = []
+ self._existing = existing or []
+
+ async def create_subscription(self, **kwargs: Any) -> dict[str, Any]:
+ self.created.append(kwargs)
+ return {"id": "SUB-1"}
+
+ async def renew_subscription(self, **kwargs: Any) -> None:
+ self.renewed.append(kwargs)
+
+ async def delete_subscription(self, *, subscription_id: str) -> None:
+ self.deleted.append(subscription_id)
+
+ async def list_subscriptions(self) -> list[dict[str, Any]]:
+ return self._existing
+
+
+def test_ensure_channel_subscription_creates_with_expected_resource() -> None:
+ key_pem, cert_pem, _ = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ fake = _FakeGraph()
+ adapter._graph = fake # type: ignore[assignment]
+ adapter._team_of_channel["19:[email protected]"] = "team-9"
+
+ _run(adapter._ensure_channel_subscription("19:[email protected]"))
+
+ assert len(fake.created) == 1
+ assert (
+ fake.created[0]["resource"]
+ == "teams/team-9/channels/19:[email protected]/messages"
+ )
+ assert fake.created[0]["client_state"] == "s3cr3t"
+ assert adapter._subscriptions["19:[email protected]"] == "SUB-1"
+
+
+def test_ensure_channel_subscription_skips_without_certificate() -> None:
+ adapter = TeamsAdapter(
+ config=TeamsConnectionConfig(
+ app_id="app-123",
+ app_password="secret",
+ tenant_id="tenant-1",
+ team_id="team-1",
+ public_base_url="https://switch.example",
+ client_state="s3cr3t",
+ )
+ )
+ fake = _FakeGraph()
+ adapter._graph = fake # type: ignore[assignment]
+ adapter._team_of_channel["19:[email protected]"] = "team-9"
+
+ _run(adapter._ensure_channel_subscription("19:[email protected]"))
+
+ # No certificate configured → no subscription created (logged, not crashed).
+ assert fake.created == []
+ assert "19:[email protected]" not in adapter._subscriptions
+
+
+def test_ensure_channel_subscriptions_recreates_missing_channel_subs() -> None:
+ # Self-heal on startup: create subs for channels that lack one, skip
+ # already-subscribed channels and non-channel (direct) conversations.
+ key_pem, cert_pem, _ = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ fake = _FakeGraph()
+ adapter._graph = fake # type: ignore[assignment]
+ adapter._subscriptions["19:[email protected]"] = "EXISTING"
+
+ _run(
+ adapter.ensure_channel_subscriptions(
+ [
+ ("19:[email protected]", "channel_public"),
+ ("19:[email protected]", "channel_private"),
+ ("19:[email protected]", "channel_public"),
+ ("a:1dmchat", "direct"),
+ ]
+ )
+ )
+
+ resources = sorted(c["resource"] for c in fake.created)
+ assert resources == [
+ "teams/team-1/channels/19:[email protected]/messages",
+ "teams/team-1/channels/19:[email protected]/messages",
+ ]
+
+
+def test_adopt_existing_subscriptions_deletes_stale_and_keeps_current() -> None:
+ # A rotated tunnel leaves subs pointing at a dead URL; on start we keep the
+ # ones matching our current URL and delete the stale ones so they can be
+ # recreated cleanly.
+ key_pem, cert_pem, _ = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ current = adapter._notification_url
+ fake = _FakeGraph(
+ existing=[
+ {
+ "id": "CUR",
+ "resource": "teams/t/channels/19:[email protected]/messages",
+ "notificationUrl": current,
+ },
+ {
+ "id": "OLD",
+ "resource": "teams/t/channels/19:[email protected]/messages",
+ "notificationUrl": "https://dead.example/api/teams/notifications",
+ },
+ {
+ "id": "OTHER",
+ "resource": "users/u/messages",
+ "notificationUrl": "https://x.example",
+ },
+ ]
+ )
+ adapter._graph = fake # type: ignore[assignment]
+
+ _run(adapter._adopt_existing_subscriptions())
+
+ assert adapter._subscriptions == {"19:[email protected]": "CUR"}
+ assert fake.deleted == ["OLD"]
+
+
+def test_channel_from_resource_parses_channel_id() -> None:
+ assert (
+ TeamsAdapter._channel_from_resource(
+ "teams/team-9/channels/19:[email protected]/messages"
+ )
+ )
+
+
+def test_lifecycle_reauthorization_renews_subscription() -> None:
+ key_pem, cert_pem, _ = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ fake = _FakeGraph()
+ adapter._graph = fake # type: ignore[assignment]
+
+ _run(
+ adapter._dispatch_graph_notification(
+ {
+ "lifecycleEvent": "reauthorizationRequired",
+ "subscriptionId": "SUB-42",
+ "clientState": "s3cr3t",
+ }
+ )
+ )
+
+ assert len(fake.renewed) == 1
+ assert fake.renewed[0]["subscription_id"] == "SUB-42"
+
+
+def test_lifecycle_event_with_bad_client_state_is_rejected() -> None:
+ # A forged lifecycle notification (e.g. reauthorizationRequired) must not be
+ # honoured without a valid clientState — the encryption authenticates only
+ # data notifications, so lifecycle events rely entirely on clientState.
+ key_pem, cert_pem, _ = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ fake = _FakeGraph()
+ adapter._graph = fake # type: ignore[assignment]
+
+ _run(
+ adapter._dispatch_graph_notification(
+ {
+ "lifecycleEvent": "reauthorizationRequired",
+ "subscriptionId": "SUB-42",
+ "clientState": "WRONG",
+ }
+ )
+ )
+
+ assert fake.renewed == []
+
+
+def test_lifecycle_subscription_removed_recreates() -> None:
+ # A subscriptionRemoved event must recreate the channel's subscription, not
+ # just log — otherwise capture silently lapses until the next restart.
+ key_pem, cert_pem, _ = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ fake = _FakeGraph()
+ adapter._graph = fake # type: ignore[assignment]
+ adapter._team_of_channel["19:[email protected]"] = "team-9"
+ adapter._subscriptions["19:[email protected]"] = "SUB-OLD"
+
+ _run(
+ adapter._dispatch_graph_notification(
+ {
+ "lifecycleEvent": "subscriptionRemoved",
+ "subscriptionId": "SUB-OLD",
+ "clientState": "s3cr3t",
+ }
+ )
+ )
+
+ # The dead subscription was replaced by a freshly created one.
+ assert len(fake.created) == 1
+ assert adapter._subscriptions["19:[email protected]"] == "SUB-1"
+
+
+def test_renew_all_subscriptions_renews_each() -> None:
+ key_pem, cert_pem, _ = _make_key_and_cert()
+ adapter = _adapter(key_pem, cert_pem)
+ fake = _FakeGraph()
+ adapter._graph = fake # type: ignore[assignment]
+ adapter._subscriptions = {
+ "19:[email protected]": "S1",
+ "19:[email protected]": "S2",
+ }
+
+ _run(adapter._renew_all_subscriptions())
+
+ assert {r["subscription_id"] for r in fake.renewed} == {"S1", "S2"}
diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_clients.py b/core/tests/switch_core/bridges/collaboration/test_teams_clients.py
new file mode 100644
index 000000000..ccb448917
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_teams_clients.py
@@ -0,0 +1,315 @@
+"""Direct tests for the real Teams HTTP clients (GraphClient, BotConnectorClient).
+
+Everywhere else the adapter tests substitute fakes for these clients, so the
+actual URL construction, request bodies, response parsing, and — crucially — the
+special-cased status codes (404-swallow on delete, 409-swallow on member add,
+``>=300`` → error) are exercised here against an in-process ``httpx.MockTransport``
+(no network).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from typing import Any
+
+import httpx
+import pytest
+
+from switch_core.bridges.collaboration.teams.connector import (
+ BotConnectorClient,
+ BotConnectorError,
+)
+from switch_core.bridges.collaboration.teams.graph import GraphClient, GraphError
+
+
+def _run(coro: Any) -> Any:
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+class _FakeTokens:
+ async def graph_token(self) -> str:
+ return "graph-tok"
+
+ async def bot_token(self) -> str:
+ return "bot-tok"
+
+
+class _Recorder:
+ """Captures each request and replies with a scripted status/body."""
+
+ def __init__(self, status: int = 200, body: Any = None) -> None:
+ self.status = status
+ self.body = {} if body is None else body
+ self.requests: list[httpx.Request] = []
+
+ def handler(self, request: httpx.Request) -> httpx.Response:
+ self.requests.append(request)
+ return httpx.Response(self.status, json=self.body)
+
+ @property
+ def last(self) -> httpx.Request:
+ return self.requests[-1]
+
+ def last_json(self) -> Any:
+ return json.loads(self.requests[-1].content)
+
+
+def _client(recorder: _Recorder) -> httpx.AsyncClient:
+ return httpx.AsyncClient(transport=httpx.MockTransport(recorder.handler))
+
+
+def _graph(recorder: _Recorder) -> GraphClient:
+ return GraphClient(tokens=_FakeTokens(), http=_client(recorder)) # type: ignore[arg-type]
+
+
+def _connector(recorder: _Recorder) -> BotConnectorClient:
+ return BotConnectorClient(tokens=_FakeTokens(), http=_client(recorder)) # type: ignore[arg-type]
+
+
+# ── GraphClient ───────────────────────────────────────────────────────────────
+
+
+def test_create_subscription_sends_expected_body() -> None:
+ rec = _Recorder(201, {"id": "SUB-1"})
+ graph = _graph(rec)
+
+ result = _run(
+ graph.create_subscription(
+ resource="teams/t1/channels/c1/messages",
+ notification_url="https://x/api/teams/notifications",
+ lifecycle_notification_url="https://x/api/teams/notifications",
+ client_state="s3cr3t",
+ expiration_iso="2026-01-01T00:00:00Z",
+ encryption_certificate="CERT",
+ encryption_certificate_id="cert-1",
+ )
+ )
+
+ assert result == {"id": "SUB-1"}
+ assert str(rec.last.url) == "https://graph.microsoft.com/v1.0/subscriptions"
+ assert rec.last.headers["Authorization"] == "Bearer graph-tok"
+ body = rec.last_json()
+ assert body["changeType"] == "created,updated"
+ assert body["includeResourceData"] is True
+ assert body["resource"] == "teams/t1/channels/c1/messages"
+ assert body["encryptionCertificate"] == "CERT"
+ assert body["clientState"] == "s3cr3t"
+
+
+def test_create_subscription_error_raises() -> None:
+ graph = _graph(_Recorder(403, {"error": "forbidden"}))
+
+ with pytest.raises(GraphError):
+ _run(
+ graph.create_subscription(
+ resource="teams/t1/channels/c1/messages",
+ notification_url="https://x/n",
+ lifecycle_notification_url="https://x/n",
+ client_state="s",
+ expiration_iso="2026-01-01T00:00:00Z",
+ encryption_certificate="CERT",
+ encryption_certificate_id="cert-1",
+ )
+ )
+
+
+def test_delete_subscription_swallows_404() -> None:
+ # An already-gone subscription is not an error.
+ graph = _graph(_Recorder(404, {"error": "not found"}))
+ _run(graph.delete_subscription(subscription_id="SUB-gone"))
+
+
+def test_delete_subscription_raises_on_other_error() -> None:
+ graph = _graph(_Recorder(500, {"error": "boom"}))
+ with pytest.raises(GraphError):
+ _run(graph.delete_subscription(subscription_id="SUB-1"))
+
+
+def test_add_channel_member_swallows_409_conflict() -> None:
+ # Already a member → 409 is idempotent, not an error.
+ rec = _Recorder(409, {"error": "conflict"})
+ graph = _graph(rec)
+ _run(graph.add_channel_member(team_id="t1", channel_id="c1", user_aad_id="u1"))
+ assert (
+ str(rec.last.url)
+ == "https://graph.microsoft.com/v1.0/teams/t1/channels/c1/members"
+ )
+
+
+def test_add_channel_member_raises_on_other_error() -> None:
+ graph = _graph(_Recorder(500, {"error": "boom"}))
+ with pytest.raises(GraphError):
+ _run(graph.add_channel_member(team_id="t1", channel_id="c1", user_aad_id="u1"))
+
+
+def test_add_team_member_swallows_409_conflict() -> None:
+ graph = _graph(_Recorder(409, {"error": "conflict"}))
+ _run(graph.add_team_member(team_id="t1", user_aad_id="u1"))
+
+
+def test_add_team_member_raises_on_other_error() -> None:
+ graph = _graph(_Recorder(500, {"error": "boom"}))
+ with pytest.raises(GraphError):
+ _run(graph.add_team_member(team_id="t1", user_aad_id="u1"))
+
+
+def test_create_channel_sends_body_and_returns_channel() -> None:
+ rec = _Recorder(201, {"id": "19:[email protected]", "membershipType": "private"})
+ graph = _graph(rec)
+
+ channel = _run(
+ graph.create_channel(
+ team_id="t1",
+ display_name="My Room",
+ description="topic",
+ membership_type="private",
+ )
+ )
+
+ assert channel["id"] == "19:[email protected]"
+ assert str(rec.last.url) == "https://graph.microsoft.com/v1.0/teams/t1/channels"
+ body = rec.last_json()
+ assert body["displayName"] == "My Room"
+ assert body["membershipType"] == "private"
+
+
+def test_list_subscriptions_returns_value_array() -> None:
+ graph = _graph(_Recorder(200, {"value": [{"id": "S1"}, {"id": "S2"}]}))
+ subs = _run(graph.list_subscriptions())
+ assert [s["id"] for s in subs] == ["S1", "S2"]
+
+
+def test_renew_subscription_error_raises() -> None:
+ graph = _graph(_Recorder(404, {"error": "gone"}))
+ with pytest.raises(GraphError):
+ _run(
+ graph.renew_subscription(
+ subscription_id="S1", expiration_iso="2026-01-01T00:00:00Z"
+ )
+ )
+
+
+# ── BotConnectorClient ────────────────────────────────────────────────────────
+
+
+def test_create_channel_thread_builds_body_and_parses_ids() -> None:
+ rec = _Recorder(201, {"id": "conv-1", "activityId": "act-1"})
+ connector = _connector(rec)
+
+ conversation_id, activity_id = _run(
+ connector.create_channel_thread(
+ service_url="https://smba.example/amer/",
+ channel_id="19:[email protected]",
+ activity={"type": "message", "text": "hi"},
+ )
+ )
+
+ assert conversation_id == "conv-1"
+ assert activity_id == "act-1"
+ assert str(rec.last.url) == "https://smba.example/amer/v3/conversations"
+ assert rec.last.headers["Authorization"] == "Bearer bot-tok"
+ body = rec.last_json()
+ assert body["isGroup"] is True
+ assert body["channelData"]["channel"]["id"] == "19:[email protected]"
+
+
+def test_create_channel_thread_falls_back_to_id_when_no_activity_id() -> None:
+ # Some responses carry only ``id`` — it doubles as the activity id.
+ rec = _Recorder(201, {"id": "conv-1"})
+ connector = _connector(rec)
+
+ conversation_id, activity_id = _run(
+ connector.create_channel_thread(
+ service_url="https://smba.example/amer/",
+ channel_id="19:[email protected]",
+ activity={"type": "message"},
+ )
+ )
+
+ assert conversation_id == "conv-1"
+ assert activity_id == "conv-1"
+
+
+def test_create_channel_thread_error_raises() -> None:
+ connector = _connector(_Recorder(500, {"error": "boom"}))
+ with pytest.raises(BotConnectorError):
+ _run(
+ connector.create_channel_thread(
+ service_url="https://smba.example/amer/",
+ channel_id="19:[email protected]",
+ activity={"type": "message"},
+ )
+ )
+
+
+def test_send_to_conversation_returns_id_and_builds_url() -> None:
+ rec = _Recorder(201, {"id": "msg-9"})
+ connector = _connector(rec)
+
+ msg_id = _run(
+ connector.send_to_conversation(
+ service_url="https://smba.example/amer/",
+ conversation_id="conv-1",
+ activity={"type": "message", "text": "hi"},
+ )
+ )
+
+ assert msg_id == "msg-9"
+ assert str(rec.last.url) == (
+ "https://smba.example/amer/v3/conversations/conv-1/activities"
+ )
+
+
+def test_send_to_conversation_error_raises() -> None:
+ connector = _connector(_Recorder(502, {"error": "bad gateway"}))
+ with pytest.raises(BotConnectorError):
+ _run(
+ connector.send_to_conversation(
+ service_url="https://smba.example/amer/",
+ conversation_id="conv-1",
+ activity={"type": "message"},
+ )
+ )
+
+
+def test_update_activity_error_raises() -> None:
+ connector = _connector(_Recorder(404, {"error": "gone"}))
+ with pytest.raises(BotConnectorError):
+ _run(
+ connector.update_activity(
+ service_url="https://smba.example/amer/",
+ conversation_id="conv-1",
+ activity_id="act-1",
+ activity={"type": "message"},
+ )
+ )
+
+
+def test_delete_activity_error_raises() -> None:
+ connector = _connector(_Recorder(403, {"error": "forbidden"}))
+ with pytest.raises(BotConnectorError):
+ _run(
+ connector.delete_activity(
+ service_url="https://smba.example/amer/",
+ conversation_id="conv-1",
+ activity_id="act-1",
+ )
+ )
+
+
+def test_delete_activity_success_is_silent() -> None:
+ rec = _Recorder(200, {})
+ connector = _connector(rec)
+ _run(
+ connector.delete_activity(
+ service_url="https://smba.example/amer/",
+ conversation_id="conv-1",
+ activity_id="act-1",
+ )
+ )
+ assert rec.last.method == "DELETE"
diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_provisioning.py b/core/tests/switch_core/bridges/collaboration/test_teams_provisioning.py
new file mode 100644
index 000000000..2ec80df0f
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_teams_provisioning.py
@@ -0,0 +1,221 @@
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import pytest
+
+from switch_core.bridges.collaboration.teams.adapter import (
+ TeamsAdapter,
+ TeamsConnectionConfig,
+)
+
+
+def _config() -> TeamsConnectionConfig:
+ return TeamsConnectionConfig(
+ app_id="app-123",
+ app_password="secret",
+ tenant_id="tenant-9",
+ team_id="team-7",
+ public_base_url="https://switch.example",
+ client_state="s3cr3t",
+ )
+
+
+def _adapter() -> TeamsAdapter:
+ return TeamsAdapter(config=_config())
+
+
+def _run(coro: Any) -> Any:
+ loop = asyncio.new_event_loop()
+ try:
+ return loop.run_until_complete(coro)
+ finally:
+ loop.close()
+
+
+class _FakeGraph:
+ def __init__(self, *, membership_type: str = "standard") -> None:
+ self.created_channels: list[dict[str, Any]] = []
+ self.channel_members: list[dict[str, Any]] = []
+ self.team_members: list[dict[str, Any]] = []
+ self._membership_type = membership_type
+
+ async def create_channel(
+ self,
+ *,
+ team_id: str,
+ display_name: str,
+ description: str,
+ membership_type: str,
+ ) -> dict[str, Any]:
+ self.created_channels.append(
+ {
+ "team_id": team_id,
+ "display_name": display_name,
+ "description": description,
+ "membership_type": membership_type,
+ }
+ )
+ return {"id": "19:[email protected]", "membershipType": membership_type}
+
+ async def get_channel(self, *, team_id: str, channel_id: str) -> dict[str, Any]:
+ return {"membershipType": self._membership_type}
+
+ async def add_channel_member(
+ self, *, team_id: str, channel_id: str, user_aad_id: str
+ ) -> None:
+ self.channel_members.append({"channel_id": channel_id, "user": user_aad_id})
+
+ async def add_team_member(self, *, team_id: str, user_aad_id: str) -> None:
+ self.team_members.append({"team_id": team_id, "user": user_aad_id})
+
+ async def create_subscription(self, **kwargs: Any) -> dict[str, Any]:
+ return {"id": "SUB-X"}
+
+
+# ── create_channel ───────────────────────────────────────────────────────────
+
+
+def test_create_standard_channel() -> None:
+ adapter = _adapter()
+ fake = _FakeGraph()
+ adapter._graph = fake # type: ignore[assignment]
+
+ channel_id = _run(adapter.create_channel("My Room", "the topic"))
+
+ assert channel_id == "19:[email protected]"
+ assert len(fake.created_channels) == 1
+ created = fake.created_channels[0]
+ assert created["team_id"] == "team-7"
+ assert created["membership_type"] == "standard"
+ # Type + team are recorded so outbound + subscription know how to reach it.
+ assert adapter._channel_type["19:[email protected]"] == "channel_public"
+ assert adapter._team_of_channel["19:[email protected]"] == "team-7"
+
+
+def test_create_private_channel_uses_private_membership() -> None:
+ adapter = _adapter()
+ fake = _FakeGraph()
+ adapter._graph = fake # type: ignore[assignment]
+
+ _run(adapter.create_channel("Secret", "x", channel_type="channel_private"))
+
+ assert fake.created_channels[0]["membership_type"] == "private"
+
+
+def test_create_channel_rejects_group_and_direct() -> None:
+ adapter = _adapter()
+ adapter._graph = _FakeGraph() # type: ignore[assignment]
+
+ for bad in ("group", "direct"):
+ try:
+ _run(adapter.create_channel("x", "y", channel_type=bad)) # type: ignore[arg-type]
+ raised = False
+ except ValueError:
+ raised = True
+ assert raised, bad
+
+
+def test_channel_name_is_sanitized() -> None:
+ assert TeamsAdapter._sanitize_channel_name("bug/fix #42: urgent!") == (
+ "bug-fix -42- urgent!"
+ )
+ assert TeamsAdapter._sanitize_channel_name(" ... ") == "switch"
+ assert len(TeamsAdapter._sanitize_channel_name("x" * 80)) == 50
+
+
+# ── get_channel_type ─────────────────────────────────────────────────────────
+
+
+def test_get_channel_type_uses_cache() -> None:
+ adapter = _adapter()
+ adapter._channel_type["19:[email protected]"] = "channel_private"
+ # No Graph client needed — the learned type wins.
+ assert _run(adapter.get_channel_type("19:[email protected]")) == "channel_private"
+
+
+def test_get_channel_type_falls_back_to_graph() -> None:
+ adapter = _adapter()
+ adapter._graph = _FakeGraph(membership_type="private") # type: ignore[assignment]
+
+ resolved = _run(adapter.get_channel_type("19:[email protected]"))
+
+ assert resolved == "channel_private"
+ # And it is cached for next time.
+ assert adapter._channel_type["19:[email protected]"] == "channel_private"
+
+
+# ── deeplink ─────────────────────────────────────────────────────────────────
+
+
+def test_channel_deeplink_is_built_from_ids() -> None:
+ adapter = _adapter()
+ adapter._team_of_channel["19:[email protected]"] = "team-7"
+
+ link = _run(adapter.channel_deeplink("19:[email protected]"))
+
+ assert link is not None
+ assert "teams.microsoft.com/l/channel/" in link
+ # The channel id is URL-encoded, and team + tenant are query params.
+ assert "19%3Ac%40thread.tacv2" in link
+ assert "groupId=team-7" in link
+ assert "tenantId=tenant-9" in link
+
+
+# ── add_users_to_channel ─────────────────────────────────────────────────────
+
+
+def test_add_users_private_channel_adds_channel_members() -> None:
+ adapter = _adapter()
+ fake = _FakeGraph()
+ adapter._graph = fake # type: ignore[assignment]
+ adapter._channel_type["19:[email protected]"] = "channel_private"
+
+ _run(adapter.add_users_to_channel("19:[email protected]", ["alice"], ["aad-a"]))
+
+ assert fake.channel_members == [
+ {"channel_id": "19:[email protected]", "user": "aad-a"}
+ ]
+ assert fake.team_members == []
+
+
+def test_add_users_standard_channel_adds_team_members() -> None:
+ adapter = _adapter()
+ fake = _FakeGraph()
+ adapter._graph = fake # type: ignore[assignment]
+ adapter._channel_type["19:[email protected]"] = "channel_public"
+
+ _run(adapter.add_users_to_channel("19:[email protected]", ["bob"], ["aad-b"]))
+
+ assert fake.team_members == [{"team_id": "team-7", "user": "aad-b"}]
+ assert fake.channel_members == []
+
+
+class _FailingGraph(_FakeGraph):
+ async def add_team_member(self, *, team_id: str, user_aad_id: str) -> None:
+ if user_aad_id == "aad-bad":
+ raise RuntimeError("Graph rejected the member add")
+ await super().add_team_member(team_id=team_id, user_aad_id=user_aad_id)
+
+
+def test_add_users_raises_on_partial_failure() -> None:
+ # A user that fails to add must surface as an error — the caller cannot be
+ # told the add succeeded when it did not (fail-loud). The good user is still
+ # added; the failure is reported afterwards.
+ adapter = _adapter()
+ fake = _FailingGraph()
+ adapter._graph = fake # type: ignore[assignment]
+ adapter._channel_type["19:[email protected]"] = "channel_public"
+
+ with pytest.raises(RuntimeError, match="aad-bad"):
+ _run(
+ adapter.add_users_to_channel(
+ ["good", "bad"],
+ ["aad-good", "aad-bad"],
+ )
+ )
+
+ # The user that could be added was still added before the error surfaced.
+ assert fake.team_members == [{"team_id": "team-7", "user": "aad-good"}]
diff --git a/core/uv.lock b/core/uv.lock
index 436f2baa1..ac1bff945 100644
--- a/core/uv.lock
+++ b/core/uv.lock
@@ -624,55 +624,55 @@ wheels = [
[[package]]
name = "cryptography"
-version = "48.0.0"
+version = "46.0.7"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cffi", marker = "platform_python_implementation != 'PyPy'" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/9f/a9/db8f313fdcd85d767d4973515e1db101f9c71f95fced83233de224673757/cryptography-48.0.0.tar.gz", hash = "sha256:5c3932f4436d1cccb036cb0eaef46e6e2db91035166f1ad6505c3c9d5a635920", size = 832984, upload-time = "2026-05-04T22:59:38.133Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/df/3d/01f6dd9190170a5a241e0e98c2d04be3664a9e6f5b9b872cde63aff1c3dd/cryptography-48.0.0-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:0c558d2cdffd8f4bbb30fc7134c74d2ca9a476f830bb053074498fbc86f41ed6", size = 8001587, upload-time = "2026-05-04T22:57:36.803Z" },
- { url = "https://files.pythonhosted.org/packages/b2/6e/e90527eef33f309beb811cf7c982c3aeffcce8e3edb178baa4ca3ae4a6fa/cryptography-48.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f5333311663ea94f75dd408665686aaf426563556bb5283554a3539177e03b8c", size = 4690433, upload-time = "2026-05-04T22:57:40.373Z" },
- { url = "https://files.pythonhosted.org/packages/90/04/673510ed51ddff56575f306cf1617d80411ee76831ccd3097599140efdfe/cryptography-48.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7995ef305d7165c3f11ae07f2517e5a4f1d5c18da1376a0a9ed496336b69e5f3", size = 4710620, upload-time = "2026-05-04T22:57:42.935Z" },
- { url = "https://files.pythonhosted.org/packages/14/d5/e9c4ef932c8d800490c34d8bd589d64a31d5890e27ec9e9ad532be893294/cryptography-48.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:40ba1f85eaa6959837b1d51c9767e230e14612eea4ef110ee8854ada22da1bf5", size = 4696283, upload-time = "2026-05-04T22:57:45.294Z" },
- { url = "https://files.pythonhosted.org/packages/0c/29/174b9dfb60b12d59ecfc6cfa04bc88c21b42a54f01b8aae09bb6e51e4c7f/cryptography-48.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:369a6348999f94bbd53435c894377b20ab95f25a9065c283570e70150d8abc3c", size = 5296573, upload-time = "2026-05-04T22:57:47.933Z" },
- { url = "https://files.pythonhosted.org/packages/95/38/0d29a6fd7d0d1373f0c0c88a04ba20e359b257753ac497564cd660fc1d55/cryptography-48.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:a0e692c683f4df67815a2d258b324e66f4738bd7a96a218c826dce4f4bd05d8f", size = 4743677, upload-time = "2026-05-04T22:57:50.067Z" },
- { url = "https://files.pythonhosted.org/packages/30/be/eef653013d5c63b6a490529e0316f9ac14a37602965d4903efed1399f32b/cryptography-48.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:18349bbc56f4743c8b12dc32e2bccb2cf83ee8b69a3bba74ef8ae857e26b3d25", size = 4330808, upload-time = "2026-05-04T22:57:52.301Z" },
- { url = "https://files.pythonhosted.org/packages/84/9e/500463e87abb7a0a0f9f256ec21123ecde0a7b5541a15e840ea54551fd81/cryptography-48.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:7e8eac43dfca5c4cccc6dad9a80504436fca53bb9bc3100a2386d730fbe6b602", size = 4695941, upload-time = "2026-05-04T22:57:54.603Z" },
- { url = "https://files.pythonhosted.org/packages/e3/dc/7303087450c2ec9e7fbb750e17c2abfbc658f23cbd0e54009509b7cc4091/cryptography-48.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:9ccdac7d40688ecb5a3b4a604b8a88c8002e3442d6c60aead1db2a89a041560c", size = 5252579, upload-time = "2026-05-04T22:57:57.207Z" },
- { url = "https://files.pythonhosted.org/packages/d0/c0/7101d3b7215edcdc90c45da544961fd8ed2d6448f77577460fa75a8443f7/cryptography-48.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:bd72e68b06bb1e96913f97dd4901119bc17f39d4586a5adf2d3e47bc2b9d58b5", size = 4743326, upload-time = "2026-05-04T22:57:59.535Z" },
- { url = "https://files.pythonhosted.org/packages/ac/d8/5b833bad13016f562ab9d063d68199a4bd121d18458e439515601d3357ec/cryptography-48.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:59baa2cb386c4f0b9905bd6eb4c2a79a69a128408fd31d32ca4d7102d4156321", size = 4826672, upload-time = "2026-05-04T22:58:01.996Z" },
- { url = "https://files.pythonhosted.org/packages/98/e1/7074eb8bf3c135558c73fc2bcf0f5633f912e6fb87e868a55c454080ef09/cryptography-48.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9249e3cd978541d665967ac2cb2787fd6a62bddf1e75b3e347a594d7dacf4f74", size = 4972574, upload-time = "2026-05-04T22:58:03.968Z" },
- { url = "https://files.pythonhosted.org/packages/04/70/e5a1b41d325f797f39427aa44ef8baf0be500065ab6d8e10369d850d4a4f/cryptography-48.0.0-cp311-abi3-win32.whl", hash = "sha256:9c459db21422be75e2809370b829a87eb37f74cd785fc4aa9ea1e5f43b47cda4", size = 3294868, upload-time = "2026-05-04T22:58:06.467Z" },
- { url = "https://files.pythonhosted.org/packages/f4/ac/8ac51b4a5fc5932eb7ee5c517ba7dc8cd834f0048962b6b352f00f41ebf9/cryptography-48.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:5b012212e08b8dd5edc78ef54da83dd9892fd9105323b3993eff6bea65dc21d7", size = 3817107, upload-time = "2026-05-04T22:58:08.845Z" },
- { url = "https://files.pythonhosted.org/packages/6b/84/70e3feea9feea87fd7cbe77efb2712ae1e3e6edf10749dc6e95f4e60e455/cryptography-48.0.0-cp314-cp314t-macosx_10_9_universal2.whl", hash = "sha256:3cb07a3ed6431663cd321ea8a000a1314c74211f823e4177fefa2255e057d1ec", size = 7986556, upload-time = "2026-05-04T22:58:11.172Z" },
- { url = "https://files.pythonhosted.org/packages/89/6e/18e07a618bb5442ba10cf4df16e99c071365528aa570dfcb8c02e25a303b/cryptography-48.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8c7378637d7d88016fa6791c159f698b3d3eed28ebf844ac36b9dc04a14dae18", size = 4684776, upload-time = "2026-05-04T22:58:13.712Z" },
- { url = "https://files.pythonhosted.org/packages/be/6a/4ea3b4c6c6759794d5ee2103c304a5076dc4b19ae1f9fe47dba439e159e9/cryptography-48.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cc90c0b39b2e3c65ef52c804b72e3c58f8a04ab2a1871272798e5f9572c17d20", size = 4698121, upload-time = "2026-05-04T22:58:16.448Z" },
- { url = "https://files.pythonhosted.org/packages/2f/59/6ff6ad6cae03bb887da2a5860b2c9805f8dac969ef01ce563336c49bd1d1/cryptography-48.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:76341972e1eff8b4bea859f09c0d3e64b96ce931b084f9b9b7db8ef364c30eff", size = 4690042, upload-time = "2026-05-04T22:58:18.544Z" },
- { url = "https://files.pythonhosted.org/packages/ca/b4/fc334ed8cfd705aca282fe4d8f5ae64a8e0f74932e9feecb344610cf6e4d/cryptography-48.0.0-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:55b7718303bf06a5753dcdccf2f3945cf18ad7bffde41b61226e4db31ab89a9c", size = 5282526, upload-time = "2026-05-04T22:58:20.75Z" },
- { url = "https://files.pythonhosted.org/packages/11/08/9f8c5386cc4cd90d8255c7cdd0f5baf459a08502a09de30dc51f553d38dc/cryptography-48.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:a64697c641c7b1b2178e573cbc31c7c6684cd56883a478d75143dbb7118036db", size = 4733116, upload-time = "2026-05-04T22:58:23.627Z" },
- { url = "https://files.pythonhosted.org/packages/b8/77/99307d7574045699f8805aa500fa0fb83422d115b5400a064ddd306d7750/cryptography-48.0.0-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:561215ea3879cb1cbbf272867e2efda62476f240fb58c64de6b393ae19246741", size = 4316030, upload-time = "2026-05-04T22:58:25.581Z" },
- { url = "https://files.pythonhosted.org/packages/fd/36/a608b98337af3cb2aff4818e406649d30572b7031918b04c87d979495348/cryptography-48.0.0-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:ad64688338ed4bc1a6618076ba75fd7194a5f1797ac60b47afe926285adb3166", size = 4689640, upload-time = "2026-05-04T22:58:27.747Z" },
- { url = "https://files.pythonhosted.org/packages/dd/a6/825010a291b4438aecc1f568bc428189fc1175515223632477c07dc0a6df/cryptography-48.0.0-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:906cbf0670286c6e0044156bc7d4af9cbb0ef6db9f73e52c3ec56ba6bdde5336", size = 5237657, upload-time = "2026-05-04T22:58:29.848Z" },
- { url = "https://files.pythonhosted.org/packages/b9/09/4e76a09b4caa29aad535ddc806f5d4c5d01885bd978bd984fbc6ca032cae/cryptography-48.0.0-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:ea8990436d914540a40ab24b6a77c0969695ed52f4a4874c5137ccf7045a7057", size = 4732362, upload-time = "2026-05-04T22:58:32.009Z" },
- { url = "https://files.pythonhosted.org/packages/18/78/444fa04a77d0cb95f417dda20d450e13c56ba8e5220fc892a1658f44f882/cryptography-48.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c18684a7f0cc9a3cb60328f496b8e3372def7c5d2df39ac267878b05565aaaae", size = 4819580, upload-time = "2026-05-04T22:58:34.254Z" },
- { url = "https://files.pythonhosted.org/packages/38/85/ea67067c70a1fd4be2c63d35eeed82658023021affccc7b17705f8527dd2/cryptography-48.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9be5aafa5736574f8f15f262adc81b2a9869e2cfe9014d52a44633905b40d52c", size = 4963283, upload-time = "2026-05-04T22:58:36.376Z" },
- { url = "https://files.pythonhosted.org/packages/75/54/cc6d0f3deac3e81c7f847e8a189a12b6cdd65059b43dad25d4316abd849a/cryptography-48.0.0-cp314-cp314t-win32.whl", hash = "sha256:c17dfe85494deaeddc5ce251aebd1d60bbe6afc8b62071bb0b469431a000124f", size = 3270954, upload-time = "2026-05-04T22:58:38.791Z" },
- { url = "https://files.pythonhosted.org/packages/49/67/cc947e288c0758a4e5473d1dcb743037ab7785541265a969240b8885441a/cryptography-48.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:27241b1dc9962e056062a8eef1991d02c3a24569c95975bd2322a8a52c6e5e12", size = 3797313, upload-time = "2026-05-04T22:58:40.746Z" },
- { url = "https://files.pythonhosted.org/packages/f2/63/61d4a4e1c6b6bab6ce1e213cd36a24c415d90e76d78c5eb8577c5541d2e8/cryptography-48.0.0-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:58d00498e8933e4a194f3076aee1b4a97dfec1a6da444535755822fe5d8b0b86", size = 7983482, upload-time = "2026-05-04T22:58:43.769Z" },
- { url = "https://files.pythonhosted.org/packages/d5/ac/f5b5995b87770c693e2596559ffafe195b4033a57f14a82268a2842953f3/cryptography-48.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:614d0949f4790582d2cc25553abd09dd723025f0c0e7c67376a1d77196743d6e", size = 4683266, upload-time = "2026-05-04T22:58:46.064Z" },
- { url = "https://files.pythonhosted.org/packages/ec/c6/8b14f67e18338fbc4adb76f66c001f5c3610b3e2d1837f268f47a347dbbb/cryptography-48.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7ce4bfae76319a532a2dc68f82cc32f5676ee792a983187dac07183690e5c66f", size = 4696228, upload-time = "2026-05-04T22:58:48.22Z" },
- { url = "https://files.pythonhosted.org/packages/ea/73/f808fbae9514bd91b47875b003f13e284c8c6bdfd904b7944e803937eec1/cryptography-48.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:2eb992bbd4661238c5a397594c83f5b4dc2bc5b848c365c8f991b6780efcc5c7", size = 4689097, upload-time = "2026-05-04T22:58:50.9Z" },
- { url = "https://files.pythonhosted.org/packages/93/01/d86632d7d28db8ae83221995752eeb6639ffb374c2d22955648cf8d52797/cryptography-48.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:22a5cb272895dce158b2cacdfdc3debd299019659f42947dbdac6f32d68fe832", size = 5283582, upload-time = "2026-05-04T22:58:53.017Z" },
- { url = "https://files.pythonhosted.org/packages/02/e1/50edc7a50334807cc4791fc4a0ce7468b4a1416d9138eab358bfc9a3d70b/cryptography-48.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:2b4d59804e8408e2fea7d1fbaf218e5ec984325221db76e6a241a9abd6cdd95c", size = 4730479, upload-time = "2026-05-04T22:58:55.611Z" },
- { url = "https://files.pythonhosted.org/packages/6f/af/99a582b1b1641ff5911ac559beb45097cf79efd4ead4657f578ef1af2d47/cryptography-48.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:984a20b0f62a26f48a3396c72e4bc34c66e356d356bf370053066b3b6d54634a", size = 4326481, upload-time = "2026-05-04T22:58:57.607Z" },
- { url = "https://files.pythonhosted.org/packages/90/ee/89aa26a06ef0a7d7611788ffd571a7c50e368cc6a4d5eef8b4884e866edb/cryptography-48.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:5a5ed8fde7a1d09376ca0b40e68cd59c69fe23b1f9768bd5824f54681626032a", size = 4688713, upload-time = "2026-05-04T22:59:00.077Z" },
- { url = "https://files.pythonhosted.org/packages/70/ba/bcb1b0bb7a33d4c7c0c4d4c7874b4a62ae4f56113a5f4baefa362dfb1f0f/cryptography-48.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:8cd666227ef7af430aa5914a9910e0ddd703e75f039cef0825cd0da71b6b711a", size = 5238165, upload-time = "2026-05-04T22:59:02.317Z" },
- { url = "https://files.pythonhosted.org/packages/c9/70/ca4003b1ce5ca3dc3186ada51908c8a9b9ff7d5cab83cc0d43ee14ec144f/cryptography-48.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9071196d81abc88b3516ac8cdfad32e2b66dd4a5393a8e68a961e9161ddc6239", size = 4729947, upload-time = "2026-05-04T22:59:05.255Z" },
- { url = "https://files.pythonhosted.org/packages/44/a0/4ec7cf774207905aef1a8d11c3750d5a1db805eb380ee4e16df317870128/cryptography-48.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1e2d54c8be6152856a36f0882ab231e70f8ec7f14e93cf87db8a2ed056bf160c", size = 4822059, upload-time = "2026-05-04T22:59:07.802Z" },
- { url = "https://files.pythonhosted.org/packages/1e/75/a2e55f99c16fcac7b5d6c1eb19ad8e00799854d6be5ca845f9259eae1681/cryptography-48.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:a5da777e32ffed6f85a7b2b3f7c5cbc88c146bfcd0a1d7baf5fcc6c52ee35dd4", size = 4960575, upload-time = "2026-05-04T22:59:09.851Z" },
- { url = "https://files.pythonhosted.org/packages/b8/23/6e6f32143ab5d8b36ca848a502c4bcd477ae75b9e1677e3530d669062578/cryptography-48.0.0-cp39-abi3-win32.whl", hash = "sha256:77a2ccbbe917f6710e05ba9adaa25fb5075620bf3ea6fb751997875aff4ae4bd", size = 3279117, upload-time = "2026-05-04T22:59:12.019Z" },
- { url = "https://files.pythonhosted.org/packages/9d/9a/0fea98a70cf1749d41d738836f6349d97945f7c89433a259a6c2642eefeb/cryptography-48.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:16cd65b9330583e4619939b3a3843eec1e6e789744bb01e7c7e2e62e33c239c8", size = 3792100, upload-time = "2026-05-04T22:59:14.884Z" },
+sdist = { url = "https://files.pythonhosted.org/packages/47/93/ac8f3d5ff04d54bc814e961a43ae5b0b146154c89c61b47bb07557679b18/cryptography-46.0.7.tar.gz", hash = "sha256:e4cfd68c5f3e0bfdad0d38e023239b96a2fe84146481852dffbcca442c245aa5", size = 750652, upload-time = "2026-04-08T01:57:54.692Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0b/5d/4a8f770695d73be252331e60e526291e3df0c9b27556a90a6b47bccca4c2/cryptography-46.0.7-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:ea42cbe97209df307fdc3b155f1b6fa2577c0defa8f1f7d3be7d31d189108ad4", size = 7179869, upload-time = "2026-04-08T01:56:17.157Z" },
+ { url = "https://files.pythonhosted.org/packages/5f/45/6d80dc379b0bbc1f9d1e429f42e4cb9e1d319c7a8201beffd967c516ea01/cryptography-46.0.7-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b36a4695e29fe69215d75960b22577197aca3f7a25b9cf9d165dcfe9d80bc325", size = 4275492, upload-time = "2026-04-08T01:56:19.36Z" },
+ { url = "https://files.pythonhosted.org/packages/4a/9a/1765afe9f572e239c3469f2cb429f3ba7b31878c893b246b4b2994ffe2fe/cryptography-46.0.7-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5ad9ef796328c5e3c4ceed237a183f5d41d21150f972455a9d926593a1dcb308", size = 4426670, upload-time = "2026-04-08T01:56:21.415Z" },
+ { url = "https://files.pythonhosted.org/packages/8f/3e/af9246aaf23cd4ee060699adab1e47ced3f5f7e7a8ffdd339f817b446462/cryptography-46.0.7-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:73510b83623e080a2c35c62c15298096e2a5dc8d51c3b4e1740211839d0dea77", size = 4280275, upload-time = "2026-04-08T01:56:23.539Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/54/6bbbfc5efe86f9d71041827b793c24811a017c6ac0fd12883e4caa86b8ed/cryptography-46.0.7-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:cbd5fb06b62bd0721e1170273d3f4d5a277044c47ca27ee257025146c34cbdd1", size = 4928402, upload-time = "2026-04-08T01:56:25.624Z" },
+ { url = "https://files.pythonhosted.org/packages/2d/cf/054b9d8220f81509939599c8bdbc0c408dbd2bdd41688616a20731371fe0/cryptography-46.0.7-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:420b1e4109cc95f0e5700eed79908cef9268265c773d3a66f7af1eef53d409ef", size = 4459985, upload-time = "2026-04-08T01:56:27.309Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/46/4e4e9c6040fb01c7467d47217d2f882daddeb8828f7df800cb806d8a2288/cryptography-46.0.7-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:24402210aa54baae71d99441d15bb5a1919c195398a87b563df84468160a65de", size = 3990652, upload-time = "2026-04-08T01:56:29.095Z" },
+ { url = "https://files.pythonhosted.org/packages/36/5f/313586c3be5a2fbe87e4c9a254207b860155a8e1f3cca99f9910008e7d08/cryptography-46.0.7-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:8a469028a86f12eb7d2fe97162d0634026d92a21f3ae0ac87ed1c4a447886c83", size = 4279805, upload-time = "2026-04-08T01:56:30.928Z" },
+ { url = "https://files.pythonhosted.org/packages/69/33/60dfc4595f334a2082749673386a4d05e4f0cf4df8248e63b2c3437585f2/cryptography-46.0.7-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:9694078c5d44c157ef3162e3bf3946510b857df5a3955458381d1c7cfc143ddb", size = 4892883, upload-time = "2026-04-08T01:56:32.614Z" },
+ { url = "https://files.pythonhosted.org/packages/c7/0b/333ddab4270c4f5b972f980adef4faa66951a4aaf646ca067af597f15563/cryptography-46.0.7-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:42a1e5f98abb6391717978baf9f90dc28a743b7d9be7f0751a6f56a75d14065b", size = 4459756, upload-time = "2026-04-08T01:56:34.306Z" },
+ { url = "https://files.pythonhosted.org/packages/d2/14/633913398b43b75f1234834170947957c6b623d1701ffc7a9600da907e89/cryptography-46.0.7-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:91bbcb08347344f810cbe49065914fe048949648f6bd5c2519f34619142bbe85", size = 4410244, upload-time = "2026-04-08T01:56:35.977Z" },
+ { url = "https://files.pythonhosted.org/packages/10/f2/19ceb3b3dc14009373432af0c13f46aa08e3ce334ec6eff13492e1812ccd/cryptography-46.0.7-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:5d1c02a14ceb9148cc7816249f64f623fbfee39e8c03b3650d842ad3f34d637e", size = 4674868, upload-time = "2026-04-08T01:56:38.034Z" },
+ { url = "https://files.pythonhosted.org/packages/1a/bb/a5c213c19ee94b15dfccc48f363738633a493812687f5567addbcbba9f6f/cryptography-46.0.7-cp311-abi3-win32.whl", hash = "sha256:d23c8ca48e44ee015cd0a54aeccdf9f09004eba9fc96f38c911011d9ff1bd457", size = 3026504, upload-time = "2026-04-08T01:56:39.666Z" },
+ { url = "https://files.pythonhosted.org/packages/2b/02/7788f9fefa1d060ca68717c3901ae7fffa21ee087a90b7f23c7a603c32ae/cryptography-46.0.7-cp311-abi3-win_amd64.whl", hash = "sha256:397655da831414d165029da9bc483bed2fe0e75dde6a1523ec2fe63f3c46046b", size = 3488363, upload-time = "2026-04-08T01:56:41.893Z" },
+ { url = "https://files.pythonhosted.org/packages/7b/56/15619b210e689c5403bb0540e4cb7dbf11a6bf42e483b7644e471a2812b3/cryptography-46.0.7-cp314-cp314t-macosx_10_9_universal2.whl", hash = "sha256:d151173275e1728cf7839aaa80c34fe550c04ddb27b34f48c232193df8db5842", size = 7119671, upload-time = "2026-04-08T01:56:44Z" },
+ { url = "https://files.pythonhosted.org/packages/74/66/e3ce040721b0b5599e175ba91ab08884c75928fbeb74597dd10ef13505d2/cryptography-46.0.7-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:db0f493b9181c7820c8134437eb8b0b4792085d37dbb24da050476ccb664e59c", size = 4268551, upload-time = "2026-04-08T01:56:46.071Z" },
+ { url = "https://files.pythonhosted.org/packages/03/11/5e395f961d6868269835dee1bafec6a1ac176505a167f68b7d8818431068/cryptography-46.0.7-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ebd6daf519b9f189f85c479427bbd6e9c9037862cf8fe89ee35503bd209ed902", size = 4408887, upload-time = "2026-04-08T01:56:47.718Z" },
+ { url = "https://files.pythonhosted.org/packages/40/53/8ed1cf4c3b9c8e611e7122fb56f1c32d09e1fff0f1d77e78d9ff7c82653e/cryptography-46.0.7-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:b7b412817be92117ec5ed95f880defe9cf18a832e8cafacf0a22337dc1981b4d", size = 4271354, upload-time = "2026-04-08T01:56:49.312Z" },
+ { url = "https://files.pythonhosted.org/packages/50/46/cf71e26025c2e767c5609162c866a78e8a2915bbcfa408b7ca495c6140c4/cryptography-46.0.7-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:fbfd0e5f273877695cb93baf14b185f4878128b250cc9f8e617ea0c025dfb022", size = 4905845, upload-time = "2026-04-08T01:56:50.916Z" },
+ { url = "https://files.pythonhosted.org/packages/c0/ea/01276740375bac6249d0a971ebdf6b4dc9ead0ee0a34ef3b5a88c1a9b0d4/cryptography-46.0.7-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:ffca7aa1d00cf7d6469b988c581598f2259e46215e0140af408966a24cf086ce", size = 4444641, upload-time = "2026-04-08T01:56:52.882Z" },
+ { url = "https://files.pythonhosted.org/packages/3d/4c/7d258f169ae71230f25d9f3d06caabcff8c3baf0978e2b7d65e0acac3827/cryptography-46.0.7-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:60627cf07e0d9274338521205899337c5d18249db56865f943cbe753aa96f40f", size = 3967749, upload-time = "2026-04-08T01:56:54.597Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/2a/2ea0767cad19e71b3530e4cad9605d0b5e338b6a1e72c37c9c1ceb86c333/cryptography-46.0.7-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:80406c3065e2c55d7f49a9550fe0c49b3f12e5bfff5dedb727e319e1afb9bf99", size = 4270942, upload-time = "2026-04-08T01:56:56.416Z" },
+ { url = "https://files.pythonhosted.org/packages/41/3d/fe14df95a83319af25717677e956567a105bb6ab25641acaa093db79975d/cryptography-46.0.7-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:c5b1ccd1239f48b7151a65bc6dd54bcfcc15e028c8ac126d3fada09db0e07ef1", size = 4871079, upload-time = "2026-04-08T01:56:58.31Z" },
+ { url = "https://files.pythonhosted.org/packages/9c/59/4a479e0f36f8f378d397f4eab4c850b4ffb79a2f0d58704b8fa0703ddc11/cryptography-46.0.7-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:d5f7520159cd9c2154eb61eb67548ca05c5774d39e9c2c4339fd793fe7d097b2", size = 4443999, upload-time = "2026-04-08T01:57:00.508Z" },
+ { url = "https://files.pythonhosted.org/packages/28/17/b59a741645822ec6d04732b43c5d35e4ef58be7bfa84a81e5ae6f05a1d33/cryptography-46.0.7-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fcd8eac50d9138c1d7fc53a653ba60a2bee81a505f9f8850b6b2888555a45d0e", size = 4399191, upload-time = "2026-04-08T01:57:02.654Z" },
+ { url = "https://files.pythonhosted.org/packages/59/6a/bb2e166d6d0e0955f1e9ff70f10ec4b2824c9cfcdb4da772c7dd69cc7d80/cryptography-46.0.7-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:65814c60f8cc400c63131584e3e1fad01235edba2614b61fbfbfa954082db0ee", size = 4655782, upload-time = "2026-04-08T01:57:04.592Z" },
+ { url = "https://files.pythonhosted.org/packages/95/b6/3da51d48415bcb63b00dc17c2eff3a651b7c4fed484308d0f19b30e8cb2c/cryptography-46.0.7-cp314-cp314t-win32.whl", hash = "sha256:fdd1736fed309b4300346f88f74cd120c27c56852c3838cab416e7a166f67298", size = 3002227, upload-time = "2026-04-08T01:57:06.91Z" },
+ { url = "https://files.pythonhosted.org/packages/32/a8/9f0e4ed57ec9cebe506e58db11ae472972ecb0c659e4d52bbaee80ca340a/cryptography-46.0.7-cp314-cp314t-win_amd64.whl", hash = "sha256:e06acf3c99be55aa3b516397fe42f5855597f430add9c17fa46bf2e0fb34c9bb", size = 3475332, upload-time = "2026-04-08T01:57:08.807Z" },
+ { url = "https://files.pythonhosted.org/packages/a7/7f/cd42fc3614386bc0c12f0cb3c4ae1fc2bbca5c9662dfed031514911d513d/cryptography-46.0.7-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:462ad5cb1c148a22b2e3bcc5ad52504dff325d17daf5df8d88c17dda1f75f2a4", size = 7165618, upload-time = "2026-04-08T01:57:10.645Z" },
+ { url = "https://files.pythonhosted.org/packages/a5/d0/36a49f0262d2319139d2829f773f1b97ef8aef7f97e6e5bd21455e5a8fb5/cryptography-46.0.7-cp38-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:84d4cced91f0f159a7ddacad249cc077e63195c36aac40b4150e7a57e84fffe7", size = 4270628, upload-time = "2026-04-08T01:57:12.885Z" },
+ { url = "https://files.pythonhosted.org/packages/8a/6c/1a42450f464dda6ffbe578a911f773e54dd48c10f9895a23a7e88b3e7db5/cryptography-46.0.7-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:128c5edfe5e5938b86b03941e94fac9ee793a94452ad1365c9fc3f4f62216832", size = 4415405, upload-time = "2026-04-08T01:57:14.923Z" },
+ { url = "https://files.pythonhosted.org/packages/9a/92/4ed714dbe93a066dc1f4b4581a464d2d7dbec9046f7c8b7016f5286329e2/cryptography-46.0.7-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:5e51be372b26ef4ba3de3c167cd3d1022934bc838ae9eaad7e644986d2a3d163", size = 4272715, upload-time = "2026-04-08T01:57:16.638Z" },
+ { url = "https://files.pythonhosted.org/packages/b7/e6/a26b84096eddd51494bba19111f8fffe976f6a09f132706f8f1bf03f51f7/cryptography-46.0.7-cp38-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:cdf1a610ef82abb396451862739e3fc93b071c844399e15b90726ef7470eeaf2", size = 4918400, upload-time = "2026-04-08T01:57:19.021Z" },
+ { url = "https://files.pythonhosted.org/packages/c7/08/ffd537b605568a148543ac3c2b239708ae0bd635064bab41359252ef88ed/cryptography-46.0.7-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:1d25aee46d0c6f1a501adcddb2d2fee4b979381346a78558ed13e50aa8a59067", size = 4450634, upload-time = "2026-04-08T01:57:21.185Z" },
+ { url = "https://files.pythonhosted.org/packages/16/01/0cd51dd86ab5b9befe0d031e276510491976c3a80e9f6e31810cce46c4ad/cryptography-46.0.7-cp38-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:cdfbe22376065ffcf8be74dc9a909f032df19bc58a699456a21712d6e5eabfd0", size = 3985233, upload-time = "2026-04-08T01:57:22.862Z" },
+ { url = "https://files.pythonhosted.org/packages/92/49/819d6ed3a7d9349c2939f81b500a738cb733ab62fbecdbc1e38e83d45e12/cryptography-46.0.7-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:abad9dac36cbf55de6eb49badd4016806b3165d396f64925bf2999bcb67837ba", size = 4271955, upload-time = "2026-04-08T01:57:24.814Z" },
+ { url = "https://files.pythonhosted.org/packages/80/07/ad9b3c56ebb95ed2473d46df0847357e01583f4c52a85754d1a55e29e4d0/cryptography-46.0.7-cp38-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:935ce7e3cfdb53e3536119a542b839bb94ec1ad081013e9ab9b7cfd478b05006", size = 4879888, upload-time = "2026-04-08T01:57:26.88Z" },
+ { url = "https://files.pythonhosted.org/packages/b8/c7/201d3d58f30c4c2bdbe9b03844c291feb77c20511cc3586daf7edc12a47b/cryptography-46.0.7-cp38-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:35719dc79d4730d30f1c2b6474bd6acda36ae2dfae1e3c16f2051f215df33ce0", size = 4449961, upload-time = "2026-04-08T01:57:29.068Z" },
+ { url = "https://files.pythonhosted.org/packages/a5/ef/649750cbf96f3033c3c976e112265c33906f8e462291a33d77f90356548c/cryptography-46.0.7-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7bbc6ccf49d05ac8f7d7b5e2e2c33830d4fe2061def88210a126d130d7f71a85", size = 4401696, upload-time = "2026-04-08T01:57:31.029Z" },
+ { url = "https://files.pythonhosted.org/packages/41/52/a8908dcb1a389a459a29008c29966c1d552588d4ae6d43f3a1a4512e0ebe/cryptography-46.0.7-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:a1529d614f44b863a7b480c6d000fe93b59acee9c82ffa027cfadc77521a9f5e", size = 4664256, upload-time = "2026-04-08T01:57:33.144Z" },
+ { url = "https://files.pythonhosted.org/packages/4b/fa/f0ab06238e899cc3fb332623f337a7364f36f4bb3f2534c2bb95a35b132c/cryptography-46.0.7-cp38-abi3-win32.whl", hash = "sha256:f247c8c1a1fb45e12586afbb436ef21ff1e80670b2861a90353d9b025583d246", size = 3013001, upload-time = "2026-04-08T01:57:34.933Z" },
+ { url = "https://files.pythonhosted.org/packages/d2/f1/00ce3bde3ca542d1acd8f8cfa38e446840945aa6363f9b74746394b14127/cryptography-46.0.7-cp38-abi3-win_amd64.whl", hash = "sha256:506c4ff91eff4f82bdac7633318a526b1d1309fc07ca76a3ad182cb5b686d6d3", size = 3472985, upload-time = "2026-04-08T01:57:36.714Z" },
]
[[package]]
@@ -2433,13 +2433,15 @@ wheels = [
[[package]]
name = "switch-core"
-version = "0.2.1"
+version = "0.6.0"
source = { editable = "." }
dependencies = [
+ { name = "aiohttp" },
{ name = "alembic" },
{ name = "asyncpg" },
{ name = "authlib" },
{ name = "bcrypt" },
+ { name = "cryptography" },
{ name = "discord-py" },
{ name = "fastapi" },
{ name = "fastmcp" },
@@ -2469,10 +2471,12 @@ dev = [
[package.metadata]
requires-dist = [
+ { name = "aiohttp", specifier = ">=3.10,<4" },
{ name = "alembic", specifier = ">=1.15,<2" },
{ name = "asyncpg", specifier = ">=0.29,<1" },
{ name = "authlib", specifier = ">=1.3,<2" },
{ name = "bcrypt", specifier = ">=4.0,<5" },
+ { name = "cryptography", specifier = ">=43,<47" },
{ name = "discord-py", specifier = ">=2.4,<3" },
{ name = "fastapi", specifier = ">=0.115,<1" },
{ name = "fastmcp", specifier = ">=3.2.0,<4" },