zeptoclaw 0.7.2

Ultra-lightweight personal AI assistant
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
//! Message types for the ZeptoClaw message bus
//!
//! This module defines the core message types used for communication
//! between channels, agents, and the message bus.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Represents an incoming message from a channel (e.g., Telegram, Discord, etc.)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InboundMessage {
    /// The channel this message came from (e.g., "telegram", "discord")
    pub channel: String,
    /// Unique identifier of the sender
    pub sender_id: String,
    /// Unique identifier of the chat/conversation
    pub chat_id: String,
    /// The text content of the message
    pub content: String,
    /// Media attachments (zero or more)
    pub media: Vec<MediaAttachment>,
    /// Session key for routing (format: "channel:chat_id")
    pub session_key: String,
    /// Additional metadata key-value pairs
    pub metadata: HashMap<String, String>,
}

/// Represents an outgoing message to be sent via a channel
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutboundMessage {
    /// The channel to send this message through
    pub channel: String,
    /// The chat/conversation to send to
    pub chat_id: String,
    /// The text content to send
    pub content: String,
    /// Optional message ID to reply to
    pub reply_to: Option<String>,
    /// Additional metadata key-value pairs for channel-specific delivery hints
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, String>,
}

/// Represents a media attachment (image, audio, video, or document)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MediaAttachment {
    /// The type of media
    pub media_type: MediaType,
    /// URL to the media (if hosted remotely)
    pub url: Option<String>,
    /// Raw binary data (if available locally)
    pub data: Option<Vec<u8>>,
    /// Original filename
    pub filename: Option<String>,
    /// Explicit MIME type (e.g., "image/jpeg", "image/png")
    pub mime_type: Option<String>,
}

/// Types of media that can be attached to messages
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum MediaType {
    /// Image files (PNG, JPG, GIF, etc.)
    Image,
    /// Audio files (MP3, WAV, OGG, etc.)
    Audio,
    /// Video files (MP4, WebM, etc.)
    Video,
    /// Document files (PDF, DOCX, etc.)
    Document,
}

impl InboundMessage {
    /// Creates a new inbound message with the required fields.
    ///
    /// The session key is automatically generated as "channel:chat_id".
    ///
    /// # Arguments
    /// * `channel` - The source channel (e.g., "telegram")
    /// * `sender_id` - Unique identifier of the message sender
    /// * `chat_id` - Unique identifier of the chat/conversation
    /// * `content` - The text content of the message
    ///
    /// # Example
    /// ```
    /// use zeptoclaw::bus::message::InboundMessage;
    ///
    /// let msg = InboundMessage::new("telegram", "user123", "chat456", "Hello, bot!");
    /// assert_eq!(msg.session_key, "telegram:chat456");
    /// ```
    pub fn new(channel: &str, sender_id: &str, chat_id: &str, content: &str) -> Self {
        Self {
            channel: channel.to_string(),
            sender_id: sender_id.to_string(),
            chat_id: chat_id.to_string(),
            content: content.to_string(),
            media: Vec::new(),
            session_key: format!("{}:{}", channel, chat_id),
            metadata: HashMap::new(),
        }
    }

    /// Attaches media to the message (builder pattern).
    ///
    /// Multiple calls push additional attachments; calling `.with_media()` twice
    /// results in a message with two attachments.
    ///
    /// # Example
    /// ```
    /// use zeptoclaw::bus::message::{InboundMessage, MediaAttachment, MediaType};
    ///
    /// let media = MediaAttachment::new(MediaType::Image).with_url("https://example.com/image.png");
    /// let msg = InboundMessage::new("telegram", "user123", "chat456", "Check this out!")
    ///     .with_media(media);
    /// assert!(!msg.media.is_empty());
    /// ```
    pub fn with_media(mut self, media: MediaAttachment) -> Self {
        self.media.push(media);
        self
    }

    /// Adds a metadata key-value pair to the message (builder pattern).
    ///
    /// # Example
    /// ```
    /// use zeptoclaw::bus::message::InboundMessage;
    ///
    /// let msg = InboundMessage::new("telegram", "user123", "chat456", "Hello")
    ///     .with_metadata("message_id", "12345")
    ///     .with_metadata("is_bot", "false");
    /// assert_eq!(msg.metadata.get("message_id"), Some(&"12345".to_string()));
    /// ```
    pub fn with_metadata(mut self, key: &str, value: &str) -> Self {
        self.metadata.insert(key.to_string(), value.to_string());
        self
    }

    /// Checks if this message has any media attached.
    pub fn has_media(&self) -> bool {
        !self.media.is_empty()
    }
}

