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.runtime_lora() {
165                    cmd.arg("--enable-lora");
166                    if !model.adapters.is_empty() {
167                        // One `--lora-modules` with every module: vLLM keeps only the last flag.
168                        cmd.arg("--lora-modules");
169                        for a in &model.adapters {
170                            cmd.arg(serde_json::json!({"name": a.id, "path": a.path, "base_model_name": model.id}).to_string());
171                        }
172                    }
173                    let max = (model.adapters.len() as u32).max(model.lora_slots.unwrap_or(0)).max(1);
174                    cmd.args(["--max-loras", &max.to_string()]);
175                    // Lets the supervisor add and remove adapters on the running engine
176                    // (`/v1/load_lora_adapter`); the endpoints sit behind the API key on loopback.
177                    cmd.env("VLLM_ALLOW_RUNTIME_LORA_UPDATING", "True");
178                }
179                cmd.env("VLLM_API_KEY", api_key);
180            }
181            EngineKind::Mlx => {
182                // mlx_lm.server stops at 512 tokens unless told otherwise; the others run to the
183                // context window.
184                let max = model.context.unwrap_or(crate::mlx::DEFAULT_MAX_TOKENS).to_string();
185                cmd.args(["--model", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--max-tokens", &max]);
186            }
187        }
188        cmd.args(&self.extra_args).args(&model.extra_args);
189        cmd
190    }
191}
192
193/// A LoRA adapter served on top of a [`ModelLaunch`]'s base model, under its own pool id.
194#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
195#[non_exhaustive]
196pub struct LoraAdapter {
197    /// Pool id; requests for it go to the base model's engine with the adapter applied.
198    pub id: String,
199    /// A LoRA GGUF for llama.cpp; a PEFT directory (or Hub id) for vLLM.
200    pub path: String,
201    /// How strongly it applies (llama.cpp per request; default 1.0). vLLM ignores it.
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub scale: Option<f32>,
204}
205
206// `check_adapters` refuses a scale that isn't finite, so equality is total for served adapters.
207impl Eq for LoraAdapter {}
208
209impl LoraAdapter {
210    pub fn new(id: impl Into<String>, path: impl Into<String>) -> Self {
211        Self { id: id.into(), path: path.into(), scale: None }
212    }
213
214    pub fn with_scale(mut self, scale: f32) -> Self {
215        self.scale = Some(scale);
216        self
217    }
218
219    /// The scale requests use: [`LoraAdapter::scale`], else 1.0.
220    pub fn effective_scale(&self) -> f32 {
221        self.scale.unwrap_or(1.0)
222    }
223}
224
225/// A model this node may be told to load.
226#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
227#[non_exhaustive]
228pub struct ModelLaunch {
229    /// Pool id; also the engine's served model name.
230    pub id: String,
231    pub engine: EngineKind,
232    /// A GGUF path for llama.cpp; a path or Hub id for vLLM; an MLX-format model directory (or
233    /// Hub id) for MLX-LM.
234    pub source: String,
235    pub context: Option<u32>,
236    /// Concurrent requests (llama.cpp slots, vLLM max sequences).
237    pub slots: Option<u32>,
238    /// llama.cpp `--n-gpu-layers`; `None` keeps the engine's default (all that fit).
239    pub gpu_layers: Option<i32>,
240    /// Models in the same group are never resident together.
241    pub swap_group: Option<String>,
242    pub embedding: bool,
243    pub extra_args: Vec<String>,
244    /// Unload after this long without requests; `None` keeps it loaded.
245    #[serde(default, with = "opt_secs")]
246    pub idle_ttl: Option<Duration>,
247    /// Wrap a stock server already running on loopback (such as `vllm serve` or `llama-server`
248    /// started by hand) instead of starting an engine: the node only probes, advertises and forwards.
249    #[serde(default)]
250    pub wrap: Option<Wrap>,
251    /// LoRA adapters served on this base (llama.cpp and vLLM only; see
252    /// [`ModelLaunch::check_adapters`]). Each is its own pool id.
253    #[serde(default, skip_serializing_if = "Vec::is_empty")]
254    pub adapters: Vec<LoraAdapter>,
255    /// vLLM only: start the engine with LoRA on (`--enable-lora`, `--max-loras` at least this)
256    /// even without adapters, so adapters can be added and removed while it runs
257    /// ([`crate::Supervisor::add_adapter_live`]). A vLLM base started with adapters can take more
258    /// at run time without it. llama.cpp ignores it: llama-server loads adapter files only at start.
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub lora_slots: Option<u32>,
261}
262
263/// A stock OpenAI-compatible server the node forwards to but doesn't own.
264#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
265pub struct Wrap {
266    /// Base URL without `/v1`, such as `http://127.0.0.1:8000`. Must be loopback.
267    pub url: String,
268    /// The server's API key, if it wants one (read from the environment or a file by the caller).
269    #[serde(default, skip_serializing)]
270    pub api_key: Option<String>,
271}
272
273impl std::fmt::Debug for Wrap {
274    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275        f.debug_struct("Wrap").field("url", &self.url).field("api_key", &self.api_key.as_ref().map(|_| "<redacted>")).finish()
276    }
277}
278
279impl Wrap {
280    /// Only loopback URLs: the wrapped server is on this machine, reached without TLS.
281    pub fn check(&self) -> Result<(), String> {
282        let rest = self.url.strip_prefix("http://").ok_or_else(|| format!("wrap url {} must start with http:// (loopback only)", self.url))?;
283        let host = match rest.strip_prefix('[') {
284            Some(v6) => v6.split(']').next().unwrap_or(""),
285            None => rest.split(['/', ':']).next().unwrap_or(""),
286        };
287        if matches!(host, "127.0.0.1" | "localhost" | "::1") { Ok(()) } else { Err(format!("wrap url {} is not loopback", self.url)) }
288    }
289
290    pub fn base(&self) -> String {
291        self.url.trim_end_matches('/').trim_end_matches("/v1").to_string()
292    }
293}
294
295mod opt_secs {
296    use std::time::Duration;
297
298    use serde::{Deserialize, Deserializer, Serializer};
299
300    pub fn serialize<S: Serializer>(d: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
301        match d {
302            Some(d) => s.serialize_some(&d.as_secs()),
303            None => s.serialize_none(),
304        }
305    }
306
307    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
308        Ok(Option::<u64>::deserialize(d)?.map(Duration::from_secs))
309    }
310}
311
312impl ModelLaunch {
313    pub fn new(id: impl Into<String>, engine: EngineKind, source: impl Into<String>) -> Self {
314        Self {
315            id: id.into(),
316            engine,
317            source: source.into(),
318            context: None,
319            slots: None,
320            gpu_layers: None,
321            swap_group: None,
322            embedding: false,
323            extra_args: Vec::new(),
324            idle_ttl: None,
325            wrap: None,
326            adapters: Vec::new(),
327            lora_slots: None,
328        }
329    }
330
331    /// See [`ModelLaunch::lora_slots`].
332    pub fn with_lora_slots(mut self, slots: u32) -> Self {
333        self.lora_slots = Some(slots);
334        self
335    }
336
337    /// Whether the engine starts able to take adapters at run time: vLLM with adapters or
338    /// [`ModelLaunch::lora_slots`].
339    pub fn runtime_lora(&self) -> bool {
340        self.engine == EngineKind::Vllm && self.wrap.is_none() && (!self.adapters.is_empty() || self.lora_slots.is_some_and(|n| n > 0))
341    }
342
343    pub fn with_adapters(mut self, adapters: Vec<LoraAdapter>) -> Self {
344        self.adapters = adapters;
345        self
346    }
347
348    /// The pool ids this launch serves: the base's, then each adapter's.
349    pub fn served_ids(&self) -> Vec<String> {
350        std::iter::once(self.id.clone()).chain(self.adapters.iter().map(|a| a.id.clone())).collect()
351    }
352
353    /// Whether the adapters can be served: llama.cpp or vLLM (not MLX-LM, not a wrapped server,
354    /// not an embedding model), unique non-empty ids other than the base's, finite scales, and
355    /// paths the engine takes. On llama.cpp each adapter must be a LoRA GGUF (`general.type` =
356    /// `adapter`, `adapter.type` = `lora`) with the base GGUF's architecture; both headers are
357    /// read. On vLLM a local adapter must be a PEFT LoRA directory; anything else must look like a
358    /// Hub id.
359    pub fn check_adapters(&self) -> Result<(), String> {
360        if self.adapters.is_empty() {
361            return Ok(());
362        }
363        let id = &self.id;
364        if self.wrap.is_some() {
365            return Err(format!("{id}: a wrapped server can't take adapters from this node"));
366        }
367        if self.embedding {
368            return Err(format!("{id}: embedding models take no adapters"));
369        }
370        if !matches!(self.engine, EngineKind::Llamacpp | EngineKind::Vllm) {
371            return Err(format!("{id}: {} serves no adapters here; use llama.cpp or vLLM", self.engine.name()));
372        }
373        let mut seen = std::collections::HashSet::new();
374        for a in &self.adapters {
375            if a.id.trim().is_empty() {
376                return Err(format!("{id}: an adapter needs an id"));
377            }
378            if a.id == *id {
379                return Err(format!("{id}: adapter id {} is the base model's", a.id));
380            }
381            if !seen.insert(a.id.as_str()) {
382                return Err(format!("{id}: adapter id {} is used twice", a.id));
383            }
384            if a.scale.is_some_and(|s| !s.is_finite()) {
385                return Err(format!("{}: the scale must be a finite number", a.id));
386            }
387        }
388        match self.engine {
389            EngineKind::Llamacpp => {
390                let header = |path: &str| -> Result<weirdnet_model::gguf::GgufHeader, String> {
391                    let f = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
392                    weirdnet_model::gguf::read_header(std::io::BufReader::new(f)).map_err(|e| format!("{path}: {e}"))
393                };
394                let base = header(&self.source)?;
395                if base.kind.is_adapter() {
396                    return Err(format!("{id}: {} is an adapter, not a base model", self.source));
397                }
398                for a in &self.adapters {
399                    if a.path.contains(',') {
400                        return Err(format!("{}: llama.cpp can't take a path with a comma ({})", a.id, a.path));
401                    }
402                    let h = header(&a.path)?;
403                    if !h.kind.is_lora() {
404                        return Err(format!("{}: {} is not a LoRA adapter GGUF", a.id, a.path));
405                    }
406                    if h.architecture != base.architecture {
407                        return Err(format!("{}: adapter architecture {} doesn't match the base's {}", a.id, h.architecture, base.architecture));
408                    }
409                }
410            }
411            _ => {
412                for a in &self.adapters {
413                    let p = Path::new(&a.path);
414                    if p.is_dir() {
415                        let config: serde_json::Value = std::fs::read(p.join("adapter_config.json"))
416                            .ok()
417                            .and_then(|b| serde_json::from_slice(&b).ok())
418                            .ok_or_else(|| format!("{}: {} has no readable adapter_config.json", a.id, a.path))?;
419                        if !config["peft_type"].as_str().unwrap_or("LORA").eq_ignore_ascii_case("lora") {
420                            return Err(format!("{}: {} is not a LoRA adapter", a.id, a.path));
421                        }
422                    } else if p.exists() {
423                        return Err(format!("{}: vLLM takes a PEFT directory, not the file {}", a.id, a.path));
424                    } else if weirdnet_model::hf::check_repo(&a.path).is_err() {
425                        return Err(format!("{}: {} is neither a directory nor a Hub id", a.id, a.path));
426                    }
427                }
428            }
429        }
430        Ok(())
431    }
432
433    /// What this model takes. Embedding models only embed (and can't run on MLX-LM at all). A
434    /// llama.cpp model takes images and audio when it has a multimodal projector (`--mmproj` in
435    /// `extra_args`); the projector decides which, and llama-server refuses what it lacks. vLLM
436    /// and MLX-LM models are text only here.
437    pub fn capabilities(&self) -> Capabilities {
438        let own = if self.embedding {
439            Capabilities::embeddings()
440        } else {
441            let media = self.engine == EngineKind::Llamacpp && self.has_projector();
442            Capabilities::text().with_vision(media).with_audio(media)
443        };
444        own.intersect(self.engine.capabilities())
445    }
446
447    fn has_projector(&self) -> bool {
448        self.extra_args.iter().any(|a| matches!(a.split('=').next(), Some("--mmproj" | "-mm" | "--mmproj-url" | "-mmu")))
449    }
450}
451
452/// The first executable called `name` on `PATH`.
453pub fn find_in_path(name: &str) -> Option<PathBuf> {
454    let path = std::env::var_os("PATH")?;
455    std::env::split_paths(&path).map(|d| d.join(name)).find(|p| is_executable(p))
456}
457
458fn is_executable(p: &Path) -> bool {
459    #[cfg(unix)]
460    {
461        use std::os::unix::fs::PermissionsExt;
462        std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
463    }
464    #[cfg(not(unix))]
465    {
466        p.is_file()
467    }
468}
469
470#[cfg(test)]
471pub(crate) mod tests {
472    use super::*;
473
474    fn args(cmd: &Command) -> Vec<String> {
475        cmd.as_std().get_args().map(|a| a.to_string_lossy().into_owned()).collect()
476    }
477
478    #[test]
479    fn llama_args() {
480        let mut m = ModelLaunch::new("qwen3-8b", EngineKind::Llamacpp, "/m/q.gguf");
481        m.context = Some(8192);
482        m.slots = Some(2);
483        let cmd = EngineConfig::llamacpp("/bin/llama-server").command(&m, 4321, "k");
484        let a = args(&cmd);
485        assert!(a.windows(2).any(|w| w == ["--host", "127.0.0.1"]));
486        assert!(a.windows(2).any(|w| w == ["--port", "4321"]));
487        assert!(a.windows(2).any(|w| w == ["--alias", "qwen3-8b"]));
488        assert!(a.windows(2).any(|w| w == ["--parallel", "2"]));
489        assert!(!a.iter().any(|x| x == "k"), "the key stays out of argv");
490    }
491
492    /// A GGUF header with string, u32 and f32 values (enough for adapter checks).
493    pub(crate) fn gguf(kv: &[(&str, serde_json::Value)]) -> Vec<u8> {
494        let mut out = b"GGUF".to_vec();
495        out.extend(3u32.to_le_bytes());
496        out.extend(0u64.to_le_bytes());
497        out.extend((kv.len() as u64).to_le_bytes());
498        let s = |out: &mut Vec<u8>, s: &str| {
499            out.extend((s.len() as u64).to_le_bytes());
500            out.extend(s.as_bytes());
501        };
502        for (k, v) in kv {
503            s(&mut out, k);
504            match v {
505                serde_json::Value::String(t) => {
506                    out.extend(8u32.to_le_bytes());
507                    s(&mut out, t);
508                }
509                serde_json::Value::Number(n) if n.is_u64() => {
510                    out.extend(4u32.to_le_bytes());
511                    out.extend((n.as_u64().unwrap() as u32).to_le_bytes());
512                }
513                serde_json::Value::Number(n) => {
514                    out.extend(6u32.to_le_bytes());
515                    out.extend((n.as_f64().unwrap() as f32).to_le_bytes());
516                }
517                _ => unreachable!(),
518            }
519        }
520        out
521    }
522
523    pub(crate) fn base_gguf(arch: &str) -> Vec<u8> {
524        gguf(&[("general.architecture", arch.into()), (format!("{arch}.block_count").as_str(), 1.into())])
525    }
526
527    pub(crate) fn lora_gguf(arch: &str) -> Vec<u8> {
528        gguf(&[
529            ("general.architecture", arch.into()),
530            ("general.type", "adapter".into()),
531            ("adapter.type", "lora".into()),
532            ("adapter.lora.alpha", 16.5.into()),
533        ])
534    }
535
536    #[test]
537    fn llama_adapter_args_and_checks() {
538        let tmp = tempfile::tempdir().unwrap();
539        let w = |name: &str, b: Vec<u8>| {
540            let p = tmp.path().join(name);
541            std::fs::write(&p, b).unwrap();
542            p.display().to_string()
543        };
544        let base = w("base.gguf", base_gguf("qwen3"));
545        let (a, b) = (w("a.gguf", lora_gguf("qwen3")), w("b.gguf", lora_gguf("qwen3")));
546        let m = ModelLaunch::new("qwen", EngineKind::Llamacpp, &base)
547            .with_adapters(vec![LoraAdapter::new("tune-a", &a).with_scale(0.5), LoraAdapter::new("tune-b", &b)]);
548        assert_eq!(m.served_ids(), ["qwen", "tune-a", "tune-b"]);
549        m.check_adapters().unwrap();
550        let argv = args(&EngineConfig::llamacpp("llama-server").command(&m, 1, "k"));
551        let loras: Vec<&String> = argv.windows(2).filter(|w| w[0] == "--lora").map(|w| &w[1]).collect();
552        assert_eq!(loras, [&a, &b], "one --lora per adapter, in order");
553        assert!(argv.iter().any(|x| x == "--lora-init-without-apply"));
554        assert!(
555            !args(&EngineConfig::llamacpp("l").command(&ModelLaunch::new("x", EngineKind::Llamacpp, &base), 1, "k"))
556                .iter()
557                .any(|x| x.starts_with("--lora"))
558        );
559
560        let bad =
561            |adapters: Vec<LoraAdapter>| ModelLaunch::new("qwen", EngineKind::Llamacpp, &base).with_adapters(adapters).check_adapters().unwrap_err();
562        assert!(bad(vec![LoraAdapter::new("qwen", &a)]).contains("base model's"));
563        assert!(bad(vec![LoraAdapter::new("t", &a), LoraAdapter::new("t", &b)]).contains("twice"));
564        assert!(bad(vec![LoraAdapter::new("t", &a).with_scale(f32::NAN)]).contains("finite"));
565        assert!(bad(vec![LoraAdapter::new("t", &base)]).contains("not a LoRA"));
566        assert!(bad(vec![LoraAdapter::new("t", w("llama.gguf", lora_gguf("llama")))]).contains("architecture"));
567        assert!(bad(vec![LoraAdapter::new("t", tmp.path().join("missing.gguf").display().to_string())]).contains("missing.gguf"));
568        assert!(bad(vec![LoraAdapter::new("t", w("a,b.gguf", lora_gguf("qwen3")))]).contains("comma"));
569        let mut emb = m.clone();
570        emb.embedding = true;
571        assert!(emb.check_adapters().unwrap_err().contains("embedding"));
572        let mut wrapped = m.clone();
573        wrapped.wrap = Some(Wrap { url: "http://127.0.0.1:1".into(), api_key: None });
574        assert!(wrapped.check_adapters().unwrap_err().contains("wrapped"));
575        let mlx = ModelLaunch::new("m", EngineKind::Mlx, &base).with_adapters(vec![LoraAdapter::new("t", &a)]);
576        assert!(mlx.check_adapters().unwrap_err().contains("mlx"));
577        let json = serde_json::to_string(&ModelLaunch::new("x", EngineKind::Llamacpp, "/m")).unwrap();
578        assert!(!json.contains("adapters"), "no adapters, same JSON as before");
579    }
580
581    #[test]
582    fn vllm_adapter_args_and_checks() {
583        let tmp = tempfile::tempdir().unwrap();
584        let peft = tmp.path().join("tune");
585        std::fs::create_dir(&peft).unwrap();
586        std::fs::write(peft.join("adapter_config.json"), br#"{"peft_type":"LORA","r":8}"#).unwrap();
587        let peft = peft.display().to_string();
588        let m = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B")
589            .with_adapters(vec![LoraAdapter::new("tune", &peft), LoraAdapter::new("hub", "owner/some-lora")]);
590        m.check_adapters().unwrap();
591        let a = args(&EngineConfig::vllm("vllm").command(&m, 9000, "k"));
592        assert_eq!(a.iter().filter(|x| *x == "--lora-modules").count(), 1, "vLLM keeps only the last --lora-modules");
593        let at = a.iter().position(|x| x == "--lora-modules").unwrap();
594        let mods: Vec<serde_json::Value> = a[at + 1..at + 3].iter().map(|j| serde_json::from_str(j).unwrap()).collect();
595        assert_eq!(mods[0], serde_json::json!({"name": "tune", "path": peft, "base_model_name": "big"}));
596        assert_eq!(mods[1]["name"], "hub");
597        assert!(a.iter().any(|x| x == "--enable-lora"));
598        assert!(a.windows(2).any(|w| w == ["--max-loras", "2"]));
599        let cmd = EngineConfig::vllm("vllm").command(&m, 9000, "k");
600        let env: Vec<_> = cmd.as_std().get_envs().map(|(k, v)| (k.to_owned(), v.map(|v| v.to_owned()))).collect();
601        assert!(env.iter().any(|(k, v)| k == "VLLM_ALLOW_RUNTIME_LORA_UPDATING" && v.as_deref() == Some("True".as_ref())));
602        // LoRA on without adapters at start, for adapters added while it runs.
603        let empty = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B").with_lora_slots(4);
604        assert!(empty.runtime_lora());
605        let a = args(&EngineConfig::vllm("vllm").command(&empty, 9000, "k"));
606        assert!(a.iter().any(|x| x == "--enable-lora") && !a.iter().any(|x| x == "--lora-modules"));
607        assert!(a.windows(2).any(|w| w == ["--max-loras", "4"]));
608        let plain = args(&EngineConfig::vllm("vllm").command(&ModelLaunch::new("big", EngineKind::Vllm, "Q/Q"), 9000, "k"));
609        assert!(!plain.iter().any(|x| x == "--enable-lora"));
610        assert!(!ModelLaunch::new("q", EngineKind::Llamacpp, "/q.gguf").with_lora_slots(2).runtime_lora(), "llama.cpp ignores it");
611        let file = tmp.path().join("x.gguf");
612        std::fs::write(&file, lora_gguf("qwen3")).unwrap();
613        let bad = |path: String| {
614            ModelLaunch::new("big", EngineKind::Vllm, "Q/Q").with_adapters(vec![LoraAdapter::new("t", path)]).check_adapters().unwrap_err()
615        };
616        assert!(bad(file.display().to_string()).contains("PEFT directory"));
617        assert!(bad("/no/such/dir".into()).contains("Hub id"));
618    }
619
620    #[test]
621    fn wrap_is_loopback_only() {
622        let w = |u: &str| Wrap { url: u.into(), api_key: None }.check();
623        assert!(w("http://127.0.0.1:8000").is_ok());
624        assert!(w("http://localhost:8000/").is_ok());
625        assert!(w("http://[::1]:8000").is_ok());
626        assert!(w("https://127.0.0.1:8000").is_err());
627        assert!(w("http://10.0.0.2:8000").is_err());
628        assert!(w("http://127.0.0.1.evil:8000").is_err());
629        assert_eq!(Wrap { url: "http://127.0.0.1:8000/v1/".into(), api_key: None }.base(), "http://127.0.0.1:8000");
630    }
631
632    #[test]
633    fn vllm_args() {
634        let m = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B");
635        let a = args(&EngineConfig::vllm("vllm").command(&m, 9000, "k"));
636        assert_eq!(&a[..2], ["serve", "Qwen/Qwen3-8B"]);
637        assert!(a.windows(2).any(|w| w == ["--served-model-name", "big"]));
638    }
639
640    #[test]
641    fn mlx_args() {
642        let mut m = ModelLaunch::new("qwen3-8b", EngineKind::Mlx, "/m/mlx/Qwen3-8B-4bit");
643        m.context = Some(4096);
644        let cmd = EngineConfig::mlx("/v/bin/mlx_lm.server").command(&m, 9, "k");
645        assert_eq!(args(&cmd), ["--model", "/m/mlx/Qwen3-8B-4bit", "--host", "127.0.0.1", "--port", "9", "--max-tokens", "4096"]);
646        assert!(cmd.as_std().get_envs().all(|(_, v)| v != Some(std::ffi::OsStr::new("k"))), "MLX-LM gets no key");
647        m.context = None;
648        let a = args(&EngineConfig::mlx("mlx_lm.server").command(&m, 9, "k"));
649        assert_eq!(a.last().map(String::as_str), Some("32768"));
650        assert_eq!(serde_json::to_string(&EngineKind::Mlx).unwrap(), "\"mlx\"");
651    }
652
653    #[test]
654    fn capabilities_as_modalities() {
655        let media = Capabilities::text().with_vision(true).with_audio(true);
656        assert_eq!(media.inputs(), Modalities::new(true, true));
657        assert_eq!(Capabilities::text().lacking(Modalities::VISION), Some("images"));
658        assert_eq!(Capabilities::text().with_vision(true).lacking(Modalities::new(true, true)), Some("audio"));
659        assert_eq!(media.lacking(Modalities::AUDIO), None);
660        assert_eq!(
661            ModelLaunch::new("x", EngineKind::Mlx, "/m/x").capabilities().lacking(Modalities::VISION),
662            Some("images"),
663            "MLX never takes images"
664        );
665    }
666
667    #[test]
668    fn capabilities() {
669        let mut m = ModelLaunch::new("x", EngineKind::Mlx, "/m/x");
670        assert_eq!(m.capabilities(), Capabilities::text());
671        m.extra_args = vec!["--mmproj".into(), "/p".into()];
672        assert!(!m.capabilities().vision, "MLX-LM never takes images");
673        m.embedding = true;
674        assert_eq!(m.capabilities(), Capabilities::default(), "MLX-LM serves no embeddings");
675
676        let mut l = ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf");
677        assert_eq!(l.capabilities(), Capabilities::text());
678        l.extra_args = vec!["--mmproj=/p/mm.gguf".into()];
679        let c = l.capabilities();
680        assert!(c.chat && c.vision && c.audio && !c.embeddings);
681        l.embedding = true;
682        assert_eq!(l.capabilities(), Capabilities::embeddings());
683
684        let v = ModelLaunch::new("v", EngineKind::Vllm, "Qwen/Qwen3-8B");
685        assert_eq!(v.capabilities(), Capabilities::text());
686        assert!(!EngineKind::Mlx.capabilities().embeddings && EngineKind::Llamacpp.capabilities().vision);
687    }
688}