Skip to main content

adk_surface/channels/
shared.rs

1//! What the WhatsApp, Slack, Discord, Matrix and Microsoft Teams adapters share (spec 3.5 §10
2//! X12, on spec 3.3 §5.3): the rules the adapter keeps, kept once.
3//!
4//! | Part | What it keeps |
5//! |---|---|
6//! | [`dispatch`] | A paired account's updates are handed over first, each account's in the order sent; a failed update is taken again only when it is a paired account's and the failure may clear, and that account's later updates wait with it (S-I6, S-I10) |
7//! | [`HANDLING`], [`patient`] | Nothing sent to an account that is not paired waits out a rate limit |
8//! | [`Kit`] | A card headed by the call in plain words, a feature's chat heading, no answer on a call that spends money, and each answer recorded with where it was given before its confirmation is sent (spec 3.3 §7.1, §7.4, §8.1, §11) |
9//! | [`Words`] | The chat screen's words, the same on every platform, which each adapter escapes for its markup (S-I9) |
10//! | [`clean_inbound`] | A person's words are only what they saw: the characters Telegram's adapter drops are dropped here too (S-I6) |
11
12use std::collections::HashSet;
13use std::fmt;
14use std::sync::Arc;
15use std::time::Duration;
16
17use adk_core::audit_log::{
18    AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditTrail,
19};
20use adk_core::principal::SubjectRef;
21use adk_core::{ApprovalRequest, ApprovalService, ErrorCategory};
22use adk_kernel::KernelError;
23use adk_kernel::channels::{
24    ChannelAnswer, ChannelBinding, ChannelBindingStore, ChannelGateway, ChannelInbound,
25    ChannelNotice, DecisionCard, StopNotice,
26};
27use async_trait::async_trait;
28use chrono::{DateTime, FixedOffset, Utc};
29use serde_json::{Value, json};
30use tokio::sync::mpsc;
31use tokio::task::JoinHandle;
32use tokio::time::Instant;
33
34#[cfg(any(feature = "whatsapp", feature = "slack", feature = "discord", feature = "teams"))]
35pub(crate) use super::telegram::wire::parse_callback;
36pub(crate) use super::telegram::wire::{
37    ANSWER_NOT_TAKEN, Heading, MESSAGE_NOT_TAKEN, callback_data, chat_images, heading, hh_mm,
38    is_hidden, is_invisible, split,
39};
40use crate::answers::{AnswerLog, AnswerRecord, SURFACE_AUDIT_DECIDE};
41use crate::origin::{Origin, SurfaceKind, Via};
42use crate::project::humanize;
43use crate::rules::{Answer, Risk};
44use crate::words;
45
46/// The longest text taken from a person, in characters.
47const MAX_INBOUND_CHARS: usize = 4096;
48/// The first wait before a paired account's update is taken again.
49const MIN_BACKOFF: Duration = Duration::from_secs(1);
50/// How many times a paired account's update is tried while the gateway's failure on it may
51/// clear, before it is dropped and the person told.
52const UPDATE_ATTEMPTS: u32 = 5;
53/// The longest rate limit a send waits out; a longer one fails the send.
54#[cfg(any(feature = "slack", feature = "discord", feature = "matrix", feature = "teams"))]
55pub(crate) const MAX_RATE_LIMIT_WAIT: Duration = Duration::from_secs(30);
56/// How many times one send is tried while the platform rate-limits it.
57pub(crate) const RATE_LIMIT_ATTEMPTS: u32 = 3;
58/// How long any call to a platform may take.
59pub(crate) const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
60
61// ---------------------------------------------------------------------------
62// Text
63// ---------------------------------------------------------------------------
64
65/// A person's text as the gateway gets it (S-I6): the characters a chat app shows as
66/// nothing dropped, at most 4096 characters, trimmed. `None` when nothing is left.
67pub(crate) fn clean_inbound(text: &str) -> Option<String> {
68    let text: String = text.chars().filter(|c| !is_invisible(*c)).take(MAX_INBOUND_CHARS).collect();
69    let text = text.trim();
70    (!text.is_empty()).then(|| text.to_string())
71}
72
73/// Text from an agent, a tool or a person without hidden characters, trimmed (S-I9).
74pub(crate) fn clean_outbound(text: &str) -> String {
75    text.chars().filter(|c| !is_hidden(*c)).collect::<String>().trim().to_string()
76}
77
78/// `text` in pieces of at most `max` characters, nothing lost and nothing repeated; empty
79/// pieces are dropped.
80pub(crate) fn chunks(text: &str, max: usize) -> Vec<String> {
81    // `split` counts UTF-16 units, at least as many as characters.
82    split(&clean_outbound(text), max).into_iter().filter(|chunk| !chunk.trim().is_empty()).collect()
83}
84
85/// `home` when it is an `http` or `https` address, the only kind a card links to.
86pub(crate) fn web_home(home: Option<&str>) -> Option<&str> {
87    home.filter(|home| home.starts_with("https://") || home.starts_with("http://"))
88}
89
90/// `text` cut to `max` characters, with `…` when it was longer.
91pub(crate) fn truncate(text: &str, max: usize) -> String {
92    if text.chars().count() <= max {
93        return text.to_string();
94    }
95    let mut cut: String = text.chars().take(max.saturating_sub(1)).collect();
96    cut.push('…');
97    cut
98}
99
100// ---------------------------------------------------------------------------
101// The chat screen's words
102// ---------------------------------------------------------------------------
103
104/// A piece of a line, which each platform renders in its own markup.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub(crate) enum Piece {
107    /// Text that may come from a model, a tool or a person: escaped by the platform (S-I9).
108    Plain(String),
109    /// A heading, escaped too.
110    Bold(String),
111    /// A command the person types, such as `adk-rust pair accept ABCD-2345`: the gateway's
112    /// own words, shown as code.
113    Code(String),
114    /// "Open in home", linking to an `http` or `https` address.
115    Link {
116        /// The address.
117        url: String,
118        /// The words.
119        label: String,
120    },
121}
122
123/// A message in the chat screen's words (spec 3.3 §5.3, §8): its lines.
124#[derive(Debug, Clone, Default, PartialEq, Eq)]
125pub(crate) struct Words {
126    pub(crate) lines: Vec<Vec<Piece>>,
127}
128
129impl Words {
130    fn line(mut self, pieces: Vec<Piece>) -> Self {
131        self.lines.push(pieces);
132        self
133    }
134
135    fn plain(text: impl Into<String>) -> Self {
136        Self::default().line(vec![Piece::Plain(text.into())])
137    }
138
139    /// `sentence`, then "Open in home" linking to `home` when it is a web address.
140    fn with_home(sentence: &str, home: Option<&str>) -> Self {
141        let words = Self::plain(sentence);
142        match web_home(home) {
143            Some(url) => words.line(vec![Piece::Link {
144                url: url.to_string(),
145                label: words::OPEN_IN_HOME.to_string(),
146            }]),
147            None => words,
148        }
149    }
150
151    /// The link the message carries, if any.
152    pub(crate) fn link(&self) -> Option<(&str, &str)> {
153        self.lines.iter().flatten().find_map(|piece| match piece {
154            Piece::Link { url, label } => Some((url.as_str(), label.as_str())),
155            _ => None,
156        })
157    }
158
159    /// The message without its link line.
160    #[cfg(any(feature = "slack", feature = "discord", feature = "matrix", feature = "teams"))]
161    pub(crate) fn without_link(&self) -> Self {
162        let lines = self
163            .lines
164            .iter()
165            .filter(|line| !line.iter().all(|piece| matches!(piece, Piece::Link { .. })))
166            .cloned()
167            .collect();
168        Self { lines }
169    }
170
171    /// The message as plain text, each piece as it reads, a link as "Open in home: url".
172    #[cfg(any(feature = "slack", feature = "matrix", feature = "teams", test))]
173    pub(crate) fn text(&self) -> String {
174        self.render(|piece| match piece {
175            Piece::Plain(text) | Piece::Bold(text) | Piece::Code(text) => text.clone(),
176            Piece::Link { url, label } => format!("{label}: {url}"),
177        })
178    }
179
180    /// The message with each piece rendered by `render`, its lines joined by newlines.
181    pub(crate) fn render(&self, mut render: impl FnMut(&Piece) -> String) -> String {
182        self.lines
183            .iter()
184            .map(|line| line.iter().map(&mut render).collect::<String>())
185            .collect::<Vec<_>>()
186            .join("\n")
187    }
188}
189
190/// An answer a card offers, as a button: the card's own words for it and the data it
191/// carries back, `y:` or `n:`, the version and the decision.
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub(crate) struct Button {
194    pub(crate) answer: ChannelAnswer,
195    pub(crate) label: &'static str,
196    pub(crate) data: String,
197}
198
199/// The buttons of `card`, one for each answer it offers and no others; empty when an answer
200/// does not fit a button, so the card is answered in the home.
201pub(crate) fn buttons(card: &DecisionCard) -> Vec<Button> {
202    let buttons: Option<Vec<Button>> = card
203        .answers
204        .iter()
205        .map(|answer| {
206            callback_data(*answer, &card.decision, card.version).map(|data| Button {
207                answer: *answer,
208                // The card's own words: "Don't add" on a suggested agent (spec 3.3 §7.2).
209                label: card.label(*answer),
210                data,
211            })
212        })
213        .collect();
214    buttons.unwrap_or_default()
215}
216
217/// A decision card as the chat screen of spec 3.3 §5.3 draws it: "Waiting for you · since
218/// 18:00", the heading, the kernel's masked summary when a route wrote one, "Finance · Medium
219/// risk", why it is answered in the home when it offers no button, and "Open in home".
220/// Nothing of the call's arguments is added to what the kernel's card carries (S-I5).
221pub(crate) fn card_words(
222    card: &DecisionCard,
223    heading: &Heading,
224    offset: Option<FixedOffset>,
225) -> Words {
226    let mut words = Words::plain(format!(
227        "{} · {}",
228        words::WAITING_FOR_YOU,
229        words::since(&hh_mm(card.asked_at, offset))
230    ));
231    if !heading.title.trim().is_empty() {
232        words = words.line(vec![Piece::Bold(clean_outbound(&heading.title))]);
233    }
234    if let Some(detail) = &heading.detail {
235        words = words.line(vec![Piece::Plain(clean_outbound(detail))]);
236    }
237    words = words.line(vec![Piece::Plain(format!(
238        "{} · {}",
239        clean_outbound(&humanize(&card.agent)),
240        Risk::from(card.risk).words()
241    ))]);
242    if card.answers.is_empty() {
243        words = words.line(vec![Piece::Plain(words::NEEDS_A_SCREEN.to_string())]);
244    } else if buttons(card).is_empty() {
245        // The decision's id is too long for a button: it is answered in the home.
246        words = words.line(vec![Piece::Plain(ChannelNotice::DecideInHome { home: None }.text())]);
247    }
248    if let Some(url) = web_home(card.home.as_deref()) {
249        words = words.line(vec![Piece::Link {
250            url: url.to_string(),
251            label: words::OPEN_IN_HOME.to_string(),
252        }]);
253    }
254    words
255}
256
257/// "All agents stopped. Use Resume all in the home app." (spec 3.3 §5.3, S-I10).
258pub(crate) fn stopped_words(notice: &StopNotice) -> Words {
259    Words::with_home(words::ALL_AGENTS_STOPPED_RESUME_IN_HOME, notice.home.as_deref())
260}
261
262/// A notice in the words of the chat screen (spec 3.3 §5.3, §8), every time at `offset`.
263/// `replying` is set when the message answers the card it is about, so a decided line need
264/// not repeat its summary.
265pub(crate) fn notice_words(
266    notice: &ChannelNotice,
267    offset: Option<FixedOffset>,
268    now: DateTime<Utc>,
269    replying: bool,
270) -> Words {
271    match notice {
272        ChannelNotice::PairingCode { code, expires_at } => Words::default().line(vec![
273            Piece::Plain("This account isn't paired yet. To pair it, run ".into()),
274            Piece::Code(format!("adk-rust pair accept {}", clean_outbound(code))),
275            Piece::Plain(format!(" where your agents run, before {}.", hh_mm(*expires_at, offset))),
276        ]),
277        ChannelNotice::PairingWaiting { expires_at } => Words::plain(format!(
278            "This account is waiting to be paired. Use the code you were sent before {}.",
279            hh_mm(*expires_at, offset)
280        )),
281        ChannelNotice::AlreadyDecided { by, said, at } => {
282            let who = by.as_deref().unwrap_or("You");
283            let line = match at {
284                Some(at) => {
285                    format!("Decided already: {who} said {said} at {}.", hh_mm(*at, offset))
286                }
287                None => format!("Decided already: {who} said {said}."),
288            };
289            Words::plain(clean_outbound(&line))
290        }
291        ChannelNotice::Decided { answer, summary } => {
292            let line = match answer {
293                ChannelAnswer::AllowOnce => format!("You allowed it once · {}", hh_mm(now, offset)),
294                ChannelAnswer::Deny => format!("You denied it · {}", hh_mm(now, offset)),
295                _ => return Words::plain(clean_outbound(&notice.text())),
296            };
297            if replying {
298                Words::plain(line)
299            } else {
300                Words::plain(line).line(vec![Piece::Plain(clean_outbound(summary))])
301            }
302        }
303        ChannelNotice::Stopped { home } => {
304            Words::with_home(words::ALL_AGENTS_STOPPED_RESUME_IN_HOME, home.as_deref())
305        }
306        ChannelNotice::DecideInHome { home } => {
307            Words::with_home(&ChannelNotice::DecideInHome { home: None }.text(), home.as_deref())
308        }
309        ChannelNotice::ResumeRefused { home } => {
310            Words::with_home(&ChannelNotice::ResumeRefused { home: None }.text(), home.as_deref())
311        }
312        other => Words::plain(clean_outbound(&other.text())),
313    }
314}
315
316// ---------------------------------------------------------------------------
317// The update in the gateway's hands
318// ---------------------------------------------------------------------------
319
320tokio::task_local! {
321    /// The update the gateway is handling, while it handles it.
322    pub(crate) static HANDLING: Arc<Handling>;
323}
324
325/// An update in the gateway's hands: whose it is and, for a pressed answer, its card.
326pub(crate) struct Handling {
327    /// The adapter's channel.
328    pub(crate) channel: &'static str,
329    /// The thread it came from.
330    pub(crate) thread: String,
331    /// The account.
332    pub(crate) account: String,
333    /// Whether the account is paired, or its pairing could not be read.
334    pub(crate) paired: bool,
335    /// Where paired accounts are kept, to name the person who answered.
336    pub(crate) bindings: Arc<dyn ChannelBindingStore>,
337    /// A pressed answer's card and decision.
338    pub(crate) press: Option<PressedCard>,
339}
340
341/// The card a pressed answer came from.
342pub(crate) struct PressedCard {
343    /// The card's message on the platform, which a notice about it replies to.
344    pub(crate) card: Option<String>,
345    /// The decision the answer is for.
346    pub(crate) decision: String,
347}
348
349impl Handling {
350    /// The update `inbound` of `channel` in `gateway`'s hands.
351    pub(crate) fn of(
352        channel: &'static str,
353        gateway: &ChannelGateway,
354        inbound: &ChannelInbound,
355        paired: bool,
356        press: Option<PressedCard>,
357    ) -> Arc<Self> {
358        Arc::new(Self {
359            channel,
360            thread: inbound.thread.clone(),
361            account: inbound.account.clone(),
362            paired,
363            bindings: Arc::clone(gateway.bindings()),
364            press,
365        })
366    }
367}
368
369/// The update of `channel` being handled for `thread`, if any.
370pub(crate) fn handling(channel: &str, thread: &str) -> Option<Arc<Handling>> {
371    HANDLING
372        .try_with(Arc::clone)
373        .ok()
374        .filter(|handling| handling.channel == channel && handling.thread == thread)
375}
376
377/// Whether a send of `channel` to `thread` waits out a rate limit: not when it answers an
378/// account that is not paired, so a stranger's flood holds up no one.
379pub(crate) fn patient(channel: &str, thread: &str) -> bool {
380    handling(channel, thread).is_none_or(|handling| handling.paired)
381}
382
383/// Whether the gateway's failure may clear by itself: a store or network outage, a timeout
384/// or a rate limit, never a refusal.
385fn may_clear(error: &KernelError) -> bool {
386    if matches!(error, KernelError::Frozen { .. }) {
387        return false;
388    }
389    match error.category() {
390        ErrorCategory::Unavailable | ErrorCategory::Timeout | ErrorCategory::RateLimited => true,
391        ErrorCategory::InvalidInput
392        | ErrorCategory::Unauthorized
393        | ErrorCategory::Forbidden
394        | ErrorCategory::NotFound
395        | ErrorCategory::Cancelled
396        | ErrorCategory::Internal
397        | ErrorCategory::Unsupported
398        | ErrorCategory::ResourceExhausted
399        | ErrorCategory::Conflict => false,
400    }
401}
402
403/// Whether `account` on `channel` is paired; `true` when its pairing could not be read, since
404/// a store's failure is not the account's doing.
405pub(crate) async fn is_paired(gateway: &ChannelGateway, channel: &str, account: &str) -> bool {
406    paired_binding(gateway, channel, account).await.map_or(true, |binding| binding.is_some())
407}
408
409/// The active binding of `account` on `channel`, or the store's error.
410pub(crate) async fn paired_binding(
411    gateway: &ChannelGateway,
412    channel: &str,
413    account: &str,
414) -> std::result::Result<Option<ChannelBinding>, ()> {
415    let id = ChannelBinding::id_for(channel, account);
416    match gateway.bindings().get_binding(&id).await {
417        Ok(binding) => Ok(binding.filter(ChannelBinding::is_active)),
418        Err(error) => {
419            tracing::debug!(channel.name = channel, error = %error, "a chat account's pairing could not be read");
420            Err(())
421        }
422    }
423}
424
425// ---------------------------------------------------------------------------
426// Handing updates over
427// ---------------------------------------------------------------------------
428
429/// One update an adapter read: what it gives the gateway, and the platform's press to
430/// acknowledge or the card it answers.
431pub(crate) struct Update<P> {
432    pub(crate) inbound: Option<ChannelInbound>,
433    pub(crate) press: Option<P>,
434}
435
436/// An adapter as [`dispatch`] drives it.
437#[async_trait]
438pub(crate) trait Taker: Send + Sync + 'static {
439    /// The platform's press.
440    type Press: Send + Sync + 'static;
441
442    /// The adapter's channel.
443    fn channel_name(&self) -> &'static str;
444
445    /// Hands one update to the gateway.
446    async fn take(
447        &self,
448        gateway: &ChannelGateway,
449        update: &Update<Self::Press>,
450        paired: bool,
451    ) -> adk_kernel::Result<()>;
452
453    /// Tells a paired person that their update reached no agent.
454    async fn not_taken(&self, update: &Update<Self::Press>);
455}
456
457struct Queued<P> {
458    update: Update<P>,
459    attempts: u32,
460    ready_at: Instant,
461}
462
463impl<P> Queued<P> {
464    fn new(update: Update<P>) -> Self {
465        Self { update, attempts: 0, ready_at: Instant::now() }
466    }
467}
468
469/// Hands the updates sent on the returned sender to `gateway` through `taker` (S-I6, S-I10):
470/// whatever has arrived is taken as one batch, a paired account's updates first, each
471/// account's in the order sent. An update the gateway fails on is taken again, after 1, 2, 4
472/// and 8 seconds, only when it is a paired account's and the failure may clear, such as a
473/// store outage; that account's later updates wait with it, while the other accounts' updates
474/// are handed over. Any other failed update is dropped, and a paired person is told it was
475/// not taken. The task ends when the sender is dropped and nothing waits.
476pub(crate) fn dispatch<T: Taker>(
477    taker: Arc<T>,
478    gateway: ChannelGateway,
479) -> (mpsc::UnboundedSender<Update<T::Press>>, JoinHandle<()>) {
480    let (sender, mut receiver) = mpsc::unbounded_channel::<Update<T::Press>>();
481    let task = tokio::spawn(async move {
482        let mut queue: Vec<Queued<T::Press>> = Vec::new();
483        let mut open = true;
484        loop {
485            if queue.is_empty() {
486                if !open {
487                    return;
488                }
489                match receiver.recv().await {
490                    Some(update) => queue.push(Queued::new(update)),
491                    None => return,
492                }
493            }
494            while let Ok(update) = receiver.try_recv() {
495                queue.push(Queued::new(update));
496            }
497            queue = take_batch(taker.as_ref(), &gateway, queue).await;
498            let Some(next) = queue.iter().map(|queued| queued.ready_at).min() else { continue };
499            if open {
500                // An update that arrives meanwhile is handed over at once.
501                tokio::select! {
502                    () = tokio::time::sleep_until(next) => {}
503                    received = receiver.recv() => match received {
504                        Some(update) => queue.push(Queued::new(update)),
505                        None => open = false,
506                    },
507                }
508            } else {
509                tokio::time::sleep_until(next).await;
510            }
511        }
512    });
513    (sender, task)
514}
515
516/// Takes one batch, as [`dispatch`] describes; returns the updates to take again.
517async fn take_batch<T: Taker>(
518    taker: &T,
519    gateway: &ChannelGateway,
520    queue: Vec<Queued<T::Press>>,
521) -> Vec<Queued<T::Press>> {
522    let now = Instant::now();
523    let mut batch = Vec::with_capacity(queue.len());
524    for queued in queue {
525        let paired = match &queued.update.inbound {
526            Some(inbound) => is_paired(gateway, taker.channel_name(), &inbound.account).await,
527            None => false,
528        };
529        batch.push((queued, paired));
530    }
531    // Stable: a paired account's updates first, each account's in the order sent.
532    batch.sort_by_key(|(_, paired)| !*paired);
533    let mut held: HashSet<String> = HashSet::new();
534    let mut kept = Vec::new();
535    for (mut queued, paired) in batch {
536        let account = queued.update.inbound.as_ref().map(|inbound| inbound.account.clone());
537        if account.as_ref().is_some_and(|account| held.contains(account)) {
538            kept.push(queued);
539            continue;
540        }
541        if queued.ready_at > now {
542            held.extend(account);
543            kept.push(queued);
544            continue;
545        }
546        let Err(error) = taker.take(gateway, &queued.update, paired).await else { continue };
547        queued.attempts += 1;
548        let attempt = queued.attempts;
549        if paired && may_clear(&error) && attempt < UPDATE_ATTEMPTS {
550            tracing::warn!(channel.name = taker.channel_name(), error = %error, attempt, "the gateway could not take a chat update; taking it again");
551            queued.ready_at = Instant::now() + MIN_BACKOFF * 2u32.pow(attempt - 1);
552            held.extend(account);
553            kept.push(queued);
554            continue;
555        }
556        tracing::warn!(channel.name = taker.channel_name(), error = %error, attempt, "the gateway could not take a chat update; dropping it");
557        if paired {
558            taker.not_taken(&queued.update).await;
559        }
560    }
561    kept
562}
563
564/// Aborts a task when dropped, so a stopped connection stops what it started.
565pub(crate) struct AbortOnDrop(pub(crate) JoinHandle<()>);
566
567impl Drop for AbortOnDrop {
568    fn drop(&mut self) {
569        self.0.abort();
570    }
571}
572
573/// A running chat adapter: its connection to the platform, or its webhook's handing over
574/// (spec 3.5 §10 X12). Dropping it stops the adapter.
575///
576/// # Example
577///
578/// ```rust,no_run
579/// use adk_surface::channels::ChannelConnection;
580///
581/// async fn stop<E: std::fmt::Debug>(connection: ChannelConnection<E>) {
582///     connection.stop();
583///     assert!(connection.join().await.is_ok());
584/// }
585/// ```
586pub struct ChannelConnection<E> {
587    task: Option<JoinHandle<std::result::Result<(), E>>>,
588}
589
590impl<E> fmt::Debug for ChannelConnection<E> {
591    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
592        f.debug_struct("ChannelConnection").field("running", &!self.is_finished()).finish()
593    }
594}
595
596impl<E: Send + 'static> ChannelConnection<E> {
597    pub(crate) fn spawn(
598        future: impl Future<Output = std::result::Result<(), E>> + Send + 'static,
599    ) -> Self {
600        Self { task: Some(tokio::spawn(future)) }
601    }
602}
603
604impl<E> ChannelConnection<E> {
605    /// Stops the adapter. The gateway it was started with is dropped with it, so its replies
606    /// and cards stop too unless the caller kept a handle.
607    pub fn stop(&self) {
608        if let Some(task) = &self.task {
609            task.abort();
610        }
611    }
612
613    /// Whether the adapter stopped: stopped, or ended by a refused token.
614    pub fn is_finished(&self) -> bool {
615        self.task.as_ref().is_none_or(JoinHandle::is_finished)
616    }
617
618    /// Waits for the adapter to stop.
619    ///
620    /// # Errors
621    ///
622    /// Returns the platform's error when it refused the adapter's token for good; a stopped
623    /// adapter ends with `Ok`.
624    pub async fn join(mut self) -> std::result::Result<(), E> {
625        let Some(task) = self.task.take() else { return Ok(()) };
626        match task.await {
627            Ok(result) => result,
628            Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
629            Err(_) => Ok(()),
630        }
631    }
632}
633
634impl<E> Drop for ChannelConnection<E> {
635    fn drop(&mut self) {
636        if let Some(task) = &self.task {
637            task.abort();
638        }
639    }
640}
641
642// ---------------------------------------------------------------------------
643// Cards and answers
644// ---------------------------------------------------------------------------
645
646/// What every adapter's builder takes beyond the platform's credentials (spec 3.3 §7.1,
647/// §8.1, §11), and what it does with them.
648#[derive(Clone, Default)]
649pub(crate) struct Kit {
650    pub(crate) offset: Option<FixedOffset>,
651    pub(crate) approvals: Option<Arc<dyn ApprovalService>>,
652    pub(crate) answers: Option<Arc<dyn AnswerLog>>,
653    pub(crate) audit: Option<AuditTrail>,
654    pub(crate) card_hints: Vec<Arc<dyn crate::hints::CardHints>>,
655}
656
657impl Kit {
658    /// The heading of `card` and the card as it is offered: headed by the call in plain
659    /// words, or a feature's chat heading, with no answer when a hint marks the call as
660    /// spending money (spec 3.3 §7.1, §7.4 rule 4).
661    pub(crate) async fn prepare(&self, card: &DecisionCard) -> (Heading, DecisionCard) {
662        let request = match &self.approvals {
663            Some(approvals) => approvals.get(&card.decision).await.unwrap_or_else(|error| {
664                tracing::warn!(error = %error, "a card's decision could not be read; headed by its summary");
665                None
666            }),
667            None => None,
668        };
669        let mut heading = heading(card, request.as_ref());
670        let mut card = card.clone();
671        // A card with images: this adapter cannot attach them, so it links to the home and
672        // never offers Allow once (spec 3.7 §8.2, board choice A17).
673        if let Some(request) = request.as_ref().filter(|request| request.id == card.decision) {
674            chat_images(request, None, &mut card, &mut heading).await;
675        }
676        if let Some(request) = request.as_ref().filter(|request| request.id == card.decision) {
677            let mut headed = false;
678            for hints in &self.card_hints {
679                let Some(hint) = hints.hint(request).await else { continue };
680                if let Some(chat) = hint.chat_heading.filter(|_| !headed) {
681                    heading.title = chat;
682                    headed = true;
683                }
684                if hint.money == Some(true) && !card.adds_agent {
685                    card.answers.clear();
686                }
687            }
688        }
689        (heading, card)
690    }
691
692    /// Before a notice to `thread` is sent: when it says an answer pressed there decided its
693    /// decision, the answer is recorded with where it was given (spec 3.3 §8.1, §11), so
694    /// neither a slow platform nor a stop loses it. Returns the pressed card's message, which
695    /// the notice replies to.
696    pub(crate) async fn before_notice(
697        &self,
698        channel: &'static str,
699        label: &'static str,
700        thread: &str,
701        notice: &ChannelNotice,
702    ) -> Option<String> {
703        let handling = handling(channel, thread)?;
704        let press = handling.press.as_ref()?;
705        if let ChannelNotice::Decided { answer, .. } = notice {
706            self.record_answer(channel, label, &handling, &press.decision, *answer).await;
707        }
708        press.card.clone()
709    }
710
711    /// Records that the person of `handling`'s account answered `decision` in `label`.
712    async fn record_answer(
713        &self,
714        channel: &str,
715        label: &str,
716        handling: &Handling,
717        decision: &str,
718        answer: ChannelAnswer,
719    ) {
720        let answer = match answer {
721            ChannelAnswer::AllowOnce => Answer::AllowOnce,
722            ChannelAnswer::Deny => Answer::Deny,
723            _ => return,
724        };
725        let id = ChannelBinding::id_for(channel, &handling.account);
726        let binding = match handling.bindings.get_binding(&id).await {
727            Ok(Some(binding)) => binding,
728            Ok(None) => return,
729            Err(error) => {
730                tracing::warn!(channel.name = channel, error = %error, "a chat answer could not be recorded");
731                return;
732            }
733        };
734        let record = AnswerRecord {
735            approval_id: decision.to_string(),
736            by: SubjectRef::human(binding.user_id),
737            via: Via { surface: SurfaceKind::Chat, origin: Origin::Chat { channel: label.into() } },
738            answer,
739            at: Utc::now(),
740        };
741        if let Some(log) = &self.answers
742            && let Err(error) = log.record(&record).await
743        {
744            tracing::warn!(channel.name = channel, error = %error, "a chat answer could not be kept in the answer log");
745        }
746        let request = match (&self.audit, &self.approvals) {
747            (Some(_), Some(approvals)) => approvals.get(decision).await.ok().flatten(),
748            _ => None,
749        };
750        let title = match &request {
751            Some(request) => crate::hints::named(&self.card_hints, request).await,
752            None => None,
753        };
754        if let Some(trail) = &self.audit
755            && let Err(error) = trail.record(answer_record(&record, request.as_ref(), title)).await
756        {
757            tracing::warn!(channel.name = channel, error = %error, "a chat answer's audit record could not be written");
758        }
759    }
760}
761
762/// The `surface.decide` record of an answer given in chat, as the engine writes its own
763/// answers' (spec 3.3 §11).
764fn answer_record(
765    record: &AnswerRecord,
766    request: Option<&ApprovalRequest>,
767    title: Option<String>,
768) -> AuditRecordDraft {
769    let decision = match record.answer {
770        Answer::Deny => AuditDecision::Rejected,
771        Answer::AllowOnce | Answer::AlwaysAllow | Answer::Edit => AuditDecision::Approved,
772    };
773    let mut draft = AuditRecordDraft::new(AuditRecordKind::Approval, SURFACE_AUDIT_DECIDE)
774        .actor(AuditActor::subject(record.by.clone()))
775        .ext("surface", serde_json::to_value(record.via.surface).unwrap_or(Value::Null))
776        .ext("origin", serde_json::to_value(&record.via.origin).unwrap_or(Value::Null))
777        .ext("approvalId", json!(record.approval_id))
778        .ext("answer", serde_json::to_value(record.answer).unwrap_or(Value::Null))
779        .ext("outcome", json!("decided"))
780        .decision(decision);
781    if let Some(request) = request {
782        draft = draft.ext("tool", json!(request.tool_name));
783        if let Some(acting) = &request.acting {
784            draft = draft.ext("actingAgent", json!(acting.agent.id.to_string()));
785        }
786        // What the call acts on, as the engine's own record names it (§8).
787        if let Some(title) = title {
788            draft = draft.ext("title", json!(title)).ext("summary", json!(request.summary));
789        }
790    }
791    draft
792}
793
794/// Implements the builder methods every adapter shares over its `kit` field.
795macro_rules! kit_builder {
796    ($adapter:literal) => {
797        /// Shows every time — "since 18:00", "07:31", a pairing code's "before 08:31" — at
798        /// `offset` east of UTC instead of in the host's time zone.
799        #[must_use]
800        pub fn utc_offset(mut self, offset: chrono::FixedOffset) -> Self {
801            self.kit.offset = Some(offset);
802            self
803        }
804
805        /// Reads each card's decision from `approvals`, the kernel's approval service, so the
806        /// card is headed by the call in plain words — "Write file", "Send email" — with a
807        /// summary an approval route wrote under it (spec 3.3 §7.1, §8). Without it, a card
808        /// is headed by the kernel's masked summary.
809        #[must_use]
810        pub fn approvals(mut self, approvals: std::sync::Arc<dyn adk_core::ApprovalService>) -> Self {
811            self.kit.approvals = Some(approvals);
812            self
813        }
814
815        #[doc = concat!("Records each answer given in ", $adapter, " in `log`, the engine's [`AnswerLog`](crate::AnswerLog), so every")]
816        #[doc = concat!("other surface shows \"You said yes in ", $adapter, " at 07:31\" (spec 3.3 §8.1). Give the log")]
817        /// the engine was built with.
818        #[must_use]
819        pub fn answer_log(mut self, log: std::sync::Arc<dyn crate::answers::AnswerLog>) -> Self {
820            self.kit.answers = Some(log);
821            self
822        }
823
824        #[doc = concat!("Writes a `surface.decide` record of each answer given in ", $adapter, " to `trail`, the")]
825        /// engine's audit trail, so an [`AuditAnswerLog`](crate::AuditAnswerLog) over the same
826        /// store finds how it was given after a restart (spec 3.3 §11).
827        #[must_use]
828        pub fn audit(mut self, trail: adk_core::audit_log::AuditTrail) -> Self {
829            self.kit.audit = Some(trail);
830            self
831        }
832
833        /// Heads a card with the chat heading a feature's [`CardHints`](crate::CardHints) give
834        /// its decision, in the order added, and offers no answer on a card a hint marks as
835        /// spending money (spec 3.3 §7.1, §7.4 rule 4). Needs [`approvals`](Self::approvals).
836        #[must_use]
837        pub fn card_hints(mut self, hints: std::sync::Arc<dyn crate::hints::CardHints>) -> Self {
838            self.kit.card_hints.push(hints);
839            self
840        }
841    };
842}
843pub(crate) use kit_builder;
844
845// ---------------------------------------------------------------------------
846// Addresses
847// ---------------------------------------------------------------------------
848
849/// Checks that `base` is an `https` address, or `http` (and `ws` with `websocket`) on
850/// loopback only, since a token travels with every call. `what` names the address in the
851/// error, such as "the Slack API address".
852pub(crate) fn checked_base(base: &str, what: &str, websocket: bool) -> Result<String, String> {
853    let base = base.trim_end_matches('/');
854    let url = reqwest::Url::parse(base)
855        .map_err(|error| format!("{what} `{base}` is not a URL: {error}"))?;
856    let secure = if websocket { "wss" } else { "https" };
857    let plain = if websocket { "ws" } else { "http" };
858    match url.scheme() {
859        scheme if scheme == secure => Ok(base.to_string()),
860        scheme if scheme == plain && is_loopback(&url) => Ok(base.to_string()),
861        scheme if scheme == plain => Err(format!(
862            "{what} `{base}` must use {secure}: the token travels with every call (plain \
863             {plain} is accepted on loopback only)"
864        )),
865        other => Err(format!("{what} `{base}` uses `{other}`: use {secure}")),
866    }
867}
868
869/// Whether `url` names this machine.
870fn is_loopback(url: &reqwest::Url) -> bool {
871    let host = url.host_str().unwrap_or_default();
872    let host = host.trim_start_matches('[').trim_end_matches(']');
873    host == "localhost"
874        || host.ends_with(".localhost")
875        || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
876}
877
878/// Checks that `token` is non-empty printable ASCII without spaces, as every platform's
879/// tokens are, so it can travel in a header. `what` names it in the error.
880pub(crate) fn checked_token(token: &str, what: &str) -> Result<(), String> {
881    if token.is_empty() || !token.bytes().all(|b| b.is_ascii_graphic()) {
882        return Err(format!("{what} is empty or malformed: copy it again from the platform"));
883    }
884    Ok(())
885}
886
887#[cfg(test)]
888mod tests {
889    use adk_core::{
890        ActingContext, AgentPrincipal, ApprovalPolicy, ApprovalRisk, ApprovalScope,
891        ApproverSelector, ToolConfirmationRequest,
892    };
893
894    use super::*;
895
896    fn utc() -> Option<FixedOffset> {
897        FixedOffset::east_opt(0)
898    }
899
900    fn card(risk: ApprovalRisk) -> DecisionCard {
901        let call =
902            ToolConfirmationRequest::new("send_email", json!({ "to": "client@example.com" }));
903        let request = ApprovalRequest::new(
904            "apr_1",
905            ApprovalScope::new("adk-rust", "ana", "s1"),
906            &call,
907            ApprovalPolicy::new([ApproverSelector::group("operator")]),
908        )
909        .with_summary("Send the invoice to client@example.com")
910        .with_risk(risk)
911        .with_acting(ActingContext::new(AgentPrincipal::derived("adk-rust", "finance")));
912        DecisionCard::from_request(&request, Some("https://home.example/ui/"))
913    }
914
915    #[test]
916    fn a_card_reads_as_the_chat_screen_and_carries_no_argument() {
917        let card = card(ApprovalRisk::Medium);
918        let words = card_words(&card, &heading(&card, None), utc());
919        let asked = hh_mm(card.asked_at, utc());
920        assert_eq!(
921            words.text(),
922            format!(
923                "Waiting for you · since {asked}\nSend the invoice to […]\nFinance · Medium \
924                 risk\nOpen in home: https://home.example/ui/"
925            )
926        );
927        assert!(!words.text().contains("client@example.com"));
928        assert_eq!(
929            buttons(&card),
930            [
931                Button {
932                    answer: ChannelAnswer::AllowOnce,
933                    label: "Allow once",
934                    data: format!("y:{}:apr_1", card.version)
935                },
936                Button {
937                    answer: ChannelAnswer::Deny,
938                    label: "Deny",
939                    data: format!("n:{}:apr_1", card.version)
940                },
941            ]
942        );
943        assert_eq!(words.link(), Some(("https://home.example/ui/", "Open in home")));
944        #[cfg(any(feature = "slack", feature = "discord", feature = "matrix", feature = "teams"))]
945        assert!(words.without_link().link().is_none());
946        let high = self::card(ApprovalRisk::High);
947        let words = card_words(&high, &heading(&high, None), utc());
948        assert!(buttons(&high).is_empty());
949        assert!(words.text().contains(words::NEEDS_A_SCREEN), "{}", words.text());
950    }
951
952    /// A chat answer is on record with the item its call acts on and the card's summary, as
953    /// the engine records its own answers (spec 3.3 §8, §11).
954    #[test]
955    fn a_chat_answer_names_the_item_a_hint_names() {
956        let call = ToolConfirmationRequest::new("verb_snooze", json!({ "item": "news-digest" }));
957        let request = ApprovalRequest::new(
958            "apr_1",
959            ApprovalScope::new("adk-rust", "ana", "s1"),
960            &call,
961            ApprovalPolicy::new([ApproverSelector::group("operator")]),
962        )
963        .with_summary("Move News digest to 19:00");
964        let given = AnswerRecord {
965            approval_id: "apr_1".into(),
966            by: SubjectRef::human("ana"),
967            via: Via {
968                surface: SurfaceKind::Chat,
969                origin: Origin::Chat { channel: "Slack".into() },
970            },
971            answer: Answer::Deny,
972            at: Utc::now(),
973        };
974        let named = answer_record(&given, Some(&request), Some("News digest".into()));
975        assert_eq!(
976            (named.ext.get("title"), named.ext.get("summary")),
977            (Some(&json!("News digest")), Some(&json!("Move News digest to 19:00")))
978        );
979        let unnamed = answer_record(&given, Some(&request), None);
980        assert_eq!((unnamed.ext.get("title"), unnamed.ext.get("summary")), (None, None));
981    }
982
983    #[test]
984    fn invisible_characters_never_reach_the_agent() {
985        assert_eq!(
986            clean_inbound("pay\u{200B}ment\u{202E} now\u{E0041} "),
987            Some("payment now".into())
988        );
989        assert_eq!(clean_inbound("\u{200F}\u{FEFF} "), None);
990        assert_eq!(clean_inbound(&"x".repeat(5000)).unwrap().chars().count(), MAX_INBOUND_CHARS);
991        assert_eq!(chunks("  Done.\u{202E}\n ", 10), ["Done."]);
992        assert!(chunks(" \u{200E} ", 10).is_empty());
993    }
994
995    #[test]
996    fn addresses_and_tokens_are_checked() {
997        assert!(checked_base("https://slack.com/api/", "x", false).is_ok());
998        assert!(checked_base("http://127.0.0.1:9", "x", false).is_ok());
999        assert!(checked_base("http://example.com", "x", false).is_err());
1000        assert!(checked_base("ws://[::1]:9/socket", "x", true).is_ok());
1001        assert!(checked_base("ws://example.com/socket", "x", true).is_err());
1002        assert!(checked_base("wss://example.com/socket", "x", true).is_ok());
1003        assert!(checked_token("xoxb-1-abc", "x").is_ok());
1004        for bad in ["", "a b", "a\nb", "é"] {
1005            assert!(checked_token(bad, "x").is_err(), "{bad:?}");
1006        }
1007        assert_eq!(truncate("abcdef", 4), "abc…");
1008        assert_eq!(truncate("abc", 4), "abc");
1009    }
1010}