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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! Docker Compose file generator for ClawGarden
//!
//! Generates per-garden docker-compose.yml and .env files.
//! Also provides container lifecycle and inspection helpers.

use anyhow::{Context, Result};
use std::path::PathBuf;

use crate::garden::load_gardens;
use crate::providers::ProviderPlugin;
use std::sync::Arc;

// ── Data types ───────────────────────────────────────────────────────────────

/// Telegram bot configuration
#[derive(Debug, Clone)]
pub struct BotConfig {
    pub name: String,
    pub role: String,
    pub token: String,
}

/// Garden creation config
#[derive(Debug, Clone)]
pub struct GardenConfig {
    pub name: String,
    pub telegram_group_id: String,
    pub bots: Vec<BotConfig>,
    /// (provider, auth_method_id, api_key)
    pub providers: Vec<(Arc<ProviderPlugin>, String, String)>,
}

/// Container status information retrieved via `docker inspect`.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct ContainerStatus {
    pub name: String,
    pub running: bool,
    pub status: String,        // "Up 2 hours", "Exited (0) 5 min ago", etc.
    pub healthy: Option<bool>, // None = no healthcheck defined
    pub started_at: Option<String>,
    pub image: String,
    #[allow(dead_code)]
    pub ports: Vec<String>,
}

// ── Config generation ────────────────────────────────────────────────────────

impl GardenConfig {
    /// Generate docker-compose.yml content
    pub fn generate_compose(&self) -> String {
        // Build bot env vars
        let mut bot_envs = String::new();
        for bot in self.bots.iter() {
            let key = format!("TELEGRAM_BOT_TOKEN_{}", bot.name.to_uppercase());
            bot_envs.push_str(&format!("      {}: \"${{{}}}\"\n", key, key));
        }

        // Build provider env vars (for backwards compatibility)
        let mut provider_envs = String::new();
        for (provider, _auth_method, _api_key) in &self.providers {
            let key = format!("{}_API_KEY", provider.id.to_uppercase());
            provider_envs.push_str(&format!("      {}: \"${{{}}}\"\n", key, key));
        }

        format!(
            r#"version: '3.8'

services:
  garden:
    container_name: {container_name}
    build:
      context: {context}
      dockerfile: docker/Dockerfile
      args:
        PI_VERSION: "${{PI_VERSION:-latest}}"
    restart: unless-stopped
    environment:
      # Telegram bot tokens
{bot_envs}
      # Telegram group configuration
      TELEGRAM_GROUP_ID: "{telegram_group_id}"
      TELEGRAM_INGRESS_BOT: "{ingress_bot}"
      # Provider API keys (for backwards compat)
{provider_envs}
      # Garden configuration
      GARDEN_WORKSPACE: /workspace
      RUST_LOG: info
      # Metrics (optional)
      METRICS_PORT: 8080
    volumes:
      - ./workspace:/workspace
      - ./pi-auth.json:/home/garden/.pi/agent/auth.json:ro
    networks:
      - garden-net
    security_opt:
      - no-new-privileges:true
    cap_drop:
      - ALL
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 30s

networks:
  garden-net:
    name: {network_name}
    driver: bridge
"#,
            container_name = format!("garden-{}", self.name),
            context = crate::garden::GardensRegistry::gardens_dir()
                .join(&self.name)
                .to_string_lossy(),
            bot_envs = bot_envs,
            telegram_group_id = self.telegram_group_id,
            ingress_bot = self
                .bots
                .first()
                .map(|b| b.name.as_str())
                .unwrap_or("ingress"),
            provider_envs = provider_envs,
            network_name = format!("garden-net-{}", self.name)
        )
    }

