1use async_trait::async_trait;
8use serde::{Deserialize, Serialize};
9use tokio::sync::mpsc;
10use tokio_util::sync::CancellationToken;
11
12#[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 Direct,
26 Group,
28 Thread,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct Sender {
40 pub id: String,
42 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub display_name: Option<String>,
47 #[serde(default)]
49 pub is_bot: bool,
50}
51
52pub const DEFAULT_MAX_DOWNLOAD_BYTES: u64 = 100 * 1024 * 1024;
55
56#[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 #[default]
66 #[serde(other)]
67 File,
68}
69
70impl AttachmentKind {
71 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 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#[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 pub source: String,
113 #[serde(default)]
116 pub kind: AttachmentKind,
117}
118
119impl Attachment {
120 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 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 pub fn with_kind(mut self, kind: AttachmentKind) -> Self {
152 self.kind = kind;
153 self
154 }
155}
156
157#[non_exhaustive]
160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
161pub struct InboundMessage {
162 pub conversation: Conversation,
163 pub sender: Sender,
164 pub message_id: String,
166 pub text: String,
167 #[serde(default, skip_serializing_if = "Vec::is_empty")]
168 pub attachments: Vec<Attachment>,
169 pub addressed: bool,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub parent_message_id: Option<String>,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub thread_id: Option<String>,
183}
184
185impl InboundMessage {
186 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#[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#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
248pub struct MessageRef {
249 pub conversation_id: String,
250 pub message_id: String,
251}
252
253#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
255pub struct ApprovalChoice {
256 pub id: String,
258 pub label: String,
259}
260
261#[non_exhaustive]
266#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
267pub struct ApprovalPrompt {
268 pub id: String,
270 pub conversation: Conversation,
271 pub text: String,
274 pub choices: Vec<ApprovalChoice>,
275 #[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#[non_exhaustive]
308#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
309pub struct ApprovalDetails {
310 pub tool: String,
312 pub arguments: serde_json::Value,
314 pub reason: String,
316 #[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#[non_exhaustive]
341#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
342pub struct RunProgress {
343 pub phase: ProgressPhase,
344 pub tools: Vec<ToolProgress>,
346 pub streamed: String,
349}
350
351#[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#[non_exhaustive]
362#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
363#[serde(rename_all = "snake_case")]
364pub enum RunEnding {
365 Done,
366 PartlyDone,
368 WaitingForApproval,
370 Stopped,
372 Blocked,
374 Failed,
376 Ended,
378}
379
380impl RunEnding {
381 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#[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#[non_exhaustive]
406#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
407#[serde(rename_all = "snake_case")]
408pub enum ToolState {
409 Running,
410 Ended(aidaemon_core::ReceiptStatus),
412}
413
414impl RunProgress {
415 pub fn working() -> Self {
417 Self {
418 phase: ProgressPhase::Working,
419 tools: Vec::new(),
420 streamed: String::new(),
421 }
422 }
423
424 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#[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 #[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 pub fn with_message(mut self, message: MessageRef) -> Self {
511 self.message = Some(message);
512 self
513 }
514}
515
516#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
519pub struct CommandSpec {
520 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
539pub struct CommandInvocation {
540 pub conversation: Conversation,
541 pub sender: Sender,
542 pub name: String,
544 pub args: String,
546 pub handle: String,
548}
549
550impl CommandInvocation {
551 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#[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#[derive(Debug, Clone, PartialEq, Eq)]
572pub struct OutboundFile {
573 pub name: String,
575 pub bytes: Vec<u8>,
576 pub mime_type: Option<String>,
577 pub caption: Option<String>,
579}
580
581#[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 pub delete_messages: bool,
590 pub files: bool,
593 pub commands: bool,
595 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 #[error("file is over the {limit_bytes} byte limit")]
627 TooLarge { limit_bytes: u64 },
628 #[error("{0}")]
629 Other(String),
630}
631
632#[async_trait]
635pub trait Channel: Send + Sync {
636 fn name(&self) -> &str;
639
640 fn capabilities(&self) -> ChannelCapabilities;
641
642 async fn run(
652 &self,
653 events: mpsc::Sender<ChannelEvent>,
654 shutdown: CancellationToken,
655 ) -> Result<(), ChannelError>;
656
657 async fn send(
659 &self,
660 conversation: &Conversation,
661 message: &OutboundMessage,
662 ) -> Result<MessageRef, ChannelError>;
663
664 async fn edit(&self, _message: &MessageRef, _text: &str) -> Result<(), ChannelError> {
671 Err(ChannelError::Unsupported("edit"))
672 }
673
674 async fn ask(&self, _prompt: &ApprovalPrompt) -> Result<MessageRef, ChannelError> {
686 Err(ChannelError::Unsupported("buttons"))
687 }
688
689 async fn remove_buttons(&self, _message: &MessageRef) -> Result<(), ChannelError> {
693 Ok(())
694 }
695
696 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 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 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 async fn typing(&self, _conversation: &Conversation) -> Result<(), ChannelError> {
735 Ok(())
736 }
737
738 async fn delete(&self, _message: &MessageRef) -> Result<(), ChannelError> {
740 Err(ChannelError::Unsupported("delete"))
741 }
742
743 async fn send_file(
745 &self,
746 _conversation: &Conversation,
747 _file: &OutboundFile,
748 ) -> Result<MessageRef, ChannelError> {
749 Err(ChannelError::Unsupported("files"))
750 }
751
752 async fn download(&self, _attachment: &Attachment) -> Result<Vec<u8>, ChannelError> {
757 Err(ChannelError::Unsupported("files"))
758 }
759
760 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 async fn register_commands(&self, _commands: &[CommandSpec]) -> Result<(), ChannelError> {
788 Ok(())
789 }
790
791 fn strips_latex(&self) -> bool {
796 true
797 }
798
799 async fn display_name(&self, _user_id: &str) -> Result<Option<String>, ChannelError> {
803 Ok(None)
804 }
805
806 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 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 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 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 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 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}