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