zeptoclaw 0.3.1

Ultra-lightweight personal AI assistant framework
Documentation
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! Channel Manager for ZeptoClaw
//!
//! This module provides the `ChannelManager` which is responsible for:
//! - Registering and managing multiple communication channels
//! - Starting and stopping all channels
//! - Dispatching outbound messages to the appropriate channels

use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{watch, RwLock};
use tokio::task::JoinHandle;
use tracing::{error, info, warn};

use crate::bus::{MessageBus, OutboundMessage};
use crate::config::Config;
use crate::error::Result;

use super::Channel;

/// The `ChannelManager` manages the lifecycle of all communication channels.
///
/// It provides methods to:
/// - Register new channels
/// - Start and stop all channels
/// - Route outbound messages to the correct channel
/// - List all registered channels
///
/// # Architecture
///
/// ```text
/// ┌─────────────────────────────────────────────────────────────┐
/// │                     ChannelManager                          │
/// │  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐       │
/// │  │Telegram │  │ Discord │  │  Slack  │  │WhatsApp │  ...  │
/// │  └────┬────┘  └────┬────┘  └────┬────┘  └────┬────┘       │
/// │       │            │            │            │              │
/// │       └────────────┴─────┬──────┴────────────┘              │
/// │                          │                                  │
/// │                    ┌─────┴─────┐                           │
/// │                    │MessageBus │                           │
/// │                    └───────────┘                           │
/// └─────────────────────────────────────────────────────────────┘
/// ```
///
/// # Example
///
/// ```ignore
/// use std::sync::Arc;
/// use zeptoclaw::bus::MessageBus;
/// use zeptoclaw::config::Config;
/// use zeptoclaw::channels::ChannelManager;
///
/// #[tokio::main]
/// async fn main() {
///     let bus = Arc::new(MessageBus::new());
///     let config = Config::default();
///     let manager = ChannelManager::new(bus, config);
///
///     // Register channels
///     // manager.register(Box::new(TelegramChannel::new(...))).await;
///
///     // Start all channels
///     manager.start_all().await.unwrap();
/// }
/// ```
pub struct ChannelManager {
    /// Map of channel name to channel instance
    channels: Arc<RwLock<HashMap<String, Box<dyn Channel>>>>,
    /// Reference to the message bus for routing
    bus: Arc<MessageBus>,
    /// Global configuration
    #[allow(dead_code)]
    config: Config,
    /// Shutdown signal sender for dispatcher
    shutdown_tx: watch::Sender<bool>,
    /// Shutdown signal receiver (cloneable)
    shutdown_rx: watch::Receiver<bool>,
    /// Handle to the dispatcher task (if running)
    dispatcher_handle: Arc<RwLock<Option<JoinHandle<()>>>>,
}

impl ChannelManager {
    /// Creates a new `ChannelManager` with the given message bus and configuration.
    ///
    /// # Arguments
    ///
    /// * `bus` - The message bus for routing messages
    /// * `config` - The global configuration
    ///
    /// # Example
    ///
    /// ```
    /// use std::sync::Arc;
    /// use zeptoclaw::bus::MessageBus;
    /// use zeptoclaw::config::Config;
    /// use zeptoclaw::channels::ChannelManager;
    ///
    /// let bus = Arc::new(MessageBus::new());
    /// let config = Config::default();
    /// let manager = ChannelManager::new(bus, config);
    /// ```
    pub fn new(bus: Arc<MessageBus>, config: Config) -> Self {
        let (shutdown_tx, shutdown_rx) = watch::channel(false);
        Self {
            channels: Arc::new(RwLock::new(HashMap::new())),
            bus,
            config,
            shutdown_tx,
            shutdown_rx,
            dispatcher_handle: Arc::new(RwLock::new(None)),
        }
    }

    /// Registers a new channel with the manager.
    ///
    /// The channel is stored by its name and can be started later with `start_all()`.
    ///
    /// # Arguments
    ///
    /// * `channel` - The channel to register
    ///
    /// # Example
    ///
    /// ```ignore
    /// let manager = ChannelManager::new(bus, config);
    /// manager.register(Box::new(telegram_channel)).await;
    /// ```
    pub async fn register(&self, channel: Box<dyn Channel>) {
        let name = channel.name().to_string();
        info!("Registering channel: {}", name);
        let mut channels = self.channels.write().await;
        channels.insert(name, channel);
    }

