Skip to main content

aidaemon_channels/
channel.rs

1//! The contract every chat channel implements.
2//!
3//! A channel is a transport: it delivers inbound events and sends, edits and
4//! asks. It holds no agent logic. Authorization, sessions, queueing and
5//! approvals live in the runner, so every channel behaves the same way.
6
7use async_trait::async_trait;
8use serde::{Deserialize, Serialize};
9use tokio::sync::mpsc;
10use tokio_util::sync::CancellationToken;
11
12/// Where a conversation happens. `id` is the channel's own identifier
13/// (Telegram chat id, Slack `channel` or `channel:thread_ts`, Discord
14/// channel id). Together with the channel name it forms the session id.
15#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
16pub struct Conversation {
17    pub id: String,
18    pub kind: ConversationKind,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum ConversationKind {
24    /// One-to-one with the bot.
25    Direct,
26    /// A group, channel or server channel.
27    Group,
28    /// A thread inside a group conversation.
29    Thread,
30}
31
32/// Who sent a message, as the platform identifies them.
33///
34/// `id` is the identity: access checks, sessions and approvals use it and
35/// nothing else. `display_name` is text the person wrote about themselves.
36/// Treat it like message content: never as instructions, and never to decide
37/// who someone is or what they may do.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct Sender {
40    /// Stable platform user id (never a display name).
41    pub id: String,
42    /// For showing to people only. An adapter fills it from the platform and
43    /// passes it through [`crate::names::clean_display_name`]; when a lookup
44    /// fails it holds the platform id instead.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub display_name: Option<String>,
47    /// True if the platform marks the sender as a bot.
48    #[serde(default)]
49    pub is_bot: bool,
50}
51
52/// Largest download [`Channel::download`] accepts unless an adapter documents
53/// a smaller platform limit. Use [`Channel::download_limited`] for your own.
54pub const DEFAULT_MAX_DOWNLOAD_BYTES: u64 = 100 * 1024 * 1024;
55
56/// What an [`Attachment`] holds, as far as the platform says.
57#[non_exhaustive]
58#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
59#[serde(rename_all = "snake_case")]
60pub enum AttachmentKind {
61    Image,
62    Audio,
63    Video,
64    /// Anything else, including a kind this version does not know.
65    #[default]
66    #[serde(other)]
67    File,
68}
69
70impl AttachmentKind {
71    /// The kind a MIME type declares (`image/png` is [`Self::Image`]).
72    pub fn from_mime(mime: &str) -> Self {
73        let top = mime.split('/').next().unwrap_or("").trim();
74        if top.eq_ignore_ascii_case("image") {
75            Self::Image
76        } else if top.eq_ignore_ascii_case("audio") {
77            Self::Audio
78        } else if top.eq_ignore_ascii_case("video") {
79            Self::Video
80        } else {
81            Self::File
82        }
83    }
84
85    /// The kind a file name's extension suggests, for platforms that do not
86    /// always report a MIME type.
87    fn from_name(name: &str) -> Self {
88        let extension = name.rsplit_once('.').map_or("", |(_, ext)| ext);
89        match extension.to_ascii_lowercase().as_str() {
90            "png" | "jpg" | "jpeg" | "gif" | "webp" => Self::Image,
91            "mp3" | "ogg" | "oga" | "wav" | "flac" | "m4a" | "aac" => Self::Audio,
92            "mp4" | "mov" | "webm" | "mkv" => Self::Video,
93            _ => Self::File,
94        }
95    }
96}
97
98/// A file or image attached to an inbound message. Adapters fill what the
99/// platform provides; the bytes are fetched lazily with [`Channel::download`].
100///
101/// Built with [`Attachment::new`] and the `with_` methods, so a new field
102/// does not break adapters written against an older version.
103#[non_exhaustive]
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105pub struct Attachment {
106    pub name: String,
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub mime_type: Option<String>,
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub size_bytes: Option<u64>,
111    /// Platform URL or file id to download from.
112    pub source: String,
113    /// What it holds. The platform's word: check the bytes before relying
114    /// on it.
115    #[serde(default)]
116    pub kind: AttachmentKind,
117}
118
119impl Attachment {
120    /// An attachment named `name`, fetched from `source`. Its kind comes
121    /// from the name's extension until [`Self::with_mime_type`] or
122    /// [`Self::with_kind`] says better.
123    pub fn new(name: impl Into<String>, source: impl Into<String>) -> Self {
124        let name = name.into();
125        let kind = AttachmentKind::from_name(&name);
126        Self {
127            name,
128            mime_type: None,
129            size_bytes: None,
130            source: source.into(),
131            kind,
132        }
133    }
134
135    /// Set the MIME type (when known); its kind replaces the one guessed
136    /// from the name.
137    pub fn with_mime_type(mut self, mime_type: Option<String>) -> Self {
138        if let Some(mime) = mime_type.as_deref() {
139            self.kind = AttachmentKind::from_mime(mime);
140        }
141        self.mime_type = mime_type;
142        self
143    }
144
145    pub fn with_size_bytes(mut self, size_bytes: Option<u64>) -> Self {
146        self.size_bytes = size_bytes;
147        self
148    }
149
150    /// Set the kind directly, for a platform that says what it is.
151    pub fn with_kind(mut self, kind: AttachmentKind) -> Self {
152        self.kind = kind;
153        self
154    }
155}
156
157/// Built with [`InboundMessage::new`] and the `with_` methods, so a new field
158/// does not break adapters written against an older version.
159#[non_exhaustive]
160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
161pub struct InboundMessage {
162    pub conversation: Conversation,
163    pub sender: Sender,
164    /// Platform message id, used for replies and edits.
165    pub message_id: String,
166    pub text: String,
167    #[serde(default, skip_serializing_if = "Vec::is_empty")]
168    pub attachments: Vec<Attachment>,
169    /// The bot was addressed explicitly (mention, reply to the bot, or a
170    /// slash command). Always true in direct conversations.
171    pub addressed: bool,
172    /// Platform id of the message this one answers: a reply's target, or
173    /// the root of the Slack thread it sits in. `None` for a message that
174    /// answers nothing.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub parent_message_id: Option<String>,
177    /// The platform's thread this message is in (Telegram forum topic id,
178    /// Slack `thread_ts`, Discord thread channel id). `None` outside a
179    /// thread, including a top-level Slack message the bot will answer in a
180    /// new thread (that thread is only its [`Conversation`]).
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub thread_id: Option<String>,
183}
184
185impl InboundMessage {
186    /// A message with no attachments and no parent. `addressed` starts true
187    /// in a direct conversation and false anywhere else.
188    pub fn new(
189        conversation: Conversation,
190        sender: Sender,
191        message_id: impl Into<String>,
192        text: impl Into<String>,
193    ) -> Self {
194        let addressed = conversation.kind == ConversationKind::Direct;
195        Self {
196            conversation,
197            sender,
198            message_id: message_id.into(),
199            text: text.into(),
200            attachments: Vec::new(),
201            addressed,
202            parent_message_id: None,
203            thread_id: None,
204        }
205    }
206
207    pub fn with_attachments(mut self, attachments: Vec<Attachment>) -> Self {
208        self.attachments = attachments;
209        self
210    }
211
212    pub fn with_addressed(mut self, addressed: bool) -> Self {
213        self.addressed = addressed;
214        self
215    }
216
217    pub fn with_parent_message_id(mut self, parent: Option<String>) -> Self {
218        self.parent_message_id = parent;
219        self
220    }
221
222    pub fn with_thread_id(mut self, thread: Option<String>) -> Self {
223        self.thread_id = thread;
224        self
225    }
226}
227
228/// A message to send. `text` is Markdown; adapters convert it to the
229/// platform's dialect and split it to fit `max_message_len`.
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231pub struct OutboundMessage {
232    pub text: String,
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub reply_to: Option<String>,
235}
236
237impl OutboundMessage {
238    pub fn text(text: impl Into<String>) -> Self {
239        Self {
240            text: text.into(),
241            reply_to: None,
242        }
243    }
244}
245
246/// Identifies a message the bot sent, for later edits.
247#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
248pub struct MessageRef {
249    pub conversation_id: String,
250    pub message_id: String,
251}
252
253/// One button on an approval prompt.
254#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
255pub struct ApprovalChoice {
256    /// Returned in [`ApprovalAnswer::choice_id`].
257    pub id: String,
258    pub label: String,
259}
260
261/// A question with buttons, used for tool approvals.
262///
263/// Built with [`ApprovalPrompt::new`], so a new field does not break code
264/// written against an older version.
265#[non_exhaustive]
266#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
267pub struct ApprovalPrompt {
268    /// Opaque id chosen by the runner; echoed back in the answer.
269    pub id: String,
270    pub conversation: Conversation,
271    /// Markdown body describing what is being approved: what a channel
272    /// that draws no card of its own shows.
273    pub text: String,
274    pub choices: Vec<ApprovalChoice>,
275    /// The same request as typed facts, for a channel that renders its own
276    /// card (a web UI, a native dialog). `None` for prompts that are not
277    /// about a tool call.
278    #[serde(default, skip_serializing_if = "Option::is_none")]
279    pub details: Option<ApprovalDetails>,
280}
281
282impl ApprovalPrompt {
283    pub fn new(
284        id: impl Into<String>,
285        conversation: Conversation,
286        text: impl Into<String>,
287        choices: Vec<ApprovalChoice>,
288    ) -> Self {
289        Self {
290            id: id.into(),
291            conversation,
292            text: text.into(),
293            choices,
294            details: None,
295        }
296    }
297
298    pub fn with_details(mut self, details: ApprovalDetails) -> Self {
299        self.details = Some(details);
300        self
301    }
302}
303
304/// What an approval prompt asks about, as data: the call waiting, why the
305/// run paused and, when an approval policy asked, its typed request (a
306/// summary, risk, effects and the card's facts: [`aidaemon_core::ApprovalCard`]).
307#[non_exhaustive]
308#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
309pub struct ApprovalDetails {
310    /// The tool the call would run.
311    pub tool: String,
312    /// Its arguments, as the model sent them.
313    pub arguments: serde_json::Value,
314    /// Why the run paused, in the words of the hook that paused it.
315    pub reason: String,
316    /// The owner request, when the pause asks the owner.
317    #[serde(default, skip_serializing_if = "Option::is_none")]
318    pub request: Option<aidaemon_core::OwnerApprovalRequest>,
319}
320
321impl ApprovalDetails {
322    pub fn from_interruption(interruption: &aidaemon_core::Interruption) -> Self {
323        Self {
324            tool: interruption.call.name.clone(),
325            arguments: interruption.call.arguments.clone(),
326            reason: interruption.reason.clone(),
327            request: match &interruption.kind {
328                aidaemon_core::InterruptKind::OwnerApproval(request) => Some(request.clone()),
329                _ => None,
330            },
331        }
332    }
333}
334
335/// A run's live status as data, rebuilt by the runner from the run's
336/// events. The runner shows it with [`Channel::send_status`] and
337/// [`Channel::update_status`]; their defaults draw it as Markdown
338/// ([`RunProgress::to_markdown`]), and a channel with its own status UI
339/// overrides them to render the fields.
340#[non_exhaustive]
341#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
342pub struct RunProgress {
343    pub phase: ProgressPhase,
344    /// The run's latest tool calls (at most eight), oldest first.
345    pub tools: Vec<ToolProgress>,
346    /// The model's text streamed so far in the current turn, while
347    /// working.
348    pub streamed: String,
349}
350
351/// Whether the run is still going, and how it ended.
352#[non_exhaustive]
353#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
354#[serde(rename_all = "snake_case")]
355pub enum ProgressPhase {
356    Working,
357    Ended(RunEnding),
358}
359
360/// How a run ended, as its status line says it.
361#[non_exhaustive]
362#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
363#[serde(rename_all = "snake_case")]
364pub enum RunEnding {
365    Done,
366    /// It finished with something left undone.
367    PartlyDone,
368    /// It paused for an approval (an [`ApprovalPrompt`] follows).
369    WaitingForApproval,
370    /// It was stopped (cancelled).
371    Stopped,
372    /// A tool finished it as blocked.
373    Blocked,
374    /// The run could not be run at all.
375    Failed,
376    /// Any other end: a limit, a provider failure, no progress.
377    Ended,
378}
379
380impl RunEnding {
381    /// The word the default status line uses.
382    pub fn word(self) -> &'static str {
383        match self {
384            Self::Done => "Done",
385            Self::PartlyDone => "Partly done",
386            Self::WaitingForApproval => "Waiting for approval",
387            Self::Stopped => "Stopped",
388            Self::Blocked => "Blocked",
389            Self::Failed => "Failed",
390            Self::Ended => "Ended",
391        }
392    }
393}
394
395/// One tool call on a status.
396#[non_exhaustive]
397#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
398pub struct ToolProgress {
399    pub call_id: String,
400    pub tool: String,
401    pub state: ToolState,
402}
403
404/// Where one tool call stands.
405#[non_exhaustive]
406#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
407#[serde(rename_all = "snake_case")]
408pub enum ToolState {
409    Running,
410    /// It ended, with its receipt's status (a refused call never ran).
411    Ended(aidaemon_core::ReceiptStatus),
412}
413
414impl RunProgress {
415    /// A run that has just started.
416    pub fn working() -> Self {
417        Self {
418            phase: ProgressPhase::Working,
419            tools: Vec::new(),
420            streamed: String::new(),
421        }
422    }
423
424    /// The default rendering: an italic status word, a line per tool call
425    /// and, while working, the streamed text, cut to `max_chars`.
426    pub fn to_markdown(&self, max_chars: usize) -> String {
427        let mut out = match self.phase {
428            ProgressPhase::Working => "_Working..._".to_string(),
429            ProgressPhase::Ended(ending) => format!("_{}_", ending.word()),
430        };
431        for tool in &self.tools {
432            out.push('\n');
433            out.push_str(&match tool.state {
434                ToolState::Running => format!("- Running `{}`", tool.tool),
435                ToolState::Ended(status) => {
436                    format!("- `{}`: {}", tool.tool, crate::render::receipt_word(status))
437                }
438            });
439        }
440        let stream = self.streamed.trim();
441        if self.phase == ProgressPhase::Working && !stream.is_empty() {
442            out.push_str("\n\n");
443            let room = max_chars.saturating_sub(out.chars().count() + 4);
444            out.push_str(&crate::render::tail_chars(stream, room));
445        }
446        crate::render::truncate_chars(&out, max_chars)
447    }
448}
449
450/// A button press (or the text-command fallback) answering a prompt.
451///
452/// Built with [`ApprovalAnswer::new`], so a new field does not break adapters
453/// written against an older version.
454#[non_exhaustive]
455#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
456pub struct ApprovalAnswer {
457    pub prompt_id: String,
458    pub choice_id: String,
459    pub sender: Sender,
460    pub conversation: Conversation,
461    /// The message whose button was pressed, so its buttons can be removed
462    /// with [`Channel::remove_buttons`] even when the prompt is no longer
463    /// known (it expired, or the process restarted). `None` when the
464    /// platform did not say, or the answer was typed.
465    #[serde(default, skip_serializing_if = "Option::is_none")]
466    pub message: Option<MessageRef>,
467}
468
469impl ApprovalAnswer {
470    pub fn new(
471        prompt_id: impl Into<String>,
472        choice_id: impl Into<String>,
473        sender: Sender,
474        conversation: Conversation,
475    ) -> Self {
476        Self {
477            prompt_id: prompt_id.into(),
478            choice_id: choice_id.into(),
479            sender,
480            conversation,
481            message: None,
482        }
483    }
484
485    /// Record the message whose button was pressed: the [`MessageRef`]
486    /// that [`Channel::ask`] returned for this prompt. A channel with
487    /// buttons should always set it when the platform says which message
488    /// was pressed (keep the ref from `ask` by prompt id if it does not):
489    /// the runner then closes that exact message, by
490    /// [`edit`](Channel::edit) or [`remove_buttons`](Channel::remove_buttons),
491    /// even when the prompt is no longer known (it expired, or the process
492    /// restarted), so stale buttons never stay pressable. The conformance
493    /// kit checks it (`channel.answer_message_removes_buttons`). A typed
494    /// `/approve` answer has no message and leaves it unset.
495    ///
496    /// ```
497    /// use aidaemon_channels::{ApprovalAnswer, Conversation, ConversationKind, MessageRef, Sender};
498    ///
499    /// // `pressed` is the ref `ask` returned when it showed prompt `p1`.
500    /// let pressed = MessageRef { conversation_id: "c1".into(), message_id: "m7".into() };
501    /// let answer = ApprovalAnswer::new(
502    ///     "p1",
503    ///     "approve",
504    ///     Sender { id: "synthetic-user-1".into(), display_name: None, is_bot: false },
505    ///     Conversation { id: "c1".into(), kind: ConversationKind::Direct },
506    /// )
507    /// .with_message(pressed.clone());
508    /// assert_eq!(answer.message, Some(pressed));
509    /// ```
510    pub fn with_message(mut self, message: MessageRef) -> Self {
511        self.message = Some(message);
512        self
513    }
514}
515
516/// A command the app offers in the platform's own command menu (Discord and
517/// Slack slash commands, Telegram's `/` menu).
518#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
519pub struct CommandSpec {
520    /// Without the leading `/`; lowercase letters, digits and `_`.
521    pub name: String,
522    pub description: String,
523}
524
525impl CommandSpec {
526    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
527        Self {
528            name: name.into(),
529            description: description.into(),
530        }
531    }
532}
533
534/// A command invoked through the platform's command UI rather than typed
535/// as text (a typed `/command` arrives as an [`InboundMessage`]). Answer it
536/// with [`Channel::answer_command`]: some platforms show the invocation as
537/// pending until it is answered.
538#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
539pub struct CommandInvocation {
540    pub conversation: Conversation,
541    pub sender: Sender,
542    /// Without the leading `/`.
543    pub name: String,
544    /// Everything after the command name, trimmed.
545    pub args: String,
546    /// Adapter-defined token for answering this invocation.
547    pub handle: String,
548}
549
550impl CommandInvocation {
551    /// The invocation as the text a user would have typed.
552    pub fn as_text(&self) -> String {
553        if self.args.is_empty() {
554            format!("/{}", self.name)
555        } else {
556            format!("/{} {}", self.name, self.args)
557        }
558    }
559}
560
561/// Everything a channel reports to the runner.
562#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
563#[serde(rename_all = "snake_case", tag = "type")]
564pub enum ChannelEvent {
565    Message(InboundMessage),
566    Approval(ApprovalAnswer),
567    Command(CommandInvocation),
568}
569
570/// A file to send.
571#[derive(Debug, Clone, PartialEq, Eq)]
572pub struct OutboundFile {
573    /// File name shown to the recipient.
574    pub name: String,
575    pub bytes: Vec<u8>,
576    pub mime_type: Option<String>,
577    /// Markdown caption sent with the file.
578    pub caption: Option<String>,
579}
580
581/// What a channel supports; the runner adapts to it.
582#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
583pub struct ChannelCapabilities {
584    pub edit_messages: bool,
585    pub buttons: bool,
586    pub typing_indicator: bool,
587    pub threads: bool,
588    /// [`Channel::delete`] works.
589    pub delete_messages: bool,
590    /// [`Channel::send_file`], [`Channel::download`] and
591    /// [`Channel::download_limited`] work.
592    pub files: bool,
593    /// The platform has a command menu ([`Channel::register_commands`]).
594    pub commands: bool,
595    /// Longest message the platform accepts, in characters.
596    pub max_message_len: usize,
597}
598
599impl Default for ChannelCapabilities {
600    fn default() -> Self {
601        Self {
602            edit_messages: false,
603            buttons: false,
604            typing_indicator: false,
605            threads: false,
606            delete_messages: false,
607            files: false,
608            commands: false,
609            max_message_len: 4000,
610        }
611    }
612}
613
614#[non_exhaustive]
615#[derive(Debug, thiserror::Error)]
616pub enum ChannelError {
617    #[error("not supported by this channel: {0}")]
618    Unsupported(&'static str),
619    #[error("rate limited; retry after {retry_after_secs:?}s")]
620    RateLimited { retry_after_secs: Option<u64> },
621    #[error("authentication failed: {0}")]
622    Auth(String),
623    #[error("transport error: {0}")]
624    Transport(String),
625    /// A download was over the size it was allowed.
626    #[error("file is over the {limit_bytes} byte limit")]
627    TooLarge { limit_bytes: u64 },
628    #[error("{0}")]
629    Other(String),
630}
631
632/// A chat transport. Implementations translate platform updates into
633/// [`ChannelEvent`]s and runner requests into platform API calls.
634#[async_trait]
635pub trait Channel: Send + Sync {
636    /// Short stable name, used as the session-id prefix (`telegram`,
637    /// `slack`, `discord`, or a bot-specific name for multi-bot setups).
638    fn name(&self) -> &str;
639
640    fn capabilities(&self) -> ChannelCapabilities;
641
642    /// Receive updates and forward them until `shutdown` is cancelled or the
643    /// receiver is dropped. Reconnects on transient failures; returns an
644    /// error only for unrecoverable ones (for example a revoked token).
645    ///
646    /// It must be re-runnable: the runner (and the conformance kit) may
647    /// call `run` again after it returned, with a new sender, and updates
648    /// arriving then go to the new one. A push-style channel (a webhook
649    /// server) keeps its listener across runs, or starts a new one, and
650    /// drops what arrives while no `run` is going.
651    async fn run(
652        &self,
653        events: mpsc::Sender<ChannelEvent>,
654        shutdown: CancellationToken,
655    ) -> Result<(), ChannelError>;
656
657    /// Send a message, splitting it if needed. Returns the last part's ref.
658    async fn send(
659        &self,
660        conversation: &Conversation,
661        message: &OutboundMessage,
662    ) -> Result<MessageRef, ChannelError>;
663
664    /// Replace the text of a message the bot sent, and remove any buttons
665    /// on it. An edit always stays one message: text too long for the
666    /// platform is cut at the end and marked with
667    /// [`crate::split::TRUNCATION_MARK`] (see
668    /// [`crate::split::truncate_for_edit`]), never split into further
669    /// messages and never an error.
670    async fn edit(&self, _message: &MessageRef, _text: &str) -> Result<(), ChannelError> {
671        Err(ChannelError::Unsupported("edit"))
672    }
673
674    /// Show an approval prompt with buttons. The runner calls it only
675    /// when [`ChannelCapabilities::buttons`] is true; otherwise, or when
676    /// this returns an error, it sends the prompt's text with
677    /// `/approve <id>` / `/deny <id>` commands instead. A channel without
678    /// buttons leaves the default.
679    ///
680    /// When the prompt is answered (or expires), the runner
681    /// [`edit`](Channel::edit)s the prompt's message to say how it ended,
682    /// which removes the buttons; it calls
683    /// [`remove_buttons`](Channel::remove_buttons) only where it cannot
684    /// edit (the channel cannot, or the prompt is no longer known).
685    async fn ask(&self, _prompt: &ApprovalPrompt) -> Result<MessageRef, ChannelError> {
686        Err(ChannelError::Unsupported("buttons"))
687    }
688
689    /// Remove the buttons from a message, leaving its text. Best effort:
690    /// the default does nothing, for channels without buttons. See
691    /// [`Channel::ask`] for when the runner calls it.
692    async fn remove_buttons(&self, _message: &MessageRef) -> Result<(), ChannelError> {
693        Ok(())
694    }
695
696    /// Post a run's live status ([`RunProgress`]). The runner calls it
697    /// once per run, when [`ChannelCapabilities::edit_messages`] is true,
698    /// and then [`Channel::update_status`] as the run goes and when it
699    /// ends. The default sends [`RunProgress::to_markdown`]; override both
700    /// to render the status natively.
701    async fn send_status(
702        &self,
703        conversation: &Conversation,
704        progress: &RunProgress,
705    ) -> Result<MessageRef, ChannelError> {
706        let text = self.status_text(progress);
707        self.send(conversation, &OutboundMessage::text(text)).await
708    }
709
710    /// Update the status [`Channel::send_status`] posted. The default
711    /// [`edit`](Channel::edit)s it to [`RunProgress::to_markdown`].
712    async fn update_status(
713        &self,
714        message: &MessageRef,
715        progress: &RunProgress,
716    ) -> Result<(), ChannelError> {
717        let text = self.status_text(progress);
718        self.edit(message, &text).await
719    }
720
721    /// The Markdown the default status methods send: the progress cut to
722    /// this channel's message length, LaTeX rewritten as for any text
723    /// ([`Channel::strips_latex`]).
724    fn status_text(&self, progress: &RunProgress) -> String {
725        let text = progress.to_markdown(self.capabilities().max_message_len);
726        if self.strips_latex() {
727            crate::latex::strip_latex_keeping_code(&text)
728        } else {
729            text
730        }
731    }
732
733    /// Show a "typing" indicator. Best effort.
734    async fn typing(&self, _conversation: &Conversation) -> Result<(), ChannelError> {
735        Ok(())
736    }
737
738    /// Delete a message the bot sent.
739    async fn delete(&self, _message: &MessageRef) -> Result<(), ChannelError> {
740        Err(ChannelError::Unsupported("delete"))
741    }
742
743    /// Send a file, with an optional caption.
744    async fn send_file(
745        &self,
746        _conversation: &Conversation,
747        _file: &OutboundFile,
748    ) -> Result<MessageRef, ChannelError> {
749        Err(ChannelError::Unsupported("files"))
750    }
751
752    /// Fetch the bytes of an inbound attachment, up to the adapter's
753    /// platform limit or else [`DEFAULT_MAX_DOWNLOAD_BYTES`]. An adapter
754    /// keeps its token to the platform's own hosts and out of its errors
755    /// and logs.
756    async fn download(&self, _attachment: &Attachment) -> Result<Vec<u8>, ChannelError> {
757        Err(ChannelError::Unsupported("files"))
758    }
759
760    /// [`Self::download`], refused with [`ChannelError::TooLarge`] over
761    /// `max_bytes`.
762    ///
763    /// The default holds any adapter to the limit, but learns the true size
764    /// only after [`Self::download`] returns. An adapter that can stop
765    /// reading part way through should override it.
766    async fn download_limited(
767        &self,
768        attachment: &Attachment,
769        max_bytes: u64,
770    ) -> Result<Vec<u8>, ChannelError> {
771        let too_large = ChannelError::TooLarge {
772            limit_bytes: max_bytes,
773        };
774        if attachment.size_bytes.is_some_and(|size| size > max_bytes) {
775            return Err(too_large);
776        }
777        let bytes = self.download(attachment).await?;
778        if bytes.len() as u64 > max_bytes {
779            return Err(too_large);
780        }
781        Ok(bytes)
782    }
783
784    /// Offer `commands` in the platform's command menu, replacing what was
785    /// offered before. A platform whose commands are configured outside the
786    /// API (Slack's app manifest) accepts the call and does nothing.
787    async fn register_commands(&self, _commands: &[CommandSpec]) -> Result<(), ChannelError> {
788        Ok(())
789    }
790
791    /// Whether the runner rewrites LaTeX in the model's text as plain text
792    /// before sending it here ([`crate::latex::strip_latex_keeping_code`]).
793    /// On by default, since chat platforms show it as raw markup; override
794    /// it to return `false` for one that renders math.
795    fn strips_latex(&self) -> bool {
796        true
797    }
798
799    /// The name a person shows on the platform, by their platform user id
800    /// (`None` when the platform has none to give). It is the person's own
801    /// text: see [`Sender`].
802    async fn display_name(&self, _user_id: &str) -> Result<Option<String>, ChannelError> {
803        Ok(None)
804    }
805
806    /// Answer a [`CommandInvocation`]. The default sends `text` to its
807    /// conversation.
808    async fn answer_command(
809        &self,
810        command: &CommandInvocation,
811        text: &str,
812    ) -> Result<(), ChannelError> {
813        self.send(&command.conversation, &OutboundMessage::text(text))
814            .await
815            .map(|_| ())
816    }
817}
818
819#[cfg(test)]
820mod tests {
821    use super::*;
822
823    #[test]
824    fn a_mime_type_outranks_the_name() {
825        assert_eq!(Attachment::new("a.png", "s").kind, AttachmentKind::Image);
826        assert_eq!(Attachment::new("a.MP3", "s").kind, AttachmentKind::Audio);
827        assert_eq!(Attachment::new("a.mov", "s").kind, AttachmentKind::Video);
828        assert_eq!(Attachment::new("a.pdf", "s").kind, AttachmentKind::File);
829        assert_eq!(Attachment::new("noext", "s").kind, AttachmentKind::File);
830        let relabelled = Attachment::new("a.png", "s").with_mime_type(Some("text/plain".into()));
831        assert_eq!(relabelled.kind, AttachmentKind::File);
832        let unlabelled = Attachment::new("a.png", "s").with_mime_type(None);
833        assert_eq!(unlabelled.kind, AttachmentKind::Image);
834    }
835
836    #[test]
837    fn older_or_newer_json_still_reads() {
838        // Written before `kind` and the links existed.
839        let old: InboundMessage = serde_json::from_value(serde_json::json!({
840            "conversation": {"id": "c", "kind": "direct"},
841            "sender": {"id": "synthetic-user-1"},
842            "message_id": "m1",
843            "text": "hi",
844            "attachments": [{"name": "a.bin", "source": "s"}],
845            "addressed": true,
846        }))
847        .unwrap();
848        assert_eq!(old.attachments[0].kind, AttachmentKind::File);
849        assert_eq!(old.parent_message_id, None);
850        assert_eq!(old.thread_id, None);
851        // A kind this version has never heard of.
852        let unknown: Attachment = serde_json::from_value(
853            serde_json::json!({"name": "a", "source": "s", "kind": "hologram"}),
854        )
855        .unwrap();
856        assert_eq!(unknown.kind, AttachmentKind::File);
857        // An unset link is not written out.
858        let written = serde_json::to_value(&old).unwrap();
859        assert!(written.get("parent_message_id").is_none());
860    }
861
862    struct Bare;
863
864    #[async_trait]
865    impl Channel for Bare {
866        fn name(&self) -> &str {
867            "bare"
868        }
869        fn capabilities(&self) -> ChannelCapabilities {
870            ChannelCapabilities::default()
871        }
872        async fn run(
873            &self,
874            _events: mpsc::Sender<ChannelEvent>,
875            _shutdown: CancellationToken,
876        ) -> Result<(), ChannelError> {
877            Ok(())
878        }
879        async fn send(
880            &self,
881            conversation: &Conversation,
882            _message: &OutboundMessage,
883        ) -> Result<MessageRef, ChannelError> {
884            Ok(MessageRef {
885                conversation_id: conversation.id.clone(),
886                message_id: "1".into(),
887            })
888        }
889    }
890
891    /// Overrides only the old method, the way an older adapter would.
892    struct OldAdapter(Vec<u8>);
893
894    #[async_trait]
895    impl Channel for OldAdapter {
896        fn name(&self) -> &str {
897            "old"
898        }
899        fn capabilities(&self) -> ChannelCapabilities {
900            ChannelCapabilities::default()
901        }
902        async fn run(
903            &self,
904            _events: mpsc::Sender<ChannelEvent>,
905            _shutdown: CancellationToken,
906        ) -> Result<(), ChannelError> {
907            Ok(())
908        }
909        async fn send(
910            &self,
911            conversation: &Conversation,
912            _message: &OutboundMessage,
913        ) -> Result<MessageRef, ChannelError> {
914            Ok(MessageRef {
915                conversation_id: conversation.id.clone(),
916                message_id: "1".into(),
917            })
918        }
919        async fn download(&self, _attachment: &Attachment) -> Result<Vec<u8>, ChannelError> {
920            Ok(self.0.clone())
921        }
922    }
923
924    #[tokio::test]
925    async fn the_defaults_are_safe() {
926        let attachment = Attachment::new("a", "s");
927        assert!(matches!(
928            Bare.download(&attachment).await,
929            Err(ChannelError::Unsupported(_))
930        ));
931        assert!(matches!(
932            Bare.download_limited(&attachment, 10).await,
933            Err(ChannelError::Unsupported(_))
934        ));
935        let message = MessageRef {
936            conversation_id: "c".into(),
937            message_id: "m".into(),
938        };
939        assert!(Bare.remove_buttons(&message).await.is_ok());
940    }
941
942    #[tokio::test]
943    async fn an_older_adapter_is_held_to_the_limit() {
944        let adapter = OldAdapter(vec![0; 11]);
945        let attachment = Attachment::new("a", "s");
946        assert_eq!(
947            adapter
948                .download_limited(&attachment, 11)
949                .await
950                .unwrap()
951                .len(),
952            11
953        );
954        assert!(matches!(
955            adapter.download_limited(&attachment, 10).await,
956            Err(ChannelError::TooLarge { limit_bytes: 10 })
957        ));
958        // A declared size over the limit is refused without fetching.
959        let declared = attachment.with_size_bytes(Some(99));
960        assert!(matches!(
961            OldAdapter(Vec::new()).download_limited(&declared, 10).await,
962            Err(ChannelError::TooLarge { .. })
963        ));
964    }
965}