clawgarden-cli 0.7.2

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
//! Agent subcommands โ€” garden agent add/list/remove/edit
//!
//! Standalone CLI commands for managing agents in a garden,
//! decoupled from the interactive `garden config` wizard.

use anyhow::Result;
use inquire::{Confirm, Password, Select, Text};

use crate::compose::BotConfig;
use crate::config::{load_current_config, save_updated_config};
use crate::garden;
use crate::ui;

/// Run `garden agent add`
pub fn cmd_add(garden_name: Option<&str>) -> Result<()> {
    let name = garden::resolve_garden_name(garden_name)?;

    println!();
    ui::section_header_no_step("๐Ÿค–", &format!("Add Agent ยท {}", name));

    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"),
    ];

    // โ”€โ”€ Agent name โ”€โ”€
    let bot_name = ui::retry_prompt(|| {
        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()
    })?;

    // Check for duplicate
    let (current_bots, current_providers) = load_current_config(&name)?;
    if current_bots.iter().any(|b| b.name == bot_name) {
        anyhow::bail!("Agent '{}' already exists in garden '{}'", bot_name, name);
    }

    // โ”€โ”€ Role selection โ”€โ”€
    println!();
    for (role_name, icon, desc) in &roles {
        println!("    {} {} {}", icon, ui::role_badge(role_name), desc);
    }
    println!();

    let role_names: Vec<&str> = roles.iter().map(|r| r.0).collect();
    let role = ui::retry_prompt(|| 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!();

    // โ”€โ”€ Telegram bot token โ”€โ”€
    let token = ui::retry_prompt(|| {
        Password::new("  Telegram bot token:")
            .without_confirmation()
            .with_help_message("Get this from @BotFather on Telegram")
            .prompt()
    })?;

    // โ”€โ”€ Confirm โ”€โ”€
    let token_preview = if token.len() > 8 { &token[..8] } else { &token };

    println!();
    ui::success(&format!(
        "{} {} as {}...",
        bot_name,
        ui::role_badge(role),
        token_preview,
    ));

    let confirm = ui::retry_prompt(|| {
        Confirm::new("  Add this agent?")
            .with_default(true)
            .prompt()
    })?;

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

    // โ”€โ”€ Save โ”€โ”€
    let mut bots = current_bots;
    bots.push(BotConfig {
        name: bot_name.clone(),
        role: role.to_string(),
        token,
        username: String::new(),
        priority: 100,
        enabled: true,
    });

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

    println!();
    ui::success(&format!(
        "Agent '{}' {} added to garden '{}'.",
        bot_name,
        ui::role_badge(role),
        name
    ));
    ui::hint(&format!(
        "Run `garden up --name {}` to apply changes.",
        name
    ));

    Ok(())
}

/// Run `garden agent list`
pub fn cmd_list(garden_name: Option<&str>) -> Result<()> {
    let name = garden::resolve_garden_name(garden_name)?;

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

    println!();
    ui::section_header_no_step("๐Ÿ“‹", &format!("Agents ยท {}", name));

    if bots.is_empty() {
        println!();
        ui::warn("No agents registered yet.");
        println!();
        ui::hint(&format!("Add one with: garden agent add --name {}", name));
        println!();
        return Ok(());
    }

    let mut rows = vec![(
        "๐Ÿค–".to_string(),
        "Agents".to_string(),
        format!("{} registered", bots.len()),
    )];

    for (i, bot) in bots.iter().enumerate() {
        let badge = ui::role_badge(&bot.role);
        rows.push((
            format!("  {}.", i + 1),
            bot.name.clone(),
            format!("{}", badge),
        ));
    }

    rows.push((
        "๐Ÿ”Œ".to_string(),
        "Providers".to_string(),
        format!("{} configured", providers.len()),
    ));

    ui::summary_box(&format!("๐ŸŒฑ {} โ€” Agents", name), &rows);

    Ok(())
}

