1pub mod access;
13pub mod capture;
14pub mod discord;
15pub mod discord_ws;
16pub mod github;
17pub mod leader;
18pub mod notification;
19pub mod remote;
20pub mod routing;
21pub mod slack;
22pub mod stream;
23pub mod telegram;
24pub mod tmux;
25pub mod transport;
26
27use std::fmt;
28use std::fmt::Debug;
29use std::fmt::Formatter;
30use std::sync::{Mutex, PoisonError};
31
32use async_trait::async_trait;
33use serde::{Deserialize, Serialize};
34use tokio::sync::mpsc::Receiver;
35use tokio::task::{AbortHandle, JoinHandle};
36
37pub(crate) fn html_escape(s: &str) -> String {
39 s.replace('&', "&")
40 .replace('<', "<")
41 .replace('>', ">")
42}
43
44pub(crate) fn split_utf8(content: &str, max_bytes: usize) -> Vec<String> {
46 if content.len() <= max_bytes {
47 return vec![content.to_string()];
48 }
49
50 let mut chunks = Vec::new();
51 let mut start = 0;
52 let total = content.len();
53
54 while start < total {
55 let mut end = (start + max_bytes).min(total);
56 while end > start && !content.is_char_boundary(end) {
57 end -= 1;
58 }
59 if end == start {
60 if let Some(ch) = content[start..].chars().next() {
62 end = start + ch.len_utf8();
63 } else {
64 break;
65 }
66 }
67 chunks.push(content[start..end].to_string());
68 start = end;
69 }
70
71 chunks
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct IncomingMessage {
77 pub channel: String,
79 pub id: String,
81 pub thread_id: String,
83 pub author: String,
85 pub body: String,
87 pub timestamp: chrono::DateTime<chrono::Utc>,
89 #[serde(default)]
91 pub metadata: serde_json::Value,
92 #[serde(default)]
94 pub topic_id: Option<String>,
95}
96
97#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct OutgoingMessage {
100 pub thread_id: String,
102 pub body: String,
104 pub reply_to: Option<String>,
106 #[serde(default)]
108 pub metadata: serde_json::Value,
109 #[serde(default)]
111 pub topic_id: Option<String>,
112}
113
114#[derive(Debug, Clone)]
116pub struct OutputChunk {
117 pub content: String,
118 pub is_final: bool,
119}
120
121#[async_trait]
123pub trait Channel: Send + Sync {
124 fn name(&self) -> &str;
126
127 async fn start(&self) -> anyhow::Result<Receiver<IncomingMessage>>;
130
131 async fn send(&self, msg: &OutgoingMessage) -> anyhow::Result<()>;
133
134 async fn ack_interaction(&self, _callback_query_id: &str) -> anyhow::Result<()> {
140 Ok(())
141 }
142
143 async fn health_check(&self) -> anyhow::Result<()>;
145
146 async fn stop(&self) {}
148}
149
150#[derive(Debug, Default)]
152pub(crate) struct Poller(Mutex<Option<AbortHandle>>);
153
154impl Poller {
155 pub(crate) fn set(&self, task: &JoinHandle<()>) {
157 let old = self
158 .0
159 .lock()
160 .unwrap_or_else(PoisonError::into_inner)
161 .replace(task.abort_handle());
162 if let Some(old) = old {
163 old.abort();
164 }
165 }
166
167 pub(crate) fn stop(&self) {
168 let task = self.0.lock().unwrap_or_else(PoisonError::into_inner).take();
169 if let Some(task) = task {
170 task.abort();
171 }
172 }
173}
174
175pub struct ChannelRegistry {
177 channels: Vec<Box<dyn Channel>>,
178}
179
180impl Debug for ChannelRegistry {
181 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
182 f.debug_list()
183 .entries(self.channels.iter().map(|c| c.name()))
184 .finish()
185 }
186}
187
188impl ChannelRegistry {
189 pub fn new() -> Self {
190 Self {
191 channels: Vec::new(),
192 }
193 }
194
195 pub fn register(&mut self, channel: Box<dyn Channel>) {
196 tracing::info!(channel = channel.name(), "registered channel");
197 self.channels.push(channel);
198 }
199
200 pub fn iter(&self) -> impl Iterator<Item = &dyn Channel> {
201 self.channels.iter().map(AsRef::as_ref)
202 }
203}