Skip to main content

adk_surface/channels/telegram/
mod.rs

1//! The Telegram adapter (spec 3.3 §5.3; §13 decisions 1–3).
2
3mod api;
4pub(super) mod wire;
5
6use std::collections::{BTreeSet, HashMap, HashSet};
7use std::fmt;
8use std::sync::Arc;
9use std::time::Duration;
10
11use adk_core::audit_log::{
12    AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditTrail,
13};
14use adk_core::principal::SubjectRef;
15use adk_core::{AdkError, ApprovalRequest, ApprovalService, ErrorCategory, ErrorComponent};
16use adk_kernel::KernelError;
17use adk_kernel::channels::{
18    ChannelAnswer, ChannelBinding, ChannelBindingStore, ChannelGateway, ChannelInbound,
19    ChannelNotice, ChannelSink, DecisionCard, InboundBody, InboundOutcome, StopNotice,
20};
21use async_trait::async_trait;
22use chrono::{FixedOffset, Utc};
23use serde_json::{Value, json};
24use tokio::task::JoinHandle;
25
26use crate::answers::{AnswerLog, AnswerRecord, SURFACE_AUDIT_DECIDE};
27use crate::error::{Result, SurfaceError};
28use crate::origin::{Origin, SurfaceKind, Via};
29use crate::rules::Answer;
30use crate::words;
31use api::BotApi;
32use wire::{Outgoing, Parsed, Press};
33
34/// The channel the Telegram adapter serves, as the kernel names it: pairings, thread
35/// sessions and `kernel.channel` audit records carry it (spec 3.3 §10 K1).
36pub const TELEGRAM_CHANNEL: &str = "telegram";
37
38/// Telegram as a person reads it, in "You said yes in Telegram at 07:31" (spec 3.3 §8.1).
39pub const TELEGRAM: &str = "Telegram";
40
41const DEFAULT_API_BASE: &str = "https://api.telegram.org";
42/// How long one `getUpdates` call waits for an update.
43const DEFAULT_POLL_TIMEOUT: Duration = Duration::from_secs(25);
44/// How long any other call may take.
45const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
46const MIN_BACKOFF: Duration = Duration::from_secs(1);
47const MAX_BACKOFF: Duration = Duration::from_secs(60);
48/// How many times a paired account's update is tried while the gateway's failure on it may
49/// clear, before it is dropped and the person told.
50const UPDATE_ATTEMPTS: u32 = 5;
51
52tokio::task_local! {
53    /// The update the gateway is handling, while it handles it.
54    static HANDLING: Arc<Handling>;
55}
56
57/// An update in the gateway's hands: whose it is and, for a pressed answer, its card.
58struct Handling {
59    /// The private chat it came from, which is the account's own.
60    thread: String,
61    /// The account.
62    account: String,
63    /// Whether the account is paired, or its pairing could not be read. A rate limit on what
64    /// is sent to an account that is not paired is never waited out.
65    paired: bool,
66    /// Where paired accounts are kept, to name the person who answered.
67    bindings: Arc<dyn ChannelBindingStore>,
68    /// A pressed answer's card and decision.
69    press: Option<PressedCard>,
70}
71
72/// The card a pressed answer came from.
73struct PressedCard {
74    /// The card's message.
75    message: Option<i64>,
76    /// The decision the answer is for.
77    decision: String,
78}
79
80/// What the polling did with the updates Telegram has not yet been told were taken.
81#[derive(Default)]
82struct Reads {
83    /// Updates taken or dropped above the offset Telegram was last given.
84    handled: BTreeSet<i64>,
85    /// How many times the gateway failed on each update that is read again.
86    failures: HashMap<i64, u32>,
87}
88
89impl Reads {
90    /// Update `id` was taken, or dropped: it is not handed over again.
91    fn done(&mut self, id: i64) {
92        self.handled.insert(id);
93        self.failures.remove(&id);
94    }
95
96    /// The gateway failed on update `id` once more; returns how many times it failed.
97    fn failed(&mut self, id: i64) -> u32 {
98        let failures = self.failures.entry(id).or_default();
99        *failures += 1;
100        *failures
101    }
102
103    /// The offset telling Telegram that `updates` were taken, up to the first one read again.
104    fn acknowledged(&mut self, updates: &[Value]) -> Option<i64> {
105        let mut ids: Vec<i64> =
106            updates.iter().filter_map(|update| update.get("update_id")?.as_i64()).collect();
107        ids.sort_unstable();
108        let mut next = None;
109        for id in ids {
110            if !self.handled.remove(&id) {
111                break;
112            }
113            next = Some(id + 1);
114        }
115        next
116    }
117}
118
119/// Whether the gateway's failure may clear by itself: a store or network outage, a timeout
120/// or a rate limit, never a refusal.
121fn may_clear(error: &KernelError) -> bool {
122    if matches!(error, KernelError::Frozen { .. }) {
123        return false;
124    }
125    match error.category() {
126        ErrorCategory::Unavailable | ErrorCategory::Timeout | ErrorCategory::RateLimited => true,
127        ErrorCategory::InvalidInput
128        | ErrorCategory::Unauthorized
129        | ErrorCategory::Forbidden
130        | ErrorCategory::NotFound
131        | ErrorCategory::Cancelled
132        | ErrorCategory::Internal
133        | ErrorCategory::Unsupported
134        | ErrorCategory::ResourceExhausted
135        | ErrorCategory::Conflict => false,
136    }
137}
138
139/// Whether `account` is paired; `true` when its pairing could not be read, since a store's
140/// failure is not the account's doing.
141async fn is_paired(gateway: &ChannelGateway, account: &str) -> bool {
142    let id = ChannelBinding::id_for(TELEGRAM_CHANNEL, account);
143    match gateway.bindings().get_binding(&id).await {
144        Ok(binding) => binding.is_some_and(|binding| binding.is_active()),
145        Err(error) => {
146            tracing::debug!(error = %error, "a telegram account's pairing could not be read");
147            true
148        }
149    }
150}
151
152/// Why the Telegram adapter could not talk to Telegram (spec 3.3 §5.3).
153///
154/// Never carries the bot token. Converts into [`AdkError`] with a `surface.telegram.*` code
155/// and provider `telegram`.
156///
157/// # Example
158///
159/// ```rust
160/// use adk_surface::channels::TelegramError;
161///
162/// let error = TelegramError::Unauthorized;
163/// assert_eq!(error.code(), "surface.telegram.unauthorized");
164/// assert!(error.to_string().contains("TELEGRAM_BOT_TOKEN"));
165/// ```
166#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
167#[non_exhaustive]
168pub enum TelegramError {
169    /// Telegram refused the bot token.
170    #[error(
171        "Telegram refused the bot token: check TELEGRAM_BOT_TOKEN, or ask @BotFather for a new one"
172    )]
173    Unauthorized,
174    /// Another process reads the bot's updates, or the bot has a webhook.
175    #[error(
176        "another process reads this bot's updates, or the bot has a webhook: stop the other \
177         process or delete the webhook (`deleteWebhook`); the adapter keeps trying"
178    )]
179    Conflict,
180    /// Telegram asked the bot to slow down for longer than the adapter waits.
181    #[error("Telegram asked to wait {retry_after} s before {method}: the bot is sending too much")]
182    RateLimited {
183        /// The Bot API method.
184        method: String,
185        /// How long Telegram asked to wait, in seconds.
186        retry_after: u64,
187    },
188    /// Telegram refused the call, such as a chat that blocked the bot.
189    #[error("Telegram refused {method} ({code}): {description}")]
190    Refused {
191        /// The Bot API method.
192        method: String,
193        /// Telegram's error code.
194        code: i64,
195        /// Telegram's description.
196        description: String,
197    },
198    /// Telegram could not be reached.
199    #[error(
200        "Telegram could not be reached for {method}: {reason}; check the network and the API \
201         address"
202    )]
203    Unreachable {
204        /// The Bot API method.
205        method: String,
206        /// What failed.
207        reason: String,
208    },
209    /// Telegram's answer was not the Bot API's JSON.
210    #[error("Telegram's answer to {method} could not be read: {reason}")]
211    InvalidResponse {
212        /// The Bot API method.
213        method: String,
214        /// What was wrong with it.
215        reason: String,
216    },
217}
218
219impl TelegramError {
220    /// The error code: `surface.telegram.unauthorized`, `.conflict`, `.rate_limited`,
221    /// `.refused`, `.unreachable` or `.invalid_response`.
222    pub fn code(&self) -> &'static str {
223        match self {
224            Self::Unauthorized => "surface.telegram.unauthorized",
225            Self::Conflict => "surface.telegram.conflict",
226            Self::RateLimited { .. } => "surface.telegram.rate_limited",
227            Self::Refused { .. } => "surface.telegram.refused",
228            Self::Unreachable { .. } => "surface.telegram.unreachable",
229            Self::InvalidResponse { .. } => "surface.telegram.invalid_response",
230        }
231    }
232}
233
234impl From<TelegramError> for AdkError {
235    fn from(error: TelegramError) -> Self {
236        let category = match &error {
237            TelegramError::Unauthorized => ErrorCategory::Unauthorized,
238            TelegramError::Conflict => ErrorCategory::Conflict,
239            TelegramError::RateLimited { .. } => ErrorCategory::RateLimited,
240            TelegramError::Refused { code: 403, .. } => ErrorCategory::Forbidden,
241            TelegramError::Refused { code: 400, .. } => ErrorCategory::InvalidInput,
242            TelegramError::Refused { .. } | TelegramError::Unreachable { .. } => {
243                ErrorCategory::Unavailable
244            }
245            TelegramError::InvalidResponse { .. } => ErrorCategory::Internal,
246        };
247        AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
248            .with_provider("telegram")
249    }
250}
251
252impl From<TelegramError> for KernelError {
253    fn from(error: TelegramError) -> Self {
254        Self::Core(error.into())
255    }
256}
257
258/// Builds a [`TelegramAdapter`].
259pub struct TelegramAdapterBuilder {
260    token: String,
261    api_base: String,
262    poll_timeout: Duration,
263    offset: Option<FixedOffset>,
264    approvals: Option<Arc<dyn ApprovalService>>,
265    answers: Option<Arc<dyn AnswerLog>>,
266    audit: Option<AuditTrail>,
267    card_hints: Vec<Arc<dyn crate::hints::CardHints>>,
268    artifacts: Option<Arc<dyn adk_artifact::ArtifactService>>,
269}
270
271impl fmt::Debug for TelegramAdapterBuilder {
272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273        f.debug_struct("TelegramAdapterBuilder")
274            .field("api_base", &self.api_base)
275            .field("poll_timeout", &self.poll_timeout)
276            .finish_non_exhaustive()
277    }
278}
279
280impl TelegramAdapterBuilder {
281    /// The Bot API's address; defaults to `https://api.telegram.org`. Plain `http` is
282    /// accepted on loopback only (a local Bot API server, or a test double), since the token
283    /// travels in the request path.
284    #[must_use]
285    pub fn api_base(mut self, url: impl Into<String>) -> Self {
286        self.api_base = url.into();
287        self
288    }
289
290    /// How long one long poll waits for an update, at least a second; defaults to 25 s.
291    #[must_use]
292    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
293        self.poll_timeout = timeout.max(Duration::from_secs(1));
294        self
295    }
296
297    /// Shows every time — "since 18:00", "07:31", a pairing code's "before 08:31" — at
298    /// `offset` east of UTC instead of in the host's time zone, as
299    /// `SurfaceEngineBuilder::utc_offset` does. Without it, times follow the host's time zone,
300    /// daylight saving time included.
301    #[must_use]
302    pub fn utc_offset(mut self, offset: FixedOffset) -> Self {
303        self.offset = Some(offset);
304        self
305    }
306
307    /// Reads each card's decision from `approvals`, the kernel's approval service, so the card
308    /// is headed by the call in plain words — "Write file", "Send email" — as the engine heads
309    /// a chat card, with a summary an approval route wrote under it (spec 3.3 §7.1, §8).
310    /// Without it, a card is headed by the kernel's masked summary.
311    #[must_use]
312    pub fn approvals(mut self, approvals: Arc<dyn ApprovalService>) -> Self {
313        self.approvals = Some(approvals);
314        self
315    }
316
317    /// Records each answer given in Telegram in `log`, the engine's [`AnswerLog`], so every
318    /// other surface shows "You said yes in Telegram at 07:31" (spec 3.3 §8.1). Give the log
319    /// the engine was built with.
320    #[must_use]
321    pub fn answer_log(mut self, log: Arc<dyn AnswerLog>) -> Self {
322        self.answers = Some(log);
323        self
324    }
325
326    /// Writes a `surface.decide` record of each answer given in Telegram to `trail`, the
327    /// engine's audit trail, so an [`AuditAnswerLog`](crate::AuditAnswerLog) over the same
328    /// store finds how it was given after a restart (spec 3.3 §11).
329    #[must_use]
330    pub fn audit(mut self, trail: AuditTrail) -> Self {
331        self.audit = Some(trail);
332        self
333    }
334
335    /// Heads a card with the chat heading a feature's [`CardHints`](crate::CardHints) give its
336    /// decision — "Snooze something in Coming up" — in the order added, as the engine heads a
337    /// chat card (spec 3.3 §7.1), and offers no answer on a card a hint marks as spending money
338    /// (§7.4 rule 4). Needs [`approvals`](Self::approvals): a hint reads the decision. Give the
339    /// hints the engine was built with.
340    ///
341    /// The kernel's chat gateway decides from the inbox entry alone: a feature whose hint marks
342    /// money also rates the call high when it is held, through its approval router, so a chat
343    /// answer is refused there too (owner question 30).
344    ///
345    /// # Example
346    ///
347    /// ```rust,no_run
348    /// use std::sync::Arc;
349    /// use adk_surface::channels::TelegramAdapter;
350    ///
351    /// # fn example(approvals: Arc<dyn adk_core::ApprovalService>, hints: Arc<dyn adk_surface::CardHints>) {
352    /// let telegram = TelegramAdapter::builder("123456789:AA-example")
353    ///     .approvals(approvals)
354    ///     .card_hints(hints)
355    ///     .build();
356    /// # let _ = telegram;
357    /// # }
358    /// ```
359    #[must_use]
360    pub fn card_hints(mut self, hints: Arc<dyn crate::hints::CardHints>) -> Self {
361        self.card_hints.push(hints);
362        self
363    }
364
365    /// The artifact service a held call's images live in (spec 3.7 §8.2, board choice A17): a
366    /// card for a call with an image attaches the exact image that would leave, its digest
367    /// checked, and offers Allow once beside it. Without it — or when the image cannot be
368    /// read — the card names the digest, links to the home and offers Deny only. Needs
369    /// [`approvals`](Self::approvals).
370    #[must_use]
371    pub fn artifacts(mut self, artifacts: Arc<dyn adk_artifact::ArtifactService>) -> Self {
372        self.artifacts = Some(artifacts);
373        self
374    }
375
376    /// The adapter.
377    ///
378    /// # Errors
379    ///
380    /// Returns `surface.invalid` for a malformed token, or an API address that is not
381    /// `https` (or `http` on loopback).
382    pub fn build(self) -> Result<TelegramAdapter> {
383        let api = BotApi::new(&self.api_base, &self.token).map_err(SurfaceError::Invalid)?;
384        Ok(TelegramAdapter {
385            inner: Arc::new(Inner {
386                api,
387                poll_timeout: self.poll_timeout,
388                offset: self.offset,
389                approvals: self.approvals,
390                answers: self.answers,
391                audit: self.audit,
392                card_hints: self.card_hints,
393                artifacts: self.artifacts,
394            }),
395        })
396    }
397}
398
399/// The Telegram adapter (spec 3.3 §5.3): a bot as the person's chat thread with their
400/// agents, over the kernel's channel contract (§10 K1).
401///
402/// It is the gateway's [`ChannelSink`] for the channel [`TELEGRAM_CHANNEL`], and
403/// [`start`](Self::start) reads the bot's updates by long polling and hands each to
404/// [`ChannelGateway::receive`]. The gateway decides what happens: pairing, turns, answers,
405/// stopping. The adapter keeps to what reaches Telegram and what is taken from it:
406///
407/// | Direction | What |
408/// |---|---|
409/// | Out | A card: "Waiting for you · since 18:00", the tool's name in plain words (with [`approvals`](TelegramAdapterBuilder::approvals)) above the kernel's masked summary when an approval route wrote one, or else that summary alone, the agent and the risk, a button for each answer the card offers and no others, and "Open in home" — never the call's arguments (S-I5). Agent replies as plain text, so nothing in them is read as markup (S-I9) |
410/// | In | New text messages and pressed buttons from a person in a private chat; groups, channels, bots, edits and media are ignored. Typed text never answers a decision (S-I4), loses the characters Telegram shows as nothing, and `/start` loses a deep link's payload (S-I6) |
411/// | Commands | `/stop` is listed among the bot's commands; "stop all" and `/stop` stop everything, and resuming is refused (S-I10) |
412///
413/// # Example
414///
415/// ```rust,no_run
416/// use std::sync::Arc;
417/// use adk_kernel::channels::{ChannelDoorbell, ChannelGateway, InMemoryChannelBindingStore};
418/// use adk_surface::channels::TelegramAdapter;
419///
420/// # async fn example(kernel: adk_kernel::Kernel, doorbell: Arc<ChannelDoorbell>) -> Result<(), Box<dyn std::error::Error>> {
421/// let telegram = TelegramAdapter::builder(std::env::var("TELEGRAM_BOT_TOKEN")?).build()?;
422/// let gateway = ChannelGateway::builder(Arc::new(kernel), Arc::new(InMemoryChannelBindingStore::new()))
423///     .sink(Arc::new(telegram.clone()))
424///     .home_url("http://127.0.0.1:8080/ui/")
425///     .doorbell(doorbell)
426///     .build();
427/// gateway.start().await?;
428/// gateway.ring_waiting().await?;
429/// let polling = telegram.start(gateway);
430/// polling.join().await?;
431/// # Ok(())
432/// # }
433/// ```
434#[derive(Clone)]
435pub struct TelegramAdapter {
436    inner: Arc<Inner>,
437}
438
439struct Inner {
440    api: BotApi,
441    poll_timeout: Duration,
442    offset: Option<FixedOffset>,
443    approvals: Option<Arc<dyn ApprovalService>>,
444    answers: Option<Arc<dyn AnswerLog>>,
445    audit: Option<AuditTrail>,
446    card_hints: Vec<Arc<dyn crate::hints::CardHints>>,
447    artifacts: Option<Arc<dyn adk_artifact::ArtifactService>>,
448}
449
450impl fmt::Debug for TelegramAdapter {
451    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
452        f.debug_struct("TelegramAdapter")
453            .field("channel", &TELEGRAM_CHANNEL)
454            .field("poll_timeout", &self.inner.poll_timeout)
455            .finish_non_exhaustive()
456    }
457}
458
459impl TelegramAdapter {
460    /// An adapter for the bot with `token`, from `@BotFather`.
461    pub fn builder(token: impl Into<String>) -> TelegramAdapterBuilder {
462        TelegramAdapterBuilder {
463            token: token.into(),
464            api_base: DEFAULT_API_BASE.to_string(),
465            poll_timeout: DEFAULT_POLL_TIMEOUT,
466            offset: None,
467            approvals: None,
468            answers: None,
469            audit: None,
470            card_hints: Vec::new(),
471            artifacts: None,
472        }
473    }
474
475    /// What the adapter makes of one Bot API `Update` (spec 3.3 S-I4, S-I6): a typed
476    /// message, a pressed answer, or `None` for anything the gateway is not given.
477    ///
478    /// # Example
479    ///
480    /// ```rust
481    /// use adk_kernel::channels::InboundBody;
482    /// use adk_surface::channels::TelegramAdapter;
483    ///
484    /// let telegram = TelegramAdapter::builder("123456789:AA-example").build().unwrap();
485    /// let update = serde_json::json!({
486    ///     "update_id": 1,
487    ///     "message": {
488    ///         "message_id": 31,
489    ///         "from": { "id": 4217, "is_bot": false, "first_name": "Ana" },
490    ///         "chat": { "id": 4217, "type": "private" },
491    ///         "date": 0,
492    ///         "text": "stop all",
493    ///     },
494    /// });
495    /// let inbound = telegram.inbound(&update).unwrap();
496    /// assert_eq!(inbound.body, InboundBody::Text { text: "stop all".into() });
497    /// assert_eq!((inbound.account.as_str(), inbound.thread.as_str()), ("4217", "4217"));
498    /// ```
499    pub fn inbound(&self, update: &Value) -> Option<ChannelInbound> {
500        wire::parse(update).inbound
501    }
502
503    /// Reads the bot's updates by long polling and hands each to `gateway`, which must have
504    /// this adapter as its sink, until [`TelegramPolling::stop`]. Lists `/stop` ("Stop all")
505    /// among the bot's commands first.
506    ///
507    /// The polling holds `gateway`, whose replies and cards stop when its last handle is
508    /// dropped: keep a clone for them to outlast the polling.
509    ///
510    /// An update is acknowledged to Telegram only once the gateway took it, so a restart
511    /// reads it again; the gateway starts one turn per message whatever the redeliveries. In
512    /// each batch a paired account's updates go first, each account's in the order sent, so
513    /// a stranger's messages never hold a paired person's "stop all" or answer (S-I6,
514    /// S-I10). An update the gateway fails on is read again, after 1, 2, 4 and 8 seconds,
515    /// only when it is a paired account's and the failure may clear, such as a store outage;
516    /// that account's later updates wait with it, while the other accounts' updates already
517    /// read are handed over. Any other failed update
518    /// is dropped, and a paired person is told it was not taken. Transport failures are
519    /// retried with backoff; a refused token ends the polling with
520    /// [`TelegramError::Unauthorized`].
521    pub fn start(&self, gateway: ChannelGateway) -> TelegramPolling {
522        let adapter = self.clone();
523        let task = tokio::spawn(async move { adapter.poll(&gateway).await });
524        TelegramPolling { task: Some(task) }
525    }
526
527    async fn poll(&self, gateway: &ChannelGateway) -> std::result::Result<(), TelegramError> {
528        let commands =
529            json!({ "commands": [{ "command": "stop", "description": words::STOP_ALL }] });
530        match self.inner.api.call("setMyCommands", &commands, REQUEST_TIMEOUT).await {
531            Err(TelegramError::Unauthorized) => return Err(TelegramError::Unauthorized),
532            Err(error) => tracing::warn!(error = %error, "the bot's commands could not be listed"),
533            Ok(_) => {}
534        }
535        let mut offset: Option<i64> = None;
536        let mut backoff = MIN_BACKOFF;
537        let mut conflicted = false;
538        let mut reads = Reads::default();
539        loop {
540            let mut request = json!({
541                "timeout": self.inner.poll_timeout.as_secs(),
542                "allowed_updates": ["message", "callback_query"],
543            });
544            if let Some(offset) = offset {
545                request["offset"] = json!(offset);
546            }
547            let timeout = self.inner.poll_timeout + REQUEST_TIMEOUT;
548            let updates = match self.inner.api.call("getUpdates", &request, timeout).await {
549                Ok(Value::Array(updates)) => {
550                    backoff = MIN_BACKOFF;
551                    conflicted = false;
552                    updates
553                }
554                Ok(_) => {
555                    tracing::warn!("telegram answered getUpdates without a list; retrying");
556                    tokio::time::sleep(backoff).await;
557                    backoff = (backoff * 2).min(MAX_BACKOFF);
558                    continue;
559                }
560                Err(TelegramError::Unauthorized) => return Err(TelegramError::Unauthorized),
561                Err(TelegramError::RateLimited { retry_after, .. }) => {
562                    tokio::time::sleep(Duration::from_secs(retry_after.max(1))).await;
563                    continue;
564                }
565                Err(error) => {
566                    // Two readers of one bot end each other's polls: said once, loudly.
567                    if matches!(error, TelegramError::Conflict) && !conflicted {
568                        conflicted = true;
569                        tracing::error!(error = %error, "another process reads this bot's updates");
570                    } else {
571                        tracing::warn!(error = %error, "reading telegram updates failed; retrying");
572                    }
573                    tokio::time::sleep(backoff).await;
574                    backoff = (backoff * 2).min(MAX_BACKOFF);
575                    continue;
576                }
577            };
578            let wait = self.take(gateway, &updates, &mut reads).await;
579            if let Some(next) = reads.acknowledged(&updates) {
580                offset = Some(next);
581            }
582            if let Some(wait) = wait {
583                tokio::time::sleep(wait).await;
584            }
585        }
586    }
587
588    /// Hands one batch of updates to the gateway, as [`start`](Self::start) describes.
589    /// Returns how long to wait before reading again when an update is to be read again.
590    async fn take(
591        &self,
592        gateway: &ChannelGateway,
593        updates: &[Value],
594        reads: &mut Reads,
595    ) -> Option<Duration> {
596        let mut batch = Vec::new();
597        for update in updates {
598            // Telegram numbers every update; one without a number cannot be acknowledged.
599            let Some(id) = update.get("update_id").and_then(Value::as_i64) else { continue };
600            if reads.handled.contains(&id) {
601                continue;
602            }
603            let parsed = wire::parse(update);
604            let paired = match &parsed.inbound {
605                Some(inbound) => is_paired(gateway, &inbound.account).await,
606                None => false,
607            };
608            batch.push((id, parsed, paired));
609        }
610        // Stable: a paired account's updates first, each account's in the order sent.
611        batch.sort_by_key(|(_, _, paired)| !*paired);
612        let mut held: HashSet<String> = HashSet::new();
613        let mut wait: Option<Duration> = None;
614        for (id, parsed, paired) in batch {
615            let account = parsed.inbound.as_ref().map(|inbound| inbound.account.clone());
616            if account.as_ref().is_some_and(|account| held.contains(account)) {
617                continue;
618            }
619            let Err(error) = self.handle(gateway, &parsed, paired).await else {
620                reads.done(id);
621                continue;
622            };
623            let attempt = reads.failed(id);
624            if paired && may_clear(&error) && attempt < UPDATE_ATTEMPTS {
625                tracing::warn!(update.id = id, error = %error, attempt, "the gateway could not take a telegram update; reading it again");
626                let delay = MIN_BACKOFF * 2u32.pow(attempt - 1);
627                wait = Some(wait.map_or(delay, |wait| wait.min(delay)));
628                held.extend(account);
629                continue;
630            }
631            tracing::warn!(update.id = id, error = %error, attempt, "the gateway could not take a telegram update; dropping it");
632            reads.done(id);
633            if paired {
634                self.not_taken(&parsed).await;
635            }
636        }
637        wait
638    }
639
640    /// Hands one update to the gateway. A pressed button is acknowledged, and its card
641    /// loses its buttons once the press was answered; an answer that decided is recorded with
642    /// where it was given before its confirmation is sent ([`ChannelSink::send_notice`]).
643    async fn handle(
644        &self,
645        gateway: &ChannelGateway,
646        parsed: &Parsed,
647        paired: bool,
648    ) -> adk_kernel::Result<()> {
649        let Some(mut inbound) = parsed.inbound.clone() else {
650            // A press that answers nothing, such as forged data, is only acknowledged.
651            if let Some(press) = &parsed.press {
652                self.acknowledge(press).await;
653            }
654            return Ok(());
655        };
656        // A paired account's photo, for a host that takes it; a stranger's is never
657        // downloaded (spec 3.5 §10 X12).
658        if paired
659            && let Some(photo) = &parsed.photo
660            && let Some(attachment) = self.inner.api.download(photo).await
661        {
662            inbound = inbound.with_attachments([attachment]);
663        }
664        let press = parsed.press.as_ref();
665        let card = match (&inbound.body, press) {
666            (InboundBody::Answer { decision, .. }, Some(press)) => Some(PressedCard {
667                message: press.card.as_ref().map(|(_, message)| *message),
668                decision: decision.clone(),
669            }),
670            _ => None,
671        };
672        let handling = Arc::new(Handling {
673            thread: inbound.thread.clone(),
674            account: inbound.account.clone(),
675            paired,
676            bindings: Arc::clone(gateway.bindings()),
677            press: card,
678        });
679        let outcome = HANDLING.scope(handling, gateway.receive(inbound)).await;
680        let Some(press) = press else { return outcome.map(drop) };
681        self.acknowledge(press).await;
682        if matches!(
683            outcome?,
684            InboundOutcome::Decided { .. }
685                | InboundOutcome::AlreadyDecided { .. }
686                | InboundOutcome::DecisionChanged { .. }
687                | InboundOutcome::DecisionRefused { .. }
688        ) {
689            self.clear_buttons(press).await;
690        }
691        Ok(())
692    }
693
694    /// Tells a paired person that their update reached no agent: a typed message, as a reply
695    /// to it, or a pressed answer that decided nothing, as a reply to its card.
696    async fn not_taken(&self, parsed: &Parsed) {
697        let Some(inbound) = &parsed.inbound else { return };
698        let (text, reply_to) = match &parsed.press {
699            Some(press) => (wire::ANSWER_NOT_TAKEN, press.card.as_ref().map(|(_, id)| *id)),
700            None => (wire::MESSAGE_NOT_TAKEN, inbound.message_id.parse().ok()),
701        };
702        let message = Outgoing::plain(text.to_string());
703        if let Err(error) = self.send(&inbound.thread, message, reply_to).await {
704            tracing::debug!(error = %error, "a person could not be told their update was not taken");
705        }
706    }
707
708    /// Stops the button's spinner.
709    async fn acknowledge(&self, press: &Press) {
710        let body = json!({ "callback_query_id": press.callback_id });
711        if let Err(error) = self.inner.api.call("answerCallbackQuery", &body, REQUEST_TIMEOUT).await
712        {
713            tracing::debug!(error = %error, "a pressed button could not be acknowledged");
714        }
715    }
716
717    /// Takes the buttons off an answered card, so it is not pressed again.
718    async fn clear_buttons(&self, press: &Press) {
719        let Some((chat, message)) = &press.card else { return };
720        let body = json!({
721            "chat_id": chat_id(chat),
722            "message_id": message,
723            "reply_markup": { "inline_keyboard": [] },
724        });
725        if let Err(error) =
726            self.inner.api.call("editMessageReplyMarkup", &body, REQUEST_TIMEOUT).await
727        {
728            tracing::debug!(error = %error, "an answered card's buttons could not be removed");
729        }
730    }
731
732    /// Records that `account`'s person answered `decision` in Telegram (spec 3.3 §8.1, §11).
733    async fn record_answer(
734        &self,
735        bindings: &dyn ChannelBindingStore,
736        account: &str,
737        decision: &str,
738        answer: ChannelAnswer,
739    ) {
740        let answer = match answer {
741            ChannelAnswer::AllowOnce => Answer::AllowOnce,
742            ChannelAnswer::Deny => Answer::Deny,
743            _ => return,
744        };
745        let id = ChannelBinding::id_for(TELEGRAM_CHANNEL, account);
746        let binding = match bindings.get_binding(&id).await {
747            Ok(Some(binding)) => binding,
748            Ok(None) => return,
749            Err(error) => {
750                tracing::warn!(error = %error, "a telegram answer could not be recorded");
751                return;
752            }
753        };
754        let record = AnswerRecord {
755            approval_id: decision.to_string(),
756            by: SubjectRef::human(binding.user_id),
757            via: Via {
758                surface: SurfaceKind::Chat,
759                origin: Origin::Chat { channel: TELEGRAM.into() },
760            },
761            answer,
762            at: Utc::now(),
763        };
764        if let Some(log) = &self.inner.answers
765            && let Err(error) = log.record(&record).await
766        {
767            tracing::warn!(error = %error, "a telegram answer could not be kept in the answer log");
768        }
769        // The call it answered, so the record names its tool and whose call it was (§11).
770        let request = match (&self.inner.audit, &self.inner.approvals) {
771            (Some(_), Some(approvals)) => approvals.get(decision).await.ok().flatten(),
772            _ => None,
773        };
774        let title = match &request {
775            Some(request) => crate::hints::named(&self.inner.card_hints, request).await,
776            None => None,
777        };
778        if let Some(trail) = &self.inner.audit
779            && let Err(error) = trail.record(answer_record(&record, request.as_ref(), title)).await
780        {
781            tracing::warn!(error = %error, "a telegram answer's audit record could not be written");
782        }
783    }
784
785    async fn send(
786        &self,
787        thread: &str,
788        message: Outgoing,
789        reply_to: Option<i64>,
790    ) -> adk_kernel::Result<()> {
791        let mut body = json!({
792            "chat_id": chat_id(thread),
793            "text": message.text,
794            "link_preview_options": { "is_disabled": true },
795        });
796        if message.html {
797            body["parse_mode"] = json!("HTML");
798        }
799        if let Some(keyboard) = message.keyboard {
800            body["reply_markup"] = keyboard;
801        }
802        if let Some(id) = reply_to {
803            body["reply_parameters"] =
804                json!({ "message_id": id, "allow_sending_without_reply": true });
805        }
806        // A rate limit on a reply to an account that is not paired is not waited out, so a
807        // stranger's flood holds up no one's updates.
808        let patient = HANDLING
809            .try_with(|handling| handling.paired || handling.thread != thread)
810            .unwrap_or(true);
811        if patient {
812            self.inner.api.call("sendMessage", &body, REQUEST_TIMEOUT).await?;
813        } else {
814            self.inner.api.call_once("sendMessage", &body, REQUEST_TIMEOUT).await?;
815        }
816        Ok(())
817    }
818}
819
820/// `thread` as the Bot API's `chat_id`: a number, or text for a channel's public `@name`.
821fn chat_id(thread: &str) -> Value {
822    thread.parse::<i64>().map_or_else(|_| json!(thread), |id| json!(id))
823}
824
825/// The `surface.decide` record of an answer given in Telegram, as the engine writes its own
826/// answers' (spec 3.3 §11).
827fn answer_record(
828    record: &AnswerRecord,
829    request: Option<&ApprovalRequest>,
830    title: Option<String>,
831) -> AuditRecordDraft {
832    let decision = match record.answer {
833        Answer::Deny => AuditDecision::Rejected,
834        Answer::AllowOnce | Answer::AlwaysAllow | Answer::Edit => AuditDecision::Approved,
835    };
836    let mut draft = AuditRecordDraft::new(AuditRecordKind::Approval, SURFACE_AUDIT_DECIDE)
837        .actor(AuditActor::subject(record.by.clone()))
838        .ext("surface", serde_json::to_value(record.via.surface).unwrap_or(Value::Null))
839        .ext("origin", serde_json::to_value(&record.via.origin).unwrap_or(Value::Null))
840        .ext("approvalId", json!(record.approval_id))
841        .ext("answer", serde_json::to_value(record.answer).unwrap_or(Value::Null))
842        .ext("outcome", json!("decided"))
843        .decision(decision);
844    if let Some(request) = request {
845        draft = draft.ext("tool", json!(request.tool_name));
846        if let Some(acting) = &request.acting {
847            draft = draft.ext("actingAgent", json!(acting.agent.id.to_string()));
848        }
849        // What the call acts on, as the engine's own record names it (§8).
850        if let Some(title) = title {
851            draft = draft.ext("title", json!(title)).ext("summary", json!(request.summary));
852        }
853    }
854    draft
855}
856
857#[async_trait]
858impl ChannelSink for TelegramAdapter {
859    fn channel(&self) -> &str {
860        TELEGRAM_CHANNEL
861    }
862
863    async fn send_message(&self, thread: &str, text: &str) -> adk_kernel::Result<()> {
864        for chunk in wire::plain_chunks(text) {
865            self.send(thread, Outgoing::plain(chunk), None).await?;
866        }
867        Ok(())
868    }
869
870    async fn send_decision(&self, thread: &str, card: &DecisionCard) -> adk_kernel::Result<()> {
871        let request = match &self.inner.approvals {
872            Some(approvals) => approvals.get(&card.decision).await.unwrap_or_else(|error| {
873                tracing::warn!(error = %error, "a card's decision could not be read; headed by its summary");
874                None
875            }),
876            None => None,
877        };
878        let mut heading = wire::heading(card, request.as_ref());
879        let mut card = card.clone();
880        // A feature's chat heading, as the engine heads a chat card (spec 3.3 §7.1); a call
881        // a hint marks as spending money is never answered in chat (§7.4 rule 4).
882        if let Some(request) = request.as_ref().filter(|request| request.id == card.decision) {
883            let mut headed = false;
884            for hints in &self.inner.card_hints {
885                let Some(hint) = hints.hint(request).await else { continue };
886                if let Some(chat) = hint.chat_heading.filter(|_| !headed) {
887                    heading.title = chat;
888                    headed = true;
889                }
890                if hint.money == Some(true) && !card.adds_agent {
891                    card.answers.clear();
892                }
893            }
894            // A call with an image: the exact image that would leave goes first, and Allow
895            // once only beside it (spec 3.7 §8.2, board choice A17).
896            let artifacts = self.inner.artifacts.as_deref();
897            if let Some(image) =
898                wire::chat_images(request, artifacts, &mut card, &mut heading).await
899            {
900                let sent =
901                    self.inner.api.send_photo(&chat_id(thread), &image, REQUEST_TIMEOUT).await;
902                if let Err(error) = sent {
903                    tracing::warn!(error = %error, "a card's image could not be sent; the card links to the home");
904                    card.answers.retain(|answer| *answer != ChannelAnswer::AllowOnce);
905                    let line = format!(
906                        "{} {}",
907                        crate::words::SHOW_THE_IMAGE_IN_THE_HOME,
908                        crate::evidence::short_digest(request.evidence[0].digest())
909                    );
910                    heading.detail = Some(match heading.detail.take() {
911                        Some(detail) => format!("{detail}\n{line}"),
912                        None => line,
913                    });
914                }
915            }
916        }
917        self.send(thread, wire::card(&card, &heading, self.inner.offset), None).await
918    }
919
920    async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> adk_kernel::Result<()> {
921        self.send(thread, wire::stopped(notice), None).await
922    }
923
924    /// A notice about a pressed card answers that card. The gateway says "decided" there
925    /// only once the answer decided the decision, a quorum's last answer included and its
926    /// earlier ones not; the answer is recorded with where it was given before the
927    /// confirmation is sent, so neither a slow Telegram nor a stop loses it (spec 3.3 §8.1,
928    /// §11).
929    async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> adk_kernel::Result<()> {
930        let handling =
931            HANDLING.try_with(Arc::clone).ok().filter(|handling| handling.thread == thread);
932        let press = handling.as_ref().and_then(|handling| handling.press.as_ref());
933        if let (Some(handling), Some(press), ChannelNotice::Decided { answer, .. }) =
934            (&handling, press, notice)
935        {
936            let bindings = handling.bindings.as_ref();
937            self.record_answer(bindings, &handling.account, &press.decision, *answer).await;
938        }
939        let reply_to = press.and_then(|press| press.message);
940        let message = wire::notice(notice, self.inner.offset, Utc::now(), reply_to.is_some());
941        self.send(thread, message, reply_to).await
942    }
943}
944
945/// The polling a [`TelegramAdapter::start`] runs; dropping it stops the polling.
946///
947/// # Example
948///
949/// ```rust,no_run
950/// # async fn example(telegram: adk_surface::channels::TelegramAdapter, gateway: adk_kernel::channels::ChannelGateway) {
951/// let polling = telegram.start(gateway);
952/// polling.stop();
953/// assert!(polling.join().await.is_ok());
954/// # }
955/// ```
956#[derive(Debug)]
957pub struct TelegramPolling {
958    task: Option<JoinHandle<std::result::Result<(), TelegramError>>>,
959}
960
961impl TelegramPolling {
962    /// Stops reading updates. The gateway given to [`TelegramAdapter::start`] is dropped
963    /// with the polling, so its replies and cards stop too unless the caller kept a handle.
964    pub fn stop(&self) {
965        if let Some(task) = &self.task {
966            task.abort();
967        }
968    }
969
970    /// Whether the polling ended: stopped, or ended by a refused token.
971    pub fn is_finished(&self) -> bool {
972        self.task.as_ref().is_none_or(JoinHandle::is_finished)
973    }
974
975    /// Waits for the polling to end.
976    ///
977    /// # Errors
978    ///
979    /// Returns [`TelegramError::Unauthorized`] when Telegram refused the bot token; a
980    /// stopped polling ends with `Ok`.
981    pub async fn join(mut self) -> std::result::Result<(), TelegramError> {
982        let Some(task) = self.task.take() else { return Ok(()) };
983        match task.await {
984            Ok(result) => result,
985            Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
986            Err(_) => Ok(()),
987        }
988    }
989}
990
991impl Drop for TelegramPolling {
992    fn drop(&mut self) {
993        self.stop();
994    }
995}
996
997#[cfg(test)]
998mod tests {
999    use adk_core::audit_log::AuditRecordDraft;
1000
1001    use super::*;
1002    use crate::answers::answer_of;
1003
1004    /// What the adapter writes is what `AuditAnswerLog` reads back.
1005    #[test]
1006    fn the_answer_record_is_read_back_as_given_in_telegram() {
1007        for answer in [Answer::AllowOnce, Answer::Deny] {
1008            let given = AnswerRecord {
1009                approval_id: "apr_1".into(),
1010                by: SubjectRef::human("ana"),
1011                via: Via {
1012                    surface: SurfaceKind::Chat,
1013                    origin: Origin::Chat { channel: TELEGRAM.into() },
1014                },
1015                answer,
1016                at: Utc::now(),
1017            };
1018            let draft: AuditRecordDraft = answer_record(&given, None, None);
1019            let record = draft.into_record("replica-1", 0, given.at, None);
1020            let read = answer_of(&record, "apr_1").expect("the record is an answer");
1021            assert_eq!(read, given);
1022            assert_eq!(read.via.phrase(), "in Telegram");
1023            assert!(answer_of(&record, "apr_2").is_none());
1024        }
1025    }
1026
1027    #[test]
1028    fn errors_say_what_to_do_and_keep_their_category() {
1029        let error: AdkError = TelegramError::Unauthorized.into();
1030        assert_eq!(error.code, "surface.telegram.unauthorized");
1031        assert_eq!(error.category, ErrorCategory::Unauthorized);
1032        let blocked = TelegramError::Refused {
1033            method: "sendMessage".into(),
1034            code: 403,
1035            description: "Forbidden: bot was blocked by the user".into(),
1036        };
1037        assert_eq!(AdkError::from(blocked).category, ErrorCategory::Forbidden);
1038        let limited = TelegramError::RateLimited { method: "sendMessage".into(), retry_after: 90 };
1039        assert!(AdkError::from(limited).is_retryable());
1040    }
1041
1042    #[test]
1043    fn the_builder_refuses_a_bad_token_or_address_without_echoing_the_token() {
1044        let error = TelegramAdapter::builder("123:secret")
1045            .api_base("http://example.com")
1046            .build()
1047            .unwrap_err();
1048        assert_eq!(error.code(), "surface.invalid");
1049        assert!(!error.to_string().contains("secret"), "{error}");
1050        assert!(TelegramAdapter::builder("").build().is_err());
1051        let adapter = TelegramAdapter::builder("123:secret").build().unwrap();
1052        assert!(!format!("{adapter:?}").contains("secret"));
1053        assert_eq!(adapter.channel(), "telegram");
1054    }
1055}