use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Conversation {
pub id: String,
pub kind: ConversationKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConversationKind {
Direct,
Group,
Thread,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Sender {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default)]
pub is_bot: bool,
}
pub const DEFAULT_MAX_DOWNLOAD_BYTES: u64 = 100 * 1024 * 1024;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AttachmentKind {
Image,
Audio,
Video,
#[default]
#[serde(other)]
File,
}
impl AttachmentKind {
pub fn from_mime(mime: &str) -> Self {
let top = mime.split('/').next().unwrap_or("").trim();
if top.eq_ignore_ascii_case("image") {
Self::Image
} else if top.eq_ignore_ascii_case("audio") {
Self::Audio
} else if top.eq_ignore_ascii_case("video") {
Self::Video
} else {
Self::File
}
}
fn from_name(name: &str) -> Self {
let extension = name.rsplit_once('.').map_or("", |(_, ext)| ext);
match extension.to_ascii_lowercase().as_str() {
"png" | "jpg" | "jpeg" | "gif" | "webp" => Self::Image,
"mp3" | "ogg" | "oga" | "wav" | "flac" | "m4a" | "aac" => Self::Audio,
"mp4" | "mov" | "webm" | "mkv" => Self::Video,
_ => Self::File,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attachment {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mime_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size_bytes: Option<u64>,
pub source: String,
#[serde(default)]
pub kind: AttachmentKind,
}
impl Attachment {
pub fn new(name: impl Into<String>, source: impl Into<String>) -> Self {
let name = name.into();
let kind = AttachmentKind::from_name(&name);
Self {
name,
mime_type: None,
size_bytes: None,
source: source.into(),
kind,
}
}
pub fn with_mime_type(mut self, mime_type: Option<String>) -> Self {
if let Some(mime) = mime_type.as_deref() {
self.kind = AttachmentKind::from_mime(mime);
}
self.mime_type = mime_type;
self
}
pub fn with_size_bytes(mut self, size_bytes: Option<u64>) -> Self {
self.size_bytes = size_bytes;
self
}
pub fn with_kind(mut self, kind: AttachmentKind) -> Self {
self.kind = kind;
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InboundMessage {
pub conversation: Conversation,
pub sender: Sender,
pub message_id: String,
pub text: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub attachments: Vec<Attachment>,
pub addressed: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent_message_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thread_id: Option<String>,
}
impl InboundMessage {
pub fn new(
conversation: Conversation,
sender: Sender,
message_id: impl Into<String>,
text: impl Into<String>,
) -> Self {
let addressed = conversation.kind == ConversationKind::Direct;
Self {
conversation,
sender,
message_id: message_id.into(),
text: text.into(),
attachments: Vec::new(),
addressed,
parent_message_id: None,
thread_id: None,
}
}
pub fn with_attachments(mut self, attachments: Vec<Attachment>) -> Self {
self.attachments = attachments;
self
}
pub fn with_addressed(mut self, addressed: bool) -> Self {
self.addressed = addressed;
self
}
pub fn with_parent_message_id(mut self, parent: Option<String>) -> Self {
self.parent_message_id = parent;
self
}
pub fn with_thread_id(mut self, thread: Option<String>) -> Self {
self.thread_id = thread;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OutboundMessage {
pub text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reply_to: Option<String>,
}
impl OutboundMessage {
pub fn text(text: impl Into<String>) -> Self {
Self {
text: text.into(),
reply_to: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MessageRef {
pub conversation_id: String,
pub message_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApprovalChoice {
pub id: String,
pub label: String,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ApprovalPrompt {
pub id: String,
pub conversation: Conversation,
pub text: String,
pub choices: Vec<ApprovalChoice>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub details: Option<ApprovalDetails>,
}
impl ApprovalPrompt {
pub fn new(
id: impl Into<String>,
conversation: Conversation,
text: impl Into<String>,
choices: Vec<ApprovalChoice>,
) -> Self {
Self {
id: id.into(),
conversation,
text: text.into(),
choices,
details: None,
}
}
pub fn with_details(mut self, details: ApprovalDetails) -> Self {
self.details = Some(details);
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ApprovalDetails {
pub tool: String,
pub arguments: serde_json::Value,
pub reason: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub request: Option<aidaemon_core::OwnerApprovalRequest>,
}
impl ApprovalDetails {
pub fn from_interruption(interruption: &aidaemon_core::Interruption) -> Self {
Self {
tool: interruption.call.name.clone(),
arguments: interruption.call.arguments.clone(),
reason: interruption.reason.clone(),
request: match &interruption.kind {
aidaemon_core::InterruptKind::OwnerApproval(request) => Some(request.clone()),
_ => None,
},
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunProgress {
pub phase: ProgressPhase,
pub tools: Vec<ToolProgress>,
pub streamed: String,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProgressPhase {
Working,
Ended(RunEnding),
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunEnding {
Done,
PartlyDone,
WaitingForApproval,
Stopped,
Blocked,
Failed,
Ended,
}
impl RunEnding {
pub fn word(self) -> &'static str {
match self {
Self::Done => "Done",
Self::PartlyDone => "Partly done",
Self::WaitingForApproval => "Waiting for approval",
Self::Stopped => "Stopped",
Self::Blocked => "Blocked",
Self::Failed => "Failed",
Self::Ended => "Ended",
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolProgress {
pub call_id: String,
pub tool: String,
pub state: ToolState,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolState {
Running,
Ended(aidaemon_core::ReceiptStatus),
}
impl RunProgress {
pub fn working() -> Self {
Self {
phase: ProgressPhase::Working,
tools: Vec::new(),
streamed: String::new(),
}
}
pub fn to_markdown(&self, max_chars: usize) -> String {
let mut out = match self.phase {
ProgressPhase::Working => "_Working..._".to_string(),
ProgressPhase::Ended(ending) => format!("_{}_", ending.word()),
};
for tool in &self.tools {
out.push('\n');
out.push_str(&match tool.state {
ToolState::Running => format!("- Running `{}`", tool.tool),
ToolState::Ended(status) => {
format!("- `{}`: {}", tool.tool, crate::render::receipt_word(status))
}
});
}
let stream = self.streamed.trim();
if self.phase == ProgressPhase::Working && !stream.is_empty() {
out.push_str("\n\n");
let room = max_chars.saturating_sub(out.chars().count() + 4);
out.push_str(&crate::render::tail_chars(stream, room));
}
crate::render::truncate_chars(&out, max_chars)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApprovalAnswer {
pub prompt_id: String,
pub choice_id: String,
pub sender: Sender,
pub conversation: Conversation,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<MessageRef>,
}
impl ApprovalAnswer {
pub fn new(
prompt_id: impl Into<String>,
choice_id: impl Into<String>,
sender: Sender,
conversation: Conversation,
) -> Self {
Self {
prompt_id: prompt_id.into(),
choice_id: choice_id.into(),
sender,
conversation,
message: None,
}
}
pub fn with_message(mut self, message: MessageRef) -> Self {
self.message = Some(message);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandSpec {
pub name: String,
pub description: String,
}
impl CommandSpec {
pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
Self {
name: name.into(),
description: description.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandInvocation {
pub conversation: Conversation,
pub sender: Sender,
pub name: String,
pub args: String,
pub handle: String,
}
impl CommandInvocation {
pub fn as_text(&self) -> String {
if self.args.is_empty() {
format!("/{}", self.name)
} else {
format!("/{} {}", self.name, self.args)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum ChannelEvent {
Message(InboundMessage),
Approval(ApprovalAnswer),
Command(CommandInvocation),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutboundFile {
pub name: String,
pub bytes: Vec<u8>,
pub mime_type: Option<String>,
pub caption: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelCapabilities {
pub edit_messages: bool,
pub buttons: bool,
pub typing_indicator: bool,
pub threads: bool,
pub delete_messages: bool,
pub files: bool,
pub commands: bool,
pub max_message_len: usize,
}
impl Default for ChannelCapabilities {
fn default() -> Self {
Self {
edit_messages: false,
buttons: false,
typing_indicator: false,
threads: false,
delete_messages: false,
files: false,
commands: false,
max_message_len: 4000,
}
}
}
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ChannelError {
#[error("not supported by this channel: {0}")]
Unsupported(&'static str),
#[error("rate limited; retry after {retry_after_secs:?}s")]
RateLimited { retry_after_secs: Option<u64> },
#[error("authentication failed: {0}")]
Auth(String),
#[error("transport error: {0}")]
Transport(String),
#[error("file is over the {limit_bytes} byte limit")]
TooLarge { limit_bytes: u64 },
#[error("{0}")]
Other(String),
}
#[async_trait]
pub trait Channel: Send + Sync {
fn name(&self) -> &str;
fn capabilities(&self) -> ChannelCapabilities;
async fn run(
&self,
events: mpsc::Sender<ChannelEvent>,
shutdown: CancellationToken,
) -> Result<(), ChannelError>;
async fn send(
&self,
conversation: &Conversation,
message: &OutboundMessage,
) -> Result<MessageRef, ChannelError>;
async fn edit(&self, _message: &MessageRef, _text: &str) -> Result<(), ChannelError> {
Err(ChannelError::Unsupported("edit"))
}
async fn ask(&self, _prompt: &ApprovalPrompt) -> Result<MessageRef, ChannelError> {
Err(ChannelError::Unsupported("buttons"))
}
async fn remove_buttons(&self, _message: &MessageRef) -> Result<(), ChannelError> {
Ok(())
}
async fn send_status(
&self,
conversation: &Conversation,
progress: &RunProgress,
) -> Result<MessageRef, ChannelError> {
let text = self.status_text(progress);
self.send(conversation, &OutboundMessage::text(text)).await
}
async fn update_status(
&self,
message: &MessageRef,
progress: &RunProgress,
) -> Result<(), ChannelError> {
let text = self.status_text(progress);
self.edit(message, &text).await
}
fn status_text(&self, progress: &RunProgress) -> String {
let text = progress.to_markdown(self.capabilities().max_message_len);
if self.strips_latex() {
crate::latex::strip_latex_keeping_code(&text)
} else {
text
}
}
async fn typing(&self, _conversation: &Conversation) -> Result<(), ChannelError> {
Ok(())
}
async fn delete(&self, _message: &MessageRef) -> Result<(), ChannelError> {
Err(ChannelError::Unsupported("delete"))
}
async fn send_file(
&self,
_conversation: &Conversation,
_file: &OutboundFile,
) -> Result<MessageRef, ChannelError> {
Err(ChannelError::Unsupported("files"))
}
async fn download(&self, _attachment: &Attachment) -> Result<Vec<u8>, ChannelError> {
Err(ChannelError::Unsupported("files"))
}
async fn download_limited(
&self,
attachment: &Attachment,
max_bytes: u64,
) -> Result<Vec<u8>, ChannelError> {
let too_large = ChannelError::TooLarge {
limit_bytes: max_bytes,
};
if attachment.size_bytes.is_some_and(|size| size > max_bytes) {
return Err(too_large);
}
let bytes = self.download(attachment).await?;
if bytes.len() as u64 > max_bytes {
return Err(too_large);
}
Ok(bytes)
}
async fn register_commands(&self, _commands: &[CommandSpec]) -> Result<(), ChannelError> {
Ok(())
}
fn strips_latex(&self) -> bool {
true
}
async fn display_name(&self, _user_id: &str) -> Result<Option<String>, ChannelError> {
Ok(None)
}
async fn answer_command(
&self,
command: &CommandInvocation,
text: &str,
) -> Result<(), ChannelError> {
self.send(&command.conversation, &OutboundMessage::text(text))
.await
.map(|_| ())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_mime_type_outranks_the_name() {
assert_eq!(Attachment::new("a.png", "s").kind, AttachmentKind::Image);
assert_eq!(Attachment::new("a.MP3", "s").kind, AttachmentKind::Audio);
assert_eq!(Attachment::new("a.mov", "s").kind, AttachmentKind::Video);
assert_eq!(Attachment::new("a.pdf", "s").kind, AttachmentKind::File);
assert_eq!(Attachment::new("noext", "s").kind, AttachmentKind::File);
let relabelled = Attachment::new("a.png", "s").with_mime_type(Some("text/plain".into()));
assert_eq!(relabelled.kind, AttachmentKind::File);
let unlabelled = Attachment::new("a.png", "s").with_mime_type(None);
assert_eq!(unlabelled.kind, AttachmentKind::Image);
}
#[test]
fn older_or_newer_json_still_reads() {
let old: InboundMessage = serde_json::from_value(serde_json::json!({
"conversation": {"id": "c", "kind": "direct"},
"sender": {"id": "synthetic-user-1"},
"message_id": "m1",
"text": "hi",
"attachments": [{"name": "a.bin", "source": "s"}],
"addressed": true,
}))
.unwrap();
assert_eq!(old.attachments[0].kind, AttachmentKind::File);
assert_eq!(old.parent_message_id, None);
assert_eq!(old.thread_id, None);
let unknown: Attachment = serde_json::from_value(
serde_json::json!({"name": "a", "source": "s", "kind": "hologram"}),
)
.unwrap();
assert_eq!(unknown.kind, AttachmentKind::File);
let written = serde_json::to_value(&old).unwrap();
assert!(written.get("parent_message_id").is_none());
}
struct Bare;
#[async_trait]
impl Channel for Bare {
fn name(&self) -> &str {
"bare"
}
fn capabilities(&self) -> ChannelCapabilities {
ChannelCapabilities::default()
}
async fn run(
&self,
_events: mpsc::Sender<ChannelEvent>,
_shutdown: CancellationToken,
) -> Result<(), ChannelError> {
Ok(())
}
async fn send(
&self,
conversation: &Conversation,
_message: &OutboundMessage,
) -> Result<MessageRef, ChannelError> {
Ok(MessageRef {
conversation_id: conversation.id.clone(),
message_id: "1".into(),
})
}
}
struct OldAdapter(Vec<u8>);
#[async_trait]
impl Channel for OldAdapter {
fn name(&self) -> &str {
"old"
}
fn capabilities(&self) -> ChannelCapabilities {
ChannelCapabilities::default()
}
async fn run(
&self,
_events: mpsc::Sender<ChannelEvent>,
_shutdown: CancellationToken,
) -> Result<(), ChannelError> {
Ok(())
}
async fn send(
&self,
conversation: &Conversation,
_message: &OutboundMessage,
) -> Result<MessageRef, ChannelError> {
Ok(MessageRef {
conversation_id: conversation.id.clone(),
message_id: "1".into(),
})
}
async fn download(&self, _attachment: &Attachment) -> Result<Vec<u8>, ChannelError> {
Ok(self.0.clone())
}
}
#[tokio::test]
async fn the_defaults_are_safe() {
let attachment = Attachment::new("a", "s");
assert!(matches!(
Bare.download(&attachment).await,
Err(ChannelError::Unsupported(_))
));
assert!(matches!(
Bare.download_limited(&attachment, 10).await,
Err(ChannelError::Unsupported(_))
));
let message = MessageRef {
conversation_id: "c".into(),
message_id: "m".into(),
};
assert!(Bare.remove_buttons(&message).await.is_ok());
}
#[tokio::test]
async fn an_older_adapter_is_held_to_the_limit() {
let adapter = OldAdapter(vec![0; 11]);
let attachment = Attachment::new("a", "s");
assert_eq!(
adapter
.download_limited(&attachment, 11)
.await
.unwrap()
.len(),
11
);
assert!(matches!(
adapter.download_limited(&attachment, 10).await,
Err(ChannelError::TooLarge { limit_bytes: 10 })
));
let declared = attachment.with_size_bytes(Some(99));
assert!(matches!(
OldAdapter(Vec::new()).download_limited(&declared, 10).await,
Err(ChannelError::TooLarge { .. })
));
}
}