Skip to main content

adk_surface/channels/teams/
mod.rs

1//! The Microsoft Teams adapter (parity with Google ADK's `TeamsRunner`, on spec 3.3 §5.3): a
2//! bot registered with Azure Bot Service — the Bot Framework's activity webhook in, every
3//! request's Bot Connector token checked; the Bot Connector REST API out, with a Microsoft
4//! Entra ID client-credentials token.
5
6mod api;
7mod auth;
8mod wire;
9
10use std::collections::{HashMap, HashSet, VecDeque};
11use std::fmt;
12use std::sync::{Arc, Mutex, PoisonError};
13
14use adk_core::{AdkError, ErrorCategory, ErrorComponent};
15use adk_kernel::KernelError;
16use adk_kernel::channels::{
17    ChannelGateway, ChannelInbound, ChannelNotice, ChannelSink, DecisionCard, InboundBody,
18    StopNotice,
19};
20use async_trait::async_trait;
21use axum::Json;
22use axum::body::Bytes;
23use axum::extract::State;
24use axum::http::{HeaderMap, StatusCode, header};
25use axum::response::{IntoResponse, Response};
26use axum::routing::post;
27use chrono::Utc;
28use serde_json::Value;
29use tokio::sync::mpsc;
30
31use super::shared::{
32    ANSWER_NOT_TAKEN, AbortOnDrop, ChannelConnection, HANDLING, Handling, Kit, MESSAGE_NOT_TAKEN,
33    PressedCard, Taker, Update, checked_base, checked_token, dispatch, kit_builder, notice_words,
34    patient, stopped_words,
35};
36use crate::error::{Result, SurfaceError};
37use api::{ConnectorApi, TokenSource};
38use auth::{ConnectorAuth, Refusal};
39
40/// The channel the Teams adapter serves, as the kernel names it: pairings, thread sessions
41/// and `kernel.channel` audit records carry it.
42pub const TEAMS_CHANNEL: &str = "teams";
43
44/// Microsoft Teams as a person reads it, in "You said yes in Microsoft Teams at 07:31" (spec
45/// 3.3 §8.1).
46pub const TEAMS: &str = "Microsoft Teams";
47
48/// The Bot Connector address for a conversation the adapter has not heard from since it
49/// started: Teams' global address for proactive messages in the public cloud.
50const DEFAULT_SERVICE_URL: &str = "https://smba.trafficmanager.net/teams/";
51/// Where Microsoft Entra ID issues access tokens.
52const DEFAULT_LOGIN_BASE: &str = "https://login.microsoftonline.com";
53/// How many activity ids the webhook remembers, so a redelivery is taken once.
54const SEEN_KEPT: usize = 4096;
55/// What Teams shows on a card when a pressed answer is handed over; the outcome follows as a
56/// reply to the card.
57const ANSWER_RECEIVED: &str = "Answer received.";
58
59/// Why the Teams adapter could not talk to Microsoft Teams.
60///
61/// Never carries the app password or an access token. Converts into [`AdkError`] with a
62/// `surface.teams.*` code and provider `teams`.
63///
64/// # Example
65///
66/// ```rust
67/// use adk_surface::channels::TeamsError;
68///
69/// let error = TeamsError::Unauthorized;
70/// assert_eq!(error.code(), "surface.teams.unauthorized");
71/// assert!(error.to_string().contains("TEAMS_APP_PASSWORD"));
72/// ```
73#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
74#[non_exhaustive]
75pub enum TeamsError {
76    /// Microsoft Entra ID refused the bot's credentials, or the Bot Connector refused its
77    /// token.
78    #[error(
79        "Microsoft Teams refused the bot's credentials: check TEAMS_APP_ID and \
80         TEAMS_APP_PASSWORD (a client secret of the bot's app registration), and TEAMS_TENANT_ID \
81         for a single-tenant bot"
82    )]
83    Unauthorized,
84    /// The Bot Connector refused the send, such as a person who blocked or uninstalled the
85    /// app (`MessageWritesBlocked`).
86    #[error(
87        "Microsoft Teams refused the message (HTTP 403): {message}; the person may have blocked or removed the app"
88    )]
89    Forbidden {
90        /// The Bot Connector's message.
91        message: String,
92    },
93    /// The Bot Connector throttled the bot (HTTP 429, or 412, 502 or 504, which Teams asks
94    /// bots to retry).
95    #[error("Microsoft Teams throttled the bot (HTTP {status}): try again later")]
96    RateLimited {
97        /// The HTTP status.
98        status: u16,
99    },
100    /// The Bot Connector refused the send, such as an unknown conversation or a message too
101    /// large.
102    #[error("Microsoft Teams refused the message (HTTP {status}): {message}")]
103    Refused {
104        /// The HTTP status.
105        status: u16,
106        /// The Bot Connector's message.
107        message: String,
108    },
109    /// Microsoft Teams or Microsoft Entra ID could not be reached.
110    #[error("Microsoft Teams could not be reached: {reason}; check the network")]
111    Unreachable {
112        /// What failed.
113        reason: String,
114    },
115    /// An answer that was not the Bot Framework's JSON.
116    #[error("Microsoft Teams' answer could not be read: {reason}")]
117    InvalidResponse {
118        /// What was wrong with it.
119        reason: String,
120    },
121}
122
123impl TeamsError {
124    /// The error code: `surface.teams.unauthorized`, `.forbidden`, `.rate_limited`,
125    /// `.refused`, `.unreachable` or `.invalid_response`.
126    pub fn code(&self) -> &'static str {
127        match self {
128            Self::Unauthorized => "surface.teams.unauthorized",
129            Self::Forbidden { .. } => "surface.teams.forbidden",
130            Self::RateLimited { .. } => "surface.teams.rate_limited",
131            Self::Refused { .. } => "surface.teams.refused",
132            Self::Unreachable { .. } => "surface.teams.unreachable",
133            Self::InvalidResponse { .. } => "surface.teams.invalid_response",
134        }
135    }
136}
137
138impl From<TeamsError> for AdkError {
139    fn from(error: TeamsError) -> Self {
140        let category = match &error {
141            TeamsError::Unauthorized => ErrorCategory::Unauthorized,
142            TeamsError::Forbidden { .. } => ErrorCategory::Forbidden,
143            TeamsError::RateLimited { .. } => ErrorCategory::RateLimited,
144            TeamsError::Refused { .. } => ErrorCategory::InvalidInput,
145            TeamsError::Unreachable { .. } => ErrorCategory::Unavailable,
146            TeamsError::InvalidResponse { .. } => ErrorCategory::Internal,
147        };
148        AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
149            .with_provider("teams")
150    }
151}
152
153impl From<TeamsError> for KernelError {
154    fn from(error: TeamsError) -> Self {
155        Self::Core(error.into())
156    }
157}
158
159/// Builds a [`TeamsAdapter`].
160pub struct TeamsAdapterBuilder {
161    app_id: String,
162    password: String,
163    tenant: Option<String>,
164    service_url: String,
165    login_base: String,
166    openid_configuration: String,
167    issuer: String,
168    kit: Kit,
169}
170
171impl fmt::Debug for TeamsAdapterBuilder {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        f.debug_struct("TeamsAdapterBuilder")
174            .field("app_id", &self.app_id)
175            .field("tenant", &self.tenant)
176            .field("service_url", &self.service_url)
177            .finish_non_exhaustive()
178    }
179}
180
181impl TeamsAdapterBuilder {
182    /// A single-tenant bot's Microsoft Entra tenant: its access token comes from that tenant,
183    /// and only activities from conversations in it are taken (`403` otherwise). Without it the
184    /// bot is multi-tenant and its token comes from `botframework.com`.
185    #[must_use]
186    pub fn tenant(mut self, tenant: impl Into<String>) -> Self {
187        self.tenant = Some(tenant.into());
188        self
189    }
190
191    /// The Bot Connector address for a conversation the adapter has not heard from since it
192    /// started, such as a wake-up after a restart; defaults to
193    /// `https://smba.trafficmanager.net/teams/`. Set it for a sovereign cloud — GCC
194    /// `https://smba.infra.gcc.teams.microsoft.com/teams`, GCC High
195    /// `https://smba.infra.gov.teams.microsoft.us/teams`. Each activity's own `serviceUrl` is
196    /// used for its conversation once one arrives.
197    #[must_use]
198    pub fn service_url(mut self, url: impl Into<String>) -> Self {
199        self.service_url = url.into();
200        self
201    }
202
203    /// Microsoft Entra ID's login address; defaults to `https://login.microsoftonline.com`.
204    /// Plain `http` is accepted on loopback only (a test double).
205    #[must_use]
206    pub fn login_base(mut self, url: impl Into<String>) -> Self {
207        self.login_base = url.into();
208        self
209    }
210
211    /// The Bot Connector's OpenID metadata document, whose `jwks_uri` lists the keys that sign
212    /// every activity's token; defaults to
213    /// `https://login.botframework.com/v1/.well-known/openidconfiguration`. Plain `http` is
214    /// accepted on loopback only (a test double).
215    #[must_use]
216    pub fn openid_configuration(mut self, url: impl Into<String>) -> Self {
217        self.openid_configuration = url.into();
218        self
219    }
220
221    /// The issuer every activity's token must carry; defaults to
222    /// `https://api.botframework.com`. Set it, with
223    /// [`openid_configuration`](Self::openid_configuration), for a sovereign cloud.
224    #[must_use]
225    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
226        self.issuer = issuer.into();
227        self
228    }
229
230    kit_builder!("Microsoft Teams");
231
232    /// The adapter.
233    ///
234    /// # Errors
235    ///
236    /// Returns `surface.invalid` for an empty or malformed app id, password or tenant, or an
237    /// address that is not `https` (or `http` on loopback).
238    pub fn build(self) -> Result<TeamsAdapter> {
239        checked_token(&self.app_id, "the bot's app id (TEAMS_APP_ID)")
240            .map_err(SurfaceError::Invalid)?;
241        if self.password.is_empty() || self.password.chars().any(char::is_control) {
242            return Err(SurfaceError::Invalid(
243                "the bot's password (TEAMS_APP_PASSWORD) is empty or malformed: copy the client \
244                 secret's value again from the app registration"
245                    .into(),
246            ));
247        }
248        if let Some(tenant) = &self.tenant {
249            checked_token(tenant, "the tenant id (TEAMS_TENANT_ID)")
250                .map_err(SurfaceError::Invalid)?;
251        }
252        let service_url = checked_base(&self.service_url, "the Bot Connector address", false)
253            .map_err(SurfaceError::Invalid)?;
254        let client = reqwest::Client::builder().build().map_err(|error| {
255            SurfaceError::Invalid(format!(
256                "the Teams HTTP client could not be built: {}",
257                error.without_url()
258            ))
259        })?;
260        let tokens = TokenSource::new(
261            client.clone(),
262            &self.login_base,
263            self.tenant.as_deref(),
264            &self.app_id,
265            &self.password,
266        )
267        .map_err(SurfaceError::Invalid)?;
268        let auth = ConnectorAuth::new(
269            client.clone(),
270            &self.openid_configuration,
271            &self.issuer,
272            &self.app_id,
273        )
274        .map_err(SurfaceError::Invalid)?;
275        Ok(TeamsAdapter {
276            inner: Arc::new(Inner {
277                api: ConnectorApi::new(client, tokens),
278                auth,
279                kit: self.kit,
280                app_id: self.app_id,
281                tenant: self.tenant,
282                service_url,
283                state: Mutex::default(),
284            }),
285        })
286    }
287}
288
289/// The Microsoft Teams adapter: a bot's one-on-one chats as a person's threads with their
290/// agents, over the kernel's channel contract (spec 3.3 §10 K1), through Azure Bot Service.
291///
292/// It is the gateway's [`ChannelSink`] for the channel [`TEAMS_CHANNEL`].
293/// [`start`](Self::start) returns the webhook as an Axum router the host serves at the bot's
294/// messaging endpoint, such as `https://agents.example.com/api/messages`: Teams has no other
295/// way in.
296///
297/// | Direction | What |
298/// |---|---|
299/// | In | `POST` is refused before it is read unless its `Authorization` carries a Bot Connector token: signed `RS256` by a key in the Bot Connector's OpenID metadata (cached a day), `iss` `https://api.botframework.com`, `aud` the bot's app id, within its validity with five minutes' skew (`401`), its key endorsing `msteams` and its `serviceurl` the activity's (`403`). Messages and pressed answers from one-on-one chats reach the gateway; group chats, channels and other Bot Framework channels are not read; an activity delivered again is taken once. Typed text never answers a decision (S-I4) and loses the characters a chat app shows as nothing (S-I6) |
300/// | Out | `POST {serviceUrl}/v3/conversations/{id}/activities` with an Entra ID token, renewed before it expires. An agent's text and every notice as `plain` text, so nothing formats (S-I9). A card as an Adaptive Card 1.4: the chat screen's lines as `TextRun`s, an `Action.Execute` for each answer the card offers and no others — `Action.Submit` on older clients — and "Open in home"; never the call's arguments (S-I5). A notice about a pressed card replies to it |
301/// | Answers | An `adaptiveCard/action` invoke is answered at once with "Answer received."; the gateway decides it with the version the card showed, as every channel does |
302/// | Wake-ups | Proactive: a card or a reply to a conversation the adapter has not heard from since it started goes to the configured [`service_url`](TeamsAdapterBuilder::service_url) |
303/// | Throttling | HTTP 429, 412, 502 and 504 are retried after `Retry-After`, else 1 and 2 seconds with jitter; never for a stranger |
304/// | Commands | "stop all" and `/stop` stop everything; resuming is refused (S-I10) |
305///
306/// # Example
307///
308/// ```rust,no_run
309/// use std::sync::Arc;
310/// use adk_kernel::channels::{ChannelDoorbell, ChannelGateway, InMemoryChannelBindingStore};
311/// use adk_surface::channels::TeamsAdapter;
312///
313/// # async fn example(kernel: adk_kernel::Kernel, doorbell: Arc<ChannelDoorbell>) -> Result<(), Box<dyn std::error::Error>> {
314/// let teams = TeamsAdapter::builder(std::env::var("TEAMS_APP_ID")?, std::env::var("TEAMS_APP_PASSWORD")?)
315///     .build()?;
316/// let gateway = ChannelGateway::builder(Arc::new(kernel), Arc::new(InMemoryChannelBindingStore::new()))
317///     .sink(Arc::new(teams.clone()))
318///     .home_url("https://home.example/ui/")
319///     .doorbell(doorbell)
320///     .build();
321/// gateway.start().await?;
322/// let webhook = teams.start(gateway);
323/// let app = axum::Router::new().nest("/api/messages", webhook.router());
324/// # let _ = app;
325/// # Ok(())
326/// # }
327/// ```
328#[derive(Clone)]
329pub struct TeamsAdapter {
330    inner: Arc<Inner>,
331}
332
333struct Inner {
334    api: ConnectorApi,
335    auth: ConnectorAuth,
336    kit: Kit,
337    app_id: String,
338    tenant: Option<String>,
339    service_url: String,
340    state: Mutex<Conversations>,
341}
342
343/// The service address of each conversation, and the activities taken.
344#[derive(Default)]
345struct Conversations {
346    service_urls: HashMap<String, String>,
347    seen: HashSet<String>,
348    order: VecDeque<String>,
349}
350
351impl Conversations {
352    /// Notes activity `id`; `false` when it was taken before.
353    fn first_time(&mut self, id: &str) -> bool {
354        if !self.seen.insert(id.to_string()) {
355            return false;
356        }
357        self.order.push_back(id.to_string());
358        while self.order.len() > SEEN_KEPT {
359            if let Some(oldest) = self.order.pop_front() {
360                self.seen.remove(&oldest);
361            }
362        }
363        true
364    }
365}
366
367impl fmt::Debug for TeamsAdapter {
368    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369        f.debug_struct("TeamsAdapter")
370            .field("channel", &TEAMS_CHANNEL)
371            .field("app_id", &self.inner.app_id)
372            .finish_non_exhaustive()
373    }
374}
375
376/// The webhook a [`TeamsAdapter::start`] serves: the router the host mounts, and the handing
377/// over of what it receives; dropping it stops the handing over.
378#[derive(Debug)]
379pub struct TeamsWebhook {
380    router: axum::Router,
381    connection: ChannelConnection<TeamsError>,
382}
383
384impl TeamsWebhook {
385    /// The webhook's route, `POST /`: mount it with `Router::nest` at the path of the bot's
386    /// messaging endpoint, such as `/api/messages`, on a public HTTPS address.
387    pub fn router(&self) -> axum::Router {
388        self.router.clone()
389    }
390
391    /// Stops handing activities over; the router then answers `503`, so the Bot Connector
392    /// delivers them again later.
393    pub fn stop(&self) {
394        self.connection.stop();
395    }
396
397    /// Whether the handing over stopped.
398    pub fn is_finished(&self) -> bool {
399        self.connection.is_finished()
400    }
401
402    /// Waits for the handing over to stop: once stopped, or once every router is dropped.
403    ///
404    /// # Errors
405    ///
406    /// Never fails today; the error type leaves room for the transport.
407    pub async fn join(self) -> std::result::Result<(), TeamsError> {
408        drop(self.router);
409        self.connection.join().await
410    }
411}
412
413/// What the webhook's handler shares.
414struct Hook {
415    adapter: TeamsAdapter,
416    sender: mpsc::UnboundedSender<Update<Carried>>,
417}
418
419/// What an activity carries beyond its inbound value: the card a pressed answer was on.
420pub(crate) struct Carried {
421    card: Option<String>,
422}
423
424/// What became of one verified activity.
425enum Delivery {
426    /// Handed over, or nothing to hand over.
427    Queued,
428    /// A redelivery, taken before.
429    Again,
430    /// The handing over stopped.
431    Closed,
432}
433
434impl TeamsAdapter {
435    /// An adapter for the bot with app id `app_id` and password `password` — a client secret
436    /// of the bot's Microsoft Entra app registration.
437    pub fn builder(app_id: impl Into<String>, password: impl Into<String>) -> TeamsAdapterBuilder {
438        TeamsAdapterBuilder {
439            app_id: app_id.into(),
440            password: password.into(),
441            tenant: None,
442            service_url: DEFAULT_SERVICE_URL.to_string(),
443            login_base: DEFAULT_LOGIN_BASE.to_string(),
444            openid_configuration: auth::OPENID_CONFIGURATION.to_string(),
445            issuer: auth::ISSUER.to_string(),
446            kit: Kit::default(),
447        }
448    }
449
450    /// What the adapter makes of one Bot Framework activity (spec 3.3 S-I4, S-I6): a typed
451    /// message or a pressed answer from a one-on-one chat, or `None`. The webhook checks the
452    /// activity's token before this; this reads only.
453    ///
454    /// # Example
455    ///
456    /// ```rust
457    /// use adk_kernel::channels::InboundBody;
458    /// use adk_surface::channels::TeamsAdapter;
459    ///
460    /// let teams = TeamsAdapter::builder("00000000-0000-0000-0000-000000000001", "secret").build().unwrap();
461    /// let activity = serde_json::json!({
462    ///     "type": "message", "id": "1485983408511", "channelId": "msteams",
463    ///     "serviceUrl": "https://smba.trafficmanager.net/amer/",
464    ///     "from": { "id": "29:ana", "name": "Ana" },
465    ///     "conversation": { "conversationType": "personal", "id": "a:dm-ana" },
466    ///     "text": "stop all",
467    /// });
468    /// let inbound = teams.inbound(&activity).unwrap();
469    /// assert_eq!(inbound.body, InboundBody::Text { text: "stop all".into() });
470    /// assert_eq!(inbound.thread, "a:dm-ana");
471    /// ```
472    pub fn inbound(&self, activity: &Value) -> Option<ChannelInbound> {
473        wire::parse(activity).and_then(|received| received.inbound)
474    }
475
476    /// Serves the webhook, handing each activity to `gateway`, which must have this adapter as
477    /// its sink, until [`TeamsWebhook::stop`].
478    ///
479    /// An activity is answered once it is queued — `200`, or the invoke response for a
480    /// pressed answer — and taken by the gateway after: a paired account's first, each
481    /// account's in the order sent (S-I6, S-I10); one the gateway fails on is taken again
482    /// only when it is a paired account's and the failure may clear. An activity whose id was
483    /// taken before is acknowledged and not taken again.
484    pub fn start(&self, gateway: ChannelGateway) -> TeamsWebhook {
485        let (sender, task) = dispatch(Arc::new(self.clone()), gateway);
486        let hook = Arc::new(Hook { adapter: self.clone(), sender });
487        let router = axum::Router::new().route("/", post(receive)).with_state(hook);
488        let connection = ChannelConnection::spawn(async move {
489            let mut dispatcher = AbortOnDrop(task);
490            let _ = (&mut dispatcher.0).await;
491            Ok(())
492        });
493        TeamsWebhook { router, connection }
494    }
495
496    /// Notes `received`'s conversation and queues what it carries.
497    fn take(
498        &self,
499        received: wire::Received,
500        sender: &mpsc::UnboundedSender<Update<Carried>>,
501    ) -> Delivery {
502        {
503            let mut state = self.inner.state.lock().unwrap_or_else(PoisonError::into_inner);
504            state.service_urls.insert(received.thread.clone(), received.service_url.clone());
505            if !state.first_time(&received.id) {
506                return Delivery::Again;
507            }
508        }
509        let Some(inbound) = received.inbound else { return Delivery::Queued };
510        let update =
511            Update { inbound: Some(inbound), press: Some(Carried { card: received.card }) };
512        if sender.send(update).is_err() { Delivery::Closed } else { Delivery::Queued }
513    }
514
515    /// The Bot Connector address of `thread`: the one its last activity named, else the
516    /// configured one.
517    fn service_url(&self, thread: &str) -> String {
518        let state = self.inner.state.lock().unwrap_or_else(PoisonError::into_inner);
519        state.service_urls.get(thread).cloned().unwrap_or_else(|| self.inner.service_url.clone())
520    }
521
522    /// Posts `activity` to `thread`, as a reply to `reply_to` when set; returns its id.
523    async fn send(
524        &self,
525        thread: &str,
526        reply_to: Option<&str>,
527        activity: &Value,
528    ) -> adk_kernel::Result<String> {
529        let service = self.service_url(thread);
530        // A throttled reply to an account that is not paired is not waited out.
531        let patient = patient(TEAMS_CHANNEL, thread);
532        Ok(self.inner.api.post(&service, thread, reply_to, activity, patient).await?)
533    }
534}
535
536/// The status a refused token is answered with; nothing of why.
537fn refused(refusal: &Refusal) -> Response {
538    let status = match refusal {
539        Refusal::Unauthenticated(_) => StatusCode::UNAUTHORIZED,
540        Refusal::Forbidden(_) => StatusCode::FORBIDDEN,
541        Refusal::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
542    };
543    status.into_response()
544}
545
546/// An activity: refused before it is read unless the Bot Connector's token vouches for it.
547async fn receive(State(hook): State<Arc<Hook>>, headers: HeaderMap, body: Bytes) -> Response {
548    let authorization = headers.get(header::AUTHORIZATION).and_then(|value| value.to_str().ok());
549    let verified = match hook.adapter.inner.auth.verify(authorization).await {
550        Ok(verified) => verified,
551        Err(refusal) => {
552            tracing::warn!(reason = ?refusal, "a teams activity without a valid bot connector token was refused");
553            return refused(&refusal);
554        }
555    };
556    let Ok(activity) = serde_json::from_slice::<Value>(&body) else {
557        return StatusCode::BAD_REQUEST.into_response();
558    };
559    let channel = activity["channelId"].as_str().unwrap_or_default();
560    let service_url = activity["serviceUrl"].as_str().unwrap_or_default();
561    if let Err(refusal) = verified.vouches_for(channel, service_url) {
562        tracing::warn!(reason = ?refusal, "a teams activity its token does not vouch for was refused");
563        return refused(&refusal);
564    }
565    // The token travels to this address with every reply.
566    if checked_base(service_url, "the activity's serviceUrl", false).is_err() {
567        tracing::warn!("a teams activity naming a service address that is not https was refused");
568        return StatusCode::FORBIDDEN.into_response();
569    }
570    let Some(received) = wire::parse(&activity) else { return StatusCode::OK.into_response() };
571    if let Some(tenant) = &hook.adapter.inner.tenant
572        && received.tenant.as_deref() != Some(tenant.as_str())
573    {
574        tracing::warn!("a teams activity from another tenant was refused");
575        return StatusCode::FORBIDDEN.into_response();
576    }
577    let invoke = received.invoke;
578    let answers = received
579        .inbound
580        .as_ref()
581        .is_some_and(|inbound| matches!(inbound.body, InboundBody::Answer { .. }));
582    match hook.adapter.take(received, &hook.sender) {
583        Delivery::Closed => StatusCode::SERVICE_UNAVAILABLE.into_response(),
584        Delivery::Queued | Delivery::Again if invoke && answers => {
585            Json(wire::invoke_message(ANSWER_RECEIVED)).into_response()
586        }
587        Delivery::Queued | Delivery::Again if invoke => {
588            Json(wire::invoke_refused("this card action is not one of the agents' answers"))
589                .into_response()
590        }
591        Delivery::Queued | Delivery::Again => StatusCode::OK.into_response(),
592    }
593}
594
595#[async_trait]
596impl Taker for TeamsAdapter {
597    /// The card a pressed answer was on.
598    type Press = Carried;
599
600    fn channel_name(&self) -> &'static str {
601        TEAMS_CHANNEL
602    }
603
604    async fn take(
605        &self,
606        gateway: &ChannelGateway,
607        update: &Update<Carried>,
608        paired: bool,
609    ) -> adk_kernel::Result<()> {
610        let Some(inbound) = update.inbound.clone() else { return Ok(()) };
611        let card = match &inbound.body {
612            InboundBody::Answer { decision, .. } => Some(PressedCard {
613                card: update.press.as_ref().and_then(|carried| carried.card.clone()),
614                decision: decision.clone(),
615            }),
616            _ => None,
617        };
618        let handling = Handling::of(TEAMS_CHANNEL, gateway, &inbound, paired, card);
619        HANDLING.scope(handling, gateway.receive(inbound)).await.map(drop)
620    }
621
622    async fn not_taken(&self, update: &Update<Carried>) {
623        let Some(inbound) = &update.inbound else { return };
624        let card = update.press.as_ref().and_then(|carried| carried.card.as_deref());
625        let (text, reply_to) = match card {
626            Some(card) => (ANSWER_NOT_TAKEN, Some(card)),
627            None => (MESSAGE_NOT_TAKEN, Some(inbound.message_id.as_str())),
628        };
629        if let Err(error) = self.send(&inbound.thread, reply_to, &wire::text(text)).await {
630            tracing::debug!(error = %error, "a person could not be told their message was not taken");
631        }
632    }
633}
634
635#[async_trait]
636impl ChannelSink for TeamsAdapter {
637    fn channel(&self) -> &str {
638        TEAMS_CHANNEL
639    }
640
641    async fn send_message(&self, thread: &str, text: &str) -> adk_kernel::Result<()> {
642        for activity in wire::plain(text) {
643            self.send(thread, None, &activity).await?;
644        }
645        Ok(())
646    }
647
648    async fn send_decision(&self, thread: &str, card: &DecisionCard) -> adk_kernel::Result<()> {
649        let (heading, card) = self.inner.kit.prepare(card).await;
650        let activity = wire::card(&card, &heading, self.inner.kit.offset);
651        self.send(thread, None, &activity).await.map(drop)
652    }
653
654    async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> adk_kernel::Result<()> {
655        self.send(thread, None, &wire::message(&stopped_words(notice))).await.map(drop)
656    }
657
658    /// A notice about a pressed card records the answer with where it was given before the
659    /// confirmation is sent, as a reply to the card (spec 3.3 §8.1, §11).
660    async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> adk_kernel::Result<()> {
661        let card = self.inner.kit.before_notice(TEAMS_CHANNEL, TEAMS, thread, notice).await;
662        let card = card.filter(|card| !card.is_empty());
663        let words = notice_words(notice, self.inner.kit.offset, Utc::now(), card.is_some());
664        self.send(thread, card.as_deref(), &wire::message(&words)).await.map(drop)
665    }
666}
667
668#[cfg(test)]
669mod tests {
670    use super::*;
671
672    const APP_ID: &str = "00000000-0000-0000-0000-000000000001";
673
674    #[test]
675    fn errors_say_what_to_do_and_keep_their_category() {
676        let error: AdkError = TeamsError::Unauthorized.into();
677        assert_eq!(error.category, ErrorCategory::Unauthorized);
678        assert_eq!(error.code, "surface.teams.unauthorized");
679        let throttled: AdkError = TeamsError::RateLimited { status: 429 }.into();
680        assert!(throttled.is_retryable());
681        let blocked: AdkError =
682            TeamsError::Forbidden { message: "MessageWritesBlocked".into() }.into();
683        assert_eq!(blocked.category, ErrorCategory::Forbidden);
684    }
685
686    #[test]
687    fn the_builder_checks_its_inputs_and_never_echoes_the_password() {
688        let adapter = TeamsAdapter::builder(APP_ID, "s3cret~pass").build().unwrap();
689        assert!(!format!("{adapter:?}").contains("s3cret"));
690        assert!(!format!("{:?}", TeamsAdapter::builder(APP_ID, "s3cret~pass")).contains("s3cret"));
691        assert_eq!(ChannelSink::channel(&adapter), "teams");
692        let empty = TeamsAdapter::builder(APP_ID, "").build().unwrap_err();
693        assert!(empty.to_string().contains("TEAMS_APP_PASSWORD"), "{empty}");
694        let id = TeamsAdapter::builder("app id", "p").build().unwrap_err();
695        assert!(id.to_string().contains("TEAMS_APP_ID"), "{id}");
696        let plain = TeamsAdapter::builder(APP_ID, "p")
697            .service_url("http://smba.example/teams")
698            .build()
699            .unwrap_err();
700        assert!(plain.to_string().contains("https"), "{plain}");
701        assert!(TeamsAdapter::builder(APP_ID, "p").tenant("a tenant").build().is_err());
702    }
703
704    #[test]
705    fn a_conversation_is_answered_where_it_last_wrote_from() {
706        let adapter = TeamsAdapter::builder(APP_ID, "p").build().unwrap();
707        assert_eq!(adapter.service_url("a:1"), "https://smba.trafficmanager.net/teams");
708        let (sender, _receiver) = mpsc::unbounded_channel();
709        let received = wire::Received {
710            id: "1".into(),
711            thread: "a:1".into(),
712            service_url: "https://smba.trafficmanager.net/emea/".into(),
713            tenant: None,
714            inbound: None,
715            card: None,
716            invoke: false,
717        };
718        assert!(matches!(adapter.take(received.clone(), &sender), Delivery::Queued));
719        assert!(matches!(adapter.take(received, &sender), Delivery::Again));
720        assert_eq!(adapter.service_url("a:1"), "https://smba.trafficmanager.net/emea/");
721        let mut state = Conversations::default();
722        assert!(state.first_time("x") && !state.first_time("x"));
723        for index in 0..SEEN_KEPT + 1 {
724            state.first_time(&format!("y{index}"));
725        }
726        assert!(state.first_time("x"), "forgotten after {SEEN_KEPT}");
727    }
728}