Skip to main content

weirdnet_backends/
engine.rs

1//! How each engine is launched and probed.
2
3use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6use serde::{Deserialize, Serialize};
7use tokio::process::Command;
8use weirdnet_agent::Modalities;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[serde(rename_all = "lowercase")]
12#[non_exhaustive]
13pub enum EngineKind {
14    /// llama.cpp `llama-server`.
15    Llamacpp,
16    /// `vllm serve` (Linux, NVIDIA sm_80+ or supported ROCm).
17    Vllm,
18    /// MLX-LM's `mlx_lm.server` (macOS on Apple silicon). Text only, no embeddings; the
19    /// supervisor puts a key-checking proxy in front of it (see [`crate::mlx`]).
20    Mlx,
21}
22
23impl EngineKind {
24    pub fn name(self) -> &'static str {
25        match self {
26            EngineKind::Llamacpp => "llamacpp",
27            EngineKind::Vllm => "vllm",
28            EngineKind::Mlx => "mlx",
29        }
30    }
31
32    /// The most this engine can serve. A model may serve less (see [`ModelLaunch::capabilities`]).
33    pub fn capabilities(self) -> Capabilities {
34        match self {
35            EngineKind::Llamacpp | EngineKind::Vllm => Capabilities { chat: true, embeddings: true, vision: true, audio: true },
36            EngineKind::Mlx => Capabilities::text(),
37        }
38    }
39}
40
41/// What a model takes, so routing can keep requests off models that can't serve them: images
42/// or audio off text-only models, embeddings off chat-only engines such as MLX-LM.
43#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
44#[non_exhaustive]
45pub struct Capabilities {
46    /// Chat and raw text completions.
47    pub chat: bool,
48    /// `/v1/embeddings`.
49    pub embeddings: bool,
50    /// Image content parts.
51    pub vision: bool,
52    /// Audio content parts.
53    pub audio: bool,
54}
55
56impl Capabilities {
57    /// Text chat and completions only.
58    pub fn text() -> Self {
59        Self { chat: true, ..Self::default() }
60    }
61
62    /// Embeddings only.
63    pub fn embeddings() -> Self {
64        Self { embeddings: true, ..Self::default() }
65    }
66
67    pub fn with_vision(mut self, on: bool) -> Self {
68        self.vision = on;
69        self
70    }
71
72    pub fn with_audio(mut self, on: bool) -> Self {
73        self.audio = on;
74        self
75    }
76
77    /// The inputs beyond text, as `weirdnet-agent` [`Modalities`] (what catalog entries carry).
78    pub fn inputs(&self) -> Modalities {
79        Modalities::new(self.vision, self.audio)
80    }
81
82    /// What a request needing `needed` would lack here (`"images"`, `"audio"`, ...), if anything.
83    pub fn lacking(&self, needed: Modalities) -> Option<&'static str> {
84        self.inputs().lacking(needed)
85    }
86
87    /// What both allow.
88    pub fn intersect(self, other: Self) -> Self {
89        Self {
90            chat: self.chat && other.chat,
91            embeddings: self.embeddings && other.embeddings,
92            vision: self.vision && other.vision,
93            audio: self.audio && other.audio,
94        }
95    }
96}
97
98/// One engine binary and how long it may take to come up.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct EngineConfig {
101    pub kind: EngineKind,
102    pub program: PathBuf,
103    /// Arguments added to every launch of this engine.
104    pub extra_args: Vec<String>,
105    pub ready_timeout: Duration,
106}
107
108impl EngineConfig {
109    pub fn llamacpp(program: impl Into<PathBuf>) -> Self {
110        Self { kind: EngineKind::Llamacpp, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(300) }
111    }
112
113    pub fn vllm(program: impl Into<PathBuf>) -> Self {
114        Self { kind: EngineKind::Vllm, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
115    }
116
117    /// `program` is `mlx_lm.server`, such as [`crate::mlx::server_in`] of a venv made by
118    /// [`crate::mlx::install`].
119    pub fn mlx(program: impl Into<PathBuf>) -> Self {
120        Self { kind: EngineKind::Mlx, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
121    }
122
123    /// The command for `model` on `127.0.0.1:port`. The API key goes in the environment, not the
124    /// command line, so other local users can't read it from the process list.
125    ///
126    /// MLX-LM takes no API key: the supervisor starts it on a private port and checks the key in
127    /// a proxy on the advertised one, so `api_key` is not passed to it.
128    pub fn command(&self, model: &ModelLaunch, port: u16, api_key: &str) -> Command {
129        let mut cmd = Command::new(&self.program);
130        match self.kind {
131            EngineKind::Llamacpp => {
132                cmd.args(["--model", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--alias", &model.id, "--no-webui"]);
133                if let Some(ctx) = model.context {
134                    cmd.args(["--ctx-size", &ctx.to_string()]);
135                }
136                if let Some(slots) = model.slots {
137                    cmd.args(["--parallel", &slots.to_string()]);
138                }
139                if let Some(ngl) = model.gpu_layers {
140                    cmd.args(["--n-gpu-layers", &ngl.to_string()]);
141                }
142                if model.embedding {
143                    cmd.arg("--embedding");
144                }
145                // Adapters load at scale 0; each request names its own (`"lora"` in the body).
146                // `--lora` rather than `--lora-scaled FNAME:SCALE`, which splits on `:` and so
147                // breaks on Windows paths; the scale is sent per request anyway.
148                for a in &model.adapters {
149                    cmd.args(["--lora", &a.path]);
150                }
151                if !model.adapters.is_empty() {
152                    cmd.arg("--lora-init-without-apply");
153                }
154                cmd.env("LLAMA_API_KEY", api_key);
155            }
156            EngineKind::Vllm => {
157                cmd.args(["serve", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--served-model-name", &model.id]);
158                if let Some(ctx) = model.context {
159                    cmd.args(["--max-model-len", &ctx.to_string()]);
160                }
161                if let Some(slots) = model.slots {
162                    cmd.args(["--max-num-seqs", &slots.to_string()]);
163                }
164                if !model.adapters.is_empty() {
165                    // One `--lora-modules` with every module: vLLM keeps only the last flag.
166                    cmd.args(["--enable-lora", "--lora-modules"]);
167                    for a in &model.adapters {
168                        cmd.arg(serde_json::json!({"name": a.id, "path": a.path, "base_model_name": model.id}).to_string());
169                    }
170                    cmd.args(["--max-loras", &model.adapters.len().to_string()]);
171                }
172                cmd.env("VLLM_API_KEY", api_key);
173            }
174            EngineKind::Mlx => {
175                // mlx_lm.server stops at 512 tokens unless told otherwise; the others run to the
176                // context window.
177                let max = model.context.unwrap_or(crate::mlx::DEFAULT_MAX_TOKENS).to_string();
178                cmd.args(["--model", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--max-tokens", &max]);
179            }
180        }
181        cmd.args(&self.extra_args).args(&model.extra_args);
182        cmd
183    }
184}
185
186/// A LoRA adapter served on top of a [`ModelLaunch`]'s base model, under its own pool id.
187#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
188#[non_exhaustive]
189pub struct LoraAdapter {
190    /// Pool id; requests for it go to the base model's engine with the adapter applied.
191    pub id: String,
192    /// A LoRA GGUF for llama.cpp; a PEFT directory (or Hub id) for vLLM.
193    pub path: String,
194    /// How strongly it applies (llama.cpp per request; default 1.0). vLLM ignores it.
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub scale: Option<f32>,
197}
198
199// `check_adapters` refuses a scale that isn't finite, so equality is total for served adapters.
200impl Eq for LoraAdapter {}
201
202impl LoraAdapter {
203    pub fn new(id: impl Into<String>, path: impl Into<String>) -> Self {
204        Self { id: id.into(), path: path.into(), scale: None }
205    }
206
207    pub fn with_scale(mut self, scale: f32) -> Self {
208        self.scale = Some(scale);
209        self
210    }
211
212    /// The scale requests use: [`LoraAdapter::scale`], else 1.0.
213    pub fn effective_scale(&self) -> f32 {
214        self.scale.unwrap_or(1.0)
215    }
216}
217
218/// A model this node may be told to load.
219#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
220#[non_exhaustive]
221pub struct ModelLaunch {
222    /// Pool id; also the engine's served model name.
223    pub id: String,
224    pub engine: EngineKind,
225    /// A GGUF path for llama.cpp; a path or Hub id for vLLM; an MLX-format model directory (or
226    /// Hub id) for MLX-LM.
227    pub source: String,
228    pub context: Option<u32>,
229    /// Concurrent requests (llama.cpp slots, vLLM max sequences).
230    pub slots: Option<u32>,
231    /// llama.cpp `--n-gpu-layers`; `None` keeps the engine's default (all that fit).
232    pub gpu_layers: Option<i32>,
233    /// Models in the same group are never resident together.
234    pub swap_group: Option<String>,
235    pub embedding: bool,
236    pub extra_args: Vec<String>,
237    /// Unload after this long without requests; `None` keeps it loaded.
238    #[serde(default, with = "opt_secs")]
239    pub idle_ttl: Option<Duration>,
240    /// Wrap a stock server already running on loopback (such as `vllm serve` or `llama-server`
241    /// started by hand) instead of starting an engine: the node only probes, advertises and forwards.
242    #[serde(default)]
243    pub wrap: Option<Wrap>,
244    /// LoRA adapters served on this base (llama.cpp and vLLM only; see
245    /// [`ModelLaunch::check_adapters`]). Each is its own pool id.
246    #[serde(default, skip_serializing_if = "Vec::is_empty")]
247    pub adapters: Vec<LoraAdapter>,
248}
249
250/// A stock OpenAI-compatible server the node forwards to but doesn't own.
251#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
252pub struct Wrap {
253    /// Base URL without `/v1`, such as `http://127.0.0.1:8000`. Must be loopback.
254    pub url: String,
255    /// The server's API key, if it wants one (read from the environment or a file by the caller).
256    #[serde(default, skip_serializing)]
257    pub api_key: Option<String>,
258}
259
260impl std::fmt::Debug for Wrap {
261    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
262        f.debug_struct("Wrap").field("url", &self.url).field("api_key", &self.api_key.as_ref().map(|_| "<redacted>")).finish()
263    }
264}
265
266impl Wrap {
267    /// Only loopback URLs: the wrapped server is on this machine, reached without TLS.
268    pub fn check(&self) -> Result<(), String> {
269        let rest = self.url.strip_prefix("http://").ok_or_else(|| format!("wrap url {} must start with http:// (loopback only)", self.url))?;
270        let host = match rest.strip_prefix('[') {
271            Some(v6) => v6.split(']').next().unwrap_or(""),
272            None => rest.split(['/', ':']).next().unwrap_or(""),
273        };
274        if matches!(host, "127.0.0.1" | "localhost" | "::1") { Ok(()) } else { Err(format!("wrap url {} is not loopback", self.url)) }
275    }
276
277    pub fn base(&self) -> String {
278        self.url.trim_end_matches('/').trim_end_matches("/v1").to_string()
279    }
280}
281
282mod opt_secs {
283    use std::time::Duration;
284
285    use serde::{Deserialize, Deserializer, Serializer};
286
287    pub fn serialize<S: Serializer>(d: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
288        match d {
289            Some(d) => s.serialize_some(&d.as_secs()),
290            None => s.serialize_none(),
291        }
292    }
293
294    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
295        Ok(Option::<u64>::deserialize(d)?.map(Duration::from_secs))
296    }
297}
298
299impl ModelLaunch {
300    pub fn new(id: impl Into<String>, engine: EngineKind, source: impl Into<String>) -> Self {
301        Self {
302            id: id.into(),
303            engine,
304            source: source.into(),
305            context: None,
306            slots: None,
307            gpu_layers: None,
308            swap_group: None,
309            embedding: false,
310            extra_args: Vec::new(),
311            idle_ttl: None,
312            wrap: None,
313            adapters: Vec::new(),
314        }
315    }
316
317    pub fn with_adapters(mut self, adapters: Vec<LoraAdapter>) -> Self {
318        self.adapters = adapters;
319        self
320    }
321
322    /// The pool ids this launch serves: the base's, then each adapter's.
323    pub fn served_ids(&self) -> Vec<String> {
324        std::iter::once(self.id.clone()).chain(self.adapters.iter().map(|a| a.id.clone())).collect()
325    }
326
327    /// Whether the adapters can be served: llama.cpp or vLLM (not MLX-LM, not a wrapped server,
328    /// not an embedding model), unique non-empty ids other than the base's, finite scales, and
329    /// paths the engine takes. On llama.cpp each adapter must be a LoRA GGUF (`general.type` =
330    /// `adapter`, `adapter.type` = `lora`) with the base GGUF's architecture; both headers are
331    /// read. On vLLM a local adapter must be a PEFT LoRA directory; anything else must look like a
332    /// Hub id.
333    pub fn check_adapters(&self) -> Result<(), String> {
334        if self.adapters.is_empty() {
335            return Ok(());
336        }
337        let id = &self.id;
338        if self.wrap.is_some() {
339            return Err(format!("{id}: a wrapped server can't take adapters from this node"));
340        }
341        if self.embedding {
342            return Err(format!("{id}: embedding models take no adapters"));
343        }
344        if !matches!(self.engine, EngineKind::Llamacpp | EngineKind::Vllm) {
345            return Err(format!("{id}: {} serves no adapters here; use llama.cpp or vLLM", self.engine.name()));
346        }
347        let mut seen = std::collections::HashSet::new();
348        for a in &self.adapters {
349            if a.id.trim().is_empty() {
350                return Err(format!("{id}: an adapter needs an id"));
351            }
352            if a.id == *id {
353                return Err(format!("{id}: adapter id {} is the base model's", a.id));
354            }
355            if !seen.insert(a.id.as_str()) {
356                return Err(format!("{id}: adapter id {} is used twice", a.id));
357            }
358            if a.scale.is_some_and(|s| !s.is_finite()) {
359                return Err(format!("{}: the scale must be a finite number", a.id));
360            }
361        }
362        match self.engine {
363            EngineKind::Llamacpp => {
364                let header = |path: &str| -> Result<weirdnet_model::gguf::GgufHeader, String> {
365                    let f = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
366                    weirdnet_model::gguf::read_header(std::io::BufReader::new(f)).map_err(|e| format!("{path}: {e}"))
367                };
368                let base = header(&self.source)?;
369                if base.kind.is_adapter() {
370                    return Err(format!("{id}: {} is an adapter, not a base model", self.source));
371                }
372                for a in &self.adapters {
373                    if a.path.contains(',') {
374                        return Err(format!("{}: llama.cpp can't take a path with a comma ({})", a.id, a.path));
375                    }
376                    let h = header(&a.path)?;
377                    if !h.kind.is_lora() {
378                        return Err(format!("{}: {} is not a LoRA adapter GGUF", a.id, a.path));
379                    }
380                    if h.architecture != base.architecture {
381                        return Err(format!("{}: adapter architecture {} doesn't match the base's {}", a.id, h.architecture, base.architecture));
382                    }
383                }
384            }
385            _ => {
386                for a in &self.adapters {
387                    let p = Path::new(&a.path);
388                    if p.is_dir() {
389                        let config: serde_json::Value = std::fs::read(p.join("adapter_config.json"))
390                            .ok()
391                            .and_then(|b| serde_json::from_slice(&b).ok())
392                            .ok_or_else(|| format!("{}: {} has no readable adapter_config.json", a.id, a.path))?;
393                        if !config["peft_type"].as_str().unwrap_or("LORA").eq_ignore_ascii_case("lora") {
394                            return Err(format!("{}: {} is not a LoRA adapter", a.id, a.path));
395                        }
396                    } else if p.exists() {
397                        return Err(format!("{}: vLLM takes a PEFT directory, not the file {}", a.id, a.path));
398                    } else if weirdnet_model::hf::check_repo(&a.path).is_err() {
399                        return Err(format!("{}: {} is neither a directory nor a Hub id", a.id, a.path));
400                    }
401                }
402            }
403        }
404        Ok(())
405    }
406
407    /// What this model takes. Embedding models only embed (and can't run on MLX-LM at all). A
408    /// llama.cpp model takes images and audio when it has a multimodal projector (`--mmproj` in
409    /// `extra_args`); the projector decides which, and llama-server refuses what it lacks. vLLM
410    /// and MLX-LM models are text only here.
411    pub fn capabilities(&self) -> Capabilities {
412        let own = if self.embedding {
413            Capabilities::embeddings()
414        } else {
415            let media = self.engine == EngineKind::Llamacpp && self.has_projector();
416            Capabilities::text().with_vision(media).with_audio(media)
417        };
418        own.intersect(self.engine.capabilities())
419    }
420
421    fn has_projector(&self) -> bool {
422        self.extra_args.iter().any(|a| matches!(a.split('=').next(), Some("--mmproj" | "-mm" | "--mmproj-url" | "-mmu")))
423    }
424}
425
426/// The first executable called `name` on `PATH`.
427pub fn find_in_path(name: &str) -> Option<PathBuf> {
428    let path = std::env::var_os("PATH")?;
429    std::env::split_paths(&path).map(|d| d.join(name)).find(|p| is_executable(p))
430}
431
432fn is_executable(p: &Path) -> bool {
433    #[cfg(unix)]
434    {
435        use std::os::unix::fs::PermissionsExt;
436        std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
437    }
438    #[cfg(not(unix))]
439    {
440        p.is_file()
441    }
442}
443
444#[cfg(test)]
445pub(crate) mod tests {
446    use super::*;
447
448    fn args(cmd: &Command) -> Vec<String> {
449        cmd.as_std().get_args().map(|a| a.to_string_lossy().into_owned()).collect()
450    }
451
452    #[test]
453    fn llama_args() {
454        let mut m = ModelLaunch::new("qwen3-8b", EngineKind::Llamacpp, "/m/q.gguf");
455        m.context = Some(8192);
456        m.slots = Some(2);
457        let cmd = EngineConfig::llamacpp("/bin/llama-server").command(&m, 4321, "k");
458        let a = args(&cmd);
459        assert!(a.windows(2).any(|w| w == ["--host", "127.0.0.1"]));
460        assert!(a.windows(2).any(|w| w == ["--port", "4321"]));
461        assert!(a.windows(2).any(|w| w == ["--alias", "qwen3-8b"]));
462        assert!(a.windows(2).any(|w| w == ["--parallel", "2"]));
463        assert!(!a.iter().any(|x| x == "k"), "the key stays out of argv");
464    }
465
466    /// A GGUF header with string, u32 and f32 values (enough for adapter checks).
467    pub(crate) fn gguf(kv: &[(&str, serde_json::Value)]) -> Vec<u8> {
468        let mut out = b"GGUF".to_vec();
469        out.extend(3u32.to_le_bytes());
470        out.extend(0u64.to_le_bytes());
471        out.extend((kv.len() as u64).to_le_bytes());
472        let s = |out: &mut Vec<u8>, s: &str| {
473            out.extend((s.len() as u64).to_le_bytes());
474            out.extend(s.as_bytes());
475        };
476        for (k, v) in kv {
477            s(&mut out, k);
478            match v {
479                serde_json::Value::String(t) => {
480                    out.extend(8u32.to_le_bytes());
481                    s(&mut out, t);
482                }
483                serde_json::Value::Number(n) if n.is_u64() => {
484                    out.extend(4u32.to_le_bytes());
485                    out.extend((n.as_u64().unwrap() as u32).to_le_bytes());
486                }
487                serde_json::Value::Number(n) => {
488                    out.extend(6u32.to_le_bytes());
489                    out.extend((n.as_f64().unwrap() as f32).to_le_bytes());
490                }
491                _ => unreachable!(),
492            }
493        }
494        out
495    }
496
497    pub(crate) fn base_gguf(arch: &str) -> Vec<u8> {
498        gguf(&[("general.architecture", arch.into()), (format!("{arch}.block_count").as_str(), 1.into())])
499    }
500
501    pub(crate) fn lora_gguf(arch: &str) -> Vec<u8> {
502        gguf(&[
503            ("general.architecture", arch.into()),
504            ("general.type", "adapter".into()),
505            ("adapter.type", "lora".into()),
506            ("adapter.lora.alpha", 16.5.into()),
507        ])
508    }
509
510    #[test]
511    fn llama_adapter_args_and_checks() {
512        let tmp = tempfile::tempdir().unwrap();
513        let w = |name: &str, b: Vec<u8>| {
514            let p = tmp.path().join(name);
515            std::fs::write(&p, b).unwrap();
516            p.display().to_string()
517        };
518        let base = w("base.gguf", base_gguf("qwen3"));
519        let (a, b) = (w("a.gguf", lora_gguf("qwen3")), w("b.gguf", lora_gguf("qwen3")));
520        let m = ModelLaunch::new("qwen", EngineKind::Llamacpp, &base)
521            .with_adapters(vec![LoraAdapter::new("tune-a", &a).with_scale(0.5), LoraAdapter::new("tune-b", &b)]);
522        assert_eq!(m.served_ids(), ["qwen", "tune-a", "tune-b"]);
523        m.check_adapters().unwrap();
524        let argv = args(&EngineConfig::llamacpp("llama-server").command(&m, 1, "k"));
525        let loras: Vec<&String> = argv.windows(2).filter(|w| w[0] == "--lora").map(|w| &w[1]).collect();
526        assert_eq!(loras, [&a, &b], "one --lora per adapter, in order");
527        assert!(argv.iter().any(|x| x == "--lora-init-without-apply"));
528        assert!(
529            !args(&EngineConfig::llamacpp("l").command(&ModelLaunch::new("x", EngineKind::Llamacpp, &base), 1, "k"))
530                .iter()
531                .any(|x| x.starts_with("--lora"))
532        );
533
534        let bad =
535            |adapters: Vec<LoraAdapter>| ModelLaunch::new("qwen", EngineKind::Llamacpp, &base).with_adapters(adapters).check_adapters().unwrap_err();
536        assert!(bad(vec![LoraAdapter::new("qwen", &a)]).contains("base model's"));
537        assert!(bad(vec![LoraAdapter::new("t", &a), LoraAdapter::new("t", &b)]).contains("twice"));
538        assert!(bad(vec![LoraAdapter::new("t", &a).with_scale(f32::NAN)]).contains("finite"));
539        assert!(bad(vec![LoraAdapter::new("t", &base)]).contains("not a LoRA"));
540        assert!(bad(vec![LoraAdapter::new("t", w("llama.gguf", lora_gguf("llama")))]).contains("architecture"));
541        assert!(bad(vec![LoraAdapter::new("t", tmp.path().join("missing.gguf").display().to_string())]).contains("missing.gguf"));
542        assert!(bad(vec![LoraAdapter::new("t", w("a,b.gguf", lora_gguf("qwen3")))]).contains("comma"));
543        let mut emb = m.clone();
544        emb.embedding = true;
545        assert!(emb.check_adapters().unwrap_err().contains("embedding"));
546        let mut wrapped = m.clone();
547        wrapped.wrap = Some(Wrap { url: "http://127.0.0.1:1".into(), api_key: None });
548        assert!(wrapped.check_adapters().unwrap_err().contains("wrapped"));
549        let mlx = ModelLaunch::new("m", EngineKind::Mlx, &base).with_adapters(vec![LoraAdapter::new("t", &a)]);
550        assert!(mlx.check_adapters().unwrap_err().contains("mlx"));
551        let json = serde_json::to_string(&ModelLaunch::new("x", EngineKind::Llamacpp, "/m")).unwrap();
552        assert!(!json.contains("adapters"), "no adapters, same JSON as before");
553    }
554
555    #[test]
556    fn vllm_adapter_args_and_checks() {
557        let tmp = tempfile::tempdir().unwrap();
558        let peft = tmp.path().join("tune");
559        std::fs::create_dir(&peft).unwrap();
560        std::fs::write(peft.join("adapter_config.json"), br#"{"peft_type":"LORA","r":8}"#).unwrap();
561        let peft = peft.display().to_string();
562        let m = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B")
563            .with_adapters(vec![LoraAdapter::new("tune", &peft), LoraAdapter::new("hub", "owner/some-lora")]);
564        m.check_adapters().unwrap();
565        let a = args(&EngineConfig::vllm("vllm").command(&m, 9000, "k"));
566        assert_eq!(a.iter().filter(|x| *x == "--lora-modules").count(), 1, "vLLM keeps only the last --lora-modules");
567        let at = a.iter().position(|x| x == "--lora-modules").unwrap();
568        let mods: Vec<serde_json::Value> = a[at + 1..at + 3].iter().map(|j| serde_json::from_str(j).unwrap()).collect();
569        assert_eq!(mods[0], serde_json::json!({"name": "tune", "path": peft, "base_model_name": "big"}));
570        assert_eq!(mods[1]["name"], "hub");
571        assert!(a.iter().any(|x| x == "--enable-lora"));
572        assert!(a.windows(2).any(|w| w == ["--max-loras", "2"]));
573        let file = tmp.path().join("x.gguf");
574        std::fs::write(&file, lora_gguf("qwen3")).unwrap();
575        let bad = |path: String| {
576            ModelLaunch::new("big", EngineKind::Vllm, "Q/Q").with_adapters(vec![LoraAdapter::new("t", path)]).check_adapters().unwrap_err()
577        };
578        assert!(bad(file.display().to_string()).contains("PEFT directory"));
579        assert!(bad("/no/such/dir".into()).contains("Hub id"));
580    }
581
582    #[test]
583    fn wrap_is_loopback_only() {
584        let w = |u: &str| Wrap { url: u.into(), api_key: None }.check();
585        assert!(w("http://127.0.0.1:8000").is_ok());
586        assert!(w("http://localhost:8000/").is_ok());
587        assert!(w("http://[::1]:8000").is_ok());
588        assert!(w("https://127.0.0.1:8000").is_err());
589        assert!(w("http://10.0.0.2:8000").is_err());
590        assert!(w("http://127.0.0.1.evil:8000").is_err());
591        assert_eq!(Wrap { url: "http://127.0.0.1:8000/v1/".into(), api_key: None }.base(), "http://127.0.0.1:8000");
592    }
593
594    #[test]
595    fn vllm_args() {
596        let m = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B");
597        let a = args(&EngineConfig::vllm("vllm").command(&m, 9000, "k"));
598        assert_eq!(&a[..2], ["serve", "Qwen/Qwen3-8B"]);
599        assert!(a.windows(2).any(|w| w == ["--served-model-name", "big"]));
600    }
601
602    #[test]
603    fn mlx_args() {
604        let mut m = ModelLaunch::new("qwen3-8b", EngineKind::Mlx, "/m/mlx/Qwen3-8B-4bit");
605        m.context = Some(4096);
606        let cmd = EngineConfig::mlx("/v/bin/mlx_lm.server").command(&m, 9, "k");
607        assert_eq!(args(&cmd), ["--model", "/m/mlx/Qwen3-8B-4bit", "--host", "127.0.0.1", "--port", "9", "--max-tokens", "4096"]);
608        assert!(cmd.as_std().get_envs().all(|(_, v)| v != Some(std::ffi::OsStr::new("k"))), "MLX-LM gets no key");
609        m.context = None;
610        let a = args(&EngineConfig::mlx("mlx_lm.server").command(&m, 9, "k"));
611        assert_eq!(a.last().map(String::as_str), Some("32768"));
612        assert_eq!(serde_json::to_string(&EngineKind::Mlx).unwrap(), "\"mlx\"");
613    }
614
615    #[test]
616    fn capabilities_as_modalities() {
617        let media = Capabilities::text().with_vision(true).with_audio(true);
618        assert_eq!(media.inputs(), Modalities::new(true, true));
619        assert_eq!(Capabilities::text().lacking(Modalities::VISION), Some("images"));
620        assert_eq!(Capabilities::text().with_vision(true).lacking(Modalities::new(true, true)), Some("audio"));
621        assert_eq!(media.lacking(Modalities::AUDIO), None);
622        assert_eq!(
623            ModelLaunch::new("x", EngineKind::Mlx, "/m/x").capabilities().lacking(Modalities::VISION),
624            Some("images"),
625            "MLX never takes images"
626        );
627    }
628
629    #[test]
630    fn capabilities() {
631        let mut m = ModelLaunch::new("x", EngineKind::Mlx, "/m/x");
632        assert_eq!(m.capabilities(), Capabilities::text());
633        m.extra_args = vec!["--mmproj".into(), "/p".into()];
634        assert!(!m.capabilities().vision, "MLX-LM never takes images");
635        m.embedding = true;
636        assert_eq!(m.capabilities(), Capabilities::default(), "MLX-LM serves no embeddings");
637
638        let mut l = ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf");
639        assert_eq!(l.capabilities(), Capabilities::text());
640        l.extra_args = vec!["--mmproj=/p/mm.gguf".into()];
641        let c = l.capabilities();
642        assert!(c.chat && c.vision && c.audio && !c.embeddings);
643        l.embedding = true;
644        assert_eq!(l.capabilities(), Capabilities::embeddings());
645
646        let v = ModelLaunch::new("v", EngineKind::Vllm, "Qwen/Qwen3-8B");
647        assert_eq!(v.capabilities(), Capabilities::text());
648        assert!(!EngineKind::Mlx.capabilities().embeddings && EngineKind::Llamacpp.capabilities().vision);
649    }
650}