muthr 0.1.47

Zero-trust orchestrator for MLX inference, container-based sandboxes, and MCP services on Apple Silicon
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
// Copyright 2026 tappunk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use tokio::fs;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;

struct TerminalStateGuard {
    fds: Vec<(i32, libc::termios)>,
}

impl TerminalStateGuard {
    fn capture() -> Self {
        let mut fds = Vec::new();

        for fd in [libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO] {
            // SAFETY: `fd` values are valid process file descriptor integers.
            let is_tty = unsafe { libc::isatty(fd) } == 1;
            if !is_tty {
                continue;
            }

            // SAFETY: zeroed `termios` is immediately initialized by `tcgetattr` on success.
            let mut termios = unsafe { std::mem::zeroed::<libc::termios>() };
            // SAFETY: `fd` is a tty and `termios` points to valid writable memory.
            let ok = unsafe { libc::tcgetattr(fd, &mut termios as *mut libc::termios) } == 0;
            if ok {
                fds.push((fd, termios));
            }
        }

        Self { fds }
    }
}

impl Drop for TerminalStateGuard {
    fn drop(&mut self) {
        for (fd, termios) in &self.fds {
            // SAFETY: `fd` and `termios` values were captured from successful `tcgetattr` calls.
            let _ = unsafe { libc::tcsetattr(*fd, libc::TCSANOW, termios as *const libc::termios) };
        }
    }
}

fn sanitize_project_name(name: &str) -> Option<String> {
    let sanitized: String = name
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
        .collect();

    if sanitized.is_empty() {
        return None;
    }

    Some(sanitized)
}

fn project_name_suffix(seed: &str) -> String {
    let hash = seed
        .as_bytes()
        .iter()
        .fold(0xcbf29ce484222325_u64, |acc, b| {
            (acc ^ u64::from(*b)).wrapping_mul(0x100000001b3)
        });
    format!("{:08x}", (hash & 0xffff_ffff) as u32)
}

fn run_container_session(
    container_id: &str,
    guest_workdir: &str,
    target_args: &[&str],
    requires_tty: bool,
) -> Result<(), color_eyre::Report> {
    let use_tty = std::io::stdin().is_terminal()
        && std::io::stdout().is_terminal()
        && std::io::stderr().is_terminal();

    if requires_tty && !use_tty {
        return Err(color_eyre::eyre::eyre!(
            "interactive TTY is required for this profile; run from a local terminal"
        ));
    }

    let run_once = |tty: bool| -> Result<std::process::ExitStatus, color_eyre::Report> {
        let _terminal_state_guard = tty.then(TerminalStateGuard::capture);

        let mut args = vec!["exec"];
        if tty {
            args.push("--interactive");
            args.push("--tty");
        }
        args.push("--workdir");
        args.push(guest_workdir);
        args.push("--user");
        args.push("muthr");
        args.push(container_id);
        args.extend_from_slice(target_args);

        let status = std::process::Command::new("container")
            .args(&args)
            .stdin(Stdio::inherit())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status()?;
        Ok(status)
    };

    let status = run_once(use_tty)?;
    if status.success() {
        return Ok(());
    }

    if use_tty && !requires_tty {
        eprintln!("warning: interactive TTY launch failed; retrying without TTY");
        let retry_status = run_once(false)?;
        if retry_status.success() {
            return Ok(());
        }
    }

    Err(color_eyre::eyre::eyre!(
        "application session exited with error"
    ))
}

fn validate_workspace_root(workspace: &Path, home: &Path) -> Result<(), color_eyre::Report> {
    if workspace == Path::new("/") {
        return Err(color_eyre::eyre::eyre!("workspace root cannot be '/'"));
    }
    if workspace == Path::new("/Users") {
        return Err(color_eyre::eyre::eyre!("workspace root cannot be '/Users'"));
    }
    if workspace == home {
        return Err(color_eyre::eyre::eyre!(
            "security violation: workspace root cannot be the home directory; use a dedicated subdirectory (for example, ~/src)"
        ));
    }
    if !workspace.starts_with(home) {
        return Err(color_eyre::eyre::eyre!(
            "workspace root must be inside '$HOME'"
        ));
    }
    Ok(())
}

