mino 1.6.0

Secure AI agent sandbox using rootless containers
Documentation
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
//! Layer resolution
//!
//! Resolves layer names to their manifests and install scripts by searching:
//! 1. Project-local: `{project_dir}/.mino/layers/{name}/`
//! 2. User-global: `~/.config/mino/layers/{name}/`
//! 3. Built-in: compiled into the binary via `include_str!`

use crate::error::{MinoError, MinoResult};
use crate::layer::manifest::LayerManifest;
use std::path::{Path, PathBuf};

// Built-in layers embedded at compile time
const BUILTIN_RUST_MANIFEST: &str = include_str!("../../images/rust/layer.toml");
const BUILTIN_RUST_INSTALL: &str = include_str!("../../images/rust/install.sh");
const BUILTIN_TS_MANIFEST: &str = include_str!("../../images/typescript/layer.toml");
const BUILTIN_TS_INSTALL: &str = include_str!("../../images/typescript/install.sh");
const BUILTIN_PYTHON_MANIFEST: &str = include_str!("../../images/python/layer.toml");
const BUILTIN_PYTHON_INSTALL: &str = include_str!("../../images/python/install.sh");

/// A fully resolved layer ready for composition
#[derive(Debug)]
pub struct ResolvedLayer {
    /// Parsed manifest
    pub manifest: LayerManifest,

    /// Install script content or path
    pub install_script: LayerScript,

    /// Where this layer was found
    pub source: LayerSource,
}

/// Install script reference
#[derive(Debug)]
pub enum LayerScript {
    /// File on disk (user-defined layer)
    Path(PathBuf),

    /// Embedded content (built-in layer)
    Embedded(&'static str),

    /// No install script (pure user-install layer handled by bootstrap)
    None,
}

impl LayerScript {
    /// Read the script content (from disk or embedded)
    pub async fn content(&self) -> MinoResult<String> {
        match self {
            Self::Path(path) => tokio::fs::read_to_string(path).await.map_err(|e| {
                MinoError::io(format!("reading install script {}", path.display()), e)
            }),
            Self::Embedded(content) => Ok((*content).to_string()),
            Self::None => Ok(String::new()),
        }
    }

