agentkernel 0.18.1

Run AI coding agents in secure, isolated microVMs
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
//! Setup and installation management for agentkernel.
//!
//! Handles downloading/building kernel, rootfs, and Firecracker.

use anyhow::{Context, Result, bail};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::plugin_installer;

/// Runtime options for rootfs
pub const RUNTIMES: &[(&str, &str)] = &[
    ("base", "Minimal Alpine Linux (~64MB)"),
    ("python", "Python 3.12 with pip (~256MB)"),
    ("node", "Node.js 20 LTS with npm (~256MB)"),
    ("go", "Go toolchain (~512MB)"),
    ("rust", "Rust with Cargo (~512MB)"),
];

/// Setup configuration
#[allow(dead_code)]
pub struct SetupConfig {
    pub data_dir: PathBuf,
    pub kernel_version: String,
    pub runtimes: Vec<String>,
    pub install_firecracker: bool,
}

impl Default for SetupConfig {
    fn default() -> Self {
        Self {
            data_dir: default_data_dir(),
            kernel_version: "6.1.70".to_string(),
            runtimes: vec!["base".to_string()],
            install_firecracker: true,
        }
    }
}

/// Get the default data directory
pub fn default_data_dir() -> PathBuf {
    if let Some(home) = std::env::var_os("HOME") {
        PathBuf::from(home).join(".local/share/agentkernel")
    } else {
        PathBuf::from("/usr/local/share/agentkernel")
    }
}

/// Check what components are installed
pub fn check_installation() -> SetupStatus {
    let data_dir = default_data_dir();

    // Check KVM status - distinguish between "not present" and "permission denied"
    let kvm_path = std::path::PathBuf::from("/dev/kvm");
    let kvm_exists = kvm_path.exists();
    let kvm_accessible = check_kvm();
    let kvm_permission_denied = kvm_exists && !kvm_accessible;

    SetupStatus {
        kernel_installed: find_kernel(&data_dir).is_some(),
        rootfs_base_installed: data_dir.join("images/rootfs/base.ext4").exists(),
        rootfs_python_installed: data_dir.join("images/rootfs/python.ext4").exists(),
        rootfs_node_installed: data_dir.join("images/rootfs/node.ext4").exists(),
        firecracker_installed: find_firecracker().is_some(),
        kvm_available: kvm_accessible,
        kvm_permission_denied,
        docker_available: check_docker(),
        apple_containers_available: check_apple_containers(),
        macos_version_supported: check_macos_version(),
    }
}

/// Installation status
#[derive(Debug)]
#[allow(dead_code)]
pub struct SetupStatus {
    pub kernel_installed: bool,
    pub rootfs_base_installed: bool,
    pub rootfs_python_installed: bool,
    pub rootfs_node_installed: bool,
    pub firecracker_installed: bool,
    pub kvm_available: bool,
    /// True if /dev/kvm exists but user lacks permission to access it
    pub kvm_permission_denied: bool,
    pub docker_available: bool,
    /// True if Apple containers CLI is installed (macOS 26+)
    pub apple_containers_available: bool,
    /// True if macOS version supports Apple containers (26+)
    pub macos_version_supported: bool,
}

impl SetupStatus {
    pub fn is_ready(&self) -> bool {
        // For Firecracker backend, we need kernel + rootfs
        let firecracker_ready =
            self.kvm_available && self.kernel_installed && self.rootfs_base_installed;

        // For container backends (Docker/Apple), just need the backend available
        let container_ready = self.docker_available || self.apple_containers_available;

        // If KVM is available, require Firecracker assets (daemon will use them)
        if self.kvm_available {
            return firecracker_ready;
        }

        container_ready
    }

    pub fn print(&self) {
        println!("Setup Status:");
        println!(
            "  Kernel:      {}",
            if self.kernel_installed {
                "installed"
            } else {
                "not installed"
            }
        );
        println!(
            "  Rootfs base: {}",
            if self.rootfs_base_installed {
                "installed"
            } else {
                "not installed"
            }
        );
        println!(
            "  Firecracker: {}",
            if self.firecracker_installed {
                "installed"
            } else {
                "not installed"
            }
        );
        // Show KVM status with helpful message if permission denied
        let kvm_status = if self.kvm_available {
            "available"
        } else if self.kvm_permission_denied {
            "permission denied"
        } else {
            "not available"
        };
        println!("  KVM:         {}", kvm_status);

        // Show guidance for KVM permission issues
        if self.kvm_permission_denied {
            println!();
            println!("  ⚠️  /dev/kvm exists but you don't have permission to access it.");
            println!("  Fix with: sudo usermod -aG kvm $USER && newgrp kvm");
        }

        println!(
            "  Docker:      {}",
            if self.docker_available {
                "available"
            } else {
                "not available"
            }
        );

        // Show Apple containers status on macOS
        if cfg!(target_os = "macos") {
            let apple_status = if self.apple_containers_available {
                "available"
            } else if self.macos_version_supported {
                "not installed (macOS 26+ detected)"
            } else {
                "not available (requires macOS 26+)"
            };
            println!("  Apple Containers: {}", apple_status);

            // Show installation hint if macOS 26+ but CLI not installed
            if self.macos_version_supported && !self.apple_containers_available {
                println!();
                println!("  💡 Apple Containers provides VM-level isolation on macOS.");
                println!("  Install from: https://github.com/apple/container/releases");
            }
        }
    }
}

