agent-office 0.0.1

A Rust-based multi-agent system with graph-structured data storage, mail system, and Zettelkasten-style knowledge base
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
use crate::domain::{Edge, GraphQuery, Properties, string_to_node_id};
use crate::services::mail::domain::{Agent, AgentId, Mail, Mailbox, MailboxId};
use crate::storage::{GraphStorage, StorageError};
use async_trait::async_trait;
use thiserror::Error;

pub mod domain;

#[derive(Error, Debug)]
pub enum MailError {
    #[error("Mailbox not found: {0}")]
    MailboxNotFound(MailboxId),
    
    #[error("Agent not found: {0}")]
    AgentNotFound(AgentId),
    
    #[error("Mail not found: {0}")]
    MailNotFound(uuid::Uuid),
    
    #[error("Storage error: {0}")]
    Storage(#[from] StorageError),
    
    #[error("Invalid operation: {0}")]
    InvalidOperation(String),
}

pub type Result<T> = std::result::Result<T, MailError>;

#[async_trait]
pub trait MailService: Send + Sync {
    // Agent operations
    async fn create_agent(&self, name: impl Into<String> + Send) -> Result<Agent>;
    async fn get_agent(&self, id: AgentId) -> Result<Agent>;
    async fn list_agents(&self) -> Result<Vec<Agent>>;
    async fn set_agent_status(&self, agent_id: AgentId, status: impl Into<String> + Send) -> Result<Agent>;
    
    // Get agent by their mailbox ID (each agent has exactly one mailbox)
    async fn get_agent_by_mailbox(&self, mailbox_id: MailboxId) -> Result<Agent>;
    
    // Get the single mailbox for an agent (auto-creates if doesn't exist)
    async fn get_agent_mailbox(&self, agent_id: AgentId) -> Result<Mailbox>;
    
    // Send mail from one agent to another
    async fn send_agent_to_agent(
        &self,
        from_agent_id: AgentId,
        to_agent_id: AgentId,
        subject: impl Into<String> + Send,
        body: impl Into<String> + Send,
    ) -> Result<Mail>;
    
    // Get mail received by an agent's mailbox
    async fn get_mailbox_inbox(&self, mailbox_id: MailboxId) -> Result<Vec<Mail>>;
    
    // Get mail sent by an agent's mailbox
    async fn get_mailbox_outbox(&self, mailbox_id: MailboxId) -> Result<Vec<Mail>>;
    
    // Get recent mail for an agent (received in last N hours)
    async fn get_recent_mail(&self, mailbox_id: MailboxId, hours: i64, limit: usize) -> Result<Vec<Mail>>;
    
    // Mark mail as read
    async fn mark_mail_as_read(&self, mail_id: uuid::Uuid) -> Result<Mail>;
    
    // Check if agent has unread mail
    async fn check_unread_mail(&self, agent_id: AgentId) -> Result<(bool, Vec<Mail>)>;
}

pub struct MailServiceImpl<S: GraphStorage> {
    storage: S,
}

impl<S: GraphStorage> MailServiceImpl<S> {
    pub fn new(storage: S) -> Self {
        Self { storage }
    }

    /// Helper to get mail by ID
    async fn get_mail(&self, mail_id: uuid::Uuid) -> Result<Mail> {
        let node = self.storage.get_node(mail_id).await
            .map_err(|e| match e {
                StorageError::NodeNotFound(_) => MailError::MailNotFound(mail_id),
                _ => MailError::Storage(e),
            })?;
        Mail::from_node(&node)
            .ok_or(MailError::MailNotFound(mail_id))
    }
}

#[async_trait]
impl<S: GraphStorage> MailService for MailServiceImpl<S> {
    async fn create_agent(&self, name: impl Into<String> + Send) -> Result<Agent> {
        let agent = Agent::new(name);
        let node = agent.to_node();
        self.storage.create_node(&node).await?;
        
        Ok(agent)
    }

    async fn get_agent(&self, id: AgentId) -> Result<Agent> {
        let node_id = string_to_node_id(&id);
        let id_clone = id.clone();
        let node = self.storage.get_node(node_id).await
            .map_err(|e| match e {
                StorageError::NodeNotFound(_) => MailError::AgentNotFound(id_clone),
                _ => MailError::Storage(e),
            })?;
        Agent::from_node(&node)
            .ok_or(MailError::AgentNotFound(id))
    }

    async fn list_agents(&self) -> Result<Vec<Agent>> {
        let query = GraphQuery::new().with_node_type("agent");
        let nodes = self.storage.query_nodes(&query).await?;
        let agents: Vec<Agent> = nodes.iter()
            .filter_map(Agent::from_node)
            .collect();
        Ok(agents)
    }

