ai-agent 0.88.0

Idiomatic agent sdk inspired by the claude code source leak
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
// Source: ~/claudecode/openclaudecode/src/tools/TeamCreateTool/TeamCreateTool.ts
// Source: ~/claudecode/openclaudecode/src/tools/TeamDeleteTool/TeamDeleteTool.ts
// Source: ~/claudecode/openclaudecode/src/tools/SendMessageTool/SendMessageTool.ts
//! Team management tools.
//!
//! Provides tools for creating and deleting multi-agent teams and sending messages.

use crate::error::AgentError;
use crate::types::*;
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};

pub const TEAM_CREATE_TOOL_NAME: &str = "TeamCreate";
pub const TEAM_DELETE_TOOL_NAME: &str = "TeamDelete";
pub const SEND_MESSAGE_TOOL_NAME: &str = "SendMessage";

/// Global team store
static TEAMS: OnceLock<Mutex<HashMap<String, Team>>> = OnceLock::new();
/// Message inbox store
static INBOX: OnceLock<Mutex<Vec<AgentMessage>>> = OnceLock::new();

fn get_teams_map() -> &'static Mutex<HashMap<String, Team>> {
    TEAMS.get_or_init(|| Mutex::new(HashMap::new()))
}

fn get_inbox() -> &'static Mutex<Vec<AgentMessage>> {
    INBOX.get_or_init(|| Mutex::new(Vec::new()))
}

#[derive(Debug, Clone)]
struct Team {
    name: String,
    description: String,
    agents: Vec<AgentInfo>,
    team_file_path: Option<String>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AgentInfo {
    pub name: String,
    pub description: Option<String>,
    pub model: Option<String>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AgentMessage {
    pub to: String,
    pub from: Option<String>,
    pub message: String,
    pub timestamp: u64,
}

/// TeamCreate tool - create a team of agents
pub struct TeamCreateTool;

impl TeamCreateTool {
    pub fn new() -> Self {
        Self
    }

    pub fn name(&self) -> &str {
        TEAMCREATE_TOOL_NAME
    }

    pub fn description(&self) -> &str {
        "Create a team of agents that can work in parallel. Teams enable swarm mode where agents collaborate on complex tasks."
    }

    pub fn user_facing_name(&self, _input: Option<&serde_json::Value>) -> String {
        "TeamCreate".to_string()
    }

    pub fn get_tool_use_summary(&self, input: Option<&serde_json::Value>) -> Option<String> {
        input.and_then(|inp| inp["name"].as_str().map(String::from))
    }

    pub fn render_tool_result_message(
        &self,
        content: &serde_json::Value,
    ) -> Option<String> {
        content["content"].as_str().map(|s| s.to_string())
    }

    pub fn input_schema(&self) -> ToolInputSchema {
        ToolInputSchema {
            schema_type: "object".to_string(),
            properties: serde_json::json!({
                "name": {
                    "type": "string",
                    "description": "Name of the team to create"
                },
                "description": {
                    "type": "string",
                    "description": "Description of what the team does"
                },
                "agents": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "name": { "type": "string", "description": "Agent name" },
                            "description": { "type": "string", "description": "Agent description" },
                            "model": { "type": "string", "description": "Agent model" }
                        }
                    },
                    "description": "List of agents in the team"
                }
            }),
            required: Some(vec!["name".to_string()]),
        }
    }

    pub async fn execute(
        &self,
        input: serde_json::Value,
        _context: &ToolContext,
    ) -> Result<ToolResult, AgentError> {
        let name = input["name"]
            .as_str()
            .ok_or_else(|| AgentError::Tool("name is required".to_string()))?
            .to_string();

        let description = input["description"].as_str().unwrap_or("").to_string();

        let agents: Vec<AgentInfo> = input["agents"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| {
                        let name = v.get("name")?.as_str()?.to_string();
                        let description = v
                            .get("description")
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string());
                        let model = v
                            .get("model")
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string());
                        Some(AgentInfo {
                            name,
                            description,
                            model,
                        })
                    })
                    .collect()
            })
            .unwrap_or_default();

        // Check for duplicate team name
        let mut guard = get_teams_map().lock().unwrap();
        if guard.contains_key(&name) {
            return Ok(ToolResult {
                result_type: "text".to_string(),
                tool_use_id: "".to_string(),
                content: format!("Error: Team '{}' already exists.", name),
                is_error: Some(true),
                was_persisted: None,
            });
        }
        drop(guard);

        // In a full implementation, this would:
        // 1. Write team file to .ai/teams/<name>/team.json
        // 2. Initialize task list for the team
        // 3. Set up AppState team context
        // 4. Spawn agent processes for each team member

        let team = Team {
            name: name.clone(),
            description: description.clone(),
            agents,
            team_file_path: None,
        };

        let mut guard = get_teams_map().lock().unwrap();
        guard.insert(name.clone(), team);
        let agent_count = guard.get(&name).map(|t| t.agents.len()).unwrap_or(0);
        drop(guard);

        Ok(ToolResult {
            result_type: "text".to_string(),
            tool_use_id: "".to_string(),
            content: format!(
                "Team '{}' created successfully.\n\
                Description: {}\n\
                Agents: {}\n\n\
                The team is ready for coordination. \
                Team members can communicate using the SendMessage tool.",
                name, description, agent_count
            ),
            is_error: Some(false),
            was_persisted: None,
        })
    }
}

