llmman 0.1.415

Run any agent on any model, models stored as OCI images
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
//! The backends `ensure_model` spawns: llama-server (local or in a
//! container), vLLM and vLLM-Omni, SGLang, and `mlx_lm.server`. Spawning,
//! the stderr tail that turns a failed load into an error message,
//! readiness polling, and where the `llama-server` binary itself comes
//! from.

use std::collections::VecDeque;
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex as StdMutex};

use anyhow::{anyhow, Context};
use reqwest::Client;
use tokio::io::{AsyncBufReadExt, AsyncRead, BufReader};
use tokio::time::{sleep, Duration, Instant};

use super::sched::parse_keep_alive_str;
use super::{canonical_ref, AppState, Engine, ModelProcess};
use crate::modelpack::{resolve_model, ModelPath};

/// `LLMMAN_SAFETENSORS_ENGINE`: which engine serves a
/// [`ModelPath::SafeTensors`] directory, the one format more than one
/// engine can. `Auto` (unset) is the pre-existing rule in
/// [`use_mlx_for_safetensors`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SafetensorsEngine {
    Auto,
    /// `vllm`, even where `mlx_lm.server` would otherwise be preferred.
    Vllm,
    /// `sglang` — see [`spawn_sglang_server`].
    Sglang,
}

pub(super) const SAFETENSORS_ENGINE_VAR: &str = "LLMMAN_SAFETENSORS_ENGINE";

/// `vllm`/`sglang` (any case); unset or empty is `Auto`; anything else
/// `None`, for the caller to warn about.
pub(super) fn parse_safetensors_engine(value: Option<&str>) -> Option<SafetensorsEngine> {
    let value = value.map(str::trim).unwrap_or_default();
    if value.is_empty() {
        return Some(SafetensorsEngine::Auto);
    }
    match value.to_ascii_lowercase().as_str() {
        "vllm" => Some(SafetensorsEngine::Vllm),
        "sglang" => Some(SafetensorsEngine::Sglang),
        _ => None,
    }
}

/// [`parse_safetensors_engine`] on the environment; an unrecognized value
/// is reported once and treated as `Auto`.
pub(super) fn safetensors_engine_from_env() -> SafetensorsEngine {
    static WARNED: std::sync::Once = std::sync::Once::new();
    let raw = std::env::var(SAFETENSORS_ENGINE_VAR).ok();
    parse_safetensors_engine(raw.as_deref()).unwrap_or_else(|| {
        WARNED.call_once(|| {
            eprintln!(
                "[llmman] warning: {SAFETENSORS_ENGINE_VAR}={:?} is not one of vllm/sglang; ignoring it",
                raw.unwrap_or_default()
            );
        });
        SafetensorsEngine::Auto
    })
}

/// Which local engine backs a resolved `ModelPath::SafeTensors`
/// directory when `LLMMAN_SAFETENSORS_ENGINE` is unset: `mlx_lm.server`
/// (see `spawn_mlx_server`) on macOS, `vllm` elsewhere. Every Mac is
/// taken to have Metal; `LLMMAN_SAFETENSORS_ENGINE=vllm` opts out.
///
/// Plain `vllm` (no plugin) has no Metal backend of its own at all — its
/// upstream-published macOS wheel is CPU-only. There *is* a way to make
/// `vllm serve` itself Metal-accelerated on Apple Silicon —
/// [vllm-metal](https://github.com/vllm-project/vllm-metal), an
/// installed-alongside `vllm.platform_plugins` plugin that overrides its
/// `CpuPlatform` autodetection with a real `MetalPlatform` (itself
/// implemented on top of MLX — see the `e2e` CI job's own "Install vLLM
/// (e2e)" step) — but it only supports a narrower set of model
/// families than `mlx_lm.server` does directly, and pulls in vLLM's own
/// full dependency footprint for a user who may not want any of the rest
/// of it. `mlx_lm.server` here is a separate, no-vLLM-at-all option: a
/// Mac gets real Metal acceleration through it without needing
/// vllm-metal (or vllm) at all.
pub(super) fn use_mlx_for_safetensors() -> bool {
    cfg!(target_os = "macos") && safetensors_engine_from_env() == SafetensorsEngine::Auto
}

pub(super) fn find_free_port() -> anyhow::Result<u16> {
    let l = TcpListener::bind("127.0.0.1:0")?;
    Ok(l.local_addr()?.port())
}

/// Shared handle onto the last few lines a spawned inference backend wrote
/// to stdout/stderr — see `spawn_tail_relay`'s own doc comment for why
/// this exists and `wait_for_ready`'s use of it.
pub(super) type OutputTail = Arc<StdMutex<VecDeque<String>>>;

/// How many trailing output lines `OutputTail` keeps — enough to catch a
/// one-or-two-line startup failure (a dynamic-linker error, "no such
/// file", an out-of-memory abort, ...) without holding onto an unbounded
/// amount of a chatty child's output.
const TAIL_LINES: usize = 20;

/// Relays a spawned child's piped stdout/stderr line-by-line to this
/// process's own stdout/stderr — preserving exactly what an inherited
/// (the previous default) stdio handle would have shown up as in
/// `llmman serve`'s own log (see daemon.rs's redirection of that to
/// serve.log) — while also appending each line to `tail` (bounded to the
/// last `TAIL_LINES`), so a caller that only learns of a crash after the
/// fact (see `wait_for_ready`) can still report *why*, instead of just
/// "the process exited" with the actual reason sitting only in a log file
/// the caller (an HTTP client, ultimately a chat UI) never sees.
fn spawn_tail_relay(
    reader: impl AsyncRead + Unpin + Send + 'static,
    tail: OutputTail,
    to_stderr: bool,
) {
    tokio::spawn(async move {
        let mut lines = BufReader::new(reader).lines();
        while let Ok(Some(line)) = lines.next_line().await {
            if to_stderr {
                eprintln!("{line}");
            } else {
                println!("{line}");
            }
            if let Ok(mut buf) = tail.lock() {
                if buf.len() >= TAIL_LINES {
                    buf.pop_front();
                }
                buf.push_back(line);
            }
        }
    });
}

