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