pub fn resolve_workspace_context() -> Result<(String, PathBuf, PathBuf), color_eyre::Report> {
    let current_dir = std::env::current_dir()?;
    let home = std::env::var("HOME")?;
    let canonical_current_dir = current_dir.canonicalize()?;

    let raw_workspace_root = if let Ok(v) = std::env::var("MUTHR_WORKSPACE_ROOT") {
        v
    } else if let Ok(cfg) = crate::config::load() {
        cfg.workspace_root
            .unwrap_or_else(|| format!("{}/src", home))
    } else {
        format!("{}/src", home)
    };

    let workspace_root = raw_workspace_root
        .strip_prefix("~/")
        .map(|p| format!("{}/{}", home, p))
        .unwrap_or(raw_workspace_root);

    let muthr_config_dir = PathBuf::from(&home).join(".config/muthr");
    if muthr_config_dir.exists()
        && let Ok(canonical_muthr_config_dir) = muthr_config_dir.canonicalize()
        && canonical_current_dir.starts_with(&canonical_muthr_config_dir)
    {
        return Ok(("muthr-config".to_string(), muthr_config_dir, current_dir));
    }

    let workspace_path = PathBuf::from(&workspace_root);
    if !workspace_path.exists() {
        eprintln!("error: workspace root '{}' does not exist", workspace_root);
        eprintln!(
            "info: create it with 'mkdir -p {}' or set MUTHR_WORKSPACE_ROOT",
            workspace_root
        );
        std::process::exit(66);
    }

    let canonical_workspace_path = workspace_path
        .canonicalize()
        .map_err(|e| color_eyre::eyre::eyre!("failed to canonicalize workspace root: {}", e))?;
    let canonical_home = PathBuf::from(&home)
        .canonicalize()
        .map_err(|e| color_eyre::eyre::eyre!("failed to canonicalize home directory: {}", e))?;

    validate_workspace_root(&canonical_workspace_path, &canonical_home)?;

    if canonical_current_dir == canonical_workspace_path {
        return Err(color_eyre::eyre::eyre!(
            "navigate into a project directory first"
        ));
    }

    let relative = canonical_current_dir
        .strip_prefix(&canonical_workspace_path)
        .map_err(|_| {
            color_eyre::eyre::eyre!("current directory is outside the configured workspace root")
        })?;
    let project_component = relative
        .components()
        .next()
        .ok_or_else(|| color_eyre::eyre::eyre!("invalid workspace path"))?
        .as_os_str();
    let project_name = project_component
        .to_str()
        .ok_or_else(|| color_eyre::eyre::eyre!("invalid project name"))?;
    let sanitized_project_name = sanitize_project_name(project_name)
        .ok_or_else(|| color_eyre::eyre::eyre!("sanitized project name is empty"))?;
    let project_token = if sanitized_project_name == project_name {
        sanitized_project_name
    } else {
        format!(
            "{}-{}",
            sanitized_project_name,
            project_name_suffix(project_name)
        )
    };

    let project_folder = format!("muthr-{}", project_token);
    let mount_point = canonical_workspace_path.join(project_component);

    Ok((project_folder, mount_point, current_dir))
}

async fn container_list_all_json() -> Option<Vec<serde_json::Value>> {
    let output = Command::new("container")
        .args(["list", "--all", "--format", "json"])
        .output()
        .await
        .ok()?;
    if !output.status.success() {
        return None;
    }

    serde_json::from_slice::<Vec<serde_json::Value>>(&output.stdout).ok()
}

fn container_id_from_item(item: &serde_json::Value) -> Option<String> {
    item.get("id")
        .and_then(|v| v.as_str())
        .or_else(|| {
            item.get("configuration")
                .and_then(|v| v.get("id"))
                .and_then(|v| v.as_str())
        })
        .map(std::borrow::ToOwned::to_owned)
}

fn container_status_from_item(item: &serde_json::Value) -> Option<String> {
    item.get("status")
        .and_then(|v| v.as_str())
        .or_else(|| item.get("state").and_then(|v| v.as_str()))
        .or_else(|| {
            item.get("status")
                .and_then(|v| v.get("state"))
                .and_then(|v| v.as_str())
        })
        .map(std::borrow::ToOwned::to_owned)
}

async fn container_exists(container_id: &str) -> bool {
    let Some(items) = container_list_all_json().await else {
        return false;
    };

    items
        .iter()
        .filter_map(container_id_from_item)
        .any(|id| id == container_id)
}

async fn container_is_running(container_id: &str) -> bool {
    let Some(items) = container_list_all_json().await else {
        return false;
    };

    items.iter().any(|item| {
        container_id_from_item(item).is_some_and(|id| id == container_id)
            && container_status_from_item(item)
                .map(|s| s.eq_ignore_ascii_case("running"))
                .unwrap_or(false)
    })
}

