agent-teams 0.1.0

Generic Rust agent teams framework replicating Claude Code Agent Teams architecture with pluggable backends for Claude Code, Codex, and Gemini CLI
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
//! Inbox-based messaging for agent teams.
//!
//! Provides the [`InboxManager`] trait and its file-system implementation
//! [`FileInboxManager`], which stores messages as JSON arrays in
//! `~/.claude/teams/{team}/inboxes/{agent}.json`.

pub mod structured;

use std::path::{Path, PathBuf};
use std::time::Duration;

use async_trait::async_trait;
use tokio::time::Instant;
use tracing::{debug, warn};

use crate::error::{Error, Result};
use crate::models::InboxMessage;
use crate::util::atomic_write::atomic_write_json;
use crate::util::file_lock::FileLock;
use crate::util::validate_name;

/// Trait for inbox-based messaging between agents.
#[async_trait]
pub trait InboxManager: Send + Sync {
    /// Send a message to the recipient specified in `message.to`.
    async fn send_message(&self, team: &str, message: InboxMessage) -> Result<()>;

    /// Broadcast a plain-text message to all `members` except the sender.
    async fn broadcast(
        &self,
        team: &str,
        from: &str,
        content: &str,
        members: &[String],
    ) -> Result<()>;

    /// Read all messages in an agent's inbox.
    async fn read_inbox(&self, team: &str, agent: &str) -> Result<Vec<InboxMessage>>;

    /// Read only unread messages in an agent's inbox.
    async fn read_unread(&self, team: &str, agent: &str) -> Result<Vec<InboxMessage>>;

    /// Mark a specific message as read.
    async fn mark_read(&self, team: &str, agent: &str, message_id: &str) -> Result<()>;

    /// Poll for new unread messages, blocking up to `timeout`.
    async fn poll_inbox(
        &self,
        team: &str,
        agent: &str,
        timeout: Duration,
    ) -> Result<Vec<InboxMessage>>;

    /// Clear all messages from an agent's inbox.
    async fn clear_inbox(&self, team: &str, agent: &str) -> Result<()>;
}

/// File-system backed [`InboxManager`].
///
/// Layout:
/// ```text
/// {base_dir}/{team}/inboxes/{agent}.json   # message array
/// {base_dir}/{team}/inboxes/{agent}.lock   # flock guard
/// ```
#[derive(Debug, Clone)]
pub struct FileInboxManager {
    base_dir: PathBuf,
}

impl Default for FileInboxManager {
    fn default() -> Self {
        let base_dir = dirs::home_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join(".claude")
            .join("teams");
        Self { base_dir }
    }
}

impl FileInboxManager {
    /// Create a new `FileInboxManager` rooted at `base_dir`.
    pub fn new(base_dir: impl Into<PathBuf>) -> Self {
        Self {
            base_dir: base_dir.into(),
        }
    }

    /// Directory containing all inboxes for a team.
    fn inbox_dir(&self, team: &str) -> PathBuf {
        self.base_dir.join(team).join("inboxes")
    }

    /// Path to a specific agent's inbox JSON file.
    fn inbox_path(&self, team: &str, agent: &str) -> PathBuf {
        self.inbox_dir(team).join(format!("{agent}.json"))
    }

    /// Path to a specific agent's inbox lock file.
    fn lock_path(&self, team: &str, agent: &str) -> PathBuf {
        self.inbox_dir(team).join(format!("{agent}.lock"))
    }

    /// Ensure the inbox directory for a team exists.
    fn ensure_inbox_dir(inbox_dir: &Path) -> Result<()> {
        std::fs::create_dir_all(inbox_dir)?;
        Ok(())
    }

    /// Read the inbox file, returning an empty vec if the file doesn't exist.
    fn read_inbox_file(path: &Path) -> Result<Vec<InboxMessage>> {
        match std::fs::read_to_string(path) {
            Ok(data) => {
                let messages: Vec<InboxMessage> = serde_json::from_str(&data)?;
                Ok(messages)
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
            Err(e) => Err(e.into()),
        }
    }
}

#[async_trait]
impl InboxManager for FileInboxManager {
    async fn send_message(&self, team: &str, message: InboxMessage) -> Result<()> {
        validate_name(team)?;
        validate_name(&message.to)?;

        let recipient = message.to.clone();
        let inbox_dir = self.inbox_dir(team);
        let lock_path = self.lock_path(team, &recipient);
        let inbox_path = self.inbox_path(team, &recipient);

        debug!(team, to = %recipient, id = %message.id, "sending message");

        // File locking is blocking, so offload to a blocking thread.
        tokio::task::spawn_blocking(move || {
            Self::ensure_inbox_dir(&inbox_dir)?;
            let _lock = FileLock::acquire(&lock_path)?;
            let mut messages = Self::read_inbox_file(&inbox_path)?;
            messages.push(message);
            atomic_write_json(&inbox_path, &messages)?;
            Ok(())
        })
        .await
        .map_err(|e| Error::JoinError(format!("{e}")))?
    }

