1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
use async_trait::async_trait;
/// A message received from or sent to a channel
#[derive(Debug, Clone)]
pub struct ChannelMessage {
pub id: String,
pub sender: String,
pub reply_target: String,
pub content: String,
pub channel: String,
pub timestamp: u64,
/// Platform thread identifier (e.g. Slack `ts`, Discord thread ID).
/// When set, replies should be posted as threaded responses.
pub thread_ts: Option<String>,
}
/// Message to send through a channel
#[derive(Debug, Clone)]
pub struct SendMessage {
pub content: String,
pub recipient: String,
pub subject: Option<String>,
/// Platform thread identifier for threaded replies (e.g. Slack `thread_ts`).
pub thread_ts: Option<String>,
/// Caller-provided or generated idempotency key for retry-safe delivery.
pub idempotency_key: Option<String>,
}
impl SendMessage {
/// Create a new message with content and recipient
pub fn new(content: impl Into<String>, recipient: impl Into<String>) -> Self {
Self {
content: content.into(),
recipient: recipient.into(),
subject: None,
thread_ts: None,
idempotency_key: None,
}
}
/// Create a new message with content, recipient, and subject
pub fn with_subject(
content: impl Into<String>,
recipient: impl Into<String>,
subject: impl Into<String>,
) -> Self {
Self {
content: content.into(),
recipient: recipient.into(),
subject: Some(subject.into()),
thread_ts: None,
idempotency_key: None,
}
}
/// Set the thread identifier for threaded replies.
pub fn in_thread(mut self, thread_ts: Option<String>) -> Self {
self.thread_ts = thread_ts;
self
}
/// Set an explicit idempotency key for retry-safe delivery.
pub fn with_idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
let idempotency_key = idempotency_key.into();
self.idempotency_key = (!idempotency_key.trim().is_empty()).then_some(idempotency_key);
self
}
/// Generate a deterministic idempotency key from this legacy send shape.
pub fn with_deterministic_idempotency_key(mut self, channel_id: impl AsRef<str>) -> Self {
let intent = crate::channel::outbound_intent_from_send_message(channel_id.as_ref(), &self);
self.idempotency_key = Some(intent.idempotency_key);
self
}
}
/// Core channel trait — implement for any messaging platform
#[async_trait]
pub trait Channel: Send + Sync {
/// Human-readable channel name
fn name(&self) -> &str;
/// Resolve the delivery target for a *recipient-less* proactive send (cron /
/// heartbeat), where the caller has no inbound message to reply to.
///
/// Returns the channel's configured default target (e.g. Discord's
/// `channel_id`) or `None` when the channel has no target it can deliver to
/// without an explicit recipient. Proactive routing skips channels that
/// return `None` instead of POSTing to an empty recipient (#3794 review —
/// Codex P2; Telegram has no configured default chat, so its `send` would
/// otherwise call the Bot API with an empty `chat_id`). Default `None` keeps
/// every existing provider opted out until it wires a real target.
fn proactive_target(&self) -> Option<String> {
None
}
/// Send a message through this channel
async fn send(&self, message: &SendMessage) -> anyhow::Result<()>;
/// Start listening for incoming messages (long-running)
async fn listen(&self, tx: tokio::sync::mpsc::Sender<ChannelMessage>) -> anyhow::Result<()>;
/// Check if channel is healthy
async fn health_check(&self) -> bool {
true
}
/// Signal that the bot is processing a response (e.g. "typing" indicator).
/// Implementations should repeat the indicator as needed for their platform.
async fn start_typing(&self, _recipient: &str) -> anyhow::Result<()> {
Ok(())
}
/// Stop any active typing indicator.
async fn stop_typing(&self, _recipient: &str) -> anyhow::Result<()> {
Ok(())
}
/// Whether this channel supports native emoji reactions on messages.
/// Channels that return `true` must handle `[REACTION:<emoji>]` content in `send()`.
fn supports_reactions(&self) -> bool {
false
}
/// Whether this channel supports progressive message updates via draft edits.
fn supports_draft_updates(&self) -> bool {
false
}
/// Send an initial draft message. Returns a platform-specific message ID for later edits.
async fn send_draft(&self, _message: &SendMessage) -> anyhow::Result<Option<String>> {
Ok(None)
}
/// Update a previously sent draft message with new accumulated content.
async fn update_draft(
&self,
_recipient: &str,
_message_id: &str,
_text: &str,
) -> anyhow::Result<()> {
Ok(())
}
/// Finalize a draft with the complete response (e.g. apply Markdown formatting).
async fn finalize_draft(
&self,
_recipient: &str,
_message_id: &str,
_text: &str,
_thread_ts: Option<&str>,
) -> anyhow::Result<()> {
Ok(())
}
}
/// Extension helpers for legacy [`Channel::send`] callers that need the
/// portable outbound-intent idempotency contract without changing provider
/// implementations yet.
#[async_trait]
pub trait ChannelSendExt: Channel {
/// Build the outbound intent for a legacy send and pass its idempotency key
/// through [`SendMessage`] before delegating to [`Channel::send`].
async fn send_with_outbound_intent(&self, message: &SendMessage) -> anyhow::Result<()> {
let message = message
.clone()
.with_deterministic_idempotency_key(self.name());
self.send(&message).await
}
}
impl<T: Channel + ?Sized> ChannelSendExt for T {}
#[cfg(test)]
mod tests {
use super::*;
struct DummyChannel;
#[async_trait]
impl Channel for DummyChannel {
fn name(&self) -> &str {
"dummy"
}
async fn send(&self, _message: &SendMessage) -> anyhow::Result<()> {
Ok(())
}
async fn listen(
&self,
tx: tokio::sync::mpsc::Sender<ChannelMessage>,
) -> anyhow::Result<()> {
tx.send(ChannelMessage {
id: "1".into(),
sender: "tester".into(),
reply_target: "tester".into(),
content: "hello".into(),
channel: "dummy".into(),
timestamp: 123,
thread_ts: None,
})
.await
.map_err(|e| anyhow::anyhow!(e.to_string()))
}
}
#[test]
fn channel_message_clone_preserves_fields() {
let message = ChannelMessage {
id: "42".into(),
sender: "alice".into(),
reply_target: "alice".into(),
content: "ping".into(),
channel: "dummy".into(),
timestamp: 999,
thread_ts: None,
};
let cloned = message.clone();
assert_eq!(cloned.id, "42");
assert_eq!(cloned.sender, "alice");
assert_eq!(cloned.reply_target, "alice");
assert_eq!(cloned.content, "ping");
assert_eq!(cloned.channel, "dummy");
assert_eq!(cloned.timestamp, 999);
}
#[test]
fn send_message_generates_deterministic_idempotency_key() {
let message = SendMessage::new("hello", "alice")
.in_thread(Some("thread-1".to_string()))
.with_deterministic_idempotency_key("telegram");
let again = SendMessage::new("hello", "alice")
.in_thread(Some("thread-1".to_string()))
.with_deterministic_idempotency_key("telegram");
assert_eq!(message.idempotency_key, again.idempotency_key);
assert!(
message
.idempotency_key
.as_deref()
.unwrap()
.starts_with("legacy-send:telegram:")
);
}
#[test]
fn explicit_send_message_idempotency_key_is_preserved() {
let message = SendMessage::new("hello", "alice")
.with_idempotency_key("caller-key")
.with_deterministic_idempotency_key("telegram");
assert_eq!(message.idempotency_key.as_deref(), Some("caller-key"));
}
#[tokio::test]
async fn default_trait_methods_return_success() {
let channel = DummyChannel;
assert!(channel.health_check().await);
assert!(channel.start_typing("bob").await.is_ok());
assert!(channel.stop_typing("bob").await.is_ok());
assert!(
channel
.send(&SendMessage::new("hello", "bob"))
.await
.is_ok()
);
// A provider that does not override `proactive_target` opts out of
// recipient-less proactive delivery (#3794).
assert_eq!(channel.proactive_target(), None);
}
#[tokio::test]
async fn default_draft_methods_return_success() {
let channel = DummyChannel;
assert!(!channel.supports_draft_updates());
assert!(
channel
.send_draft(&SendMessage::new("draft", "bob"))
.await
.unwrap()
.is_none()
);
assert!(channel.update_draft("bob", "msg_1", "text").await.is_ok());
assert!(
channel
.finalize_draft("bob", "msg_1", "final text", None)
.await
.is_ok()
);
}
#[tokio::test]
async fn listen_sends_message_to_channel() {
let channel = DummyChannel;
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
channel.listen(tx).await.unwrap();
let received = rx.recv().await.expect("message should be sent");
assert_eq!(received.sender, "tester");
assert_eq!(received.content, "hello");
assert_eq!(received.channel, "dummy");
}
}