pub async fn sandbox_exists(container_id: &str) -> bool {
    container_exists(container_id).await
}

pub async fn cleanup_untracked_vms(verbose: bool) -> Result<(), color_eyre::Report> {
    let _lock =
        crate::lifecycle::acquire("container-lifecycle", std::time::Duration::from_secs(20))
            .await?;
    let home = std::env::var("HOME")?;
    let cache_dir = PathBuf::from(home).join(".cache/muthr");

    let Some(items) = container_list_all_json().await else {
        if verbose {
            eprintln!("warning: failed to list containers for cleanup");
        }
        return Ok(());
    };

    for item in items {
        let Some(container_id) = container_id_from_item(&item) else {
            continue;
        };
        if !container_id.starts_with("muthr-")
            || container_id == "muthr-services"
            || container_id == "muthr-searxng"
        {
            continue;
        }

        let is_managed_project = item
            .get("configuration")
            .and_then(|v| v.get("labels"))
            .and_then(|v| v.get("muthr.managed"))
            .and_then(|v| v.as_str())
            .is_some_and(|v| v == "true")
            && item
                .get("configuration")
                .and_then(|v| v.get("labels"))
                .and_then(|v| v.get("muthr.owner"))
                .and_then(|v| v.as_str())
                .is_some_and(|v| v == "project");
        if !is_managed_project {
            if verbose {
                eprintln!(
                    "info: skipping unlabeled sandbox container {}",
                    container_id
                );
            }
            continue;
        }

        let profile_cache = cache_dir.join(format!("{}-profiles", container_id));
        if profile_cache.exists() {
            continue;
        }

        let running = container_status_from_item(&item)
            .map(|s| s.eq_ignore_ascii_case("running"))
            .unwrap_or(false);
        if running {
            if verbose {
                eprintln!(
                    "info: skipping running untracked sandbox container {}",
                    container_id
                );
            }
            continue;
        }

        if verbose {
            eprintln!(
                "warning: removing untracked sandbox container {}",
                container_id
            );
        }
        delete_container_impl(&container_id, true).await?;
    }

    Ok(())
}

pub async fn sandbox_is_running(container_id: &str) -> bool {
    container_is_running(container_id).await
}

pub async fn stop_container_with_timeout(
    container_id: &str,
    timeout_secs: u64,
) -> Result<bool, color_eyre::Report> {
    if !container_is_running(container_id).await {
        return Ok(false);
    }

    let status = Command::new("container")
        .args(["stop", "--time", &timeout_secs.to_string(), container_id])
        .status()
        .await?;
    if !status.success() {
        return Err(color_eyre::eyre::eyre!(
            "failed to stop container '{}'",
            container_id
        ));
    }

    Ok(true)
}

pub async fn stop_container_by_name(container_id: &str) -> Result<(), color_eyre::Report> {
    let _ = stop_container_with_timeout(container_id, 30).await?;
    Ok(())
}

pub async fn protect_vm(vm_name: &str) -> Result<(), color_eyre::Report> {
    let _ = vm_name;
    Ok(())
}

pub async fn unprotect_vm(vm_name: &str) -> Result<(), color_eyre::Report> {
    let _ = vm_name;
    Ok(())
}

pub async fn delete_sandbox(container_id: &str, force: bool) -> Result<(), color_eyre::Report> {
    delete_container(container_id, force).await
}

pub async fn run_provision_script(
    container_id: &str,
    script_name: &str,
    engine_runtime: &str,
    model_name: &str,
    ctx_window: u32,
    mount_point: &std::path::Path,
    port: u16,
) -> Result<(), color_eyre::Report> {
    run_provision_container(
        container_id,
        script_name,
        engine_runtime,
        model_name,
        ctx_window,
        mount_point,
        port,
    )
    .await
}

