room-sandbox 1.2.0

Dockerized multi-agent sandbox for room
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
use std::fmt;

use anyhow::{Context, Result};
use clap::Args;
use inquire::{Confirm, MultiSelect, Select, Text};

use crate::config::{
    self, AgentDef, AgentRole, AuthConfig, AuthMethod, Config, EnvironmentConfig, Language,
    ProjectConfig, RoomConfig, Utility,
};
use crate::docker;
use crate::state::State;

#[derive(Clone)]
struct LangOption {
    lang: Language,
    label: &'static str,
}

impl fmt::Display for LangOption {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.label)
    }
}

#[derive(Clone)]
struct UtilityOption {
    utility: Utility,
    label: &'static str,
}

impl fmt::Display for UtilityOption {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.label)
    }
}

#[derive(Args)]
pub struct InitArgs {
    /// Git repo URL or org/repo shorthand
    #[arg(long)]
    repo: Option<String>,

    /// Comma-separated agent names
    #[arg(long, value_delimiter = ',')]
    agents: Option<Vec<String>>,

    /// Comma-separated languages (rust, node, python)
    #[arg(long, value_delimiter = ',')]
    languages: Option<Vec<String>>,

    /// Comma-separated utilities (glow, playwright)
    #[arg(long, value_delimiter = ',')]
    utilities: Option<Vec<String>>,

    /// Auth method (gh-cli, pat, ssh)
    #[arg(long)]
    auth: Option<String>,

    /// Default room name
    #[arg(long)]
    room: Option<String>,
}

pub fn run(args: InitArgs) -> Result<()> {
    let detected_repo = config::validate_init_dir()?;
    let is_interactive = args.repo.is_none();

    if let Some(ref remote) = detected_repo {
        eprintln!("Detected git repo: {remote}");
    }

    let config = if is_interactive {
        run_wizard(detected_repo)?
    } else {
        build_from_args(args, detected_repo)?
    };

    eprintln!("\n--- Writing sandbox.toml ---");
    config.save()?;

    eprintln!("--- Setting up .room-sandbox/ ---");
    setup_sandbox_dir(&config)?;

    eprintln!("--- Writing Docker assets ---");
    docker::write_assets(&config)?;

    eprintln!("--- Cloning agent workspaces ---");
    std::fs::create_dir_all(config::workspaces_dir())?;
    for agent in &config.agents {
        docker::clone_workspace(&config.project.repo, &agent.name)?;
    }

    eprintln!("\n--- Building container (this may take a while on first run) ---");
    docker::build()?;

    eprintln!("--- Starting container ---");
    docker::up()?;

    // Inject role-based instructions
    eprintln!("--- Writing agent instructions ---");
    docker::inject_agent_instructions(&config)?;

    State::save_from_config(&config)?;

    eprintln!("\n=== Sandbox ready ===");
    eprintln!("  Agents: {}", config.agent_names_joined());
    eprintln!("  Room:   {}", config.room.default);
    eprintln!();
    eprintln!("\x1b[33m  !! Claude Code authentication required !!\x1b[0m");
    eprintln!("  Agents need to authenticate with Claude before they can work.");
    eprintln!("  Run this once — the session is shared across all agents:");
    eprintln!();
    eprintln!("    room-sandbox claude <agent-name>");
    eprintln!("    > type /login and follow the browser prompt");
    eprintln!();
    eprintln!("Next steps:");
    eprintln!("  room-sandbox agent start --all     Start all agents");
    eprintln!("  room-sandbox tui                   Open the room TUI");
    eprintln!("  room-sandbox shell <name>          Shell into a workspace");

    Ok(())
}

