sprit-mutilagent 0.3.2

A robust command-line toolkit for managing multiple AI coding agents in isolated tmux sessions with comprehensive workspace management and health monitoring
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
use crate::cli::AgentsCommands;
use crate::commands::config::{AgentConfig, SpriteConfig};
use crate::error::SpriteError;
use crate::utils::git;
use anyhow::{Context, Result};
use std::io::{self, Write};
use std::path::PathBuf;

/// Execute agents command with subcommands
pub fn execute(command: AgentsCommands) -> Result<()> {
    match command {
        AgentsCommands::List => list_agents(),
        AgentsCommands::Create {
            agent_id,
            branch,
            workspace,
            model,
            description,
            no_workspace,
        } => create_agent(
            agent_id,
            branch,
            workspace,
            model,
            description,
            no_workspace,
        ),
        AgentsCommands::Remove {
            agent_id,
            force,
            keep_workspace,
        } => remove_agent(agent_id, force, keep_workspace),
        AgentsCommands::Show { agent_id } => show_agent(agent_id),
        AgentsCommands::Validate => validate_agents(),
        AgentsCommands::Provision { agent_id } => provision_agents(agent_id),
    }
}

/// List all configured agents
fn list_agents() -> Result<()> {
    let config = SpriteConfig::load().context("Failed to load configuration")?;

    if config.agents.is_empty() {
        println!("📝 No agents configured.");
        println!("Use 'sprite agents create <id>' to add your first agent.");
        return Ok(());
    }

    println!("🤖 Configured Agents ({}) :", config.agents.len());
    println!();

    // Sort agents by ID for consistent display
    let mut agents: Vec<_> = config.agents.iter().collect();
    agents.sort_by_key(|a| &a.id);

    for agent_config in agents {
        let workspace_path = PathBuf::from(&agent_config.worktree_path);
        let workspace_exists = workspace_path.exists();

        // Get git status if workspace exists
        let git_status = if workspace_exists {
            match git::get_current_branch_at(&workspace_path) {
                Ok(branch) => {
                    if branch == agent_config.branch {
                        format!("✅ Ready (branch: {})", branch)
                    } else {
                        format!("⚠️  Wrong branch ({} ≠ {})", branch, agent_config.branch)
                    }
                }
                Err(_) => "❌ Not a git repository".to_string(),
            }
        } else {
            "❌ Workspace missing".to_string()
        };

        println!("  Agent {} :", agent_config.id);
        println!(
            "    📁 Workspace: {} {}",
            agent_config.worktree_path, git_status
        );
        println!("    🌿 Branch: {}", agent_config.branch);
        println!("    🤖 Model: {}", agent_config.model);
        println!("    📝 Description: {}", agent_config.description);
        println!();
    }

    Ok(())
}

/// Create a new agent
fn create_agent(
    agent_id: String,
    branch: Option<String>,
    workspace: Option<String>,
    model: String,
    description: Option<String>,
    no_workspace: bool,
) -> Result<()> {
    println!("🚀 Creating new agent: {}", agent_id);

    // Load existing configuration
    let mut config = SpriteConfig::load().context("Failed to load configuration")?;

    // Check if agent already exists
    if config.agents.iter().any(|a| a.id == agent_id) {
        return Err(SpriteError::config(format!(
            "Agent {} already exists. Use a different ID or remove the existing agent first.",
            agent_id
        ))
        .into());
    }

    // Validate agent ID format
    if agent_id.is_empty() || agent_id.contains('/') || agent_id.contains("..") {
        return Err(SpriteError::config(
            "Invalid agent ID. Must be a simple identifier without slashes or '..'.",
        )
        .into());
    }

    // Set default values
    let branch_name = branch.unwrap_or_else(|| format!("agents/{}", agent_id));
    let workspace_path = workspace.unwrap_or_else(|| format!("agents/{}", agent_id));
    let agent_description = description.unwrap_or_else(|| format!("Agent {} workspace", agent_id));

    // Create agent configuration
    let agent_config = AgentConfig {
        id: agent_id.clone(),
        branch: branch_name.clone(),
        worktree_path: workspace_path.clone(),
        model,
        description: agent_description,
        status: "inactive".to_string(),
        config: Default::default(),
    };

    // Add agent to configuration
    config.agents.push(agent_config);

    // Save configuration
    config
        .save()
        .context("Failed to save updated configuration")?;

    println!("  ✅ Agent configuration saved");

    // Create workspace if requested
    if !no_workspace {
        println!("  🔧 Creating workspace...");

        // Validate git repository first
        git::validate_git_repository().context("Failed to validate git repository")?;

        // Create branch if it doesn't exist
        if !git::branch_exists(&branch_name)? {
            git::create_branch_from(&branch_name, "main") // Assuming main is the base branch
                .with_context(|| format!("Failed to create branch: {}", branch_name))?;
            println!("    🌿 Created branch: {}", branch_name);
        } else {
            println!("    🌿 Using existing branch: {}", branch_name);
        }

        // Create worktree
        let workspace_path_buf = PathBuf::from(&workspace_path);
        git::create_worktree(&workspace_path_buf, &branch_name)
            .with_context(|| format!("Failed to create worktree: {}", workspace_path))?;

        println!("    ✅ Created workspace: {}", workspace_path);
    } else {
        println!("  ⏭️  Skipping workspace creation (use --no-workspace)");
    }

    println!("✅ Agent {} created successfully!", agent_id);
    println!("   Configuration: agents/agents.yaml");
    if !no_workspace {
        println!("   Workspace: {}", workspace_path);
        println!("   Branch: {}", branch_name);
    }

    Ok(())
}