async fn compute_specs_revision_hash(
    script_path: &Path,
    lib_dir: &Path,
) -> Result<String, color_eyre::Report> {
    let mut files = vec![script_path.to_path_buf()];
    files.extend(collect_regular_files_recursive(lib_dir)?);
    files.sort();

    let mut shasum_cmd = Command::new("shasum");
    shasum_cmd.args(["-a", "256"]);
    for file in &files {
        shasum_cmd.arg(file);
    }

    let output = shasum_cmd.output().await?;
    if !output.status.success() {
        return Err(color_eyre::eyre::eyre!(
            "failed to compute provision hash for script and library"
        ));
    }

    let mut second_pass = Command::new("shasum")
        .args(["-a", "256"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()?;
    if let Some(mut stdin) = second_pass.stdin.take() {
        stdin.write_all(&output.stdout).await?;
        stdin.shutdown().await?;
    }
    let second_output = second_pass.wait_with_output().await?;
    if !second_output.status.success() {
        return Err(color_eyre::eyre::eyre!(
            "failed to finalize provision hash digest"
        ));
    }

    let stdout = String::from_utf8_lossy(&second_output.stdout);
    let hash = stdout
        .split_whitespace()
        .next()
        .ok_or_else(|| color_eyre::eyre::eyre!("invalid shasum output"))?;
    Ok(hash.to_string())
}

fn collect_regular_files_recursive(root: &Path) -> Result<Vec<PathBuf>, color_eyre::Report> {
    let mut files = Vec::new();
    let mut dirs = vec![root.to_path_buf()];

    while let Some(dir) = dirs.pop() {
        for entry in std::fs::read_dir(&dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                dirs.push(path);
            } else if path.is_file() {
                files.push(path);
            }
        }
    }

    Ok(files)
}

async fn resolve_active_model_and_ctx(
    home: &str,
    server_port: u16,
    _engine_name: &str,
) -> (String, u32) {
    let default_model = crate::config::load()
        .ok()
        .and_then(|cfg| cfg.default_engine_profile)
        .filter(|m| !m.trim().is_empty())
        .unwrap_or_else(|| "mlx-community/Qwen3.5-9B-MLX-4bit".to_string());
    let preset_ctx_hint = 131072;

    let active_model_file = PathBuf::from(home).join(".cache/muthr/active-preset-name-mlxcel");
    let active_model_from_file = fs::read_to_string(&active_model_file)
        .await
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty());

    let fallback_model = active_model_from_file.unwrap_or_else(|| default_model.clone());

    let parsed_model = match crate::model::poll_loaded_model("127.0.0.1", server_port, 20, 1.0)
        .await
    {
        Ok(model) => model,
        Err(err) => {
            eprintln!(
                "warning: failed to poll loaded model from inference server, using fallback: {}",
                err
            );
            fallback_model.clone()
        }
    };
    let sanitized_model = if parsed_model.contains('/') || parsed_model.contains('\\') {
        std::path::Path::new(&parsed_model)
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or(&parsed_model)
            .to_string()
    } else {
        parsed_model.clone()
    };
    let active_model = if sanitized_model.trim().is_empty() {
        fallback_model
    } else {
        sanitized_model
    };
    let model_ctx_window = crate::model::get_ctx_window("127.0.0.1", server_port)
        .await
        .unwrap_or(preset_ctx_hint);
    let ctx_window = std::cmp::max(model_ctx_window, preset_ctx_hint);

    (active_model, ctx_window)
}

async fn discover_container_gateway() -> Option<String> {
    let output = Command::new("container")
        .args(["network", "list", "--format", "json"])
        .output()
        .await
        .ok()?;
    if !output.status.success() {
        return None;
    }

    let entries = serde_json::from_slice::<Vec<serde_json::Value>>(&output.stdout).ok()?;
    for entry in entries {
        let candidates = [
            entry.get("gateway"),
            entry.get("Gateway"),
            entry.get("status").and_then(|v| v.get("ipv4Gateway")),
            entry.get("status").and_then(|v| v.get("ipv6Gateway")),
            entry.get("status").and_then(|v| v.get("gateway")),
            entry.get("Status").and_then(|v| v.get("IPv4Gateway")),
            entry.get("Status").and_then(|v| v.get("IPv6Gateway")),
            entry.get("Status").and_then(|v| v.get("Gateway")),
            entry.get("ipam").and_then(|v| v.get("gateway")),
            entry.get("IPAM").and_then(|v| v.get("Gateway")),
            entry
                .get("subnets")
                .and_then(|v| v.as_array())
                .and_then(|arr| arr.first())
                .and_then(|v| v.get("gateway")),
            entry
                .get("Subnets")
                .and_then(|v| v.as_array())
                .and_then(|arr| arr.first())
                .and_then(|v| v.get("Gateway")),
        ];

        for candidate in candidates.into_iter().flatten() {
            if let Some(ip) = candidate.as_str()
                && !ip.trim().is_empty()
            {
                return Some(ip.trim().to_string());
            }
        }
    }

    None
}