pub(super) async fn spawn_llama_server(
    bin: &Path,
    model: &Path,
    mmproj: Option<&Path>,
    opts: crate::container::LlamaOptions<'_>,
) -> anyhow::Result<(tokio::process::Child, OutputTail)> {
    let crate::container::LlamaOptions {
        port,
        ctx_size,
        flash_attention,
        kv_cache_type,
        context_shift,
        split_mode,
        num_parallel,
        embeddings,
        batch_size,
        threads,
        // A local child shares the daemon's cgroup already.
        cpus: _,
    } = opts;
    let mut cmd = tokio::process::Command::new(bin);
    cmd.args([
        "--model",
        model.to_str().context("non-UTF-8 model path")?,
        "--port",
        &port.to_string(),
        "--host",
        "127.0.0.1",
    ]);
    // See ModelPath::mmproj's doc comment — enables llama-server to
    // actually act on `images` (vision) and serve
    // `/v1/audio/transcriptions` (audio) instead of silently ignoring
    // both.
    if let Some(mmproj) = mmproj {
        cmd.args([
            "--mmproj",
            mmproj.to_str().context("non-UTF-8 mmproj path")?,
        ]);
    }
    // `ctx_size` is already the effective value (see
    // context_length_from_env); `None` leaves --ctx-size unset, falling
    // back to n_ctx_train.
    if let Some(n) = ctx_size {
        cmd.args(["--ctx-size", &n.to_string()]);
    }
    // See flash_attention_from_env's doc comment; `None` leaves
    // --flash-attn unset, falling back to llama-server's own `auto`.
    if let Some(mode) = flash_attention {
        cmd.args(["--flash-attn", mode]);
    }
    // See kv_cache_type_from_env's doc comment; `None` leaves
    // --cache-type-k/-v unset, falling back to llama-server's own `f16`.
    if let Some(t) = kv_cache_type {
        cmd.args(["--cache-type-k", t, "--cache-type-v", t]);
    }
    // See supports_context_shift's doc comment.
    cmd.arg(if context_shift {
        "--context-shift"
    } else {
        "--no-context-shift"
    });
    // See sched_spread_from_env's doc comment; `None` leaves
    // --split-mode unset, falling back to llama-server's own `layer`.
    if let Some(mode) = split_mode {
        cmd.args(["--split-mode", mode]);
    }
    // See num_parallel_from_env's doc comment.
    if let Some(n) = num_parallel {
        cmd.args(["--parallel", &n.to_string()]);
    }
    // See threads_from_env_or_host's doc comment; `None` leaves
    // --threads unset, falling back to llama-server's own autodetection.
    if let Some(n) = threads {
        cmd.args(["--threads", &n.to_string()]);
    }
    // See LlamaOptions::embeddings and ::batch_size.
    if embeddings {
        cmd.arg("--embeddings");
    }
    if let Some(n) = batch_size {
        let n = n.to_string();
        cmd.args(["-b", &n, "-ub", &n]);
    }
    // See GPU_VISIBLE_DEVICE_VARS's own doc comment — already inherited
    // by default, forwarded explicitly here for clarity.
    for var in GPU_VISIBLE_DEVICE_VARS {
        if let Ok(val) = std::env::var(var) {
            cmd.env(var, val);
        }
    }
    // See LLAMA_CPP_ENV_PASSTHROUGH_VARS's doc comment.
    for var in LLAMA_CPP_ENV_PASSTHROUGH_VARS {
        if let Ok(val) = std::env::var(var) {
            cmd.env(var, val);
        }
    }
    crate::debug_log!("spawning {}: {:?}", bin.display(), cmd);
    // Piped (not inherited) so a startup crash's own explanation — e.g. a
    // dynamic linker's "error while loading shared libraries" — can be
    // captured into `tail` and surfaced by `wait_for_ready`, not just
    // dropped into a log file nobody making the request ever sees. See
    // `spawn_tail_relay`'s own doc comment for how this keeps showing up
    // in that log too.
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());
    let mut child = cmd
        .kill_on_drop(true)
        .spawn()
        .with_context(|| format!("spawn llama-server from {}", bin.display()))?;
    let tail = tail_child_output(&mut child);
    Ok((child, tail))
}

/// Takes `child`'s piped stdout/stderr and relays both through
/// [`spawn_tail_relay`], returning the shared tail.
pub(super) fn tail_child_output(child: &mut tokio::process::Child) -> OutputTail {
    let tail: OutputTail = Arc::new(StdMutex::new(VecDeque::with_capacity(TAIL_LINES)));
    if let Some(stdout) = child.stdout.take() {
        spawn_tail_relay(stdout, tail.clone(), false);
    }
    if let Some(stderr) = child.stderr.take() {
        spawn_tail_relay(stderr, tail.clone(), true);
    }
    tail
}

/// vLLM should only override its model-derived default for explicit
/// positive user input. This deliberately skips backend_ctx_size's
/// num_parallel scaling because vLLM's limit is per request, not split
/// across llama-server-style request slots.
pub(super) fn vllm_max_model_len(ctx_size: Option<u32>, ctx_size_explicit: bool) -> Option<u32> {
    ctx_size.filter(|n| ctx_size_explicit && *n > 0)
}

/// Extra argv appended to every `vllm serve` (plain and `--omni`, local
/// or in a container): the engine's own knobs, `--dtype bfloat16 --tp 2`.
pub(super) const VLLM_ARGS_VAR: &str = "LLMMAN_VLLM_ARGS";

