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::speech::SpeechProfile;
10use weirdnet_agent::{MediaLimits, Modalities};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
13#[serde(rename_all = "lowercase")]
14#[non_exhaustive]
15pub enum EngineKind {
16    /// llama.cpp `llama-server`.
17    Llamacpp,
18    /// `vllm serve` (Linux, NVIDIA sm_80+ or supported ROCm).
19    Vllm,
20    /// MLX-LM's `mlx_lm.server` (macOS on Apple silicon). Text only, no embeddings; the
21    /// supervisor puts a key-checking proxy in front of it (see [`crate::mlx`]).
22    Mlx,
23    /// vLLM-Omni (`vllm serve MODEL --omni`, Linux, NVIDIA): speech out through
24    /// `/v1/audio/speech` (Qwen3-TTS, VoxCPM2, Fish Audio Drama 3), and text chat. `vllm-omni`
25    /// on the wire. vLLM and the `vllm-omni` package go in one venv, pinned to one release (see
26    /// [`EngineKind::install_hint`]). Since 0.4.10.
27    #[serde(rename = "vllm-omni")]
28    VllmOmni,
29}
30
31impl EngineKind {
32    pub fn name(self) -> &'static str {
33        match self {
34            EngineKind::Llamacpp => "llamacpp",
35            EngineKind::Vllm => "vllm",
36            EngineKind::Mlx => "mlx",
37            EngineKind::VllmOmni => "vllm-omni",
38        }
39    }
40
41    /// The engine named `name` ([`EngineKind::name`]; `vllm_omni` and `omni` are taken for
42    /// `vllm-omni`), case-insensitive. Since 0.4.10.
43    pub fn parse(name: &str) -> Option<Self> {
44        match name.trim().to_ascii_lowercase().as_str() {
45            "llamacpp" | "llama.cpp" | "llama-server" => Some(EngineKind::Llamacpp),
46            "vllm" => Some(EngineKind::Vllm),
47            "mlx" | "mlx-lm" => Some(EngineKind::Mlx),
48            "vllm-omni" | "vllm_omni" | "omni" => Some(EngineKind::VllmOmni),
49            _ => None,
50        }
51    }
52
53    /// The most this engine can serve. A model may serve less (see [`ModelLaunch::capabilities`]).
54    /// Native video (`video_url` parts) is vLLM's; speech out is llama.cpp's (a speech model with
55    /// its projector) and vLLM-Omni's.
56    pub fn capabilities(self) -> Capabilities {
57        match self {
58            EngineKind::Llamacpp => {
59                Capabilities { chat: true, embeddings: true, vision: true, audio: true, transcribe: true, speak: true, ..Capabilities::default() }
60            }
61            EngineKind::Vllm => {
62                Capabilities { chat: true, embeddings: true, vision: true, audio: true, transcribe: true, video: true, ..Capabilities::default() }
63            }
64            EngineKind::Mlx => Capabilities::text(),
65            EngineKind::VllmOmni => Capabilities { chat: true, speak: true, ..Capabilities::default() },
66        }
67    }
68
69    /// Whether the engine runs on `os` and `arch` (as in [`std::env::consts`]): llama.cpp
70    /// everywhere, vLLM and vLLM-Omni on Linux only, MLX-LM on macOS on Apple silicon only.
71    /// Since 0.4.10.
72    pub fn supported(self, os: &str, arch: &str) -> bool {
73        match self {
74            EngineKind::Llamacpp => true,
75            EngineKind::Vllm | EngineKind::VllmOmni => os == "linux",
76            EngineKind::Mlx => crate::mlx::supported(os, arch),
77        }
78    }
79
80    /// Whether the engine runs on this machine's OS and architecture ([`EngineKind::supported`]).
81    /// Since 0.4.10.
82    pub fn supported_here(self) -> bool {
83        self.supported(std::env::consts::OS, std::env::consts::ARCH)
84    }
85
86    /// The program the engine is started as, looked for on `PATH` when no path is configured:
87    /// `llama-server`, `vllm` (vLLM-Omni too: `vllm serve MODEL --omni`) or `mlx_lm.server`.
88    /// Since 0.4.10.
89    pub fn program(self) -> &'static str {
90        match self {
91            EngineKind::Llamacpp => "llama-server",
92            EngineKind::Vllm | EngineKind::VllmOmni => "vllm",
93            EngineKind::Mlx => "mlx_lm.server",
94        }
95    }
96
97    /// How to install the engine, for an error or a setup screen. Since 0.4.10.
98    pub fn install_hint(self) -> &'static str {
99        match self {
100            EngineKind::Llamacpp => "install llama.cpp (https://github.com/ggml-org/llama.cpp) and put `llama-server` on PATH",
101            EngineKind::Vllm => "install vLLM in a venv (`pip install vllm`; Linux, NVIDIA sm_80+ or supported ROCm) and put its `vllm` on PATH",
102            EngineKind::VllmOmni => {
103                "install vLLM and vLLM-Omni in one venv, pinned to one release (`pip install vllm vllm-omni`; Linux, NVIDIA), and put its `vllm` on PATH; it runs as `vllm serve MODEL --omni`"
104            }
105            EngineKind::Mlx => "install MLX-LM into a venv (weirdnet_backends::mlx::install; macOS on Apple silicon)",
106        }
107    }
108}
109
110/// What a model takes, so routing can keep requests off models that can't serve them: images
111/// or audio off text-only models, embeddings off chat-only engines such as MLX-LM. With its
112/// media and request [`limits`](Capabilities::limits) when known, so clients can size images,
113/// audio and whole requests (catalog/1 [`CatalogModel::limits`]).
114#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
115#[non_exhaustive]
116pub struct Capabilities {
117    /// Chat and raw text completions.
118    pub chat: bool,
119    /// `/v1/embeddings`.
120    pub embeddings: bool,
121    /// Image content parts.
122    pub vision: bool,
123    /// Audio content parts.
124    pub audio: bool,
125    /// Media and request limits (images per request, image token cost and edge, audio length and
126    /// token rate, request bytes), each absent when unknown, never defaulted: measured when the
127    /// model loads or set by the operator ([`ModelLaunch::limits`]). Left out of records when none
128    /// is known; absent in records from nodes before 0.4.8.
129    #[serde(default, skip_serializing_if = "MediaLimits::is_unknown")]
130    pub limits: MediaLimits,
131    /// Speech to text (infer/2 `Transcribe`): the model has the transcription role
132    /// ([`ModelLaunch::transcribe`]) and its engine can serve it (llama.cpp with an audio
133    /// projector, vLLM's `/v1/audio/transcriptions`). Its catalog/1 purpose is
134    /// [`Purpose::Transcribe`]. Left out of
135    /// records when false; absent (false) in records from nodes before 0.4.9.
136    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
137    pub transcribe: bool,
138    /// Video content parts sent whole (`video_url` with a `data:video/` URL, `weirdnet-agent`
139    /// `ContentPart::VideoUrl`): a model the operator marked as reading video
140    /// ([`ModelLaunch::video`]) on vLLM. catalog/1 `inputs.video`. Left out of records when
141    /// false; absent (false) in records from nodes before 0.4.10. Since 0.4.10.
142    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
143    pub video: bool,
144    /// Text to speech (infer/2 `Speak`): the model has the speech role ([`ModelLaunch::speak`])
145    /// and its engine can serve it (llama.cpp with the model's projector, vLLM-Omni). Its
146    /// catalog/1 purpose is [`Purpose::Speak`]; what it does is its speech profile
147    /// ([`ModelStatus::speech`](crate::ModelStatus::speech)). Left out of records when false;
148    /// absent (false) in records from nodes before 0.4.10. Since 0.4.10.
149    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
150    pub speak: bool,
151}
152
153impl Capabilities {
154    /// Text chat and completions only.
155    pub fn text() -> Self {
156        Self { chat: true, ..Self::default() }
157    }
158
159    /// Embeddings only.
160    pub fn embeddings() -> Self {
161        Self { embeddings: true, ..Self::default() }
162    }
163
164    pub fn with_vision(mut self, on: bool) -> Self {
165        self.vision = on;
166        self
167    }
168
169    pub fn with_audio(mut self, on: bool) -> Self {
170        self.audio = on;
171        self
172    }
173
174    /// See [`Capabilities::limits`].
175    pub fn with_limits(mut self, limits: MediaLimits) -> Self {
176        self.limits = limits;
177        self
178    }
179
180    /// See [`Capabilities::transcribe`].
181    pub fn with_transcribe(mut self, on: bool) -> Self {
182        self.transcribe = on;
183        self
184    }
185
186    /// See [`Capabilities::video`]. Since 0.4.10.
187    pub fn with_video(mut self, on: bool) -> Self {
188        self.video = on;
189        self
190    }
191
192    /// See [`Capabilities::speak`]. Since 0.4.10.
193    pub fn with_speak(mut self, on: bool) -> Self {
194        self.speak = on;
195        self
196    }
197
198    /// A catalog/1 entry with these inputs and limits: `entry` with [`CatalogModel::inputs`]
199    /// and [`CatalogModel::limits`] set from these (the rest of `entry` is kept).
200    pub fn apply_to(&self, entry: CatalogModel) -> CatalogModel {
201        entry.with_inputs(self.inputs()).with_limits(self.limits)
202    }
203
204    /// The catalog/1 purpose of a model with these capabilities: [`Purpose::Embedding`] for an
205    /// embedding model (`embedding`, as [`ModelLaunch::embedding`] or [`ModelStatus::embedding`](crate::ModelStatus::embedding)),
206    /// else [`Purpose::Speak`] when it [speaks](Capabilities::speak) (since 0.4.10), else
207    /// [`Purpose::Transcribe`] when it [transcribes](Capabilities::transcribe), else
208    /// [`Purpose::Chat`].
209    pub fn purpose(&self, embedding: bool) -> Purpose {
210        if embedding {
211            Purpose::Embedding
212        } else if self.speak {
213            Purpose::Speak
214        } else if self.transcribe {
215            Purpose::Transcribe
216        } else {
217            Purpose::Chat
218        }
219    }
220
221    /// The inputs beyond text, as `weirdnet-agent` [`Modalities`] (what catalog entries carry),
222    /// video included (since 0.4.10).
223    pub fn inputs(&self) -> Modalities {
224        Modalities::new(self.vision, self.audio).with_video(self.video)
225    }
226
227    /// What a request needing `needed` would lack here (`"images"`, `"audio"`, ...), if anything.
228    pub fn lacking(&self, needed: Modalities) -> Option<&'static str> {
229        self.inputs().lacking(needed)
230    }
231
232    /// What both allow, with the stricter limits ([`MediaLimits::tightest`]: a limit only one
233    /// side knows is kept).
234    pub fn intersect(self, other: Self) -> Self {
235        Self {
236            chat: self.chat && other.chat,
237            embeddings: self.embeddings && other.embeddings,
238            vision: self.vision && other.vision,
239            audio: self.audio && other.audio,
240            limits: self.limits.tightest(other.limits),
241            transcribe: self.transcribe && other.transcribe,
242            video: self.video && other.video,
243            speak: self.speak && other.speak,
244        }
245    }
246}
247
248/// One engine binary and how long it may take to come up.
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub struct EngineConfig {
251    pub kind: EngineKind,
252    pub program: PathBuf,
253    /// Arguments added to every launch of this engine.
254    pub extra_args: Vec<String>,
255    pub ready_timeout: Duration,
256}
257
258impl EngineConfig {
259    pub fn llamacpp(program: impl Into<PathBuf>) -> Self {
260        Self { kind: EngineKind::Llamacpp, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(300) }
261    }
262
263    pub fn vllm(program: impl Into<PathBuf>) -> Self {
264        Self { kind: EngineKind::Vllm, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
265    }
266
267    /// vLLM-Omni: `program` is the `vllm` of the venv vLLM-Omni is installed in; each model
268    /// starts as `vllm serve MODEL --omni`. Since 0.4.10.
269    pub fn vllm_omni(program: impl Into<PathBuf>) -> Self {
270        Self { kind: EngineKind::VllmOmni, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
271    }
272
273    /// The engine's version as `program --version` prints it (its first line, stdout or
274    /// stderr), within 30 s; `None` when it doesn't run or says nothing. For a setup screen and
275    /// logs. Since 0.4.10.
276    pub async fn version(&self) -> Option<String> {
277        let mut cmd = Command::new(&self.program);
278        cmd.arg("--version").stdin(std::process::Stdio::null()).kill_on_drop(true);
279        let out = tokio::time::timeout(Duration::from_secs(30), cmd.output()).await.ok()?.ok()?;
280        let text = [out.stdout, out.stderr].iter().map(|b| String::from_utf8_lossy(b).into_owned()).collect::<Vec<_>>().join("\n");
281        text.lines().map(str::trim).find(|l| !l.is_empty()).map(str::to_string)
282    }
283
284    /// `program` is `mlx_lm.server`, such as [`crate::mlx::server_in`] of a venv made by
285    /// [`crate::mlx::install`].
286    pub fn mlx(program: impl Into<PathBuf>) -> Self {
287        Self { kind: EngineKind::Mlx, program: program.into(), extra_args: Vec::new(), ready_timeout: Duration::from_secs(1200) }
288    }
289
290    /// The command for `model` on `127.0.0.1:port`. The API key goes in the environment, not the
291    /// command line, so other local users can't read it from the process list.
292    ///
293    /// MLX-LM takes no API key: the supervisor starts it on a private port and checks the key in
294    /// a proxy on the advertised one, so `api_key` is not passed to it.
295    pub fn command(&self, model: &ModelLaunch, port: u16, api_key: &str) -> Command {
296        let mut cmd = Command::new(&self.program);
297        match self.kind {
298            EngineKind::Llamacpp => {
299                cmd.args(["--model", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--alias", &model.id, "--no-webui"]);
300                if let Some(ctx) = model.context {
301                    cmd.args(["--ctx-size", &ctx.to_string()]);
302                }
303                if let Some(slots) = model.slots {
304                    cmd.args(["--parallel", &slots.to_string()]);
305                }
306                if let Some(ngl) = model.gpu_layers {
307                    cmd.args(["--n-gpu-layers", &ngl.to_string()]);
308                }
309                if model.embedding {
310                    cmd.arg("--embedding");
311                }
312                if let Some(mmproj) = &model.mmproj {
313                    cmd.args(["--mmproj", mmproj]);
314                }
315                // Adapters load at scale 0; each request names its own (`"lora"` in the body).
316                // `--lora` rather than `--lora-scaled FNAME:SCALE`, which splits on `:` and so
317                // breaks on Windows paths; the scale is sent per request anyway.
318                for a in &model.adapters {
319                    cmd.args(["--lora", &a.path]);
320                }
321                if !model.adapters.is_empty() {
322                    cmd.arg("--lora-init-without-apply");
323                }
324                cmd.env("LLAMA_API_KEY", api_key);
325            }
326            EngineKind::Vllm => {
327                cmd.args(["serve", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--served-model-name", &model.id]);
328                if let Some(ctx) = model.context {
329                    cmd.args(["--max-model-len", &ctx.to_string()]);
330                }
331                if let Some(slots) = model.slots {
332                    cmd.args(["--max-num-seqs", &slots.to_string()]);
333                }
334                if model.runtime_lora() {
335                    cmd.arg("--enable-lora");
336                    if !model.adapters.is_empty() {
337                        // One `--lora-modules` with every module: vLLM keeps only the last flag.
338                        cmd.arg("--lora-modules");
339                        for a in &model.adapters {
340                            cmd.arg(serde_json::json!({"name": a.id, "path": a.path, "base_model_name": model.id}).to_string());
341                        }
342                    }
343                    let max = (model.adapters.len() as u32).max(model.lora_slots.unwrap_or(0)).max(1);
344                    cmd.args(["--max-loras", &max.to_string()]);
345                    // Lets the supervisor add and remove adapters on the running engine
346                    // (`/v1/load_lora_adapter`); the endpoints sit behind the API key on loopback.
347                    cmd.env("VLLM_ALLOW_RUNTIME_LORA_UPDATING", "True");
348                }
349                cmd.env("VLLM_API_KEY", api_key);
350            }
351            EngineKind::VllmOmni => {
352                // Reference clips travel inline as `data:` URLs only, so it never gets
353                // `--allowed-local-media-path` (see `ModelLaunch::check_speech`).
354                cmd.args(["serve", &model.source, "--omni", "--host", "127.0.0.1", "--port", &port.to_string(), "--served-model-name", &model.id]);
355                if let Some(ctx) = model.context {
356                    cmd.args(["--max-model-len", &ctx.to_string()]);
357                }
358                if let Some(slots) = model.slots {
359                    cmd.args(["--max-num-seqs", &slots.to_string()]);
360                }
361                cmd.env("VLLM_API_KEY", api_key);
362            }
363            EngineKind::Mlx => {
364                // mlx_lm.server stops at 512 tokens unless told otherwise; the others run to the
365                // context window.
366                let max = model.context.unwrap_or(crate::mlx::DEFAULT_MAX_TOKENS).to_string();
367                cmd.args(["--model", &model.source, "--host", "127.0.0.1", "--port", &port.to_string(), "--max-tokens", &max]);
368            }
369        }
370        cmd.args(&self.extra_args).args(&model.extra_args);
371        cmd
372    }
373}
374
375/// A LoRA adapter served on top of a [`ModelLaunch`]'s base model, under its own pool id.
376#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
377#[non_exhaustive]
378pub struct LoraAdapter {
379    /// Pool id; requests for it go to the base model's engine with the adapter applied.
380    pub id: String,
381    /// A LoRA GGUF for llama.cpp; a PEFT directory (or Hub id) for vLLM.
382    pub path: String,
383    /// How strongly it applies (llama.cpp per request; default 1.0). vLLM ignores it.
384    #[serde(default, skip_serializing_if = "Option::is_none")]
385    pub scale: Option<f32>,
386}
387
388// `check_adapters` refuses a scale that isn't finite, so equality is total for served adapters.
389impl Eq for LoraAdapter {}
390
391impl LoraAdapter {
392    pub fn new(id: impl Into<String>, path: impl Into<String>) -> Self {
393        Self { id: id.into(), path: path.into(), scale: None }
394    }
395
396    pub fn with_scale(mut self, scale: f32) -> Self {
397        self.scale = Some(scale);
398        self
399    }
400
401    /// The scale requests use: [`LoraAdapter::scale`], else 1.0.
402    pub fn effective_scale(&self) -> f32 {
403        self.scale.unwrap_or(1.0)
404    }
405}
406
407/// A model this node may be told to load.
408#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
409#[non_exhaustive]
410pub struct ModelLaunch {
411    /// Pool id; also the engine's served model name.
412    pub id: String,
413    pub engine: EngineKind,
414    /// A GGUF path for llama.cpp; a path or Hub id for vLLM; an MLX-format model directory (or
415    /// Hub id) for MLX-LM.
416    pub source: String,
417    pub context: Option<u32>,
418    /// Concurrent requests (llama.cpp slots, vLLM max sequences).
419    pub slots: Option<u32>,
420    /// llama.cpp `--n-gpu-layers`; `None` keeps the engine's default (all that fit).
421    pub gpu_layers: Option<i32>,
422    /// Models in the same group are never resident together.
423    pub swap_group: Option<String>,
424    pub embedding: bool,
425    pub extra_args: Vec<String>,
426    /// Unload after this long without requests; `None` keeps it loaded.
427    #[serde(default, with = "opt_secs")]
428    pub idle_ttl: Option<Duration>,
429    /// Wrap a stock server already running on loopback (such as `vllm serve` or `llama-server`
430    /// started by hand) instead of starting an engine: the node only probes, advertises and forwards.
431    #[serde(default)]
432    pub wrap: Option<Wrap>,
433    /// LoRA adapters served on this base (llama.cpp and vLLM only; see
434    /// [`ModelLaunch::check_adapters`]). Each is its own pool id.
435    #[serde(default, skip_serializing_if = "Vec::is_empty")]
436    pub adapters: Vec<LoraAdapter>,
437    /// vLLM only: start the engine with LoRA on (`--enable-lora`, `--max-loras` at least this)
438    /// even without adapters, so adapters can be added and removed while it runs
439    /// ([`crate::Supervisor::add_adapter_live`]). A vLLM base started with adapters can take more
440    /// at run time without it. llama.cpp ignores it: llama-server loads adapter files only at start.
441    #[serde(default, skip_serializing_if = "Option::is_none")]
442    pub lora_slots: Option<u32>,
443    /// llama.cpp only: a multimodal projector GGUF (`--mmproj`), so the model takes images
444    /// (and audio, when the projector has it). See [`crate::Supervisor::set_projector_live`].
445    #[serde(default, skip_serializing_if = "Option::is_none")]
446    pub mmproj: Option<String>,
447    /// Media and request limits the operator sets for this model on this hardware (such as
448    /// `image_tokens` or `max_images` a node can't measure); they become
449    /// [`Capabilities::limits`]. Unknown by default, and never defaulted in code.
450    #[serde(default, skip_serializing_if = "MediaLimits::is_unknown")]
451    pub limits: MediaLimits,
452    /// The transcription role: a speech-to-text model (Voxtral through llama.cpp with its audio
453    /// projector, Whisper through vLLM), served over infer/2 `Transcribe` and published with
454    /// [`Purpose::Transcribe`]. See
455    /// [`ModelLaunch::capabilities`] for when the engine can serve it.
456    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
457    pub transcribe: bool,
458    /// The model reads video parts whole (`video_url`, such as Qwen2.5-VL or Qwen3-VL on vLLM).
459    /// The operator says so: the engine doesn't report it. Served on vLLM (a wrapped
460    /// mistral.rs server is declared as vLLM: it takes the same `video_url` part); llama.cpp and
461    /// MLX-LM take no video, and a request with a video part is refused there with
462    /// `weirdnet-agent`'s `VIDEO_FALLBACK` (send frames instead). Since 0.4.10.
463    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
464    pub video: bool,
465    /// The speech role: a text-to-speech model (Kokoro, VoxCPM2, Fish Audio Drama 3 or Qwen3-TTS
466    /// through llama.cpp with its projector; Qwen3-TTS through vLLM-Omni), served over infer/2
467    /// `Speak` and published with [`Purpose::Speak`]. A speaking model serves nothing else.
468    /// See [`ModelLaunch::capabilities`]. Since 0.4.10.
469    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
470    pub speak: bool,
471    /// The operator's speech settings for a speaking model, field by field, narrowing only: fewer
472    /// voices or languages, smaller limits, or a limit the engine doesn't report
473    /// (`weirdnet-agent`'s [`SpeechProfile::narrowed_by`]). Never defaults; unknown by default.
474    /// Widening what the model's catalog entry says is refused by [`ModelLaunch::check_speech`],
475    /// and widening what the engine reports at load leaves the model without a profile.
476    /// Since 0.4.10.
477    #[serde(default, skip_serializing_if = "SpeechProfile::is_unknown")]
478    pub speech: SpeechProfile,
479}
480
481/// A stock OpenAI-compatible server the node forwards to but doesn't own.
482#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
483pub struct Wrap {
484    /// Base URL without `/v1`, such as `http://127.0.0.1:8000`. Must be loopback.
485    pub url: String,
486    /// The server's API key, if it wants one (read from the environment or a file by the caller).
487    #[serde(default, skip_serializing)]
488    pub api_key: Option<String>,
489}
490
491impl std::fmt::Debug for Wrap {
492    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
493        f.debug_struct("Wrap").field("url", &self.url).field("api_key", &self.api_key.as_ref().map(|_| "<redacted>")).finish()
494    }
495}
496
497impl Wrap {
498    /// Only loopback URLs: the wrapped server is on this machine, reached without TLS.
499    pub fn check(&self) -> Result<(), String> {
500        let rest = self.url.strip_prefix("http://").ok_or_else(|| format!("wrap url {} must start with http:// (loopback only)", self.url))?;
501        let host = match rest.strip_prefix('[') {
502            Some(v6) => v6.split(']').next().unwrap_or(""),
503            None => rest.split(['/', ':']).next().unwrap_or(""),
504        };
505        if matches!(host, "127.0.0.1" | "localhost" | "::1") { Ok(()) } else { Err(format!("wrap url {} is not loopback", self.url)) }
506    }
507
508    pub fn base(&self) -> String {
509        self.url.trim_end_matches('/').trim_end_matches("/v1").to_string()
510    }
511}
512
513mod opt_secs {
514    use std::time::Duration;
515
516    use serde::{Deserialize, Deserializer, Serializer};
517
518    pub fn serialize<S: Serializer>(d: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
519        match d {
520            Some(d) => s.serialize_some(&d.as_secs()),
521            None => s.serialize_none(),
522        }
523    }
524
525    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
526        Ok(Option::<u64>::deserialize(d)?.map(Duration::from_secs))
527    }
528}
529
530impl ModelLaunch {
531    pub fn new(id: impl Into<String>, engine: EngineKind, source: impl Into<String>) -> Self {
532        Self {
533            id: id.into(),
534            engine,
535            source: source.into(),
536            context: None,
537            slots: None,
538            gpu_layers: None,
539            swap_group: None,
540            embedding: false,
541            extra_args: Vec::new(),
542            idle_ttl: None,
543            wrap: None,
544            adapters: Vec::new(),
545            lora_slots: None,
546            mmproj: None,
547            limits: MediaLimits::UNKNOWN,
548            transcribe: false,
549            video: false,
550            speak: false,
551            speech: SpeechProfile::default(),
552        }
553    }
554
555    /// See [`ModelLaunch::video`]. Since 0.4.10.
556    pub fn with_video(mut self, on: bool) -> Self {
557        self.video = on;
558        self
559    }
560
561    /// See [`ModelLaunch::speak`]. Since 0.4.10.
562    pub fn with_speak(mut self, on: bool) -> Self {
563        self.speak = on;
564        self
565    }
566
567    /// See [`ModelLaunch::speech`]. Since 0.4.10.
568    pub fn with_speech(mut self, speech: SpeechProfile) -> Self {
569        self.speech = speech;
570        self
571    }
572
573    /// What `weirdnet-model`'s catalog says this speaking model does ([`CatalogEntry::speech`](weirdnet_model::hw::CatalogEntry::speech)),
574    /// for the entry with this id or this source (a vLLM-Omni Hub repo, a llama.cpp GGUF file
575    /// name) whose files suit the engine: GGUF for llama.cpp, Hub checkpoints for vLLM-Omni.
576    /// `None` when no entry matches. Since 0.4.10.
577    pub fn cataloged_speech(&self) -> Option<weirdnet_model::SpeechProfile> {
578        if !matches!(self.engine, EngineKind::Llamacpp | EngineKind::VllmOmni) {
579            return None;
580        }
581        let gguf = self.engine == EngineKind::Llamacpp;
582        let name = |p: &str| Path::new(p).file_name().map(|n| n.to_string_lossy().to_ascii_lowercase());
583        let file = name(&self.source);
584        weirdnet_model::hw::by_purpose(weirdnet_model::hw::Purpose::Speak)
585            .into_iter()
586            .filter(|e| e.is_gguf() == gguf)
587            .find(|e| {
588                e.id() == self.id
589                    || (!gguf && e.spec.repo.eq_ignore_ascii_case(self.source.trim()))
590                    || (gguf && file.is_some() && name(&e.spec.file) == file)
591            })
592            .and_then(|e| e.speech())
593    }
594
595    /// Whether the speech role can be served as set: only on llama.cpp (with the model's
596    /// projector) or vLLM-Omni, not as an embedding or transcription model, never with
597    /// vLLM-Omni's `--allowed-local-media-path` (reference clips travel inline only), and
598    /// operator settings ([`ModelLaunch::speech`]) that only narrow what the model's catalog
599    /// entry says, when there is one ([`ModelLaunch::cataloged_speech`]). Settings on a model
600    /// without the role are refused too. Since 0.4.10.
601    pub fn check_speech(&self) -> Result<(), String> {
602        let id = &self.id;
603        if !self.speak {
604            return if self.speech.is_unknown() { Ok(()) } else { Err(format!("{id}: speech settings need the speak role")) };
605        }
606        if self.embedding || self.transcribe {
607            return Err(format!("{id}: a speaking model can't also be an embedding or transcription model"));
608        }
609        match self.engine {
610            EngineKind::Llamacpp if !self.has_projector() => {
611                return Err(format!("{id}: llama.cpp speaks only with the model's projector (mmproj)"));
612            }
613            EngineKind::Llamacpp | EngineKind::VllmOmni => {}
614            other => return Err(format!("{id}: {} has no speech engine; use llama.cpp or vLLM-Omni", other.name())),
615        }
616        if self.engine == EngineKind::VllmOmni && self.extra_args.iter().any(|a| a.split('=').next() == Some("--allowed-local-media-path")) {
617            return Err(format!("{id}: vLLM-Omni must not read local media (--allowed-local-media-path); reference clips travel inline"));
618        }
619        if !self.speech.is_unknown()
620            && let Some(cataloged) = self.cataloged_speech()
621        {
622            cataloged.to_agent().narrowed_by(&self.speech).map_err(|e| format!("{id}: speech settings widen the model's: {e}"))?;
623        }
624        Ok(())
625    }
626
627    /// See [`ModelLaunch::transcribe`].
628    pub fn with_transcribe(mut self, on: bool) -> Self {
629        self.transcribe = on;
630        self
631    }
632
633    /// Its catalog/1 purpose: [`Purpose::Embedding`] for an embedding model, [`Purpose::Transcribe`]
634    /// when it transcribes here ([`Capabilities::transcribe`]), else [`Purpose::Chat`].
635    pub fn purpose(&self) -> Purpose {
636        self.capabilities().purpose(self.embedding)
637    }
638
639    /// See [`ModelLaunch::limits`].
640    pub fn with_limits(mut self, limits: MediaLimits) -> Self {
641        self.limits = limits;
642        self
643    }
644
645    /// See [`ModelLaunch::mmproj`].
646    pub fn with_mmproj(mut self, path: impl Into<String>) -> Self {
647        self.mmproj = Some(path.into());
648        self
649    }
650
651    /// See [`ModelLaunch::lora_slots`].
652    pub fn with_lora_slots(mut self, slots: u32) -> Self {
653        self.lora_slots = Some(slots);
654        self
655    }
656
657    /// Whether the engine starts able to take adapters at run time: vLLM with adapters or
658    /// [`ModelLaunch::lora_slots`].
659    pub fn runtime_lora(&self) -> bool {
660        self.engine == EngineKind::Vllm && self.wrap.is_none() && (!self.adapters.is_empty() || self.lora_slots.is_some_and(|n| n > 0))
661    }
662
663    pub fn with_adapters(mut self, adapters: Vec<LoraAdapter>) -> Self {
664        self.adapters = adapters;
665        self
666    }
667
668    /// The pool ids this launch serves: the base's, then each adapter's.
669    pub fn served_ids(&self) -> Vec<String> {
670        std::iter::once(self.id.clone()).chain(self.adapters.iter().map(|a| a.id.clone())).collect()
671    }
672
673    /// Whether the adapters can be served: llama.cpp or vLLM (not MLX-LM, not a wrapped server,
674    /// not an embedding model), unique non-empty ids other than the base's, finite scales, and
675    /// paths the engine takes. On llama.cpp each adapter must be a LoRA GGUF (`general.type` =
676    /// `adapter`, `adapter.type` = `lora`) with the base GGUF's architecture; both headers are
677    /// read. On vLLM a local adapter must be a PEFT LoRA directory; anything else must look like a
678    /// Hub id.
679    pub fn check_adapters(&self) -> Result<(), String> {
680        if self.adapters.is_empty() {
681            return Ok(());
682        }
683        let id = &self.id;
684        if self.wrap.is_some() {
685            return Err(format!("{id}: a wrapped server can't take adapters from this node"));
686        }
687        if self.embedding {
688            return Err(format!("{id}: embedding models take no adapters"));
689        }
690        if !matches!(self.engine, EngineKind::Llamacpp | EngineKind::Vllm) {
691            return Err(format!("{id}: {} serves no adapters here; use llama.cpp or vLLM", self.engine.name()));
692        }
693        let mut seen = std::collections::HashSet::new();
694        for a in &self.adapters {
695            if a.id.trim().is_empty() {
696                return Err(format!("{id}: an adapter needs an id"));
697            }
698            if a.id == *id {
699                return Err(format!("{id}: adapter id {} is the base model's", a.id));
700            }
701            if !seen.insert(a.id.as_str()) {
702                return Err(format!("{id}: adapter id {} is used twice", a.id));
703            }
704            if a.scale.is_some_and(|s| !s.is_finite()) {
705                return Err(format!("{}: the scale must be a finite number", a.id));
706            }
707        }
708        match self.engine {
709            EngineKind::Llamacpp => {
710                let header = |path: &str| -> Result<weirdnet_model::gguf::GgufHeader, String> {
711                    let f = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
712                    weirdnet_model::gguf::read_header(std::io::BufReader::new(f)).map_err(|e| format!("{path}: {e}"))
713                };
714                let base = header(&self.source)?;
715                if base.kind.is_adapter() {
716                    return Err(format!("{id}: {} is an adapter, not a base model", self.source));
717                }
718                for a in &self.adapters {
719                    if a.path.contains(',') {
720                        return Err(format!("{}: llama.cpp can't take a path with a comma ({})", a.id, a.path));
721                    }
722                    let h = header(&a.path)?;
723                    if !h.kind.is_lora() {
724                        return Err(format!("{}: {} is not a LoRA adapter GGUF", a.id, a.path));
725                    }
726                    if h.architecture != base.architecture {
727                        return Err(format!("{}: adapter architecture {} doesn't match the base's {}", a.id, h.architecture, base.architecture));
728                    }
729                }
730            }
731            _ => {
732                for a in &self.adapters {
733                    let p = Path::new(&a.path);
734                    if p.is_dir() {
735                        let config: serde_json::Value = std::fs::read(p.join("adapter_config.json"))
736                            .ok()
737                            .and_then(|b| serde_json::from_slice(&b).ok())
738                            .ok_or_else(|| format!("{}: {} has no readable adapter_config.json", a.id, a.path))?;
739                        if !config["peft_type"].as_str().unwrap_or("LORA").eq_ignore_ascii_case("lora") {
740                            return Err(format!("{}: {} is not a LoRA adapter", a.id, a.path));
741                        }
742                    } else if p.exists() {
743                        return Err(format!("{}: vLLM takes a PEFT directory, not the file {}", a.id, a.path));
744                    } else if weirdnet_model::hf::check_repo(&a.path).is_err() {
745                        return Err(format!("{}: {} is neither a directory nor a Hub id", a.id, a.path));
746                    }
747                }
748            }
749        }
750        Ok(())
751    }
752
753    /// What this model takes. Embedding models only embed (and can't run on MLX-LM at all). A
754    /// llama.cpp model takes images and audio when it has a multimodal projector
755    /// ([`ModelLaunch::mmproj`], or `--mmproj` in `extra_args`); the projector decides which, and
756    /// llama-server refuses what it lacks. vLLM and MLX-LM models are text only here. The
757    /// [`limits`](ModelLaunch::limits) are carried over as set. A model with the
758    /// [`transcribe`](ModelLaunch::transcribe) role transcribes on llama.cpp with a projector
759    /// (an audio one: llama-server refuses audio otherwise) and on vLLM; never as an embedding
760    /// model or on MLX-LM.
761    ///
762    /// Since 0.4.10: a model marked [`video`](ModelLaunch::video) reads video on vLLM (nowhere
763    /// else); a model with the [`speak`](ModelLaunch::speak) role speaks and does nothing else,
764    /// on llama.cpp with its projector or on vLLM-Omni (elsewhere it serves nothing).
765    ///
766    /// Since 0.4.12: a vLLM model marked `video` takes images too (it reads video as frames, and
767    /// such models read single images the same way), so its image cost, measured at load for
768    /// Qwen-VL processors, is published with it.
769    pub fn capabilities(&self) -> Capabilities {
770        let own = if self.embedding {
771            Capabilities::embeddings()
772        } else if self.speak {
773            let speaks = match self.engine {
774                EngineKind::Llamacpp => self.has_projector(),
775                EngineKind::VllmOmni => true,
776                _ => false,
777            };
778            Capabilities::default().with_speak(speaks)
779        } else {
780            let media = self.engine == EngineKind::Llamacpp && self.has_projector();
781            let transcribe = self.transcribe && (media || self.engine == EngineKind::Vllm);
782            let video = self.video && self.engine == EngineKind::Vllm;
783            // A model that reads video reads its frames as images: it takes images too.
784            Capabilities::text().with_vision(media || video).with_audio(media).with_transcribe(transcribe).with_video(video)
785        };
786        own.with_limits(self.limits).intersect(self.engine.capabilities())
787    }
788
789    fn has_projector(&self) -> bool {
790        self.mmproj.is_some() || self.extra_args.iter().any(|a| matches!(a.split('=').next(), Some("--mmproj" | "-mm" | "--mmproj-url" | "-mmu")))
791    }
792}
793
794/// The first executable called `name` on `PATH`.
795pub fn find_in_path(name: &str) -> Option<PathBuf> {
796    let path = std::env::var_os("PATH")?;
797    std::env::split_paths(&path).map(|d| d.join(name)).find(|p| is_executable(p))
798}
799
800fn is_executable(p: &Path) -> bool {
801    #[cfg(unix)]
802    {
803        use std::os::unix::fs::PermissionsExt;
804        std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
805    }
806    #[cfg(not(unix))]
807    {
808        p.is_file()
809    }
810}
811
812#[cfg(test)]
813pub(crate) mod tests {
814    use super::*;
815
816    fn args(cmd: &Command) -> Vec<String> {
817        cmd.as_std().get_args().map(|a| a.to_string_lossy().into_owned()).collect()
818    }
819
820    #[test]
821    fn llama_args() {
822        let mut m = ModelLaunch::new("qwen3-8b", EngineKind::Llamacpp, "/m/q.gguf");
823        m.context = Some(8192);
824        m.slots = Some(2);
825        let cmd = EngineConfig::llamacpp("/bin/llama-server").command(&m, 4321, "k");
826        let a = args(&cmd);
827        assert!(a.windows(2).any(|w| w == ["--host", "127.0.0.1"]));
828        assert!(a.windows(2).any(|w| w == ["--port", "4321"]));
829        assert!(a.windows(2).any(|w| w == ["--alias", "qwen3-8b"]));
830        assert!(a.windows(2).any(|w| w == ["--parallel", "2"]));
831        assert!(!a.iter().any(|x| x == "k"), "the key stays out of argv");
832    }
833
834    #[test]
835    fn a_projector_goes_on_the_command_and_into_capabilities() {
836        let m = ModelLaunch::new("v", EngineKind::Llamacpp, "/m/v.gguf");
837        assert!(!m.capabilities().vision);
838        let m = m.with_mmproj("/m/mmproj.gguf");
839        let a = args(&EngineConfig::llamacpp("/bin/llama-server").command(&m, 4321, "k"));
840        assert!(a.windows(2).any(|w| w == ["--mmproj", "/m/mmproj.gguf"]));
841        assert!(m.capabilities().vision);
842        let back: ModelLaunch = serde_json::from_value(serde_json::to_value(&m).unwrap()).unwrap();
843        assert_eq!(back.mmproj.as_deref(), Some("/m/mmproj.gguf"));
844    }
845
846    /// A GGUF header with string, u32 and f32 values (enough for adapter checks).
847    pub(crate) fn gguf(kv: &[(&str, serde_json::Value)]) -> Vec<u8> {
848        let mut out = b"GGUF".to_vec();
849        out.extend(3u32.to_le_bytes());
850        out.extend(0u64.to_le_bytes());
851        out.extend((kv.len() as u64).to_le_bytes());
852        let s = |out: &mut Vec<u8>, s: &str| {
853            out.extend((s.len() as u64).to_le_bytes());
854            out.extend(s.as_bytes());
855        };
856        for (k, v) in kv {
857            s(&mut out, k);
858            match v {
859                serde_json::Value::String(t) => {
860                    out.extend(8u32.to_le_bytes());
861                    s(&mut out, t);
862                }
863                serde_json::Value::Number(n) if n.is_u64() => {
864                    out.extend(4u32.to_le_bytes());
865                    out.extend((n.as_u64().unwrap() as u32).to_le_bytes());
866                }
867                serde_json::Value::Number(n) => {
868                    out.extend(6u32.to_le_bytes());
869                    out.extend((n.as_f64().unwrap() as f32).to_le_bytes());
870                }
871                serde_json::Value::Bool(b) => {
872                    out.extend(7u32.to_le_bytes());
873                    out.push(*b as u8);
874                }
875                _ => unreachable!(),
876            }
877        }
878        out
879    }
880
881    pub(crate) fn base_gguf(arch: &str) -> Vec<u8> {
882        gguf(&[("general.architecture", arch.into()), (format!("{arch}.block_count").as_str(), 1.into())])
883    }
884
885    pub(crate) fn lora_gguf(arch: &str) -> Vec<u8> {
886        gguf(&[
887            ("general.architecture", arch.into()),
888            ("general.type", "adapter".into()),
889            ("adapter.type", "lora".into()),
890            ("adapter.lora.alpha", 16.5.into()),
891        ])
892    }
893
894    #[test]
895    fn llama_adapter_args_and_checks() {
896        let tmp = tempfile::tempdir().unwrap();
897        let w = |name: &str, b: Vec<u8>| {
898            let p = tmp.path().join(name);
899            std::fs::write(&p, b).unwrap();
900            p.display().to_string()
901        };
902        let base = w("base.gguf", base_gguf("qwen3"));
903        let (a, b) = (w("a.gguf", lora_gguf("qwen3")), w("b.gguf", lora_gguf("qwen3")));
904        let m = ModelLaunch::new("qwen", EngineKind::Llamacpp, &base)
905            .with_adapters(vec![LoraAdapter::new("tune-a", &a).with_scale(0.5), LoraAdapter::new("tune-b", &b)]);
906        assert_eq!(m.served_ids(), ["qwen", "tune-a", "tune-b"]);
907        m.check_adapters().unwrap();
908        let argv = args(&EngineConfig::llamacpp("llama-server").command(&m, 1, "k"));
909        let loras: Vec<&String> = argv.windows(2).filter(|w| w[0] == "--lora").map(|w| &w[1]).collect();
910        assert_eq!(loras, [&a, &b], "one --lora per adapter, in order");
911        assert!(argv.iter().any(|x| x == "--lora-init-without-apply"));
912        assert!(
913            !args(&EngineConfig::llamacpp("l").command(&ModelLaunch::new("x", EngineKind::Llamacpp, &base), 1, "k"))
914                .iter()
915                .any(|x| x.starts_with("--lora"))
916        );
917
918        let bad =
919            |adapters: Vec<LoraAdapter>| ModelLaunch::new("qwen", EngineKind::Llamacpp, &base).with_adapters(adapters).check_adapters().unwrap_err();
920        assert!(bad(vec![LoraAdapter::new("qwen", &a)]).contains("base model's"));
921        assert!(bad(vec![LoraAdapter::new("t", &a), LoraAdapter::new("t", &b)]).contains("twice"));
922        assert!(bad(vec![LoraAdapter::new("t", &a).with_scale(f32::NAN)]).contains("finite"));
923        assert!(bad(vec![LoraAdapter::new("t", &base)]).contains("not a LoRA"));
924        assert!(bad(vec![LoraAdapter::new("t", w("llama.gguf", lora_gguf("llama")))]).contains("architecture"));
925        assert!(bad(vec![LoraAdapter::new("t", tmp.path().join("missing.gguf").display().to_string())]).contains("missing.gguf"));
926        assert!(bad(vec![LoraAdapter::new("t", w("a,b.gguf", lora_gguf("qwen3")))]).contains("comma"));
927        let mut emb = m.clone();
928        emb.embedding = true;
929        assert!(emb.check_adapters().unwrap_err().contains("embedding"));
930        let mut wrapped = m.clone();
931        wrapped.wrap = Some(Wrap { url: "http://127.0.0.1:1".into(), api_key: None });
932        assert!(wrapped.check_adapters().unwrap_err().contains("wrapped"));
933        let mlx = ModelLaunch::new("m", EngineKind::Mlx, &base).with_adapters(vec![LoraAdapter::new("t", &a)]);
934        assert!(mlx.check_adapters().unwrap_err().contains("mlx"));
935        let json = serde_json::to_string(&ModelLaunch::new("x", EngineKind::Llamacpp, "/m")).unwrap();
936        assert!(!json.contains("adapters"), "no adapters, same JSON as before");
937    }
938
939    #[test]
940    fn vllm_adapter_args_and_checks() {
941        let tmp = tempfile::tempdir().unwrap();
942        let peft = tmp.path().join("tune");
943        std::fs::create_dir(&peft).unwrap();
944        std::fs::write(peft.join("adapter_config.json"), br#"{"peft_type":"LORA","r":8}"#).unwrap();
945        let peft = peft.display().to_string();
946        let m = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B")
947            .with_adapters(vec![LoraAdapter::new("tune", &peft), LoraAdapter::new("hub", "owner/some-lora")]);
948        m.check_adapters().unwrap();
949        let a = args(&EngineConfig::vllm("vllm").command(&m, 9000, "k"));
950        assert_eq!(a.iter().filter(|x| *x == "--lora-modules").count(), 1, "vLLM keeps only the last --lora-modules");
951        let at = a.iter().position(|x| x == "--lora-modules").unwrap();
952        let mods: Vec<serde_json::Value> = a[at + 1..at + 3].iter().map(|j| serde_json::from_str(j).unwrap()).collect();
953        assert_eq!(mods[0], serde_json::json!({"name": "tune", "path": peft, "base_model_name": "big"}));
954        assert_eq!(mods[1]["name"], "hub");
955        assert!(a.iter().any(|x| x == "--enable-lora"));
956        assert!(a.windows(2).any(|w| w == ["--max-loras", "2"]));
957        let cmd = EngineConfig::vllm("vllm").command(&m, 9000, "k");
958        let env: Vec<_> = cmd.as_std().get_envs().map(|(k, v)| (k.to_owned(), v.map(|v| v.to_owned()))).collect();
959        assert!(env.iter().any(|(k, v)| k == "VLLM_ALLOW_RUNTIME_LORA_UPDATING" && v.as_deref() == Some("True".as_ref())));
960        // LoRA on without adapters at start, for adapters added while it runs.
961        let empty = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B").with_lora_slots(4);
962        assert!(empty.runtime_lora());
963        let a = args(&EngineConfig::vllm("vllm").command(&empty, 9000, "k"));
964        assert!(a.iter().any(|x| x == "--enable-lora") && !a.iter().any(|x| x == "--lora-modules"));
965        assert!(a.windows(2).any(|w| w == ["--max-loras", "4"]));
966        let plain = args(&EngineConfig::vllm("vllm").command(&ModelLaunch::new("big", EngineKind::Vllm, "Q/Q"), 9000, "k"));
967        assert!(!plain.iter().any(|x| x == "--enable-lora"));
968        assert!(!ModelLaunch::new("q", EngineKind::Llamacpp, "/q.gguf").with_lora_slots(2).runtime_lora(), "llama.cpp ignores it");
969        let file = tmp.path().join("x.gguf");
970        std::fs::write(&file, lora_gguf("qwen3")).unwrap();
971        let bad = |path: String| {
972            ModelLaunch::new("big", EngineKind::Vllm, "Q/Q").with_adapters(vec![LoraAdapter::new("t", path)]).check_adapters().unwrap_err()
973        };
974        assert!(bad(file.display().to_string()).contains("PEFT directory"));
975        assert!(bad("/no/such/dir".into()).contains("Hub id"));
976    }
977
978    #[test]
979    fn wrap_is_loopback_only() {
980        let w = |u: &str| Wrap { url: u.into(), api_key: None }.check();
981        assert!(w("http://127.0.0.1:8000").is_ok());
982        assert!(w("http://localhost:8000/").is_ok());
983        assert!(w("http://[::1]:8000").is_ok());
984        assert!(w("https://127.0.0.1:8000").is_err());
985        assert!(w("http://10.0.0.2:8000").is_err());
986        assert!(w("http://127.0.0.1.evil:8000").is_err());
987        assert_eq!(Wrap { url: "http://127.0.0.1:8000/v1/".into(), api_key: None }.base(), "http://127.0.0.1:8000");
988    }
989
990    #[test]
991    fn vllm_args() {
992        let m = ModelLaunch::new("big", EngineKind::Vllm, "Qwen/Qwen3-8B");
993        let a = args(&EngineConfig::vllm("vllm").command(&m, 9000, "k"));
994        assert_eq!(&a[..2], ["serve", "Qwen/Qwen3-8B"]);
995        assert!(a.windows(2).any(|w| w == ["--served-model-name", "big"]));
996    }
997
998    #[test]
999    fn mlx_args() {
1000        let mut m = ModelLaunch::new("qwen3-8b", EngineKind::Mlx, "/m/mlx/Qwen3-8B-4bit");
1001        m.context = Some(4096);
1002        let cmd = EngineConfig::mlx("/v/bin/mlx_lm.server").command(&m, 9, "k");
1003        assert_eq!(args(&cmd), ["--model", "/m/mlx/Qwen3-8B-4bit", "--host", "127.0.0.1", "--port", "9", "--max-tokens", "4096"]);
1004        assert!(cmd.as_std().get_envs().all(|(_, v)| v != Some(std::ffi::OsStr::new("k"))), "MLX-LM gets no key");
1005        m.context = None;
1006        let a = args(&EngineConfig::mlx("mlx_lm.server").command(&m, 9, "k"));
1007        assert_eq!(a.last().map(String::as_str), Some("32768"));
1008        assert_eq!(serde_json::to_string(&EngineKind::Mlx).unwrap(), "\"mlx\"");
1009    }
1010
1011    #[test]
1012    fn capabilities_as_modalities() {
1013        let media = Capabilities::text().with_vision(true).with_audio(true);
1014        assert_eq!(media.inputs(), Modalities::new(true, true));
1015        assert_eq!(Capabilities::text().lacking(Modalities::VISION), Some("images"));
1016        assert_eq!(Capabilities::text().with_vision(true).lacking(Modalities::new(true, true)), Some("audio"));
1017        assert_eq!(media.lacking(Modalities::AUDIO), None);
1018        assert_eq!(
1019            ModelLaunch::new("x", EngineKind::Mlx, "/m/x").capabilities().lacking(Modalities::VISION),
1020            Some("images"),
1021            "MLX never takes images"
1022        );
1023    }
1024
1025    #[test]
1026    fn capabilities() {
1027        let mut m = ModelLaunch::new("x", EngineKind::Mlx, "/m/x");
1028        assert_eq!(m.capabilities(), Capabilities::text());
1029        m.extra_args = vec!["--mmproj".into(), "/p".into()];
1030        assert!(!m.capabilities().vision, "MLX-LM never takes images");
1031        m.embedding = true;
1032        assert_eq!(m.capabilities(), Capabilities::default(), "MLX-LM serves no embeddings");
1033
1034        let mut l = ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf");
1035        assert_eq!(l.capabilities(), Capabilities::text());
1036        l.extra_args = vec!["--mmproj=/p/mm.gguf".into()];
1037        let c = l.capabilities();
1038        assert!(c.chat && c.vision && c.audio && !c.embeddings);
1039        l.embedding = true;
1040        assert_eq!(l.capabilities(), Capabilities::embeddings());
1041
1042        let v = ModelLaunch::new("v", EngineKind::Vllm, "Qwen/Qwen3-8B");
1043        assert_eq!(v.capabilities(), Capabilities::text());
1044        assert!(!EngineKind::Mlx.capabilities().embeddings && EngineKind::Llamacpp.capabilities().vision);
1045    }
1046
1047    fn limits() -> MediaLimits {
1048        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)
1049    }
1050
1051    #[test]
1052    fn limits_reach_capabilities_and_catalog_entries() {
1053        assert!(Capabilities::text().limits.is_unknown());
1054        let l = ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf").with_mmproj("/p/mm.gguf").with_limits(limits());
1055        let c = l.capabilities();
1056        assert_eq!(c.limits, limits(), "the operator's limits survive the engine's (which knows none)");
1057        assert!(c.vision && c.audio);
1058        let both = c.intersect(Capabilities::text().with_vision(true).with_limits(MediaLimits::new().with_max_images(2)));
1059        assert_eq!((both.limits.max_images, both.limits.image_tokens), (Some(2), Some(256)), "stricter wins, one-sided kept");
1060        use weirdnet_agent::remote::catalog::{ModelState as CatalogState, Purpose};
1061        let entry = c.apply_to(CatalogModel::new("g", Purpose::Chat, CatalogState::Warm).with_replicas(1));
1062        assert_eq!((entry.inputs, entry.limits, entry.replicas), (Modalities::new(true, true), limits(), 1));
1063        // Through the wire and back.
1064        let wire: CatalogModel = serde_json::from_str(&serde_json::to_string(&entry).unwrap()).unwrap();
1065        assert_eq!(wire.limits, limits());
1066    }
1067
1068    #[test]
1069    fn transcription_role_and_purpose() {
1070        use weirdnet_agent::remote::catalog::Purpose;
1071        let vox = ModelLaunch::new("vox", EngineKind::Llamacpp, "/m/v.gguf").with_mmproj("/m/mm.gguf").with_transcribe(true);
1072        assert!(vox.capabilities().transcribe && vox.capabilities().audio);
1073        assert_eq!(vox.purpose(), Purpose::Transcribe);
1074        let no_projector = ModelLaunch::new("v", EngineKind::Llamacpp, "/m/v.gguf").with_transcribe(true);
1075        assert!(!no_projector.capabilities().transcribe, "llama-server takes no audio without a projector");
1076        assert_eq!(no_projector.purpose(), Purpose::Chat);
1077        let mut via_args = no_projector.clone();
1078        via_args.extra_args = vec!["-mm".into(), "/m/mm.gguf".into()];
1079        assert!(via_args.capabilities().transcribe);
1080        let whisper = ModelLaunch::new("w", EngineKind::Vllm, "openai/whisper-large-v3").with_transcribe(true);
1081        assert!(whisper.capabilities().transcribe && !whisper.capabilities().audio);
1082        assert!(!ModelLaunch::new("m", EngineKind::Mlx, "/m").with_transcribe(true).capabilities().transcribe);
1083        let mut emb = vox.clone();
1084        emb.embedding = true;
1085        assert_eq!((emb.capabilities().transcribe, emb.purpose()), (false, Purpose::Embedding));
1086        assert_eq!(ModelLaunch::new("c", EngineKind::Llamacpp, "/m/c.gguf").purpose(), Purpose::Chat);
1087        let both = vox.capabilities().intersect(Capabilities::text().with_audio(true));
1088        assert!(!both.transcribe, "both sides must transcribe");
1089
1090        // On the wire: left out when false, so old records and old readers are unchanged.
1091        let json = serde_json::to_string(&Capabilities::text()).unwrap();
1092        assert!(!json.contains("transcribe"));
1093        let back: Capabilities = serde_json::from_str(&serde_json::to_string(&vox.capabilities()).unwrap()).unwrap();
1094        assert!(back.transcribe);
1095        let cbor = weirdnet_agent::remote::to_cbor(&vox.capabilities()).unwrap();
1096        assert!(weirdnet_agent::remote::from_cbor::<Capabilities>(&cbor).unwrap().transcribe);
1097        assert!(!serde_json::to_string(&no_projector.clone().with_transcribe(false)).unwrap().contains("transcribe"));
1098        let old: ModelLaunch = serde_json::from_str(&serde_json::to_string(&ModelLaunch::new("o", EngineKind::Llamacpp, "/o")).unwrap()).unwrap();
1099        assert!(!old.transcribe);
1100        let l: ModelLaunch = serde_json::from_value(serde_json::to_value(&whisper).unwrap()).unwrap();
1101        assert!(l.transcribe);
1102    }
1103
1104    #[test]
1105    fn vllm_omni_is_its_own_engine() {
1106        assert_eq!(serde_json::to_string(&EngineKind::VllmOmni).unwrap(), r#""vllm-omni""#);
1107        assert_eq!(serde_json::from_str::<EngineKind>(r#""vllm-omni""#).unwrap(), EngineKind::VllmOmni);
1108        for k in [EngineKind::Llamacpp, EngineKind::Vllm, EngineKind::Mlx, EngineKind::VllmOmni] {
1109            assert_eq!(EngineKind::parse(k.name()), Some(k));
1110            assert!(!k.install_hint().is_empty());
1111        }
1112        assert_eq!(
1113            (EngineKind::parse("omni"), EngineKind::parse("llama.cpp"), EngineKind::parse("x")),
1114            (Some(EngineKind::VllmOmni), Some(EngineKind::Llamacpp), None)
1115        );
1116        assert!(EngineKind::VllmOmni.supported("linux", "x86_64") && !EngineKind::VllmOmni.supported("macos", "aarch64"));
1117        assert!(EngineKind::Llamacpp.supported("windows", "x86_64") && !EngineKind::Mlx.supported("linux", "x86_64"));
1118        assert_eq!((EngineKind::VllmOmni.program(), EngineKind::Llamacpp.program()), ("vllm", "llama-server"));
1119        let caps = EngineKind::VllmOmni.capabilities();
1120        assert!(caps.speak && caps.chat && !caps.video && !caps.embeddings);
1121        assert!(EngineKind::Llamacpp.capabilities().speak && !EngineKind::Llamacpp.capabilities().video);
1122        assert!(EngineKind::Vllm.capabilities().video && !EngineKind::Vllm.capabilities().speak);
1123
1124        let mut m = ModelLaunch::new("qwen3-tts-1.7b-customvoice", EngineKind::VllmOmni, "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice").with_speak(true);
1125        m.slots = Some(4);
1126        let a = args(&EngineConfig::vllm_omni("/venv/bin/vllm").command(&m, 4321, "k"));
1127        assert_eq!(&a[..3], ["serve", "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice", "--omni"]);
1128        assert!(a.windows(2).any(|w| w == ["--served-model-name", "qwen3-tts-1.7b-customvoice"]));
1129        assert!(a.windows(2).any(|w| w == ["--max-num-seqs", "4"]));
1130        assert!(!a.iter().any(|x| x == "k" || x.starts_with("--allowed-local-media-path")), "no key in argv, no local media");
1131        assert_eq!(EngineConfig::vllm_omni("/v").ready_timeout, Duration::from_secs(1200));
1132    }
1133
1134    #[test]
1135    fn speakers_speak_and_nothing_else() {
1136        let kokoro = ModelLaunch::new("kokoro-82m", EngineKind::Llamacpp, "/m/kokoro.gguf").with_speak(true);
1137        assert_eq!(kokoro.capabilities(), Capabilities::default(), "no projector: llama.cpp can't speak");
1138        assert!(kokoro.check_speech().unwrap_err().contains("projector"));
1139        let kokoro = kokoro.with_mmproj("/m/mmproj-kokoro.gguf");
1140        assert_eq!(kokoro.capabilities(), Capabilities::default().with_speak(true));
1141        assert_eq!(kokoro.purpose(), Purpose::Speak);
1142        assert!(kokoro.check_speech().is_ok());
1143        let omni = ModelLaunch::new("q", EngineKind::VllmOmni, "Qwen/X").with_speak(true);
1144        assert_eq!((omni.capabilities().speak, omni.purpose()), (true, Purpose::Speak));
1145        for engine in [EngineKind::Vllm, EngineKind::Mlx] {
1146            let m = ModelLaunch::new("s", engine, "/m/s").with_speak(true);
1147            assert!(!m.capabilities().speak && m.check_speech().unwrap_err().contains("no speech engine"), "{engine:?}");
1148        }
1149        let mut both = omni.clone().with_transcribe(true);
1150        assert!(both.check_speech().is_err());
1151        both.transcribe = false;
1152        both.extra_args = vec!["--allowed-local-media-path=/".into()];
1153        assert!(both.check_speech().unwrap_err().contains("local media"));
1154        // Settings without the role, and settings that widen the catalog's.
1155        let p = SpeechProfile::new().with_max_input_chars(100);
1156        assert!(ModelLaunch::new("c", EngineKind::Llamacpp, "/m/c.gguf").with_speech(p.clone()).check_speech().is_err());
1157        assert!(kokoro.clone().with_speech(p.clone().with_presets(vec!["af_heart".into()])).check_speech().is_ok());
1158        let e = kokoro.clone().with_speech(SpeechProfile::new().with_presets(vec!["alloy".into()])).check_speech().unwrap_err();
1159        assert!(e.contains("widen") && e.contains("alloy"), "{e}");
1160        assert!(kokoro.clone().with_speech(SpeechProfile::new().with_design(true)).check_speech().is_err());
1161
1162        // The catalog entry by id, Hub repo or GGUF file name, for the right engine only.
1163        assert!(kokoro.cataloged_speech().unwrap().raw);
1164        let by_repo = ModelLaunch::new("tts", EngineKind::VllmOmni, "Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign");
1165        let entry = weirdnet_model::hw::find(weirdnet_model::hw::QWEN3_TTS_1_7B_VOICEDESIGN).unwrap();
1166        assert_eq!(by_repo.cataloged_speech().is_some(), entry.spec.repo.eq_ignore_ascii_case("Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign"));
1167        let by_repo = ModelLaunch::new("tts", EngineKind::VllmOmni, entry.spec.repo.clone());
1168        assert!(by_repo.cataloged_speech().unwrap().design);
1169        let gguf = weirdnet_model::hw::find(weirdnet_model::hw::VOXCPM2).unwrap();
1170        let by_file = ModelLaunch::new("vox", EngineKind::Llamacpp, format!("/models/{}", gguf.spec.file));
1171        assert!(by_file.cataloged_speech().unwrap().design);
1172        assert!(ModelLaunch::new("kokoro-82m", EngineKind::VllmOmni, "x/y").cataloged_speech().is_none(), "a GGUF entry is not vLLM-Omni's");
1173        assert!(ModelLaunch::new("kokoro-82m", EngineKind::Vllm, "x/y").cataloged_speech().is_none());
1174
1175        let json = serde_json::to_value(kokoro.clone().with_speech(p.clone())).unwrap();
1176        assert_eq!((json["speak"].as_bool(), json["speech"]["max_input_chars"].as_u64()), (Some(true), Some(100)));
1177        let back: ModelLaunch = serde_json::from_value(json).unwrap();
1178        assert_eq!(back.speech, p);
1179    }
1180
1181    #[test]
1182    fn video_is_vllms_on_the_operators_word() {
1183        let vl = ModelLaunch::new("vl", EngineKind::Vllm, "Qwen/Qwen2.5-VL-7B-Instruct");
1184        assert!(!vl.capabilities().video);
1185        let vl = vl.with_video(true);
1186        let caps = vl.capabilities();
1187        assert!(caps.video && caps.chat && caps.vision, "a video model takes images too");
1188        assert_eq!(caps.inputs(), Modalities::new(true, false).with_video(true));
1189        assert_eq!(caps.lacking(Modalities::VIDEO), None);
1190        assert_eq!(Capabilities::text().lacking(Modalities::VIDEO), Some("video"));
1191        assert!(!ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf").with_mmproj("/m/p.gguf").with_video(true).capabilities().video);
1192        assert!(!ModelLaunch::new("m", EngineKind::Mlx, "/m/m").with_video(true).capabilities().video);
1193        assert!(!caps.intersect(Capabilities::text()).video);
1194        let limits = MediaLimits::new().with_video_max_seconds(120).with_video_frames_per_minute(120);
1195        let entry = caps.with_limits(limits).apply_to(CatalogModel::new("vl", Purpose::Chat, weirdnet_agent::remote::catalog::ModelState::Warm));
1196        assert!(entry.inputs.video);
1197        assert_eq!((entry.limits.video_max_seconds, entry.limits.video_frame_rate()), (Some(120), Some(2.0)));
1198        let json = serde_json::to_string(&caps).unwrap();
1199        assert!(json.contains(r#""video":true"#) && !json.contains("speak"));
1200        assert_eq!(serde_json::from_str::<Capabilities>(&json).unwrap(), caps);
1201        let cbor = weirdnet_agent::remote::to_cbor(&caps).unwrap();
1202        assert_eq!(weirdnet_agent::remote::from_cbor::<Capabilities>(&cbor).unwrap(), caps);
1203    }
1204
1205    #[test]
1206    fn records_without_limits_read_as_before() {
1207        let old = r#"{"chat":true,"embeddings":false,"vision":true,"audio":false}"#;
1208        let c: Capabilities = serde_json::from_str(old).unwrap();
1209        assert_eq!(c, Capabilities::text().with_vision(true));
1210        assert!(c.limits.is_unknown());
1211        assert_eq!(serde_json::to_string(&c).unwrap(), old, "no limits: the record looks as before");
1212        let with: Capabilities = serde_json::from_str(&serde_json::to_string(&c.with_limits(limits())).unwrap()).unwrap();
1213        assert_eq!(with.limits, limits());
1214        let cbor = weirdnet_agent::remote::to_cbor(&c.with_limits(limits())).unwrap();
1215        assert_eq!(weirdnet_agent::remote::from_cbor::<Capabilities>(&cbor).unwrap(), c.with_limits(limits()));
1216        assert_eq!(weirdnet_agent::remote::from_cbor::<Capabilities>(&weirdnet_agent::remote::to_cbor(&c).unwrap()).unwrap(), c);
1217        let launch = ModelLaunch::new("g", EngineKind::Llamacpp, "/m/g.gguf");
1218        let json = serde_json::to_string(&launch).unwrap();
1219        assert!(!json.contains("limits"));
1220        let back: ModelLaunch = serde_json::from_str(&json).unwrap();
1221        assert_eq!(back, launch);
1222        let with = launch.with_limits(limits());
1223        assert_eq!(serde_json::from_str::<ModelLaunch>(&serde_json::to_string(&with).unwrap()).unwrap(), with);
1224    }
1225}