async fn resolve_container_host_gateway() -> Result<String, color_eyre::Report> {
    let cfg = crate::config::load()?;
    let host = if let Some(configured) = cfg.container_host_gateway {
        configured.trim().to_string()
    } else if let Ok(env_host) = std::env::var("MUTHR_CONTAINER_HOST_GATEWAY") {
        env_host.trim().to_string()
    } else {
        discover_container_gateway()
            .await
            .ok_or_else(|| {
                color_eyre::eyre::eyre!(
                    "could not determine container host gateway; set MUTHR_CONTAINER_HOST_GATEWAY or container_host_gateway in config"
                )
            })?
    };

    if host.is_empty() {
        return Err(color_eyre::eyre::eyre!(
            "container host gateway resolved to an empty value"
        ));
    }

    Ok(host)
}

async fn backend_openai_url(port: u16) -> Result<String, color_eyre::Report> {
    let host = resolve_container_host_gateway().await?;

    Ok(format!("http://{}:{}/v1", host, port))
}

pub async fn start(profile_name: String) -> Result<(), color_eyre::Report> {
    start_container(profile_name).await
}

pub async fn stop() -> Result<(), color_eyre::Report> {
    stop_container().await
}

pub async fn ls(out_fmt: crate::OutputFormat) -> Result<(), color_eyre::Report> {
    list_containers(out_fmt).await
}

async fn start_container(profile_name: String) -> Result<(), color_eyre::Report> {
    let _lock =
        crate::lifecycle::acquire("container-lifecycle", std::time::Duration::from_secs(20))
            .await?;
    let (container_id, project_root, workdir) = resolve_workspace_context()?;
    eprintln!("info: target: {}", container_id);

    let mount_src = project_root
        .to_str()
        .ok_or_else(|| color_eyre::eyre::eyre!("workspace path contains invalid UTF-8"))?;

    let exists = container_exists(&container_id).await;
    if !exists {
        eprintln!("info: creating container {}", container_id);
        let volume = format!("{}:/workspace", mount_src);
        let status = Command::new("container")
            .args([
                "create",
                "--name",
                &container_id,
                "--detach",
                "--label",
                "muthr.managed=true",
                "--label",
                "muthr.owner=project",
                "--volume",
                &volume,
                "--workdir",
                "/workspace",
                "debian:13-slim",
                "sh",
                "-lc",
                "while true; do sleep 3600; done",
            ])
            .status()
            .await?;
        if !status.success() {
            return Err(color_eyre::eyre::eyre!(
                "failed to create container '{}' (run 'container system start' if the service is not running)",
                container_id
            ));
        }
    }

    if !container_is_running(&container_id).await {
        let status = Command::new("container")
            .args(["start", &container_id])
            .status()
            .await?;
        if !status.success() {
            return Err(color_eyre::eyre::eyre!(
                "failed to start container '{}'",
                container_id
            ));
        }
    }

    ensure_container_runtime_baseline(&container_id).await?;

    let guest_workdir = match workdir.strip_prefix(&project_root) {
        Ok(relative_workdir) => PathBuf::from("/workspace").join(relative_workdir),
        Err(_) => PathBuf::from("/workspace"),
    };
    let guest_workdir_str = guest_workdir
        .to_str()
        .ok_or_else(|| color_eyre::eyre::eyre!("guest workdir contains invalid UTF-8"))?;

    let home = std::env::var("HOME")?;
    let cfg = crate::config::load()?;
    let server_port = cfg.server_port.unwrap_or(8080);
    let engine_name = cfg.default_engine_runtime.as_deref().unwrap_or("mlxcel");
    let (active_model, ctx_window) =
        resolve_active_model_and_ctx(&home, server_port, engine_name).await;

    if profile_name != "base" {
        let cache_dir = PathBuf::from(&home)
            .join(".cache/muthr")
            .join(format!("{}-profiles", container_id));

        eprintln!("info: applying profile: {}", profile_name);
        run_provision_container(
            &container_id,
            &profile_name,
            engine_name,
            &active_model,
            ctx_window,
            Path::new("/workspace"),
            server_port,
        )
        .await?;

        let existing_profiles = fs::read_to_string(&cache_dir).await.unwrap_or_default();
        if !existing_profiles.lines().any(|l| l.trim() == profile_name) {
            let mut existing = existing_profiles;
            if !existing.is_empty() && !existing.ends_with('\n') {
                existing.push('\n');
            }
            existing.push_str(&profile_name);
            existing.push('\n');
            let Some(cache_parent) = cache_dir.parent() else {
                return Err(color_eyre::eyre::eyre!("invalid profile cache path"));
            };
            fs::create_dir_all(cache_parent).await?;
            fs::write(&cache_dir, existing).await?;
        }

        eprintln!("info: launching workspace context");
        let target_args = match profile_name.as_str() {
            "opencode" => vec!["opencode"],
            _ => vec![],
        };

        let requires_tty = profile_name == "opencode";
        run_container_session(&container_id, guest_workdir_str, &target_args, requires_tty)?;

        return Ok(());
    }

    let cache_dir = PathBuf::from(&home)
        .join(".cache/muthr")
        .join(format!("{}-profiles", container_id));
    if !cache_dir.exists() {
        let Some(cache_parent) = cache_dir.parent() else {
            return Err(color_eyre::eyre::eyre!("invalid profile cache path"));
        };
        fs::create_dir_all(cache_parent).await?;
        fs::write(&cache_dir, "base\n").await?;
    }

    eprintln!("info: container ready, launching shell");
    run_container_session(&container_id, guest_workdir_str, &["sh"], false)
        .map_err(|_| color_eyre::eyre::eyre!("shell session exited with error"))?;

    Ok(())
}