fn run_wizard(detected_repo: Option<String>) -> Result<Config> {
    eprintln!("\n=== room-sandbox init ===\n");

    // 1. Repo
    let repo_input: String = if let Some(ref detected) = detected_repo {
        let use_detected = Confirm::new(&format!("Use detected repo ({detected})?"))
            .with_default(true)
            .prompt()?;
        if use_detected {
            detected.clone()
        } else {
            Text::new("Git repo (org/repo, SSH, or HTTPS URL):").prompt()?
        }
    } else {
        Text::new("Git repo (org/repo, SSH, or HTTPS URL):").prompt()?
    };

    // 2. Auto-detect languages (shallow clone if needed)
    let detected_languages = if detected_repo.is_some() {
        config::detect_languages(&std::env::current_dir()?)
    } else {
        detect_from_shallow_clone(&repo_input)
    };

    // 3. Languages
    eprintln!();
    let all_languages = vec![
        LangOption {
            lang: Language::Rust,
            label: "rust",
        },
        LangOption {
            lang: Language::Node,
            label: "node",
        },
        LangOption {
            lang: Language::Python,
            label: "python",
        },
    ];
    let defaults: Vec<usize> = all_languages
        .iter()
        .enumerate()
        .filter(|(_, l)| detected_languages.contains(&l.lang))
        .map(|(i, _)| i)
        .collect();

    let lang_selections = MultiSelect::new("Languages:", all_languages.clone())
        .with_default(&defaults)
        .prompt()?;

    let languages: Vec<Language> = lang_selections.into_iter().map(|l| l.lang).collect();

    // 4. Utilities
    eprintln!();
    let all_utilities = vec![
        UtilityOption {
            utility: Utility::Glow,
            label: "glow (markdown reader)",
        },
        UtilityOption {
            utility: Utility::Playwright,
            label: "playwright (browser automation)",
        },
        UtilityOption {
            utility: Utility::Just,
            label: "just (command runner)",
        },
        UtilityOption {
            utility: Utility::Mise,
            label: "mise (tool version manager)",
        },
        UtilityOption {
            utility: Utility::Proto,
            label: "proto (toolchain manager)",
        },
        UtilityOption {
            utility: Utility::Pulumi,
            label: "pulumi (infrastructure as code)",
        },
        UtilityOption {
            utility: Utility::Ansible,
            label: "ansible (automation, requires python)",
        },
        UtilityOption {
            utility: Utility::AwsCli,
            label: "aws-cli (AWS command line)",
        },
        UtilityOption {
            utility: Utility::Terraform,
            label: "terraform (infrastructure as code)",
        },
        UtilityOption {
            utility: Utility::Docker,
            label: "docker (Docker-in-Docker CLI)",
        },
        UtilityOption {
            utility: Utility::Kubectl,
            label: "kubectl (Kubernetes CLI)",
        },
        UtilityOption {
            utility: Utility::Yq,
            label: "yq (YAML processor)",
        },
    ];

    let utility_selections = MultiSelect::new("Utilities:", all_utilities.clone()).prompt()?;

    let utilities: Vec<Utility> = utility_selections.into_iter().map(|u| u.utility).collect();

    // 5. Agents
    eprintln!();
    let agents_input = Text::new("Agent names (comma-separated):")
        .with_default("r2d2, c3po, wall-e, qa, manager")
        .prompt()?;
    let agent_name_list: Vec<String> = agents_input
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();

    for name in &agent_name_list {
        config::validate_agent_name(name)?;
    }

    let roles = vec!["coder", "reviewer", "manager"];
    let mut agent_defs: Vec<AgentDef> = Vec::new();
    for name in &agent_name_list {
        let role_selection = Select::new(&format!("Role for '{name}':"), roles.clone()).prompt()?;
        let role = match role_selection {
            "reviewer" => AgentRole::Reviewer,
            "manager" => AgentRole::Manager,
            _ => AgentRole::Coder,
        };
        agent_defs.push(AgentDef {
            name: name.clone(),
            role,
        });
    }

    // 6. Auth
    eprintln!();
    let gh_accounts = detect_gh_accounts();
    let auth_method;
    let mut selected_gh_account: Option<String> = None;

    if gh_accounts.is_empty() {
        let auth_options = vec!["PAT (provide a token)", "SSH only"];
        eprintln!("No gh CLI accounts detected.");
        let selection = Select::new("Auth method:", auth_options).prompt()?;
        auth_method = match selection {
            "PAT (provide a token)" => AuthMethod::Pat,
            _ => AuthMethod::Ssh,
        };
    } else {
        let mut auth_options: Vec<String> = gh_accounts
            .iter()
            .map(|a| {
                let marker = if a.active { " (active)" } else { "" };
                format!("gh-cli: {}{marker}", a.username)
            })
            .collect();
        auth_options.push("PAT (provide a token)".to_string());
        auth_options.push("SSH only".to_string());

        let selection = Select::new("Auth method:", auth_options.clone()).prompt()?;

        let selected_idx = auth_options
            .iter()
            .position(|o| *o == selection)
            .unwrap_or(0);
        if selected_idx < gh_accounts.len() {
            auth_method = AuthMethod::GhCli;
            selected_gh_account = Some(gh_accounts[selected_idx].username.clone());
        } else if selection == "PAT (provide a token)" {
            auth_method = AuthMethod::Pat;
        } else {
            auth_method = AuthMethod::Ssh;
        }
    };

    // 7. SSH mount
    eprintln!();
    let mount_ssh = Confirm::new("Mount ~/.ssh into container?")
        .with_default(auth_method == AuthMethod::Ssh)
        .prompt()?;

    // 8. Room name
    eprintln!();
    let room_name = Text::new("Default room name:")
        .with_default("dev")
        .prompt()?;

    // Normalize repo URL now that we know auth method
    let repo = config::normalize_repo_url(&repo_input, &auth_method);
    let container_name = config::default_container_name()?;
    // Stash the selected gh account for .env generation
    let gh_account_for_env = selected_gh_account;

    Ok(Config {
        project: ProjectConfig {
            repo,
            container_name,
        },
        agents: agent_defs,
        room: RoomConfig { default: room_name },
        auth: AuthConfig {
            method: auth_method,
            mount_ssh,
            gh_account: gh_account_for_env,
        },
        environment: EnvironmentConfig {
            languages,
            utilities,
        },
    })
}