/// The same for `sglang serve` / `sglang.launch_server`.
pub(super) const SGLANG_ARGS_VAR: &str = "LLMMAN_SGLANG_ARGS";

/// Splits an `LLMMAN_*_ARGS` value on whitespace, like `LLMMAN_SHELL` (no
/// quoting). Appended after llmman's own flags, so a repeated flag wins
/// on an argparse engine.
pub(super) fn split_extra_args(value: Option<&str>) -> Vec<String> {
    value
        .unwrap_or_default()
        .split_whitespace()
        .map(String::from)
        .collect()
}

/// [`split_extra_args`] on the environment variable `var`.
fn extra_args_from_env(var: &str) -> Vec<String> {
    split_extra_args(std::env::var(var).ok().as_deref())
}

/// argv after the `vllm` binary, shared with `container::spawn_engine`
/// (which passes its `/models` mount and `0.0.0.0`) and kept separate so
/// context forwarding is testable.
pub(super) fn vllm_serve_args(
    model_dir: &str,
    host: &str,
    port: u16,
    model_name: &str,
    max_model_len: Option<u32>,
) -> Vec<String> {
    let mut args = vec![
        "serve".into(),
        model_dir.into(),
        "--port".into(),
        port.to_string(),
        "--host".into(),
        host.into(),
        // Register the model under the same name used in API requests so
        // {"model": "<ref>"} is accepted by vllm's OpenAI-compatible API.
        "--served-model-name".into(),
        model_name.into(),
    ];
    if let Some(n) = max_model_len {
        args.push("--max-model-len".into());
        args.push(n.to_string());
    }
    args
}

/// [`vllm_serve_args`] plus `LLMMAN_VLLM_ARGS`.
pub(super) fn vllm_serve_args_from_env(
    model_dir: &str,
    host: &str,
    port: u16,
    model_name: &str,
    max_model_len: Option<u32>,
) -> Vec<String> {
    let mut args = vllm_serve_args(model_dir, host, port, model_name, max_model_len);
    args.extend(extra_args_from_env(VLLM_ARGS_VAR));
    args
}

/// `<bin> <args>` in its own process group, so [`ModelProcess`]'s Drop can
/// kill the engine's whole worker tree (not just this pid) without
/// killing us. vllm and sglang both fork workers.
fn grouped_command(bin: &Path, args: Vec<String>) -> tokio::process::Command {
    let mut cmd = tokio::process::Command::new(bin);
    cmd.args(args).kill_on_drop(true);
    #[cfg(unix)]
    cmd.process_group(0);
    cmd
}

pub(super) async fn spawn_vllm_server(
    model_dir: &Path,
    port: u16,
    model_name: &str,
    max_model_len: Option<u32>,
) -> anyhow::Result<tokio::process::Child> {
    let vllm = which_binary("vllm")?;
    let args = vllm_serve_args_from_env(
        model_dir.to_str().context("non-UTF-8 model path")?,
        "127.0.0.1",
        port,
        model_name,
        max_model_len,
    );
    let mut cmd = grouped_command(&vllm, args);
    crate::debug_log!("spawning {}: {:?}", vllm.display(), cmd);
    cmd.spawn()
        .with_context(|| format!("spawn vllm from {}", vllm.display()))
}

/// Set (`1`/`true`/...) to keep Cosmos3's safety guardrails on under
/// vLLM-Omni; see [`vllm_omni_serve_args`].
const VLLM_OMNI_GUARDRAILS_VAR: &str = "LLMMAN_VLLM_OMNI_GUARDRAILS";

/// argv after `vllm` for a [`ModelPath::Omni`] model: [`vllm_serve_args`]
/// plus `--omni` (the vLLM-Omni plugin picks the pipeline from
/// `model_index.json`), no `--max-model-len` (no context window).
///
/// `--no-guardrails` unless `LLMMAN_VLLM_OMNI_GUARDRAILS` is set: Cosmos3's
/// guardrails need the `cosmos-guardrail` package and a runtime download of
/// the gated `nvidia/Cosmos-1.0-Guardrail`, and vLLM-Omni refuses to start
/// without them — a model served from llmman's store has neither.
/// `--init-timeout` mirrors llmman's load deadline so vLLM-Omni's own
/// (10 minutes) does not give up first.
fn vllm_omni_serve_args(
    model_dir: &str,
    host: &str,
    port: u16,
    model_name: &str,
    guardrails: bool,
    init_timeout: Duration,
) -> Vec<String> {
    let mut args = vllm_serve_args(model_dir, host, port, model_name, None);
    args.push("--omni".into());
    if !guardrails {
        args.push("--no-guardrails".into());
    }
    args.push("--init-timeout".into());
    args.push(init_timeout.as_secs().max(1).to_string());
    args
}

/// [`vllm_omni_serve_args`] from the environment, plus `LLMMAN_VLLM_ARGS`;
/// an unbounded `LLMMAN_LOAD_TIMEOUT` becomes a day.
pub(super) fn vllm_omni_serve_args_from_env(
    model_dir: &str,
    host: &str,
    port: u16,
    model_name: &str,
) -> Vec<String> {
    let guardrails = crate::env_flag_set(VLLM_OMNI_GUARDRAILS_VAR);
    let init_timeout = load_timeout_from_env().unwrap_or(Duration::from_secs(24 * 3600));
    let mut args =
        vllm_omni_serve_args(model_dir, host, port, model_name, guardrails, init_timeout);
    args.extend(extra_args_from_env(VLLM_ARGS_VAR));
    args
}

