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