adapter.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. """Microsoft Teams adapter: microsoft-teams-apps SDK for auth/activity processing, an aiohttp
  2. webhook server for inbound, ``App.send()`` for proactive sends.
  3. Requires the ``teams`` extra (auto-installed by the gateway on first start, or
  4. ``<hermes-venv>/bin/pip install microsoft-teams-apps aiohttp``) and credentials via env
  5. (TEAMS_CLIENT_ID / TEAMS_CLIENT_SECRET / TEAMS_TENANT_ID, optional TEAMS_PORT) or
  6. ``platforms.teams.extra`` in config.yaml (``client_id`` / ``client_secret`` / ``tenant_id`` / ``port``).
  7. """
  8. from __future__ import annotations
  9. import asyncio
  10. # microsoft-teams-apps calls ``load_dotenv(find_dotenv(usecwd=True))`` at ``microsoft_teams.apps.app``
  11. # import time. Importing it during plugin discovery / ``TeamsSummaryWriter`` imports would pollute process
  12. # ``os.environ`` from a cwd-discovered ``.env`` (#62935). Detect presence via find_spec only; bind symbols
  13. # in ``check_teams_requirements()`` behind a dotenv no-op.
  14. import importlib.util
  15. import json
  16. import logging
  17. import re
  18. import sys
  19. import uuid
  20. from collections import deque
  21. from contextlib import contextmanager, suppress
  22. from pathlib import Path
  23. from typing import Any, Dict, Iterator, Optional
  24. from urllib.parse import urlparse
  25. try:
  26. from aiohttp import web
  27. AIOHTTP_AVAILABLE = True
  28. except ImportError:
  29. AIOHTTP_AVAILABLE = False
  30. web = None # type: ignore[assignment]
  31. def _probe_teams_sdk_available() -> bool:
  32. """True when ``microsoft_teams.apps`` is on sys.path, without importing it: the SDK loads a cwd
  33. ``.env`` at import, so ``check_teams_requirements()`` binds symbols behind a dotenv no-op.
  34. Sibling packages share the namespace, so probe the parent first — ``find_spec`` of the child
  35. raises on 3.11+ if the parent is absent."""
  36. try:
  37. find_spec = importlib.util.find_spec
  38. return find_spec("microsoft_teams") is not None and find_spec("microsoft_teams.apps") is not None
  39. except (ValueError, ModuleNotFoundError, ImportError):
  40. return "microsoft_teams.apps" in sys.modules # test stubs may lack ``__spec__``
  41. TEAMS_SDK_AVAILABLE = _probe_teams_sdk_available()
  42. # SDK symbols stay None until check_teams_requirements() binds them (via _SDK_IMPORTS below).
  43. ClientOptions = App = ActivityContext = MessageActivity = ConversationReference = None # type: ignore[assignment,misc]
  44. TypingActivityInput = AdaptiveCardInvokeActivity = AdaptiveCardActionCardResponse = None # type: ignore[assignment,misc]
  45. AdaptiveCardActionMessageResponse = AdaptiveCardInvokeResponse = InvokeResponse = None # type: ignore[assignment,misc]
  46. HttpRequest = HttpResponse = HttpRouteHandler = AdaptiveCard = ExecuteAction = TextBlock = None # type: ignore[assignment,misc]
  47. HttpMethod = str # type: ignore[assignment,misc]
  48. from gateway.config import Platform, PlatformConfig
  49. from gateway.platforms.helpers import MessageDeduplicator
  50. from gateway.platforms.base import (
  51. gateway_trust_env, BasePlatformAdapter, ExecApprovalPrompt, SendResult, cache_image_from_url, cache_media_bytes_async,
  52. )
  53. from gateway.platforms.base_exec_approval import approval_timeout_seconds, format_approval_deadline_line
  54. from agent.i18n import t
  55. from gateway.platforms.event import MessageEvent, MessageType
  56. from gateway.platforms._shared import (
  57. coerce_port, extra_or_secret as _extra_or_secret, get_scoped_secret as _get_scoped_secret,
  58. seed_extra_from_env as _seed_extra_from_env, send_error
  59. )
  60. logger = logging.getLogger(__name__)
  61. _DEFAULT_PORT = 3978
  62. _MAX_BODY_BYTES = 1_048_576 # Bot Framework activities are JSON well under 1 MiB
  63. # ``None`` host → aiohttp binds IPv4 + IPv6 ("0.0.0.0" was unreachable on IPv6-only
  64. # networks such as Fly.io 6PN). Pin via TEAMS_HOST or extra.host.
  65. _DEFAULT_HOST = None
  66. _WEBHOOK_PATH = "/api/messages"
  67. # Regional/government tenants override via ``TEAMS_SERVICE_URL`` / ``extra['service_url']``.
  68. _DEFAULT_TEAMS_SERVICE_URL = "https://smba.trafficmanager.net/teams/"
  69. # Hosts that may receive a freshly minted bearer token (blocks SSRF / token exfiltration via a
  70. # tampered env var). Exact match only: any Azure customer can register ``<name>.trafficmanager.net``.
  71. _ALLOWED_TEAMS_SERVICE_HOSTS = frozenset({"smba.trafficmanager.net", "smba.infra.gov.teams.microsoft.us"})
  72. # Conservative conversation-ID charset (``thread.skype`` / ``thread.tacv2`` suffixes included) so a
  73. # hostile value cannot path-traverse out of ``/v3/conversations/<id>/activities``.
  74. _TEAMS_CONV_ID_RE = re.compile(r"^[A-Za-z0-9:@\-_.]+$")
  75. _BF_TOKEN_SCOPE = "https://api.botframework.com/.default"
  76. def _bf_token_request(tenant_id: str, client_id: str, client_secret: str) -> tuple[str, dict]:
  77. """(token URL, client-credentials form) for a Bot Framework bearer token."""
  78. return (
  79. f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token",
  80. {"grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret, "scope": _BF_TOKEN_SCOPE},
  81. )
  82. def _is_allowed_https_host(url: str, *, check_port: bool = False) -> bool:
  83. """https + host in ``_ALLOWED_TEAMS_SERVICE_HOSTS`` (+ default port when asked)."""
  84. try:
  85. parsed = urlparse(url)
  86. if parsed.scheme != "https" or (check_port and parsed.port not in (None, 443)):
  87. return False
  88. return parsed.hostname in _ALLOWED_TEAMS_SERVICE_HOSTS
  89. except Exception:
  90. return False
  91. def _is_botframework_attachment_url(url: str) -> bool:
  92. """True if ``url`` is a Bot Framework connector attachment host (may carry the bot token)."""
  93. return _is_allowed_https_host(url, check_port=True)
  94. def _validate_teams_service_url(raw: str) -> Optional[str]:
  95. """Normalized (trailing-slash) service URL, or ``None`` if not on the allowlist."""
  96. if not raw or not _is_allowed_https_host(raw):
  97. return None
  98. return raw if raw.endswith("/") else raw + "/"
  99. class _AiohttpBridgeAdapter:
  100. """HttpServerAdapter bridging SDK route registrations into our aiohttp app; without it
  101. ``App()`` unconditionally imports fastapi/uvicorn and allocates a ``FastAPI()``."""
  102. def __init__(self, aiohttp_app: web.Application):
  103. self._aiohttp_app = aiohttp_app
  104. def register_route(self, method: HttpMethod, path: str, handler: HttpRouteHandler) -> None:
  105. async def _aiohttp_handler(request: web.Request) -> web.Response:
  106. result: HttpResponse = await handler(HttpRequest(body=await request.json(), headers=dict(request.headers)))
  107. status = result.get("status", 200)
  108. resp_body = result.get("body")
  109. if resp_body is not None:
  110. return web.Response(status=status, body=json.dumps(resp_body), content_type="application/json")
  111. return web.Response(status=status)
  112. self._aiohttp_app.router.add_route(method, path, _aiohttp_handler)
  113. def serve_static(self, path: str, directory: str) -> None:
  114. pass
  115. async def start(self, port: int) -> None:
  116. raise NotImplementedError("aiohttp server is managed by the adapter")
  117. async def stop(self) -> None:
  118. pass
  119. def check_requirements() -> bool:
  120. """PASSIVE probe (registry ``check_fn``): SDK + aiohttp importable? Never installs."""
  121. return TEAMS_SDK_AVAILABLE and AIOHTTP_AVAILABLE
  122. def _credentials(config) -> tuple[str, str, str]:
  123. """(client_id, client_secret, tenant_id): ``config.extra`` first, then the profile-scoped env.
  124. client_id/tenant_id are read through the same scoped reader as the secret: under multiplex,
  125. ``os.environ`` holds the DEFAULT profile's app identity, and pairing it with a secondary's
  126. secret requests a Bot Framework token for the wrong app. ``extra`` wins so a per-profile
  127. config.yaml identity is never overridden by the process env.
  128. """
  129. extra = getattr(config, "extra", {}) or {}
  130. return (
  131. extra.get("client_id") or _get_scoped_secret("TEAMS_CLIENT_ID", ""),
  132. extra.get("client_secret") or _get_scoped_secret("TEAMS_CLIENT_SECRET", ""),
  133. extra.get("tenant_id") or _get_scoped_secret("TEAMS_TENANT_ID", ""))
  134. def validate_config(config) -> bool:
  135. return bool(all(_credentials(config)))
  136. def is_connected(config) -> bool:
  137. return validate_config(config)
  138. def _env_enablement() -> dict | None:
  139. """``env_enablement_fn``: seed ``PlatformConfig.extra`` from the profile's env before adapter construction
  140. so ``gateway status`` reflects env-only setups without the SDK; ``None`` when not minimally configured.
  141. Every identity/endpoint is per-profile (the app the secret belongs to, its regional service URL, the
  142. cron home conversation), so a secondary is never seeded with the default profile's Teams app."""
  143. seed = _seed_extra_from_env((
  144. ("TEAMS_CLIENT_ID", "client_id", None), ("TEAMS_CLIENT_SECRET", "client_secret", None),
  145. ("TEAMS_TENANT_ID", "tenant_id", None), ("TEAMS_PORT", "port", int), ("TEAMS_SERVICE_URL", "service_url", None),
  146. ), home_env="TEAMS_HOME_CHANNEL")
  147. if not all(seed.get(k) for k in ("client_id", "client_secret", "tenant_id")):
  148. return None
  149. return seed
  150. async def _standalone_send(
  151. pconfig, chat_id: str, message: str, *,
  152. thread_id: Optional[str] = None, media_files: Optional[list] = None, force_document: bool = False,
  153. ) -> dict[str, Any]:
  154. """Acquire a Bot Framework bearer token and POST a single message activity; used by
  155. ``send_message_tool._send_via_adapter`` when the gateway runner is not in this process
  156. (``hermes cron``). ``TEAMS_SERVICE_URL`` is allowlisted and ``chat_id`` charset-checked
  157. (SSRF/path traversal). ``media_files`` / ``force_document`` are signature parity only — text-only."""
  158. extra = getattr(pconfig, "extra", {}) or {}
  159. client_id, client_secret, tenant_id = _credentials(pconfig)
  160. if not (client_id and client_secret and tenant_id):
  161. return send_error("Teams standalone send: TEAMS_CLIENT_ID, TEAMS_CLIENT_SECRET, and TEAMS_TENANT_ID are all required")
  162. raw_service_url = extra.get("service_url") or _get_scoped_secret("TEAMS_SERVICE_URL", "") or _DEFAULT_TEAMS_SERVICE_URL
  163. service_url = _validate_teams_service_url(raw_service_url)
  164. for failed, error in (
  165. (service_url is None, f"TEAMS_SERVICE_URL host is not on the Bot Framework allowlist; "
  166. f"expected one of {sorted(_ALLOWED_TEAMS_SERVICE_HOSTS)}"),
  167. (not chat_id, "chat_id (conversation ID) is required"),
  168. (not _TEAMS_CONV_ID_RE.match(chat_id or ""), "chat_id contains characters outside the Bot Framework conversation ID set"),
  169. (not _TEAMS_CONV_ID_RE.match(tenant_id), "TEAMS_TENANT_ID contains characters outside the expected set"),
  170. (not AIOHTTP_AVAILABLE, "aiohttp not installed")):
  171. if failed:
  172. return send_error(f"Teams standalone send: {error}")
  173. token_url, token_form = _bf_token_request(tenant_id, client_id, client_secret)
  174. activities_url = f"{service_url}v3/conversations/{chat_id}/activities"
  175. try:
  176. import aiohttp as _aiohttp
  177. # Per-request timeouts so a slow STS endpoint cannot starve the activity POST.
  178. per_request_timeout = _aiohttp.ClientTimeout(total=15.0)
  179. async with _aiohttp.ClientSession(trust_env=gateway_trust_env()) as session:
  180. async with session.post(
  181. token_url, data=token_form, headers={"Content-Type": "application/x-www-form-urlencoded"},
  182. timeout=per_request_timeout,
  183. ) as token_resp:
  184. if token_resp.status >= 400:
  185. body = await token_resp.text()
  186. return send_error(f"Teams standalone send: token request failed ({token_resp.status}): {body[:300]}")
  187. token_payload = await token_resp.json()
  188. access_token = token_payload.get("access_token")
  189. if not access_token:
  190. return send_error("Teams standalone send: token response missing access_token")
  191. async with session.post(
  192. activities_url, json={"type": "message", "text": message, "textFormat": "markdown"},
  193. headers={"Authorization": f"Bearer {access_token}", "Content-Type": "application/json"},
  194. timeout=per_request_timeout,
  195. ) as send_resp:
  196. if send_resp.status >= 400:
  197. body = await send_resp.text()
  198. return send_error(f"Teams standalone send: activity post failed ({send_resp.status}): {body[:300]}")
  199. send_payload = await send_resp.json()
  200. return {"success": True, "message_id": send_payload.get("id")}
  201. except asyncio.CancelledError:
  202. raise
  203. except Exception as e:
  204. logger.debug("Teams standalone send raised", exc_info=True)
  205. return send_error(f"Teams standalone send failed: {e}")
  206. # SDK module → names rebound into this module's globals by check_teams_requirements().
  207. _SDK_IMPORTS = {
  208. "microsoft_teams.apps": ("App", "ActivityContext"),
  209. "microsoft_teams.common.http.client": ("ClientOptions",),
  210. "microsoft_teams.api": ("MessageActivity", "ConversationReference"),
  211. "microsoft_teams.api.activities.typing": ("TypingActivityInput",),
  212. "microsoft_teams.api.activities.invoke.adaptive_card": ("AdaptiveCardInvokeActivity",),
  213. "microsoft_teams.api.models.adaptive_card": ("AdaptiveCardActionCardResponse", "AdaptiveCardActionMessageResponse"),
  214. "microsoft_teams.api.models.invoke_response": ("InvokeResponse", "AdaptiveCardInvokeResponse"),
  215. "microsoft_teams.apps.http.adapter": ("HttpMethod", "HttpRequest", "HttpResponse", "HttpRouteHandler"),
  216. "microsoft_teams.cards": ("AdaptiveCard", "ExecuteAction", "TextBlock")}
  217. # NOTE: ``check_requirements`` is the
  218. # PASSIVE probe (registry ``check_fn``, status / unit tests) — it must never trigger a pip install.
  219. # ``check_teams_requirements`` is the ACTIVE lazy-installer, registered as ``ensure_deps_fn``: the
  220. # registry's ``create_adapter()`` runs it when the passive probe fails, right before the gateway connects
  221. # Teams (#79812). ``connect()`` re-checks defensively.
  222. @contextmanager
  223. def _suppress_third_party_dotenv() -> Iterator[None]:
  224. """No-op ``dotenv.load_dotenv`` while importing the Teams SDK: ``microsoft_teams.apps.app`` loads a
  225. cwd-discovered ``.env`` at import, mutating process-global ``os.environ``. Hermes owns dotenv loading.
  226. See #62935.
  227. """
  228. try:
  229. import dotenv as _dotenv
  230. except ImportError:
  231. _dotenv = None
  232. original = getattr(_dotenv, "load_dotenv", None)
  233. if original is None:
  234. yield
  235. return
  236. _dotenv.load_dotenv = lambda *args, **kwargs: False # type: ignore[assignment]
  237. try:
  238. yield
  239. finally:
  240. _dotenv.load_dotenv = original # type: ignore[assignment]
  241. def check_teams_requirements() -> bool:
  242. """Ensure the Teams SDK is importable, lazy-installing it on first use.
  243. Lazy-installs ``microsoft-teams-apps`` via
  244. ``pm.ensure_import("teams")`` if not present, then rebinds
  245. all module-level SDK globals on success. Returns True once the SDK (and
  246. aiohttp) are importable, False if they couldn't be installed/imported.
  247. ``App is not None`` means symbols are already bound — ``TEAMS_SDK_AVAILABLE``
  248. alone can be True from ``find_spec`` without an import having run yet.
  249. """
  250. if App is not None and AIOHTTP_AVAILABLE:
  251. return True
  252. def _import() -> dict:
  253. from aiohttp import web as _web
  254. bindings: dict = {"web": _web, "AIOHTTP_AVAILABLE": True}
  255. with _suppress_third_party_dotenv():
  256. for module_name, names in _SDK_IMPORTS.items():
  257. module = importlib.import_module(module_name)
  258. for name in names:
  259. try:
  260. bindings[name] = getattr(module, name)
  261. except AttributeError as exc: # same failure class as ``from X import Y``
  262. raise ImportError(f"cannot import name {name!r} from {module_name!r}") from exc
  263. bindings["TEAMS_SDK_AVAILABLE"] = True
  264. return bindings
  265. from pm.extras import ensure_and_bind
  266. return ensure_and_bind("teams", _import, globals())
  267. _CHAT_TYPES = {"personal": "dm", "groupChat": "group", "channel": "channel"}
  268. # DOCUMENT wins over PHOTO/VIDEO/AUDIO for mixed attachments: document-context
  269. # injection gates strictly on MessageType.DOCUMENT (same precedence as Email/Signal).
  270. _MEDIA_KIND_PRECEDENCE = (
  271. ("document", MessageType.DOCUMENT), ("image", MessageType.PHOTO),
  272. ("video", MessageType.VIDEO), ("audio", MessageType.AUDIO))
  273. _APPROVAL_CHOICES = {"approve_once": "once", "approve_session": "session", "approve_always": "always", "deny": "deny"}
  274. # choice → catalog key of the card footer; resolved through ``t()`` at click time, never at import.
  275. _APPROVAL_LABEL_KEYS = {
  276. "once": "platform.teams.approval.resolved_once", "session": "platform.teams.approval.resolved_session",
  277. "always": "platform.teams.approval.resolved_always", "deny": "platform.teams.approval.resolved_deny",
  278. }
  279. def _approval_body(cmd: str, desc: str, *, always: bool = False) -> list:
  280. """Adaptive Card body blocks for an approval prompt; unless ``always``, empty ``cmd``/``desc`` omit their blocks."""
  281. body = []
  282. if cmd or always:
  283. body.append(TextBlock(text=f"⚠️ {t('gateway.exec_approval.header')}", wrap=True, weight="Bolder"))
  284. body.append(TextBlock(text=f"```\n{cmd}\n```", wrap=True))
  285. if desc or always:
  286. body.append(TextBlock(text=f"{t('gateway.exec_approval.reason_label')}: {desc}", wrap=True, isSubtle=True))
  287. return body
  288. class TeamsAdapter(BasePlatformAdapter):
  289. """Microsoft Teams adapter using the microsoft-teams-apps SDK."""
  290. # Answers /p/<profile>/... on the default listener for a served secondary (shared_ingress).
  291. serves_profile_prefix: bool = True
  292. MAX_MESSAGE_LENGTH = 28000 # Teams text message limit (~28 KB)
  293. splits_long_messages = True # send() chunks via truncate_message()
  294. def __init__(self, config: PlatformConfig):
  295. super().__init__(config, Platform("teams"))
  296. # Kept on the instance: ``platforms.teams.extra.*`` keys are read after construction too.
  297. self._extra: dict[str, Any] = config.extra or {}
  298. self._client_id, self._client_secret, self._tenant_id = _credentials(config)
  299. # (token, expiry monotonic ts) for connector attachment auth; refreshed under
  300. # _bf_token_lock so concurrent attachments can't stampede the STS.
  301. self._bf_token_cache: Optional[tuple] = None
  302. self._bf_token_lock: Optional[asyncio.Lock] = None
  303. self._port = coerce_port(self._extra.get("port") or _get_scoped_secret("TEAMS_PORT", str(_DEFAULT_PORT)), _DEFAULT_PORT)
  304. _raw_host = self._extra.get("host") or _get_scoped_secret("TEAMS_HOST", "") or _DEFAULT_HOST # falsy → dual-stack None
  305. self._host: Optional[str] = str(_raw_host) if _raw_host else None
  306. self._app: Optional[App] = None
  307. self._runner: Optional[web.AppRunner] = None
  308. self._dedup = MessageDeduplicator(max_size=1000)
  309. # chat_id → ConversationReference so proactive cards use the right conversation type.
  310. self._conv_refs: dict[str, Any] = {}
  311. self._require_mention: bool = self._parse_require_mention(config)
  312. # Outbound activity ids (bounded) so require_mention can exempt replies to our own messages.
  313. self._sent_ids: deque = deque(maxlen=500)
  314. # prompt id → (command preview, reason) for the resolved card; button data carries only the id,
  315. # because a copy per button can push a long non-ASCII command past Teams' ~28 KB card cap.
  316. self._approval_previews: dict[str, tuple[str, str]] = {}
  317. @staticmethod
  318. def _parse_require_mention(config) -> bool:
  319. """TEAMS_REQUIRE_MENTION (scoped) → ``require_mention`` in config.extra → false (opt-in, same
  320. default as TELEGRAM_REQUIRE_MENTION). Without RSC Teams only delivers mention activities to a
  321. group bot anyway, so the gate changes nothing until the app gains ChannelMessage.Read.Group /
  322. ChatMessage.Read.Chat and starts receiving every conversation message."""
  323. configured = _extra_or_secret(config.extra, "require_mention", "TEAMS_REQUIRE_MENTION", False)
  324. if isinstance(configured, bool):
  325. return configured
  326. return str(configured).strip().lower() not in {"false", "0", "no", "off"}
  327. async def connect(self, *, is_reconnect: bool = False) -> bool:
  328. # Reconnect paths reach here without create_adapter()'s installer — re-run to bind SDK globals.
  329. check_teams_requirements()
  330. pip = f"{sys.executable} -m pip install"
  331. for failed, code, message in (
  332. (App is None or ClientOptions is None, "MISSING_SDK",
  333. f"microsoft-teams-apps could not be installed. Run: {pip} microsoft-teams-apps"),
  334. (not AIOHTTP_AVAILABLE, "MISSING_SDK", f"aiohttp not installed. Run: {pip} aiohttp"),
  335. (not self._client_id or not self._client_secret or not self._tenant_id, "MISSING_CREDENTIALS",
  336. "TEAMS_CLIENT_ID, TEAMS_CLIENT_SECRET, and TEAMS_TENANT_ID are all required")):
  337. if failed:
  338. self._set_fatal_error(code, message, retryable=False)
  339. return False
  340. try:
  341. # aiohttp app first — the bridge adapter wires SDK routes into it.
  342. # Set up aiohttp app first — the bridge adapter wires SDK routes into it. client_max_size: Bot
  343. # Framework activities are JSON (caps out well under 1 MiB); an explicit cap keeps
  344. # oversized/chunked bodies from being buffered unbounded on a 0.0.0.0 bind (same pattern as
  345. # webhook.py / raft, #58536/#58902).
  346. aiohttp_app = web.Application(client_max_size=_MAX_BODY_BYTES)
  347. aiohttp_app.router.add_get("/health", lambda _: web.Response(text="ok"))
  348. self._app = App(
  349. client_id=self._client_id, client_secret=self._client_secret, tenant_id=self._tenant_id,
  350. http_server_adapter=_AiohttpBridgeAdapter(aiohttp_app),
  351. client=ClientOptions(headers={"User-Agent": "Hermes"}))
  352. # Handlers (ours, then plugin on_* decorators) must be wired before initialize(),
  353. # which registers POST /api/messages on aiohttp_app via the bridge's register_route().
  354. @self._app.on_message
  355. async def _handle_message(ctx: ActivityContext[MessageActivity]):
  356. await self._on_message(ctx)
  357. @self._app.on_card_action
  358. async def _handle_card_action(
  359. ctx: ActivityContext[AdaptiveCardInvokeActivity],
  360. ) -> InvokeResponse[AdaptiveCardActionMessageResponse]:
  361. return await self._on_card_action(ctx)
  362. self._wire_plugin_handlers(self._app)
  363. await self._app.initialize()
  364. # Shared-listener mode (multiplex secondary): no bind; served at /p/<profile>/api/messages.
  365. from gateway.platforms.shared_ingress import bind_listener
  366. self._runner = await bind_listener(self, aiohttp_app, self._host, self._port, _WEBHOOK_PATH)
  367. self._running = True
  368. self._mark_connected()
  369. if self._runner is not None:
  370. logger.info(
  371. "[teams] Webhook server listening on %s:%d%s",
  372. self._host or "* (all interfaces, IPv4+IPv6)", self._port, _WEBHOOK_PATH)
  373. return True
  374. except Exception as e:
  375. self._set_fatal_error("CONNECT_FAILED", f"Teams connection failed: {e}", retryable=True)
  376. logger.error("[teams] Failed to connect: %s", e, exc_info=True)
  377. return False
  378. async def disconnect(self) -> None:
  379. self._running = False
  380. if self._runner:
  381. await self._runner.cleanup()
  382. self._runner = self._app = None
  383. self._mark_disconnected()
  384. logger.info("[teams] Disconnected")
  385. async def _get_botframework_token(self) -> str:
  386. """Bot Framework bearer token (client credentials), cached until ~5 min before expiry; connector
  387. attachments are NOT pre-authenticated, unlike SharePoint downloadUrls. The lock is created lazily
  388. because ``asyncio.Lock()`` in __init__ may bind the wrong loop."""
  389. import time
  390. import httpx
  391. if self._bf_token_lock is None:
  392. self._bf_token_lock = asyncio.Lock()
  393. async with self._bf_token_lock:
  394. cached = self._bf_token_cache
  395. if cached and cached[1] > time.monotonic() + 300:
  396. return cached[0]
  397. if not (self._client_id and self._client_secret and self._tenant_id):
  398. raise ValueError("Missing TEAMS_CLIENT_ID/SECRET/TENANT_ID for attachment auth")
  399. token_url, token_form = _bf_token_request(self._tenant_id, self._client_id, self._client_secret)
  400. async with httpx.AsyncClient(timeout=15.0) as client:
  401. resp = await client.post(token_url, data=token_form)
  402. resp.raise_for_status()
  403. payload = resp.json()
  404. expires_in = float(payload.get("expires_in", 3600) or 3600)
  405. self._bf_token_cache = (payload["access_token"], time.monotonic() + expires_in)
  406. return self._bf_token_cache[0]
  407. async def _fetch_attachment_bytes(self, url: str, timeout: float = 30.0) -> bytes:
  408. """Download attachment bytes with SSRF protection. Connector URLs get the bot's bearer token;
  409. redirects and body size go through the shared guards (as the cache_*_from_url helpers)."""
  410. from tools.url_safety import create_ssrf_safe_async_client, is_safe_url
  411. from gateway.platforms.base import ssrf_redirect_guard, _read_httpx_body_with_limit
  412. if not is_safe_url(url):
  413. raise ValueError("Blocked unsafe attachment URL (SSRF protection)")
  414. headers = {"User-Agent": "Mozilla/5.0 (compatible; HermesAgent/1.0)"}
  415. if _is_botframework_attachment_url(url):
  416. try:
  417. headers["Authorization"] = f"Bearer {await self._get_botframework_token()}"
  418. except Exception as e:
  419. logger.warning("[teams] Could not acquire Bot Framework token for attachment: %s", e)
  420. async with create_ssrf_safe_async_client(
  421. timeout=timeout, follow_redirects=True, event_hooks={"response": [ssrf_redirect_guard]}) as client:
  422. async with client.stream("GET", url, headers=headers) as response:
  423. response.raise_for_status()
  424. # Never buffer .content — a lying Content-Length must not OOM the gateway.
  425. return await _read_httpx_body_with_limit(response, media_type="attachment")
  426. async def _on_message(self, ctx: ActivityContext[MessageActivity]) -> None:
  427. activity = ctx.activity
  428. # Teams writes the bot's conversation identity as ``28:<app id>`` (activity.recipient) while
  429. # App.id is the bare app id — accept both when deciding "is this us".
  430. recipient_id = getattr(getattr(activity, "recipient", None), "id", None)
  431. bot_ids = {i for i in (self._app.id if self._app else None, recipient_id) if isinstance(i, str) and i}
  432. bot_ids |= {f"28:{i}" for i in tuple(bot_ids) if not i.startswith("28:")}
  433. if getattr(activity.from_, "id", None) in bot_ids:
  434. return
  435. msg_id = getattr(activity, "id", None)
  436. if msg_id and self._dedup.is_duplicate(msg_id):
  437. return
  438. conv = activity.conversation
  439. conv_id = getattr(conv, "id", None)
  440. if conv_id: # cache the conversation reference for proactive sends (approval cards, etc.)
  441. self._conv_refs[conv_id] = ctx.conversation_ref
  442. text = activity.text if hasattr(activity, "text") and activity.text else ""
  443. if self._require_mention and getattr(conv, "conversation_type", None) != "personal":
  444. # RSC-delivered history: every channel/groupChat message arrives. Keep the ones that
  445. # @mention the bot or reply to one of its own messages; drop the rest BEFORE the
  446. # attachment loop so a gated post never downloads anything onto the host.
  447. if not self._activity_mentions_bot(activity, bot_ids, text) and getattr(activity, "reply_to_id", None) not in self._sent_ids:
  448. logger.debug("[teams] Dropping non-personal message without a bot mention (chat=%s, msg=%s)", conv_id, msg_id)
  449. return
  450. if "<at>" in text: # strip the <at>BotName</at> tags Teams prepends for @mentions
  451. text = re.sub(r"<at>[^<]*</at>\s*", "", text).strip()
  452. from_account = activity.from_
  453. user_id = getattr(from_account, "aad_object_id", None) or getattr(from_account, "id", "")
  454. source = self.build_source(
  455. chat_id=conv.id,
  456. chat_name=getattr(conv, "name", None) or "",
  457. chat_type=_CHAT_TYPES.get(getattr(conv, "conversation_type", None) or "", "dm"),
  458. user_id=str(user_id),
  459. user_name=getattr(from_account, "name", None) or "",
  460. guild_id=getattr(conv, "tenant_id", None) or self._tenant_id,
  461. message_id=msg_id)
  462. media: list = [m for m in [await self._cache_attachment(a) for a in getattr(activity, "attachments", None) or []] if m]
  463. media_kinds = [kind for _, _, kind in media] # media items are (path, media_type, kind)
  464. msg_type = next((t for kind, t in _MEDIA_KIND_PRECEDENCE if kind in media_kinds), MessageType.TEXT)
  465. await self.handle_message(MessageEvent(
  466. text=text, source=source, message_type=msg_type, message_id=msg_id,
  467. media_urls=[path for path, _, _ in media], media_types=[mt for _, mt, _ in media]))
  468. @staticmethod
  469. def _activity_mentions_bot(activity: Any, bot_ids: set, text: str) -> bool:
  470. """True when a ``mention`` entity points at the bot (``mentioned.id`` is ``28:<app id>`` on the
  471. wire; ``bot_ids`` carries both spellings). A payload with no mention entities at all falls back
  472. to the rendered ``<at>`` tag; one that mentions only other people does not."""
  473. mentions = [e for e in getattr(activity, "entities", None) or [] if getattr(e, "type", None) == "mention"]
  474. if not mentions:
  475. return "<at>" in text
  476. return any(str(getattr(getattr(e, "mentioned", None), "id", "")) in bot_ids for e in mentions)
  477. async def _cache_attachment(self, att: Any) -> Optional[tuple]:
  478. """Download + cache one inbound attachment → ``(path, media_type, kind)`` or ``None``."""
  479. content_url = getattr(att, "content_url", None)
  480. content_type = (getattr(att, "content_type", None) or "").lower()
  481. att_name = getattr(att, "name", None) or ""
  482. # Skip non-file payloads: Teams mirrors the message body as a text/html attachment,
  483. # and cards arrive as application/vnd.microsoft.card.*
  484. if (content_type in ("text/html", "text/plain") and not content_url) or content_type.startswith("application/vnd.microsoft.card"):
  485. return None
  486. if content_type == "application/vnd.microsoft.teams.file.download.info":
  487. # Consent-free download: content carries a pre-authed SharePoint downloadUrl + file type.
  488. content = getattr(att, "content", None)
  489. if not isinstance(content, dict):
  490. content = getattr(content, "__dict__", None) or {}
  491. download_url = content.get("downloadUrl") or content.get("download_url")
  492. file_type = (content.get("fileType") or content.get("file_type") or "").lstrip(".")
  493. if not download_url:
  494. return None
  495. filename = att_name or (f"document.{file_type}" if file_type else "document")
  496. try:
  497. data = await self._fetch_attachment_bytes(download_url)
  498. cached = await cache_media_bytes_async(data, filename=filename, mime_type="")
  499. if not cached:
  500. logger.warning("[teams] Unsupported document type for attachment '%s', skipping", filename)
  501. return None
  502. return cached.path, cached.media_type, cached.kind
  503. except Exception as e:
  504. logger.warning("[teams] Failed to cache file attachment '%s': %s", filename, e)
  505. return None
  506. if content_url and content_type.startswith("image/"):
  507. try:
  508. if _is_botframework_attachment_url(content_url):
  509. # Connector URL needs the bot's bearer token; the generic cache helper sends none.
  510. data = await self._fetch_attachment_bytes(content_url)
  511. ext = content_type.split("/")[-1].split(";")[0] or "png"
  512. cached = await cache_media_bytes_async(data, filename=att_name or f"image.{ext}", mime_type=content_type)
  513. if not cached:
  514. logger.warning(
  515. "[teams] Bot Framework attachment '%s' returned data that failed image validation, skipping",
  516. att_name or content_url)
  517. return None
  518. return cached.path, cached.media_type, "image"
  519. path = await cache_image_from_url(content_url)
  520. return (path, content_type, "image") if path else None
  521. except Exception as e:
  522. logger.warning("[teams] Failed to cache image attachment: %s", e)
  523. return None
  524. if content_url: # direct-URL non-image attachment (video/audio/document)
  525. try:
  526. data = await self._fetch_attachment_bytes(content_url)
  527. cached = await cache_media_bytes_async(data, filename=att_name, mime_type=content_type)
  528. return (cached.path, cached.media_type, cached.kind) if cached else None
  529. except Exception as e:
  530. logger.warning("[teams] Failed to cache attachment '%s' (%s): %s", att_name or content_url, content_type, e)
  531. return None
  532. async def _send_card(self, chat_id: str, card: AdaptiveCard) -> Any:
  533. """Send an AdaptiveCard, using a stored ConversationReference when available."""
  534. from microsoft_teams.api import MessageActivityInput
  535. if not self._app:
  536. return None
  537. return await self._send_via_conv_ref(chat_id, MessageActivityInput().add_card(card), card)
  538. async def _send_via_conv_ref(self, chat_id: str, activity: Any, fallback: Any) -> Any:
  539. """Send ``activity`` through the cached ConversationReference, else ``App.send(fallback)``."""
  540. conv_ref = self._conv_refs.get(chat_id)
  541. if conv_ref:
  542. result = await self._app.activity_sender.send(activity, conv_ref)
  543. else:
  544. result = await self._app.send(chat_id, fallback)
  545. self._remember_sent(result)
  546. return result
  547. def _remember_sent(self, result: Any) -> None:
  548. """Track an outbound activity id (bounded deque) for the require_mention reply exemption."""
  549. sent_id = getattr(result, "id", None)
  550. if isinstance(sent_id, str) and sent_id:
  551. self._sent_ids.append(sent_id)
  552. @staticmethod
  553. def _invoke_message(text: str) -> InvokeResponse[AdaptiveCardActionMessageResponse]:
  554. return InvokeResponse(status=200, body=AdaptiveCardActionMessageResponse(value=text))
  555. @staticmethod
  556. def _invoke_card(body: list) -> InvokeResponse[AdaptiveCardActionMessageResponse]:
  557. card = AdaptiveCard().with_version("1.4").with_body(body)
  558. return InvokeResponse(status=200, body=AdaptiveCardActionCardResponse(value=card))
  559. async def _on_card_action(
  560. self, ctx: ActivityContext[AdaptiveCardInvokeActivity]
  561. ) -> InvokeResponse[AdaptiveCardActionMessageResponse]:
  562. from tools.approval import has_blocking_approval, resolve_gateway_approval_card
  563. data = ctx.activity.value.action.data or {}
  564. hermes_action = data.get("hermes_action", "")
  565. session_key = data.get("session_key", "")
  566. if not hermes_action or not session_key:
  567. return self._invoke_message(t("platform.teams.approval.unknown_action"))
  568. denied = self._card_action_denied(ctx.activity.from_)
  569. if denied:
  570. return self._invoke_message(denied)
  571. choice = _APPROVAL_CHOICES.get(hermes_action)
  572. if not choice:
  573. return self._invoke_message(t("platform.teams.approval.unknown_action"))
  574. # Cards from an older build carry cmd/desc in the button data instead.
  575. cmd, desc = self._approval_previews.get(data.get("prompt_id", ""), (data.get("cmd", ""), data.get("desc", "")))
  576. if not has_blocking_approval(session_key) or not resolve_gateway_approval_card(
  577. session_key, choice, data.get("request_id")):
  578. body = _approval_body(cmd, desc)
  579. return self._invoke_card([*body, TextBlock(text=t("platform.shared.approval_expired"), wrap=True)])
  580. body = _approval_body(cmd, desc)
  581. body.append(TextBlock(text=t(_APPROVAL_LABEL_KEYS[choice]), wrap=True, weight="Bolder"))
  582. return self._invoke_card(body)
  583. @staticmethod
  584. def _card_action_denied(from_account: Any) -> Optional[str]:
  585. """Default-deny gate for approval clicks: require TEAMS_ALLOWED_USERS or an explicit
  586. TEAMS_ALLOW_ALL_USERS=true opt-in, else anyone who can message the bot could approve.
  587. Returns the user-facing denial text, or ``None`` when allowed."""
  588. # Scoped reads: under multiplex os.environ is the DEFAULT profile's allow-all/allowlist.
  589. if _get_scoped_secret("TEAMS_ALLOW_ALL_USERS", "").strip().lower() in {"1", "true", "yes"}:
  590. return None
  591. allowed_csv = _get_scoped_secret("TEAMS_ALLOWED_USERS", "").strip()
  592. if not allowed_csv:
  593. logger.warning(
  594. "[teams] card action rejected: TEAMS_ALLOWED_USERS not configured "
  595. "and TEAMS_ALLOW_ALL_USERS not set — default deny")
  596. return t("platform.teams.approval.requires_allowlist")
  597. clicker_id = getattr(from_account, "aad_object_id", None) or getattr(from_account, "id", "")
  598. allowed_ids = {uid.strip() for uid in allowed_csv.split(",") if uid.strip()}
  599. if "*" not in allowed_ids and clicker_id not in allowed_ids:
  600. logger.warning("[teams] Unauthorized card action by %s — ignoring", clicker_id)
  601. return t("platform.shared.not_authorized")
  602. return None
  603. _EA_CMD_BUDGET = 2000
  604. _EA_PREVIEWS_KEPT = 256
  605. _EA_CARD_ACTIONS = {"once": "approve_once", "session": "approve_session", "always": "approve_always", "deny": "deny"}
  606. _EA_CARD_STYLES = {"primary": "positive", "danger": "destructive"}
  607. async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult:
  608. """Adaptive Card: the shared text is split into its header / fenced command / reason blocks."""
  609. if not self._app:
  610. return SendResult(success=False, error="Teams app not initialized")
  611. # The resolved card shows the prompt's own command preview, looked up by id on click.
  612. cmd = self._truncate_preview(prompt.command, self._EA_CMD_BUDGET)
  613. prompt_id = uuid.uuid4().hex
  614. self._approval_previews[prompt_id] = (cmd, prompt.description)
  615. if len(self._approval_previews) > self._EA_PREVIEWS_KEPT:
  616. self._approval_previews.pop(next(iter(self._approval_previews)))
  617. btn_data_base = {"session_key": prompt.session_key, "prompt_id": prompt_id}
  618. if prompt.request_id:
  619. btn_data_base["request_id"] = prompt.request_id
  620. actions = []
  621. for label, choice, style in prompt.actions:
  622. kw = {"style": self._EA_CARD_STYLES[style]} if style else {}
  623. actions.append(ExecuteAction(
  624. title=label, verb="hermes_approve",
  625. data={**btn_data_base, "hermes_action": self._EA_CARD_ACTIONS[choice]}, **kw))
  626. body = _approval_body(cmd, prompt.description, always=True)
  627. body.append(TextBlock(text=format_approval_deadline_line(approval_timeout_seconds()), wrap=True))
  628. if prompt.smart_denied:
  629. body.append(TextBlock(text=self._EA_SMART_DENY_LINE.strip(), wrap=True))
  630. card = AdaptiveCard().with_version("1.4").with_body(body).with_actions(actions)
  631. try:
  632. result = await self._send_card(prompt.chat_id, card)
  633. return SendResult(success=True, message_id=getattr(result, "id", None) if result else None)
  634. except Exception as e:
  635. logger.error("[teams] send_exec_approval failed: %s", e, exc_info=True)
  636. return SendResult(success=False, error=str(e), retryable=True)
  637. async def send(
  638. self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[dict[str, Any]] = None
  639. ) -> SendResult:
  640. if not self._app:
  641. return SendResult(success=False, error="Teams app not initialized")
  642. last_message_id = None
  643. for chunk in self.truncate_message(self.format_message(content)):
  644. try:
  645. if reply_to and reply_to.isdigit() and reply_to != "0":
  646. try:
  647. result = await self._app.reply(chat_id, reply_to, chunk)
  648. except Exception as reply_err:
  649. # Group chats 400 on threaded sends; the SDK has no typed HTTP errors → fall back on any.
  650. logger.debug("Teams reply() failed, falling back to flat send: %s", reply_err)
  651. result = await self._app.send(chat_id, chunk)
  652. else:
  653. result = await self._app.send(chat_id, chunk)
  654. last_message_id = getattr(result, "id", None)
  655. self._remember_sent(result)
  656. except Exception as e:
  657. return SendResult(success=False, error=str(e), retryable=True)
  658. return SendResult(success=True, message_id=last_message_id)
  659. async def send_typing(self, chat_id: str, metadata: Optional[dict[str, Any]] = None) -> None:
  660. if self._app:
  661. with suppress(Exception):
  662. await self._app.send(chat_id, TypingActivityInput())
  663. async def _send_media_attachment(
  664. self, chat_id: str, source: str, default_mime: str, caption: Optional[str] = None, media_label: str = "media"
  665. ) -> SendResult:
  666. """Send any media file/URL as a Teams attachment (shared by send_image/video/voice/document).
  667. Remote ``http(s)://`` URLs are attached by reference; local paths (optional ``file://`` prefix)
  668. are base64-encoded into a data URI. MIME is guessed from the path, else ``default_mime``."""
  669. if not self._app:
  670. return SendResult(success=False, error="Teams app not initialized")
  671. try:
  672. import base64
  673. import mimetypes
  674. from microsoft_teams.api import Attachment, MessageActivityInput
  675. if source.startswith(("http://", "https://")):
  676. content_url = source
  677. mime_type = mimetypes.guess_type(source.split("?")[0])[0] or default_mime
  678. else:
  679. path = source.removeprefix("file://")
  680. mime_type = mimetypes.guess_type(path)[0] or default_mime
  681. data = await asyncio.to_thread(Path(path).read_bytes)
  682. content_url = f"data:{mime_type};base64,{base64.b64encode(data).decode()}"
  683. activity = MessageActivityInput().add_attachments(Attachment(content_type=mime_type, content_url=content_url))
  684. if caption:
  685. activity = activity.add_text(caption)
  686. result = await self._send_via_conv_ref(chat_id, activity, activity)
  687. return SendResult(success=True, message_id=getattr(result, "id", None))
  688. except Exception as e:
  689. logger.error("[teams] send_%s failed: %s", media_label, e, exc_info=True)
  690. return SendResult(success=False, error=str(e), retryable=True)
  691. async def send_image(self, chat_id: str, image_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
  692. metadata: Optional[dict[str, Any]] = None) -> SendResult:
  693. return await self._send_media_attachment(chat_id, image_url, "image/png", caption=caption, media_label="image")
  694. async def send_image_file(self, chat_id: str, image_path: str, caption: Optional[str] = None,
  695. reply_to: Optional[str] = None, **kwargs) -> SendResult:
  696. return await self.send_image(chat_id=chat_id, image_url=image_path, caption=caption, reply_to=reply_to)
  697. async def send_video(self, chat_id: str, video_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
  698. metadata: Optional[dict[str, Any]] = None, **kwargs) -> SendResult:
  699. return await self._send_media_attachment(chat_id, video_path, "video/mp4", caption=caption, media_label="video")
  700. async def send_voice(self, chat_id: str, audio_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
  701. metadata: Optional[dict[str, Any]] = None, **kwargs) -> SendResult:
  702. return await self._send_media_attachment(chat_id, audio_path, "audio/mpeg", caption=caption, media_label="voice")
  703. async def send_document(self, chat_id: str, file_path: str, caption: Optional[str] = None, file_name: Optional[str] = None,
  704. reply_to: Optional[str] = None, metadata: Optional[dict[str, Any]] = None, **kwargs) -> SendResult:
  705. return await self._send_media_attachment(
  706. chat_id, file_path, "application/octet-stream", caption=caption, media_label="document")
  707. async def get_chat_info(self, chat_id: str) -> dict:
  708. return {"name": chat_id, "type": "unknown", "chat_id": chat_id}
  709. _SETUP_CREDENTIALS = (
  710. ("Client ID", "TEAMS_CLIENT_ID", {}),
  711. ("Client secret", "TEAMS_CLIENT_SECRET", {"password": True}),
  712. ("Tenant ID", "TEAMS_TENANT_ID", {}))
  713. _SETUP_INTRO = ( # "" → blank line
  714. "You'll need the Teams CLI. If you haven't already:", " npm install -g @microsoft/teams.cli@preview",
  715. " teams login", "", "Then expose port 3978 publicly (devtunnel / ngrok / cloudflared),", "and create your bot:",
  716. ' teams app create --name "Hermes" --endpoint "https://<tunnel>/api/messages"', "",
  717. "The CLI will print CLIENT_ID, CLIENT_SECRET, and TENANT_ID. Paste them below.", "")
  718. def interactive_setup() -> None:
  719. from hermes_cli.config import get_env_value, save_env_value
  720. from hermes_cli.cli_output import prompt, prompt_yes_no, print_info, print_success, print_warning
  721. from hermes_cli.setup_platforms import declines_reconfigure
  722. if declines_reconfigure("Teams", "Reconfigure Teams?", "TEAMS_CLIENT_ID"):
  723. return
  724. for line in _SETUP_INTRO:
  725. print_info(line) if line else print()
  726. for label, env_key, prompt_kwargs in _SETUP_CREDENTIALS:
  727. value = prompt(label, default=get_env_value(env_key) or "", **prompt_kwargs)
  728. if not value:
  729. print_warning(f"{label} is required — skipping Teams setup")
  730. return
  731. save_env_value(env_key, value.strip())
  732. print()
  733. print_info("To find your AAD object ID for the allowlist: teams status --verbose")
  734. if prompt_yes_no("Restrict access to specific users? (recommended)", True):
  735. allowed = prompt("Allowed AAD object IDs (comma-separated)", default=get_env_value("TEAMS_ALLOWED_USERS") or "")
  736. if allowed:
  737. save_env_value("TEAMS_ALLOWED_USERS", allowed.replace(" ", ""))
  738. print_success("Allowlist configured")
  739. else:
  740. save_env_value("TEAMS_ALLOWED_USERS", "")
  741. else:
  742. save_env_value("TEAMS_ALLOW_ALL_USERS", "true")
  743. print_warning("⚠️ Open access — anyone who can message the bot can command it.")
  744. print()
  745. print_success("Teams configuration saved to ~/.hermes/.env")
  746. print_info("Install the app in Teams: teams app install --id <teamsAppId>")
  747. print_info("Restart the gateway: hermes gateway restart")
  748. def _install_hint() -> str:
  749. """Point to the setup flow that requests PM's declared Teams extra."""
  750. return "Teams SDK missing — run `hermes setup`, configure Teams, then restart the gateway"
  751. def register(ctx) -> None:
  752. ctx.register_platform(
  753. name="teams", label="Microsoft Teams", adapter_factory=lambda cfg: TeamsAdapter(cfg),
  754. dashboard_description="Connect Hermes to Microsoft Teams chats via the Bot Framework.",
  755. docs_url="https://hermes-agent.nousresearch.com/docs/user-guide/messaging/teams",
  756. check_fn=check_requirements, # PASSIVE probe — never installs
  757. ensure_deps_fn=check_teams_requirements, # ACTIVE lazy-installer, run by create_adapter()
  758. validate_config=validate_config, is_connected=is_connected,
  759. required_env=["TEAMS_CLIENT_ID", "TEAMS_CLIENT_SECRET", "TEAMS_TENANT_ID"],
  760. install_hint=_install_hint(), setup_fn=interactive_setup,
  761. env_enablement_fn=_env_enablement, # env-only setups show up in gateway status
  762. cron_deliver_env_var="TEAMS_HOME_CHANNEL", # deliver=teams cron home-channel routing
  763. standalone_sender_fn=_standalone_send, # out-of-process cron delivery via Bot Framework REST
  764. allowed_users_env="TEAMS_ALLOWED_USERS", allow_all_env="TEAMS_ALLOW_ALL_USERS",
  765. max_message_length=28000, # Teams supports up to ~28 KB per message
  766. emoji="💼", allow_update_command=True,
  767. platform_hint=(
  768. "You are chatting via Microsoft Teams. Teams renders a subset of "
  769. "markdown — bold (**text**), italic (*text*), and inline code "
  770. "(`code`) work, but complex tables or raw HTML do not. Keep "
  771. "responses clear and professional."))