/// Remove an agent
fn remove_agent(agent_id: String, force: bool, keep_workspace: bool) -> Result<()> {
    println!("🗑️  Removing agent: {}", agent_id);

    // Load configuration
    let mut config = SpriteConfig::load().context("Failed to load configuration")?;

    // Find the agent
    let agent_index = config
        .agents
        .iter()
        .position(|a| a.id == agent_id)
        .ok_or_else(|| SpriteError::config(format!("Agent {} does not exist.", agent_id)))?;
    let agent_config = &config.agents[agent_index];

    // Confirmation prompt (unless force is true)
    if !force {
        println!(
            "This will remove agent {} with the following configuration:",
            agent_id
        );
        println!("  Workspace: {}", agent_config.worktree_path);
        println!("  Branch: {}", agent_config.branch);
        println!("  Model: {}", agent_config.model);
        if !keep_workspace {
            println!("  ⚠️  Workspace directory will be REMOVED");
        } else {
            println!("  📁 Workspace directory will be kept");
        }
        println!();
        print!("Are you sure you want to continue? [y/N] ");
        io::stdout().flush().unwrap();

        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        let input = input.trim().to_lowercase();

        if input != "y" && input != "yes" {
            println!("❌ Agent removal cancelled.");
            return Ok(());
        }
    }

    // Remove workspace directory (unless keep_workspace is true)
    if !keep_workspace {
        let workspace_path = PathBuf::from(&agent_config.worktree_path);
        if workspace_path.exists() {
            // First, remove the git worktree
            if let Err(e) = git::remove_worktree(&workspace_path) {
                println!("⚠️  Warning: Failed to remove git worktree: {}", e);
            }

            // Then remove the directory if it still exists
            if workspace_path.exists() {
                std::fs::remove_dir_all(&workspace_path).with_context(|| {
                    format!(
                        "Failed to remove workspace directory: {}",
                        workspace_path.display()
                    )
                })?;
                println!(
                    "  ✅ Removed workspace directory: {}",
                    agent_config.worktree_path
                );
            }
        } else {
            println!(
                "  ℹ️  Workspace directory does not exist: {}",
                agent_config.worktree_path
            );
        }
    } else {
        println!(
            "  📁 Keeping workspace directory: {}",
            agent_config.worktree_path
        );
    }

    // Remove agent from configuration
    config.agents.remove(agent_index);

    // Save configuration
    config
        .save()
        .context("Failed to save updated configuration")?;

    println!("  ✅ Agent configuration removed");
    println!("✅ Agent {} removed successfully!", agent_id);

    Ok(())
}

/// Show agent details
fn show_agent(agent_id: Option<String>) -> Result<()> {
    let config = SpriteConfig::load().context("Failed to load configuration")?;

    match agent_id {
        Some(id) => {
            // Show specific agent
            if let Some(agent_config) = config.agents.iter().find(|a| a.id == id) {
                println!("🤖 Agent {} :", id);
                println!("  📁 Workspace: {}", agent_config.worktree_path);
                println!("  🌿 Branch: {}", agent_config.branch);
                println!("  🤖 Model: {}", agent_config.model);
                println!("  📝 Description: {}", agent_config.description);

                // Show workspace status
                let workspace_path = PathBuf::from(&agent_config.worktree_path);
                if workspace_path.exists() {
                    println!();
                    println!("  📊 Workspace Status:");

                    if let Ok(branch) = git::get_current_branch_at(&workspace_path) {
                        println!("    Current branch: {}", branch);
                        if branch == agent_config.branch {
                            println!("    Status: ✅ On correct branch");
                        } else {
                            println!(
                                "    Status: ⚠️  Wrong branch (should be {})",
                                agent_config.branch
                            );
                        }
                    }

                    if let Ok(status) = git::get_status_string_at(&workspace_path) {
                        if status.is_empty() {
                            println!("    Working tree: ✅ Clean");
                        } else {
                            println!("    Working tree: ⚠️  Has changes");
                            for line in status.lines().take(5) {
                                println!("      {}", line);
                            }
                        }
                    }
                } else {
                    println!();
                    println!("  ❌ Workspace does not exist");
                    println!("  💡 Run 'sprite agents provision {}' to create it", id);
                }
            } else {
                return Err(SpriteError::config(format!("Agent {} does not exist.", id)).into());
            }
        }
        None => {
            // Show all agents (same as list)
            list_agents()?;
        }
    }

    Ok(())
}