/// Find installed kernel
fn find_kernel(data_dir: &Path) -> Option<PathBuf> {
    let kernel_dir = data_dir.join("images/kernel");
    if kernel_dir.exists()
        && let Ok(entries) = std::fs::read_dir(&kernel_dir)
    {
        for entry in entries.flatten() {
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            if name_str.starts_with("vmlinux-") && name_str.ends_with("-agentkernel") {
                return Some(entry.path());
            }
        }
    }
    None
}

/// Find Firecracker binary
fn find_firecracker() -> Option<PathBuf> {
    // Check agentkernel's own bin directory first
    let data_dir = default_data_dir();
    let local_fc = data_dir.join("bin/firecracker");
    if local_fc.exists() {
        return Some(local_fc);
    }

    // Check PATH
    if let Ok(output) = Command::new("which").arg("firecracker").output()
        && output.status.success()
    {
        let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if !path.is_empty() {
            return Some(PathBuf::from(path));
        }
    }

    // Check common locations
    let locations = ["/usr/local/bin/firecracker", "/usr/bin/firecracker"];

    for loc in locations {
        let path = PathBuf::from(loc);
        if path.exists() {
            return Some(path);
        }
    }

    None
}

/// Check if KVM is available and accessible
///
/// Returns true only if /dev/kvm exists AND the current user has read/write access.
/// This prevents the confusing case where status says "KVM: available" but operations fail.
fn check_kvm() -> bool {
    let kvm_path = std::path::PathBuf::from("/dev/kvm");
    if !kvm_path.exists() {
        return false;
    }

    // Check if we can actually access KVM (not just that it exists)
    // Try to open with read/write to verify permissions
    #[cfg(unix)]
    {
        use std::fs::OpenOptions;
        OpenOptions::new()
            .read(true)
            .write(true)
            .open(&kvm_path)
            .is_ok()
    }
    #[cfg(not(unix))]
    {
        false
    }
}

