clawgarden-cli 0.1.1

ClawGarden CLI - Multi-bot/multi-agent Garden management tool
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! Garden configuration tool
//!
//! Allows adding/removing bots and providers from an existing garden.

use anyhow::{Context, Result};
use inquire::{Confirm, MultiSelect, Password, Select, Text};
use std::sync::Arc;

use crate::compose::{BotConfig, GardenConfig};
use crate::garden::load_gardens;
use crate::providers::{ProviderAuthMethod, ProviderPlugin, ProviderRegistry};
use crate::ui;

/// Run interactive configuration for a garden
pub fn run_config(name: &str) -> Result<()> {
    let registry = load_gardens()?;

    if !registry.exists(name) {
        anyhow::bail!("Garden '{}' not found. Run 'garden new' first.", name);
    }

    println!();
    ui::section_header_no_step("โš™๏ธ", &format!("Garden Config ยท {}", name));

    loop {
        let choice = Select::new(
            "  What would you like to do?",
            vec![
                "๐Ÿค– Add an agent",
                "๐Ÿค– Remove an agent",
                "๐Ÿ”Œ Add a provider",
                "๐Ÿ”Œ Remove a provider",
                "๐Ÿ“‹ View configuration",
                "๐Ÿ”„ Restart container",
                "โŒ Exit",
            ],
        )
        .prompt()?;

        match choice {
            "๐Ÿค– Add an agent" => add_bot(name)?,
            "๐Ÿค– Remove an agent" => remove_bot(name)?,
            "๐Ÿ”Œ Add a provider" => add_provider(name)?,
            "๐Ÿ”Œ Remove a provider" => remove_provider(name)?,
            "๐Ÿ“‹ View configuration" => show_config(name)?,
            "๐Ÿ”„ Restart container" => restart_garden(name)?,
            "โŒ Exit" => break,
            _ => {}
        }
    }

    Ok(())
}

/// Add a new bot to the garden
fn add_bot(name: &str) -> Result<()> {
    println!();
    ui::divider();
    println!("  {} Adding a new agent", "\x1b[1m\x1b[38;5;255m");
    println!("{}", "\x1b[0m");

    let roles = [
        ("PM", "๐Ÿ“‹", "Coordinates tasks & keeps the team on track"),
        ("DEV", "๐Ÿ’ป", "Writes and reviews code, implements features"),
        (
            "CRITIC",
            "๐Ÿ”",
            "Reviews output, catches issues & blind spots",
        ),
        (
            "DESIGNER",
            "๐ŸŽจ",
            "UI/UX design, system architecture thinking",
        ),
        (
            "RESEARCHER",
            "๐Ÿ”ฌ",
            "Investigates, documents, and gathers context",
        ),
        ("TESTER", "๐Ÿงช", "Quality assurance, edge-case explorer"),
        ("OPS", "๐Ÿ”ง", "Deployment, DevOps, infrastructure management"),
        ("ANALYST", "๐Ÿ“Š", "Data analysis, metrics, insights"),
        ("OTHER", "โœจ", "Custom role โ€” define your own specialty"),
    ];

    let role_names: Vec<&str> = roles.iter().map(|r| r.0).collect();

    let bot_name = Text::new("  Agent name (e.g. alex):")
        .with_validator(|input: &str| {
            if input.is_empty() {
                return Err("Please enter a name".into());
            }
            if input.contains(' ') {
                return Err("No spaces allowed".into());
            }
            Ok(inquire::validator::Validation::Valid)
        })
        .with_help_message("This will be used as the bot identifier internally")
        .prompt()?;

    // Show role selection with descriptions
    println!();
    for (role_name, icon, desc) in &roles {
        println!("    {} {} {}", icon, ui::role_badge(role_name), desc);
    }
    println!();

    let role = Select::new("  Choose a role:", role_names.to_vec()).prompt()?;

    let role_desc = roles
        .iter()
        .find(|r| r.0 == role)
        .map(|r| r.2)
        .unwrap_or("");
    ui::hint(role_desc);
    println!();

    let token = Password::new("  Telegram bot token:")
        .without_confirmation()
        .with_help_message("Get this from @BotFather on Telegram")
        .prompt()?;

    let bot = BotConfig {
        name: bot_name.clone(),
        role: role.to_string(),
        token,
    };

    // Show summary
    println!();
    let token_preview = if bot.token.len() > 8 {
        &bot.token[..8]
    } else {
        &bot.token
    };
    ui::success(&format!(
        "{} {} as {}...",
        bot.name,
        ui::role_badge(&bot.role),
        token_preview,
    ));

    let confirm = Confirm::new("\n  Add this agent?")
        .with_default(true)
        .prompt()?;

    if !confirm {
        ui::warn("Cancelled.");
        return Ok(());
    }

    // Load current config
    let (current_bots, current_providers) = load_current_config(name)?;
    let mut bots = current_bots;
    bots.push(bot);

    // Save updated config
    save_updated_config(name, &bots, &current_providers)?;

    println!();
    ui::success(&format!("Agent '{}' added.", bot_name));
    Ok(())
}

