Skip to main content

car_inference/
registry.rs

1//! Unified model registry — local and remote models under one schema.
2//!
3//! Replaces the hardcoded `ModelRegistry` from `models.rs` with a schema-driven
4//! registry that treats all models as first-class typed resources. Users can
5//! register custom models (fine-tuned endpoints, private APIs) alongside the
6//! built-in catalog.
7
8use crate::schema::reasoning_params;
9use std::collections::HashMap;
10use std::path::{Path, PathBuf};
11use std::time::SystemTime;
12
13use serde::{Deserialize, Serialize};
14use tracing::info;
15
16use crate::schema::*;
17use crate::InferenceError;
18
19/// Filter for querying the registry.
20#[derive(Debug, Clone, Default)]
21pub struct ModelFilter {
22    /// Required capabilities (model must have ALL of these).
23    pub capabilities: Vec<ModelCapability>,
24    /// Maximum on-disk / RAM size in MB.
25    pub max_size_mb: Option<u64>,
26    /// Maximum expected latency in ms (from declared envelope).
27    pub max_latency_ms: Option<u64>,
28    /// Maximum cost per 1M output tokens in USD.
29    pub max_cost_per_mtok: Option<f64>,
30    /// Required tags (model must have ALL of these).
31    pub tags: Vec<String>,
32    /// Filter by provider.
33    pub provider: Option<String>,
34    /// Only local models.
35    pub local_only: bool,
36    /// Only models that are currently available.
37    pub available_only: bool,
38}
39
40/// A curated replacement for a local model that is installed but no longer
41/// the preferred model in its line.
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct ModelUpgrade {
44    pub from_id: String,
45    pub from_name: String,
46    pub to_id: String,
47    pub to_name: String,
48    pub reason: String,
49    pub target_runtime: Option<String>,
50    pub target_runtime_requirement: Option<String>,
51    pub minimum_runtimes: Vec<ModelRuntimeRequirement>,
52    pub target_available: bool,
53    pub target_pullable: bool,
54    pub remove_old_supported: bool,
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct ModelRuntimeRequirement {
59    pub name: String,
60    pub minimum_version: String,
61}
62
63/// Unified registry of all known models.
64pub struct UnifiedRegistry {
65    models_dir: PathBuf,
66    /// All registered models, keyed by id.
67    models: HashMap<String, ModelSchema>,
68    /// User-added model config file path (~/.car/models.json).
69    user_config_path: PathBuf,
70}
71
72#[derive(Debug, Clone, Deserialize)]
73struct ModelUpgradeRule {
74    from_ids: Vec<String>,
75    to_id: String,
76    reason: String,
77    target_runtime: Option<String>,
78    target_runtime_requirement: Option<String>,
79    #[serde(default)]
80    minimum_runtimes: Vec<ModelRuntimeRequirement>,
81    #[serde(default = "default_remove_old_after_available")]
82    remove_old_after_available: bool,
83}
84
85fn default_remove_old_after_available() -> bool {
86    true
87}
88
89fn model_upgrade_rules() -> Vec<ModelUpgradeRule> {
90    serde_json::from_str(include_str!("../assets/model-upgrades.json"))
91        .expect("built-in model-upgrades.json should parse")
92}
93
94impl UnifiedRegistry {
95    pub fn new(models_dir: PathBuf) -> Self {
96        let user_config_path = models_dir
97            .parent()
98            .unwrap_or(&models_dir)
99            .join("models.json");
100
101        let mut registry = Self {
102            models_dir,
103            models: HashMap::new(),
104            user_config_path,
105        };
106        registry.load_builtin_catalog();
107        registry.refresh_availability();
108        // Load user config on top (silently ignore if missing)
109        let _ = registry.load_user_config();
110        registry
111    }
112
113    /// Register a model at runtime.
114    pub fn register(&mut self, mut schema: ModelSchema) {
115        // Check availability for local models
116        if schema.is_mlx() {
117            schema.available = if schema.tags.contains(&"speech".to_string()) {
118                speech_mlx_available()
119            } else if let ModelSource::Mlx { ref hf_repo, .. } = schema.source {
120                let mlx_dir = self.models_dir.join(&schema.name);
121                mlx_dir.join("config.json").exists()
122                    || latest_huggingface_repo_snapshot(hf_repo).is_some()
123            } else {
124                let mlx_dir = self.models_dir.join(&schema.name);
125                mlx_dir.join("config.json").exists()
126            };
127        } else if schema.is_vllm_mlx() {
128            // vLLM-MLX: available if endpoint env var set or was manually marked available
129            schema.available = std::env::var("VLLM_MLX_ENDPOINT").is_ok() || schema.available;
130        } else if schema.is_local() {
131            let local_path = self.models_dir.join(&schema.name).join("model.gguf");
132            schema.available = local_path.exists();
133        } else if schema.is_remote() {
134            // Remote models are assumed available if the env var exists
135            if let ModelSource::RemoteApi {
136                ref api_key_env, ..
137            } = schema.source
138            {
139                schema.available = std::env::var(api_key_env).is_ok();
140            }
141        }
142        info!(id = %schema.id, name = %schema.name, available = schema.available, "registered model");
143        self.models.insert(schema.id.clone(), schema);
144    }
145
146    /// Unregister a model by id. Returns the removed schema if found.
147    pub fn unregister(&mut self, id: &str) -> Option<ModelSchema> {
148        let removed = self.models.remove(id);
149        if let Some(ref m) = removed {
150            info!(id = %m.id, "unregistered model");
151        }
152        removed
153    }
154
155    /// List all models.
156    pub fn list(&self) -> Vec<&ModelSchema> {
157        let mut models: Vec<&ModelSchema> = self.models.values().collect();
158        models.sort_by(|a, b| a.id.cmp(&b.id));
159        models
160    }
161
162    /// Query models matching a filter.
163    pub fn query(&self, filter: &ModelFilter) -> Vec<&ModelSchema> {
164        self.models
165            .values()
166            .filter(|m| {
167                // Capability check: model must have ALL required capabilities
168                if !filter.capabilities.iter().all(|c| m.has_capability(*c)) {
169                    return false;
170                }
171                // Size check
172                if let Some(max) = filter.max_size_mb {
173                    if m.size_mb() > max && m.is_local() {
174                        return false;
175                    }
176                }
177                // Latency check (declared envelope)
178                if let Some(max) = filter.max_latency_ms {
179                    if let Some(p50) = m.performance.latency_p50_ms {
180                        if p50 > max {
181                            return false;
182                        }
183                    }
184                }
185                // Cost check
186                if let Some(max) = filter.max_cost_per_mtok {
187                    if let Some(cost) = m.cost.output_per_mtok {
188                        if cost > max {
189                            return false;
190                        }
191                    }
192                }
193                // Tag check
194                if !filter.tags.iter().all(|t| m.tags.contains(t)) {
195                    return false;
196                }
197                // Provider check
198                if let Some(ref p) = filter.provider {
199                    if &m.provider != p {
200                        return false;
201                    }
202                }
203                // Local only
204                if filter.local_only && !m.is_local() {
205                    return false;
206                }
207                // Available only
208                if filter.available_only && !m.available {
209                    return false;
210                }
211                true
212            })
213            .collect()
214    }
215
216    /// Query models by a single capability.
217    pub fn query_by_capability(&self, cap: ModelCapability) -> Vec<&ModelSchema> {
218        self.query(&ModelFilter {
219            capabilities: vec![cap],
220            ..Default::default()
221        })
222    }
223
224    /// Report installed local models with curated newer replacements.
225    pub fn available_upgrades(&self) -> Vec<ModelUpgrade> {
226        let mut upgrades = Vec::new();
227        for rule in model_upgrade_rules() {
228            let Some(from) = rule
229                .from_ids
230                .iter()
231                .find_map(|id| self.models.get(id.as_str()))
232                .filter(|schema| schema.available)
233            else {
234                continue;
235            };
236            let Some(to) = self.models.get(rule.to_id.as_str()) else {
237                continue;
238            };
239            upgrades.push(ModelUpgrade {
240                from_id: from.id.clone(),
241                from_name: from.name.clone(),
242                to_id: to.id.clone(),
243                to_name: to.name.clone(),
244                reason: rule.reason.clone(),
245                target_runtime: rule.target_runtime.clone(),
246                target_runtime_requirement: rule.target_runtime_requirement.clone(),
247                minimum_runtimes: rule.minimum_runtimes.clone(),
248                target_available: to.available,
249                target_pullable: matches!(
250                    to.source,
251                    ModelSource::Local { .. } | ModelSource::Mlx { .. }
252                ),
253                remove_old_supported: matches!(
254                    from.source,
255                    ModelSource::Local { .. } | ModelSource::Mlx { .. }
256                ) && rule.remove_old_after_available,
257            });
258        }
259        upgrades.sort_by(|a, b| a.from_id.cmp(&b.from_id).then(a.to_id.cmp(&b.to_id)));
260        upgrades.dedup_by(|a, b| a.from_id == b.from_id && a.to_id == b.to_id);
261        upgrades
262    }
263
264    /// Get a specific model by id.
265    pub fn get(&self, id: &str) -> Option<&ModelSchema> {
266        self.models.get(id)
267    }
268
269    /// Find a model by name (case-insensitive). For backward compatibility
270    /// with the old registry that used short names like "Qwen3-4B".
271    pub fn find_by_name(&self, name: &str) -> Option<&ModelSchema> {
272        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
273        if !name.to_ascii_lowercase().ends_with("-mlx") {
274            if let Some(mlx_variant) = self
275                .models
276                .values()
277                .find(|m| m.name.eq_ignore_ascii_case(&format!("{name}-MLX")))
278            {
279                return Some(mlx_variant);
280            }
281        }
282
283        self.models
284            .values()
285            .find(|m| m.name.eq_ignore_ascii_case(name))
286    }
287
288    /// On Apple Silicon, resolve a GGUF/Candle model to its MLX equivalent.
289    /// Returns the MLX model schema if one exists with the same family and
290    /// matching capabilities; otherwise returns None.
291    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
292    pub fn resolve_mlx_equivalent(&self, schema: &ModelSchema) -> Option<&ModelSchema> {
293        // Already MLX — no redirect needed.
294        if schema.is_mlx() || schema.is_vllm_mlx() {
295            return None;
296        }
297        // Only redirect local GGUF models.
298        if !matches!(schema.source, ModelSource::Local { .. }) {
299            return None;
300        }
301        // Find an MLX model in the same family with at least the same primary capability.
302        let primary_cap = schema.capabilities.first()?;
303        self.models.values().find(|m| {
304            m.is_mlx()
305                && m.family == schema.family
306                && m.capabilities.contains(primary_cap)
307        })
308    }
309
310    /// Ensure a local model is downloaded, returning its local directory path.
311    pub async fn ensure_local(&self, id: &str) -> Result<PathBuf, InferenceError> {
312        let schema = self
313            .get(id)
314            .or_else(|| self.find_by_name(id))
315            .ok_or_else(|| InferenceError::ModelNotFound(id.to_string()))?;
316
317        match &schema.source {
318            ModelSource::Local {
319                hf_repo,
320                hf_filename,
321                tokenizer_repo,
322            } => {
323                let model_dir = self.models_dir.join(&schema.name);
324                let model_path = model_dir.join("model.gguf");
325                let tokenizer_path = model_dir.join("tokenizer.json");
326
327                if model_path.exists() && tokenizer_path.exists() {
328                    return Ok(model_dir);
329                }
330
331                std::fs::create_dir_all(&model_dir)?;
332
333                if !model_path.exists() {
334                    info!(model = %schema.name, repo = %hf_repo, "downloading model weights");
335                    download_file(hf_repo, hf_filename, &model_path).await?;
336                }
337                if !tokenizer_path.exists() {
338                    info!(model = %schema.name, repo = %tokenizer_repo, "downloading tokenizer");
339                    download_file(tokenizer_repo, "tokenizer.json", &tokenizer_path).await?;
340                }
341
342                Ok(model_dir)
343            }
344            ModelSource::Mlx {
345                hf_repo,
346                hf_weight_file,
347            } => {
348                let model_dir = self.models_dir.join(&schema.name);
349                let config_path = model_dir.join("config.json");
350
351                if config_path.exists() {
352                    ensure_auxiliary_mlx_files(&schema.name, hf_repo, &model_dir).await?;
353                    info!(model = %schema.name, path = %model_dir.display(), "using managed local MLX model");
354                    return Ok(model_dir);
355                }
356
357                if let Some(snapshot_dir) = latest_huggingface_repo_snapshot(hf_repo) {
358                    ensure_auxiliary_mlx_files(&schema.name, hf_repo, &snapshot_dir).await?;
359                    info!(model = %schema.name, path = %snapshot_dir.display(), "using cached MLX snapshot");
360                    return Ok(snapshot_dir);
361                }
362
363                std::fs::create_dir_all(&model_dir)?;
364
365                info!(model = %schema.name, repo = %hf_repo, "downloading MLX model");
366
367                // Download config, tokenizer, and weight files
368                download_file(hf_repo, "config.json", &config_path).await?;
369                let tok_path = model_dir.join("tokenizer.json");
370                if !tok_path.exists() {
371                    download_file(hf_repo, "tokenizer.json", &tok_path).await?;
372                }
373                let tok_config_path = model_dir.join("tokenizer_config.json");
374                if !tok_config_path.exists() {
375                    let _ = download_file(hf_repo, "tokenizer_config.json", &tok_config_path).await;
376                }
377
378                // Download weight files
379                if let Some(ref wf) = hf_weight_file {
380                    let wf_path = model_dir.join(wf);
381                    if !wf_path.exists() {
382                        download_file(hf_repo, wf, &wf_path).await?;
383                    }
384                } else {
385                    // Try single file first, then sharded
386                    let single = model_dir.join("model.safetensors");
387                    if !single.exists() {
388                        match download_file(hf_repo, "model.safetensors", &single).await {
389                            Ok(()) => {}
390                            Err(_) => {
391                                // Sharded: download index and then each shard
392                                let index_path = model_dir.join("model.safetensors.index.json");
393                                download_file(hf_repo, "model.safetensors.index.json", &index_path)
394                                    .await?;
395
396                                let index_json: serde_json::Value =
397                                    serde_json::from_str(&std::fs::read_to_string(&index_path)?)
398                                        .map_err(|e| {
399                                            InferenceError::InferenceFailed(format!(
400                                                "parse index: {e}"
401                                            ))
402                                        })?;
403
404                                if let Some(weight_map) =
405                                    index_json.get("weight_map").and_then(|m| m.as_object())
406                                {
407                                    let mut files: std::collections::HashSet<String> =
408                                        std::collections::HashSet::new();
409                                    for filename in weight_map.values() {
410                                        if let Some(f) = filename.as_str() {
411                                            files.insert(f.to_string());
412                                        }
413                                    }
414                                    for file in &files {
415                                        let dest = model_dir.join(file);
416                                        if !dest.exists() {
417                                            info!(file = %file, "downloading weight shard");
418                                            download_file(hf_repo, file, &dest).await?;
419                                        }
420                                    }
421                                }
422                            }
423                        }
424                    }
425                }
426
427                ensure_auxiliary_mlx_files(&schema.name, hf_repo, &model_dir).await?;
428                Ok(model_dir)
429            }
430            _ => Err(InferenceError::InferenceFailed(format!(
431                "model {} is not local",
432                id
433            ))),
434        }
435    }
436
437    /// Remove a downloaded local model.
438    pub fn remove_local(&mut self, id: &str) -> Result<(), InferenceError> {
439        let schema = self
440            .get(id)
441            .or_else(|| self.find_by_name(id))
442            .ok_or_else(|| InferenceError::ModelNotFound(id.to_string()))?;
443
444        let model_dir = self.models_dir.join(&schema.name);
445        if model_dir.exists() {
446            std::fs::remove_dir_all(&model_dir)?;
447            info!(model = %schema.name, "removed model");
448        }
449
450        match &schema.source {
451            ModelSource::Mlx { hf_repo, .. } => {
452                let repo_dir = huggingface_repo_dir(hf_repo);
453                if repo_dir.exists() {
454                    std::fs::remove_dir_all(&repo_dir)?;
455                    info!(model = %schema.name, repo = %hf_repo, "removed Hugging Face cache");
456                }
457            }
458            ModelSource::Local {
459                hf_repo,
460                tokenizer_repo,
461                ..
462            } => {
463                for repo in [hf_repo, tokenizer_repo] {
464                    let repo_dir = huggingface_repo_dir(repo);
465                    if repo_dir.exists() {
466                        std::fs::remove_dir_all(&repo_dir)?;
467                        info!(model = %schema.name, repo = %repo, "removed Hugging Face cache");
468                    }
469                }
470            }
471            _ => {}
472        }
473
474        // Update availability
475        let id = schema.id.clone();
476        if let Some(m) = self.models.get_mut(&id) {
477            m.available = false;
478        }
479        Ok(())
480    }
481
482    /// Refresh availability flags for all models.
483    ///
484    /// Runtime-true vs catalog-says: this is what closes the gap
485    /// `models.list_unified` callers rely on. If a model is listed
486    /// as `available: true` here, an `infer` call against it should
487    /// reach the backend, not bail with `UnsupportedMode { ...
488    /// "mlx-vlm CLI not found on PATH" }` (the #137 trap).
489    pub fn refresh_availability(&mut self) {
490        let models_dir = self.models_dir.clone();
491        // mlx-vlm CLI is the same probe call no matter which model
492        // requires it; do it once per refresh, not per-model.
493        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
494        let mlx_vlm_cli_present = crate::backend::mlx_vlm_cli::is_available();
495        #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
496        let mlx_vlm_cli_present = false;
497
498        for m in self.models.values_mut() {
499            match &m.source {
500                ModelSource::Mlx { .. } => {
501                    // Models tagged `requires-mlx-vlm` shell out to the
502                    // mlx_vlm Python CLI for image inference (#115).
503                    // If the CLI isn't on PATH, the runtime reaches it
504                    // anyway and bails — the registry MUST reflect that
505                    // by marking such entries unavailable until the
506                    // user installs `uv tool install mlx-vlm`. #137.
507                    let needs_mlx_vlm =
508                        m.tags.iter().any(|t| t == "requires-mlx-vlm");
509
510                    m.available = if needs_mlx_vlm {
511                        mlx_vlm_cli_present
512                    } else if m.tags.contains(&"speech".to_string()) {
513                        speech_mlx_available()
514                    } else {
515                        let mlx_dir = models_dir.join(&m.name);
516                        mlx_dir.join("config.json").exists()
517                    };
518                }
519                ModelSource::Local { .. } => {
520                    let local_path = models_dir.join(&m.name).join("model.gguf");
521                    m.available = local_path.exists();
522                }
523                ModelSource::RemoteApi { api_key_env, .. } => {
524                    m.available = std::env::var(api_key_env).is_ok();
525                }
526                ModelSource::Ollama { .. } => {
527                    // Assume available; health check is async and done lazily
528                    m.available = true;
529                }
530                ModelSource::VllmMlx { .. } => {
531                    // vLLM-MLX availability checked via health endpoint lazily
532                    // Mark as available if VLLM_MLX_ENDPOINT env var is set or default endpoint assumed
533                    m.available = std::env::var("VLLM_MLX_ENDPOINT").is_ok() || m.available;
534                    // preserve manual registration
535                }
536                ModelSource::Proprietary { auth, .. } => {
537                    // Check auth availability
538                    m.available = match auth {
539                        crate::schema::ProprietaryAuth::ApiKeyEnv { env_var } => {
540                            std::env::var(env_var).is_ok()
541                        }
542                        crate::schema::ProprietaryAuth::BearerTokenEnv { env_var } => {
543                            std::env::var(env_var).is_ok()
544                        }
545                        crate::schema::ProprietaryAuth::OAuth2Pkce { .. } => {
546                            // OAuth2 availability determined at runtime by token provider
547                            true
548                        }
549                    };
550                }
551                ModelSource::AppleFoundationModels { .. } => {
552                    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
553                    {
554                        m.available = crate::backend::foundation_models::is_available();
555                    }
556                    #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
557                    {
558                        m.available = false;
559                    }
560                }
561            }
562        }
563    }
564
565    /// Persist user-registered (non-builtin) models to disk.
566    pub fn save_user_config(&self) -> Result<(), InferenceError> {
567        let user_models: Vec<&ModelSchema> = self
568            .models
569            .values()
570            .filter(|m| !m.tags.contains(&"builtin".to_string()))
571            .collect();
572
573        if user_models.is_empty() {
574            return Ok(());
575        }
576
577        let json = serde_json::to_string_pretty(&user_models)
578            .map_err(|e| InferenceError::InferenceFailed(format!("serialize: {e}")))?;
579        std::fs::write(&self.user_config_path, json)?;
580        Ok(())
581    }
582
583    /// Load user-registered models from disk.
584    pub fn load_user_config(&mut self) -> Result<(), InferenceError> {
585        if !self.user_config_path.exists() {
586            return Ok(());
587        }
588
589        let json = std::fs::read_to_string(&self.user_config_path)?;
590        let models: Vec<ModelSchema> = serde_json::from_str(&json)
591            .map_err(|e| InferenceError::InferenceFailed(format!("parse models.json: {e}")))?;
592
593        for m in models {
594            self.register(m);
595        }
596        Ok(())
597    }
598
599    /// Get the models directory path.
600    pub fn models_dir(&self) -> &Path {
601        &self.models_dir
602    }
603
604    /// Load the built-in Qwen3 catalog as ModelSchema objects.
605    fn load_builtin_catalog(&mut self) {
606        for schema in builtin_catalog() {
607            self.models.insert(schema.id.clone(), schema);
608        }
609    }
610}
611
612fn speech_mlx_available() -> bool {
613    // On Apple Silicon, speech uses native MLX backends — no Python CLI needed.
614    // Models are available if we're on the right platform (weights are downloaded on demand).
615    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
616    { true }
617
618    // On other platforms, check for the Python mlx-audio CLI.
619    #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
620    {
621        let runtime_root = speech_runtime_root();
622        runtime_root.join("bin").join("mlx_audio.stt.generate").exists()
623            || runtime_root.join("bin").join("mlx_audio.tts.generate").exists()
624    }
625}
626
627fn speech_runtime_root() -> PathBuf {
628    if let Ok(path) = std::env::var("CAR_SPEECH_RUNTIME_DIR") {
629        if !path.trim().is_empty() {
630            return PathBuf::from(path);
631        }
632    }
633    std::env::var("HOME")
634        .map(PathBuf::from)
635        .unwrap_or_else(|_| PathBuf::from("."))
636        .join(".car")
637        .join("speech-runtime")
638}
639
640/// Backward-compatible ModelInfo for listing (used by CLI and old callers).
641#[derive(Debug, Clone, Serialize, Deserialize)]
642pub struct ModelInfo {
643    pub id: String,
644    pub name: String,
645    pub provider: String,
646    pub capabilities: Vec<ModelCapability>,
647    pub param_count: String,
648    pub size_mb: u64,
649    pub context_length: usize,
650    pub available: bool,
651    pub is_local: bool,
652    /// Public benchmark scores carried straight through from `ModelSchema`.
653    /// The built-in catalog ships this empty; populating it is a curation
654    /// step (see `BenchmarkScore` in the schema for shape and conventions).
655    #[serde(default)]
656    pub public_benchmarks: Vec<crate::schema::BenchmarkScore>,
657}
658
659impl From<&ModelSchema> for ModelInfo {
660    fn from(s: &ModelSchema) -> Self {
661        ModelInfo {
662            id: s.id.clone(),
663            name: s.name.clone(),
664            provider: s.provider.clone(),
665            capabilities: s.capabilities.clone(),
666            param_count: s.param_count.clone(),
667            size_mb: s.size_mb(),
668            context_length: s.context_length,
669            available: s.available,
670            is_local: s.is_local(),
671            public_benchmarks: s.public_benchmarks.clone(),
672        }
673    }
674}
675
676/// Download a single file from a HuggingFace repo.
677async fn download_file(repo: &str, filename: &str, dest: &Path) -> Result<(), InferenceError> {
678    let api = hf_hub::api::tokio::Api::new()
679        .map_err(|e| InferenceError::DownloadFailed(e.to_string()))?;
680
681    let repo = api.model(repo.to_string());
682    let path = repo
683        .get(filename)
684        .await
685        .map_err(|e| InferenceError::DownloadFailed(format!("{filename}: {e}")))?;
686
687    if dest.exists() {
688        return Ok(());
689    }
690
691    // Try symlink first, fall back to copy
692    #[cfg(unix)]
693    {
694        if std::os::unix::fs::symlink(&path, dest).is_ok() {
695            return Ok(());
696        }
697    }
698
699    std::fs::copy(&path, dest)
700        .map_err(|e| InferenceError::DownloadFailed(format!("copy to {}: {e}", dest.display())))?;
701    Ok(())
702}
703
704async fn ensure_auxiliary_mlx_files(
705    model_name: &str,
706    hf_repo: &str,
707    model_dir: &Path,
708) -> Result<(), InferenceError> {
709    if hf_repo == "mlx-community/Flux-1.lite-8B-MLX-Q4" || model_name == "Flux-1.lite-8B-MLX-Q4" {
710        let t5_tokenizer_path = model_dir.join("tokenizer_2").join("tokenizer.json");
711        if !t5_tokenizer_path.exists() {
712            std::fs::create_dir_all(
713                t5_tokenizer_path
714                    .parent()
715                    .ok_or_else(|| InferenceError::InferenceFailed("invalid tokenizer path".into()))?,
716            )?;
717            info!(
718                path = %t5_tokenizer_path.display(),
719                "downloading missing Flux tokenizer_2/tokenizer.json from base model"
720            );
721            download_file("Freepik/flux.1-lite-8B", "tokenizer_2/tokenizer.json", &t5_tokenizer_path)
722                .await?;
723        }
724    }
725    Ok(())
726}
727
728fn huggingface_repo_has_snapshot(repo_id: &str) -> bool {
729    latest_huggingface_repo_snapshot(repo_id).is_some()
730}
731
732fn huggingface_cache_root() -> PathBuf {
733    std::env::var("HF_HOME")
734        .map(PathBuf::from)
735        .unwrap_or_else(|_| {
736            std::env::var("HOME")
737                .map(PathBuf::from)
738                .unwrap_or_else(|_| PathBuf::from("."))
739                .join(".cache")
740                .join("huggingface")
741        })
742        .join("hub")
743}
744
745fn huggingface_repo_dir(repo_id: &str) -> PathBuf {
746    huggingface_cache_root().join(format!("models--{}", repo_id.replace('/', "--")))
747}
748
749fn resolve_huggingface_ref_snapshot(repo_dir: &Path, name: &str) -> Option<PathBuf> {
750    let sha = std::fs::read_to_string(repo_dir.join("refs").join(name))
751        .ok()?
752        .trim()
753        .to_string();
754    if sha.is_empty() {
755        return None;
756    }
757
758    let snapshot = repo_dir.join("snapshots").join(sha);
759    if snapshot_looks_ready(&snapshot) {
760        Some(snapshot)
761    } else {
762        None
763    }
764}
765
766fn latest_huggingface_repo_snapshot(repo_id: &str) -> Option<PathBuf> {
767    let repo_dir = huggingface_repo_dir(repo_id);
768    if let Some(snapshot) = resolve_huggingface_ref_snapshot(&repo_dir, "main") {
769        return Some(snapshot);
770    }
771
772    let snapshots = repo_dir.join("snapshots");
773    let mut candidates: Vec<(SystemTime, PathBuf)> = std::fs::read_dir(snapshots)
774        .ok()?
775        .filter_map(Result::ok)
776        .map(|e| e.path())
777        .filter(|p| p.is_dir() && snapshot_looks_ready(p))
778        .map(|path| {
779            let modified = path
780                .metadata()
781                .and_then(|metadata| metadata.modified())
782                .unwrap_or(SystemTime::UNIX_EPOCH);
783            (modified, path)
784        })
785        .collect();
786    candidates.sort();
787    candidates.pop().map(|(_, path)| path)
788}
789
790fn snapshot_looks_ready(path: &Path) -> bool {
791    if path.join("config.json").exists() || path.join("model_index.json").exists() {
792        return true;
793    }
794    snapshot_contains_ext(path, "safetensors")
795}
796
797fn snapshot_contains_ext(root: &Path, ext: &str) -> bool {
798    let Ok(entries) = std::fs::read_dir(root) else {
799        return false;
800    };
801    entries.filter_map(Result::ok).any(|entry| {
802        let path = entry.path();
803        if path.is_dir() {
804            snapshot_contains_ext(&path, ext)
805        } else {
806            path.extension()
807                .and_then(|value| value.to_str())
808                .map(|value| value.eq_ignore_ascii_case(ext))
809                .unwrap_or(false)
810        }
811    })
812}
813
814async fn download_hf_repo_snapshot(repo_id: &str) -> Result<(PathBuf, usize), InferenceError> {
815    let api = hf_hub::api::tokio::ApiBuilder::from_env()
816        .with_progress(false)
817        .build()
818        .map_err(|e| InferenceError::DownloadFailed(format!("init hf api: {e}")))?;
819    let repo = api.model(repo_id.to_string());
820    let info = repo
821        .info()
822        .await
823        .map_err(|e| InferenceError::DownloadFailed(format!("{repo_id}: {e}")))?;
824
825    let snapshot_path = std::env::var("HF_HOME")
826        .map(PathBuf::from)
827        .unwrap_or_else(|_| {
828            std::env::var("HOME")
829                .map(PathBuf::from)
830                .unwrap_or_else(|_| PathBuf::from("."))
831                .join(".cache")
832                .join("huggingface")
833        })
834        .join("hub")
835        .join(format!("models--{}", repo_id.replace('/', "--")))
836        .join("snapshots")
837        .join(&info.sha);
838    let mut downloaded = 0usize;
839    for sibling in &info.siblings {
840        let local_path = snapshot_path.join(&sibling.rfilename);
841        if local_path.exists() {
842            downloaded += 1;
843            continue;
844        }
845        repo.download(&sibling.rfilename).await.map_err(|e| {
846            InferenceError::DownloadFailed(format!("{repo_id}/{}: {e}", sibling.rfilename))
847        })?;
848        downloaded += 1;
849    }
850
851    Ok((snapshot_path, downloaded))
852}
853
854/// Built-in catalog parsed from `builtin_catalog.json`.
855///
856/// Adding, removing, or editing a model is a JSON-only change — Rust
857/// source stays put. The JSON is embedded at compile time via
858/// `include_str!`, parsed once into a `LazyLock`, and cloned on each
859/// call. A malformed JSON file fails the integration test
860/// `builtin_catalog_json_parses` so the binary never ships unable
861/// to load its own catalog.
862const BUILTIN_CATALOG_JSON: &str = include_str!("builtin_catalog.json");
863
864static BUILTIN_CATALOG: std::sync::LazyLock<Vec<ModelSchema>> =
865    std::sync::LazyLock::new(|| {
866        serde_json::from_str(BUILTIN_CATALOG_JSON)
867            .expect("builtin_catalog.json failed to parse — fix the JSON, not this code")
868    });
869
870fn builtin_catalog() -> Vec<ModelSchema> {
871    BUILTIN_CATALOG.clone()
872}
873
874#[cfg(test)]
875mod tests {
876    use super::*;
877    use tempfile::TempDir;
878
879    fn test_registry() -> (UnifiedRegistry, TempDir) {
880        let tmp = TempDir::new().unwrap();
881        let reg = UnifiedRegistry::new(tmp.path().join("models"));
882        (reg, tmp)
883    }
884
885    #[test]
886    fn builtin_catalog_loads() {
887        let (reg, _tmp) = test_registry();
888        let all = reg.list();
889        assert_eq!(all.len(), builtin_catalog().len());
890    }
891
892    /// #137: a model tagged `requires-mlx-vlm` must report
893    /// `available: true` if and only if `mlx_vlm_cli::is_available()`
894    /// returns true. Without this, registry consumers (FFI
895    /// `listModelsUnified`, the tray Models submenu, agent routing)
896    /// see a model as available, the user picks it, and inference
897    /// bails with `mlx-vlm CLI not found on PATH`.
898    ///
899    /// The probe is environmental — runs the same check on the host
900    /// the test executes on. CI usually doesn't have `mlx_vlm`
901    /// installed → expected unavailable; a dev box with it installed
902    /// → expected available. Either way, the registry tracks the
903    /// runtime probe.
904    #[test]
905    fn mlx_vlm_models_reflect_runtime_availability() {
906        let (reg, _tmp) = test_registry();
907        let mlx_vlm_models: Vec<&ModelSchema> = reg
908            .list()
909            .into_iter()
910            .filter(|m| m.tags.iter().any(|t| t == "requires-mlx-vlm"))
911            .collect();
912        assert!(
913            !mlx_vlm_models.is_empty(),
914            "catalog should contain at least one model tagged \
915             `requires-mlx-vlm` — otherwise this regression has \
916             nothing to guard"
917        );
918
919        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
920        let expected = crate::backend::mlx_vlm_cli::is_available();
921        #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
922        let expected = false;
923
924        for m in mlx_vlm_models {
925            assert_eq!(
926                m.available, expected,
927                "model {} `available` field should reflect \
928                 mlx_vlm CLI presence (expected {expected}, got {})",
929                m.id, m.available
930            );
931        }
932    }
933
934    /// Embedded JSON must parse cleanly — if it doesn't, the runtime
935    /// would panic on first registry load. Catch it in CI instead.
936    #[test]
937    fn builtin_catalog_json_parses() {
938        let catalog: Vec<ModelSchema> = serde_json::from_str(BUILTIN_CATALOG_JSON)
939            .expect("builtin_catalog.json must be valid ModelSchema array");
940        assert!(
941            !catalog.is_empty(),
942            "embedded catalog has no entries — that's almost certainly wrong"
943        );
944
945        let mut seen = std::collections::HashSet::new();
946        for entry in &catalog {
947            assert!(
948                seen.insert(entry.id.clone()),
949                "duplicate id in builtin_catalog.json: {}",
950                entry.id
951            );
952        }
953    }
954
955    #[test]
956    fn public_benchmarks_round_trip_through_model_info() {
957        use crate::schema::BenchmarkScore;
958        let (mut reg, _tmp) = test_registry();
959        let mut schema = reg
960            .find_by_name("Qwen3-4B")
961            .expect("catalog has Qwen3-4B")
962            .clone();
963        schema.id = "test/qwen3-4b-with-bench".into();
964        schema.public_benchmarks = vec![
965            BenchmarkScore {
966                name: "MMLU-Pro".into(),
967                score: 0.482,
968                harness: Some("5-shot CoT".into()),
969                source_url: Some("https://example.invalid/qwen3-4b-card".into()),
970                measured_at: Some("2025-08-12".into()),
971            },
972            BenchmarkScore {
973                name: "HumanEval".into(),
974                score: 0.713,
975                harness: Some("pass@1".into()),
976                source_url: None,
977                measured_at: None,
978            },
979        ];
980        reg.register(schema);
981
982        let stored = reg
983            .get("test/qwen3-4b-with-bench")
984            .expect("registered model is retrievable");
985        let info = ModelInfo::from(stored);
986        assert_eq!(info.public_benchmarks.len(), 2);
987
988        // The serialized JSON shape is what the WS / FFI clients consume.
989        let json = serde_json::to_string(&info).unwrap();
990        assert!(json.contains("\"public_benchmarks\""));
991        assert!(json.contains("\"MMLU-Pro\""));
992        assert!(json.contains("\"5-shot CoT\""));
993
994        // Round-trip back through serde to confirm deserialization works.
995        let decoded: ModelInfo = serde_json::from_str(&json).unwrap();
996        assert_eq!(decoded.public_benchmarks.len(), 2);
997        assert_eq!(decoded.public_benchmarks[0].name, "MMLU-Pro");
998        assert_eq!(decoded.public_benchmarks[1].name, "HumanEval");
999    }
1000
1001    #[test]
1002    fn public_benchmarks_default_to_empty_when_absent_in_json() {
1003        // Older user-config JSON written before this field existed must
1004        // still deserialize cleanly into the new ModelSchema shape.
1005        let legacy_json = r#"{
1006            "id": "legacy/test:1",
1007            "name": "Legacy Test",
1008            "provider": "test",
1009            "family": "test",
1010            "version": "",
1011            "capabilities": ["generate"],
1012            "context_length": 4096,
1013            "param_count": "1B",
1014            "quantization": null,
1015            "performance": {},
1016            "cost": {},
1017            "source": { "type": "ollama", "model_tag": "legacy:1" },
1018            "tags": [],
1019            "supported_params": []
1020        }"#;
1021        let schema: ModelSchema = serde_json::from_str(legacy_json).unwrap();
1022        assert!(schema.public_benchmarks.is_empty());
1023    }
1024
1025    #[test]
1026    fn find_by_name() {
1027        let (reg, _tmp) = test_registry();
1028        let m = reg.find_by_name("Qwen3-4B").unwrap();
1029        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
1030        assert_eq!(m.id, "mlx/qwen3-4b:4bit");
1031        #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
1032        assert_eq!(m.id, "qwen/qwen3-4b:q4_k_m");
1033        assert!(m.has_capability(ModelCapability::Code));
1034    }
1035
1036    #[test]
1037    fn query_by_capability() {
1038        let (reg, _tmp) = test_registry();
1039        let embed_models = reg.query_by_capability(ModelCapability::Embed);
1040        assert_eq!(embed_models.len(), 2);
1041        assert!(embed_models
1042            .iter()
1043            .any(|model| model.name == "Qwen3-Embedding-0.6B"));
1044        assert!(embed_models
1045            .iter()
1046            .any(|model| model.name == "Qwen3-Embedding-0.6B-MLX"));
1047    }
1048
1049    #[test]
1050    fn query_with_filter() {
1051        let (reg, _tmp) = test_registry();
1052        let code_small = reg.query(&ModelFilter {
1053            capabilities: vec![ModelCapability::Code],
1054            max_size_mb: Some(3000),
1055            local_only: true,
1056            ..Default::default()
1057        });
1058        // Qwen3-1.7B, Qwen3-1.7B-MLX, Qwen3-4B, and Qwen3-4B-MLX fit and have Code capability.
1059        assert_eq!(code_small.len(), 4);
1060    }
1061
1062    #[test]
1063    fn register_remote() {
1064        let (mut reg, _tmp) = test_registry();
1065        let initial_len = reg.list().len();
1066        let initial_reasoning_len = reg
1067            .query(&ModelFilter {
1068                capabilities: vec![ModelCapability::Reasoning, ModelCapability::ToolUse],
1069                ..Default::default()
1070            })
1071            .len();
1072        let remote = ModelSchema {
1073            id: "anthropic/claude-sonnet-4-6:latest".into(),
1074            name: "Claude Sonnet 4.6".into(),
1075            provider: "anthropic".into(),
1076            family: "claude-4".into(),
1077            version: "latest".into(),
1078            capabilities: vec![
1079                ModelCapability::Generate,
1080                ModelCapability::Code,
1081                ModelCapability::Reasoning,
1082                ModelCapability::ToolUse,
1083            ],
1084            context_length: 200000,
1085            param_count: String::new(),
1086            quantization: None,
1087            performance: PerformanceEnvelope {
1088                latency_p50_ms: Some(2000),
1089                ..Default::default()
1090            },
1091            cost: CostModel {
1092                input_per_mtok: Some(3.0),
1093                output_per_mtok: Some(15.0),
1094                ..Default::default()
1095            },
1096            source: ModelSource::RemoteApi {
1097                endpoint: "https://api.anthropic.com/v1/messages".into(),
1098                api_key_env: "ANTHROPIC_API_KEY".into(),
1099                api_key_envs: vec![],
1100                api_version: Some("2023-06-01".into()),
1101                protocol: ApiProtocol::Anthropic,
1102            },
1103            tags: vec![],
1104            supported_params: vec![],
1105            public_benchmarks: vec![],
1106            available: false,
1107        };
1108
1109        reg.register(remote);
1110        // Same ID as builtin claude-sonnet-4-6 — replaces, count stays same
1111        assert_eq!(reg.list().len(), initial_len);
1112
1113        let reasoning = reg.query(&ModelFilter {
1114            capabilities: vec![ModelCapability::Reasoning, ModelCapability::ToolUse],
1115            ..Default::default()
1116        });
1117        // Replacing an existing remote slot should not change the reasoning/tool-use lineup size.
1118        assert_eq!(reasoning.len(), initial_reasoning_len);
1119    }
1120
1121    #[test]
1122    fn unregister() {
1123        let (mut reg, _tmp) = test_registry();
1124        let initial_len = reg.list().len();
1125        let removed = reg.unregister("qwen/qwen3-0.6b:q8_0");
1126        assert!(removed.is_some());
1127        assert_eq!(reg.list().len(), initial_len - 1);
1128    }
1129
1130    #[test]
1131    fn speech_models_are_curated() {
1132        let (reg, _tmp) = test_registry();
1133        let stt = reg.query_by_capability(ModelCapability::SpeechToText);
1134        let tts = reg.query_by_capability(ModelCapability::TextToSpeech);
1135        assert_eq!(stt.len(), 2);
1136        assert_eq!(tts.len(), 4);
1137    }
1138
1139    #[test]
1140    fn qwen_8b_variants_keep_tool_use_consistent() {
1141        let (reg, _tmp) = test_registry();
1142        for name in ["Qwen3-8B", "Qwen3-8B-MLX"] {
1143            let model = reg.find_by_name(name).expect("model should exist");
1144            assert!(model.has_capability(ModelCapability::ToolUse));
1145            assert!(model.has_capability(ModelCapability::MultiToolCall));
1146        }
1147    }
1148
1149    #[test]
1150    fn mac_name_resolution_prefers_mlx_siblings() {
1151        // Only used inside the aarch64-macos cfg below; non-mac targets
1152        // keep the test as a smoke compile.
1153        #[allow(unused_variables)]
1154        let (reg, _tmp) = test_registry();
1155        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
1156        {
1157            assert_eq!(reg.find_by_name("Qwen3-0.6B").unwrap().id, "mlx/qwen3-0.6b:6bit");
1158            assert_eq!(reg.find_by_name("Qwen3-1.7B").unwrap().id, "mlx/qwen3-1.7b:3bit");
1159            assert_eq!(
1160                reg.find_by_name("Qwen3-Embedding-0.6B").unwrap().id,
1161                "mlx/qwen3-embedding-0.6b:mxfp8"
1162            );
1163        }
1164    }
1165
1166    #[test]
1167    fn remote_multimodal_models_are_curated_as_vision_capable() {
1168        let (reg, _tmp) = test_registry();
1169        for name in [
1170            "claude-opus-4-7",
1171            "claude-opus-4-6",
1172            "claude-sonnet-4-6",
1173            "claude-haiku-4-5",
1174            "gpt-5.4",
1175            "gpt-5.4-mini",
1176            "o3",
1177            "o4-mini",
1178            "gpt-4.1-mini",
1179            "gemini-2.5-pro",
1180            "gemini-2.5-flash",
1181        ] {
1182            let model = reg.find_by_name(name).expect("model should exist");
1183            assert!(
1184                model.has_capability(ModelCapability::Vision),
1185                "{name} should be curated as vision-capable"
1186            );
1187        }
1188    }
1189
1190    #[test]
1191    fn qwen25vl_entries_are_replaced_by_qwen3vl_in_builtin_catalog() {
1192        let (reg, _tmp) = test_registry();
1193
1194        let stale_ids = [
1195            // Native MLX text tower can't tokenize images — never advertise.
1196            "mlx/qwen2.5-vl-3b:4bit",
1197            "mlx/qwen2.5-vl-7b:4bit",
1198            // Qwen2.5-VL is superseded by Qwen3-VL; drop the mlx-vlm CLI
1199            // catalog entries so callers route to the upgraded family.
1200            "mlx-vlm/qwen2.5-vl-3b:4bit",
1201            "mlx-vlm/qwen2.5-vl-7b:4bit",
1202            // Same supersession applies to the vLLM-MLX route.
1203            "vllm-mlx/qwen2.5-vl-3b:4bit",
1204        ];
1205        for id in stale_ids {
1206            assert!(
1207                reg.get(id).is_none(),
1208                "{id} is superseded by Qwen3-VL; the catalog must not advertise it"
1209            );
1210        }
1211
1212        let vision_ids: Vec<&str> = reg
1213            .query_by_capability(ModelCapability::Vision)
1214            .into_iter()
1215            .map(|model| model.id.as_str())
1216            .collect();
1217        for stale in stale_ids {
1218            assert!(
1219                !vision_ids.contains(&stale),
1220                "{stale} must not be reachable through the Vision capability index"
1221            );
1222        }
1223        assert!(
1224            vision_ids.contains(&"mlx-vlm/qwen3-vl-2b:bf16"),
1225            "Qwen3-VL is the supported local VL family and must route as Vision"
1226        );
1227    }
1228
1229    #[test]
1230    fn gemini_models_are_curated_for_multimodal_tool_use() {
1231        let (reg, _tmp) = test_registry();
1232        for name in ["gemini-2.5-pro", "gemini-2.5-flash"] {
1233            let model = reg.find_by_name(name).expect("model should exist");
1234            assert!(model.has_capability(ModelCapability::Vision));
1235            assert!(model.has_capability(ModelCapability::ToolUse));
1236            assert!(model.has_capability(ModelCapability::MultiToolCall));
1237        }
1238    }
1239
1240    #[test]
1241    fn visual_generation_models_are_curated() {
1242        let (reg, _tmp) = test_registry();
1243        assert_eq!(
1244            reg.query_by_capability(ModelCapability::ImageGeneration).len(),
1245            1
1246        );
1247        assert_eq!(
1248            reg.query_by_capability(ModelCapability::VideoGeneration).len(),
1249            1
1250        );
1251    }
1252}