clawgarden-cli 0.4.0

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
//! Provider subcommands โ€” garden provider add/list/remove
//!
//! Standalone CLI commands for managing providers in a garden,
//! with model selection support.

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

use crate::compose::ProviderEntry;
use crate::config::{load_current_config, save_updated_config, select_provider_model};
use crate::garden::load_gardens;
use crate::providers::{ProviderAuthMethod, ProviderRegistry};
use crate::ui;

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

    println!();
    ui::section_header_no_step("๐Ÿ”Œ", &format!("Add Provider ยท {}", name));

    let providers = ProviderRegistry::providers();
    let provider_options: Vec<String> = providers
        .iter()
        .map(|p| {
            let model_hint = match &p.default_model {
                Some(m) => format!(" โ†’ {}", m),
                None => String::new(),
            };
            format!("{} {}{}", p.icon, p.label, model_hint)
        })
        .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| {
                let model_hint = match &p.default_model {
                    Some(m) => format!(" โ†’ {}", m),
                    None => String::new(),
                };
                format!("{} {}{}", p.icon, p.label, model_hint) == *provider_label
            })
            .expect("Provider not found");

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

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

        // API key
        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()?;

        // Model selection
        let model = select_provider_model(provider)?;

        providers_data.push(ProviderEntry {
            provider: Arc::new(provider.clone()),
            auth_method_id: auth_method.id.clone(),
            api_key,
            model,
        });

        println!();
        ui::success(&format!(
            "{} ({}) configured โ†’ {}",
            provider.label, auth_method.label,
            providers_data.last().unwrap().model
        ));
    }

    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 to garden '{}'.", added, name));
    ui::hint(&format!("Run `garden up --name {}` to apply changes.", name));

    Ok(())
}

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

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

    println!();
    ui::section_header_no_step("๐Ÿ”Œ", &format!("Providers ยท {}", name));

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

    let mut rows = vec![(
        "๐Ÿ”Œ".to_string(),
        "Providers".to_string(),
        format!("{} configured", providers.len()),
    )];

    for (i, entry) in providers.iter().enumerate() {
        rows.push((
            format!("  {}.", i + 1),
            entry.provider.label.clone(),
            format!("{} โ†’ {}", entry.provider.icon, entry.model),
        ));
    }

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

    Ok(())
}

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

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

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

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

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

    let provider_labels: Vec<String> = current_providers
        .iter()
        .map(|entry| {
            format!(
                "{} {} ({}) โ†’ {}",
                entry.provider.icon,
                entry.provider.label,
                entry.auth_method_id,
                entry.model
            )
        })
        .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<ProviderEntry> = current_providers
        .into_iter()
        .filter(|entry| {
            let label = format!(
                "{} {} ({}) โ†’ {}",
                entry.provider.icon,
                entry.provider.label,
                entry.auth_method_id,
                entry.model
            );
            !remove_labels.contains(&label)
        })
        .collect();

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

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

    Ok(())
}

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

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

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

    if current_providers.is_empty() {
        println!();
        ui::warn("No providers configured.");
        ui::hint(&format!(
            "Add one with: garden provider add --name {}",
            name
        ));
        return Ok(());
    }

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

    // Select which provider to edit
    let provider_labels: Vec<String> = current_providers
        .iter()
        .map(|entry| {
            format!(
                "{} {} โ†’ {}",
                entry.provider.icon, entry.provider.label, entry.model
            )
        })
        .collect();

    let selection = Select::new("  Select a provider to edit:", provider_labels).prompt()?;
    let idx = current_providers
        .iter()
        .position(|entry| {
            format!(
                "{} {} โ†’ {}",
                entry.provider.icon, entry.provider.label, entry.model
            ) == selection
        })
        .expect("Selected provider not found");

    let entry = &current_providers[idx];
    let provider = entry.provider.clone();
    let old_model = entry.model.clone();
    let old_api_key = entry.api_key.clone();
    let old_auth_method_id = entry.auth_method_id.clone();

    // Show current values
    println!();
    ui::divider();
    println!(
        "  {} {} โ€” current configuration",
        provider.icon, provider.label
    );
    println!();
    let masked_key = if old_api_key.len() > 8 {
        format!("{}...", &old_api_key[..8])
    } else {
        "****".to_string()
    };
    ui::hint(&format!("  Model:        {}", old_model));
    ui::hint(&format!("  API key:      {}", masked_key));
    ui::hint(&format!("  Auth method:  {}", old_auth_method_id));
    println!();

    // What to edit
    let edit_choices = vec!["๐ŸŽฏ Change model", "๐Ÿ”‘ Change API key", "๐ŸŽฏ๐Ÿ”‘ Change both"];
    let action = Select::new("  What would you like to change?", edit_choices).prompt()?;

    let mut new_model = old_model.clone();
    let mut new_api_key = old_api_key.clone();
    let new_auth_method_id = old_auth_method_id.clone();

    match action {
        "๐ŸŽฏ Change model" => {
            new_model = select_provider_model(&provider)?;
        }
        "๐Ÿ”‘ Change API key" => {
            let api_key = Password::new(&format!("  Enter new {} API key:", provider.label))
                .without_confirmation()
                .with_help_message("This will be stored in .env and pi-auth.json")
                .prompt()?;
            new_api_key = api_key;
        }
        "๐ŸŽฏ๐Ÿ”‘ Change both" => {
            new_model = select_provider_model(&provider)?;
            println!();
            let api_key = Password::new(&format!("  Enter new {} API key:", provider.label))
                .without_confirmation()
                .with_help_message("This will be stored in .env and pi-auth.json")
                .prompt()?;
            new_api_key = api_key;
        }
        _ => unreachable!(),
    }

    // Summary
    println!();
    if new_model != old_model {
        ui::success(&format!(
            "Model: {} โ†’ {}",
            old_model, new_model
        ));
    }
    if new_api_key != old_api_key {
        let new_masked = if new_api_key.len() > 8 {
            format!("{}...", &new_api_key[..8])
        } else {
            "****".to_string()
        };
        ui::success(&format!("API key: updated to {}", new_masked));
    }

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

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

    // Apply
    current_providers[idx] = ProviderEntry {
        provider: provider.clone(),
        auth_method_id: new_auth_method_id,
        api_key: new_api_key,
        model: new_model,
    };

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

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

    Ok(())
}

// โ”€โ”€ Helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Resolve garden name from argument or default
fn resolve_garden_name(name: Option<&str>) -> Result<String> {
    if let Some(n) = name {
        let registry = load_gardens()?;
        if !registry.exists(n) {
            anyhow::bail!("Garden '{}' not found. Run 'garden new' first.", n);
        }
        return Ok(n.to_string());
    }

    let registry = load_gardens()?;

    if registry.gardens.is_empty() {
        anyhow::bail!("No gardens found. Run 'garden new' to create one.");
    }

    if registry.gardens.len() == 1 {
        return Ok(registry.gardens[0].name.clone());
    }

    // Multiple gardens โ€” ask user
    let names: Vec<&str> = registry.gardens.iter().map(|g| g.name.as_str()).collect();
    let selection = Select::new("  Select a garden:", names.to_vec()).prompt()?;
    Ok(selection.to_string())
}

/// Select auth method for a provider
fn select_auth_method(provider: &crate::providers::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"))
}