/// Remove a bot from the garden
fn remove_bot(name: &str) -> Result<()> {
    let (current_bots, current_providers) = load_current_config(name)?;

    if current_bots.is_empty() {
        println!();
        ui::warn("No agents registered.");
        return Ok(());
    }

    // Show current bots
    println!();
    println!("  {} Registered agents:", "\x1b[2m");
    for (i, bot) in current_bots.iter().enumerate() {
        println!(
            "    {} {}. {} {}",
            "\x1b[2m",
            i + 1,
            bot.name,
            ui::role_badge(&bot.role)
        );
    }
    println!("{}", "\x1b[0m");

    let to_remove = MultiSelect::new(
        "  Select agents to remove:",
        current_bots.iter().map(|b| b.name.clone()).collect(),
    )
    .prompt()?;

    if to_remove.is_empty() {
        ui::warn("Nothing selected.");
        return Ok(());
    }

    let confirm = Confirm::new(&format!("\n  Remove {} agent(s)?", to_remove.len()))
        .with_default(true)
        .prompt()?;

    if !confirm {
        ui::warn("Cancelled.");
        return Ok(());
    }

    let remove_names: Vec<String> = to_remove.into_iter().collect();
    let bots: Vec<BotConfig> = current_bots
        .into_iter()
        .filter(|b| !remove_names.contains(&b.name))
        .collect();

    save_updated_config(name, &bots, &current_providers)?;

    println!();
    ui::success("Selected agents removed.");
    Ok(())
}

/// Add a new provider to the garden
fn add_provider(name: &str) -> Result<()> {
    println!();
    ui::divider();
    println!("  {} Adding a new provider", "\x1b[1m\x1b[38;5;255m");
    println!("{}", "\x1b[0m");

    let providers = ProviderRegistry::providers();
    let provider_options: Vec<String> = providers
        .iter()
        .map(|p| format!("{} {}", p.icon, p.label))
        .collect();

    let selection = MultiSelect::new("  Select providers to add:", provider_options).prompt()?;

    if selection.is_empty() {
        ui::warn("Nothing selected.");
        return Ok(());
    }

    let (current_bots, mut providers_data) = load_current_config(name)?;
    let original_count = providers_data.len();

    for provider_label in &selection {
        let provider = providers
            .iter()
            .find(|p| format!("{} {}", p.icon, p.label) == *provider_label)
            .expect("Provider not found");

        println!();
        println!("  {} {} setup:", provider.icon, provider.label);

        let auth_method = if provider.auth.len() > 1 {
            select_auth_method(provider)?
        } else {
            provider.auth.first().unwrap().clone()
        };

        let api_key = Password::new(&format!("  Enter {} API key:", auth_method.label))
            .without_confirmation()
            .with_help_message("This will be stored in .env and pi-auth.json")
            .prompt()?;

        providers_data.push((Arc::new(provider.clone()), auth_method.id.clone(), api_key));

        println!();
        ui::success(&format!(
            "{} ({}) configured",
            provider.label, auth_method.label
        ));
    }

    let added = providers_data.len() - original_count;
    let confirm = Confirm::new(&format!("\n  Add {} provider(s)?", added))
        .with_default(true)
        .prompt()?;

    if !confirm {
        ui::warn("Cancelled.");
        return Ok(());
    }

    save_updated_config(name, &current_bots, &providers_data)?;

    println!();
    ui::success(&format!("{} provider(s) added.", added));
    Ok(())
}