    /// Generate .env file content
    pub fn generate_env(&self) -> String {
        let mut lines = vec![
            "# ClawGarden Environment Configuration".to_string(),
            "# DO NOT COMMIT THIS FILE TO VERSION CONTROL".to_string(),
            "".to_string(),
        ];

        // Bot tokens
        lines.push("# Telegram Bot Tokens".to_string());
        for bot in &self.bots {
            let key = format!("TELEGRAM_BOT_TOKEN_{}", bot.name.to_uppercase());
            lines.push(format!("{}={}", key, bot.token));
        }
        lines.push("".to_string());

        // Provider keys
        lines.push("# AI Provider API Keys".to_string());
        for (provider, _auth_method, api_key) in &self.providers {
            let key = format!("{}_API_KEY", provider.id.to_uppercase());
            lines.push(format!("{}={}", key, api_key));
        }
        lines.push("".to_string());

        // Other config
        lines.push("# Configuration".to_string());
        lines.push(format!("TELEGRAM_GROUP_ID={}", self.telegram_group_id));
        lines.push("PI_VERSION=latest".to_string());
        lines.push("RUST_LOG=info".to_string());

        lines.join("\n")
    }

    /// Write docker-compose.yml and .env to garden directory
    pub fn write(&self) -> Result<(PathBuf, PathBuf)> {
        let registry = load_gardens()?;
        let garden_dir = registry.garden_dir(&self.name);
        let workspace_dir = registry.workspace_dir(&self.name);

        // Create directories
        std::fs::create_dir_all(&garden_dir).context("Failed to create garden directory")?;
        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")?;

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

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

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

        // Write registry.json
        let registry_path = workspace_dir.join("agents/registry.json");
        let registry_json = self.generate_registry_json();
        std::fs::write(&registry_path, 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((compose_path, env_path))
    }

    /// Generate pi auth.json content
    pub fn generate_auth_json(&self) -> String {
        use crate::providers::PiAuthJson;

        let provider_keys: Vec<(String, String)> = self
            .providers
            .iter()
            .map(|(p, _auth_method, key)| (p.id.clone(), key.clone()))
            .collect();

        let auth = PiAuthJson::new(&provider_keys);
        auth.to_json_string().unwrap_or_else(|_| "{}".to_string())
    }

    /// Generate registry.json content
    pub fn generate_registry_json(&self) -> String {
        let mut agents = vec![];

        for bot in &self.bots {
            let agent = serde_json::json!({
                "name": bot.name,
                "role": bot.role,
                "enabled": true,
                "priority": 50,
                "bot": {
                    "token_env": format!("TELEGRAM_BOT_TOKEN_{}", bot.name.to_uppercase())
                }
            });
            agents.push(agent);
        }

        let registry = serde_json::json!({
            "version": 1,
            "telegram": {
                "group_id": self.telegram_group_id,
                "ingress_bot": self.bots.first().map(|b| b.name.as_str()).unwrap_or("ingress")
            },
            "agents": agents
        });

        serde_json::to_string_pretty(&registry).unwrap()
    }
}

// ── Container lifecycle ──────────────────────────────────────────────────────

/// Start a garden
pub fn start_garden(name: &str) -> Result<()> {
    let registry = load_gardens()?;

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

    let compose_file = registry.compose_file(name);

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

    // Load .env and export variables for docker-compose
    let env_file = registry.env_file(name);
    load_env_file(&env_file)?;

    crate::ui::spinner(&format!("Starting garden '{}'...", name), 600);

    let result = std::process::Command::new(docker_compose_bin())
        .args(["-f", compose_file.to_str().unwrap(), "up", "-d"])
        .current_dir(registry.garden_dir(name))
        .status();

    match result {
        Ok(status) if status.success() => {
            println!();
            crate::ui::success(&format!("Garden '{}' is blooming!", name));
            println!("  Container: garden-{}", name);
            Ok(())
        }
        Ok(status) => {
            anyhow::bail!("Failed to start garden (exit code: {:?})", status.code());
        }
        Err(e) => {
            anyhow::bail!("Failed to execute docker-compose: {}", e);
        }
    }
}

/// Stop a garden
pub fn stop_garden(name: &str) -> Result<()> {
    let registry = load_gardens()?;

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

    let compose_file = registry.compose_file(name);

    if !compose_file.exists() {
        println!("Garden '{}' is not initialized.", name);
        return Ok(());
    }

    crate::ui::spinner(&format!("Stopping garden '{}'...", name), 400);

    let result = std::process::Command::new(docker_compose_bin())
        .args(["-f", compose_file.to_str().unwrap(), "down"])
        .current_dir(registry.garden_dir(name))
        .status();

    match result {
        Ok(status) if status.success() => {
            println!();
            crate::ui::success(&format!("Garden '{}' put to rest.", name));
            Ok(())
        }
        Ok(status) => {
            anyhow::bail!("Failed to stop garden (exit code: {:?})", status.code());
        }
        Err(e) => {
            anyhow::bail!("Failed to execute docker-compose: {}", e);
        }
    }
}

/// Restart a garden (down + up)
pub fn restart_garden(name: &str) -> Result<()> {
    crate::ui::spinner(&format!("Restarting garden '{}'...", name), 500);
    stop_garden_quiet(name)?;
    start_garden(name)
}

/// Get logs from a garden
pub fn garden_logs(name: &str, follow: bool, lines: usize) -> Result<std::process::ExitStatus> {
    let registry = load_gardens()?;

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

    let compose_file = registry.compose_file(name);

    if !compose_file.exists() {
        anyhow::bail!("Garden '{}' is not initialized", name);
    }

    let mut args = vec![
        "-f".to_string(),
        compose_file.to_string_lossy().to_string(),
        "logs".to_string(),
    ];

    if follow {
        args.push("--follow".to_string());
    }

    args.push(format!("--tail={}", lines));

    let result = std::process::Command::new(docker_compose_bin())
        .args(&args)
        .current_dir(registry.garden_dir(name))
        .status();

    Ok(result?)
}

/// Execute command in a garden
pub fn garden_exec(name: &str, command: &[String]) -> Result<std::process::ExitStatus> {
    let registry = load_gardens()?;

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

    let compose_file = registry.compose_file(name);

    if !compose_file.exists() {
        anyhow::bail!("Garden '{}' is not initialized", name);
    }

    let mut args = vec![
        "-f".to_string(),
        compose_file.to_string_lossy().to_string(),
        "exec".to_string(),
        "-T".to_string(),
        "garden".to_string(),
    ];
    args.extend(command.to_vec());

    let result = std::process::Command::new(docker_compose_bin())
        .args(&args)
        .current_dir(registry.garden_dir(name))
        .status();

    Ok(result?)
}

/// Open an interactive shell in the garden container
pub fn garden_shell(name: &str, shell: &str) -> Result<std::process::ExitStatus> {
    let registry = load_gardens()?;

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

    let compose_file = registry.compose_file(name);

    if !compose_file.exists() {
        anyhow::bail!("Garden '{}' is not initialized", name);
    }

    let args = vec![
        "-f".to_string(),
        compose_file.to_string_lossy().to_string(),
        "exec".to_string(),
        "garden".to_string(),
        shell.to_string(),
    ];

    let result = std::process::Command::new(docker_compose_bin())
        .args(&args)
        .current_dir(registry.garden_dir(name))
        .status();

    Ok(result?)
}

// ── Container inspection ─────────────────────────────────────────────────────

/// Inspect a running container and return its status.
pub fn inspect_container(name: &str) -> Result<ContainerStatus> {
    let container_name = format!("garden-{}", name);

    let output = std::process::Command::new("docker")
        .args([
            "inspect",
            "--format",
            "{{.State.Running}}|{{.State.Status}}|{{.State.StartedAt}}|{{.Config.Image}}|{{range $p, $conf := .NetworkSettings.Ports}}{{if $conf}}{{$p}} {{end}}{{end}}",
            &container_name,
        ])
        .output();

    match output {
        Ok(out) if out.status.success() => {
            let stdout = String::from_utf8_lossy(&out.stdout);
            let parts: Vec<&str> = stdout.trim().split('|').collect();

            let running = parts.first().map(|s| *s == "true").unwrap_or(false);
            let status_raw = parts.get(1).map(|s| *s).unwrap_or("unknown");
            let started_at = parts.get(2).map(|s| s.to_string());
            let image = parts.get(3).map(|s| s.to_string()).unwrap_or_default();
            let ports_str = parts.get(4).map(|s| s.to_string()).unwrap_or_default();
            let ports: Vec<String> = if ports_str.is_empty() {
                vec![]
            } else {
                ports_str
                    .split_whitespace()
                    .map(|s| s.to_string())
                    .collect()
            };

            // Derive human-readable status
            let status = if running {
                format!(
                    "Up{}",
                    started_at
                        .as_ref()
                        .map(|t| format!(" since {}", t))
                        .unwrap_or_default()
                )
            } else {
                status_raw.to_string()
            };

            // Check health
            let healthy = check_health(&container_name);

            Ok(ContainerStatus {
                name: container_name,
                running,
                status,
                healthy,
                started_at,
                image,
                ports,
            })
        }
        Ok(_) => {
            // Container doesn't exist
            Ok(ContainerStatus {
                name: container_name,
                running: false,
                status: "not created".to_string(),
                healthy: None,
                started_at: None,
                image: String::new(),
                ports: vec![],
            })
        }
        Err(e) => {
            anyhow::bail!("Failed to inspect container: {}", e);
        }
    }
}

/// Check health status from docker healthcheck.
fn check_health(container_name: &str) -> Option<bool> {
    let output = std::process::Command::new("docker")
        .args([
            "inspect",
            "--format",
            "{{.State.Health.Status}}",
            container_name,
        ])
        .output();

    match output {
        Ok(out) if out.status.success() => {
            let stdout = String::from_utf8_lossy(&out.stdout);
            match stdout.trim() {
                "healthy" => Some(true),
                "unhealthy" => Some(false),
                "starting" => None, // still starting up
                _ => None,
            }
        }
        _ => None, // No healthcheck defined or container not running
    }
}

/// Get container resource usage (CPU %, memory) via `docker stats --no-stream`.
pub fn container_stats(name: &str) -> Option<String> {
    let container_name = format!("garden-{}", name);
    let output = std::process::Command::new("docker")
        .args([
            "stats",
            "--no-stream",
            "--format",
            "{{.CPUPerc}} CPU · {{.MemUsage}}",
            &container_name,
        ])
        .output()
        .ok()?;

    if output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        let line = stdout.lines().nth(1).unwrap_or("").trim();
        if !line.is_empty() {
            return Some(line.to_string());
        }
    }
    None
}