async fn run_provision_container(
    container_id: &str,
    script_name: &str,
    engine_runtime: &str,
    model_name: &str,
    ctx_window: u32,
    mount_point: &std::path::Path,
    port: u16,
) -> Result<(), color_eyre::Report> {
    fn validate_script_name(script_name: &str) -> Result<(), color_eyre::Report> {
        if script_name.is_empty() {
            return Err(color_eyre::eyre::eyre!("invalid profile name: empty"));
        }
        if script_name
            .chars()
            .any(|c| !(c.is_ascii_alphanumeric() || c == '-' || c == '_'))
        {
            return Err(color_eyre::eyre::eyre!(
                "invalid profile name: unsupported characters"
            ));
        }
        Ok(())
    }

    fn validate_engine_runtime(engine_runtime: &str) -> Result<(), color_eyre::Report> {
        if engine_runtime.is_empty() {
            return Err(color_eyre::eyre::eyre!("invalid runtime: empty"));
        }
        if engine_runtime
            .chars()
            .any(|c| !(c.is_ascii_alphanumeric() || c == '-' || c == '_'))
        {
            return Err(color_eyre::eyre::eyre!(
                "invalid runtime: unsupported characters"
            ));
        }
        Ok(())
    }

    validate_script_name(script_name)?;
    validate_engine_runtime(engine_runtime)?;

    let home = std::env::var("HOME")?;
    let host_script = PathBuf::from(&home).join(format!(
        ".config/muthr/sandbox.d/container/provision.d/{}.sh",
        script_name
    ));

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

    let mount_str = mount_point
        .to_str()
        .ok_or_else(|| color_eyre::eyre::eyre!("workspace mount path contains invalid UTF-8"))?;

    fn validate_env_value(value: &str, field: &str) -> Result<(), color_eyre::Report> {
        if value.contains('\0') || value.contains('\n') || value.contains('\r') {
            return Err(color_eyre::eyre::eyre!(
                "invalid value for {}: contains control characters",
                field
            ));
        }
        Ok(())
    }

    fn validate_model_name(model_name: &str) -> Result<(), color_eyre::Report> {
        if model_name.is_empty() {
            return Err(color_eyre::eyre::eyre!("invalid model name: empty"));
        }
        if model_name
            .chars()
            .any(|c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | ':' | '/')))
        {
            return Err(color_eyre::eyre::eyre!(
                "invalid model name: unsupported characters"
            ));
        }
        Ok(())
    }

    eprintln!("info: provisioning: {}", script_name);
    let host_gateway = resolve_container_host_gateway().await?;
    let openai_url = backend_openai_url(port).await?;
    let searxng_url = format!("http://{}:18766", host_gateway);
    validate_env_value(&openai_url, "MUTHR_OPENAI_URL")?;
    validate_env_value(&host_gateway, "MUTHR_CONTAINER_HOST_GATEWAY")?;
    validate_env_value(&searxng_url, "MUTHR_SEARXNG_URL")?;
    validate_env_value(model_name, "MUTHR_MODEL_NAME")?;
    validate_model_name(model_name)?;
    validate_env_value(mount_str, "MUTHR_WORKSPACE_MOUNT")?;
    validate_env_value(engine_runtime, "MUTHR_ENGINE_RUNTIME")?;

    let host_lib_dir = host_script
        .parent()
        .ok_or_else(|| color_eyre::eyre::eyre!("invalid provision script path"))?
        .join("lib");
    if !host_lib_dir.is_dir() {
        return Err(color_eyre::eyre::eyre!(
            "provision library directory not found: {:?}",
            host_lib_dir
        ));
    }

    let specs_rev = compute_specs_revision_hash(&host_script, &host_lib_dir).await?;
    let guest_provision_dir = format!("/tmp/muthr-provision-{}", script_name);
    let guest_script_path = format!("{}/{}.sh", guest_provision_dir, script_name);

    let mkdir_status = Command::new("container")
        .args(["exec", container_id, "mkdir", "-p", &guest_provision_dir])
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()
        .await?;
    if !mkdir_status.success() {
        return Err(color_eyre::eyre::eyre!(
            "failed to prepare guest provision directory"
        ));
    }

    let copy_script_status = Command::new("container")
        .args([
            "copy",
            host_script.to_str().ok_or_else(|| {
                color_eyre::eyre::eyre!("provision script path contains invalid UTF-8")
            })?,
            &format!("{}:{}", container_id, guest_script_path),
        ])
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()
        .await?;
    if !copy_script_status.success() {
        return Err(color_eyre::eyre::eyre!(
            "failed to copy provision script into container"
        ));
    }

    let copy_lib_status = Command::new("container")
        .args([
            "copy",
            host_lib_dir.to_str().ok_or_else(|| {
                color_eyre::eyre::eyre!("provision lib path contains invalid UTF-8")
            })?,
            &format!("{}:{}", container_id, guest_provision_dir),
        ])
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()
        .await?;
    if !copy_lib_status.success() {
        return Err(color_eyre::eyre::eyre!(
            "failed to copy provision library into container"
        ));
    }

    let mut child = Command::new("container")
        .args(["exec", "--workdir", "/tmp"])
        .arg("--user")
        .arg("muthr")
        .arg("--env")
        .arg(format!("MUTHR_OPENAI_URL={}", openai_url))
        .arg("--env")
        .arg(format!("MUTHR_MODEL_NAME={}", model_name))
        .arg("--env")
        .arg(format!("MUTHR_CTX_WINDOW={}", ctx_window))
        .arg("--env")
        .arg(format!("MUTHR_WORKSPACE_MOUNT={}", mount_str))
        .arg("--env")
        .arg(format!("MUTHR_SPECS_REV={}", specs_rev))
        .arg("--env")
        .arg(format!("MUTHR_CONTAINER_HOST_GATEWAY={}", host_gateway))
        .arg("--env")
        .arg(format!("MUTHR_SEARXNG_URL={}", searxng_url))
        .arg("--env")
        .arg(format!("MUTHR_ENGINE_RUNTIME={}", engine_runtime))
        .arg(container_id)
        .arg("bash")
        .arg(&guest_script_path)
        .stdin(Stdio::piped())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .kill_on_drop(true)
        .spawn()?;

    if let Some(ref mut stdin) = child.stdin {
        stdin.shutdown().await.ok();
    }
    std::mem::drop(child.stdin.take());

    let status = child.wait().await?;
    if !status.success() {
        return Err(color_eyre::eyre::eyre!("provision failed: {}", script_name));
    }

    eprintln!("info: provisioned: {}", script_name);
    Ok(())
}