/// Check if Docker is available
fn check_docker() -> bool {
    Command::new("docker")
        .arg("version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Check if Apple containers CLI is installed
fn check_apple_containers() -> bool {
    Command::new("container")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Check if macOS version supports Apple containers (26+)
fn check_macos_version() -> bool {
    if !cfg!(target_os = "macos") {
        return false;
    }

    Command::new("sw_vers")
        .arg("-productVersion")
        .output()
        .ok()
        .and_then(|output| {
            String::from_utf8(output.stdout).ok().and_then(|version| {
                version
                    .trim()
                    .split('.')
                    .next()
                    .and_then(|major| major.parse::<u32>().ok())
                    .map(|major| major >= 26)
            })
        })
        .unwrap_or(false)
}

/// Initialize Apple containers system (start service and download kernel if needed)
fn initialize_apple_containers() -> Result<()> {
    // Check if system is already running
    let status_output = Command::new("container")
        .args(["system", "status"])
        .output()?;

    if status_output.status.success()
        && String::from_utf8_lossy(&status_output.stdout).contains("is running")
    {
        println!("  Apple container system already running");
        return Ok(());
    }

    // Start the system (auto-accept kernel download)
    println!("  Starting Apple container system...");
    let output = Command::new("sh")
        .args(["-c", "echo 'Y' | container system start"])
        .output()
        .context("Failed to start Apple container system")?;

    if output.status.success() {
        println!("  Apple container system started");

        // Pre-pull alpine image for faster first run
        println!("  Pre-pulling alpine:3.20 image...");
        let _ = Command::new("container")
            .args(["image", "pull", "alpine:3.20"])
            .output();
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if !stderr.contains("already") {
            bail!("Failed to start Apple container system: {}", stderr);
        }
    }

    Ok(())
}

/// Prompt user to select from options
#[allow(dead_code)]
pub fn prompt_select(prompt: &str, options: &[(&str, &str)], default: usize) -> Result<usize> {
    println!("\n{}", prompt);
    for (i, (name, desc)) in options.iter().enumerate() {
        let marker = if i == default { " (recommended)" } else { "" };
        println!("  {}. {} - {}{}", i + 1, name, desc, marker);
    }

    print!("\nEnter choice [{}]: ", default + 1);
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    let input = input.trim();

    if input.is_empty() {
        return Ok(default);
    }

    match input.parse::<usize>() {
        Ok(n) if n >= 1 && n <= options.len() => Ok(n - 1),
        _ => {
            println!("Invalid choice, using default.");
            Ok(default)
        }
    }
}

/// Prompt user for yes/no
pub fn prompt_yes_no(prompt: &str, default: bool) -> Result<bool> {
    let default_str = if default { "Y/n" } else { "y/N" };
    print!("{} [{}]: ", prompt, default_str);
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    let input = input.trim().to_lowercase();

    if input.is_empty() {
        return Ok(default);
    }

    Ok(input == "y" || input == "yes")
}

/// Prompt user to select multiple options
pub fn prompt_multi_select(
    prompt: &str,
    options: &[(&str, &str)],
    defaults: &[usize],
) -> Result<Vec<usize>> {
    println!("\n{}", prompt);
    for (i, (name, desc)) in options.iter().enumerate() {
        let marker = if defaults.contains(&i) { " *" } else { "" };
        println!("  {}. {} - {}{}", i + 1, name, desc, marker);
    }
    println!("\n  (* = selected by default)");

    print!("Enter choices (comma-separated) or press Enter for defaults: ");
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    let input = input.trim();

    if input.is_empty() {
        return Ok(defaults.to_vec());
    }

    let mut selected = Vec::new();
    for part in input.split(',') {
        let part = part.trim();
        if let Ok(n) = part.parse::<usize>()
            && n >= 1
            && n <= options.len()
            && !selected.contains(&(n - 1))
        {
            selected.push(n - 1);
        }
    }

    if selected.is_empty() {
        return Ok(defaults.to_vec());
    }

    Ok(selected)
}

/// Run the interactive setup
pub async fn run_setup(non_interactive: bool) -> Result<()> {
    println!("=== Agentkernel Setup ===\n");

    let status = check_installation();
    status.print();

    if status.is_ready() && non_interactive {
        println!("\nAgentkernel is already set up and ready to use!");
        offer_plugin_install(non_interactive)?;
        return Ok(());
    }

    // Check platform requirements
    if !status.kvm_available && !status.docker_available {
        println!("\nWarning: Neither KVM nor Docker is available.");
        println!("  - On Linux: Ensure /dev/kvm exists and is accessible");
        println!("  - On macOS: Install Docker Desktop");
        if !non_interactive && !prompt_yes_no("Continue anyway?", false)? {
            return Ok(());
        }
    }

    let data_dir = default_data_dir();
    println!("\nInstall location: {}", data_dir.display());

    // Determine what to install
    let mut install_kernel = !status.kernel_installed;
    let mut install_firecracker = !status.firecracker_installed;
    let mut runtimes_to_install: Vec<String> = Vec::new();

    if non_interactive {
        // Non-interactive: install everything needed
        if !status.rootfs_base_installed {
            runtimes_to_install.push("base".to_string());
        }
    } else {
        // Interactive mode: ask user
        if !status.kernel_installed {
            install_kernel = prompt_yes_no("\nBuild and install kernel?", true)?;
        }

        if !status.firecracker_installed {
            install_firecracker = prompt_yes_no("Download and install Firecracker?", true)?;
        }

        // Ask which runtimes to install
        let runtime_options: Vec<(&str, &str)> = RUNTIMES.to_vec();
        let defaults = vec![0]; // base is default

        let selected = prompt_multi_select(
            "Which runtimes would you like to install?",
            &runtime_options,
            &defaults,
        )?;

        for idx in selected {
            let runtime = RUNTIMES[idx].0;
            let rootfs_path = data_dir.join(format!("images/rootfs/{}.ext4", runtime));
            if !rootfs_path.exists() {
                runtimes_to_install.push(runtime.to_string());
            }
        }
    }

    // Create directories
    std::fs::create_dir_all(data_dir.join("images/kernel"))?;
    std::fs::create_dir_all(data_dir.join("images/rootfs"))?;
    std::fs::create_dir_all(data_dir.join("bin"))?;

    // Check for Docker (needed for building)
    if (install_kernel || !runtimes_to_install.is_empty()) && !status.docker_available {
        bail!("Docker is required to build kernel and rootfs images. Please install Docker first.");
    }

    // Install kernel
    if install_kernel {
        println!("\n==> Building kernel...");
        build_kernel(&data_dir).await?;
    }

    // Install runtimes
    for runtime in &runtimes_to_install {
        println!("\n==> Building {} rootfs...", runtime);
        build_rootfs(&data_dir, runtime).await?;
    }

    // Install Firecracker
    if install_firecracker {
        println!("\n==> Installing Firecracker...");
        install_firecracker_binary(&data_dir).await?;
    }

    // Pre-pull Docker images for faster container startup
    if status.docker_available {
        println!("\n==> Pre-pulling Docker images...");
        if let Err(e) = prepull_docker_images(false) {
            eprintln!("Warning: Failed to pre-pull some images: {}", e);
        }
    }

    // Initialize Apple containers system if available
    if status.macos_version_supported && status.apple_containers_available {
        println!("\n==> Initializing Apple container system...");
        if let Err(e) = initialize_apple_containers() {
            eprintln!("Warning: Failed to initialize Apple containers: {}", e);
        }
    }

    println!("\n=== Setup Complete ===");

    // Re-check status after installation
    let final_status = check_installation();

    // Offer verification test if Firecracker backend is available
    if final_status.kernel_installed
        && final_status.rootfs_base_installed
        && final_status.firecracker_installed
    {
        if final_status.kvm_available {
            if !non_interactive {
                println!();
                if prompt_yes_no("Run a quick verification test?", true)? {
                    run_verification_test(&data_dir).await?;
                }
            }
        } else if final_status.kvm_permission_denied {
            println!(
                "\n⚠️  KVM permission denied - you need to fix this before using Firecracker."
            );
            println!("\nTo fix KVM permissions:");
            println!("  1. Add yourself to the kvm group:");
            println!("     sudo usermod -aG kvm $USER");
            println!("  2. Apply the group change (choose one):");
            println!("     - Log out and back in, OR");
            println!("     - Run: newgrp kvm");
            println!("     - Run commands with: sg kvm -c 'agentkernel start ...'");
            println!("\nAfter fixing permissions, run: agentkernel setup --verify");
        }
    }

    offer_plugin_install(non_interactive)?;

    println!("\nYou can now create sandboxes with:");
    println!("  agentkernel create my-sandbox");
    println!("  agentkernel start my-sandbox");

    Ok(())
}

/// Build the kernel
async fn build_kernel(data_dir: &Path) -> Result<()> {
    // Find the build script in the source directory or use embedded version
    let script_content = include_str!("../images/build/build-kernel.sh");
    let config_content = include_str!("../images/kernel/microvm.config");

    // Create temp directory for build
    let temp_dir = std::env::temp_dir().join("agentkernel-kernel-build");
    std::fs::create_dir_all(&temp_dir)?;

    // Write build script and config
    let script_path = temp_dir.join("build-kernel.sh");
    let config_path = temp_dir.join("microvm.config");
    std::fs::write(&script_path, script_content)?;
    std::fs::write(&config_path, config_content)?;

    // Make script executable
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755))?;
    }

    // Build Docker image
    let dockerfile = r#"
FROM ubuntu:24.04
RUN apt-get update && apt-get install -y \
    build-essential bc bison flex libelf-dev libssl-dev curl xz-utils cpio \
    && rm -rf /var/lib/apt/lists/*
WORKDIR /build
COPY build-kernel.sh /build/
COPY microvm.config /kernel/
RUN chmod +x /build/build-kernel.sh
RUN mkdir -p /kernel
ENV BUILD_DIR=/tmp/kernel-build
ENTRYPOINT ["/build/build-kernel.sh"]
CMD ["6.1.70"]
"#;

    let dockerfile_path = temp_dir.join("Dockerfile");
    std::fs::write(&dockerfile_path, dockerfile)?;

    // Build the Docker image
    let status = Command::new("docker")
        .args(["build", "-t", "agentkernel-kernel-builder", "."])
        .current_dir(&temp_dir)
        .status()
        .context("Failed to build kernel builder Docker image")?;

    if !status.success() {
        bail!("Failed to build kernel builder Docker image");
    }

    // Run the build
    let kernel_dir = data_dir.join("images/kernel");
    std::fs::create_dir_all(&kernel_dir)?;

    // Copy config to kernel dir BEFORE running Docker (volume mount shadows image contents)
    std::fs::write(kernel_dir.join("microvm.config"), config_content)?;

    let status = Command::new("docker")
        .args([
            "run",
            "--rm",
            "-v",
            &format!("{}:/kernel", kernel_dir.display()),
            "agentkernel-kernel-builder",
            "6.1.70",
        ])
        .status()
        .context("Failed to run kernel build")?;

    if !status.success() {
        bail!("Kernel build failed");
    }

    println!("Kernel installed to: {}", kernel_dir.display());
    Ok(())
}

/// Build the guest agent binary for inclusion in rootfs
///
/// Cross-compiles the guest agent to x86_64-unknown-linux-musl for static linking.
async fn build_guest_agent(data_dir: &Path) -> Result<()> {
    let bin_dir = data_dir.join("bin");
    std::fs::create_dir_all(&bin_dir)?;

    // Embedded guest agent source
    let guest_agent_source = include_str!("embedded/guest_agent_main.rs");
    let guest_agent_cargo = include_str!("embedded/guest_agent_cargo.toml");

    // Create temp directory for build
    let temp_dir = std::env::temp_dir().join("agentkernel-guest-build");
    std::fs::create_dir_all(&temp_dir)?;
    std::fs::create_dir_all(temp_dir.join("src"))?;

    // Write source files
    std::fs::write(temp_dir.join("src/main.rs"), guest_agent_source)?;
    std::fs::write(temp_dir.join("Cargo.toml"), guest_agent_cargo)?;

    // Dockerfile for building with musl
    let dockerfile = r#"
FROM rust:1.85-alpine AS builder
RUN apk add --no-cache musl-dev
WORKDIR /build
COPY . .
RUN cargo build --release --target x86_64-unknown-linux-musl 2>/dev/null || cargo build --release
RUN cp target/*/release/agent /agent || cp target/release/agent /agent

FROM scratch
COPY --from=builder /agent /agent
CMD ["/agent"]
"#;

    std::fs::write(temp_dir.join("Dockerfile"), dockerfile)?;

    // Build in Docker
    let status = Command::new("docker")
        .args(["build", "-t", "agentkernel-guest-builder", "."])
        .current_dir(&temp_dir)
        .status()
        .context("Failed to build guest agent Docker image")?;

    if !status.success() {
        bail!("Failed to build guest agent Docker image");
    }

    // Extract the binary using docker cp
    // First remove any existing temp container
    let _ = Command::new("docker")
        .args(["rm", "-f", "agentkernel-guest-tmp"])
        .output();

    // Create a temporary container from the built image
    let status = Command::new("docker")
        .args([
            "create",
            "--name",
            "agentkernel-guest-tmp",
            "agentkernel-guest-builder",
        ])
        .status()
        .context("Failed to create temp container")?;

    if !status.success() {
        bail!("Failed to create temp container for guest agent");
    }

    // Copy the binary out
    let status = Command::new("docker")
        .args([
            "cp",
            "agentkernel-guest-tmp:/agent",
            &bin_dir.join("agent").to_string_lossy(),
        ])
        .status()
        .context("Failed to extract guest agent binary")?;

    // Clean up temp container
    let _ = Command::new("docker")
        .args(["rm", "-f", "agentkernel-guest-tmp"])
        .output();

    if !status.success() {
        bail!("Failed to extract guest agent binary");
    }

    // Make executable and verify the binary is valid
    let agent_path = bin_dir.join("agent");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if agent_path.exists() {
            std::fs::set_permissions(&agent_path, std::fs::Permissions::from_mode(0o755))?;
        }
    }

    // Verify the binary is non-empty (catches build failures like wrong Rust edition)
    let agent_size = std::fs::metadata(&agent_path).map(|m| m.len()).unwrap_or(0);
    if agent_size == 0 {
        bail!(
            "Guest agent binary is empty (0 bytes). This usually means the Rust build failed.\n\
             Check that guest-agent/Cargo.toml uses a supported Rust edition (2021, not 2024)."
        );
    }
    if agent_size < 10000 {
        eprintln!(
            "Warning: Guest agent binary is unusually small ({} bytes). It may not work correctly.",
            agent_size
        );
    }

    println!(
        "Guest agent built: {} ({} bytes)",
        agent_path.display(),
        agent_size
    );
    Ok(())
}