impl Default for TeamCreateTool {
    fn default() -> Self {
        Self::new()
    }
}

/// TeamDelete tool - delete a team
pub struct TeamDeleteTool;

impl TeamDeleteTool {
    pub fn new() -> Self {
        Self
    }

    pub fn name(&self) -> &str {
        TEAM_DELETE_TOOL_NAME
    }

    pub fn description(&self) -> &str {
        "Delete a previously created team. All team members will be stopped and the team configuration will be removed."
    }

    pub fn user_facing_name(&self, _input: Option<&serde_json::Value>) -> String {
        "TeamDelete".to_string()
    }

    pub fn get_tool_use_summary(&self, input: Option<&serde_json::Value>) -> Option<String> {
        input.and_then(|inp| inp["name"].as_str().map(String::from))
    }

    pub fn render_tool_result_message(
        &self,
        content: &serde_json::Value,
    ) -> Option<String> {
        content["content"].as_str().map(|s| s.to_string())
    }

    pub fn input_schema(&self) -> ToolInputSchema {
        ToolInputSchema {
            schema_type: "object".to_string(),
            properties: serde_json::json!({
                "name": {
                    "type": "string",
                    "description": "Name of the team to delete"
                }
            }),
            required: Some(vec!["name".to_string()]),
        }
    }

    pub async fn execute(
        &self,
        input: serde_json::Value,
        _context: &ToolContext,
    ) -> Result<ToolResult, AgentError> {
        let name = input["name"]
            .as_str()
            .ok_or_else(|| AgentError::Tool("name is required".to_string()))?;

        let mut guard = get_teams_map().lock().unwrap();
        let team = guard.remove(name);
        drop(guard);

        let team = team.ok_or_else(|| AgentError::Tool(format!("Team '{}' not found", name)))?;

        // In a full implementation, this would:
        // 1. Check for active team members and warn/abort
        // 2. Stop all running team agents
        // 3. Clean up worktrees associated with the team
        // 4. Reset team colors
        // 5. Clear AppState team context
        // 6. Delete team file

        let agent_names: Vec<String> = team.agents.iter().map(|a| a.name.clone()).collect();

        Ok(ToolResult {
            result_type: "text".to_string(),
            tool_use_id: "".to_string(),
            content: format!(
                "Team '{}' deleted successfully.\n\
                Stopped {} agent(s): {}",
                name,
                agent_names.len(),
                agent_names.join(", ")
            ),
            is_error: Some(false),
            was_persisted: None,
        })
    }
}

impl Default for TeamDeleteTool {
    fn default() -> Self {
        Self::new()
    }
}

/// SendMessage tool - send message between agents
pub struct SendMessageTool;

impl SendMessageTool {
    pub fn new() -> Self {
        Self
    }

    pub fn name(&self) -> &str {
        SEND_MESSAGE_TOOL_NAME
    }

    pub fn description(&self) -> &str {
        "Send a message to another agent. Use 'to: *' to broadcast to all agents. Supports direct messages, shutdown requests, and plan approvals."
    }

    pub fn user_facing_name(&self, _input: Option<&serde_json::Value>) -> String {
        "SendMessage".to_string()
    }

