Skip to main content

adk_surface/channels/slack/
mod.rs

1//! The Slack adapter (spec 3.5 §10 X12, on spec 3.3 §5.3): Socket Mode in, the Web API out.
2
3mod api;
4mod wire;
5
6use std::fmt;
7use std::sync::Arc;
8use std::time::Duration;
9
10use adk_core::{AdkError, ErrorCategory, ErrorComponent};
11use adk_kernel::KernelError;
12use adk_kernel::channels::{
13    ChannelGateway, ChannelInbound, ChannelNotice, ChannelSink, DecisionCard, InboundBody,
14    InboundOutcome, StopNotice,
15};
16use async_trait::async_trait;
17use chrono::Utc;
18use futures::{SinkExt, StreamExt};
19use serde_json::{Value, json};
20use tokio::sync::mpsc;
21use tokio_tungstenite::tungstenite::Message;
22
23use super::shared::{
24    ANSWER_NOT_TAKEN, AbortOnDrop, ChannelConnection, HANDLING, Handling, Kit, MESSAGE_NOT_TAKEN,
25    PressedCard, REQUEST_TIMEOUT, Taker, Update, checked_base, dispatch, kit_builder, notice_words,
26    patient, stopped_words,
27};
28use crate::error::{Result, SurfaceError};
29use api::SlackApi;
30use wire::Press;
31
32/// The channel the Slack adapter serves, as the kernel names it: pairings, thread sessions
33/// and `kernel.channel` audit records carry it (spec 3.5 §10 X12).
34pub const SLACK_CHANNEL: &str = "slack";
35
36/// Slack as a person reads it, in "You said yes in Slack at 07:31" (spec 3.3 §8.1).
37pub const SLACK: &str = "Slack";
38
39const DEFAULT_API_BASE: &str = "https://slack.com/api";
40const MIN_BACKOFF: Duration = Duration::from_secs(1);
41const MAX_BACKOFF: Duration = Duration::from_secs(60);
42/// How often the adapter pings the socket, and how long it waits for any frame before it
43/// connects again.
44const PING_EVERY: Duration = Duration::from_secs(30);
45const SILENT_FOR: Duration = Duration::from_secs(90);
46
47/// Why the Slack adapter could not talk to Slack (spec 3.5 §10 X12).
48///
49/// Never carries a token. Converts into [`AdkError`] with a `surface.slack.*` code and
50/// provider `slack`.
51///
52/// # Example
53///
54/// ```rust
55/// use adk_surface::channels::SlackError;
56///
57/// let error = SlackError::Unauthorized;
58/// assert_eq!(error.code(), "surface.slack.unauthorized");
59/// assert!(error.to_string().contains("SLACK_APP_TOKEN"));
60/// ```
61#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
62#[non_exhaustive]
63pub enum SlackError {
64    /// Slack refused a token.
65    #[error(
66        "Slack refused a token: check SLACK_APP_TOKEN (an app-level token with \
67         `connections:write`) and SLACK_BOT_TOKEN (the bot token, `xoxb-`)"
68    )]
69    Unauthorized,
70    /// Slack asked the app to slow down for longer than the adapter waits.
71    #[error("Slack asked to wait {retry_after} s before {method}: the app is sending too much")]
72    RateLimited {
73        /// The Web API method.
74        method: String,
75        /// How long Slack asked to wait, in seconds.
76        retry_after: u64,
77    },
78    /// Slack refused the call, such as a conversation the app is not in.
79    #[error("Slack refused {method}: {error}")]
80    Refused {
81        /// The Web API method.
82        method: String,
83        /// Slack's error, such as `channel_not_found`.
84        error: String,
85    },
86    /// Slack could not be reached.
87    #[error(
88        "Slack could not be reached for {method}: {reason}; check the network and the API address"
89    )]
90    Unreachable {
91        /// The Web API method, or `socket`.
92        method: String,
93        /// What failed.
94        reason: String,
95    },
96    /// Slack's answer was not the Web API's JSON.
97    #[error("Slack's answer to {method} could not be read: {reason}")]
98    InvalidResponse {
99        /// The Web API method.
100        method: String,
101        /// What was wrong with it.
102        reason: String,
103    },
104}
105
106impl SlackError {
107    /// The error code: `surface.slack.unauthorized`, `.rate_limited`, `.refused`,
108    /// `.unreachable` or `.invalid_response`.
109    pub fn code(&self) -> &'static str {
110        match self {
111            Self::Unauthorized => "surface.slack.unauthorized",
112            Self::RateLimited { .. } => "surface.slack.rate_limited",
113            Self::Refused { .. } => "surface.slack.refused",
114            Self::Unreachable { .. } => "surface.slack.unreachable",
115            Self::InvalidResponse { .. } => "surface.slack.invalid_response",
116        }
117    }
118}
119
120impl From<SlackError> for AdkError {
121    fn from(error: SlackError) -> Self {
122        let category = match &error {
123            SlackError::Unauthorized => ErrorCategory::Unauthorized,
124            SlackError::RateLimited { .. } => ErrorCategory::RateLimited,
125            SlackError::Refused { error, .. } => match error.as_str() {
126                "channel_not_found" | "not_in_channel" | "is_archived" | "cannot_dm_bot"
127                | "restricted_action" | "missing_scope" => ErrorCategory::Forbidden,
128                "invalid_arguments" | "invalid_blocks" | "msg_too_long" | "no_text" => {
129                    ErrorCategory::InvalidInput
130                }
131                _ => ErrorCategory::Unavailable,
132            },
133            SlackError::Unreachable { .. } => ErrorCategory::Unavailable,
134            SlackError::InvalidResponse { .. } => ErrorCategory::Internal,
135        };
136        AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
137            .with_provider("slack")
138    }
139}
140
141impl From<SlackError> for KernelError {
142    fn from(error: SlackError) -> Self {
143        Self::Core(error.into())
144    }
145}
146
147/// The Socket Mode connection a [`SlackAdapter::start`] runs; dropping it stops it.
148pub type SlackConnection = ChannelConnection<SlackError>;
149
150/// Builds a [`SlackAdapter`].
151pub struct SlackAdapterBuilder {
152    app_token: String,
153    bot_token: String,
154    api_base: String,
155    kit: Kit,
156}
157
158impl fmt::Debug for SlackAdapterBuilder {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        f.debug_struct("SlackAdapterBuilder")
161            .field("api_base", &self.api_base)
162            .finish_non_exhaustive()
163    }
164}
165
166impl SlackAdapterBuilder {
167    /// The Web API's address; defaults to `https://slack.com/api`. Plain `http` is accepted
168    /// on loopback only (a test double), since the tokens travel with every call.
169    #[must_use]
170    pub fn api_base(mut self, url: impl Into<String>) -> Self {
171        self.api_base = url.into();
172        self
173    }
174
175    kit_builder!("Slack");
176
177    /// The adapter.
178    ///
179    /// # Errors
180    ///
181    /// Returns `surface.invalid` for an empty or malformed token, or an API address that is
182    /// not `https` (or `http` on loopback).
183    pub fn build(self) -> Result<SlackAdapter> {
184        let api = SlackApi::new(&self.api_base, &self.app_token, &self.bot_token)
185            .map_err(SurfaceError::Invalid)?;
186        Ok(SlackAdapter { inner: Arc::new(Inner { api, kit: self.kit }) })
187    }
188}
189
190/// The Slack adapter (spec 3.5 §10 X12): a Slack app's direct messages as the person's chat
191/// thread with their agents, over the kernel's channel contract (spec 3.3 §10 K1).
192///
193/// It is the gateway's [`ChannelSink`] for the channel [`SLACK_CHANNEL`], and
194/// [`start`](Self::start) reads the app's events over Socket Mode — a WebSocket the adapter
195/// opens, so no inbound port — and hands each to [`ChannelGateway::receive`]. Every envelope
196/// is acknowledged with its `envelope_id` as it arrives.
197///
198/// | Direction | What |
199/// |---|---|
200/// | Out | A card as Block Kit: "Waiting for you · since 18:00", the call in plain words, the agent and the risk as plain text, a button for each answer the card offers and no others, and "Open in home" — never the call's arguments (S-I5). Agent replies with `&`, `<` and `>` escaped and `mrkdwn` off (S-I9) |
201/// | In | New messages from a person in a direct message with the app, and pressed buttons (`block_actions`); channels, bots, edits and files are ignored. Typed text never answers a decision (S-I4) and loses the characters a chat app shows as nothing (S-I6) |
202/// | Commands | `/stop` in the direct message, once the app declares it, and "stop all" stop everything; resuming is refused (S-I10) |
203///
204/// # Example
205///
206/// ```rust,no_run
207/// use std::sync::Arc;
208/// use adk_kernel::channels::{ChannelDoorbell, ChannelGateway, InMemoryChannelBindingStore};
209/// use adk_surface::channels::SlackAdapter;
210///
211/// # async fn example(kernel: adk_kernel::Kernel, doorbell: Arc<ChannelDoorbell>) -> Result<(), Box<dyn std::error::Error>> {
212/// let slack = SlackAdapter::builder(std::env::var("SLACK_APP_TOKEN")?, std::env::var("SLACK_BOT_TOKEN")?).build()?;
213/// let gateway = ChannelGateway::builder(Arc::new(kernel), Arc::new(InMemoryChannelBindingStore::new()))
214///     .sink(Arc::new(slack.clone()))
215///     .home_url("http://127.0.0.1:8080/ui/")
216///     .doorbell(doorbell)
217///     .build();
218/// gateway.start().await?;
219/// let connection = slack.start(gateway);
220/// connection.join().await?;
221/// # Ok(())
222/// # }
223/// ```
224#[derive(Clone)]
225pub struct SlackAdapter {
226    inner: Arc<Inner>,
227}
228
229struct Inner {
230    api: SlackApi,
231    kit: Kit,
232}
233
234impl fmt::Debug for SlackAdapter {
235    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236        f.debug_struct("SlackAdapter").field("channel", &SLACK_CHANNEL).finish_non_exhaustive()
237    }
238}
239
240/// What an envelope carries beyond its inbound value.
241pub(crate) struct Carried {
242    /// A pressed button's card.
243    press: Option<Press>,
244    /// The files a message shared.
245    files: Vec<crate::channels::media::FileRef>,
246}
247
248/// Why a socket ended.
249enum Ended {
250    /// Slack asked for a new connection.
251    Reconnect,
252    /// The connection failed.
253    Failed(String),
254}
255
256impl SlackAdapter {
257    /// An adapter for the app with `app_token` (`xapp-…`, with `connections:write`) and
258    /// `bot_token` (`xoxb-…`, with `chat:write` and `im:history`).
259    pub fn builder(
260        app_token: impl Into<String>,
261        bot_token: impl Into<String>,
262    ) -> SlackAdapterBuilder {
263        SlackAdapterBuilder {
264            app_token: app_token.into(),
265            bot_token: bot_token.into(),
266            api_base: DEFAULT_API_BASE.to_string(),
267            kit: Kit::default(),
268        }
269    }
270
271    /// What the adapter makes of one Socket Mode envelope (spec 3.3 S-I4, S-I6): a typed
272    /// message, a pressed answer, `/stop`, or `None` for anything the gateway is not given.
273    ///
274    /// # Example
275    ///
276    /// ```rust
277    /// use adk_kernel::channels::InboundBody;
278    /// use adk_surface::channels::SlackAdapter;
279    ///
280    /// let slack = SlackAdapter::builder("xapp-1-example", "xoxb-1-example").build().unwrap();
281    /// let envelope = serde_json::json!({
282    ///     "envelope_id": "e1",
283    ///     "type": "events_api",
284    ///     "payload": { "event": {
285    ///         "type": "message", "channel_type": "im", "user": "U4217",
286    ///         "channel": "D4217", "ts": "1761300000.000100", "text": "stop all",
287    ///     }},
288    /// });
289    /// let inbound = slack.inbound(&envelope).unwrap();
290    /// assert_eq!(inbound.body, InboundBody::Text { text: "stop all".into() });
291    /// assert_eq!((inbound.account.as_str(), inbound.thread.as_str()), ("U4217", "D4217"));
292    /// ```
293    pub fn inbound(&self, envelope: &Value) -> Option<ChannelInbound> {
294        wire::parse(envelope).inbound
295    }
296
297    /// Opens the app's Socket Mode connection and hands each event to `gateway`, which must
298    /// have this adapter as its sink, until [`SlackConnection::stop`].
299    ///
300    /// Every envelope is acknowledged as it arrives. A paired account's events go to the
301    /// gateway first, each account's in the order sent (S-I6, S-I10); one the gateway fails
302    /// on is taken again only when it is a paired account's and the failure may clear.
303    /// When Slack asks for a new connection (`disconnect`), or the socket goes quiet or
304    /// closes, the adapter opens a new one; a refused token ends the connection with
305    /// [`SlackError::Unauthorized`].
306    pub fn start(&self, gateway: ChannelGateway) -> SlackConnection {
307        let adapter = self.clone();
308        ChannelConnection::spawn(async move { adapter.run(gateway).await })
309    }
310
311    async fn run(&self, gateway: ChannelGateway) -> std::result::Result<(), SlackError> {
312        let (sender, task) = dispatch(Arc::new(self.clone()), gateway);
313        let _dispatcher = AbortOnDrop(task);
314        let mut backoff = MIN_BACKOFF;
315        loop {
316            let url = match self.inner.api.open_socket().await {
317                Ok(url) => url,
318                Err(SlackError::Unauthorized) => return Err(SlackError::Unauthorized),
319                Err(error) => {
320                    tracing::warn!(error = %error, "the slack socket could not be opened; retrying");
321                    tokio::time::sleep(backoff).await;
322                    backoff = (backoff * 2).min(MAX_BACKOFF);
323                    continue;
324                }
325            };
326            match self.serve(&url, &sender).await {
327                Ended::Reconnect => backoff = MIN_BACKOFF,
328                Ended::Failed(reason) => {
329                    tracing::warn!(reason = %reason, "the slack socket ended; connecting again");
330                    tokio::time::sleep(backoff).await;
331                    backoff = (backoff * 2).min(MAX_BACKOFF);
332                }
333            }
334        }
335    }
336
337    /// Reads one socket until Slack asks for another or it fails.
338    async fn serve(&self, url: &str, sender: &mpsc::UnboundedSender<Update<Carried>>) -> Ended {
339        if let Err(reason) = checked_base(url, "the Slack socket address", true) {
340            return Ended::Failed(reason);
341        }
342        adk_core::ensure_crypto_provider();
343        let connect = tokio_tungstenite::connect_async(url);
344        let mut socket = match tokio::time::timeout(REQUEST_TIMEOUT, connect).await {
345            Ok(Ok((socket, _))) => socket,
346            Ok(Err(error)) => return Ended::Failed(error.to_string()),
347            Err(_) => return Ended::Failed("the socket did not open in time".into()),
348        };
349        let mut ping = tokio::time::interval(PING_EVERY);
350        ping.tick().await;
351        let mut heard = tokio::time::Instant::now();
352        loop {
353            let frame = tokio::select! {
354                _ = ping.tick() => {
355                    if heard.elapsed() > SILENT_FOR {
356                        return Ended::Failed("the socket went quiet".into());
357                    }
358                    if let Err(error) = socket.send(Message::Ping(Vec::new().into())).await {
359                        return Ended::Failed(error.to_string());
360                    }
361                    continue;
362                }
363                frame = socket.next() => frame,
364            };
365            heard = tokio::time::Instant::now();
366            let text = match frame {
367                Some(Ok(Message::Text(text))) => text,
368                Some(Ok(Message::Close(_))) | None => {
369                    return Ended::Failed("the socket closed".into());
370                }
371                Some(Ok(_)) => continue,
372                Some(Err(error)) => return Ended::Failed(error.to_string()),
373            };
374            let Ok(envelope) = serde_json::from_str::<Value>(text.as_str()) else { continue };
375            match envelope["type"].as_str() {
376                Some("hello") => continue,
377                Some("disconnect") => return Ended::Reconnect,
378                _ => {}
379            }
380            // Acknowledged at once, so Slack does not deliver it again.
381            if let Some(id) = envelope["envelope_id"].as_str() {
382                let ack = json!({ "envelope_id": id }).to_string();
383                if let Err(error) = socket.send(Message::Text(ack.into())).await {
384                    return Ended::Failed(error.to_string());
385                }
386            }
387            let parsed = wire::parse(&envelope);
388            if parsed.inbound.is_some()
389                && sender
390                    .send(Update {
391                        inbound: parsed.inbound,
392                        press: Some(Carried { press: parsed.press, files: parsed.files }),
393                    })
394                    .is_err()
395            {
396                return Ended::Failed("the adapter stopped".into());
397            }
398        }
399    }
400
401    /// Takes the answer buttons off an answered card, so it is not pressed again.
402    async fn clear_buttons(&self, press: &Press) {
403        let Some((channel, ts)) = &press.card else { return };
404        let mut body = wire::answered(press);
405        body["channel"] = json!(channel);
406        body["ts"] = json!(ts);
407        if let Err(error) = self.inner.api.call("chat.update", &body, true).await {
408            tracing::debug!(error = %error, "an answered card's buttons could not be removed");
409        }
410    }
411
412    async fn post(&self, thread: &str, mut body: Value) -> adk_kernel::Result<()> {
413        body["channel"] = json!(thread);
414        // A rate limit on a reply to an account that is not paired is not waited out, so a
415        // stranger's flood holds up no one's events.
416        let patient = patient(SLACK_CHANNEL, thread);
417        self.inner.api.call("chat.postMessage", &body, patient).await?;
418        Ok(())
419    }
420}
421
422#[async_trait]
423impl Taker for SlackAdapter {
424    type Press = Carried;
425
426    fn channel_name(&self) -> &'static str {
427        SLACK_CHANNEL
428    }
429
430    /// Hands one event to the gateway; an answered card loses its answer buttons.
431    async fn take(
432        &self,
433        gateway: &ChannelGateway,
434        update: &Update<Carried>,
435        paired: bool,
436    ) -> adk_kernel::Result<()> {
437        let Some(mut inbound) = update.inbound.clone() else { return Ok(()) };
438        let carried = update.press.as_ref();
439        let press = carried.and_then(|carried| carried.press.as_ref());
440        // A paired account's images, for a host that takes them; a stranger's are never
441        // downloaded (spec 3.5 §10 X12).
442        let files = carried.map_or(&[][..], |carried| carried.files.as_slice());
443        if paired && !files.is_empty() {
444            let api = &self.inner.api;
445            let attachments =
446                crate::channels::media::fetch_all(files, |file| api.download(file)).await;
447            inbound = inbound.with_attachments(attachments);
448        }
449        let card = match (&inbound.body, press) {
450            (InboundBody::Answer { decision, .. }, Some(press)) => Some(PressedCard {
451                card: press.card.as_ref().map(|(_, ts)| ts.clone()),
452                decision: decision.clone(),
453            }),
454            _ => None,
455        };
456        let handling = Handling::of(SLACK_CHANNEL, gateway, &inbound, paired, card);
457        let outcome = HANDLING.scope(handling, gateway.receive(inbound)).await;
458        let Some(press) = press else { return outcome.map(drop) };
459        if matches!(
460            outcome?,
461            InboundOutcome::Decided { .. }
462                | InboundOutcome::AlreadyDecided { .. }
463                | InboundOutcome::DecisionChanged { .. }
464                | InboundOutcome::DecisionRefused { .. }
465        ) {
466            self.clear_buttons(press).await;
467        }
468        Ok(())
469    }
470
471    async fn not_taken(&self, update: &Update<Carried>) {
472        let Some(inbound) = &update.inbound else { return };
473        let pressed = update.press.as_ref().is_some_and(|carried| carried.press.is_some());
474        let text = if pressed { ANSWER_NOT_TAKEN } else { MESSAGE_NOT_TAKEN };
475        for body in wire::plain(text) {
476            if let Err(error) = self.post(&inbound.thread, body).await {
477                tracing::debug!(error = %error, "a person could not be told their message was not taken");
478            }
479        }
480    }
481}
482
483#[async_trait]
484impl ChannelSink for SlackAdapter {
485    fn channel(&self) -> &str {
486        SLACK_CHANNEL
487    }
488
489    async fn send_message(&self, thread: &str, text: &str) -> adk_kernel::Result<()> {
490        for body in wire::plain(text) {
491            self.post(thread, body).await?;
492        }
493        Ok(())
494    }
495
496    async fn send_decision(&self, thread: &str, card: &DecisionCard) -> adk_kernel::Result<()> {
497        let (heading, card) = self.inner.kit.prepare(card).await;
498        self.post(thread, wire::card(&card, &heading, self.inner.kit.offset)).await
499    }
500
501    async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> adk_kernel::Result<()> {
502        self.post(thread, wire::message(&stopped_words(notice))).await
503    }
504
505    /// A notice about a pressed card records the answer with where it was given before the
506    /// confirmation is sent (spec 3.3 §8.1, §11).
507    async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> adk_kernel::Result<()> {
508        self.inner.kit.before_notice(SLACK_CHANNEL, SLACK, thread, notice).await;
509        let words = notice_words(notice, self.inner.kit.offset, Utc::now(), false);
510        self.post(thread, wire::message(&words)).await
511    }
512}
513
514#[cfg(test)]
515mod tests {
516    use super::*;
517
518    #[test]
519    fn errors_say_what_to_do_and_keep_their_category() {
520        let error: AdkError = SlackError::Unauthorized.into();
521        assert_eq!(
522            (error.code, error.category),
523            ("surface.slack.unauthorized", ErrorCategory::Unauthorized)
524        );
525        let refused = SlackError::Refused {
526            method: "chat.postMessage".into(),
527            error: "not_in_channel".into(),
528        };
529        assert_eq!(AdkError::from(refused).category, ErrorCategory::Forbidden);
530        let limited =
531            SlackError::RateLimited { method: "chat.postMessage".into(), retry_after: 90 };
532        assert!(AdkError::from(limited).is_retryable());
533    }
534
535    #[test]
536    fn the_builder_refuses_a_bad_token_or_address_without_echoing_the_token() {
537        let error = SlackAdapter::builder("xapp-secret", "xoxb-secret")
538            .api_base("http://example.com/api")
539            .build()
540            .unwrap_err();
541        assert_eq!(error.code(), "surface.invalid");
542        assert!(!error.to_string().contains("secret"), "{error}");
543        assert!(SlackAdapter::builder("", "xoxb-1").build().is_err());
544        assert!(SlackAdapter::builder("xapp-1", "xoxb 1").build().is_err());
545        let adapter = SlackAdapter::builder("xapp-secret", "xoxb-secret").build().unwrap();
546        assert!(!format!("{adapter:?}").contains("secret"));
547        assert_eq!(ChannelSink::channel(&adapter), "slack");
548    }
549}