impl OutboundMessage {
    /// Creates a new outbound message.
    ///
    /// # Arguments
    /// * `channel` - The target channel (e.g., "telegram")
    /// * `chat_id` - The chat/conversation to send to
    /// * `content` - The text content to send
    ///
    /// # Example
    /// ```
    /// use zeptoclaw::bus::message::OutboundMessage;
    ///
    /// let msg = OutboundMessage::new("telegram", "chat456", "Hello from the bot!");
    /// assert_eq!(msg.channel, "telegram");
    /// ```
    pub fn new(channel: &str, chat_id: &str, content: &str) -> Self {
        Self {
            channel: channel.to_string(),
            chat_id: chat_id.to_string(),
            content: content.to_string(),
            reply_to: None,
            metadata: HashMap::new(),
        }
    }

    /// Sets the message ID to reply to (builder pattern).
    ///
    /// # Example
    /// ```
    /// use zeptoclaw::bus::message::OutboundMessage;
    ///
    /// let msg = OutboundMessage::new("telegram", "chat456", "This is a reply")
    ///     .with_reply("original_msg_123");
    /// assert_eq!(msg.reply_to, Some("original_msg_123".to_string()));
    /// ```
    pub fn with_reply(mut self, message_id: &str) -> Self {
        self.reply_to = Some(message_id.to_string());
        self
    }

    /// Adds a metadata key-value pair to the outbound message.
    pub fn with_metadata(mut self, key: &str, value: &str) -> Self {
        self.metadata.insert(key.to_string(), value.to_string());
        self
    }

    /// Creates an outbound message as a response to an inbound message.
    ///
    /// # Example
    /// ```
    /// use zeptoclaw::bus::message::{InboundMessage, OutboundMessage};
    ///
    /// let inbound = InboundMessage::new("telegram", "user123", "chat456", "Hello");
    /// let response = OutboundMessage::reply_to(&inbound, "Hello back!");
    /// assert_eq!(response.channel, "telegram");
    /// assert_eq!(response.chat_id, "chat456");
    /// ```
    pub fn reply_to(msg: &InboundMessage, content: &str) -> Self {
        Self::new(&msg.channel, &msg.chat_id, content)
    }
}

impl MediaAttachment {
    /// Creates a new media attachment of the specified type.
    pub fn new(media_type: MediaType) -> Self {
        Self {
            media_type,
            url: None,
            data: None,
            filename: None,
            mime_type: None,
        }
    }

    /// Sets the URL for the media (builder pattern).
    pub fn with_url(mut self, url: &str) -> Self {
        self.url = Some(url.to_string());
        self
    }

    /// Sets the raw binary data (builder pattern).
    pub fn with_data(mut self, data: Vec<u8>) -> Self {
        self.data = Some(data);
        self
    }

    /// Sets the filename (builder pattern).
    pub fn with_filename(mut self, filename: &str) -> Self {
        self.filename = Some(filename.to_string());
        self
    }

    /// Sets the MIME type for the media (builder pattern).
    ///
    /// # Example
    /// ```
    /// use zeptoclaw::bus::message::{MediaAttachment, MediaType};
    ///
    /// let media = MediaAttachment::new(MediaType::Image)
    ///     .with_mime_type("image/webp");
    /// assert_eq!(media.mime_type, Some("image/webp".to_string()));
    /// ```
    pub fn with_mime_type(mut self, mime_type: &str) -> Self {
        self.mime_type = Some(mime_type.to_string());
        self
    }

    /// Checks if the media has a URL.
    pub fn has_url(&self) -> bool {
        self.url.is_some()
    }