// ── Internal helpers ─────────────────────────────────────────────────────────

/// Detect the correct docker-compose binary (cached after first call).
/// Prefers V2 plugin (`docker compose`) over standalone (`docker-compose`).
pub fn docker_compose_bin() -> &'static str {
    use once_cell::sync::Lazy;
    static BIN: Lazy<&str> = Lazy::new(|| {
        // Try V2 plugin first: `docker compose version`
        if let Ok(out) = std::process::Command::new("docker")
            .args(["compose", "version"])
            .output()
        {
            if out.status.success() {
                return "docker";
            }
        }
        // Fall back to standalone binary
        "docker-compose"
    });
    *BIN
}

/// Build compose args with the correct subcommand prefix.
/// V2: ["compose", "-f", file, ...]
/// V1: ["-f", file, ...]
fn compose_args(file: &str, subcmd: &[&str]) -> Vec<String> {
    let bin = docker_compose_bin();
    let mut args = Vec::new();
    if bin == "docker" {
        args.push("compose".to_string());
    }
    args.push("-f".to_string());
    args.push(file.to_string());
    for s in subcmd {
        args.push(s.to_string());
    }
    args
}

/// Stop a garden without printing success messages (used by restart).
fn stop_garden_quiet(name: &str) -> Result<()> {
    let registry = load_gardens()?;
    if !registry.exists(name) {
        return Ok(());
    }
    let compose_file = registry.compose_file(name);
    if !compose_file.exists() {
        return Ok(());
    }
    let _ = std::process::Command::new(docker_compose_bin())
        .args(compose_args(compose_file.to_str().unwrap_or(""), &["down"]))
        .current_dir(registry.garden_dir(name))
        .output();
    Ok(())
}

/// Load .env file and set environment variables
fn load_env_file(path: &PathBuf) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }

    let content = std::fs::read_to_string(path).context("Failed to read .env file")?;

    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        if let Some((key, value)) = line.split_once('=') {
            let key = key.trim();
            let value = value.trim();
            std::env::set_var(key, value);
        }
    }

    Ok(())
}