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
//! Onboarding wizard for ClawGarden
//!
//! Interactive CLI wizard that guides users through creating a garden.
//! Designed around a "digital garden" metaphor — planting seeds (bots),
//! choosing sunlight (providers), and watching it bloom.

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

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

/// Selected provider with chosen auth method and API key
type SelectedProvider = (Arc<ProviderPlugin>, String, String);

/// Total number of wizard steps
const TOTAL_STEPS: usize = 7;

// ── Wizard entry point ───────────────────────────────────────────────────────

/// Run the full onboarding wizard
pub fn run_wizard() -> Result<()> {
    run_wizard_inner(false)
}

/// Run the wizard, skipping the dependency check step.
pub fn run_wizard_skip_deps() -> Result<()> {
    run_wizard_inner(true)
}

fn run_wizard_inner(skip_deps: bool) -> Result<()> {
    ui::print_banner();

    println!(
        "  {}Welcome to the garden setup wizard.{}",
        ui::DIM,
        ui::RESET
    );
    println!(
        "  {}We'll walk through {} steps to plant your garden.{}",
        ui::DIM,
        TOTAL_STEPS,
        ui::RESET
    );
    ui::flower_separator();

    // Step 1: Dependency check (skip if caller already checked)
    if !skip_deps {
        let step = 1;
        ui::progress_bar(0, TOTAL_STEPS);
        ui::section_header(step, TOTAL_STEPS, "🌱", "Garden Bed Preparation");
        ui::hint("First, let's make sure your soil is ready...");
        println!();
        step_dependency_check()?;
    }
    // Step 2: Garden name
    let step = 2;
    ui::progress_bar(1, TOTAL_STEPS);
    ui::section_header(step, TOTAL_STEPS, "📛", "Name Your Garden");
    ui::hint("Give your garden a name — like \"my-garden\" or \"team-chat\".");
    println!();
    let name: String = Text::new("  Garden name:")
        .with_placeholder("my-garden")
        .with_help_message("lowercase, hyphens allowed")
        .prompt()?;
    let name = name.trim().to_string();
    if name.is_empty() {
        anyhow::bail!("Garden name is required");
    }

    // Step 3: Telegram bots
    let step = 3;
    ui::progress_bar(2, TOTAL_STEPS);
    ui::section_header(step, TOTAL_STEPS, "🤖", "Plant Your Seeds");
    ui::hint("Each agent needs a Telegram bot. Add as many as you like.");
    println!();
    let bots = step_telegram_bots()?;

    // Step 4: Telegram group ID
    let step = 4;
    ui::progress_bar(3, TOTAL_STEPS);
    ui::section_header(step, TOTAL_STEPS, "💬", "Telegram Group Link");
    ui::hint("Where will your agents live? This is the group they'll chat in.");
    println!();
    let group_id = step_telegram_group_id()?;

    // Step 5: Pi providers
    let step = 5;
    ui::progress_bar(4, TOTAL_STEPS);
    ui::section_header(step, TOTAL_STEPS, "☀️", "Choose Your Sunlight");
    ui::hint("AI providers power your agents. Pick one or more to fuel them.");
    println!();
    let providers = step_providers()?;

    // Step 6: Summary and create
    let step = 6;
    ui::progress_bar(5, TOTAL_STEPS);
    ui::section_header(step, TOTAL_STEPS, "📋", "Garden Blueprint");
    ui::hint("Review everything before we plant.");
    println!();
    step_create_garden(&name, &group_id, &bots, &providers)?;

    // Step 7: Start garden
    let step = 7;
    ui::progress_bar(6, TOTAL_STEPS);
    ui::section_header(step, TOTAL_STEPS, "🚀", "Let It Bloom");
    println!();
    step_start_garden(&name)?;

    // Done
    ui::progress_bar(TOTAL_STEPS, TOTAL_STEPS);
    ui::celebration(&name);
    ui::next_steps(&name);
    ui::flower_separator();

    Ok(())
}

// ── Step implementations ─────────────────────────────────────────────────────