/// Build a rootfs image
async fn build_rootfs(data_dir: &Path, runtime: &str) -> Result<()> {
    let rootfs_dir = data_dir.join("images/rootfs");
    std::fs::create_dir_all(&rootfs_dir)?;

    // First, build the guest agent if not already built
    let agent_bin = data_dir.join("bin/agent");
    if !agent_bin.exists() {
        println!("Building guest agent...");
        build_guest_agent(data_dir).await?;
    }

    // Size based on runtime
    let size_mb = match runtime {
        "base" => 64,
        "python" | "node" => 256,
        "go" | "rust" => 512,
        _ => 256,
    };

    // Packages based on runtime
    let packages = match runtime {
        "python" => "python3 py3-pip",
        "node" => "nodejs npm",
        "go" => "go",
        "rust" => "rust cargo",
        _ => "",
    };

    // Build script that runs inside Docker
    let build_script = format!(
        r#"#!/bin/sh
set -eu

# Install required tools
apk add --no-cache e2fsprogs

ROOTFS_IMG="/output/{runtime}.ext4"
MOUNT_DIR="/mnt/rootfs"
SIZE_MB={size_mb}
PACKAGES="{packages}"

echo "Creating ${{SIZE_MB}}MB ext4 image..."
dd if=/dev/zero of="$ROOTFS_IMG" bs=1M count=$SIZE_MB 2>/dev/null
mkfs.ext4 -F "$ROOTFS_IMG"

echo "Mounting and populating rootfs..."
mkdir -p "$MOUNT_DIR"
mount -o loop "$ROOTFS_IMG" "$MOUNT_DIR"

echo "Installing Alpine base system..."
apk -X https://dl-cdn.alpinelinux.org/alpine/v3.20/main \
    -X https://dl-cdn.alpinelinux.org/alpine/v3.20/community \
    -U --allow-untrusted --root "$MOUNT_DIR" --initdb \
    add alpine-base busybox-static $PACKAGES || true

mkdir -p "$MOUNT_DIR"/{{dev,proc,sys,tmp,run,root,app,usr/bin}}
chmod 1777 "$MOUNT_DIR/tmp"

# Copy guest agent if available
if [ -f /agent-bin/agent ]; then
    cp /agent-bin/agent "$MOUNT_DIR/usr/bin/agent"
    chmod +x "$MOUNT_DIR/usr/bin/agent"
    echo "Guest agent installed"
fi

# Create device nodes
mknod -m 622 "$MOUNT_DIR/dev/console" c 5 1 || true
mknod -m 666 "$MOUNT_DIR/dev/null" c 1 3 || true
mknod -m 666 "$MOUNT_DIR/dev/zero" c 1 5 || true
mknod -m 666 "$MOUNT_DIR/dev/tty" c 5 0 || true
mknod -m 666 "$MOUNT_DIR/dev/random" c 1 8 || true
mknod -m 666 "$MOUNT_DIR/dev/urandom" c 1 9 || true

# Create init script that starts the guest agent
cat > "$MOUNT_DIR/init" << 'INIT'
#!/bin/busybox sh
/bin/busybox mount -t proc proc /proc
/bin/busybox mount -t sysfs sysfs /sys
/bin/busybox mount -t devtmpfs devtmpfs /dev 2>/dev/null || true
/bin/busybox hostname agentkernel

# Start guest agent in background if available
if [ -x /usr/bin/agent ]; then
    /usr/bin/agent &
    AGENT_PID=$!
    echo "Guest agent started"
fi

echo "Agentkernel guest ready"
if [ $# -gt 0 ]; then
    exec "$@"
elif [ -n "$AGENT_PID" ]; then
    wait $AGENT_PID
else
    exec /bin/busybox sh
fi
INIT
chmod +x "$MOUNT_DIR/init"

# Set up /etc files
echo "agentkernel" > "$MOUNT_DIR/etc/hostname"
echo "root:x:0:0:root:/root:/bin/sh" > "$MOUNT_DIR/etc/passwd"
echo "root:x:0:" > "$MOUNT_DIR/etc/group"

umount "$MOUNT_DIR"

# Fix ownership so Firecracker can access the file
if [ -n "$HOST_UID" ] && [ -n "$HOST_GID" ]; then
    chown "$HOST_UID:$HOST_GID" "$ROOTFS_IMG"
fi

echo "Rootfs created: $ROOTFS_IMG"
ls -lh "$ROOTFS_IMG"
"#,
        runtime = runtime,
        size_mb = size_mb,
        packages = packages
    );

    // Create temp directory
    let temp_dir = std::env::temp_dir().join("agentkernel-rootfs-build");
    std::fs::create_dir_all(&temp_dir)?;

    let script_path = temp_dir.join("build.sh");
    std::fs::write(&script_path, &build_script)?;

    // Run build in Docker
    // SECURITY NOTE: Building rootfs images requires privileged access to create
    // loop devices and mount filesystems. This is only used during setup, not
    // during normal sandbox operation. The build runs a minimal Alpine container
    // with a controlled script. For production deployments, consider using
    // pre-built images instead of building locally.
    eprintln!("  (Building with privileged Docker - required for loop device access)");

    // Get current user's UID/GID to fix ownership after build
    let uid = Command::new("id")
        .args(["-u"])
        .output()
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_else(|_| "1000".to_string());
    let gid = Command::new("id")
        .args(["-g"])
        .output()
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_else(|_| "1000".to_string());

    let status = Command::new("docker")
        .args([
            "run",
            "--rm",
            "--privileged",
            "-e",
            &format!("HOST_UID={}", uid),
            "-e",
            &format!("HOST_GID={}", gid),
            // Security: Mount build script as read-only to prevent tampering
            "-v",
            &format!("{}:/output", rootfs_dir.display()),
            "-v",
            &format!("{}:/build.sh:ro", script_path.display()),
            "-v",
            &format!("{}:/agent-bin:ro", data_dir.join("bin").display()),
            "alpine:3.20",
            "/bin/sh",
            "/build.sh",
        ])
        .status()
        .context("Failed to run rootfs build")?;

    if !status.success() {
        bail!("Rootfs build failed for {}", runtime);
    }

    // Fix ownership - Docker creates files as root, but we need user access for Firecracker
    let rootfs_path = rootfs_dir.join(format!("{}.ext4", runtime));
    #[cfg(unix)]
    {
        use std::os::unix::fs::chown;
        if let (Some(uid), Some(gid)) = (
            std::env::var("UID").ok().and_then(|s| s.parse().ok()),
            std::env::var("GID")
                .ok()
                .or_else(|| std::env::var("GROUPS").ok())
                .and_then(|s| s.split_whitespace().next().and_then(|g| g.parse().ok())),
        ) {
            let _ = chown(&rootfs_path, Some(uid), Some(gid));
        } else {
            // Fallback: try to get uid/gid from the id command
            if let Ok(output) = Command::new("id").args(["-u"]).output()
                && output.status.success()
            {
                let uid: u32 = String::from_utf8_lossy(&output.stdout)
                    .trim()
                    .parse()
                    .unwrap_or(1000);
                if let Ok(output) = Command::new("id").args(["-g"]).output()
                    && output.status.success()
                {
                    let gid: u32 = String::from_utf8_lossy(&output.stdout)
                        .trim()
                        .parse()
                        .unwrap_or(1000);
                    let _ = chown(&rootfs_path, Some(uid), Some(gid));
                }
            }
        }
    }

    println!(
        "Rootfs installed to: {}/{}.ext4",
        rootfs_dir.display(),
        runtime
    );
    Ok(())
}

/// Run a quick verification test to ensure Firecracker can boot
async fn run_verification_test(data_dir: &Path) -> Result<()> {
    println!("\n==> Running verification test...");

    let kernel_path = find_kernel(data_dir).ok_or_else(|| anyhow::anyhow!("Kernel not found"))?;
    let rootfs_path = data_dir.join("images/rootfs/base.ext4");
    let firecracker_path = data_dir.join("bin/firecracker");

    if !rootfs_path.exists() {
        bail!("Rootfs not found: {}", rootfs_path.display());
    }
    if !firecracker_path.exists() {
        bail!("Firecracker not found: {}", firecracker_path.display());
    }

    println!("  Kernel: {}", kernel_path.display());
    println!("  Rootfs: {}", rootfs_path.display());
    println!("  Firecracker: {}", firecracker_path.display());

    // Create a test using our vmm module
    // For now, just verify the files exist and are accessible
    let kernel_size = std::fs::metadata(&kernel_path)?.len();
    let rootfs_size = std::fs::metadata(&rootfs_path)?.len();
    let fc_size = std::fs::metadata(&firecracker_path)?.len();

    println!("\n  Kernel size: {} bytes", kernel_size);
    println!("  Rootfs size: {} bytes", rootfs_size);
    println!("  Firecracker size: {} bytes", fc_size);

    // Basic sanity checks
    if kernel_size < 1_000_000 {
        eprintln!("  ⚠️  Kernel seems too small, might not be built correctly");
    }
    if rootfs_size < 10_000_000 {
        eprintln!("  ⚠️  Rootfs seems too small, might not be built correctly");
    }

    // Check guest agent in rootfs (would require mounting, skip for now)
    let agent_path = data_dir.join("bin/agent");
    if agent_path.exists() {
        let agent_size = std::fs::metadata(&agent_path)?.len();
        println!("  Guest agent: {} bytes", agent_size);
        if agent_size > 0 {
            println!("\n✓ All components look good!");
            println!(
                "\nNote: Full boot test requires KVM access. Create and start a sandbox to test:"
            );
            println!("  agentkernel create test-sandbox");
            println!("  agentkernel start test-sandbox");
            println!("  agentkernel exec test-sandbox -- echo 'Hello from microVM!'");
        }
    } else {
        eprintln!("  ⚠️  Guest agent not found at {}", agent_path.display());
    }

    Ok(())
}

/// Detect installed agents and offer to install plugins.
fn offer_plugin_install(non_interactive: bool) -> Result<()> {
    let uninstalled = plugin_installer::detect_uninstalled_plugins();
    if uninstalled.is_empty() {
        return Ok(());
    }

    println!("\n==> Agent plugins");
    println!(
        "Detected agents without plugins: {}",
        uninstalled
            .iter()
            .map(|t| t.name())
            .collect::<Vec<_>>()
            .join(", ")
    );

    let should_install = if non_interactive {
        true
    } else {
        prompt_yes_no("Install agent plugins now?", true)?
    };

    if should_install {
        if let Err(e) = plugin_installer::install_detected_plugins(&uninstalled) {
            eprintln!("Warning: Failed to install some plugins: {}", e);
        }
    } else {
        println!("  Skipped. Run later with: agentkernel plugin install <agent>");
    }

    Ok(())
}

/// Common Docker images to pre-pull for faster container startup
const DOCKER_IMAGES: &[&str] = &[
    "alpine:3.20",        // Default pool image
    "python:3.12-alpine", // Python runtime
    "node:20-alpine",     // Node.js runtime
    "golang:1.22-alpine", // Go runtime
    "rust:1.85-alpine",   // Rust runtime
];

/// Pre-pull common Docker images to avoid download delays during sandbox creation
pub fn prepull_docker_images(quiet: bool) -> Result<()> {
    if !check_docker() {
        if !quiet {
            println!("Docker not available, skipping image pre-pull");
        }
        return Ok(());
    }

    if !quiet {
        println!("Pre-pulling common Docker images for faster startup...");
    }

    for image in DOCKER_IMAGES {
        if !quiet {
            print!("  Pulling {}... ", image);
            io::stdout().flush()?;
        }

        let output = Command::new("docker")
            .args(["pull", "-q", image])
            .output()
            .context("Failed to pull Docker image")?;

        if output.status.success() {
            if !quiet {
                println!("done");
            }
        } else if !quiet {
            println!("failed (will be pulled on first use)");
        }
    }

    Ok(())
}

/// Install Firecracker binary
async fn install_firecracker_binary(data_dir: &Path) -> Result<()> {
    let bin_dir = data_dir.join("bin");
    std::fs::create_dir_all(&bin_dir)?;

    // Detect architecture
    let arch = if cfg!(target_arch = "x86_64") {
        "x86_64"
    } else if cfg!(target_arch = "aarch64") {
        "aarch64"
    } else {
        bail!("Unsupported architecture");
    };

    let version = "v1.7.0";
    let url = format!(
        "https://github.com/firecracker-microvm/firecracker/releases/download/{}/firecracker-{}-{}.tgz",
        version, version, arch
    );

    println!("Downloading Firecracker {} for {}...", version, arch);

    // Download and extract
    let status = Command::new("sh")
        .args([
            "-c",
            &format!(
                r#"curl -fsSL "{}" | tar -xz -C "{}" && \
                   mv "{}/release-{}-{}/firecracker-{}-{}" "{}/firecracker" && \
                   chmod +x "{}/firecracker" && \
                   rm -rf "{}/release-{}-{}""#,
                url,
                bin_dir.display(),
                bin_dir.display(),
                version,
                arch,
                version,
                arch,
                bin_dir.display(),
                bin_dir.display(),
                bin_dir.display(),
                version,
                arch
            ),
        ])
        .status()
        .context("Failed to download Firecracker")?;

    if !status.success() {
        bail!("Failed to download Firecracker");
    }

    let firecracker_path = bin_dir.join("firecracker");
    println!("Firecracker installed to: {}", firecracker_path.display());

    // Add to PATH hint
    println!("\nAdd to your PATH:");
    println!("  export PATH=\"{}:$PATH\"", bin_dir.display());

    Ok(())
}