/// `vllm serve --omni` from the `vllm` on `PATH`.
pub(super) async fn spawn_vllm_omni_server(
    model_dir: &Path,
    port: u16,
    model_name: &str,
) -> anyhow::Result<(tokio::process::Child, OutputTail)> {
    let vllm = which_binary("vllm")?;
    if !vllm_has_omni_plugin(&vllm).await {
        anyhow::bail!(
            "{} has no vllm-omni plugin, which a Diffusers-layout model needs \
             (`uv pip install vllm-omni` into the same environment, or serve it \
             with --runtime docker to use the vllm/vllm-omni image)",
            vllm.display()
        );
    }
    let args = vllm_omni_serve_args_from_env(
        model_dir.to_str().context("non-UTF-8 model path")?,
        "127.0.0.1",
        port,
        model_name,
    );
    spawn_piped(grouped_command(&vllm, args), &vllm, "vllm --omni")
}

/// Spawns `cmd` with stdio piped, like a llama-server's, so a startup
/// failure's reason reaches `wait_for_ready` through the returned tail.
fn spawn_piped(
    mut cmd: tokio::process::Command,
    bin: &Path,
    what: &str,
) -> anyhow::Result<(tokio::process::Child, OutputTail)> {
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());
    crate::debug_log!("spawning {}: {:?}", bin.display(), cmd);
    let mut child = cmd
        .spawn()
        .with_context(|| format!("spawn {what} from {}", bin.display()))?;
    let tail = tail_child_output(&mut child);
    Ok((child, tail))
}

/// The name SGLang registers `model_ref` under. SGLang reads `:` in
/// `--served-model-name` and in a request's `model` as its
/// `model:lora-adapter` separator, so a reference's `:tag` becomes `-tag`;
/// `backend_wire_model` rewrites requests to match.
pub(super) fn sglang_served_model_name(model_ref: &str) -> String {
    model_ref.replace(':', "-")
}

/// argv after SGLang's launcher (`sglang serve` locally, `python3 -m
/// sglang.launch_server` in the `lmsysorg/sglang` image): the same shape
/// as [`vllm_serve_args`] in SGLang's spelling, with `--context-length`
/// fed by the [`vllm_max_model_len`] rule.
pub(super) fn sglang_serve_args(
    model_dir: &str,
    host: &str,
    port: u16,
    model_name: &str,
    context_length: Option<u32>,
) -> Vec<String> {
    let mut args = vec![
        "--model-path".into(),
        model_dir.into(),
        "--port".into(),
        port.to_string(),
        "--host".into(),
        host.into(),
        "--served-model-name".into(),
        sglang_served_model_name(model_name),
    ];
    if let Some(n) = context_length {
        args.push("--context-length".into());
        args.push(n.to_string());
    }
    args
}

/// [`sglang_serve_args`] plus `LLMMAN_SGLANG_ARGS`.
pub(super) fn sglang_serve_args_from_env(
    model_dir: &str,
    host: &str,
    port: u16,
    model_name: &str,
    context_length: Option<u32>,
) -> Vec<String> {
    let mut args = sglang_serve_args(model_dir, host, port, model_name, context_length);
    args.extend(extra_args_from_env(SGLANG_ARGS_VAR));
    args
}

/// `sglang serve <args>` from the `sglang` console script on `PATH`, in
/// its own process group like vllm (it forks a scheduler and detokenizer).
pub(super) async fn spawn_sglang_server(
    model_dir: &Path,
    port: u16,
    model_name: &str,
    context_length: Option<u32>,
) -> anyhow::Result<(tokio::process::Child, OutputTail)> {
    let sglang = which_binary("sglang").map_err(|e| {
        anyhow!(
            "{e} (`uv pip install sglang` puts it there, or drop {SAFETENSORS_ENGINE_VAR}=sglang \
             to serve this model with vllm)"
        )
    })?;
    let mut args = vec!["serve".to_string()];
    args.extend(sglang_serve_args_from_env(
        model_dir.to_str().context("non-UTF-8 model path")?,
        "127.0.0.1",
        port,
        model_name,
        context_length,
    ));
    spawn_piped(grouped_command(&sglang, args), &sglang, "sglang")
}

/// Longest [`vllm_has_omni_plugin`] waits before assuming yes.
const OMNI_PLUGIN_PROBE_TIMEOUT: Duration = Duration::from_secs(60);

/// Whether the Python behind the `vllm` console script can `import
/// vllm_omni` — a clear error up front instead of vLLM's "unrecognized
/// arguments: --omni" after importing torch. When the launcher is not a
/// `#!/path/to/python` script, or the probe fails or stalls, the answer
/// is yes and vLLM itself reports.
async fn vllm_has_omni_plugin(vllm: &Path) -> bool {
    let Some(python) = console_script_interpreter(vllm) else {
        return true;
    };
    let probe = tokio::process::Command::new(&python)
        .args(["-c", "import vllm_omni"])
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .kill_on_drop(true)
        .status();
    match tokio::time::timeout(OMNI_PLUGIN_PROBE_TIMEOUT, probe).await {
        Ok(Ok(status)) => status.success(),
        Ok(Err(_)) | Err(_) => true,
    }
}

/// The interpreter of a `#!/path/to/python` script (not `#!/usr/bin/env`).
fn console_script_interpreter(script: &Path) -> Option<PathBuf> {
    let mut head = [0u8; 512];
    let n = std::fs::File::open(script)
        .and_then(|mut f| std::io::Read::read(&mut f, &mut head))
        .ok()?;
    let first = std::str::from_utf8(&head[..n]).ok()?.lines().next()?;
    let interp = first.strip_prefix("#!")?.split_whitespace().next()?;
    (!interp.ends_with("/env") && interp.contains("python")).then(|| PathBuf::from(interp))
}