/// Step 1: Check dependencies
fn step_dependency_check() -> Result<()> {
    // Animated check
    ui::spinner("Inspecting garden bed...", 800);

    let check = deps::DependencyCheck::check_all();
    check.print_report();

    if !check.is_ready() {
        println!();
        ui::error("Your garden bed needs some work. Fix the issues above and re-run.");
        anyhow::bail!("Missing dependencies");
    }

    println!();
    let cont = Confirm::new("  Ready to proceed?")
        .with_default(true)
        .prompt()?;

    if !cont {
        anyhow::bail!("Onboarding cancelled.");
    }

    Ok(())
}

/// Step 3: Telegram bots (loop)
fn step_telegram_bots() -> Result<Vec<BotConfig>> {
    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 mut bots = Vec::new();
    let mut bot_number = 0;

    loop {
        bot_number += 1;

        println!("  ──── Agent #{} ────\n", bot_number);

        // Bot name
        let name = Text::new("  Agent name (lowercase, 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()?;

        if bots.iter().any(|b: &BotConfig| b.name == name) {
            println!();
            ui::warn(&format!(
                "'{}' is already planted. Choose a different name.",
                name
            ));
            println!();
            bot_number -= 1;
            continue;
        }

        println!("  {} Available roles:", "\x1b[1m");
        for (role_name, icon, desc) in &roles {
            println!("    {} {} {}", icon, ui::role_badge(role_name), desc,);
        }
        println!("{}", ui::RESET);

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

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

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

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

        println!(
            "  {} {} {} as {}",
            ui::GREEN,
            &bot.name,
            ui::role_badge(&bot.role),
            if bot.token.len() > 8 {
                &bot.token[..8]
            } else {
                &bot.token
            }
            .to_string()
                + "...",
        );
        println!("{}", ui::RESET);

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

        if confirm {
            bots.push(bot);
            ui::success("Agent planted!");
        } else {
            ui::warn("Skipped.");
            bot_number -= 1;
        }

        println!();

        if bots.is_empty() {
            let add_more = Confirm::new("  No agents yet. Add one?")
                .with_default(true)
                .prompt()?;
            if !add_more {
                break;
            }
        } else {
            // Show current roster
            println!("  {} Your garden so far:", ui::DIM);
            for (i, b) in bots.iter().enumerate() {
                println!(
                    "    {}{}. {} {}",
                    ui::DIM,
                    i + 1,
                    b.name,
                    ui::role_badge(&b.role),
                );
            }
            println!("{}", ui::RESET);

            let add_more = Confirm::new("\n  Plant another agent?")
                .with_default(false)
                .prompt()?;

            if !add_more {
                break;
            }
        }
    }

    if bots.is_empty() {
        println!();
        ui::error("A garden needs at least one agent to tend it.");
        anyhow::bail!("At least one bot is required");
    }

    // Final roster display
    println!();
    ui::divider();
    println!(
        "  {} Garden Roster ({} agents){}",
        "\x1b[1m",
        bots.len(),
        ui::RESET
    );
    println!();
    for (i, bot) in bots.iter().enumerate() {
        println!(
            "    {} {} {}",
            format!("{:>2}.", i + 1),
            bot.name,
            ui::role_badge(&bot.role),
        );
    }
    ui::divider();

    Ok(bots)
}

/// Step 4: Telegram group ID
fn step_telegram_group_id() -> Result<String> {
    println!("  Which Telegram group will your agents live in?");
    println!();
    ui::tip("Add your bots to a Telegram group first, then get the group ID.");
    println!();

    let group_id = Text::new("  Telegram group ID:")
        .with_default("-1001234567890")
        .with_validator(|input: &str| {
            if !input.starts_with('-') {
                return Err("Group IDs start with '-' (e.g. -1001234567890)".into());
            }
            if input.len() < 10 {
                return Err("That looks too short for a group ID".into());
            }
            Ok(inquire::validator::Validation::Valid)
        })
        .with_help_message("You can find this by adding @RawDataBot to your group")
        .prompt()?;

    println!();
    ui::success(&format!("Group {} linked.", group_id));

    Ok(group_id)
}

/// Step 5: Pi providers (plugin-based selection with auth method choice)
fn step_providers() -> Result<Vec<SelectedProvider>> {
    let providers = ProviderRegistry::providers();

    println!("  Which AI providers will power your agents?");
    println!();
    println!("  {} Available providers:", "\x1b[1m");
    for (i, p) in providers.iter().enumerate() {
        println!(
            "    {} {} {}{}",
            format!("{:>2}.", i + 1),
            p.icon,
            p.label,
            match &p.default_model {
                Some(m) => format!(" {}{}{}", ui::DIM, m, ui::RESET),
                None => String::new(),
            },
        );
    }
    println!("{}", ui::RESET);
    println!();

    // Use multi-select with inquire
    let provider_options: Vec<String> = providers
        .iter()
        .map(|p| format!("{} {}", p.icon, p.label))
        .collect();

    let selections = inquire::MultiSelect::new(
        "  Select providers (space to toggle, enter to confirm):",
        provider_options,
    )
    .prompt()?;

    if selections.is_empty() {
        anyhow::bail!("At least one provider must be selected");
    }

    let mut selected_providers = Vec::new();

    for provider_label in &selections {
        // Find the provider by matching the formatted label
        let provider = providers
            .iter()
            .find(|p| format!("{} {}", p.icon, p.label) == *provider_label)
            .expect("Provider not found");

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

        // If provider has multiple auth methods, let user choose
        let auth_method = if provider.auth.len() > 1 {
            select_auth_method(provider)?
        } else {
            provider
                .auth
                .first()
                .expect("No auth method defined")
                .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()?;

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

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

    // Provider summary
    println!();
    ui::divider();
    println!(
        "  {} Sunlight Sources ({} providers){}",
        "\x1b[1m",
        selected_providers.len(),
        ui::RESET
    );
    println!();
    for (i, (p, method_id, _)) in selected_providers.iter().enumerate() {
        println!(
            "    {} {} {} via {}",
            format!("{:>2}.", i + 1),
            p.icon,
            p.label,
            method_id,
        );
    }
    ui::divider();

    Ok(selected_providers)
}

/// 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"))
}

/// Step 6: Create garden files
fn step_create_garden(
    name: &str,
    group_id: &str,
    bots: &[BotConfig],
    providers: &[SelectedProvider],
) -> Result<()> {
    // Build summary box
    let mut rows = vec![
        ("🏡".to_string(), "Garden".to_string(), name.to_string()),
        ("💬".to_string(), "Group".to_string(), group_id.to_string()),
    ];

    rows.push((
        "🤖".to_string(),
        "Agents".to_string(),
        format!("{} bots", bots.len()),
    ));
    for (i, bot) in bots.iter().enumerate() {
        rows.push((
            "  ".to_string(),
            format!("  #{}", i + 1),
            format!("{} {}", bot.name, ui::role_badge(&bot.role)),
        ));
    }

    rows.push((
        "🔌".to_string(),
        "Providers".to_string(),
        format!("{} providers", providers.len()),
    ));
    for (i, (p, method_id, _)) in providers.iter().enumerate() {
        rows.push((
            "  ".to_string(),
            format!("  #{}", i + 1),
            format!("{} ({})", p.icon, method_id),
        ));
    }

    ui::summary_box(&format!("🌿 {} — Garden Blueprint", name), &rows);

    println!();
    let confirm = Confirm::new("  Create this garden?")
        .with_default(true)
        .prompt()?;

    if !confirm {
        anyhow::bail!("Onboarding cancelled.");
    }

    println!();
    ui::spinner("Planting seeds...", 600);

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

    let (compose_path, env_path) = config.write()?;

    ui::spinner("Watering the garden...", 400);

    println!();
    println!("  {} Files created:", "\x1b[1m");
    println!(
        "    📄 {}",
        compose_path.file_name().unwrap().to_string_lossy()
    );
    println!("    🔐 {}", env_path.file_name().unwrap().to_string_lossy());
    println!("{}", ui::RESET);

    // Register in gardens.json
    let mut registry = load_gardens()?;
    registry.add(name.to_string(), registry.garden_dir(name))?;

    println!();
    ui::success(&format!("Garden '{}' registered.", name));

    Ok(())
}

/// Step 7: Start garden
fn step_start_garden(name: &str) -> Result<()> {
    println!("  Your garden is ready. Want to bring it to life?");
    println!();

    let start = Confirm::new("  Start the garden now?")
        .with_default(true)
        .prompt()?;

    if start {
        println!();
        ui::spinner("Warming up the greenhouse...", 500);
        crate::compose::start_garden(name)?;
    } else {
        println!();
        ui::hint("You can start it later with:");
        println!("    {}garden up --name {}{}", ui::GREEN, name, ui::RESET);
    }

    Ok(())
}