Skip to main content

weirdnet_backends/
engine.rs

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