async fn ensure_container_runtime_baseline(container_id: &str) -> Result<(), color_eyre::Report> {
    let marker = "/var/lib/muthr/container-baseline-v2";
    let has_marker = Command::new("container")
        .args([
            "exec",
            container_id,
            "sh",
            "-lc",
            &format!("test -f {}", marker),
        ])
        .status()
        .await?;
    if has_marker.success() {
        return Ok(());
    }

    let install_status = Command::new("container")
        .args([
            "exec",
            container_id,
            "sh",
            "-lc",
            "apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq bash curl ca-certificates sudo git nodejs npm && if ! id -u muthr >/dev/null 2>&1; then useradd -m -s /bin/bash muthr; fi && usermod -aG sudo muthr && install -d -m 755 /etc/sudoers.d && printf 'muthr ALL=(ALL) NOPASSWD:ALL\\n' >/etc/sudoers.d/muthr && chmod 0440 /etc/sudoers.d/muthr && (chown -R muthr:muthr /workspace || true)",
        ])
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()
        .await?;
    if !install_status.success() {
        return Err(color_eyre::eyre::eyre!(
            "failed to install container baseline dependencies"
        ));
    }

    let marker_status = Command::new("container")
        .args([
            "exec",
            container_id,
            "sh",
            "-lc",
            "mkdir -p /var/lib/muthr && touch /var/lib/muthr/container-baseline-v2",
        ])
        .status()
        .await?;
    if !marker_status.success() {
        eprintln!("warning: failed to persist container baseline marker");
    }

    Ok(())
}