/// Run `garden agent edit` โ€” edit role or token of an existing agent
pub fn cmd_edit(garden_name: Option<&str>) -> Result<()> {
    let name = garden::resolve_garden_name(garden_name)?;

    println!();
    ui::section_header_no_step("โœ๏ธ", &format!("Edit Agent ยท {}", name));

    let (current_bots, current_providers) = load_current_config(&name)?;

    if current_bots.is_empty() {
        println!();
        ui::warn("No agents registered.");
        ui::hint(&format!("Add one with: garden agent add --name {}", name));
        return Ok(());
    }

    // Show current agents
    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");

    // Select agent
    let bot_labels: Vec<String> = current_bots
        .iter()
        .map(|b| format!("{} {}", b.name, ui::role_badge(&b.role)))
        .collect();

    let selection = ui::retry_prompt(|| {
        Select::new("  Select an agent to edit:", bot_labels.clone()).prompt()
    })?;

    let idx = current_bots
        .iter()
        .position(|b| format!("{} {}", b.name, ui::role_badge(&b.role)) == selection)
        .ok_or_else(|| anyhow::anyhow!("Agent '{}' not found", selection))?;

    let entry = &current_bots[idx];
    let bot_name = entry.name.clone();
    let old_role = entry.role.clone();
    let old_token = entry.token.clone();

    // Show current values
    println!();
    ui::divider();
    println!("  {} โ€” current configuration", bot_name);
    println!();
    let masked_token = if old_token.len() > 8 {
        format!("{}...", &old_token[..8])
    } else {
        "****".to_string()
    };
    ui::hint(&format!("  Role:   {}", ui::role_badge(&old_role)));
    ui::hint(&format!("  Token:  {}", masked_token));
    println!();

    // What to edit
    let edit_choices = vec!["๐ŸŽญ Change role", "๐Ÿ”‘ Change token", "๐ŸŽญ๐Ÿ”‘ Change both"];
    let action = ui::retry_prompt(|| {
        Select::new("  What would you like to change?", edit_choices.clone()).prompt()
    })?;

    let roles = [
        ("PM", "๐Ÿ“‹"),
        ("DEV", "๐Ÿ’ป"),
        ("CRITIC", "๐Ÿ”"),
        ("DESIGNER", "๐ŸŽจ"),
        ("RESEARCHER", "๐Ÿ”ฌ"),
        ("TESTER", "๐Ÿงช"),
        ("OPS", "๐Ÿ”ง"),
        ("ANALYST", "๐Ÿ“Š"),
        ("OTHER", "โœจ"),
    ];
    let role_names: Vec<&str> = roles.iter().map(|r| r.0).collect();

    let mut new_role = old_role.clone();
    let mut new_token = old_token.clone();

    match action {
        "๐ŸŽญ Change role" => {
            println!();
            for (role_name, icon) in &roles {
                println!("    {} {}", icon, ui::role_badge(role_name));
            }
            println!();
            new_role = ui::retry_prompt(|| {
                Select::new("  Choose a new role:", role_names.to_vec()).prompt()
            })?
            .to_string();
        }
        "๐Ÿ”‘ Change token" => {
            new_token = ui::retry_prompt(|| {
                Password::new(&format!("  Enter new token for {}:", bot_name))
                    .without_confirmation()
                    .with_help_message("Get this from @BotFather on Telegram")
                    .prompt()
            })?;
        }
        "๐ŸŽญ๐Ÿ”‘ Change both" => {
            println!();
            for (role_name, icon) in &roles {
                println!("    {} {}", icon, ui::role_badge(role_name));
            }
            println!();
            new_role = ui::retry_prompt(|| {
                Select::new("  Choose a new role:", role_names.to_vec()).prompt()
            })?
            .to_string();
            println!();
            new_token = ui::retry_prompt(|| {
                Password::new(&format!("  Enter new token for {}:", bot_name))
                    .without_confirmation()
                    .with_help_message("Get this from @BotFather on Telegram")
                    .prompt()
            })?;
        }
        _ => unreachable!(),
    }

    // Summary
    println!();
    if new_role != old_role {
        ui::success(&format!(
            "Role: {} โ†’ {}",
            ui::role_badge(&old_role),
            ui::role_badge(&new_role)
        ));
    }
    if new_token != old_token {
        let new_masked = if new_token.len() > 8 {
            format!("{}...", &new_token[..8])
        } else {
            "****".to_string()
        };
        ui::success(&format!("Token: updated to {}", new_masked));
    }

    let confirm =
        ui::retry_prompt(|| Confirm::new("  Apply changes?").with_default(true).prompt())?;

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

    // Apply โ€” preserve username/priority/enabled from existing bot
    let old_username = current_bots[idx].username.clone();
    let old_priority = current_bots[idx].priority;
    let old_enabled = current_bots[idx].enabled;
    let mut bots = current_bots;
    bots[idx] = BotConfig {
        name: bot_name.clone(),
        role: new_role,
        token: new_token,
        username: old_username,
        priority: old_priority,
        enabled: old_enabled,
    };

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

    println!();
    ui::success(&format!(
        "Agent '{}' updated in garden '{}'.",
        bot_name, name
    ));
    ui::hint(&format!(
        "Run `garden up --name {}` to apply changes.",
        name
    ));

    Ok(())
}

/// Run `garden agent remove`
pub fn cmd_remove(garden_name: Option<&str>, agent_name: Option<&str>) -> Result<()> {
    let name = garden::resolve_garden_name(garden_name)?;

    println!();
    ui::section_header_no_step("๐Ÿ—‘๏ธ", &format!("Remove Agent ยท {}", name));

    let (current_bots, current_providers) = load_current_config(&name)?;

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

    // If agent name given via CLI arg, use it directly; otherwise prompt
    let to_remove = if let Some(agent) = agent_name {
        if !current_bots.iter().any(|b| b.name == agent) {
            anyhow::bail!(
                "Agent '{}' not found in garden '{}'. Registered: {}",
                agent,
                name,
                current_bots
                    .iter()
                    .map(|b| b.name.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            );
        }
        agent.to_string()
    } else {
        // Interactive selection
        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 bot_names: Vec<&str> = current_bots.iter().map(|b| b.name.as_str()).collect();
        let selection = ui::retry_prompt(|| {
            Select::new("  Select agent to remove:", bot_names.to_vec()).prompt()
        })?;
        selection.to_string()
    };

    // Confirm
    let confirm = ui::retry_prompt(|| {
        Confirm::new(&format!("  Remove agent '{}'?", to_remove))
            .with_default(false)
            .prompt()
    })?;

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

    // Remove and save
    let bots: Vec<BotConfig> = current_bots
        .into_iter()
        .filter(|b| b.name != to_remove)
        .collect();

    if bots.is_empty() {
        ui::warn("Garden will have no agents after removal.");
        let proceed =
            ui::retry_prompt(|| Confirm::new("  Continue?").with_default(false).prompt())?;
        if !proceed {
            ui::warn("Cancelled.");
            return Ok(());
        }
    }

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

    println!();
    ui::success(&format!(
        "Agent '{}' removed from garden '{}'.",
        to_remove, name
    ));
    ui::hint(&format!(
        "Run `garden up --name {}` to apply changes.",
        name
    ));

    Ok(())
}