/// Remove a provider from the garden
fn remove_provider(name: &str) -> Result<()> {
    let (current_bots, current_providers) = load_current_config(name)?;

    if current_providers.is_empty() {
        println!();
        ui::warn("No providers registered.");
        return Ok(());
    }

    // Show current providers
    println!();
    println!("  {} Registered providers:", "\x1b[2m");
    for (i, (provider, method_id, _)) in current_providers.iter().enumerate() {
        println!(
            "    {} {}. {} ({})",
            "\x1b[2m",
            i + 1,
            provider.icon,
            method_id
        );
    }
    println!("{}", "\x1b[0m");

    let provider_labels: Vec<String> = current_providers
        .iter()
        .map(|(p, method_id, _)| format!("{} {} ({})", p.icon, p.label, method_id))
        .collect();

    let to_remove = MultiSelect::new("  Select providers to remove:", provider_labels).prompt()?;

    if to_remove.is_empty() {
        ui::warn("Nothing selected.");
        return Ok(());
    }

    let confirm = Confirm::new(&format!("\n  Remove {} provider(s)?", to_remove.len()))
        .with_default(true)
        .prompt()?;

    if !confirm {
        ui::warn("Cancelled.");
        return Ok(());
    }

    let remove_labels: Vec<String> = to_remove.into_iter().collect();
    let providers: Vec<(Arc<ProviderPlugin>, String, String)> = current_providers
        .into_iter()
        .filter(|(p, method_id, _)| {
            let label = format!("{} {} ({})", p.icon, p.label, method_id);
            !remove_labels.contains(&label)
        })
        .collect();

    save_updated_config(name, &current_bots, &providers)?;

    println!();
    ui::success("Selected providers removed.");
    Ok(())
}

/// Show current configuration
fn show_config(name: &str) -> Result<()> {
    let registry = load_gardens()?;

    let garden_dir = registry.garden_dir(name);
    let compose_file = registry.compose_file(name);
    let env_file = registry.env_file(name);

    let mut rows = vec![
        ("๐Ÿก".to_string(), "Garden".to_string(), name.to_string()),
        (
            "๐Ÿ“".to_string(),
            "Path".to_string(),
            garden_dir.display().to_string(),
        ),
        (
            "๐Ÿณ".to_string(),
            "Container".to_string(),
            format!("garden-{}", name),
        ),
        (
            "๐Ÿ“„".to_string(),
            "Compose".to_string(),
            if compose_file.exists() {
                "โœ“ present".to_string()
            } else {
                "โœ— missing".to_string()
            },
        ),
        (
            "๐Ÿ”".to_string(),
            ".env".to_string(),
            if env_file.exists() {
                "โœ“ present".to_string()
            } else {
                "โœ— missing".to_string()
            },
        ),
    ];

    let (bots, providers) = load_current_config(name)?;

    rows.push((
        "๐Ÿค–".to_string(),
        "Agents".to_string(),
        format!("{} total", bots.len()),
    ));
    for bot in &bots {
        rows.push((
            "  ".to_string(),
            "  ".to_string(),
            format!("{} {}", bot.name, ui::role_badge(&bot.role)),
        ));
    }

    rows.push((
        "๐Ÿ”Œ".to_string(),
        "Providers".to_string(),
        format!("{} total", providers.len()),
    ));
    for (provider, method_id, _) in &providers {
        rows.push((
            "  ".to_string(),
            "  ".to_string(),
            format!("{} {} ({})", provider.icon, provider.label, method_id),
        ));
    }

    ui::summary_box(&format!("โš™๏ธ {} โ€” Configuration", name), &rows);

    Ok(())
}

/// Restart container to apply configuration changes
fn restart_garden(name: &str) -> Result<()> {
    println!();
    ui::spinner("Restarting container...", 500);
    crate::compose::restart_garden(name)?;
    println!();
    ui::success("Container restarted.");
    Ok(())
}

// โ”€โ”€ Config persistence โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Load current configuration from a garden.
///
/// Returns (bots, providers) โ€” parses bots from registry.json and
/// providers from the .env file (by matching known provider env var patterns).
fn load_current_config(
    name: &str,
) -> Result<(Vec<BotConfig>, Vec<(Arc<ProviderPlugin>, String, String)>)> {
    let registry = load_gardens()?;
    let workspace_dir = registry.workspace_dir(name);
    let registry_file = workspace_dir.join("agents/registry.json");
    let env_file = registry.env_file(name);

    // โ”€โ”€ Load .env into a lookup map (used for both tokens and providers) โ”€โ”€
    let mut env_map: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    if env_file.exists() {
        let env_content = std::fs::read_to_string(&env_file).context("Failed to read .env")?;
        for line in env_content.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            if let Some((key, value)) = line.split_once('=') {
                env_map.insert(key.trim().to_string(), value.trim().to_string());
            }
        }
    }

    // โ”€โ”€ Parse bots from registry.json, resolve actual tokens from .env โ”€โ”€
    let mut bots = Vec::new();
    if registry_file.exists() {
        let content =
            std::fs::read_to_string(&registry_file).context("Failed to read registry.json")?;
        let json: serde_json::Value =
            serde_json::from_str(&content).context("Failed to parse registry.json")?;

        if let Some(agents) = json.get("agents").and_then(|a| a.as_array()) {
            for agent in agents {
                if let (Some(name), Some(_bot), Some(role)) = (
                    agent.get("name").and_then(|v| v.as_str()),
                    agent.get("bot").and_then(|v| v.as_object()),
                    agent.get("role").and_then(|v| v.as_str()),
                ) {
                    let token_env_key = agent
                        .get("bot")
                        .and_then(|v| v.get("token_env"))
                        .and_then(|v| v.as_str())
                        .unwrap_or_default();

                    // Resolve the actual token value from .env
                    let token = env_map.get(token_env_key).cloned().unwrap_or_default();

                    bots.push(BotConfig {
                        name: name.to_string(),
                        role: role.to_string(),
                        token,
                    });
                }
            }
        }
    }

    // โ”€โ”€ Parse providers from .env (by matching known provider env var patterns) โ”€โ”€
    let mut providers: Vec<(Arc<ProviderPlugin>, String, String)> = Vec::new();
    for known in ProviderRegistry::providers() {
        let env_key = format!("{}_API_KEY", known.id.to_uppercase());
        if let Some(value) = env_map.get(&env_key) {
            if !value.is_empty() {
                let auth = known
                    .auth
                    .first()
                    .map(|a| a.id.clone())
                    .unwrap_or_else(|| "api-key".to_string());
                providers.push((Arc::new(known.clone()), auth, value.clone()));
            }
        }
    }

    Ok((bots, providers))
}

