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