/// Spawns `mlx_lm.server` (<https://github.com/ml-explore/mlx-lm>) —
/// Apple Silicon's own Metal-accelerated alternative to `vllm` for a
/// [`ModelPath::SafeTensors`] directory, picked instead of it by
/// [`use_mlx_for_safetensors`]. The binary is chosen the way `--runtime`
/// chooses `llama-server` (see [`mlx_source`]); normally installed at
/// daemon startup, here only if that failed.
///
/// Deliberately does *not* pass `mlx_lm.server`'s own `--model` flag,
/// even though that's its documented way to preload one: confirmed
/// against its own `server.py` that doing so loads the model in a
/// background thread (`ResponseGenerator.__init__`'s
/// `Thread(target=self._generate)`) with no `try`/`except` anywhere
/// around that particular load — a bad model directory would silently
/// kill only that one thread, not this process, while its
/// `ThreadingHTTPServer` (started right alongside it, not after) keeps
/// right on reporting `/health` as ready regardless. `wait_for_ready`
/// would then report this backend ready, and every real request queued
/// behind that dead thread would hang forever instead of ever seeing an
/// error.
///
/// Loading instead happens on the *first real request* — every caller
/// sends this model's actual absolute directory path (not its
/// human-readable reference) as that request's own `"model"` field, via
/// [`backend_wire_model`](super::backend_wire_model) — which goes through `ModelProvider.load`'s
/// own `try`/`except` in the request-handling path instead, and so does
/// report a real error back to that request on a bad model directory.
pub(super) async fn spawn_mlx_server(
    state: &AppState,
    port: u16,
) -> anyhow::Result<tokio::process::Child> {
    let mlx =
        match mlx_source(state.0.runtime.requested()) {
            None => which_binary("mlx_lm.server").context("--runtime path")?,
            Some(fallback) => tokio::task::spawn_blocking(move || {
                crate::mlx_release::ensure_mlx_server(fallback)
            })
            .await
            .context("ensure mlx_lm.server task panicked")?
            .map_err(|e| {
                anyhow!("{e:#} (set {SAFETENSORS_ENGINE_VAR}=vllm to serve this model with vllm)")
            })?,
        };
    let mut cmd = tokio::process::Command::new(&mlx);
    cmd.args(["--port", &port.to_string(), "--host", "127.0.0.1"]);
    cmd.kill_on_drop(true)
        .spawn()
        .with_context(|| format!("spawn mlx_lm.server from {}", mlx.display()))
}

/// How `runtime` sources `mlx_lm.server`, mirroring `llama-server`:
/// `None` is `PATH` only (`path`); otherwise llmman's own install, with
/// or without a `PATH` fallback (`auto` and `bin`). Container runtimes
/// never reach mlx (Linux only) and get `bin`'s answer.
pub(super) fn mlx_source(runtime: super::runtime::Runtime) -> Option<crate::mlx_release::Fallback> {
    use super::runtime::Runtime;
    use crate::mlx_release::Fallback;
    match runtime {
        Runtime::Path => None,
        Runtime::Auto => Some(Fallback::Path),
        Runtime::Bin | Runtime::Docker | Runtime::Podman => Some(Fallback::None),
    }
}

fn which_binary(name: &str) -> anyhow::Result<PathBuf> {
    crate::find_on_path(name).ok_or_else(|| anyhow::anyhow!("{name} not found on PATH"))
}

/// [`wait_for_ready`]'s default deadline — longer than Ollama's own 5m
/// default since vllm can take several minutes to load a large model.
/// Overridable via `LLMMAN_LOAD_TIMEOUT`.
const DEFAULT_LOAD_TIMEOUT: Duration = Duration::from_secs(600);

/// `None` = wait forever, from an `LLMMAN_LOAD_TIMEOUT` of 0 or
/// negative (mirrors Ollama's `OLLAMA_LOAD_TIMEOUT`).
fn load_timeout_from_env() -> Option<Duration> {
    match std::env::var("LLMMAN_LOAD_TIMEOUT") {
        Ok(v) => parse_load_timeout(&v).unwrap_or(Some(DEFAULT_LOAD_TIMEOUT)),
        Err(_) => Some(DEFAULT_LOAD_TIMEOUT),
    }
}

/// Reuses [`parse_keep_alive_str`]'s duration syntax, but unlike
/// keep_alive, a zero value also means "forever" here (matches
/// `OLLAMA_LOAD_TIMEOUT`'s documented behavior). Unlike a plain
/// delegation, a leading `-` is only treated as "forever" once the
/// magnitude after it actually parses as a duration —
/// `parse_keep_alive_str`'s own dash-prefix shortcut accepts any
/// `"-..."` unconditionally, which would otherwise make a typo like
/// `LLMMAN_LOAD_TIMEOUT=-garbage` disable the timeout forever instead of
/// falling back to the documented default.
fn parse_load_timeout(value: &str) -> Option<Option<Duration>> {
    let trimmed = value.trim();
    if let Some(magnitude) = trimmed.strip_prefix('-') {
        return parse_keep_alive_str(magnitude).map(|_| None);
    }
    Some(match parse_keep_alive_str(trimmed)? {
        Some(d) if d.is_zero() => None,
        other => other,
    })
}

/// Poll interval between `/health` checks in [`wait_for_ready`].
pub(super) const POLL_INTERVAL: Duration = Duration::from_millis(500);

/// How long one `/health` request in [`wait_for_ready`] may take. Longer
/// than [`POLL_INTERVAL`]: SGLang's `/health` runs a one-token generation,
/// which on CPU takes about as long as the interval — bounded by it, every
/// poll timed out and the load never became ready (seen in CI).
const HEALTH_TIMEOUT: Duration = Duration::from_secs(30);

