muthr 0.1.10

A zero-trust orchestrator that automates llama.cpp and Lima to safely run local AI agents in isolated VMs.
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
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use tempfile::NamedTempFile;
use tokio::fs;
use tokio::process::Command;

use crate::engine;
use crate::model;
use crate::preset;
use crate::ui;

pub fn resolve_workspace_context() -> Result<(String, PathBuf, PathBuf), color_eyre::Report> {
    let current_dir = std::env::current_dir()?;
    let canonical_current = std::fs::canonicalize(&current_dir)?;

    let home = std::env::var("HOME")?;

    let raw_workspace_root = std::env::var("OPENCODE_WORKSPACE_ROOT")
        .unwrap_or_else(|_| format!("{}/src/projects", home));
    let canonical_workspace = std::fs::canonicalize(Path::new(&raw_workspace_root))
        .unwrap_or_else(|_| PathBuf::from(&raw_workspace_root));

    let dotfiles_path = PathBuf::from(format!("{}/dotfiles", home));
    let canonical_dotfiles =
        std::fs::canonicalize(&dotfiles_path).unwrap_or_else(|_| dotfiles_path.clone());

    if canonical_current.starts_with(&canonical_dotfiles) {
        Ok(("dotfiles-sandbox".to_string(), dotfiles_path, current_dir))
    } else if canonical_current.starts_with(&canonical_workspace) {
        if canonical_current == canonical_workspace {
            return Err(color_eyre::eyre::eyre!(
                "Navigate into a project directory first."
            ));
        }
        let relative = canonical_current.strip_prefix(&canonical_workspace)?;
        let project_folder = relative
            .components()
            .next()
            .ok_or_else(|| color_eyre::eyre::eyre!("Invalid workspace path"))?
            .as_os_str()
            .to_str()
            .ok_or_else(|| color_eyre::eyre::eyre!("Invalid project name"))?
            .to_string();

        let sanitized: String = project_folder
            .chars()
            .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
            .collect();

        if sanitized.is_empty() {
            return Err(color_eyre::eyre::eyre!("Sanitized project name is empty"));
        }

        let vm_name = format!("{}-sandbox", sanitized);
        let mount_point = PathBuf::from(&raw_workspace_root).join(&project_folder);
        Ok((vm_name, mount_point, current_dir))
    } else {
        Err(color_eyre::eyre::eyre!(
            "Sandbox tasks are restricted to workspace roots or dotfile directories."
        ))
    }
}

pub async fn vm_exists(vm_name: &str) -> bool {
    let output = Command::new("limactl")
        .args(["ls", "-q"])
        .output()
        .await
        .ok()
        .filter(|o| o.status.success());

    if let Some(out) = output {
        let stdout = String::from_utf8_lossy(&out.stdout);
        for line in stdout.lines() {
            if line == vm_name {
                return true;
            }
        }
    }
    false
}

pub async fn vm_is_running(vm_name: &str) -> bool {
    let output = Command::new("limactl")
        .args(["ls", "-f", "'{{.Status}}'", vm_name])
        .output()
        .await
        .ok();

    if let Some(out) = output {
        if out.status.success() {
            let status = String::from_utf8_lossy(&out.stdout).trim().to_string();
            return status == "Running";
        }
    }
    false
}

pub async fn vm_stop(vm_name: &str) -> Result<(), color_eyre::Report> {
    println!(
        "\n[PROC] Sandbox environment exited. Auto-stopping VM ({})...",
        vm_name
    );

    let output = Command::new("limactl")
        .arg("stop")
        .arg(vm_name)
        .output()
        .await
        .ok();

    match output {
        Some(out) if out.status.success() => {
            println!("[ OK ] VM stopped cleanly. System memory reclaimed.");
        }
        _ => {
            eprintln!("[WARN] ACPI stop sequence sent.");
        }
    }
    Ok(())
}

async fn vm_create(
    vm_name: &str,
    workspace_root: &Path,
    mount_point: &Path,
) -> Result<(), color_eyre::Report> {
    let home = std::env::var("HOME")?;
    let template_path = PathBuf::from(&home).join(".config/muthr/lima/templates/sandbox.yaml");

    if !template_path.exists() {
        return Err(color_eyre::eyre::eyre!(
            "Template not found: {:?}",
            template_path
        ));
    }

    let content = fs::read_to_string(&template_path).await?;
    let expanded = content
        .replace(
            "__WORKSPACE_ROOT__",
            workspace_root.to_str().unwrap_or_default(),
        )
        .replace("__MOUNT_POINT__", mount_point.to_str().unwrap_or_default());

    println!(
        "[PROC] VM '{}' not found. Creating and starting...",
        vm_name
    );
    let mut tmp_yaml = NamedTempFile::new()?;
    tmp_yaml.write_all(expanded.as_bytes())?;

    let create_status = Command::new("limactl")
        .args(["create", "--name", vm_name])
        .arg(tmp_yaml.path())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()
        .await?;

    if !create_status.success() {
        return Err(color_eyre::eyre::eyre!("Failed to create VM: {}", vm_name));
    }

    let start_status = Command::new("limactl")
        .arg("start")
        .arg(vm_name)
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()
        .await?;

    if !start_status.success() {
        return Err(color_eyre::eyre::eyre!("Failed to start VM: {}", vm_name));
    }
    Ok(())
}