/// Save updated configuration to a garden
fn save_updated_config(
    name: &str,
    bots: &[BotConfig],
    providers: &[(Arc<ProviderPlugin>, String, String)],
) -> Result<()> {
    let registry = load_gardens()?;
    let garden_dir = registry.garden_dir(name);
    let workspace_dir = registry.workspace_dir(name);

    // Create directories if needed
    std::fs::create_dir_all(&workspace_dir.join("agents"))
        .context("Failed to create agents directory")?;
    std::fs::create_dir_all(&workspace_dir.join("data"))
        .context("Failed to create data directory")?;
    std::fs::create_dir_all(&workspace_dir.join("logs"))
        .context("Failed to create logs directory")?;

    let config = GardenConfig {
        name: name.to_string(),
        telegram_group_id: load_telegram_group_id(name)?,
        bots: bots.to_vec(),
        providers: providers.to_vec(),
    };

    // Write docker-compose.yml
    let compose_path = registry.compose_file(name);
    std::fs::write(&compose_path, config.generate_compose())
        .context("Failed to write docker-compose.yml")?;

    // Write .env
    let env_path = registry.env_file(name);
    std::fs::write(&env_path, config.generate_env()).context("Failed to write .env file")?;

    // Write pi-auth.json
    let auth_json_path = garden_dir.join("pi-auth.json");
    std::fs::write(&auth_json_path, config.generate_auth_json())
        .context("Failed to write pi-auth.json")?;

    // Write registry.json
    let registry_path = workspace_dir.join("agents/registry.json");
    std::fs::write(&registry_path, config.generate_registry_json())
        .context("Failed to write registry.json")?;

    // Write allowlist
    let allowlist_path = workspace_dir.join("agents/.allowlist");
    std::fs::write(&allowlist_path, "pi-coding-agent\n").context("Failed to write allowlist")?;

    Ok(())
}

/// Load Telegram group ID from .env file
fn load_telegram_group_id(name: &str) -> Result<String> {
    let registry = load_gardens()?;
    let env_file = registry.env_file(name);

    if !env_file.exists() {
        return Ok(String::new());
    }

    let content = std::fs::read_to_string(&env_file)?;
    for line in content.lines() {
        if line.starts_with("TELEGRAM_GROUP_ID=") {
            if let Some(value) = line.split_once('=') {
                return Ok(value.1.trim().to_string());
            }
        }
    }

    Ok(String::new())
}

/// Select auth method for a provider (when multiple available)
fn select_auth_method(provider: &ProviderPlugin) -> Result<ProviderAuthMethod> {
    if provider.auth.len() == 1 {
        return Ok(provider.auth.first().unwrap().clone());
    }

    let method_options: Vec<String> = provider
        .auth
        .iter()
        .map(|m| match &m.hint {
            Some(h) => format!("{} ({})", m.label, h),
            None => m.label.clone(),
        })
        .collect();

    let selection = Select::new("  Select authentication method:", method_options).prompt()?;

    provider
        .auth
        .iter()
        .find(|m| match &m.hint {
            Some(h) => format!("{} ({})", m.label, h) == selection,
            None => m.label == selection,
        })
        .cloned()
        .ok_or_else(|| anyhow::anyhow!("Auth method not found"))
}