    async fn set_agent_status(&self, agent_id: AgentId, status: impl Into<String> + Send) -> Result<Agent> {
        let mut agent = self.get_agent(agent_id).await?;
        agent.status = status.into();
        let node = agent.to_node();
        self.storage.update_node(&node).await?;
        Ok(agent)
    }

    async fn get_agent_by_mailbox(&self, mailbox_id: MailboxId) -> Result<Agent> {
        // The mailbox ID is the agent's node ID, so get the agent directly
        let node = self.storage.get_node(mailbox_id).await
            .map_err(|e| match e {
                StorageError::NodeNotFound(_) => MailError::MailboxNotFound(mailbox_id),
                _ => MailError::Storage(e),
            })?;
        
        Agent::from_node(&node)
            .ok_or_else(|| MailError::InvalidOperation(
                "Node exists but is not an agent".to_string()
            ))
    }

    async fn get_agent_mailbox(&self, agent_id: AgentId) -> Result<Mailbox> {
        // Verify agent exists - the agent's node IS the mailbox
        let agent = self.get_agent(agent_id.clone()).await?;
        let node_id = string_to_node_id(&agent.id);
        
        // Create a mailbox representation from the agent
        let mailbox = Mailbox {
            id: node_id,
            owner_id: agent.id,
            name: "Mailbox".to_string(),
            created_at: agent.created_at,
        };
        
        Ok(mailbox)
    }

    async fn send_agent_to_agent(
        &self,
        from_agent_id: AgentId,
        to_agent_id: AgentId,
        subject: impl Into<String> + Send,
        body: impl Into<String> + Send,
    ) -> Result<Mail> {
        // Verify both agents exist
        let from_agent = self.get_agent(from_agent_id).await?;
        let to_agent = self.get_agent(to_agent_id).await?;
        
        // Use agent node IDs as mailbox IDs
        let from_mailbox_id = string_to_node_id(&from_agent.id);
        let to_mailbox_id = string_to_node_id(&to_agent.id);
        
        // Create mail
        let mail = Mail::new(from_mailbox_id, to_mailbox_id, subject, body);
        let node = mail.to_node();
        
        // Create mail node
        self.storage.create_node(&node).await?;
        
        // Create edges for sender and receiver
        let from_edge = Edge::new(
            "sent_from",
            from_mailbox_id,
            mail.id,
            Properties::new(),
        );
        self.storage.create_edge(&from_edge).await?;
        
        let to_edge = Edge::new(
            "sent_to",
            mail.id,
            to_mailbox_id,
            Properties::new(),
        );
        self.storage.create_edge(&to_edge).await?;
        
        Ok(mail)
    }

    async fn get_mailbox_inbox(&self, mailbox_id: MailboxId) -> Result<Vec<Mail>> {
        // Verify mailbox (agent) exists
        let _agent = self.storage.get_node(mailbox_id).await
            .map_err(|e| match e {
                StorageError::NodeNotFound(_) => MailError::MailboxNotFound(mailbox_id),
                _ => MailError::Storage(e),
            })?;
        
        // Get all mail where there's an edge from mail -> mailbox (sent_to)
        let incoming_edges = self.storage
            .get_edges_to(mailbox_id, Some("sent_to"))
            .await?;
        
        let mut mails = Vec::new();
        for edge in incoming_edges {
            if let Ok(mail) = self.get_mail(edge.from_node_id).await {
                mails.push(mail);
            }
        }
        
        // Sort by creation date, newest first
        mails.sort_by(|a, b| b.created_at.cmp(&a.created_at));
        
        Ok(mails)
    }

    async fn get_mailbox_outbox(&self, mailbox_id: MailboxId) -> Result<Vec<Mail>> {
        // Verify mailbox (agent) exists
        let _agent = self.storage.get_node(mailbox_id).await
            .map_err(|e| match e {
                StorageError::NodeNotFound(_) => MailError::MailboxNotFound(mailbox_id),
                _ => MailError::Storage(e),
            })?;
        
        // Get all mail where there's an edge from mailbox -> mail (sent_from)
        let outgoing_edges = self.storage
            .get_edges_from(mailbox_id, Some("sent_from"))
            .await?;
        
        let mut mails = Vec::new();
        for edge in outgoing_edges {
            if let Ok(mail) = self.get_mail(edge.to_node_id).await {
                mails.push(mail);
            }
        }
        
        // Sort by creation date, newest first
        mails.sort_by(|a, b| b.created_at.cmp(&a.created_at));
        
        Ok(mails)
    }