async fn stop_container() -> Result<(), color_eyre::Report> {
    let _lock =
        crate::lifecycle::acquire("container-lifecycle", std::time::Duration::from_secs(20))
            .await?;
    let (container_id, _, _) = resolve_workspace_context()?;
    if !container_exists(&container_id).await {
        return Ok(());
    }

    if !container_is_running(&container_id).await {
        eprintln!("info: already stopped {}", container_id);
        return Ok(());
    }

    let status = Command::new("container")
        .args(["stop", &container_id])
        .status()
        .await?;
    if !status.success() {
        return Err(color_eyre::eyre::eyre!(
            "failed to stop container '{}'",
            container_id
        ));
    }

    eprintln!("info: stopped {}", container_id);
    Ok(())
}

async fn delete_container(container_id: &str, force: bool) -> Result<(), color_eyre::Report> {
    let _lock =
        crate::lifecycle::acquire("container-lifecycle", std::time::Duration::from_secs(20))
            .await?;
    delete_container_impl(container_id, force).await
}

async fn delete_container_impl(container_id: &str, force: bool) -> Result<(), color_eyre::Report> {
    if !force && !std::io::stdout().is_terminal() {
        eprintln!("error: terminal required for deletion, use --force to skip");
        std::process::exit(77);
    }

    if !container_exists(container_id).await {
        return Ok(());
    }

    if container_is_running(container_id).await && !force {
        let stop_status = Command::new("container")
            .args(["stop", container_id])
            .status()
            .await?;
        if !stop_status.success() {
            return Err(color_eyre::eyre::eyre!(
                "failed to stop container '{}' before deletion",
                container_id
            ));
        }
    }

    let mut args: Vec<&str> = vec!["delete"];
    if force {
        args.push("--force");
    }
    args.push(container_id);

    let status = Command::new("container").args(args).status().await?;
    if !status.success() {
        return Err(color_eyre::eyre::eyre!(
            "failed to delete container '{}'",
            container_id
        ));
    }

    eprintln!("info: deleted {}", container_id);
    Ok(())
}

async fn list_containers(out_fmt: crate::OutputFormat) -> Result<(), color_eyre::Report> {
    let Some(items) = container_list_all_json().await else {
        return Err(color_eyre::eyre::eyre!(
            "failed to list containers (run 'container system start' if the service is not running)"
        ));
    };

    let mut entries: Vec<(String, String, String)> = items
        .iter()
        .filter_map(|item| {
            let id = container_id_from_item(item)?;
            if !id.starts_with("muthr-") || id == "muthr-services" || id == "muthr-searxng" {
                return None;
            }
            let status = container_status_from_item(item).unwrap_or_else(|| "unknown".to_string());
            Some((id.clone(), status, "/workspace".to_string()))
        })
        .collect();

    entries.sort_by(|a, b| a.0.cmp(&b.0));

    if entries.is_empty() {
        if out_fmt == crate::OutputFormat::Text {
            eprintln!("no managed sandbox containers");
        } else if out_fmt == crate::OutputFormat::Json {
            println!("[]");
        }
        return Ok(());
    }

    if out_fmt == crate::OutputFormat::Json {
        let payload: Vec<serde_json::Value> = entries
            .iter()
            .map(|(name, status, mount)| {
                serde_json::json!({"name": name, "status": status, "mount": mount})
            })
            .collect();
        println!("{}", serde_json::to_string(&payload)?);
        return Ok(());
    }

    if out_fmt == crate::OutputFormat::Ndjson {
        for (name, status, mount) in &entries {
            let payload = serde_json::json!({"name": name, "status": status, "mount": mount});
            println!("{}", serde_json::to_string(&payload)?);
        }
        return Ok(());
    }

    for (name, status, mount) in &entries {
        eprintln!("  {:<30} {}  mount: {}", name, status, mount);
    }

    Ok(())
}