    /// Checks if the media has binary data.
    pub fn has_data(&self) -> bool {
        self.data.is_some()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_inbound_message_creation() {
        let msg = InboundMessage::new("telegram", "user123", "chat456", "Hello");
        assert_eq!(msg.channel, "telegram");
        assert_eq!(msg.sender_id, "user123");
        assert_eq!(msg.chat_id, "chat456");
        assert_eq!(msg.content, "Hello");
        assert_eq!(msg.session_key, "telegram:chat456");
        assert!(msg.media.is_empty());
        assert!(msg.metadata.is_empty());
    }

    #[test]
    fn test_inbound_message_with_media() {
        let media = MediaAttachment::new(MediaType::Image)
            .with_url("https://example.com/image.png")
            .with_filename("image.png");

        let msg =
            InboundMessage::new("discord", "user1", "channel1", "Check this").with_media(media);

        assert!(msg.has_media());
        let attachment = msg.media.first().unwrap();
        assert_eq!(attachment.media_type, MediaType::Image);
        assert_eq!(
            attachment.url,
            Some("https://example.com/image.png".to_string())
        );
        assert_eq!(attachment.filename, Some("image.png".to_string()));
    }

    #[test]
    fn test_inbound_message_with_metadata() {
        let msg = InboundMessage::new("telegram", "user123", "chat456", "Hello")
            .with_metadata("message_id", "12345")
            .with_metadata("timestamp", "2024-01-01T00:00:00Z");

        assert_eq!(msg.metadata.len(), 2);
        assert_eq!(msg.metadata.get("message_id"), Some(&"12345".to_string()));
        assert_eq!(
            msg.metadata.get("timestamp"),
            Some(&"2024-01-01T00:00:00Z".to_string())
        );
    }

    #[test]
    fn test_outbound_message_creation() {
        let msg = OutboundMessage::new("telegram", "chat456", "Response");
        assert_eq!(msg.channel, "telegram");
        assert_eq!(msg.chat_id, "chat456");
        assert_eq!(msg.content, "Response");
        assert!(msg.reply_to.is_none());
        assert!(msg.metadata.is_empty());
    }

    #[test]
    fn test_outbound_message_with_reply() {
        let msg = OutboundMessage::new("telegram", "chat456", "This is a reply")
            .with_reply("original_msg_123");

        assert_eq!(msg.reply_to, Some("original_msg_123".to_string()));
    }

    #[test]
    fn test_outbound_message_with_metadata() {
        let msg = OutboundMessage::new("discord", "channel1", "Hello")
            .with_metadata("discord_thread_name", "Daily Updates")
            .with_metadata("discord_thread_auto_archive_minutes", "60");

        assert_eq!(
            msg.metadata.get("discord_thread_name"),
            Some(&"Daily Updates".to_string())
        );
        assert_eq!(
            msg.metadata.get("discord_thread_auto_archive_minutes"),
            Some(&"60".to_string())
        );
    }

    #[test]
    fn test_outbound_reply_to_inbound() {
        let inbound = InboundMessage::new("telegram", "user123", "chat456", "Hello");
        let response = OutboundMessage::reply_to(&inbound, "Hello back!");

        assert_eq!(response.channel, "telegram");
        assert_eq!(response.chat_id, "chat456");
        assert_eq!(response.content, "Hello back!");
    }

    #[test]
    fn test_media_attachment_creation() {
        let media = MediaAttachment::new(MediaType::Audio)
            .with_url("https://example.com/audio.mp3")
            .with_data(vec![1, 2, 3, 4])
            .with_filename("audio.mp3");

        assert_eq!(media.media_type, MediaType::Audio);
        assert!(media.has_url());
        assert!(media.has_data());
        assert_eq!(media.filename, Some("audio.mp3".to_string()));
    }

    #[test]
    fn test_media_type_equality() {
        assert_eq!(MediaType::Image, MediaType::Image);
        assert_ne!(MediaType::Image, MediaType::Audio);
        assert_ne!(MediaType::Video, MediaType::Document);
    }

    #[test]
    fn test_inbound_message_with_multiple_media() {
        let media1 = MediaAttachment::new(MediaType::Image)
            .with_data(vec![0xFF, 0xD8])
            .with_mime_type("image/jpeg");
        let media2 = MediaAttachment::new(MediaType::Image)
            .with_data(vec![0x89, 0x50])
            .with_mime_type("image/png");

        let msg = InboundMessage::new("telegram", "user1", "chat1", "Two images")
            .with_media(media1)
            .with_media(media2);

        assert_eq!(msg.media.len(), 2);
        assert!(msg.has_media());
    }

    #[test]
    fn test_media_attachment_mime_type() {
        let media = MediaAttachment::new(MediaType::Image).with_mime_type("image/webp");
        assert_eq!(media.mime_type, Some("image/webp".to_string()));
    }

    #[test]
    fn test_message_serialization() {
        let msg = InboundMessage::new("telegram", "user123", "chat456", "Hello")
            .with_metadata("key", "value");

        let json = serde_json::to_string(&msg).expect("Failed to serialize");
        let deserialized: InboundMessage =
            serde_json::from_str(&json).expect("Failed to deserialize");

        assert_eq!(deserialized.channel, "telegram");
        assert_eq!(deserialized.content, "Hello");
        assert_eq!(deserialized.metadata.get("key"), Some(&"value".to_string()));
    }

    #[test]
    fn test_outbound_message_serialization() {
        let msg = OutboundMessage::new("discord", "channel1", "Hello Discord!")
            .with_reply("msg_123")
            .with_metadata("discord_thread_name", "ops-thread");

        let json = serde_json::to_string(&msg).expect("Failed to serialize");
        let deserialized: OutboundMessage =
            serde_json::from_str(&json).expect("Failed to deserialize");

        assert_eq!(deserialized.channel, "discord");
        assert_eq!(deserialized.reply_to, Some("msg_123".to_string()));
        assert_eq!(
            deserialized.metadata.get("discord_thread_name"),
            Some(&"ops-thread".to_string())
        );
    }
}