    async fn get_recent_mail(&self, mailbox_id: MailboxId, hours: i64, limit: usize) -> Result<Vec<Mail>> {
        let since = chrono::Utc::now() - chrono::Duration::hours(hours);
        
        // Get all mail in the inbox
        let inbox = self.get_mailbox_inbox(mailbox_id).await?;
        
        // Filter to recent mail only
        let recent: Vec<Mail> = inbox.into_iter()
            .filter(|mail| mail.created_at >= since)
            .take(limit)
            .collect();
        
        Ok(recent)
    }

    async fn mark_mail_as_read(&self, mail_id: uuid::Uuid) -> Result<Mail> {
        let mut mail = self.get_mail(mail_id).await?;
        mail.mark_as_read();
        
        let node = mail.to_node();
        self.storage.update_node(&node).await?;
        
        Ok(mail)
    }

    async fn check_unread_mail(&self, agent_id: AgentId) -> Result<(bool, Vec<Mail>)> {
        // Get the agent's mailbox ID
        let mailbox = self.get_agent_mailbox(agent_id).await?;
        
        // Get inbox and filter for unread
        let inbox = self.get_mailbox_inbox(mailbox.id).await?;
        let unread: Vec<Mail> = inbox.into_iter()
            .filter(|mail| !mail.read)
            .collect();
        
        let has_unread = !unread.is_empty();
        
        Ok((has_unread, unread))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::memory::InMemoryStorage;

    #[tokio::test]
    async fn test_create_agent() {
        let storage = InMemoryStorage::new();
        let service = MailServiceImpl::new(storage);
        
        let agent = service.create_agent("Test Agent").await.unwrap();
        assert_eq!(agent.name, "Test Agent");
    }

    #[tokio::test]
    async fn test_create_agent_auto_creates_mailbox() {
        let storage = InMemoryStorage::new();
        let service = MailServiceImpl::new(storage);
        
        let agent = service.create_agent("Agent").await.unwrap();
        
        // Should be able to get the mailbox for the agent
        let mailbox = service.get_agent_mailbox(agent.id.clone()).await.unwrap();
        assert_eq!(mailbox.owner_id, agent.id);
        
        // The mailbox ID should be the same as the agent's node ID
        let expected_mailbox_id = string_to_node_id(&agent.id);
        assert_eq!(mailbox.id, expected_mailbox_id);
    }

    #[tokio::test]
    async fn test_send_and_receive_mail() {
        let storage = InMemoryStorage::new();
        let service = MailServiceImpl::new(storage);
        
        // Create two agents - mailboxes are auto-created
        let agent1 = service.create_agent("Sender").await.unwrap();
        let agent2 = service.create_agent("Receiver").await.unwrap();
        
        // Send mail directly between agents
        let mail = service
            .send_agent_to_agent(
                agent1.id.clone(),
                agent2.id.clone(),
                "Hello",
                "This is a test message",
            )
            .await
            .unwrap();
        
        assert_eq!(mail.subject, "Hello");
        assert_eq!(mail.body, "This is a test message");
        assert!(!mail.read);
        
        // Check receiver's inbox
        let inbox = service.get_mailbox_inbox(string_to_node_id(&agent2.id)).await.unwrap();
        assert_eq!(inbox.len(), 1);
        assert_eq!(inbox[0].subject, "Hello");
        
        // Check sender's outbox
        let outbox = service.get_mailbox_outbox(string_to_node_id(&agent1.id)).await.unwrap();
        assert_eq!(outbox.len(), 1);
        assert_eq!(outbox[0].subject, "Hello");
    }

    #[tokio::test]
    async fn test_mark_mail_as_read() {
        let storage = InMemoryStorage::new();
        let service = MailServiceImpl::new(storage);
        
        let agent1 = service.create_agent("Sender").await.unwrap();
        let agent2 = service.create_agent("Receiver").await.unwrap();
        
        let mail = service
            .send_agent_to_agent(agent1.id, agent2.id, "Test", "Body")
            .await
            .unwrap();
        
        assert!(!mail.read);
        
        let updated = service.mark_mail_as_read(mail.id).await.unwrap();
        assert!(updated.read);
    }

    #[tokio::test]
    async fn test_check_unread_mail() {
        let storage = InMemoryStorage::new();
        let service = MailServiceImpl::new(storage);
        
        let agent1 = service.create_agent("Sender").await.unwrap();
        let agent2 = service.create_agent("Receiver").await.unwrap();
        
        // Initially no unread mail
        let (has_unread, unread) = service.check_unread_mail(agent2.id.clone()).await.unwrap();
        assert!(!has_unread);
        assert!(unread.is_empty());
        
        // Send mail
        service.send_agent_to_agent(agent1.id, agent2.id.clone(), "Test", "Body").await.unwrap();
        
        // Now there is unread mail
        let (has_unread, unread) = service.check_unread_mail(agent2.id.clone()).await.unwrap();
        assert!(has_unread);
        assert_eq!(unread.len(), 1);
        
        // Mark as read
        let mail_id = unread[0].id;
        service.mark_mail_as_read(mail_id).await.unwrap();
        
        // No more unread
        let (has_unread, unread) = service.check_unread_mail(agent2.id).await.unwrap();
        assert!(!has_unread);
        assert!(unread.is_empty());
    }

    #[tokio::test]
    async fn test_get_recent_mail() {
        let storage = InMemoryStorage::new();
        let service = MailServiceImpl::new(storage);
        
        let agent1 = service.create_agent("Sender").await.unwrap();
        let agent2 = service.create_agent("Receiver").await.unwrap();
        
        // Send some mail
        service.send_agent_to_agent(agent1.id.clone(), agent2.id.clone(), "Recent", "Body").await.unwrap();
        
        // Get recent mail (last 24 hours)
        let recent = service.get_recent_mail(
            string_to_node_id(&agent2.id),
            24,
            10
        ).await.unwrap();
        
        assert_eq!(recent.len(), 1);
        assert_eq!(recent[0].subject, "Recent");
    }

    #[tokio::test]
    async fn test_get_nonexistent_agent() {
        let storage = InMemoryStorage::new();
        let service = MailServiceImpl::new(storage);
        
        let fake_id = "nonexistent_agent".to_string();
        let result = service.get_agent(fake_id).await;
        
        assert!(matches!(result, Err(MailError::AgentNotFound(_))));
    }

    #[tokio::test]
    async fn test_get_agent_by_mailbox() {
        let storage = InMemoryStorage::new();
        let service = MailServiceImpl::new(storage);
        
        let agent = service.create_agent("Test Agent").await.unwrap();
        let mailbox = service.get_agent_mailbox(agent.id.clone()).await.unwrap();
        
        // Get agent by mailbox
        let found_agent = service.get_agent_by_mailbox(mailbox.id).await.unwrap();
        assert_eq!(found_agent.id, agent.id);
        assert_eq!(found_agent.name, agent.name);
    }

    #[tokio::test]
    async fn test_list_agents() {
        let storage = InMemoryStorage::new();
        let service = MailServiceImpl::new(storage);
        
        // Create multiple agents
        service.create_agent("Agent 1").await.unwrap();
        service.create_agent("Agent 2").await.unwrap();
        service.create_agent("Agent 3").await.unwrap();
        
        let agents = service.list_agents().await.unwrap();
        assert_eq!(agents.len(), 3);
    }

    #[tokio::test]
    async fn test_set_agent_status() {
        let storage = InMemoryStorage::new();
        let service = MailServiceImpl::new(storage);
        
        let agent = service.create_agent("Test Agent").await.unwrap();
        assert_eq!(agent.status, "offline");
        
        let updated = service.set_agent_status(agent.id.clone(), "online").await.unwrap();
        assert_eq!(updated.status, "online");
        
        // Verify persisted
        let retrieved = service.get_agent(agent.id).await.unwrap();
        assert_eq!(retrieved.status, "online");
    }

    #[tokio::test]
    async fn test_multiple_mails_sorting() {
        let storage = InMemoryStorage::new();
        let service = MailServiceImpl::new(storage);
        
        let agent1 = service.create_agent("Sender").await.unwrap();
        let agent2 = service.create_agent("Receiver").await.unwrap();
        
        // Send multiple mails
        service.send_agent_to_agent(agent1.id.clone(), agent2.id.clone(), "First", "Body1").await.unwrap();
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
        service.send_agent_to_agent(agent1.id.clone(), agent2.id.clone(), "Second", "Body2").await.unwrap();
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
        service.send_agent_to_agent(agent1.id.clone(), agent2.id.clone(), "Third", "Body3").await.unwrap();
        
        let inbox = service.get_mailbox_inbox(string_to_node_id(&agent2.id)).await.unwrap();
        assert_eq!(inbox.len(), 3);
        // Should be sorted newest first
        assert_eq!(inbox[0].subject, "Third");
        assert_eq!(inbox[1].subject, "Second");
        assert_eq!(inbox[2].subject, "First");
    }
}