    pub fn get_tool_use_summary(&self, input: Option<&serde_json::Value>) -> Option<String> {
        input.and_then(|inp| inp["to"].as_str().map(String::from))
    }

    pub fn render_tool_result_message(
        &self,
        content: &serde_json::Value,
    ) -> Option<String> {
        content["content"].as_str().map(|s| s.to_string())
    }

    pub fn input_schema(&self) -> ToolInputSchema {
        ToolInputSchema {
            schema_type: "object".to_string(),
            properties: serde_json::json!({
                "to": {
                    "type": "string",
                    "description": "Agent name to send message to. Use '*' to broadcast to all agents."
                },
                "message": {
                    "type": "string",
                    "description": "Message content"
                }
            }),
            required: Some(vec!["to".to_string(), "message".to_string()]),
        }
    }

    pub async fn execute(
        &self,
        input: serde_json::Value,
        _context: &ToolContext,
    ) -> Result<ToolResult, AgentError> {
        let to = input["to"]
            .as_str()
            .ok_or_else(|| AgentError::Tool("to is required".to_string()))?;

        let message = input["message"]
            .as_str()
            .ok_or_else(|| AgentError::Tool("message is required".to_string()))?;

        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);

        let msg = AgentMessage {
            to: to.to_string(),
            from: None,
            message: message.to_string(),
            timestamp,
        };

        // In a full implementation, this would:
        // 1. For direct messages: deliver via UDS socket or in-process channel
        // 2. For broadcasts (*): send to all connected agents
        // 3. For shutdown requests: trigger agent termination
        // 4. For plan approvals: route to plan approval handler
        // 5. For bridge messaging: use cross-session communication

        let mut inbox = get_inbox().lock().unwrap();
        inbox.push(msg);
        let inbox_len = inbox.len();
        drop(inbox);

        let recipient = if to == "*" {
            "all agents (broadcast)".to_string()
        } else {
            format!("agent '{}'", to)
        };

        Ok(ToolResult {
            result_type: "text".to_string(),
            tool_use_id: "".to_string(),
            content: format!(
                "Message sent to {}.\n\
                Message: {}\n\
                Inbox size: {}",
                recipient, message, inbox_len
            ),
            is_error: Some(false),
            was_persisted: None,
        })
    }
}

impl Default for SendMessageTool {
    fn default() -> Self {
        Self::new()
    }
}

// Fix: constant name
const TEAMCREATE_TOOL_NAME: &str = "TeamCreate";

/// Reset the global team and inbox stores for test isolation.
pub fn reset_teams_for_testing() {
    let mut guard = get_teams_map().lock().unwrap();
    guard.clear();
    drop(guard);
    let mut inbox = get_inbox().lock().unwrap();
    inbox.clear();
}

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

    use crate::tests::common::clear_all_test_state;

    #[tokio::test]
    async fn test_team_create_and_delete() {
        clear_all_test_state();
        let create = TeamCreateTool::new();
        let result = create
            .execute(
                serde_json::json!({
                    "name": "test-team",
                    "description": "A test team",
                    "agents": [
                        { "name": "agent1", "description": "First agent" }
                    ]
                }),
                &ToolContext::default(),
            )
            .await;
        assert!(result.is_ok());

        let delete = TeamDeleteTool::new();
        let result = delete
            .execute(
                serde_json::json!({ "name": "test-team" }),
                &ToolContext::default(),
            )
            .await;
        assert!(result.is_ok());
        assert!(result.unwrap().content.contains("deleted"));
    }

    #[tokio::test]
    async fn test_send_message() {
        clear_all_test_state();
        let send = SendMessageTool::new();
        let result = send
            .execute(
                serde_json::json!({
                    "to": "agent1",
                    "message": "Hello from test"
                }),
                &ToolContext::default(),
            )
            .await;
        assert!(result.is_ok());
        assert!(result.unwrap().content.contains("agent 'agent1'"));
    }

    #[tokio::test]
    async fn test_send_message_broadcast() {
        clear_all_test_state();
        let send = SendMessageTool::new();
        let result = send
            .execute(
                serde_json::json!({
                    "to": "*",
                    "message": "Broadcast message"
                }),
                &ToolContext::default(),
            )
            .await;
        assert!(result.is_ok());
        assert!(result.unwrap().content.contains("broadcast"));
    }
}