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 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
37/// Escape `&`, `<` and `>` for Telegram's HTML parse_mode, which rejects bare ones
38pub(crate) fn html_escape(s: &str) -> String {
39    s.replace('&', "&amp;")
40        .replace('<', "&lt;")
41        .replace('>', "&gt;")
42}
43
44/// Split content into chunks of at most `max_bytes`, never inside a UTF-8 character
45pub(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            // A single char over the limit still goes out whole
61            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/// A message received from any channel.
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct IncomingMessage {
77    /// Channel that produced this message (e.g. "github", "telegram", "discord")
78    pub channel: String,
79    /// Unique ID within the channel (comment ID, message ID, etc.)
80    pub id: String,
81    /// Thread/conversation context (issue number, chat ID, channel ID)
82    pub thread_id: String,
83    /// Author identifier
84    pub author: String,
85    /// Raw text content
86    pub body: String,
87    /// When the message was created
88    pub timestamp: chrono::DateTime<chrono::Utc>,
89    /// Optional metadata (labels, attachments, etc.)
90    #[serde(default)]
91    pub metadata: serde_json::Value,
92    /// Optional forum topic / thread ID (e.g. Telegram forum topic)
93    #[serde(default)]
94    pub topic_id: Option<String>,
95}
96
97/// A message to send to a channel.
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct OutgoingMessage {
100    /// Target thread/conversation
101    pub thread_id: String,
102    /// Message body (markdown)
103    pub body: String,
104    /// Optional: reply to a specific message ID
105    pub reply_to: Option<String>,
106    /// Optional metadata for channel-specific features
107    #[serde(default)]
108    pub metadata: serde_json::Value,
109    /// Optional forum topic / thread ID (e.g. Telegram forum topic)
110    #[serde(default)]
111    pub topic_id: Option<String>,
112}
113
114/// An agent output chunk for streaming.
115#[derive(Debug, Clone)]
116pub struct OutputChunk {
117    pub content: String,
118    pub is_final: bool,
119}
120
121/// The core channel trait. All external interfaces implement this.
122#[async_trait]
123pub trait Channel: Send + Sync {
124    /// Human-readable channel name.
125    fn name(&self) -> &str;
126
127    /// Start listening for incoming messages.
128    /// Returns a receiver that the engine polls.
129    async fn start(&self) -> anyhow::Result<Receiver<IncomingMessage>>;
130
131    /// Send a message to a thread/conversation.
132    async fn send(&self, msg: &OutgoingMessage) -> anyhow::Result<()>;
133
134    /// Acknowledge an interactive callback to dismiss the loading indicator.
135    ///
136    /// Telegram requires `answerCallbackQuery` to dismiss the spinner after a button press.
137    /// Discord buttons are already acknowledged in the websocket handler — no-op here.
138    /// Default implementation is a no-op so non-interactive channels need not implement it.
139    async fn ack_interaction(&self, _callback_query_id: &str) -> anyhow::Result<()> {
140        Ok(())
141    }
142
143    /// Check if this channel is healthy/connected.
144    async fn health_check(&self) -> anyhow::Result<()>;
145
146    /// Stop listening and close the connection. A later `start` listens again
147    async fn stop(&self) {}
148}
149
150/// The task a channel listens in, so `stop` can end it
151#[derive(Debug, Default)]
152pub(crate) struct Poller(Mutex<Option<AbortHandle>>);
153
154impl Poller {
155    /// Keep `task` as the listener and end the one before it
156    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
175/// Registry of active channels.
176pub 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}