    async fn broadcast(
        &self,
        team: &str,
        from: &str,
        content: &str,
        members: &[String],
    ) -> Result<()> {
        validate_name(team)?;

        debug!(team, from, count = members.len(), "broadcasting message");

        for member in members {
            if member == from {
                continue;
            }
            let msg = InboxMessage::new(from, member.as_str(), content);
            self.send_message(team, msg).await?;
        }
        Ok(())
    }

    async fn read_inbox(&self, team: &str, agent: &str) -> Result<Vec<InboxMessage>> {
        validate_name(team)?;
        validate_name(agent)?;

        let inbox_dir = self.inbox_dir(team);
        let lock_path = self.lock_path(team, agent);
        let inbox_path = self.inbox_path(team, agent);

        tokio::task::spawn_blocking(move || {
            Self::ensure_inbox_dir(&inbox_dir)?;
            let _lock = FileLock::acquire(&lock_path)?;
            Self::read_inbox_file(&inbox_path)
        })
        .await
        .map_err(|e| Error::JoinError(format!("{e}")))?
    }

    async fn read_unread(&self, team: &str, agent: &str) -> Result<Vec<InboxMessage>> {
        validate_name(team)?;
        validate_name(agent)?;

        let all = self.read_inbox(team, agent).await?;
        Ok(all.into_iter().filter(|m| !m.read).collect())
    }

    async fn mark_read(&self, team: &str, agent: &str, message_id: &str) -> Result<()> {
        validate_name(team)?;
        validate_name(agent)?;

        let inbox_dir = self.inbox_dir(team);
        let lock_path = self.lock_path(team, agent);
        let inbox_path = self.inbox_path(team, agent);
        let message_id = message_id.to_owned();

        debug!(team, agent, id = %message_id, "marking message as read");

        tokio::task::spawn_blocking(move || {
            Self::ensure_inbox_dir(&inbox_dir)?;
            let _lock = FileLock::acquire(&lock_path)?;
            let mut messages = Self::read_inbox_file(&inbox_path)?;

            let found = messages.iter_mut().find(|m| m.id == message_id);
            match found {
                Some(msg) => {
                    msg.read = true;
                    atomic_write_json(&inbox_path, &messages)?;
                    Ok(())
                }
                None => {
                    warn!(id = %message_id, "message not found in inbox");
                    Ok(())
                }
            }
        })
        .await
        .map_err(|e| Error::JoinError(format!("{e}")))?
    }

    async fn poll_inbox(
        &self,
        team: &str,
        agent: &str,
        timeout: Duration,
    ) -> Result<Vec<InboxMessage>> {
        validate_name(team)?;
        validate_name(agent)?;

        let deadline = Instant::now() + timeout;

        loop {
            let unread = self.read_unread(team, agent).await?;
            if !unread.is_empty() {
                return Ok(unread);
            }

            if Instant::now() >= deadline {
                return Ok(Vec::new());
            }

            // Sleep before polling again, but don't overshoot the deadline.
            let remaining = deadline.saturating_duration_since(Instant::now());
            let sleep_dur = remaining.min(Duration::from_millis(500));
            if sleep_dur.is_zero() {
                return Ok(Vec::new());
            }
            tokio::time::sleep(sleep_dur).await;
        }
    }

    async fn clear_inbox(&self, team: &str, agent: &str) -> Result<()> {
        validate_name(team)?;
        validate_name(agent)?;

        let inbox_dir = self.inbox_dir(team);
        let lock_path = self.lock_path(team, agent);
        let inbox_path = self.inbox_path(team, agent);

        debug!(team, agent, "clearing inbox");

        tokio::task::spawn_blocking(move || {
            Self::ensure_inbox_dir(&inbox_dir)?;
            let _lock = FileLock::acquire(&lock_path)?;
            let empty: Vec<InboxMessage> = Vec::new();
            atomic_write_json(&inbox_path, &empty)?;
            Ok(())
        })
        .await
        .map_err(|e| Error::JoinError(format!("{e}")))?
    }
}

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

    fn make_manager(dir: &Path) -> FileInboxManager {
        FileInboxManager::new(dir)
    }

    #[tokio::test]
    async fn send_and_read_single_message() {
        let dir = tempfile::tempdir().unwrap();
        let mgr = make_manager(dir.path());

        let msg = InboxMessage::new("lead", "worker-1", "Hello worker!");
        mgr.send_message("test-team", msg).await.unwrap();

        let inbox = mgr.read_inbox("test-team", "worker-1").await.unwrap();
        assert_eq!(inbox.len(), 1);
        assert_eq!(inbox[0].from, "lead");
        assert_eq!(inbox[0].to, "worker-1");
        assert_eq!(inbox[0].content, "Hello worker!");
        assert!(!inbox[0].read);
    }

    #[tokio::test]
    async fn send_multiple_and_read_unread() {
        let dir = tempfile::tempdir().unwrap();
        let mgr = make_manager(dir.path());

        let msg1 = InboxMessage::new("lead", "worker-1", "Task 1");
        let msg2 = InboxMessage::new("lead", "worker-1", "Task 2");
        mgr.send_message("test-team", msg1).await.unwrap();
        mgr.send_message("test-team", msg2).await.unwrap();

        let unread = mgr.read_unread("test-team", "worker-1").await.unwrap();
        assert_eq!(unread.len(), 2);
    }

