//! Hugging Face GGUF library (Capri `packages/runtime/src/huggingface/*`): //! search → inspect a pinned revision → choose a file by quantization and VRAM → plan → //! resumable SHA-256-verified download → import into Ollama (`/api/blobs` + `/api/create`) → remove. use std::io::{Read, Seek, Write}; use std::path::{Path, PathBuf}; use std::sync::LazyLock; use std::time::{Duration, Instant}; use anyhow::{anyhow, bail, ensure, Context, Result}; use capri_llm::Ollama; use futures::StreamExt; use regex::Regex; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; use url::Url; use crate::hardware::Hardware; pub const HUB: &str = "https://huggingface.co"; const CDN_HOSTS: &[&str] = &[ "huggingface.co", "cdn-lfs.huggingface.co", "cdn-lfs.hf.co", "cdn-lfs-us-1.hf.co", "cdn-lfs-eu-1.hf.co", "cas-bridge.xethub.hf.co", "cas-server.xethub.hf.co", "transfer.xethub.hf.co", "us.aws.cdn.hf.co", "eu.aws.cdn.hf.co", ]; const RESERVE: u64 = 64 << 20; const DESCRIPTION: &str = "Imported Hugging Face model. Capability metadata is checked against the local engine; task quality requires evaluation."; static REPO: LazyLock = LazyLock::new(|| Regex::new(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,95}/[A-Za-z0-9][A-Za-z0-9_.-]{0,95}$").expect("valid regex")); static REVISION: LazyLock = LazyLock::new(|| Regex::new(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$").expect("valid regex")); static SPLIT: LazyLock = LazyLock::new(|| Regex::new(r"(?i)^(.*)-(\d{5})-of-(\d{5})\.gguf$").expect("valid regex")); fn http_error(status: u16) -> anyhow::Error { anyhow!(match status { 401 => "Hugging Face authentication is required or the token has expired.".to_string(), 403 => "Hugging Face access denied. Check model approval and token permissions.".into(), 404 => "The Hugging Face model, revision or file was not found.".into(), 429 => "Hugging Face rate limit reached. Try again later.".into(), n => format!("Hugging Face request failed (HTTP {n})."), }) } /// Removes tokens and URLs from texts shown in the UI. pub fn scrub(message: &str) -> String { let token = Regex::new(r"hf_[A-Za-z0-9]{8,}").expect("valid regex"); let url = Regex::new(r"https://\S+").expect("valid regex"); url.replace_all(&token.replace_all(message, "[REDACTED]"), "[remote address]").into_owned() } /// Windows-safe relative file name (files may be copied to other systems). pub fn safe_file_name(name: &str) -> bool { let device = Regex::new(r"(?i)^(?:con|prn|aux|nul|com\d|lpt\d)(?:\..*)?$").expect("valid regex"); name.chars().count() <= 240 && !name.chars().any(|c| c.is_control() || matches!(c, '\\' | ':' | '%' | '?' | '#' | '<' | '>' | '"' | '|' | '*')) && name.split('/').all(|s| !s.is_empty() && s != "." && s != ".." && !s.ends_with('.') && !s.ends_with(' ') && !device.is_match(s)) } #[derive(Clone, Debug, Default, PartialEq)] pub struct RepoRef { pub repository: String, pub revision: Option, pub file: Option, } /// `owner/model` or a huggingface.co model URL (optionally `/tree|blob|resolve//`). pub fn parse_repository(input: &str) -> Result { let input = input.trim(); ensure!(!input.is_empty() && input.len() <= 1000, "Enter a Hugging Face repository or model URL."); let mut out = RepoRef::default(); if input.contains("://") { let url = Url::parse(input).map_err(|_| anyhow!("Use a model URL from huggingface.co without credentials or query parameters."))?; ensure!( url.origin().ascii_serialization() == HUB && url.username().is_empty() && url.password().is_none() && url.query().is_none() && url.fragment().is_none(), "Use a model URL from huggingface.co without credentials or query parameters." ); // Percent-encoded segments stay encoded and are rejected by the name rules below. let segments: Vec = url.path_segments().into_iter().flatten().filter(|s| !s.is_empty()).map(str::to_string).collect(); ensure!(segments.len() == 2 || (segments.len() >= 4 && matches!(segments[2].as_str(), "tree" | "blob" | "resolve")), "Unsupported Hugging Face model URL."); out.repository = format!("{}/{}", segments[0], segments[1]); if segments.len() >= 4 { ensure!(REVISION.is_match(&segments[3]), "Unsupported Hugging Face model URL."); out.revision = Some(segments[3].clone()); if segments.len() > 4 { let file = segments[4..].join("/"); ensure!(safe_file_name(&file), "Invalid Hugging Face filename."); out.file = Some(file); } } } else { out.repository = input.to_string(); } ensure!(REPO.is_match(&out.repository) && !out.repository.contains(".."), "Use a Hugging Face repository in owner/model form."); Ok(out) } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchRow { pub repository: String, pub downloads: u64, pub gated: bool, pub private: bool, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HubFile { pub path: String, /// `gguf` | `projector` | `other` pub kind: String, pub bytes: Option, pub sha256: Option, pub split: bool, } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct RepoInfo { pub repository: String, /// Pinned 40-hex commit used for every download. pub revision: String, pub task: String, pub files: Vec, pub license: Option, pub languages: Vec, pub gated: bool, pub private: bool, pub selected_filename: Option, } fn sha256_hex(v: &Value) -> Option { let s = v.as_str()?.trim_start_matches("sha256:"); (s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())).then(|| s.to_ascii_lowercase()) } /// Quantization tag of a GGUF file name (`Q4_K_M`, `IQ4_XS`, `Q8_0`, `F16`…). pub fn quantization(path: &str) -> Option { let re = Regex::new(r"(?i)(?:^|[-_.])((?:I?Q\d(?:_[A-Z0-9]+)*)|BF16|F16|F32)(?:[-_.]|$)").expect("valid regex"); let name = path.rsplit('/').next().unwrap_or(path); re.captures(name.trim_end_matches(".gguf")).map(|c| c[1].to_ascii_uppercase()) } /// Preferred quantizations, best quality first. const QUANT_ORDER: &[&str] = &["Q8_0", "Q6_K", "Q5_K_M", "Q5_K_S", "Q5_0", "Q4_K_M", "Q4_K_S", "IQ4_XS", "IQ4_NL", "Q4_0", "Q3_K_L", "Q3_K_M", "IQ3_M", "Q3_K_S", "IQ3_XS", "Q2_K", "IQ2_M"]; /// Expands a shard name to all shard names (`x-00001-of-00003.gguf` → 3 names). fn shard_names(path: &str) -> Option> { let c = SPLIT.captures(path)?; let count: usize = c[3].parse().ok()?; Some((1..=count).map(|i| format!("{}-{i:05}-of-{count:05}.gguf", &c[1])).collect()) } /// Picks the weight file for this machine: the best quantization whose total size leaves room /// for context in dedicated VRAM (or half the RAM without a GPU); else the smallest file. pub fn choose_file(info: &RepoInfo, hw: &Hardware) -> Option { let size = |name: &str| info.files.iter().find(|f| f.path == name).and_then(|f| f.bytes); let candidates: Vec<(String, u64, usize)> = info .files .iter() .filter(|f| f.kind == "gguf" && (!f.split || SPLIT.captures(&f.path).is_some_and(|c| &c[2] == "00001"))) .filter_map(|f| { let total = match shard_names(&f.path) { Some(names) => names.iter().map(|n| size(n)).sum::>()?, None => f.bytes?, }; let rank = quantization(&f.path).and_then(|q| QUANT_ORDER.iter().position(|o| *o == q)).unwrap_or(QUANT_ORDER.len()); Some((f.path.clone(), total, rank)) }) .collect(); let vram = hw.dedicated_vram_gib(); let budget = if vram > 0.0 { vram - 1.5 } else { hw.ram_gib() * 0.5 } * (1u64 << 30) as f64; candidates .iter() .filter(|(_, bytes, rank)| (*bytes as f64) <= budget && *rank < QUANT_ORDER.len()) .min_by_key(|(_, _, rank)| *rank) .or_else(|| candidates.iter().min_by_key(|(_, bytes, _)| *bytes)) .map(|(path, _, _)| path.clone()) } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PlanFile { pub path: String, pub bytes: u64, pub sha256: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Plan { pub schema_version: u32, pub task: String, pub repository: String, pub revision: String, pub files: Vec, pub context_tokens: u32, pub license: Option, pub languages: Vec, pub private: bool, pub total_bytes: u64, pub id: String, } /// `hf-` + first 24 hex of sha256 of compact `{repository, revision, files}` JSON (same bytes as Capri's JS). pub fn plan_id(repository: &str, revision: &str, files: &[PlanFile]) -> String { #[derive(Serialize)] struct IdInput<'a> { repository: &'a str, revision: &'a str, files: &'a [PlanFile], } let json = serde_json::to_string(&IdInput { repository, revision, files }).expect("serializable"); format!("hf-{}", &hex::encode(Sha256::digest(json.as_bytes()))[..24]) } /// Installation plan for a weight file (all shards) and an optional projector. pub fn plan(info: &RepoInfo, filename: &str, projector: Option<&str>, context_tokens: u32) -> Result { ensure!(info.task == "llm", "Install this voice through a supported Capri TTS adapter."); let weights = match shard_names(filename) { Some(names) => { ensure!((2..=128).contains(&names.len()), "This GGUF shard count is outside the supported range."); names } None => vec![filename.to_string()], }; let mut files = Vec::new(); for (name, kind) in weights.iter().map(|n| (n.as_str(), "gguf")).chain(projector.map(|p| (p, "projector"))) { let f = info.files.iter().find(|f| f.path == name && f.kind == kind).context("The GGUF selection has a missing shard or an incompatible projector.")?; let (Some(bytes), Some(sha256)) = (f.bytes, f.sha256.clone()) else { bail!("This file has no independently verifiable size and SHA-256.") }; files.push(PlanFile { path: f.path.clone(), bytes, sha256 }); } let plan = Plan { schema_version: 1, task: "llm".into(), id: plan_id(&info.repository, &info.revision, &files), repository: info.repository.clone(), revision: info.revision.clone(), total_bytes: files.iter().map(|f| f.bytes).sum(), files, context_tokens, license: info.license.clone(), languages: info.languages.clone(), private: info.private, }; validate_plan(&plan)?; Ok(plan) } pub fn validate_plan(plan: &Plan) -> Result<()> { let hex40 = plan.revision.len() == 40 && plan.revision.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()); ensure!( plan.schema_version == 1 && plan.task == "llm" && hex40 && (1..=129).contains(&plan.files.len()) && plan.files.iter().all(|f| safe_file_name(&f.path) && (12..=256 << 30).contains(&f.bytes) && sha256_hex(&json!(f.sha256)).as_deref() == Some(f.sha256.as_str())) && plan.id == plan_id(&plan.repository, &plan.revision, &plan.files) && plan.total_bytes == plan.files.iter().map(|f| f.bytes).sum::() && (8192..=262_144).contains(&plan.context_tokens), "Invalid Hugging Face installation plan." ); Ok(()) } #[derive(Clone, Debug, Default, PartialEq)] pub struct Progress { /// `downloading` | `verifying` | `installed` | `importing` pub status: &'static str, pub file: String, pub completed: u64, pub total: u64, pub bytes_per_second: f64, } /// Hub HTTP client: allowlisted hosts, manual redirects, token only on huggingface.co. #[derive(Clone)] pub struct Hub { http: reqwest::Client, base: Url, token: Option, } impl std::fmt::Debug for Hub { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Hub").field("base", &self.base.as_str()).field("has_token", &self.token.is_some()).finish() } } fn free_space(path: &Path) -> Option { let s = nix::sys::statvfs::statvfs(path).ok()?; Some(s.blocks_available() as u64 * s.fragment_size() as u64) } fn is_gguf(path: &Path) -> bool { let mut header = [0u8; 8]; std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut header)).is_ok() && &header[..4] == b"GGUF" && matches!(u32::from_le_bytes(header[4..].try_into().expect("4 bytes")), 2 | 3) } /// Feeds a reader into a hasher (256 KiB chunks); returns the byte count. fn hash_into(mut reader: impl Read, hasher: &mut Sha256) -> std::io::Result { let mut buf = vec![0u8; 256 * 1024]; let mut total = 0; loop { match reader.read(&mut buf)? { 0 => return Ok(total), n => { hasher.update(&buf[..n]); total += n as u64; } } } } fn hash_file(path: &Path) -> Result<(Sha256, u64)> { let mut hasher = Sha256::new(); let n = hash_into(std::fs::File::open(path)?, &mut hasher)?; Ok((hasher, n)) } impl Hub { pub fn new(token: Option) -> Self { Self::with_base(HUB, token) } /// `base` replaces `https://huggingface.co` (tests). pub fn with_base(base: &str, token: Option) -> Self { let http = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()).connect_timeout(Duration::from_secs(30)).build().expect("HTTP client"); Self { http, base: Url::parse(base).expect("hub base"), token } } fn allowed(&self, url: &Url) -> bool { url.origin() == self.base.origin() || (url.scheme() == "https" && url.port().is_none() && url.username().is_empty() && url.password().is_none() && url.fragment().is_none() && url.host_str().is_some_and(|h| CDN_HOSTS.contains(&h))) } async fn get(&self, mut url: Url, accept: &str, range: Option, timeout: Duration) -> Result { for _ in 0..=5 { ensure!(self.allowed(&url), "Unapproved Hugging Face network destination."); let mut request = self.http.get(url.clone()).header("accept", accept).header("accept-encoding", "identity").timeout(timeout); if let (Some(token), true) = (&self.token, url.origin() == self.base.origin()) { request = request.bearer_auth(token); } if let Some(offset) = range.filter(|&o| o > 0) { request = request.header("range", format!("bytes={offset}-")); } let response = request.send().await.map_err(|_| anyhow!("Hugging Face connection failed or timed out. Check the network and proxy."))?; if !matches!(response.status().as_u16(), 301 | 302 | 303 | 307 | 308) { return Ok(response); } let location = response.headers().get("location").and_then(|l| l.to_str().ok()).context("Hugging Face returned an invalid redirect.")?; url = url.join(location).map_err(|_| anyhow!("Hugging Face returned an invalid redirect."))?; } bail!("Hugging Face returned too many redirects.") } async fn json(&self, url: Url) -> Result { let response = self.get(url, "application/json", None, Duration::from_secs(30)).await?; if !response.status().is_success() { return Err(http_error(response.status().as_u16())); } let bytes = response.bytes().await.map_err(|_| anyhow!("Hugging Face metadata could not be read within the size and time limits."))?; ensure!(bytes.len() <= 4 << 20, "Hugging Face metadata could not be read within the size and time limits."); serde_json::from_slice(&bytes).map_err(|_| anyhow!("Hugging Face returned invalid metadata.")) } /// GGUF language models, most downloaded first (`limit` 1…30). pub async fn search(&self, query: &str, limit: u32) -> Result> { let query = query.trim(); ensure!(!query.is_empty() && query.chars().count() <= 160, "Enter a model name and select a model type."); let mut url = self.base.join("/api/models")?; url.query_pairs_mut() .append_pair("search", query) .append_pair("limit", &limit.clamp(1, 30).to_string()) .append_pair("sort", "downloads") .append_pair("direction", "-1") .append_pair("full", "true") .append_pair("filter", "gguf"); let rows = self.json(url).await?; let rows = rows.as_array().context("Hugging Face returned invalid metadata.")?; Ok(rows .iter() .filter_map(|r| { let repository = r["id"].as_str().or(r["modelId"].as_str())?; REPO.is_match(repository).then(|| SearchRow { repository: repository.into(), downloads: r["downloads"].as_u64().unwrap_or(0), gated: r["gated"].as_bool().unwrap_or(r["gated"].is_string()), private: r["private"].as_bool().unwrap_or(false), }) }) .collect()) } /// Immutable file manifest of a revision (`main` by default). pub async fn inspect(&self, input: &str, revision: Option<&str>) -> Result { let r = parse_repository(input)?; let revision = revision.map(str::to_string).or(r.revision).unwrap_or_else(|| "main".into()); ensure!(REVISION.is_match(&revision), "Unsupported Hugging Face model URL."); let url = self.base.join(&format!("/api/models/{}/revision/{}?blobs=true", r.repository, revision))?; let v = self.json(url).await?; let sha = v["sha"].as_str().filter(|s| s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())); let siblings = v["siblings"].as_array().filter(|s| s.len() <= 4096); let (Some(sha), Some(siblings)) = (sha, siblings) else { bail!("Hugging Face did not provide a bounded immutable file manifest.") }; let files = siblings .iter() .filter_map(|s| { let path = s["rfilename"].as_str().filter(|p| safe_file_name(p))?; let last = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase(); let kind = if !last.ends_with(".gguf") { "other" } else if last.starts_with("mmproj") || last.starts_with("projector") { "projector" } else { "gguf" }; Some(HubFile { path: path.into(), kind: kind.into(), bytes: s["lfs"]["size"].as_u64().or(s["size"].as_u64()), sha256: sha256_hex(&s["lfs"]["sha256"]).or_else(|| sha256_hex(&s["lfs"]["oid"])), split: SPLIT.is_match(path), }) }) .collect(); let languages = match &v["cardData"]["language"] { Value::String(s) => vec![s.clone()], Value::Array(a) => a.iter().filter_map(|l| l.as_str().map(str::to_string)).collect(), _ => vec![], }; let lang = Regex::new(r"^[a-zA-Z0-9-]{2,20}$").expect("valid regex"); Ok(RepoInfo { repository: r.repository, revision: sha.into(), task: if v["pipeline_tag"] == "text-to-speech" { "tts" } else { "llm" }.into(), files, license: v["cardData"]["license"].as_str().filter(|l| l.len() <= 100).map(str::to_string), languages: languages.into_iter().filter(|l| lang.is_match(l)).take(100).collect(), gated: v["gated"].as_bool().unwrap_or(v["gated"].is_string()), private: v["private"].as_bool().unwrap_or(false), selected_filename: r.file, }) } /// Resumable verified download into `/`. `progress(done, bytes/s)`. /// Partial bytes are kept for the next attempt; a file is published only after its hash matches. pub async fn download(&self, plan: &Plan, file: &PlanFile, folder: &Path, mut progress: impl FnMut(u64, f64)) -> Result { let target = folder.join(&file.sha256); let partial = folder.join(format!("{}.partial", file.sha256)); std::fs::create_dir_all(folder)?; if std::fs::metadata(&target).is_ok_and(|m| m.len() == file.bytes) && hex::encode(hash_file(&target)?.0.finalize()) == file.sha256 { progress(file.bytes, 0.0); return Ok(target); } let path: String = file.path.split('/').map(|s| url::form_urlencoded::byte_serialize(s.as_bytes()).collect::().replace('+', "%20")).collect::>().join("/"); let url = self.base.join(&format!("/{}/resolve/{}/{path}", plan.repository, plan.revision))?; let permanent = Regex::new(r"(?i)checksum|byte range|manifest|declared size|disk space|denied|authentication|not found|Unapproved").expect("valid regex"); let mut last_error = anyhow!("Hugging Face download could not be completed. Retry to resume."); for attempt in 0..4u32 { match self.attempt(&url, file, &partial, &mut progress).await { Ok(()) => { std::fs::rename(&partial, &target)?; return Ok(target); } Err(e) => { if permanent.is_match(&e.to_string()) { return Err(e); } last_error = e; tokio::time::sleep(Duration::from_millis(1000 * 2u64.pow(attempt))).await; } } } Err(last_error.context("Hugging Face download could not be completed. Retry to resume.")) } async fn attempt(&self, url: &Url, file: &PlanFile, partial: &Path, progress: &mut impl FnMut(u64, f64)) -> Result<()> { let mut offset = std::fs::symlink_metadata(partial).map(|m| m.len()).unwrap_or(0); if offset >= file.bytes { let (hasher, _) = hash_file(partial)?; if offset == file.bytes && hex::encode(hasher.finalize()) == file.sha256 { return Ok(()); } std::fs::remove_file(partial)?; offset = 0; } let folder = partial.parent().context("no folder")?; ensure!(free_space(folder).is_none_or(|free| free >= file.bytes - offset + RESERVE), "There is not enough free disk space for this Hugging Face model."); let response = self.get(url.clone(), "application/octet-stream", Some(offset), Duration::from_secs(7200)).await?; let mut out = std::fs::OpenOptions::new().create(true).append(true).open(partial)?; let mut hasher = Sha256::new(); match response.status().as_u16() { 206 => { let range = response.headers().get("content-range").and_then(|v| v.to_str().ok()).unwrap_or(""); ensure!(range == format!("bytes {offset}-{}/{}", file.bytes - 1, file.bytes), "Hugging Face returned an invalid byte range."); hash_into(std::fs::File::open(partial)?.take(offset), &mut hasher)?; } 200 => { // A full body is never appended to a prefix. out.set_len(0)?; out.seek(std::io::SeekFrom::Start(0))?; offset = 0; } status => return Err(http_error(status)), } if let Some(len) = response.content_length() { ensure!(len == file.bytes - offset, "Hugging Face file size differs from the resolved manifest."); } let (started, mut done, mut reported) = (Instant::now(), offset, Instant::now()); let mut stream = response.bytes_stream(); loop { let chunk = match tokio::time::timeout(Duration::from_secs(45), stream.next()).await { Err(_) => bail!("Hugging Face download stalled."), Ok(None) => break, Ok(Some(chunk)) => chunk.map_err(|_| anyhow!("Hugging Face connection failed or timed out. Check the network and proxy."))?, }; done += chunk.len() as u64; ensure!(done <= file.bytes, "Hugging Face file exceeds its declared size."); out.write_all(&chunk)?; hasher.update(&chunk); if reported.elapsed() >= Duration::from_millis(250) { reported = Instant::now(); ensure!(free_space(folder).is_none_or(|f| f >= 32 << 20), "Free disk space was exhausted during the model download."); progress(done, (done - offset) as f64 / started.elapsed().as_secs_f64().max(0.1)); } } out.sync_all()?; ensure!(done == file.bytes, "Hugging Face download was incomplete."); progress(done, 0.0); if hex::encode(hasher.finalize()) != file.sha256 { let _ = std::fs::remove_file(partial); bail!("Hugging Face checksum verification failed."); } Ok(()) } } /// Model profile of an imported package. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Profile { pub id: String, pub source: String, pub family: String, pub model: String, pub alias: String, pub context_tokens: u32, pub context_limit: u32, pub cpu_threads: u32, pub capabilities: Vec, pub ram_gib: f64, pub recommended_vram_gib: f64, pub memory_estimated: bool, pub size_bytes: u64, pub experimental: bool, pub description: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Receipt { #[serde(flatten)] pub plan: Plan, pub installed_at: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub profile: Option, } /// Exclusive `.operation.lock` with the owner pid; a dead owner's lock is stale. struct OpLock(PathBuf); impl OpLock { fn take(root: &Path) -> Result { use std::os::unix::fs::OpenOptionsExt; std::fs::create_dir_all(root)?; let path = root.join(".operation.lock"); for _ in 0..2 { match std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&path) { Ok(mut f) => { f.write_all(json!({"pid": std::process::id()}).to_string().as_bytes())?; return Ok(Self(path)); } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { let pid = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice::(&b).ok()).and_then(|v| v["pid"].as_i64()); let dead = pid.is_some_and(|p| nix::sys::signal::kill(nix::unistd::Pid::from_raw(p as i32), None) == Err(nix::errno::Errno::ESRCH)); ensure!(dead, "Another Hugging Face operation is running. Wait for it to finish."); std::fs::remove_file(&path)?; } Err(e) => return Err(e.into()), } } bail!("Another Hugging Face operation is running. Wait for it to finish.") } } impl Drop for OpLock { fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } } /// Packages under `/huggingface`: `blobs/` and `packages//receipt.json`. pub struct Library { pub root: PathBuf, } impl Library { pub fn new(root: PathBuf) -> Self { Self { root } } fn blob(&self, sha: &str) -> PathBuf { self.root.join("blobs").join(sha) } fn receipt_path(&self, id: &str) -> PathBuf { self.root.join("packages").join(id).join("receipt.json") } /// Valid packages whose blobs are all present; invalid ones are omitted. pub fn list(&self) -> Vec { let mut out: Vec = std::fs::read_dir(self.root.join("packages")) .into_iter() .flatten() .flatten() .filter_map(|e| { let id = e.file_name().into_string().ok()?; let bytes = capri_core::fsutil::read_regular(&self.receipt_path(&id), 256 * 1024).ok()??; let r: Receipt = serde_json::from_slice(&bytes).ok()?; let complete = r.plan.files.iter().all(|f| std::fs::metadata(self.blob(&f.sha256)).is_ok_and(|m| m.len() == f.bytes)); (r.plan.id == id && validate_plan(&r.plan).is_ok() && complete && r.profile.as_ref().is_none_or(|p| p.id == id && p.alias == format!("capri-{id}:latest"))).then_some(r) }) .collect(); out.sort_by(|a, b| a.plan.repository.cmp(&b.plan.repository)); out } fn write_receipt(&self, receipt: &Receipt) -> Result<()> { let path = self.receipt_path(&receipt.plan.id); std::fs::create_dir_all(path.parent().context("no parent")?)?; capri_core::fsutil::write_json_atomic(&path, receipt) } /// Downloads every file of the plan and records the receipt (keeps an existing profile). pub async fn install(&self, hub: &Hub, plan: &Plan, mut progress: impl FnMut(&Progress)) -> Result<()> { validate_plan(plan)?; let _lock = OpLock::take(&self.root)?; let blobs = self.root.join("blobs"); std::fs::create_dir_all(&blobs)?; let missing: u64 = plan.files.iter().filter(|f| !self.blob(&f.sha256).exists()).map(|f| f.bytes).sum(); ensure!(free_space(&blobs).is_none_or(|free| free >= missing + plan.total_bytes + RESERVE), "There is not enough free disk space for download and model import."); let mut before = 0; for file in &plan.files { let path = hub .download(plan, file, &blobs, |done, rate| { progress(&Progress { status: "downloading", file: file.path.clone(), completed: before + done, total: plan.total_bytes, bytes_per_second: rate }) }) .await?; if file.path.to_ascii_lowercase().ends_with(".gguf") && !is_gguf(&path) { bail!("The selected file is not a supported GGUF model."); } before += file.bytes; } let profile = self.list().into_iter().find(|r| r.plan.id == plan.id).and_then(|r| r.profile); self.write_receipt(&Receipt { plan: plan.clone(), installed_at: chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string(), profile })?; progress(&Progress { status: "installed", completed: plan.total_bytes, total: plan.total_bytes, ..Default::default() }); Ok(()) } /// Imports an installed package into Ollama as `capri-:latest` and records its profile. pub async fn import(&self, ollama: &Ollama, id: &str) -> Result { let _lock = OpLock::take(&self.root)?; let mut receipt = self.list().into_iter().find(|r| r.plan.id == id).context("Hugging Face package needs repair.")?; let alias = format!("capri-{id}:latest"); let mut files = serde_json::Map::new(); for f in &receipt.plan.files { let path = self.blob(&f.sha256); let sha = path.clone(); let digest = tokio::task::spawn_blocking(move || hash_file(&sha).map(|(h, _)| hex::encode(h.finalize()))).await??; ensure!(digest == f.sha256, "Hugging Face package checksum changed. Repair the model."); ensure!(is_gguf(&path), "The selected file is not a supported GGUF model."); ollama.upload_blob(&format!("sha256:{digest}"), &path).await.map_err(|e| anyhow!("Local model import failed ({e})."))?; files.insert(f.path.clone(), json!(format!("sha256:{digest}"))); } let new_alias = receipt.profile.is_none(); let result = async { ollama.create(json!({"model": alias, "files": files})).await.map_err(|_| anyhow!("The local engine does not support this GGUF model."))?; let show = ollama.show_info(&alias).await?.unwrap_or_default(); let arch = show["model_info"]["general.architecture"].as_str().unwrap_or(""); let limit = show["model_info"][format!("{arch}.context_length")].as_u64().filter(|&l| l >= 8192); let (Some(limit), true) = (limit, show["template"].as_str().is_some_and(|t| !t.trim().is_empty())) else { bail!("The imported model needs a verified chat template and context of at least 8K.") }; let caps: Vec = show["capabilities"].as_array().into_iter().flatten().filter_map(|c| c.as_str().map(str::to_string)).collect(); ensure!(caps.iter().any(|c| c == "completion"), "This model does not support text completion."); let projector = receipt.plan.files.iter().any(|f| f.path.rsplit('/').next().is_some_and(|n| n.to_ascii_lowercase().starts_with("mmproj") || n.to_ascii_lowercase().starts_with("projector"))); ensure!(!projector || caps.iter().any(|c| c == "vision"), "The selected projector does not provide compatible vision support."); let limit = limit.min(262_144) as u32; let gib = receipt.plan.total_bytes as f64 / (1u64 << 30) as f64; Ok(Profile { id: id.into(), source: "huggingface".into(), family: receipt.plan.repository.clone(), model: alias.clone(), alias: alias.clone(), context_tokens: receipt.plan.context_tokens.min(limit), context_limit: limit, cpu_threads: 4, capabilities: ["tools", "vision", "thinking"].iter().filter(|c| caps.iter().any(|x| x == *c)).map(|c| c.to_string()).collect(), ram_gib: (gib * 1.3 + 4.0).ceil(), recommended_vram_gib: (gib + 2.0).ceil(), memory_estimated: true, size_bytes: receipt.plan.total_bytes, experimental: true, description: DESCRIPTION.into(), }) } .await; match result { Ok(profile) => { receipt.profile = Some(profile.clone()); self.write_receipt(&receipt)?; Ok(profile) } Err(e) => { if new_alias { let _ = ollama.delete(&alias).await; } Err(e) } } } /// Removes a package (refuses the active or a resident model); shared blobs are kept. /// Returns the freed bytes. pub async fn remove(&self, ollama: &Ollama, id: &str, active_model: &str) -> Result { let _lock = OpLock::take(&self.root)?; let all = self.list(); let receipt = all.iter().find(|r| r.plan.id == id).context("Hugging Face package needs repair.")?; if let Some(profile) = &receipt.profile { ensure!(profile.alias != active_model, "Switch to another model before removing the active model."); ensure!(!ollama.ps().await.unwrap_or_default().iter().any(|m| m.name == profile.alias), "Unload this model before removing it."); ollama.delete(&profile.alias).await?; } std::fs::remove_dir_all(self.root.join("packages").join(id))?; let mut freed = 0; for f in &receipt.plan.files { if !all.iter().any(|r| r.plan.id != id && r.plan.files.iter().any(|g| g.sha256 == f.sha256)) && std::fs::remove_file(self.blob(&f.sha256)).is_ok() { freed += f.bytes; } } Ok(freed) } } #[cfg(test)] mod tests { use super::*; use wiremock::matchers::{header, method, path, query_param}; use wiremock::{Mock, MockServer, Request, ResponseTemplate}; const REV: &str = "0123456789abcdef0123456789abcdef01234567"; fn gguf(len: usize) -> Vec { let mut v = b"GGUF\x03\x00\x00\x00".to_vec(); v.resize(len, 7); v } fn sha(bytes: &[u8]) -> String { hex::encode(Sha256::digest(bytes)) } #[test] fn repository_references_and_names() { assert_eq!(parse_repository("org/Model-GGUF").unwrap().repository, "org/Model-GGUF"); let r = parse_repository("https://huggingface.co/org/M/blob/main/sub/m.Q4_K_M.gguf").unwrap(); assert_eq!((r.revision.as_deref(), r.file.as_deref()), (Some("main"), Some("sub/m.Q4_K_M.gguf"))); for bad in ["https://evil.example/org/m", "https://huggingface.co/org/m?x=1", "org", "org/../x", "https://huggingface.co/org/m/commits/main"] { assert!(parse_repository(bad).is_err(), "{bad}"); } assert!(!safe_file_name("a/../b") && !safe_file_name("con.gguf") && !safe_file_name("a:b") && safe_file_name("dir/x.gguf")); assert_eq!(quantization("Qwen3-4B-Q4_K_M.gguf").as_deref(), Some("Q4_K_M")); assert_eq!(quantization("model.IQ4_XS.gguf").as_deref(), Some("IQ4_XS")); assert_eq!(quantization("model-f16.gguf").as_deref(), Some("F16")); assert_eq!(scrub("token hf_abcdefghijk at https://x.example/a?sig=1 failed"), "token [REDACTED] at [remote address] failed"); } fn info(files: Vec<(&str, &str, u64)>) -> RepoInfo { RepoInfo { repository: "org/m".into(), revision: REV.into(), task: "llm".into(), files: files.into_iter().map(|(p, k, b)| HubFile { path: p.into(), kind: k.into(), bytes: Some(b), sha256: Some("a".repeat(64)), split: SPLIT.is_match(p) }).collect(), ..Default::default() } } #[test] fn file_choice_and_plans() { let gib = 1u64 << 30; let repo = info(vec![("m-Q8_0.gguf", "gguf", 8 * gib), ("m-Q6_K.gguf", "gguf", 6 * gib), ("m-Q4_K_M.gguf", "gguf", 4 * gib), ("m-F16.gguf", "gguf", 15 * gib), ("mmproj-f16.gguf", "projector", gib)]); let gpu = |v: f64| Hardware { ram_bytes: 24 * gib, gpus: vec![crate::hardware::Gpu { memory_kind: "dedicated".into(), vram_mib: Some((v * 1024.0) as u64), ..Default::default() }], ..Default::default() }; assert_eq!(choose_file(&repo, &gpu(8.0)).as_deref(), Some("m-Q6_K.gguf")); assert_eq!(choose_file(&repo, &gpu(12.0)).as_deref(), Some("m-Q8_0.gguf")); assert_eq!(choose_file(&repo, &Hardware { ram_bytes: 4 * gib, ..Default::default() }).as_deref(), Some("m-Q4_K_M.gguf"), "nothing fits: smallest"); let p = plan(&repo, "m-Q4_K_M.gguf", Some("mmproj-f16.gguf"), 32768).unwrap(); assert_eq!((p.files.len(), p.total_bytes), (2, 5 * gib)); assert!(p.id.starts_with("hf-") && p.id.len() == 27); let mut tampered = p.clone(); tampered.files[0].bytes += 1; tampered.total_bytes += 1; assert!(validate_plan(&tampered).is_err(), "id is bound to the files"); let shards = info(vec![("x-00001-of-00002.gguf", "gguf", gib), ("x-00002-of-00002.gguf", "gguf", gib)]); assert_eq!(plan(&shards, "x-00001-of-00002.gguf", None, 32768).unwrap().files.len(), 2); let broken = info(vec![("x-00001-of-00003.gguf", "gguf", gib)]); assert!(plan(&broken, "x-00001-of-00003.gguf", None, 32768).is_err()); assert_eq!(choose_file(&shards, &gpu(8.0)).as_deref(), Some("x-00001-of-00002.gguf")); } #[test] fn plan_id_matches_capri_js() { // JSON.stringify({repository, revision, files:[{path, bytes, sha256}]}) hashed in Node. let files = [PlanFile { path: "example-3b.Q4_K_M.gguf".into(), bytes: 2019377440, sha256: "a".repeat(64) }]; let json = format!(r#"{{"repository":"example-org/Example-3B-GGUF","revision":"{REV}","files":[{{"path":"example-3b.Q4_K_M.gguf","bytes":2019377440,"sha256":"{}"}}]}}"#, "a".repeat(64)); assert_eq!(plan_id("example-org/Example-3B-GGUF", REV, &files), format!("hf-{}", &sha(json.as_bytes())[..24])); } #[tokio::test] async fn search_inspect_and_token_scoping() { let server = MockServer::start().await; Mock::given(method("GET")).and(path("/api/models")).and(query_param("filter", "gguf")).and(header("authorization", "Bearer hf_tokentokentokentoken1")) .respond_with(ResponseTemplate::new(200).set_body_json(json!([{"id": "org/A-GGUF", "downloads": 5, "gated": "auto"}, {"id": "bad id"}]))).mount(&server).await; Mock::given(method("GET")).and(path("/api/models/org/A-GGUF/revision/main")) .respond_with(ResponseTemplate::new(200).set_body_json(json!({"sha": REV, "cardData": {"license": "apache-2.0", "language": ["en", "!!"]}, "siblings": [ {"rfilename": "a-Q4_K_M.gguf", "lfs": {"size": 100, "sha256": "b".repeat(64)}}, {"rfilename": "mmproj-a.gguf", "size": 50, "lfs": {"oid": format!("sha256:{}", "c".repeat(64))}}, {"rfilename": "../evil.gguf"}, {"rfilename": "README.md", "size": 3}]}))).mount(&server).await; let hub = Hub::with_base(&server.uri(), Some("hf_tokentokentokentoken1".into())); let rows = hub.search("qwen", 20).await.unwrap(); assert_eq!(rows, vec![SearchRow { repository: "org/A-GGUF".into(), downloads: 5, gated: true, private: false }]); let info = hub.inspect("org/A-GGUF", None).await.unwrap(); assert_eq!(info.files.len(), 3, "unsafe names skipped"); assert_eq!((info.files[1].kind.as_str(), info.files[1].sha256.clone()), ("projector", Some("c".repeat(64)))); assert_eq!((info.license.as_deref(), info.languages.clone()), (Some("apache-2.0"), vec!["en".to_string()])); assert!(hub.get(Url::parse("https://evil.example/x").unwrap(), "*/*", None, Duration::from_secs(1)).await.unwrap_err().to_string().contains("Unapproved")); assert!(hub.inspect("org/missing", None).await.unwrap_err().to_string().contains("not found")); } #[tokio::test] async fn resumable_verified_install_import_and_remove() { let body = gguf(4096); let digest = sha(&body); let server = MockServer::start().await; let full = body.clone(); Mock::given(method("GET")).and(path(format!("/org/m/resolve/{REV}/m.Q4_K_M.gguf"))).respond_with(move |r: &Request| { match r.headers.get("range").and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("bytes=")?.strip_suffix('-')?.parse::().ok()) { Some(offset) => ResponseTemplate::new(206).insert_header("content-range", format!("bytes {offset}-{}/{}", full.len() - 1, full.len())).set_body_bytes(full[offset..].to_vec()), None => ResponseTemplate::new(200).set_body_bytes(full.clone()), } }).mount(&server).await; let dir = tempfile::tempdir().unwrap(); let lib = Library::new(dir.path().to_path_buf()); let info = RepoInfo { repository: "org/m".into(), revision: REV.into(), task: "llm".into(), files: vec![HubFile { path: "m.Q4_K_M.gguf".into(), kind: "gguf".into(), bytes: Some(4096), sha256: Some(digest.clone()), split: false }], ..Default::default() }; let p = plan(&info, "m.Q4_K_M.gguf", None, 32768).unwrap(); // A retained partial download resumes with a Range request. std::fs::create_dir_all(dir.path().join("blobs")).unwrap(); std::fs::write(dir.path().join("blobs").join(format!("{digest}.partial")), &body[..1000]).unwrap(); let hub = Hub::with_base(&server.uri(), Some("hf_tokentokentokentoken1".into())); let mut last = Progress::default(); lib.install(&hub, &p, |pr| last = pr.clone()).await.unwrap(); assert_eq!((last.status, last.completed), ("installed", 4096)); assert_eq!(std::fs::read(dir.path().join("blobs").join(&digest)).unwrap(), body); let get = server.received_requests().await.unwrap(); assert_eq!(get[0].headers.get("range").unwrap(), "bytes=1000-"); assert_eq!(lib.list().len(), 1); // A corrupted body never replaces anything. let bad = PlanFile { path: "m.Q4_K_M.gguf".into(), bytes: 4096, sha256: "d".repeat(64) }; let err = hub.download(&p, &bad, &dir.path().join("other"), |_, _| {}).await.unwrap_err(); assert_eq!(err.to_string(), "Hugging Face checksum verification failed."); assert!(!dir.path().join("other").join("d".repeat(64)).exists()); let ollama = MockServer::start().await; Mock::given(method("POST")).and(path(format!("/api/blobs/sha256:{digest}"))).respond_with(ResponseTemplate::new(201)).mount(&ollama).await; Mock::given(method("POST")).and(path("/api/create")).respond_with(ResponseTemplate::new(200).set_body_string(r#"{"status":"success"}"#)).mount(&ollama).await; Mock::given(method("POST")).and(path("/api/show")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"template": "{{ .Prompt }}", "capabilities": ["completion", "tools"], "model_info": {"general.architecture": "qwen3", "qwen3.context_length": 40960}}))).mount(&ollama).await; Mock::given(method("GET")).and(path("/api/ps")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": []}))).mount(&ollama).await; Mock::given(method("DELETE")).and(path("/api/delete")).respond_with(ResponseTemplate::new(200)).mount(&ollama).await; let client = Ollama::new(ollama.uri()); let profile = lib.import(&client, &p.id).await.unwrap(); assert_eq!((profile.alias.clone(), profile.context_limit, profile.capabilities.clone()), (format!("capri-{}:latest", p.id), 40960, vec!["tools".to_string()])); let create: Value = serde_json::from_slice(&ollama.received_requests().await.unwrap().into_iter().find(|r| r.url.path() == "/api/create").unwrap().body).unwrap(); assert_eq!(create["files"]["m.Q4_K_M.gguf"], format!("sha256:{digest}")); assert_eq!(lib.list()[0].profile.as_ref(), Some(&profile)); assert!(lib.remove(&client, &p.id, &profile.alias).await.is_err(), "active model is kept"); assert_eq!(lib.remove(&client, &p.id, "capri-qwen3.5:4b").await.unwrap(), 4096); assert!(lib.list().is_empty() && !dir.path().join("blobs").join(&digest).exists()); } #[test] fn operation_lock_is_exclusive_and_recovers_stale_owner() { let dir = tempfile::tempdir().unwrap(); let held = OpLock::take(dir.path()).unwrap(); assert!(OpLock::take(dir.path()).is_err()); drop(held); std::fs::write(dir.path().join(".operation.lock"), r#"{"pid":999999999}"#).unwrap(); assert!(OpLock::take(dir.path()).is_ok(), "dead owner"); } }