    /// Returns a list of all registered channel names.
    ///
    /// # Example
    ///
    /// ```
    /// use std::sync::Arc;
    /// use zeptoclaw::bus::MessageBus;
    /// use zeptoclaw::config::Config;
    /// use zeptoclaw::channels::ChannelManager;
    ///
    /// # tokio_test::block_on(async {
    /// let bus = Arc::new(MessageBus::new());
    /// let config = Config::default();
    /// let manager = ChannelManager::new(bus, config);
    ///
    /// let channels = manager.channels().await;
    /// assert!(channels.is_empty());
    /// # })
    /// ```
    pub async fn channels(&self) -> Vec<String> {
        let channels = self.channels.read().await;
        channels.keys().cloned().collect()
    }

    /// Returns the number of registered channels.
    pub async fn channel_count(&self) -> usize {
        let channels = self.channels.read().await;
        channels.len()
    }

    /// Checks if a channel with the given name is registered.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the channel to check
    pub async fn has_channel(&self, name: &str) -> bool {
        let channels = self.channels.read().await;
        channels.contains_key(name)
    }

    /// Starts all registered channels.
    ///
    /// This method:
    /// 1. Iterates over all registered channels and starts each one
    /// 2. Spawns a background task to dispatch outbound messages
    ///
    /// Errors from individual channels are logged but do not prevent
    /// other channels from starting.
    ///
    /// # Errors
    ///
    /// Returns `Ok(())` even if individual channels fail to start.
    /// Check logs for channel-specific errors.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let manager = ChannelManager::new(bus, config);
    /// manager.register(Box::new(telegram_channel)).await;
    /// manager.start_all().await?;
    /// ```
    pub async fn start_all(&self) -> Result<()> {
        // Check if dispatcher is already running to prevent multiple dispatcher tasks
        {
            let dispatcher_handle = self.dispatcher_handle.read().await;
            if let Some(ref handle) = *dispatcher_handle {
                if !handle.is_finished() {
                    warn!("Dispatcher already running, skipping start");
                    return Ok(());
                }
            }
        }

        let mut channels = self.channels.write().await;
        for (name, channel) in channels.iter_mut() {
            info!("Starting channel: {}", name);
            if let Err(e) = channel.start().await {
                error!("Failed to start channel {}: {}", name, e);
            }
        }
        drop(channels); // Release the write lock before spawning

        // Reset shutdown signal for fresh start
        let _ = self.shutdown_tx.send(false);

        // Start outbound dispatcher
        let bus = self.bus.clone();
        let channels_ref = self.channels.clone();
        let shutdown_rx = self.shutdown_rx.clone();
        let handle = tokio::spawn(async move {
            dispatch_outbound(bus, channels_ref, shutdown_rx).await;
        });

        // Store the handle so we can wait for it to stop
        let mut dispatcher_handle = self.dispatcher_handle.write().await;
        *dispatcher_handle = Some(handle);

        Ok(())
    }

    /// Stops all registered channels.
    ///
    /// Errors from individual channels are logged but do not prevent
    /// other channels from stopping.
    ///
    /// # Errors
    ///
    /// Returns `Ok(())` even if individual channels fail to stop.
    /// Check logs for channel-specific errors.
    ///
    /// # Example
    ///
    /// ```ignore
    /// manager.stop_all().await?;
    /// ```
    pub async fn stop_all(&self) -> Result<()> {
        // Signal the dispatcher to stop
        info!("Signaling dispatcher to stop");
        let _ = self.shutdown_tx.send(true);

        // Wait for dispatcher to finish (with timeout)
        let mut dispatcher_handle = self.dispatcher_handle.write().await;
        if let Some(handle) = dispatcher_handle.take() {
            match tokio::time::timeout(std::time::Duration::from_secs(5), handle).await {
                Ok(_) => info!("Dispatcher stopped cleanly"),
                Err(_) => warn!("Dispatcher did not stop within timeout"),
            }
        }

        // Stop all channels
        let mut channels = self.channels.write().await;
        for (name, channel) in channels.iter_mut() {
            info!("Stopping channel: {}", name);
            if let Err(e) = channel.stop().await {
                error!("Failed to stop channel {}: {}", name, e);
            }
        }
        Ok(())
    }

