Skip to main content

orch/channels/
mod.rs

1//! Channel abstraction — the core trait for all I/O surfaces.
2//!
3//! Every external interface (GitHub, Telegram, Discord, tmux) implements
4//! the `Channel` trait. This gives the engine a uniform way to:
5//! - Receive commands/messages
6//! - Send task updates and agent output
7//!
8//! Channels are bidirectional and async. The engine doesn't care whether
9//! a message came from a Telegram DM, a GitHub issue comment, or a
10//! Discord thread — it processes the same `IncomingMessage` type.
11
12pub mod access;
13pub mod capture;
14pub mod discord;
15pub mod discord_ws;
16pub mod github;
17pub mod leader;
18pub mod notification;
19pub mod routing;
20pub mod slack;
21pub mod stream;
22pub mod telegram;
23pub mod tmux;
24pub mod transport;
25
26use std::fmt;
27use std::fmt::Debug;
28use std::fmt::Formatter;
29use std::sync::{Mutex, PoisonError};
30
31use async_trait::async_trait;
32use serde::{Deserialize, Serialize};
33use tokio::sync::mpsc::Receiver;
34use tokio::task::{AbortHandle, JoinHandle};
35
36/// Escape `&`, `<` and `>` for Telegram's HTML parse_mode, which rejects bare ones
37pub(crate) fn html_escape(s: &str) -> String {
38    s.replace('&', "&amp;")
39        .replace('<', "&lt;")
40        .replace('>', "&gt;")
41}
42
43/// Split content into chunks of at most `max_bytes`, never inside a UTF-8 character
44pub(crate) fn split_utf8(content: &str, max_bytes: usize) -> Vec<String> {
45    if content.len() <= max_bytes {
46        return vec![content.to_string()];
47    }
48
49    let mut chunks = Vec::new();
50    let mut start = 0;
51    let total = content.len();
52
53    while start < total {
54        let mut end = (start + max_bytes).min(total);
55        while end > start && !content.is_char_boundary(end) {
56            end -= 1;
57        }
58        if end == start {
59            // A single char over the limit still goes out whole
60            if let Some(ch) = content[start..].chars().next() {
61                end = start + ch.len_utf8();
62            } else {
63                break;
64            }
65        }
66        chunks.push(content[start..end].to_string());
67        start = end;
68    }
69
70    chunks
71}
72
73/// A message received from any channel.
74#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct IncomingMessage {
76    /// Channel that produced this message (e.g. "github", "telegram", "discord")
77    pub channel: String,
78    /// Unique ID within the channel (comment ID, message ID, etc.)
79    pub id: String,
80    /// Thread/conversation context (issue number, chat ID, channel ID)
81    pub thread_id: String,
82    /// Author identifier
83    pub author: String,
84    /// Raw text content
85    pub body: String,
86    /// When the message was created
87    pub timestamp: chrono::DateTime<chrono::Utc>,
88    /// Optional metadata (labels, attachments, etc.)
89    #[serde(default)]
90    pub metadata: serde_json::Value,
91    /// Optional forum topic / thread ID (e.g. Telegram forum topic)
92    #[serde(default)]
93    pub topic_id: Option<String>,
94}
95
96/// A message to send to a channel.
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct OutgoingMessage {
99    /// Target thread/conversation
100    pub thread_id: String,
101    /// Message body (markdown)
102    pub body: String,
103    /// Optional: reply to a specific message ID
104    pub reply_to: Option<String>,
105    /// Optional metadata for channel-specific features
106    #[serde(default)]
107    pub metadata: serde_json::Value,
108    /// Optional forum topic / thread ID (e.g. Telegram forum topic)
109    #[serde(default)]
110    pub topic_id: Option<String>,
111}
112
113/// An agent output chunk for streaming.
114#[derive(Debug, Clone)]
115pub struct OutputChunk {
116    pub content: String,
117    pub is_final: bool,
118}
119
120/// The core channel trait. All external interfaces implement this.
121#[async_trait]
122pub trait Channel: Send + Sync {
123    /// Human-readable channel name.
124    fn name(&self) -> &str;
125
126    /// Start listening for incoming messages.
127    /// Returns a receiver that the engine polls.
128    async fn start(&self) -> anyhow::Result<Receiver<IncomingMessage>>;
129
130    /// Send a message to a thread/conversation.
131    async fn send(&self, msg: &OutgoingMessage) -> anyhow::Result<()>;
132
133    /// Acknowledge an interactive callback to dismiss the loading indicator.
134    ///
135    /// Telegram requires `answerCallbackQuery` to dismiss the spinner after a button press.
136    /// Discord buttons are already acknowledged in the websocket handler — no-op here.
137    /// Default implementation is a no-op so non-interactive channels need not implement it.
138    async fn ack_interaction(&self, _callback_query_id: &str) -> anyhow::Result<()> {
139        Ok(())
140    }
141
142    /// Check if this channel is healthy/connected.
143    async fn health_check(&self) -> anyhow::Result<()>;
144
145    /// Stop listening and close the connection. A later `start` listens again
146    async fn stop(&self) {}
147}
148
149/// The task a channel listens in, so `stop` can end it
150#[derive(Debug, Default)]
151pub(crate) struct Poller(Mutex<Option<AbortHandle>>);
152
153impl Poller {
154    /// Keep `task` as the listener and end the one before it
155    pub(crate) fn set(&self, task: &JoinHandle<()>) {
156        let old = self
157            .0
158            .lock()
159            .unwrap_or_else(PoisonError::into_inner)
160            .replace(task.abort_handle());
161        if let Some(old) = old {
162            old.abort();
163        }
164    }
165
166    pub(crate) fn stop(&self) {
167        let task = self.0.lock().unwrap_or_else(PoisonError::into_inner).take();
168        if let Some(task) = task {
169            task.abort();
170        }
171    }
172}
173
174/// Registry of active channels.
175pub struct ChannelRegistry {
176    channels: Vec<Box<dyn Channel>>,
177}
178
179impl Debug for ChannelRegistry {
180    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
181        f.debug_list()
182            .entries(self.channels.iter().map(|c| c.name()))
183            .finish()
184    }
185}
186
187impl ChannelRegistry {
188    pub fn new() -> Self {
189        Self {
190            channels: Vec::new(),
191        }
192    }
193
194    pub fn register(&mut self, channel: Box<dyn Channel>) {
195        tracing::info!(channel = channel.name(), "registered channel");
196        self.channels.push(channel);
197    }
198
199    pub fn iter(&self) -> impl Iterator<Item = &dyn Channel> {
200        self.channels.iter().map(AsRef::as_ref)
201    }
202}