/// Polls `process`'s `/health` endpoint until ready, bailing out early
/// if `process` itself exits first (so a crash-on-startup doesn't hang
/// the caller for the whole deadline). `stderr_tail`, when given (every
/// piped child — see `ensure_model`), includes the crash reason in the
/// error.
pub(super) async fn wait_for_ready(
    client: &Client,
    port: u16,
    process: &mut ModelProcess,
    stderr_tail: Option<&OutputTail>,
) -> anyhow::Result<()> {
    let url = format!("http://127.0.0.1:{port}/health");
    // `None` = wait forever (LLMMAN_LOAD_TIMEOUT of 0 or negative, or a
    // value so large that adding it to `Instant::now()` would overflow
    // — `checked_add`, not `+`, so a huge-but-validly-parsed timeout
    // can't panic the request task).
    let load_timeout = load_timeout_from_env();
    let deadline = load_timeout.and_then(|d| Instant::now().checked_add(d));
    loop {
        let remaining = deadline.map(|d| d.saturating_duration_since(Instant::now()));
        if remaining.is_some_and(|r| r.is_zero()) {
            return Err(anyhow!(
                "inference server on port {port} did not become ready within {:?}",
                load_timeout.unwrap_or_default()
            ));
        }
        if !process.is_alive() {
            let detail = stderr_tail.and_then(|t| {
                let lines = t.lock().ok()?;
                (!lines.is_empty()).then(|| lines.iter().cloned().collect::<Vec<_>>().join(" | "))
            });
            return Err(match detail {
                Some(detail) => anyhow!(
                    "inference server on port {port} exited before becoming ready: {detail}"
                ),
                None => anyhow!("inference server on port {port} exited before becoming ready"),
            });
        }
        // Bound the request by HEALTH_TIMEOUT, not the full remaining
        // deadline — otherwise a /health that connects but then stalls
        // could occupy up to the whole deadline (or forever, if unset)
        // without rechecking process liveness or the deadline.
        let bound = remaining.map_or(HEALTH_TIMEOUT, |r| r.min(HEALTH_TIMEOUT));
        let attempt_start = Instant::now();
        if let Ok(resp) = client.get(&url).timeout(bound).send().await {
            // llama-server/vllm: 200 once loaded. mlx_lm.server: 200 as
            // soon as its listener is up, not once a model is loaded
            // (see spawn_mlx_server) — an accepted, documented gap for
            // that one engine only.
            if resp.status().is_success() {
                return Ok(());
            }
        }
        // Only the unused remainder of one POLL_INTERVAL — not another
        // full one on top of whatever the attempt above already took —
        // so a consistently-stalling /health still gets rechecked every
        // POLL_INTERVAL, not every 2x that. Still never past the
        // overall deadline either.
        let sleep_for = POLL_INTERVAL.saturating_sub(attempt_start.elapsed());
        let remaining = deadline.map(|d| d.saturating_duration_since(Instant::now()));
        sleep(remaining.map_or(sleep_for, |r| sleep_for.min(r))).await;
    }
}

/// GPU device-selection vars Ollama documents. A local `llama-server`
/// child inherits these for free; forwarded explicitly here so
/// `crate::container::spawn`'s `docker run`/`podman run` (which does
/// *not* inherit the host env) can reuse the same list.
pub const GPU_VISIBLE_DEVICE_VARS: &[&str] = &[
    "CUDA_VISIBLE_DEVICES",
    "HIP_VISIBLE_DEVICES",
    "ROCR_VISIBLE_DEVICES",
    "GGML_VK_VISIBLE_DEVICES",
    "GPU_DEVICE_ORDINAL",
    "HSA_OVERRIDE_GFX_VERSION",
];

/// llama.cpp's own env-configurable arguments (`common/arg.cpp`'s
/// `set_env`), forwarded the same way as [`GPU_VISIBLE_DEVICE_VARS`] —
/// llama-server reads these itself, llmman just makes sure they reach it.
pub const LLAMA_CPP_ENV_PASSTHROUGH_VARS: &[&str] = &[
    "LLAMA_ARG_FIT",
    "LLAMA_ARG_FIT_TARGET",
    "LLAMA_ARG_THREADS",
    "LLAMA_ARG_N_GPU_LAYERS",
];