    /// Sends a message to a specific channel.
    ///
    /// # Arguments
    ///
    /// * `channel_name` - The name of the channel to send to
    /// * `msg` - The outbound message to send
    ///
    /// # Errors
    ///
    /// Returns an error if the channel fails to send the message.
    /// If the channel is not found, a warning is logged and `Ok(())` is returned.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let msg = OutboundMessage::new("telegram", "chat123", "Hello!");
    /// manager.send("telegram", msg).await?;
    /// ```
    pub async fn send(&self, channel_name: &str, msg: OutboundMessage) -> Result<()> {
        let channels = self.channels.read().await;
        if let Some(channel) = channels.get(channel_name) {
            channel.send(msg).await
        } else {
            warn!("Channel not found: {}", channel_name);
            Ok(())
        }
    }

    /// Returns a reference to the message bus.
    pub fn bus(&self) -> Arc<MessageBus> {
        self.bus.clone()
    }
}

/// Background task that dispatches outbound messages from the bus to channels.
///
/// This function runs in a loop, consuming outbound messages from the bus
/// and routing them to the appropriate channel based on the message's
/// `channel` field. It stops when the shutdown signal is received.
///
/// # Arguments
///
/// * `bus` - The message bus to consume from
/// * `channels` - The shared map of channels
/// * `shutdown_rx` - Receiver for shutdown signals
async fn dispatch_outbound(
    bus: Arc<MessageBus>,
    channels: Arc<RwLock<HashMap<String, Box<dyn Channel>>>>,
    mut shutdown_rx: watch::Receiver<bool>,
) {
    info!("Outbound dispatcher started");
    loop {
        tokio::select! {
            // Check for shutdown signal
            _ = shutdown_rx.changed() => {
                if *shutdown_rx.borrow() {
                    info!("Outbound dispatcher received shutdown signal");
                    break;
                }
            }
            // Wait for outbound messages
            msg = bus.consume_outbound() => {
                if let Some(msg) = msg {
                    let channel_name = msg.channel.clone();
                    let channels = channels.read().await;
                    if let Some(channel) = channels.get(&channel_name) {
                        if let Err(e) = channel.send(msg.clone()).await {
                            error!("Failed to send message to {}: {}", channel_name, e);
                        }
                    } else {
                        warn!("Unknown channel for outbound message: {}", channel_name);
                    }
                } else {
                    // Channel closed
                    info!("Outbound channel closed");
                    break;
                }
            }
        }
    }
    info!("Outbound dispatcher stopped");
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use std::sync::atomic::{AtomicBool, Ordering};

    /// A mock channel for testing
    struct MockChannel {
        name: String,
        running: Arc<AtomicBool>,
        allowlist: Vec<String>,
    }

    impl MockChannel {
        fn new(name: &str) -> Self {
            Self {
                name: name.to_string(),
                running: Arc::new(AtomicBool::new(false)),
                allowlist: Vec::new(),
            }
        }

        fn with_allowlist(name: &str, allowlist: Vec<String>) -> Self {
            Self {
                name: name.to_string(),
                running: Arc::new(AtomicBool::new(false)),
                allowlist,
            }
        }
    }

    #[async_trait]
    impl Channel for MockChannel {
        fn name(&self) -> &str {
            &self.name
        }

        async fn start(&mut self) -> Result<()> {
            self.running.store(true, Ordering::SeqCst);
            Ok(())
        }

        async fn stop(&mut self) -> Result<()> {
            self.running.store(false, Ordering::SeqCst);
            Ok(())
        }

        async fn send(&self, _msg: OutboundMessage) -> Result<()> {
            Ok(())
        }

        fn is_running(&self) -> bool {
            self.running.load(Ordering::SeqCst)
        }

        fn is_allowed(&self, user_id: &str) -> bool {
            self.allowlist.is_empty() || self.allowlist.contains(&user_id.to_string())
        }
    }

    #[tokio::test]
    async fn test_channel_manager_creation() {
        let bus = Arc::new(MessageBus::new());
        let config = Config::default();
        let manager = ChannelManager::new(bus, config);
        assert!(manager.channels().await.is_empty());
    }

    #[tokio::test]
    async fn test_register_channel() {
        let bus = Arc::new(MessageBus::new());
        let config = Config::default();
        let manager = ChannelManager::new(bus, config);

        let channel = MockChannel::new("test");
        manager.register(Box::new(channel)).await;

        let channels = manager.channels().await;
        assert_eq!(channels.len(), 1);
        assert!(channels.contains(&"test".to_string()));
    }

    #[tokio::test]
    async fn test_register_multiple_channels() {
        let bus = Arc::new(MessageBus::new());
        let config = Config::default();
        let manager = ChannelManager::new(bus, config);

        manager
            .register(Box::new(MockChannel::new("telegram")))
            .await;
        manager
            .register(Box::new(MockChannel::new("discord")))
            .await;
        manager.register(Box::new(MockChannel::new("slack"))).await;

        assert_eq!(manager.channel_count().await, 3);
        assert!(manager.has_channel("telegram").await);
        assert!(manager.has_channel("discord").await);
        assert!(manager.has_channel("slack").await);
        assert!(!manager.has_channel("whatsapp").await);
    }

    #[tokio::test]
    async fn test_start_all() {
        let bus = Arc::new(MessageBus::new());
        let config = Config::default();
        let manager = ChannelManager::new(bus, config);

        let channel = MockChannel::new("test");
        manager.register(Box::new(channel)).await;

        manager.start_all().await.unwrap();

        // Give the dispatcher task time to start
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
    }

    #[tokio::test]
    async fn test_stop_all() {
        let bus = Arc::new(MessageBus::new());
        let config = Config::default();
        let manager = ChannelManager::new(bus, config);

        manager.register(Box::new(MockChannel::new("test"))).await;
        manager.start_all().await.unwrap();
        manager.stop_all().await.unwrap();
    }

    #[tokio::test]
    async fn test_double_start_prevented() {
        // Regression test: calling start_all() twice should not spawn multiple dispatchers
        let bus = Arc::new(MessageBus::new());
        let config = Config::default();
        let manager = ChannelManager::new(bus, config);

        manager.register(Box::new(MockChannel::new("test"))).await;

        // First start
        manager.start_all().await.unwrap();
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;

        // Second start should be a no-op (dispatcher already running)
        manager.start_all().await.unwrap();

        // Clean shutdown
        manager.stop_all().await.unwrap();
    }

    #[tokio::test]
    async fn test_send_to_unknown_channel() {
        let bus = Arc::new(MessageBus::new());
        let config = Config::default();
        let manager = ChannelManager::new(bus, config);

        let msg = OutboundMessage::new("unknown", "chat123", "Hello");
        let result = manager.send("unknown", msg).await;
        assert!(result.is_ok()); // Should not error, just warn
    }

    #[tokio::test]
    async fn test_send_to_registered_channel() {
        let bus = Arc::new(MessageBus::new());
        let config = Config::default();
        let manager = ChannelManager::new(bus, config);

        manager.register(Box::new(MockChannel::new("test"))).await;

        let msg = OutboundMessage::new("test", "chat123", "Hello");
        let result = manager.send("test", msg).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_channel_allowlist() {
        let channel = MockChannel::with_allowlist("test", vec!["user1".to_string()]);
        assert!(channel.is_allowed("user1"));
        assert!(!channel.is_allowed("user2"));
    }

    #[tokio::test]
    async fn test_channel_empty_allowlist() {
        let channel = MockChannel::new("test");
        assert!(channel.is_allowed("anyone"));
    }

    #[tokio::test]
    async fn test_bus_reference() {
        let bus = Arc::new(MessageBus::new());
        let config = Config::default();
        let manager = ChannelManager::new(bus.clone(), config);

        // The bus reference should be the same
        assert!(Arc::ptr_eq(&bus, &manager.bus()));
    }
}