async fn vm_start(vm_name: &str) -> Result<(), color_eyre::Report> {
    println!("[PROC] Starting sandbox VM ({})...", vm_name);
    let status = Command::new("limactl")
        .arg("start")
        .arg(vm_name)
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()
        .await?;

    if !status.success() {
        return Err(color_eyre::eyre::eyre!("Failed to start VM: {}", vm_name));
    }
    Ok(())
}

async fn is_vm_provisioned(vm_name: &str) -> bool {
    let output = Command::new("limactl")
        .args(["shell", "--workdir", "/tmp", vm_name])
        .arg("bash")
        .arg("-c")
        .arg("test -f /var/log/opencode_provision.lock")
        .output()
        .await
        .ok();

    match output {
        Some(out) => out.status.success(),
        None => false,
    }
}

async fn run_provision(vm_name: &str, script_name: &str) -> Result<(), color_eyre::Report> {
    let home = std::env::var("HOME")?;
    let host_script =
        PathBuf::from(&home).join(format!(".config/muthr/lima/provision/{}.sh", script_name));

    if !host_script.exists() {
        return Err(color_eyre::eyre::eyre!(
            "Provision script not found: {:?}",
            host_script
        ));
    }

    println!("[PROC] Running provision: {}...", script_name);

    let script_str = host_script
        .to_str()
        .ok_or_else(|| color_eyre::eyre::eyre!("Invalid UTF-8 in provision script path"))?;

    let status = Command::new("bash")
        .arg(script_str)
        .arg(vm_name)
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()
        .await?;

    if !status.success() {
        return Err(color_eyre::eyre::eyre!("Provision failed: {}", script_name));
    }

    println!("[ OK ] Provision complete: {}", script_name);
    Ok(())
}

async fn handle_provisioning(vm_name: &str) -> Result<(), color_eyre::Report> {
    if is_vm_provisioned(vm_name).await {
        return Ok(());
    }

    let options = vec![
        "Base only -- shell access, no extra installs",
        "Base + opencode -- MCP servers + opencode-ai CLI",
    ];

    let is_tty = std::io::stdout().is_terminal();

    let idx = if is_tty {
        match ui::select_list(&options) {
            Some(i) => i,
            None => {
                println!("[INFO] Skipping provision. Base VM only.");
                return Ok(());
            }
        }
    } else {
        println!("[INFO] No TTY detected. Defaulting to: {}", options[1]);
        1
    };

    if idx == 1 {
        run_provision(vm_name, "opencode").await?;
    }
    Ok(())
}