    /// Returns true if this script has meaningful content to run in compose.
    pub fn has_content(&self) -> bool {
        !matches!(self, Self::None)
    }
}

/// A discoverable layer with metadata (for interactive selection)
#[derive(Debug, Clone)]
pub struct AvailableLayer {
    pub name: String,
    pub description: String,
    pub source: LayerSource,
}

/// Where a layer was resolved from
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LayerSource {
    /// `.mino/layers/{name}/` in the project directory
    ProjectLocal,

    /// `~/.config/mino/layers/{name}/`
    UserGlobal,

    /// Compiled into the binary
    BuiltIn,
}

/// Resolve a list of layer names to their manifests and scripts.
///
/// Resolution chain (first match wins per layer):
/// 1. `{project_dir}/.mino/layers/{name}/`
/// 2. `~/.config/mino/layers/{name}/`
/// 3. Built-in embedded layers
pub async fn resolve_layers(
    names: &[String],
    project_dir: &Path,
) -> MinoResult<Vec<ResolvedLayer>> {
    let mut resolved = Vec::with_capacity(names.len());

    for name in names {
        let layer = resolve_single(name, project_dir).await?;
        resolved.push(layer);
    }

    Ok(resolved)
}

/// Validate that a layer name is safe (no path traversal, no special characters).
fn validate_layer_name(name: &str) -> MinoResult<()> {
    if name.is_empty() {
        return Err(MinoError::User("Layer name cannot be empty".to_string()));
    }
    if name.contains('/') || name.contains('\\') || name.contains("..") || name.contains('\0') {
        return Err(MinoError::User(format!(
            "Invalid layer name '{}': must not contain path separators or '..'",
            name
        )));
    }
    // Only allow alphanumeric, hyphens, underscores
    if !name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    {
        return Err(MinoError::User(format!(
            "Invalid layer name '{}': must contain only alphanumeric characters, hyphens, or underscores",
            name
        )));
    }
    Ok(())
}

async fn resolve_single(name: &str, project_dir: &Path) -> MinoResult<ResolvedLayer> {
    validate_layer_name(name)?;

    let project_layer_dir = project_dir.join(".mino").join("layers").join(name);
    let global_layer_dir = dirs::config_dir().map(|d| d.join("mino").join("layers").join(name));

    // 1. Project-local
    if let Some(layer) = try_resolve_from_dir(&project_layer_dir, LayerSource::ProjectLocal).await?
    {
        return Ok(layer);
    }

    // 2. User-global
    if let Some(ref dir) = global_layer_dir {
        if let Some(layer) = try_resolve_from_dir(dir, LayerSource::UserGlobal).await? {
            return Ok(layer);
        }
    }

    // 3. Built-in
    if let Some(layer) = resolve_builtin(name)? {
        return Ok(layer);
    }

    // Build the searched paths string for the error
    let mut searched = vec![project_layer_dir.display().to_string()];
    if let Some(ref dir) = global_layer_dir {
        searched.push(dir.display().to_string());
    }
    searched.push("built-in layers".to_string());

    Err(MinoError::LayerNotFound {
        name: name.to_string(),
        searched: searched.join(", "),
    })
}

/// Try to resolve a layer from a directory on disk.
/// Returns None if the directory doesn't exist.
/// Returns Err if the directory exists but is invalid (missing files).
async fn try_resolve_from_dir(
    dir: &Path,
    source: LayerSource,
) -> MinoResult<Option<ResolvedLayer>> {
    let manifest_path = dir.join("layer.toml");
    let script_path = dir.join("install.sh");

    if !manifest_path.exists() {
        return Ok(None);
    }

    let manifest = LayerManifest::from_file(&manifest_path).await?;
    manifest.user_install.validate()?;
    manifest.root_install.validate()?;

    // install.sh is optional if the layer has [user_install]
    let install_script = if script_path.exists() {
        LayerScript::Path(script_path)
    } else if !manifest.user_install.is_empty() {
        LayerScript::None
    } else {
        return Err(MinoError::LayerScriptMissing(
            script_path.display().to_string(),
        ));
    };

    Ok(Some(ResolvedLayer {
        manifest,
        install_script,
        source,
    }))
}

/// Resolve a built-in layer by name
fn resolve_builtin(name: &str) -> MinoResult<Option<ResolvedLayer>> {
    let (manifest_str, install_str) = match name {
        "rust" | "cargo" => (BUILTIN_RUST_MANIFEST, BUILTIN_RUST_INSTALL),
        "typescript" | "ts" | "node" => (BUILTIN_TS_MANIFEST, BUILTIN_TS_INSTALL),
        "python" | "py" => (BUILTIN_PYTHON_MANIFEST, BUILTIN_PYTHON_INSTALL),
        _ => return Ok(None),
    };

    let manifest = LayerManifest::parse(manifest_str)?;
    manifest.user_install.validate()?;
    manifest.root_install.validate()?;

    // Use LayerScript::None for layers where install.sh is a placeholder
    let install_script = if install_str.trim().is_empty()
        || install_str
            .lines()
            .all(|l| l.trim().is_empty() || l.starts_with('#'))
    {
        LayerScript::None
    } else {
        LayerScript::Embedded(install_str)
    };

    Ok(Some(ResolvedLayer {
        manifest,
        install_script,
        source: LayerSource::BuiltIn,
    }))
}

/// List all available layers from all sources (for interactive prompts).
///
/// Scans project-local, user-global, and built-in sources.
/// Deduplicates by name (first source wins, matching resolution precedence).
pub async fn list_available_layers(project_dir: &Path) -> MinoResult<Vec<AvailableLayer>> {
    let mut seen = std::collections::HashSet::new();
    let mut layers = Vec::new();

    // 1. Project-local layers
    let project_layers_dir = project_dir.join(".mino").join("layers");
    scan_layer_dir(
        &project_layers_dir,
        LayerSource::ProjectLocal,
        &mut seen,
        &mut layers,
    )
    .await;

    // 2. User-global layers
    if let Some(global_dir) = dirs::config_dir().map(|d| d.join("mino").join("layers")) {
        scan_layer_dir(&global_dir, LayerSource::UserGlobal, &mut seen, &mut layers).await;
    }

    // 3. Built-in layers
    for (name, manifest_str) in &[
        ("typescript", BUILTIN_TS_MANIFEST),
        ("rust", BUILTIN_RUST_MANIFEST),
        ("python", BUILTIN_PYTHON_MANIFEST),
    ] {
        if seen.contains(*name) {
            continue;
        }
        if let Ok(manifest) = LayerManifest::parse(manifest_str) {
            seen.insert(name.to_string());
            layers.push(AvailableLayer {
                name: manifest.layer.name.clone(),
                description: manifest.layer.description.clone(),
                source: LayerSource::BuiltIn,
            });
        }
    }

    Ok(layers)
}

/// Scan a directory for layer subdirectories containing layer.toml
async fn scan_layer_dir(
    dir: &Path,
    source: LayerSource,
    seen: &mut std::collections::HashSet<String>,
    layers: &mut Vec<AvailableLayer>,
) {
    let entries = match tokio::fs::read_dir(dir).await {
        Ok(e) => e,
        Err(_) => return, // Directory doesn't exist, skip
    };

    let mut entries = entries;
    while let Ok(Some(entry)) = entries.next_entry().await {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let manifest_path = path.join("layer.toml");
        if !manifest_path.exists() {
            continue;
        }
        if let Ok(manifest) = LayerManifest::from_file(&manifest_path).await {
            let name = manifest.layer.name.clone();
            if seen.contains(&name) {
                continue;
            }
            seen.insert(name.clone());
            layers.push(AvailableLayer {
                name,
                description: manifest.layer.description.clone(),
                source: source.clone(),
            });
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn resolve_builtin_rust() {
        let layer = resolve_builtin("rust").unwrap().unwrap();
        assert_eq!(layer.manifest.layer.name, "rust");
        assert!(matches!(layer.source, LayerSource::BuiltIn));
        // Rust layer is now pure user-install (placeholder install.sh → None)
        assert!(matches!(layer.install_script, LayerScript::None));
        assert!(layer.manifest.has_user_install());
    }

    #[test]
    fn resolve_builtin_typescript() {
        let layer = resolve_builtin("typescript").unwrap().unwrap();
        assert_eq!(layer.manifest.layer.name, "typescript");
    }

    #[test]
    fn resolve_builtin_aliases() {
        assert!(resolve_builtin("cargo").unwrap().is_some());
        assert!(resolve_builtin("ts").unwrap().is_some());
        assert!(resolve_builtin("node").unwrap().is_some());
    }

    #[test]
    fn resolve_builtin_unknown() {
        assert!(resolve_builtin("java").unwrap().is_none());
    }

    #[tokio::test]
    async fn resolve_project_local_layer() {
        let temp = TempDir::new().unwrap();
        let layer_dir = temp.path().join(".mino").join("layers").join("custom");
        std::fs::create_dir_all(&layer_dir).unwrap();

        let manifest = r#"
[layer]
name = "custom"
description = "Custom layer"
version = "1"

[env]
MY_VAR = "/custom/path"
"#;
        std::fs::write(layer_dir.join("layer.toml"), manifest).unwrap();
        std::fs::write(layer_dir.join("install.sh"), "#!/bin/bash\necho ok").unwrap();

        let layers = resolve_layers(&["custom".to_string()], temp.path())
            .await
            .unwrap();

        assert_eq!(layers.len(), 1);
        assert_eq!(layers[0].manifest.layer.name, "custom");
        assert_eq!(layers[0].source, LayerSource::ProjectLocal);
        assert!(matches!(layers[0].install_script, LayerScript::Path(_)));
    }

    #[tokio::test]
    async fn resolve_missing_layer_errors() {
        let temp = TempDir::new().unwrap();
        let result = resolve_layers(&["nonexistent".to_string()], temp.path()).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("not found"));
    }

    #[tokio::test]
    async fn project_local_overrides_builtin() {
        let temp = TempDir::new().unwrap();
        let layer_dir = temp.path().join(".mino").join("layers").join("rust");
        std::fs::create_dir_all(&layer_dir).unwrap();

        let manifest = r#"
[layer]
name = "rust"
description = "Custom Rust"
version = "99"
"#;
        std::fs::write(layer_dir.join("layer.toml"), manifest).unwrap();
        std::fs::write(layer_dir.join("install.sh"), "#!/bin/bash\necho custom").unwrap();

        let layers = resolve_layers(&["rust".to_string()], temp.path())
            .await
            .unwrap();

        assert_eq!(layers[0].manifest.layer.version, "99");
        assert_eq!(layers[0].source, LayerSource::ProjectLocal);
    }

    #[tokio::test]
    async fn embedded_script_content() {
        // Python layer still has a real install script (root packages)
        let layer = resolve_builtin("python").unwrap().unwrap();
        let content = layer.install_script.content().await.unwrap();
        assert!(content.contains("python3"));
        assert!(content.contains("dnf"));
    }

    #[test]
    fn resolve_builtin_rust_user_install() {
        let layer = resolve_builtin("rust").unwrap().unwrap();
        assert_eq!(
            layer.manifest.user_install.runtime.as_deref(),
            Some("rustup")
        );
        assert!(layer
            .manifest
            .user_install
            .cargo_tools
            .contains(&"sccache".to_string()));
    }

    #[test]
    fn resolve_builtin_typescript_user_install() {
        let layer = resolve_builtin("typescript").unwrap().unwrap();
        assert!(matches!(layer.install_script, LayerScript::None));
        assert_eq!(layer.manifest.user_install.runtime.as_deref(), Some("nvm"));
        assert!(layer
            .manifest
            .user_install
            .npm_globals
            .contains(&"pnpm".to_string()));
    }

    #[test]
    fn validate_layer_name_rejects_traversal() {
        assert!(validate_layer_name("../etc").is_err());
        assert!(validate_layer_name("foo/bar").is_err());
        assert!(validate_layer_name("foo\\bar").is_err());
        assert!(validate_layer_name("..").is_err());
    }

    #[test]
    fn validate_layer_name_rejects_empty() {
        assert!(validate_layer_name("").is_err());
    }

    #[test]
    fn validate_layer_name_rejects_special_chars() {
        assert!(validate_layer_name("rust!").is_err());
        assert!(validate_layer_name("hello world").is_err());
        assert!(validate_layer_name("layer.name").is_err());
    }

    #[test]
    fn validate_layer_name_accepts_valid() {
        assert!(validate_layer_name("rust").is_ok());
        assert!(validate_layer_name("typescript").is_ok());
        assert!(validate_layer_name("my-layer").is_ok());
        assert!(validate_layer_name("my_layer_v2").is_ok());
    }

    #[tokio::test]
    async fn resolve_rejects_traversal_name() {
        let temp = TempDir::new().unwrap();
        let result = resolve_layers(&["../evil".to_string()], temp.path()).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Invalid layer name"));
    }

    #[tokio::test]
    async fn list_available_includes_builtins() {
        let temp = TempDir::new().unwrap();
        let layers = list_available_layers(temp.path()).await.unwrap();

        let names: Vec<&str> = layers.iter().map(|l| l.name.as_str()).collect();
        assert!(names.contains(&"typescript"));
        assert!(names.contains(&"rust"));
        assert!(names.contains(&"python"));
        assert!(layers.iter().all(|l| l.source == LayerSource::BuiltIn));
    }

    #[tokio::test]
    async fn list_available_includes_project_local() {
        let temp = TempDir::new().unwrap();
        let layer_dir = temp.path().join(".mino").join("layers").join("python");
        std::fs::create_dir_all(&layer_dir).unwrap();
        std::fs::write(
            layer_dir.join("layer.toml"),
            "[layer]\nname = \"python\"\ndescription = \"Python 3\"\nversion = \"1\"\n",
        )
        .unwrap();
        std::fs::write(layer_dir.join("install.sh"), "#!/bin/bash\necho ok").unwrap();

        let layers = list_available_layers(temp.path()).await.unwrap();
        let names: Vec<&str> = layers.iter().map(|l| l.name.as_str()).collect();
        assert!(names.contains(&"python"));
    }

    #[test]
    fn resolve_builtin_python() {
        let layer = resolve_builtin("python").unwrap().unwrap();
        assert_eq!(layer.manifest.layer.name, "python");
        assert!(matches!(layer.source, LayerSource::BuiltIn));
        assert!(matches!(layer.install_script, LayerScript::Embedded(_)));
    }

    #[test]
    fn resolve_builtin_python_alias() {
        let layer = resolve_builtin("py").unwrap().unwrap();
        assert_eq!(layer.manifest.layer.name, "python");
    }

    #[tokio::test]
    async fn embedded_python_script_content() {
        let layer = resolve_builtin("python").unwrap().unwrap();
        let content = layer.install_script.content().await.unwrap();
        // Python install.sh now only handles system packages
        assert!(content.contains("python3"));
        assert!(content.contains("dnf"));
        // uv and ruff moved to [user_install]
        assert!(layer.manifest.has_user_install());
        assert_eq!(layer.manifest.user_install.runtime.as_deref(), Some("uv"));
        assert!(layer
            .manifest
            .user_install
            .uv_tools
            .contains(&"ruff".to_string()));
    }

    #[tokio::test]
    async fn resolve_user_install_only_layer_no_script() {
        let temp = TempDir::new().unwrap();
        let layer_dir = temp.path().join(".mino").join("layers").join("mytools");
        std::fs::create_dir_all(&layer_dir).unwrap();

        let manifest = r#"
[layer]
name = "mytools"
description = "User install only"
version = "1"

[user_install]
runtime = "nvm"
runtime_version = "22"
npm_globals = ["pnpm"]
"#;
        std::fs::write(layer_dir.join("layer.toml"), manifest).unwrap();
        // No install.sh — should succeed because user_install is present

        let layers = resolve_layers(&["mytools".to_string()], temp.path())
            .await
            .unwrap();

        assert_eq!(layers.len(), 1);
        assert_eq!(layers[0].manifest.layer.name, "mytools");
        assert!(matches!(layers[0].install_script, LayerScript::None));
        assert!(layers[0].manifest.has_user_install());
    }

    #[tokio::test]
    async fn resolve_missing_script_still_errors_without_user_install() {
        // Original test: layer with NO user_install AND no install.sh is still an error
        let temp = TempDir::new().unwrap();
        let layer_dir = temp.path().join(".mino").join("layers").join("broken");
        std::fs::create_dir_all(&layer_dir).unwrap();

        let manifest = r#"
[layer]
name = "broken"
description = "Broken layer"
version = "1"
"#;
        std::fs::write(layer_dir.join("layer.toml"), manifest).unwrap();
        // No install.sh and no user_install

        let result = resolve_layers(&["broken".to_string()], temp.path()).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("install script missing"));
    }

    #[test]
    fn layer_script_none_has_no_content() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let content = rt.block_on(LayerScript::None.content()).unwrap();
        assert!(content.is_empty());
        assert!(!LayerScript::None.has_content());
    }

    #[tokio::test]
    async fn list_available_deduplicates_by_name() {
        let temp = TempDir::new().unwrap();
        // Create a project-local "rust" layer (should shadow built-in)
        let layer_dir = temp.path().join(".mino").join("layers").join("rust");
        std::fs::create_dir_all(&layer_dir).unwrap();
        std::fs::write(
            layer_dir.join("layer.toml"),
            "[layer]\nname = \"rust\"\ndescription = \"Custom Rust\"\nversion = \"99\"\n",
        )
        .unwrap();
        std::fs::write(layer_dir.join("install.sh"), "#!/bin/bash\necho ok").unwrap();

        let layers = list_available_layers(temp.path()).await.unwrap();
        let rust_layers: Vec<&AvailableLayer> =
            layers.iter().filter(|l| l.name == "rust").collect();
        assert_eq!(rust_layers.len(), 1);
        assert_eq!(rust_layers[0].source, LayerSource::ProjectLocal);
        assert_eq!(rust_layers[0].description, "Custom Rust");
    }
}