fn build_from_args(args: InitArgs, detected_repo: Option<String>) -> Result<Config> {
    let auth_method = match args.auth.as_deref() {
        Some("pat") => AuthMethod::Pat,
        Some("ssh") => AuthMethod::Ssh,
        _ => AuthMethod::GhCli,
    };

    let repo_input = args
        .repo
        .or(detected_repo)
        .context("--repo is required when not in a git repo")?;
    let repo = config::normalize_repo_url(&repo_input, &auth_method);

    let agent_defs: Vec<AgentDef> = args
        .agents
        .unwrap_or_else(|| {
            vec![
                "r2d2".into(),
                "c3po".into(),
                "wall-e".into(),
                "qa".into(),
                "manager".into(),
            ]
        })
        .into_iter()
        .map(|name| AgentDef {
            name,
            role: AgentRole::default(),
        })
        .collect();

    let languages = args
        .languages
        .map(|langs| {
            langs
                .into_iter()
                .filter_map(|l| match l.as_str() {
                    "rust" => Some(Language::Rust),
                    "node" => Some(Language::Node),
                    "python" => Some(Language::Python),
                    _ => None,
                })
                .collect()
        })
        .unwrap_or_default();

    let utilities = args
        .utilities
        .map(|us| {
            us.into_iter()
                .filter_map(|u| match u.as_str() {
                    "glow" => Some(Utility::Glow),
                    "playwright" => Some(Utility::Playwright),
                    "just" => Some(Utility::Just),
                    "mise" => Some(Utility::Mise),
                    "proto" => Some(Utility::Proto),
                    "pulumi" => Some(Utility::Pulumi),
                    "ansible" => Some(Utility::Ansible),
                    "aws-cli" | "aws" => Some(Utility::AwsCli),
                    "terraform" => Some(Utility::Terraform),
                    "docker" => Some(Utility::Docker),
                    "kubectl" => Some(Utility::Kubectl),
                    "yq" => Some(Utility::Yq),
                    _ => None,
                })
                .collect()
        })
        .unwrap_or_default();

    let container_name = config::default_container_name()?;

    Ok(Config {
        project: ProjectConfig {
            repo,
            container_name,
        },
        agents: agent_defs,
        room: RoomConfig {
            default: args.room.unwrap_or_else(|| "dev".to_string()),
        },
        auth: AuthConfig {
            method: auth_method,
            mount_ssh: auth_method == AuthMethod::Ssh,
            gh_account: None,
        },
        environment: EnvironmentConfig {
            languages,
            utilities,
        },
    })
}