pub async fn up(port: u16) -> Result<(), color_eyre::Report> {
    let (vm_name, mount_point, workdir) = resolve_workspace_context()?;

    println!("[INFO] Target Virtual Environment Context: {}", vm_name);

    if !engine::verify_health(port).await {
        return Err(color_eyre::eyre::eyre!(
            "Inference pipeline unreachable at 127.0.0.1:{}. Run 'muthr serve' first.",
            port
        ));
    }

    let home = std::env::var("HOME")?;
    let presets = preset::list_presets()?;

    let workspace_root = if vm_name == "dotfiles-sandbox" {
        PathBuf::from(&home).join("dotfiles")
    } else {
        PathBuf::from(&home).join("src/projects")
    };

    if !vm_exists(&vm_name).await {
        vm_create(&vm_name, &workspace_root, &mount_point).await?;
    } else if !vm_is_running(&vm_name).await {
        vm_start(&vm_name).await?;
    } else {
        println!("[ OK ] VM already running");
    }

    handle_provisioning(&vm_name).await?;

    let loaded_model = model::poll_loaded_model("127.0.0.1", port, 20, 1.5).await?;
    println!("[INFO] Model detected: {}", loaded_model);

    let ctx_window = model::get_ctx_window("127.0.0.1", port).await?;
    println!("[INFO] Context window: {}", ctx_window);

    let runtime_config = {
        let active_profile_path = PathBuf::from(&home).join(".cache/muthr/opencode-profile");
        let preset_to_use = if active_profile_path.exists() {
            let content = fs::read_to_string(&active_profile_path).await?;
            let mut preset_name = String::new();
            for line in content.lines() {
                if line.starts_with("export LLAMA_ARG_MODELS_PRESET=") {
                    if let Some(start) = line.find('"') {
                        if let Some(end) = line[start + 1..].find('"') {
                            preset_name = line[start + 1..start + 1 + end].to_string();
                        }
                    }
                }
            }
            if !preset_name.is_empty() {
                presets
                    .iter()
                    .find(|p| p.path.to_string_lossy() == preset_name)
            } else {
                None
            }
        } else {
            None
        };

        let selected_preset = preset_to_use.or(presets.first());
        match selected_preset {
            Some(p) => crate::config::generate_runtime_config(p, port, &mount_point)?,
            None => {
                return Err(color_eyre::eyre::eyre!(
                    "No presets available for config generation"
                ))
            }
        }
    };

    println!("[PROC] Injecting runtime configuration mapping...");
    let cp_status = Command::new("limactl")
        .args([
            "cp",
            runtime_config.to_str().unwrap(),
            &format!("{}:/tmp/opencode-config.json", vm_name),
        ])
        .status()
        .await?;

    if !cp_status.success() {
        return Err(color_eyre::eyre::eyre!(
            "Failed to sync runtime configuration profile into guest instance container."
        ));
    }

    println!("[PROC] Attaching shell interaction channels to container layer...");

    let status = Command::new("limactl")
        .args([
            "shell",
            "--workdir",
            workdir.to_str().unwrap_or("/tmp"),
            &vm_name,
            "--",
            "env",
            "PATH=/home/user.guest/.opencode/bin:/home/user.guest/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
            "OPENCODE_CONFIG=/tmp/opencode-config.json",
            "opencode",
        ])
        .stdin(Stdio::inherit())
        .status()
        .await?;

    vm_stop(&vm_name).await?;

    if !status.success() {
        return Err(color_eyre::eyre::eyre!(
            "opencode session exited with error"
        ));
    }
    Ok(())
}

pub async fn down() -> Result<(), color_eyre::Report> {
    let (vm_name, _, _) = resolve_workspace_context()?;

    if !vm_exists(&vm_name).await {
        println!("[WARN] VM '{}' does not exist", vm_name);
        return Ok(());
    }

    vm_stop(&vm_name).await?;
    Ok(())
}

pub async fn list() -> Result<(), color_eyre::Report> {
    let sandbox_suffix = "-sandbox";

    println!("[INFO] Sandbox VMs:");
    println!("===============================================================================");

    let output = Command::new("limactl")
        .args(["ls", "-q"])
        .output()
        .await
        .ok();

    let vms: Vec<String> = match output {
        Some(out) if out.status.success() => String::from_utf8_lossy(&out.stdout)
            .lines()
            .filter(|v| v.ends_with(sandbox_suffix))
            .map(|v| v.to_string())
            .collect(),
        _ => Vec::new(),
    };

    if vms.is_empty() {
        println!("[WARN] No sandbox VMs found");
        return Ok(());
    }

    let is_tty = std::io::stdout().is_terminal();

    if !is_tty {
        for vm in &vms {
            let status = Command::new("limactl")
                .args(["ls", "-f", "'{{.Status}}'", vm])
                .output()
                .await
                .ok()
                .and_then(|out| {
                    String::from_utf8_lossy(&out.stdout)
                        .trim()
                        .to_string()
                        .split_whitespace()
                        .next()
                        .map(|s| s.to_string())
                })
                .unwrap_or_else(|| "Unknown".to_string());

            let project = vm.strip_suffix(sandbox_suffix).unwrap_or(vm);
            let mount_point = if project == "dotfiles" {
                "/sandbox-dotfiles"
            } else {
                &format!("/sandbox-{}", project)
            };

            println!("  {:<30} {}  Mount: {}", vm, status, mount_point);
        }
    } else {
        let mut rows: Vec<Vec<String>> = Vec::new();
        for vm in &vms {
            let status = Command::new("limactl")
                .args(["ls", "-f", "'{{.Status}}'", vm])
                .output()
                .await
                .ok()
                .and_then(|out| {
                    String::from_utf8_lossy(&out.stdout)
                        .trim()
                        .to_string()
                        .split_whitespace()
                        .next()
                        .map(|s| s.to_string())
                })
                .unwrap_or_else(|| "Unknown".to_string());

            let project = vm.strip_suffix(sandbox_suffix).unwrap_or(vm);
            let mount_point = if project == "dotfiles" {
                "/sandbox-dotfiles"
            } else {
                &format!("/sandbox-{}", project)
            };

            rows.push(vec![vm.clone(), status, mount_point.to_string()]);
        }

        let headers = vec!["VM Name", "Status", "Mount Point"];
        ui::select_table(&headers, rows);
    }

    println!("===============================================================================");
    Ok(())
}