    #[tokio::test]
    async fn mark_read_filters_unread() {
        let dir = tempfile::tempdir().unwrap();
        let mgr = make_manager(dir.path());

        let msg = InboxMessage::new("lead", "worker-1", "Read me");
        let msg_id = msg.id.clone();
        mgr.send_message("test-team", msg).await.unwrap();

        mgr.mark_read("test-team", "worker-1", &msg_id)
            .await
            .unwrap();

        let unread = mgr.read_unread("test-team", "worker-1").await.unwrap();
        assert!(unread.is_empty());

        // But the message is still in the full inbox.
        let all = mgr.read_inbox("test-team", "worker-1").await.unwrap();
        assert_eq!(all.len(), 1);
        assert!(all[0].read);
    }

    #[tokio::test]
    async fn broadcast_sends_to_all_except_sender() {
        let dir = tempfile::tempdir().unwrap();
        let mgr = make_manager(dir.path());

        let members = vec![
            "lead".to_string(),
            "worker-1".to_string(),
            "worker-2".to_string(),
        ];
        mgr.broadcast("test-team", "lead", "Announcement!", &members)
            .await
            .unwrap();

        // lead should NOT have a message
        let lead_inbox = mgr.read_inbox("test-team", "lead").await.unwrap();
        assert!(lead_inbox.is_empty());

        // Both workers should have the message
        let w1 = mgr.read_inbox("test-team", "worker-1").await.unwrap();
        assert_eq!(w1.len(), 1);
        assert_eq!(w1[0].content, "Announcement!");

        let w2 = mgr.read_inbox("test-team", "worker-2").await.unwrap();
        assert_eq!(w2.len(), 1);
        assert_eq!(w2[0].content, "Announcement!");
    }

    #[tokio::test]
    async fn clear_inbox_removes_all() {
        let dir = tempfile::tempdir().unwrap();
        let mgr = make_manager(dir.path());

        mgr.send_message("t", InboxMessage::new("a", "b", "1"))
            .await
            .unwrap();
        mgr.send_message("t", InboxMessage::new("a", "b", "2"))
            .await
            .unwrap();

        mgr.clear_inbox("t", "b").await.unwrap();

        let inbox = mgr.read_inbox("t", "b").await.unwrap();
        assert!(inbox.is_empty());
    }

    #[tokio::test]
    async fn poll_returns_immediately_when_messages_exist() {
        let dir = tempfile::tempdir().unwrap();
        let mgr = make_manager(dir.path());

        mgr.send_message("t", InboxMessage::new("a", "b", "hi"))
            .await
            .unwrap();

        let start = Instant::now();
        let msgs = mgr
            .poll_inbox("t", "b", Duration::from_secs(5))
            .await
            .unwrap();
        let elapsed = start.elapsed();

        assert_eq!(msgs.len(), 1);
        assert!(elapsed < Duration::from_secs(1), "poll should return immediately");
    }

    #[tokio::test]
    async fn poll_times_out_with_empty_result() {
        let dir = tempfile::tempdir().unwrap();
        let mgr = make_manager(dir.path());

        let start = Instant::now();
        let msgs = mgr
            .poll_inbox("t", "agent", Duration::from_millis(600))
            .await
            .unwrap();
        let elapsed = start.elapsed();

        assert!(msgs.is_empty());
        assert!(elapsed >= Duration::from_millis(500), "should wait near timeout");
        assert!(elapsed < Duration::from_secs(3), "should not wait too long");
    }

    #[tokio::test]
    async fn read_empty_inbox() {
        let dir = tempfile::tempdir().unwrap();
        let mgr = make_manager(dir.path());

        let inbox = mgr.read_inbox("team", "nobody").await.unwrap();
        assert!(inbox.is_empty());
    }

    #[tokio::test]
    async fn structured_message_round_trip_via_inbox() {
        let dir = tempfile::tempdir().unwrap();
        let mgr = make_manager(dir.path());

        let structured = StructuredMessage::TaskAssignment {
            task_id: "42".into(),
            subject: "Fix the bug".into(),
            description: Some("It's broken".into()),
            assigned_by: None,
            timestamp: None,
        };
        let msg = InboxMessage::from_structured("lead", "worker-1", &structured).unwrap();
        mgr.send_message("t", msg).await.unwrap();

        let inbox = mgr.read_inbox("t", "worker-1").await.unwrap();
        assert_eq!(inbox.len(), 1);

        let parsed = inbox[0].try_as_structured().unwrap();
        match parsed {
            StructuredMessage::TaskAssignment {
                task_id, subject, ..
            } => {
                assert_eq!(task_id, "42");
                assert_eq!(subject, "Fix the bug");
            }
            other => panic!("expected TaskAssignment, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn mark_read_nonexistent_message_is_ok() {
        let dir = tempfile::tempdir().unwrap();
        let mgr = make_manager(dir.path());

        // Marking read on a non-existent inbox is fine (no panic, no error).
        mgr.mark_read("t", "agent", "nonexistent-id").await.unwrap();
    }
}