/// Validate all agent workspaces
fn validate_agents() -> Result<()> {
    let config = SpriteConfig::load().context("Failed to load configuration")?;

    if config.agents.is_empty() {
        println!("📝 No agents configured.");
        return Ok(());
    }

    println!("🔍 Validating agent workspaces...");
    println!();

    let mut valid_count = 0;
    let total_count = config.agents.len();

    for agent_config in &config.agents {
        let workspace_path = PathBuf::from(&agent_config.worktree_path);

        print!("  Agent {}: ", agent_config.id);

        // Check workspace exists
        if !workspace_path.exists() {
            println!("❌ Workspace does not exist");
            continue;
        }

        // Check it's a git repository
        if !git::is_git_repository_at(&workspace_path)? {
            println!("❌ Not a git repository");
            continue;
        }

        // Check correct branch
        match git::get_current_branch_at(&workspace_path) {
            Ok(branch) => {
                if branch == agent_config.branch {
                    print!("✅ Valid");
                } else {
                    print!("⚠️  Wrong branch ({} ≠ {})", branch, agent_config.branch);
                }
            }
            Err(_) => {
                print!("❌ Cannot determine current branch");
            }
        }

        // Check if branch exists
        if git::branch_exists(&agent_config.branch)? {
            println!(" (branch exists)");
        } else {
            println!(" (branch missing)");
        }

        valid_count += 1;
    }

    println!();
    if valid_count == total_count {
        println!("✅ All {} agent workspaces are valid!", total_count);
    } else {
        println!(
            "⚠️  {}/{} agent workspaces are valid",
            valid_count, total_count
        );
        println!("💡 Use 'sprite agents provision' to fix missing workspaces");
    }

    Ok(())
}

/// Provision workspaces for agents
fn provision_agents(agent_id: Option<String>) -> Result<()> {
    let config = SpriteConfig::load().context("Failed to load configuration")?;

    // Validate git repository first
    git::validate_git_repository().context("Failed to validate git repository")?;

    let agents_to_provision: Vec<AgentConfig> = if let Some(id) = agent_id {
        // Provision specific agent
        if let Some(agent_config) = config.agents.iter().find(|a| a.id == id) {
            vec![agent_config.clone()]
        } else {
            return Err(SpriteError::config(format!("Agent {} does not exist.", id)).into());
        }
    } else {
        // Provision all agents
        config.agents.clone()
    };

    if agents_to_provision.is_empty() {
        println!("📝 No agents to provision.");
        return Ok(());
    }

    println!(
        "🔧 Provisioning workspaces for {} agent(s)...",
        agents_to_provision.len()
    );

    for agent_config in agents_to_provision {
        println!("  🤖 Agent {}:", agent_config.id);

        let workspace_path = PathBuf::from(&agent_config.worktree_path);

        // Check if workspace already exists
        if workspace_path.exists() {
            if git::is_git_repository_at(&workspace_path)? {
                println!("    ✅ Workspace already exists");

                // Check if it's on the correct branch
                if let Ok(current_branch) = git::get_current_branch_at(&workspace_path) {
                    if current_branch != agent_config.branch {
                        println!("    🔄 Switching to branch: {}", agent_config.branch);
                        git::checkout_branch(&workspace_path, &agent_config.branch)?;
                        println!("    ✅ Switched to correct branch");
                    }
                }
            } else {
                return Err(SpriteError::config(format!(
                    "Workspace path exists but is not a git repository: {}",
                    agent_config.worktree_path
                ))
                .into());
            }
        } else {
            // Create branch if it doesn't exist
            if !git::branch_exists(&agent_config.branch)? {
                println!("    🌿 Creating branch: {}", agent_config.branch);
                git::create_branch_from(&agent_config.branch, "main")?;
            }

            // Create worktree
            println!("    📁 Creating workspace: {}", agent_config.worktree_path);
            git::create_worktree(&workspace_path, &agent_config.branch)?;
            println!("    ✅ Workspace created");
        }
    }

    println!("✅ Workspace provisioning complete!");

    Ok(())
}