/// If `model_ref` would be served by `Engine::Mlx` were it loaded right
/// now, returns its canonical name (see `ensure_model`'s own doc
/// comment on why that can differ from the caller's own input) —
/// *without* spawning any backend process or loading any weights.
/// Checks the already-running case first (a cheap map lookup); if it
/// isn't running, resolves it to a `ModelPath` — extracting/locating
/// its files on disk if it's already in the local store, but never
/// spawning a process — and applies the exact same
/// `ModelPath::SafeTensors` + `use_mlx_for_safetensors()` rule
/// `ensure_model` itself uses to pick an engine.
///
/// Returns `None` — "don't reject early", not "definitely not mlx" —
/// for a model that isn't in the local store at all yet (nothing to
/// resolve without also pulling it first, which this deliberately
/// never does) or that fails to resolve for any other reason:
/// `ensure_model` is still the right place to actually pull, load, and
/// (if it turns out to be `Engine::Mlx` after all) reject that one
/// first real request — this is only a cheap pre-check for the
/// overwhelmingly common repeat-request case, not a full substitute
/// for it.
///
/// Used only by `proxy_openai_passthrough`'s own `/v1/embeddings`
/// guard, so an already-pulled (or already-loaded) MLX-served model
/// doesn't pay for a full `mlx_lm.server` spawn and weights load on
/// every single embeddings request that could never succeed there
/// anyway — only ever the very first one, against a model that isn't
/// locally resolvable at all yet.
pub(super) async fn would_use_mlx(state: &AppState, model_ref: &str) -> Option<String> {
    // An invalid reference is never locally resolvable, so treat it like any
    // other unresolvable case: return None and let ensure_model reject it.
    let model_ref = crate::shortnames::resolve_ollama_api(model_ref).ok()?;
    let model_ref = crate::storage::default_tag(&model_ref);
    let model_ref = canonical_ref(&state.0.store_path, &model_ref);

    {
        let mgr = state.0.manager.lock().await;
        if let Some(running) = mgr.running.get(&model_ref) {
            return matches!(running.process, ModelProcess::Local(Engine::Mlx, _, _))
                .then(|| model_ref.clone());
        }
    }

    if !use_mlx_for_safetensors() {
        return None;
    }
    let store_path = state.0.store_path.clone();
    let cache_path = state.0.cache_path.clone();
    let lookup_ref = model_ref.clone();
    let is_safetensors = tokio::task::spawn_blocking(move || {
        resolve_model(&store_path, &cache_path, &lookup_ref)
            .map(|p| matches!(p, ModelPath::SafeTensors(_)))
            .unwrap_or(false)
    })
    .await
    .unwrap_or(false);
    is_safetensors.then_some(model_ref)
}

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

    #[test]
    fn parse_load_timeout_accepts_the_same_duration_syntax_as_keep_alive() {
        assert_eq!(
            parse_load_timeout("300"),
            Some(Some(Duration::from_secs(300)))
        );
        assert_eq!(
            parse_load_timeout("10m"),
            Some(Some(Duration::from_secs(600)))
        );
        assert_eq!(parse_load_timeout("garbage"), None);
    }

    #[test]
    fn parse_load_timeout_treats_zero_or_negative_as_infinite() {
        // Unlike keep_alive (where 0 means "unload immediately"),
        // OLLAMA_LOAD_TIMEOUT documents 0 as meaning "wait forever", same
        // as any negative value.
        assert_eq!(parse_load_timeout("0"), Some(None));
        assert_eq!(parse_load_timeout("-1"), Some(None));
        assert_eq!(parse_load_timeout("-10m"), Some(None));
    }

    #[test]
    fn parse_load_timeout_rejects_a_dash_prefixed_non_duration_instead_of_disabling_forever() {
        // A bare "starts with '-'" isn't enough — the magnitude must
        // actually parse as a duration, or this must fall through to
        // the default (via load_timeout_from_env's own unwrap_or), not
        // silently disable the timeout forever.
        assert_eq!(parse_load_timeout("-garbage"), None);
        assert_eq!(parse_load_timeout("-"), None);
    }

    #[test]
    fn vllm_max_model_len_uses_only_explicit_ctx_size() {
        assert_eq!(vllm_max_model_len(Some(4096), true), Some(4096));
        assert_eq!(vllm_max_model_len(Some(0), true), None);
        assert_eq!(vllm_max_model_len(Some(65536), false), None);
        assert_eq!(vllm_max_model_len(None, true), None);
        assert_eq!(vllm_max_model_len(None, false), None);
    }

    #[test]
    fn vllm_serve_args_handles_max_model_len() {
        for (max_model_len, expected) in [
            (Some(256), Some("256")),
            (Some(1024), Some("1024")),
            (Some(4096), Some("4096")),
            (None, None),
        ] {
            let args = vllm_serve_args(
                "/models/qwen",
                "127.0.0.1",
                8000,
                "qwen3.5:0.8b",
                max_model_len,
            );
            let pos = args.iter().position(|arg| arg == "--max-model-len");

            match expected {
                Some(value) => {
                    let i = pos.expect("--max-model-len should be present");
                    assert_eq!(args.get(i + 1).map(String::as_str), Some(value));
                }
                None => assert!(pos.is_none()),
            }
        }
    }

    /// Local and container `vllm serve` argv differ only in dir and host.
    #[test]
    fn vllm_serve_args_differ_between_local_and_container_only_in_dir_and_host() {
        let local = vllm_serve_args("/cache/abc/model", "127.0.0.1", 8000, "m", Some(4096));
        let container = vllm_serve_args("/models", "0.0.0.0", 8000, "m", Some(4096));
        assert_eq!(local[0], "serve");
        assert_eq!(local[1], "/cache/abc/model");
        assert_eq!(container[1], "/models");
        let host = |args: &[String]| {
            let i = args.iter().position(|a| a == "--host").unwrap();
            args[i + 1].clone()
        };
        assert_eq!(host(&local), "127.0.0.1");
        assert_eq!(host(&container), "0.0.0.0");
        let rest = |args: &[String]| {
            let i = args.iter().position(|a| a == "--host").unwrap();
            [&args[2..i], &args[i + 2..]].concat()
        };
        assert_eq!(rest(&local), rest(&container));
    }

    #[test]
    fn vllm_omni_serve_args_add_omni_and_disable_guardrails_by_default() {
        let args = vllm_omni_serve_args(
            "/models",
            "0.0.0.0",
            8000,
            "nvidia/Cosmos3-Edge",
            false,
            Duration::from_secs(600),
        );
        // vllm-omni's own recipe: `vllm serve <model> --omni --host --port`
        assert_eq!(args[0], "serve");
        assert_eq!(args[1], "/models");
        assert!(args.contains(&"--omni".to_string()));
        assert!(args.contains(&"--no-guardrails".to_string()));
        let i = args.iter().position(|a| a == "--init-timeout").unwrap();
        assert_eq!(args[i + 1], "600");
        let i = args
            .iter()
            .position(|a| a == "--served-model-name")
            .unwrap();
        assert_eq!(args[i + 1], "nvidia/Cosmos3-Edge");
        // a diffusion pipeline has no context window
        assert!(!args.contains(&"--max-model-len".to_string()));
    }

    #[test]
    fn vllm_omni_serve_args_keep_guardrails_when_asked() {
        let args = vllm_omni_serve_args("/m", "127.0.0.1", 8000, "m", true, Duration::from_secs(1));
        assert!(args.contains(&"--omni".to_string()));
        assert!(!args.contains(&"--no-guardrails".to_string()));
    }

    #[test]
    fn parse_safetensors_engine_accepts_vllm_sglang_or_nothing() {
        assert_eq!(
            parse_safetensors_engine(None),
            Some(SafetensorsEngine::Auto)
        );
        assert_eq!(
            parse_safetensors_engine(Some("")),
            Some(SafetensorsEngine::Auto)
        );
        assert_eq!(
            parse_safetensors_engine(Some("  ")),
            Some(SafetensorsEngine::Auto)
        );
        assert_eq!(
            parse_safetensors_engine(Some("vllm")),
            Some(SafetensorsEngine::Vllm)
        );
        assert_eq!(
            parse_safetensors_engine(Some("SGLang")),
            Some(SafetensorsEngine::Sglang)
        );
        assert_eq!(
            parse_safetensors_engine(Some(" sglang ")),
            Some(SafetensorsEngine::Sglang)
        );
        // Unknown names are reported by the caller, not silently mapped.
        assert_eq!(parse_safetensors_engine(Some("mlx")), None);
        assert_eq!(parse_safetensors_engine(Some("tgi")), None);
    }

    #[test]
    fn split_extra_args_splits_on_whitespace_only() {
        assert_eq!(split_extra_args(None), Vec::<String>::new());
        assert_eq!(split_extra_args(Some("")), Vec::<String>::new());
        assert_eq!(split_extra_args(Some("   \t ")), Vec::<String>::new());
        assert_eq!(
            split_extra_args(Some("  --dtype bfloat16\t--enforce-eager\n--tp 2 ")),
            ["--dtype", "bfloat16", "--enforce-eager", "--tp", "2"]
        );
        // No shell quoting: a quoted value is passed with its quotes.
        assert_eq!(
            split_extra_args(Some("--chat-template 'a b'")),
            ["--chat-template", "'a", "b'"]
        );
    }

    #[test]
    fn sglang_serve_args_speak_sglangs_flag_names() {
        let args = sglang_serve_args("/models", "0.0.0.0", 30000, "qwen3.5:0.8b", Some(4096));
        // SGLang's own recipe: `--model-path <dir> --host --port`, no
        // positional model and no `serve` subcommand here (the launcher
        // prefix differs between a local `sglang serve` and the image's
        // `python3 -m sglang.launch_server`).
        assert_eq!(&args[..2], &["--model-path", "/models"]);
        assert!(!args.contains(&"serve".to_string()));
        let value = |flag: &str| {
            let i = args.iter().position(|a| a == flag).unwrap();
            args[i + 1].clone()
        };
        assert_eq!(value("--host"), "0.0.0.0");
        assert_eq!(value("--port"), "30000");
        // `:` is SGLang's LoRA-adapter separator (see sglang_served_model_name).
        assert_eq!(value("--served-model-name"), "qwen3.5-0.8b");
        assert_eq!(value("--context-length"), "4096");
        assert!(!args.contains(&"--max-model-len".to_string()));
    }

    #[test]
    fn sglang_served_model_name_drops_the_colon_sglang_reserves() {
        assert_eq!(
            sglang_served_model_name("docker.io/ai/qwen3.5:0.8b-safetensors"),
            "docker.io/ai/qwen3.5-0.8b-safetensors"
        );
        assert_eq!(
            sglang_served_model_name("hf.co/HuggingFaceTB/SmolLM2-135M-Instruct:latest"),
            "hf.co/HuggingFaceTB/SmolLM2-135M-Instruct-latest"
        );
    }

    #[test]
    fn sglang_serve_args_leave_context_length_to_the_model_when_unset() {
        let args = sglang_serve_args("/models", "127.0.0.1", 30000, "m", None);
        assert!(!args.contains(&"--context-length".to_string()));
    }

    /// Local and container SGLang argv differ only in dir and host, like
    /// vLLM's.
    #[test]
    fn sglang_serve_args_differ_between_local_and_container_only_in_dir_and_host() {
        let local = sglang_serve_args("/cache/abc/model", "127.0.0.1", 30000, "m", Some(4096));
        let container = sglang_serve_args("/models", "0.0.0.0", 30000, "m", Some(4096));
        assert_eq!(local[1], "/cache/abc/model");
        assert_eq!(container[1], "/models");
        let host = |args: &[String]| {
            let i = args.iter().position(|a| a == "--host").unwrap();
            args[i + 1].clone()
        };
        assert_eq!(host(&local), "127.0.0.1");
        assert_eq!(host(&container), "0.0.0.0");
        let rest = |args: &[String]| {
            let i = args.iter().position(|a| a == "--host").unwrap();
            [&args[2..i], &args[i + 2..]].concat()
        };
        assert_eq!(rest(&local), rest(&container));
    }

    #[test]
    fn console_script_interpreter_reads_a_python_shebang_only() {
        let dir = std::env::temp_dir().join(format!("llmman-shebang-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let script = dir.join("vllm");
        std::fs::write(
            &script,
            "#!/opt/venv/bin/python3\n# -*- coding: utf-8 -*-\n",
        )
        .unwrap();
        assert_eq!(
            console_script_interpreter(&script),
            Some(PathBuf::from("/opt/venv/bin/python3"))
        );
        std::fs::write(&script, "#!/usr/bin/env python3\nimport sys\n").unwrap();
        assert_eq!(console_script_interpreter(&script), None);
        std::fs::write(&script, "#!/bin/sh\nexec vllm \"$@\"\n").unwrap();
        assert_eq!(console_script_interpreter(&script), None);
        std::fs::write(&script, b"\x7fELF\x02\x01\x01").unwrap();
        assert_eq!(console_script_interpreter(&script), None);
        let _ = std::fs::remove_dir_all(&dir);
    }
}