fn setup_sandbox_dir(config: &Config) -> Result<()> {
    let dir = config::sandbox_dir();
    std::fs::create_dir_all(&dir)?;

    // Write .env
    let env_content = generate_env(config)?;
    std::fs::write(dir.join(".env"), env_content)?;

    // Add .room-sandbox/ to .gitignore if not already there
    let gitignore_path = std::path::PathBuf::from(".gitignore");
    let gitignore_entry = ".room-sandbox/";
    if gitignore_path.exists() {
        let content = std::fs::read_to_string(&gitignore_path)?;
        if !content.lines().any(|l| l.trim() == gitignore_entry) {
            std::fs::write(&gitignore_path, format!("{content}\n{gitignore_entry}\n"))?;
        }
    } else {
        std::fs::write(&gitignore_path, format!("{gitignore_entry}\n"))?;
    }

    Ok(())
}

fn generate_env(config: &Config) -> Result<String> {
    let mut lines = vec![
        "# === Required ===".to_string(),
        String::new(),
        "# Anthropic API key for Claude Code".to_string(),
        "ANTHROPIC_API_KEY=".to_string(),
    ];

    match config.auth.method {
        AuthMethod::GhCli => {
            let mut cmd = std::process::Command::new("gh");
            cmd.args(["auth", "token"]);
            if let Some(ref account) = config.auth.gh_account {
                cmd.args(["-u", account]);
            }
            let token = cmd
                .output()
                .ok()
                .and_then(|o| {
                    if o.status.success() {
                        Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
                    } else {
                        None
                    }
                })
                .unwrap_or_default();
            let account_label = config.auth.gh_account.as_deref().unwrap_or("default");
            lines.push(String::new());
            lines.push(format!(
                "# GitHub token (from gh CLI, account: {account_label})"
            ));
            lines.push(format!("GH_TOKEN={token}"));
        }
        AuthMethod::Pat => {
            lines.push(String::new());
            lines.push("# GitHub personal access token".to_string());
            lines.push("GH_TOKEN=".to_string());
        }
        AuthMethod::Ssh => {}
    }

    lines.push(String::new());
    lines.push("# === Optional ===".to_string());
    lines.push(String::new());
    lines.push("# App .env to distribute to each workspace".to_string());
    lines.push("APP_ENV=".to_string());

    Ok(lines.join("\n"))
}

struct GhAccount {
    username: String,
    active: bool,
}

fn detect_gh_accounts() -> Vec<GhAccount> {
    let output = match std::process::Command::new("gh")
        .args(["auth", "status"])
        .output()
    {
        Ok(o) => o,
        Err(_) => return Vec::new(),
    };

    // gh auth status may output to stdout or stderr depending on version
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let text = if stdout.contains("Logged in") {
        stdout
    } else {
        stderr
    };

    let mut accounts = Vec::new();

    for line in text.lines() {
        let trimmed = line.trim();
        // Lines like: "✓ Logged in to github.com account knoxio (keyring)"
        if trimmed.contains("Logged in")
            && trimmed.contains("account")
            && let Some(after_account) = trimmed.split("account ").nth(1)
        {
            let username = after_account
                .split_whitespace()
                .next()
                .unwrap_or("")
                .to_string();
            if !username.is_empty() {
                accounts.push(GhAccount {
                    username,
                    active: false,
                });
            }
        }
        // Lines like: "- Active account: true"
        if trimmed.contains("Active account: true")
            && let Some(last) = accounts.last_mut()
        {
            last.active = true;
        }
    }

    accounts
}

fn detect_from_shallow_clone(repo_input: &str) -> Vec<Language> {
    let temp = std::env::temp_dir().join("room-sandbox-detect");
    let _ = std::fs::remove_dir_all(&temp);

    // Try SSH first, then HTTPS for short form
    let urls_to_try = if repo_input.starts_with("git@") || repo_input.starts_with("http") {
        vec![repo_input.to_string()]
    } else {
        vec![
            format!(
                "https://github.com/{}.git",
                repo_input.trim_end_matches(".git")
            ),
            format!("git@github.com:{}.git", repo_input.trim_end_matches(".git")),
        ]
    };

    for url in &urls_to_try {
        let result = std::process::Command::new("git")
            .args(["clone", "--depth", "1", url])
            .arg(&temp)
            .output();

        if let Ok(output) = result
            && output.status.success()
        {
            let langs = config::detect_languages(&temp);
            let _ = std::fs::remove_dir_all(&temp);
            return langs;
        }
    }

    let _ = std::fs::remove_dir_all(&temp);
    Vec::new()
}