A high-performance inference engine for AI models
hf
eugenea2ff75c0f8e0
diff --git a/Cargo.lock b/Cargo.lockindex 7c37b3c9c..2667339c0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1791,6 +1791,8 @@ dependencies = ["serde","serde-wasm-bindgen","serde_json",+ "sha1",+ "sha2","tempfile","thiserror 2.0.18","tokio",@@ -7606,6 +7608,7 @@ dependencies = ["uzu-engine","wasm-bindgen","wasm-bindgen-futures",+ "wiremock",][[package]]diff --git a/Cargo.toml b/Cargo.tomlindex 9470e3917..6e0b4fb0e 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -142,6 +142,8 @@ reqwest = { version = "0.13.2", features = ["query",] }crc32c = "0.6.8"+sha1 = "0.10.6"+sha2 = "0.10.9"base64 = "0.22.1"bitflags = "2.11.1"bon = "3.10.0"diff --git a/apps/playground/Sources/Views/ModelListView.swift b/apps/playground/Sources/Views/ModelListView.swiftindex 3458f551f..1674d2229 100644--- a/apps/playground/Sources/Views/ModelListView.swift+++ b/apps/playground/Sources/Views/ModelListView.swift@@ -130,7 +130,7 @@ struct ModelListView: View {guardlet selectedIdentifier,let model = group.modelByIdentifier[selectedIdentifier],- model.isLocal(),+ model.isOnDevice(),let state = engineWrapper.downloadStates[model.identifier]else { return }@@ -349,7 +349,7 @@ struct ModelListView: View {private var selectedModelState: DownloadState? {guard let selectedIdentifier else { return nil }guard let model = models()- .filter({ $0.isLocal() })+ .filter({ $0.isOnDevice() }).first(where: { $0.identifier == selectedIdentifier }) else {return nil}@@ -360,7 +360,7 @@ struct ModelListView: View {private func select(identifier: String) {selectedIdentifier = identifierif let model = models()- .filter({ $0.isLocal() })+ .filter({ $0.isOnDevice() }).first(where: { $0.identifier == selectedIdentifier }),let state = engineWrapper.downloadStates[model.identifier] {selectedModelSection = section(for: state)@@ -490,7 +490,7 @@ struct ModelListView: View {}}let cloud = all.filter { $0.isRemote() }.sorted { $0.name() < $1.name() }- let local = all.filter { $0.isLocal() }+ let local = all.filter { $0.isOnDevice() }let modelByIdentifier = Dictionary(uniqueKeysWithValues: all.map { ($0.identifier, $0) })var bySection: [ModelSection: [String]] = [:]diff --git a/crates/legacy/cli/src/bench/runner.rs b/crates/legacy/cli/src/bench/runner.rsindex ef1b7a9e1..3a15b9b42 100644--- a/crates/legacy/cli/src/bench/runner.rs+++ b/crates/legacy/cli/src/bench/runner.rs@@ -4,7 +4,7 @@ use std::{};use anyhow::{Context, Result};-use shoji::types::model::{ModelFamily, ModelReference};+use shoji::types::model::{ModelFamily, ModelSource};use sysinfo::System;use uzu::{engine::{Engine, EngineConfig},@@ -168,9 +168,9 @@ impl BenchRunner {.to_lowercase();let all_models = engine.models().await?;for model in all_models {- if let ModelAccessibility::Local {- reference:- ModelReference::Mirai {+ if let ModelAccessibility::OnDevice {+ source:+ ModelSource::Registry {toolchain_version: _toolchain_version,repository,source_repository,diff --git a/crates/legacy/cli/src/common/thinking.rs b/crates/legacy/cli/src/common/thinking.rsindex b4520c10a..864f7481a 100644--- a/crates/legacy/cli/src/common/thinking.rs+++ b/crates/legacy/cli/src/common/thinking.rs@@ -204,7 +204,7 @@ impl ThinkingSupport {mod tests {use shoji::types::{basic::Value,- model::{ModelAccessibility, ModelReference, ModelSpecialization},+ model::{ModelAccessibility, ModelSource, ModelSpecialization},};use super::*;@@ -236,8 +236,8 @@ mod tests {"uzu".to_string(),"0.0".to_string(),vec![ModelSpecialization::Chat {}],- ModelAccessibility::Local {- reference: ModelReference::Local {+ ModelAccessibility::OnDevice {+ source: ModelSource::Filesystem {path: "/nonexistent".to_string(),},},diff --git a/crates/legacy/cli/src/interactive/components/application.rs b/crates/legacy/cli/src/interactive/components/application.rsindex 7bea57406..ee704bf19 100644--- a/crates/legacy/cli/src/interactive/components/application.rs+++ b/crates/legacy/cli/src/interactive/components/application.rs@@ -154,7 +154,7 @@ pub fn Application(match engine.model(identifier.clone()).await {Ok(Some(model)) => {let model_exists = model.is_downloadable()- || !model.is_local()+ || !model.is_on_device()|| matches!(engine.model_path(&model).await,Some(path) if std::path::Path::new(&path).exists()diff --git a/crates/legacy/download-manager/Cargo.toml b/crates/legacy/download-manager/Cargo.tomlindex 6313543e9..a78e94347 100644--- a/crates/legacy/download-manager/Cargo.toml+++ b/crates/legacy/download-manager/Cargo.toml@@ -53,6 +53,8 @@ serde_json.workspace = trueasync-trait.workspace = truethiserror.workspace = truecrc32c.workspace = true+sha1.workspace = true+sha2.workspace = truebase64.workspace = truetracing.workspace = truereqwest.workspace = truediff --git a/crates/legacy/download-manager/src/backends/apple/apple_active_task.rs b/crates/legacy/download-manager/src/backends/apple/apple_active_task.rsindex 52cb36acf..b91838d7c 100644--- a/crates/legacy/download-manager/src/backends/apple/apple_active_task.rs+++ b/crates/legacy/download-manager/src/backends/apple/apple_active_task.rs@@ -17,16 +17,19 @@ use crate::backends::{pub struct AppleActiveTask {task: Retained<NSURLSessionDownloadTask>,event_registry: AppleEventRegistry,+ authenticated: bool,}impl AppleActiveTask {pub fn new(task: Retained<NSURLSessionDownloadTask>,event_registry: AppleEventRegistry,+ authenticated: bool,) -> Self {Self {task,event_registry,+ authenticated,}}@@ -41,6 +44,14 @@ impl ActiveTask for AppleActiveTask {self: Box<Self>,resume_artifact_path: &Path,) -> Result<(), BackendError> {+ // The resume blob archives the original and current requests with all their headers, so producing one+ // for an authenticated task would write the bearer token to disk and freeze it into the resumed request.+ // Authenticated downloads therefore start over after a pause or a relaunch on this backend; the universal+ // backend resumes them from the partial file and re-sends the token from memory instead.+ if self.authenticated {+ self.cancel().await;+ return Ok(());+ }self.unregister();let (sender, receiver) = tokio_oneshot_channel::<Vec<u8>>();{diff --git a/crates/legacy/download-manager/src/backends/apple/apple_backend.rs b/crates/legacy/download-manager/src/backends/apple/apple_backend.rsindex dbb0b9c21..a0ec2c2e3 100644--- a/crates/legacy/download-manager/src/backends/apple/apple_backend.rs+++ b/crates/legacy/download-manager/src/backends/apple/apple_backend.rs@@ -8,8 +8,9 @@ use block2::RcBlock;use kiban::{fs, rt::RuntimeHandle};use objc2::{rc::Retained, runtime::ProtocolObject};use objc2_foundation::{- NSArray, NSBundle, NSData, NSString, NSURL, NSURLSession, NSURLSessionConfiguration, NSURLSessionDataTask,- NSURLSessionDelegate, NSURLSessionDownloadTask, NSURLSessionTaskState, NSURLSessionUploadTask,+ NSArray, NSBundle, NSData, NSMutableURLRequest, NSString, NSURL, NSURLSession, NSURLSessionConfiguration,+ NSURLSessionDataTask, NSURLSessionDelegate, NSURLSessionDownloadTask, NSURLSessionTaskState,+ NSURLSessionUploadTask,};use tokio::sync::{OnceCell as TokioOnceCell, oneshot::channel as tokio_oneshot_channel};@@ -112,12 +113,13 @@ impl AppleBackend {AppleEventSink {generation,destination: config.destination.clone(),+ expected_bytes: config.expected_bytes,events,runtime_handle: self.runtime_handle.clone(),},);task.resume();- Box::new(AppleActiveTask::new(task, Arc::clone(&self.event_registry)))+ Box::new(AppleActiveTask::new(task, Arc::clone(&self.event_registry), config.bearer_token.is_some()))}fn is_live(task: &NSURLSessionDownloadTask) -> bool {@@ -145,7 +147,18 @@ impl Backend for AppleBackend {let task = if resume_data.is_empty() {let url = NSURL::URLWithString(&NSString::from_str(&config.source_url)).ok_or_else(|| AppleBackendError::InvalidUrl(config.source_url.clone()))?;- self.session.downloadTaskWithURL(&url)+ let request = NSMutableURLRequest::requestWithURL(&url);+ request.setValue_forHTTPHeaderField(+ Some(&NSString::from_str("identity")),+ &NSString::from_str("Accept-Encoding"),+ );+ if let Some(token) = &config.bearer_token {+ request.setValue_forHTTPHeaderField(+ Some(&NSString::from_str(&token.header_value())),+ &NSString::from_str("Authorization"),+ );+ }+ self.session.downloadTaskWithRequest(&request)} else {self.session.downloadTaskWithResumeData(&NSData::with_bytes(&resume_data))};@@ -194,7 +207,7 @@ impl Backend for AppleBackend {&& AppleTaskDescription::of(&task).is_some_and(|description| {description.download_id == config.download_id&& description.source_url == config.source_url- && description.crc32c == config.expected_crc32c+ && description.checksum == config.expected_checksum}){attached = Some(self.activate(task, &config, generation, events.clone()));diff --git a/crates/legacy/download-manager/src/backends/apple/apple_event_sink.rs b/crates/legacy/download-manager/src/backends/apple/apple_event_sink.rsindex 7c5bed6b4..d13879bfd 100644--- a/crates/legacy/download-manager/src/backends/apple/apple_event_sink.rs+++ b/crates/legacy/download-manager/src/backends/apple/apple_event_sink.rs@@ -8,6 +8,7 @@ use crate::backends::{BackendEventSender, DownloadGeneration};pub struct AppleEventSink {pub generation: DownloadGeneration,pub destination: PathBuf,+ pub expected_bytes: Option<u64>,pub events: BackendEventSender,pub runtime_handle: RuntimeHandle,}diff --git a/crates/legacy/download-manager/src/backends/apple/apple_session_delegate.rs b/crates/legacy/download-manager/src/backends/apple/apple_session_delegate.rsindex a8e382ad7..6c53e8ba3 100644--- a/crates/legacy/download-manager/src/backends/apple/apple_session_delegate.rs+++ b/crates/legacy/download-manager/src/backends/apple/apple_session_delegate.rs@@ -5,8 +5,8 @@ use objc2::{rc::{Allocated, Retained},};use objc2_foundation::{- NSError, NSObject, NSObjectProtocol, NSURL, NSURLSession, NSURLSessionDelegate, NSURLSessionDownloadDelegate,- NSURLSessionDownloadTask, NSURLSessionTask, NSURLSessionTaskDelegate,+ NSError, NSHTTPURLResponse, NSObject, NSObjectProtocol, NSURL, NSURLSession, NSURLSessionDelegate,+ NSURLSessionDownloadDelegate, NSURLSessionDownloadTask, NSURLSessionTask, NSURLSessionTaskDelegate,};use crate::backends::{@@ -71,6 +71,23 @@ define_class!(else {return;};+ let status = download_task+ .response()+ .and_then(|response| response.downcast::<NSHTTPURLResponse>().ok())+ .map(|response| response.statusCode());+ if let Some(status) = status+ && !(200..300).contains(&status)+ {+ sink.runtime_handle.clone().spawn(async move {+ sink.events+ .send_terminal(BackendEvent::Error {+ generation: sink.generation,+ message: format!("download failed with HTTP status {status}"),+ })+ .await;+ });+ return;+ }let Some(temporary_path) = location.path().map(|path| PathBuf::from(path.to_string())) else {return;};@@ -115,6 +132,25 @@ define_class!(return;};let downloaded_bytes = cumulative_bytes_written.max(0) as u64;+ if let Some(expected_bytes) = sink.expected_bytes+ && downloaded_bytes > expected_bytes+ {+ download_task.cancel();+ Self::ivars(self)+ .event_registry+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .remove(&download_task.taskIdentifier());+ sink.runtime_handle.clone().spawn(async move {+ sink.events+ .send_terminal(BackendEvent::Error {+ generation: sink.generation,+ message: format!("response exceeded the declared size of {expected_bytes} bytes"),+ })+ .await;+ });+ return;+ }let total_bytes = (total_expected_bytes_to_write > 0).then_some(total_expected_bytes_to_write as u64);sink.events.send_progress(sink.generation, downloaded_bytes, total_bytes);}diff --git a/crates/legacy/download-manager/src/backends/apple/apple_task_description.rs b/crates/legacy/download-manager/src/backends/apple/apple_task_description.rsindex b0d29cb52..0686cbed5 100644--- a/crates/legacy/download-manager/src/backends/apple/apple_task_description.rs+++ b/crates/legacy/download-manager/src/backends/apple/apple_task_description.rs@@ -1,7 +1,7 @@use objc2_foundation::NSURLSessionDownloadTask;use serde::{Deserialize, Serialize};-use crate::{Crc32c, DownloadId, file_download::DownloadConfig};+use crate::{Checksum, DownloadId, file_download::DownloadConfig};#[derive(Serialize, Deserialize, Debug)]pub struct AppleTaskDescription {@@ -9,7 +9,7 @@ pub struct AppleTaskDescription {pub download_id: DownloadId,pub source_url: String,#[serde(default)]- pub crc32c: Option<Crc32c>,+ pub checksum: Option<Checksum>,}impl From<&DownloadConfig> for AppleTaskDescription {@@ -17,7 +17,7 @@ impl From<&DownloadConfig> for AppleTaskDescription {Self {download_id: config.download_id,source_url: config.source_url.clone(),- crc32c: config.expected_crc32c.clone(),+ checksum: config.expected_checksum.clone(),}}}diff --git a/crates/legacy/download-manager/src/backends/backend.rs b/crates/legacy/download-manager/src/backends/backend.rsindex 8a031b4d9..69fcb29fe 100644--- a/crates/legacy/download-manager/src/backends/backend.rs+++ b/crates/legacy/download-manager/src/backends/backend.rs@@ -8,7 +8,7 @@ use kiban::fs;use crate::{DownloadPhase, DownloadState,backends::{ActiveTask, BackendError, BackendEventSender, DownloadGeneration, VerifyError},- crc_receipt::CrcReceipt,+ checksum_receipt::ChecksumReceipt,file_download::DownloadConfig,locks::{DestinationLock, LockError},};@@ -57,7 +57,7 @@ pub trait Backend: Send + Sync {) -> Result<(DownloadState, Option<DestinationLock>), BackendError> {let untouched = !fs::asyn::is_file(&config.destination).await&& !fs::asyn::is_file(&config.resume_artifact_path).await- && !CrcReceipt::exists(&config.destination).await+ && !ChecksumReceipt::exists(&config.destination).await&& DestinationLock::foreign_owner(&config.destination, &config.owner).await.is_none();let pending_task = self.has_pending_task(config).await?;if untouched && !pending_task {@@ -95,7 +95,7 @@ pub trait Backend: Send + Sync {let _ = fs::asyn::remove_file(&config.resume_artifact_path).await;} else {let _ = fs::asyn::remove_file(&config.destination).await;- CrcReceipt::remove(&config.destination).await;+ ChecksumReceipt::remove(&config.destination).await;}}let (phase, downloaded_bytes, total_bytes) = match (downloaded, resume_bytes, foreign_owner) {@@ -126,16 +126,16 @@ pub trait Backend: Send + Sync {actual,});}- let Some(crc) = &config.expected_crc32c else {+ let Some(checksum) = &config.expected_checksum else {return Ok(actual);};- if CrcReceipt::matches(&config.destination, crc).await {+ if ChecksumReceipt::matches(&config.destination, checksum).await {return Ok(actual);}- if !crc.verify(&config.destination).await? {- return Err(VerifyError::Crc);+ if !checksum.verify(&config.destination).await? {+ return Err(VerifyError::Checksum(checksum.algorithm()));}- let _ = CrcReceipt::save(&config.destination, crc).await;+ let _ = ChecksumReceipt::save(&config.destination, checksum).await;Ok(actual)}@@ -145,6 +145,6 @@ pub trait Backend: Send + Sync {) {let _ = fs::asyn::remove_file(&config.resume_artifact_path).await;let _ = fs::asyn::remove_file(&config.destination).await;- CrcReceipt::remove(&config.destination).await;+ ChecksumReceipt::remove(&config.destination).await;}}diff --git a/crates/legacy/download-manager/src/backends/universal/universal_stream.rs b/crates/legacy/download-manager/src/backends/universal/universal_stream.rsindex 5422e6532..d334a4dc6 100644--- a/crates/legacy/download-manager/src/backends/universal/universal_stream.rs+++ b/crates/legacy/download-manager/src/backends/universal/universal_stream.rs@@ -4,7 +4,7 @@ use futures_util::StreamExt;use kiban::{fs, fs::PartFile, time::Instant};use reqwest::{Client, StatusCode,- header::{CONTENT_LENGTH, CONTENT_RANGE, RANGE},+ header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_RANGE, RANGE},};use tokio::sync::{oneshot::Sender as TokioOneshotSender, watch::Receiver as TokioWatchReceiver};@@ -85,6 +85,9 @@ impl UniversalStream {let artifact = config.resume_artifact_path.as_path();let mut resume_from = fs::asyn::file_length(artifact).await.unwrap_or(0);let mut request = self.client.get(&config.source_url);+ if let Some(token) = &config.bearer_token {+ request = request.header(AUTHORIZATION, token.header_value());+ }if resume_from > 0 {request = request.header(RANGE, format!("bytes={resume_from}-"));}@@ -151,8 +154,15 @@ impl UniversalStream {break;};let chunk = chunk?;- file.write_all(&chunk).await?;downloaded_bytes += chunk.len() as u64;+ if let Some(expected_bytes) = config.expected_bytes+ && downloaded_bytes > expected_bytes+ {+ return Err(UniversalBackendError::Protocol(format!(+ "response exceeded the declared size of {expected_bytes} bytes"+ )));+ }+ file.write_all(&chunk).await?;if last_progress.elapsed() >= PROGRESS_INTERVAL {self.events.send_progress(self.generation, downloaded_bytes, total_bytes);last_progress = Instant::now();diff --git a/crates/legacy/download-manager/src/backends/verify_error.rs b/crates/legacy/download-manager/src/backends/verify_error.rsindex 4ef38fe67..9058b6c78 100644--- a/crates/legacy/download-manager/src/backends/verify_error.rs+++ b/crates/legacy/download-manager/src/backends/verify_error.rs@@ -7,6 +7,6 @@ pub enum VerifyError {expected: u64,actual: u64,},- #[error("CRC verification failed")]- Crc,+ #[error("{0} verification failed")]+ Checksum(&'static str),}diff --git a/crates/legacy/download-manager/src/bearer_token.rs b/crates/legacy/download-manager/src/bearer_token.rsnew file mode 100644index 000000000..daad4aebe--- /dev/null+++ b/crates/legacy/download-manager/src/bearer_token.rs@@ -0,0 +1,25 @@+use std::fmt::{Debug, Formatter, Result as FmtResult};++#[derive(Clone, PartialEq, Eq, Hash)]+pub struct BearerToken(String);++impl BearerToken {+ pub fn header_value(&self) -> String {+ format!("Bearer {}", self.0)+ }+}++impl From<String> for BearerToken {+ fn from(token: String) -> Self {+ Self(token)+ }+}++impl Debug for BearerToken {+ fn fmt(+ &self,+ formatter: &mut Formatter<'_>,+ ) -> FmtResult {+ formatter.write_str("BearerToken(<redacted>)")+ }+}diff --git a/crates/legacy/download-manager/src/cached_download_task.rs b/crates/legacy/download-manager/src/cached_download_task.rsdeleted file mode 100644index e88a08168..000000000--- a/crates/legacy/download-manager/src/cached_download_task.rs+++ /dev/null@@ -1,10 +0,0 @@-use std::sync::Weak;--use tokio::sync::watch::Receiver as TokioWatchReceiver;--use crate::{DownloadState, DownloadTask};--pub struct CachedDownloadTask {- pub task: Weak<DownloadTask>,- pub live_state: Option<TokioWatchReceiver<DownloadState>>,-}diff --git a/crates/legacy/download-manager/src/checksum.rs b/crates/legacy/download-manager/src/checksum.rsnew file mode 100644index 000000000..818dd2a56--- /dev/null+++ b/crates/legacy/download-manager/src/checksum.rs@@ -0,0 +1,86 @@+use std::{+ io::{Error as IoError, ErrorKind},+ path::Path,+};++use base64::Engine;+use kiban::fs;+use serde::{Deserialize, Serialize};+use sha1::Sha1;+use sha2::{Digest, Sha256};++const READ_CHUNK_SIZE: u64 = 8 * 1024 * 1024;++#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum Checksum {+ Crc32c(String),+ Sha256(String),+ GitBlobSha1(String),+}++impl Checksum {+ pub fn algorithm(&self) -> &'static str {+ match self {+ Self::Crc32c(_) => "CRC32C",+ Self::Sha256(_) => "SHA-256",+ Self::GitBlobSha1(_) => "Git blob SHA-1",+ }+ }++ pub async fn verify(+ &self,+ path: &Path,+ ) -> Result<bool, IoError> {+ let length = fs::asyn::file_length(path).await?;+ match self {+ Self::Crc32c(expected) => {+ let Some(expected) = base64::engine::general_purpose::STANDARD+ .decode(expected)+ .ok()+ .and_then(|bytes| Some(u32::from_be_bytes(bytes.try_into().ok()?)))+ else {+ return Ok(false);+ };+ let actual = fold_chunks(path, length, 0_u32, |checksum, chunk| {+ *checksum = ::crc32c::crc32c_append(*checksum, chunk)+ })+ .await?;+ Ok(actual == expected)+ },+ Self::Sha256(expected) => {+ let digest =+ fold_chunks(path, length, Sha256::new(), |hasher, chunk| hasher.update(chunk)).await?.finalize();+ Ok(hex(&digest) == expected.to_ascii_lowercase())+ },+ Self::GitBlobSha1(expected) => {+ let mut hasher = Sha1::new();+ hasher.update(format!("blob {length}\0"));+ let digest = fold_chunks(path, length, hasher, |hasher, chunk| hasher.update(chunk)).await?.finalize();+ Ok(hex(&digest) == expected.to_ascii_lowercase())+ },+ }+ }+}++async fn fold_chunks<S>(+ path: &Path,+ length: u64,+ mut state: S,+ mut update: impl FnMut(&mut S, &[u8]),+) -> Result<S, IoError> {+ let mut offset = 0_u64;+ while offset < length {+ let end = offset.saturating_add(READ_CHUNK_SIZE).min(length);+ let chunk = fs::asyn::read_range(path, offset..end).await?;+ if chunk.len() as u64 != end - offset {+ return Err(IoError::new(ErrorKind::UnexpectedEof, "file changed during checksum verification"));+ }+ update(&mut state, &chunk);+ offset = end;+ }+ Ok(state)+}++fn hex(bytes: &[u8]) -> String {+ bytes.iter().map(|byte| format!("{byte:02x}")).collect()+}diff --git a/crates/legacy/download-manager/src/crc_receipt.rs b/crates/legacy/download-manager/src/checksum_receipt.rssimilarity index 79%rename from crates/legacy/download-manager/src/crc_receipt.rsrename to crates/legacy/download-manager/src/checksum_receipt.rsindex 1f2ac377d..3f002c1f5 100644--- a/crates/legacy/download-manager/src/crc_receipt.rs+++ b/crates/legacy/download-manager/src/checksum_receipt.rs@@ -6,33 +6,33 @@ use std::{use kiban::{fs, time::SystemTime};use serde::{Deserialize, Serialize};-use crate::Crc32c;+use crate::Checksum;#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]-pub struct CrcReceipt {+pub struct ChecksumReceipt {version: u8,- crc: Crc32c,+ checksum: Checksum,file_size: u64,modified_unix_seconds: u64,modified_nanos: u32,}-impl CrcReceipt {+impl ChecksumReceipt {pub async fn matches(destination: &Path,- crc: &Crc32c,+ checksum: &Checksum,) -> bool {matches!(- (Self::load(destination).await, Self::for_file(destination, crc).await),+ (Self::load(destination).await, Self::for_file(destination, checksum).await),(Some(saved), Some(current)) if saved == current)}pub async fn save(destination: &Path,- crc: &Crc32c,+ checksum: &Checksum,) -> Result<(), io::Error> {- let Some(receipt) = Self::for_file(destination, crc).await else {+ let Some(receipt) = Self::for_file(destination, checksum).await else {return Ok(());};fs::asyn::write(Self::path_for(destination), serde_json::to_vec(&receipt).map_err(io::Error::other)?).await@@ -52,13 +52,13 @@ impl CrcReceipt {async fn for_file(destination: &Path,- crc: &Crc32c,+ checksum: &Checksum,) -> Option<Self> {let file_size = fs::asyn::file_length(destination).await.ok()?;let modified = fs::asyn::file_modified(destination).await.ok()?.duration_since(SystemTime::UNIX_EPOCH).ok()?;Some(Self {- version: 1,- crc: crc.clone(),+ version: 2,+ checksum: checksum.clone(),file_size,modified_unix_seconds: modified.as_secs(),modified_nanos: modified.subsec_nanos(),@@ -66,6 +66,6 @@ impl CrcReceipt {}fn path_for(destination: &Path) -> PathBuf {- PathBuf::from(format!("{}.crc", destination.display()))+ PathBuf::from(format!("{}.checksum", destination.display()))}}diff --git a/crates/legacy/download-manager/src/crc32c.rs b/crates/legacy/download-manager/src/crc32c.rsdeleted file mode 100644index 2ae831586..000000000--- a/crates/legacy/download-manager/src/crc32c.rs+++ /dev/null@@ -1,49 +0,0 @@-use std::{- io::{Error as IoError, ErrorKind},- path::Path,-};--use base64::Engine;-use kiban::fs;-use serde::{Deserialize, Serialize};--const READ_CHUNK_SIZE: u64 = 8 * 1024 * 1024;--#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(transparent)]-pub struct Crc32c(String);--impl From<String> for Crc32c {- fn from(encoded: String) -> Self {- Self(encoded)- }-}--impl Crc32c {- pub async fn verify(- &self,- path: &Path,- ) -> Result<bool, IoError> {- let Some(expected) = self.decode() else {- return Ok(false);- };- let length = fs::asyn::file_length(path).await?;- let mut checksum = 0_u32;- let mut offset = 0_u64;- while offset < length {- let end = offset.saturating_add(READ_CHUNK_SIZE).min(length);- let chunk = fs::asyn::read_range(path, offset..end).await?;- if chunk.len() as u64 != end - offset {- return Err(IoError::new(ErrorKind::UnexpectedEof, "file changed during CRC verification"));- }- checksum = ::crc32c::crc32c_append(checksum, &chunk);- offset = end;- }- Ok(checksum == expected)- }-- fn decode(&self) -> Option<u32> {- let bytes = base64::engine::general_purpose::STANDARD.decode(&self.0).ok()?;- Some(u32::from_be_bytes(bytes.try_into().ok()?))- }-}diff --git a/crates/legacy/download-manager/src/download_error.rs b/crates/legacy/download-manager/src/download_error.rsindex 00b636a75..29c8d80d5 100644--- a/crates/legacy/download-manager/src/download_error.rs+++ b/crates/legacy/download-manager/src/download_error.rs@@ -10,4 +10,6 @@ pub enum DownloadError {FileDownload(#[from] FileDownloadError),#[error("conflicting download config for destination: {0}")]ConflictingConfig(String),+ #[error("bearer token requires https: {0}")]+ InsecureRequest(String),}diff --git a/crates/legacy/download-manager/src/download_manager.rs b/crates/legacy/download-manager/src/download_manager.rsindex f3af154d7..18d264f26 100644--- a/crates/legacy/download-manager/src/download_manager.rs+++ b/crates/legacy/download-manager/src/download_manager.rs@@ -1,17 +1,18 @@use std::{collections::HashMap,- sync::{Arc, Mutex, PoisonError},+ net::IpAddr,+ sync::{Arc, Mutex, PoisonError, Weak},};use kiban::rt::RuntimeHandle;-use tokio::sync::Mutex as TokioMutex;+use reqwest::Url;+use tokio::sync::{Mutex as TokioMutex, watch::Receiver as TokioWatchReceiver};use uuid::Uuid;use crate::{- DownloadError, DownloadId, DownloadManagerType, DownloadTask, DownloadTaskKind, DownloadTaskRequest,+ DownloadError, DownloadId, DownloadManagerType, DownloadState, DownloadTask, DownloadTaskKind, DownloadTaskRequest,GroupDownloadTask,backends::{Backend, UniversalBackend},- cached_download_task::CachedDownloadTask,file_download::{DownloadConfig, FileDownloadWorker},locks::LockOwner,};@@ -19,7 +20,8 @@ use crate::{pub struct DownloadManager {owner: LockOwner,backend: Arc<dyn Backend>,- tasks: Mutex<HashMap<DownloadId, CachedDownloadTask>>,+ tasks: Mutex<HashMap<DownloadId, Weak<DownloadTask>>>,+ live_states: Mutex<HashMap<DownloadId, TokioWatchReceiver<DownloadState>>>,construction_locks: Mutex<HashMap<DownloadId, Arc<TokioMutex<()>>>>,}@@ -50,6 +52,7 @@ impl DownloadManager {},backend,tasks: Mutex::default(),+ live_states: Mutex::default(),construction_locks: Mutex::default(),}}@@ -84,33 +87,20 @@ impl DownloadManager {if let Some(cached) = self.cached(download_id, &request) {return cached;}- let stopping = self- .tasks- .lock()- .unwrap_or_else(PoisonError::into_inner)- .get(&download_id)- .and_then(|cached| cached.live_state.clone());+ let stopping = self.live_states.lock().unwrap_or_else(PoisonError::into_inner).get(&download_id).cloned();if let Some(mut live_state) = stopping {while live_state.changed().await.is_ok() {}}let task = Arc::new(self.build(&request, ancestors).await?);- let live_state = match &*task {- DownloadTask::File(file) => Some(file.live_state()),- DownloadTask::Group(_) => None,- };{let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);- tasks.retain(|_, cached| {- cached.task.strong_count() > 0- || cached.live_state.as_ref().is_some_and(|live_state| live_state.has_changed().is_ok())- });- tasks.insert(- download_id,- CachedDownloadTask {- task: Arc::downgrade(&task),- live_state,- },- );+ tasks.retain(|_, task| task.strong_count() > 0);+ tasks.insert(download_id, Arc::downgrade(&task));+ }+ if let DownloadTask::File(file) = &*task {+ let mut live_states = self.live_states.lock().unwrap_or_else(PoisonError::into_inner);+ live_states.retain(|_, live_state| live_state.has_changed().is_ok());+ live_states.insert(download_id, file.live_state());}self.construction_locks.lock()@@ -124,7 +114,7 @@ impl DownloadManager {download_id: DownloadId,request: &DownloadTaskRequest,) -> Option<Result<Arc<DownloadTask>, DownloadError>> {- let task = self.tasks.lock().unwrap_or_else(PoisonError::into_inner).get(&download_id)?.task.upgrade()?;+ let task = self.tasks.lock().unwrap_or_else(PoisonError::into_inner).get(&download_id)?.upgrade()?;Some(if task.request() == request {Ok(task)} else {@@ -140,15 +130,20 @@ impl DownloadManager {match &request.kind {DownloadTaskKind::File {source_url,- expected_crc32c,+ bearer_token,+ expected_checksum,expected_bytes,} => {+ if bearer_token.is_some() && !carries_token_securely(source_url) {+ return Err(DownloadError::InsecureRequest(source_url.clone()));+ }let config = Arc::new(DownloadConfig {download_id: request.download_id(),source_url: source_url.clone(),+ bearer_token: bearer_token.clone(),destination: request.destination.clone(),resume_artifact_path: self.backend.resume_artifact_path(&request.destination),- expected_crc32c: expected_crc32c.clone(),+ expected_checksum: expected_checksum.clone(),expected_bytes: *expected_bytes,owner: self.owner.clone(),});@@ -174,3 +169,13 @@ impl DownloadManager {}}}++fn carries_token_securely(source_url: &str) -> bool {+ Url::parse(source_url).is_ok_and(|url| {+ url.scheme() == "https"+ || url.host_str().is_some_and(|host| {+ host.eq_ignore_ascii_case("localhost")+ || host.trim_matches(['[', ']']).parse::<IpAddr>().is_ok_and(|address| address.is_loopback())+ })+ })+}diff --git a/crates/legacy/download-manager/src/download_manager_type.rs b/crates/legacy/download-manager/src/download_manager_type.rsindex 4b5f62955..c06ffc5c1 100644--- a/crates/legacy/download-manager/src/download_manager_type.rs+++ b/crates/legacy/download-manager/src/download_manager_type.rs@@ -4,6 +4,8 @@ use serde::{Deserialize, Serialize};#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum DownloadManagerType {+ // NSURLSession. Downloads that carry a bearer token cannot resume here: pausing or quitting discards their+ // progress, see `AppleActiveTask::pause`.#[cfg(target_vendor = "apple")]#[default]Native,diff --git a/crates/legacy/download-manager/src/download_task_kind.rs b/crates/legacy/download-manager/src/download_task_kind.rsindex 3176b89d3..528e41d71 100644--- a/crates/legacy/download-manager/src/download_task_kind.rs+++ b/crates/legacy/download-manager/src/download_task_kind.rs@@ -1,10 +1,11 @@-use crate::{Crc32c, DownloadTaskRequest};+use crate::{BearerToken, Checksum, DownloadTaskRequest};#[derive(Clone, Debug, PartialEq, Eq)]pub enum DownloadTaskKind {File {source_url: String,- expected_crc32c: Option<Crc32c>,+ bearer_token: Option<BearerToken>,+ expected_checksum: Option<Checksum>,expected_bytes: Option<u64>,},Group(Vec<DownloadTaskRequest>),diff --git a/crates/legacy/download-manager/src/download_task_request.rs b/crates/legacy/download-manager/src/download_task_request.rsindex 8434b9a52..efa5588d1 100644--- a/crates/legacy/download-manager/src/download_task_request.rs+++ b/crates/legacy/download-manager/src/download_task_request.rs@@ -3,7 +3,7 @@ use std::path::{Path, PathBuf};use bon::bon;use uuid::Uuid;-use crate::{Crc32c, DownloadId, DownloadTaskKind};+use crate::{BearerToken, Checksum, DownloadId, DownloadTaskKind};#[derive(Clone, Debug, PartialEq, Eq)]pub struct DownloadTaskRequest {@@ -17,14 +17,16 @@ impl DownloadTaskRequest {pub fn file(#[builder(into)] destination: PathBuf,#[builder(into)] source_url: String,- #[builder(into)] expected_crc32c: Option<Crc32c>,+ #[builder(into)] bearer_token: Option<BearerToken>,+ expected_checksum: Option<Checksum>,expected_bytes: Option<u64>,) -> Self {Self {destination,kind: DownloadTaskKind::File {source_url,- expected_crc32c,+ bearer_token,+ expected_checksum,expected_bytes,},}diff --git a/crates/legacy/download-manager/src/file_download/download_config.rs b/crates/legacy/download-manager/src/file_download/download_config.rsindex 157d715e7..52785e229 100644--- a/crates/legacy/download-manager/src/file_download/download_config.rs+++ b/crates/legacy/download-manager/src/file_download/download_config.rs@@ -1,13 +1,14 @@use std::path::PathBuf;-use crate::{Crc32c, DownloadId, locks::LockOwner};+use crate::{BearerToken, Checksum, DownloadId, locks::LockOwner};pub struct DownloadConfig {pub download_id: DownloadId,pub source_url: String,+ pub bearer_token: Option<BearerToken>,pub destination: PathBuf,pub resume_artifact_path: PathBuf,- pub expected_crc32c: Option<Crc32c>,+ pub expected_checksum: Option<Checksum>,pub expected_bytes: Option<u64>,pub owner: LockOwner,}diff --git a/crates/legacy/download-manager/src/lib.rs b/crates/legacy/download-manager/src/lib.rsindex 012a07fdf..3e7b03d92 100644--- a/crates/legacy/download-manager/src/lib.rs+++ b/crates/legacy/download-manager/src/lib.rs@@ -2,9 +2,9 @@uniffi::setup_scaffolding!();mod backends;-mod cached_download_task;-mod crc32c;-mod crc_receipt;+mod bearer_token;+mod checksum;+mod checksum_receipt;mod download_error;mod download_id;mod download_manager;@@ -21,7 +21,8 @@ mod locks;#[cfg(target_vendor = "apple")]pub use backends::AppleBackendError;pub use backends::BackendError;-pub use crc32c::Crc32c;+pub use bearer_token::BearerToken;+pub use checksum::Checksum;pub use download_error::DownloadError;pub use download_id::DownloadId;pub use download_manager::DownloadManager;diff --git a/crates/legacy/download-manager/tests/common/helpers.rs b/crates/legacy/download-manager/tests/common/helpers.rsindex e4301ad4d..8142980d3 100644--- a/crates/legacy/download-manager/tests/common/helpers.rs+++ b/crates/legacy/download-manager/tests/common/helpers.rs@@ -1,6 +1,6 @@use std::{path::Path, time::Duration};-use download_manager::{DestinationLock, DownloadState, DownloadTask, DownloadTaskRequest, LockOwner};+use download_manager::{Checksum, DestinationLock, DownloadState, DownloadTask, DownloadTaskRequest, LockOwner};use kiban::stream::BoxStream;use mock_registry::MockRegistry;use tokio::time::timeout;@@ -16,7 +16,7 @@ pub fn file_request(DownloadTaskRequest::file().destination(destination).source_url(source_url)- .maybe_expected_crc32c(expected_crc32c)+ .maybe_expected_checksum(expected_crc32c.map(Checksum::Crc32c)).maybe_expected_bytes(expected_bytes).build()}@@ -31,7 +31,7 @@ pub fn model_request(DownloadTaskRequest::file().destination(&served.file.name).source_url(&served.file.url)- .expected_crc32c(served.crc32c()?)+ .expected_checksum(Checksum::Crc32c(served.crc32c()?)).expected_bytes(served.file.size as u64).build(),);diff --git a/crates/legacy/download-manager/tests/download_manager.rs b/crates/legacy/download-manager/tests/download_manager.rsindex e0e80a97d..8ce80106f 100644--- a/crates/legacy/download-manager/tests/download_manager.rs+++ b/crates/legacy/download-manager/tests/download_manager.rs@@ -3,8 +3,8 @@ mod common;use std::{path::Path, sync::Arc, time::Duration};use download_manager::{- DestinationLock, DownloadError, DownloadManager, DownloadManagerType, DownloadPhase, DownloadState, DownloadTask,- DownloadTaskRequest, LockError, LockOwner,+ Checksum, DestinationLock, DownloadError, DownloadManager, DownloadManagerType, DownloadPhase, DownloadState,+ DownloadTask, DownloadTaskRequest, LockError, LockOwner,};use kiban::rt::RuntimeHandle;use rstest::rstest;@@ -12,11 +12,15 @@ use tokio::time::timeout;use uuid::Uuid;use wiremock::{Mock, MockServer, ResponseTemplate,- matchers::{method, path},+ matchers::{header, method, path},};use crate::common::{Behavior, MockRegistry, artifact_path, file_request, foreign_lock, model_request, wait_for_state};+const HELLO: &[u8] = b"hello\n";+const HELLO_SHA256: &str = "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";+const HELLO_GIT_BLOB_SHA1: &str = "ce013625030ba8dba906f756967f9e9ca394464a";+fn manager(kind: DownloadManagerType) -> DownloadManager {DownloadManager::new(kind, RuntimeHandle::current())}@@ -89,7 +93,7 @@ async fn model_lifecycle(#[case] kind: DownloadManagerType) -> Result<(), Box<dyfor served in registry.files.iter() {let destination = directory.path().join(&served.file.name);assert_eq!(tokio::fs::read(&destination).await?, served.bytes.to_vec());- assert!(artifact_path(&destination, "crc").is_file());+ assert!(artifact_path(&destination, "checksum").is_file());}model.delete().await?;@@ -98,7 +102,7 @@ async fn model_lifecycle(#[case] kind: DownloadManagerType) -> Result<(), Box<dyfor served in registry.files.iter() {let destination = directory.path().join(&served.file.name);assert!(!destination.exists());- assert!(!artifact_path(&destination, "crc").exists());+ assert!(!artifact_path(&destination, "checksum").exists());assert!(!artifact_path(&destination, "lock").exists());}@@ -141,16 +145,16 @@ async fn startup_reconciliation(assert_eq!(task.state().phase, DownloadPhase::Downloaded {});assert!(!artifact.exists());let receipt: serde_json::Value =- serde_json::from_str(&tokio::fs::read_to_string(artifact_path(&destination, "crc")).await?)?;- assert_eq!(receipt["version"].as_u64(), Some(1));- assert_eq!(receipt["crc"].as_str(), Some(crc.as_str()));+ serde_json::from_str(&tokio::fs::read_to_string(artifact_path(&destination, "checksum")).await?)?;+ assert_eq!(receipt["version"].as_u64(), Some(2));+ assert_eq!(receipt["checksum"]["Crc32c"].as_str(), Some(crc.as_str()));assert_eq!(receipt["file_size"].as_u64(), size);let mut changed_bytes = served.bytes.to_vec();changed_bytes[0] = changed_bytes[0].wrapping_add(1);let stale_receipt = serde_json::to_vec(&serde_json::json!({- "version": 1,- "crc": crc.clone(),+ "version": 2,+ "checksum": { "Crc32c": crc.clone() },"file_size": served.file.size,"modified_unix_seconds": 0,"modified_nanos": 0,@@ -159,7 +163,7 @@ async fn startup_reconciliation(let stale = tempfile::tempdir()?;let destination = stale.path().join(&served.file.name);tokio::fs::write(&destination, &changed_bytes).await?;- tokio::fs::write(artifact_path(&destination, "crc"), cache).await?;+ tokio::fs::write(artifact_path(&destination, "checksum"), cache).await?;let task = manager.download_task(request(&destination)).await?;assert_eq!(task.state().phase, DownloadPhase::NotDownloaded {});assert!(!destination.exists());@@ -175,7 +179,7 @@ async fn startup_reconciliation(let destination = locked.path().join(&served.file.name);let artifact = artifact_path(&destination, resume_artifact_extension);tokio::fs::write(&destination, b"corrupt").await?;- tokio::fs::write(artifact_path(&destination, "crc"), &crc).await?;+ tokio::fs::write(artifact_path(&destination, "checksum"), &crc).await?;tokio::fs::write(&artifact, b"partial").await?;let lock = foreign_lock(&destination).await;let group = manager@@ -194,7 +198,7 @@ async fn startup_reconciliation(assert!(matches!(group.state().phase, DownloadPhase::Locked { .. }));assert!(matches!(group.delete().await, Err(DownloadError::Lock(LockError::LockedByOther { .. }))));assert!(destination.exists());- assert!(artifact_path(&destination, "crc").exists());+ assert!(artifact_path(&destination, "checksum").exists());assert!(artifact.exists());let mut progress = group.progress();if kind == DownloadManagerType::Universal {@@ -436,3 +440,104 @@ async fn ancestor_destination_rejected(#[case] kind: DownloadManagerType) -> Resassert!(matches!(result, Err(DownloadError::ConflictingConfig(_))));Ok(())}++#[rstest]+#[case::universal(DownloadManagerType::Universal)]+#[cfg_attr(target_vendor = "apple", case::native(DownloadManagerType::Native))]+#[tokio::test(flavor = "multi_thread")]+async fn checksums(#[case] kind: DownloadManagerType) -> Result<(), Box<dyn std::error::Error>> {+ let manager = manager(kind);+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/hello"))+ .respond_with(ResponseTemplate::new(200).set_body_bytes(HELLO))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/jello"))+ .respond_with(ResponseTemplate::new(200).set_body_bytes(b"jello\n".as_slice()))+ .mount(&server)+ .await;+ let directory = tempfile::tempdir()?;+ for (checksum, algorithm) in [+ (Checksum::Sha256(HELLO_SHA256.to_string()), "SHA-256"),+ (Checksum::GitBlobSha1(HELLO_GIT_BLOB_SHA1.to_string()), "Git blob SHA-1"),+ ] {+ let request = |name: &str| {+ DownloadTaskRequest::file()+ .destination(directory.path().join(format!("{algorithm} {name}")))+ .source_url(format!("{}/{name}", server.uri()))+ .expected_checksum(checksum.clone())+ .expected_bytes(HELLO.len() as u64)+ .build()+ };+ let task = manager.download_task(request("hello")).await?;+ let mut progress = task.progress();+ task.download().await?;+ wait_for_state(&task, &mut progress, |state| matches!(state.phase, DownloadPhase::Downloaded {})).await;+ assert!(artifact_path(&task.request().destination, "checksum").is_file());++ let corrupt = manager.download_task(request("jello")).await?;+ let mut progress = corrupt.progress();+ corrupt.download().await?;+ let state =+ wait_for_state(&corrupt, &mut progress, |state| matches!(state.phase, DownloadPhase::Error { .. })).await;+ let DownloadPhase::Error {+ message,+ } = state.phase+ else {+ panic!("expected an error phase, got {:?}", state.phase)+ };+ assert!(message.contains(algorithm), "unexpected error: {message}");+ }+ Ok(())+}++#[rstest]+#[case::universal(DownloadManagerType::Universal)]+#[cfg_attr(target_vendor = "apple", case::native(DownloadManagerType::Native))]+#[tokio::test(flavor = "multi_thread")]+async fn bearer_token(#[case] kind: DownloadManagerType) -> Result<(), Box<dyn std::error::Error>> {+ let manager = manager(kind);+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/private"))+ .and(header("authorization", "Bearer secret"))+ .respond_with(ResponseTemplate::new(200).set_body_bytes(HELLO))+ .mount(&server)+ .await;+ let directory = tempfile::tempdir()?;+ let request = |name: &str, token: Option<&str>| {+ DownloadTaskRequest::file()+ .destination(directory.path().join(name))+ .source_url(format!("{}/private", server.uri()))+ .maybe_bearer_token(token.map(str::to_string))+ .expected_bytes(HELLO.len() as u64)+ .build()+ };++ let authenticated = manager.download_task(request("authenticated", Some("secret"))).await?;+ assert!(!format!("{:?}", authenticated.request()).contains("secret"));+ let mut progress = authenticated.progress();+ authenticated.download().await?;+ wait_for_state(&authenticated, &mut progress, |state| matches!(state.phase, DownloadPhase::Downloaded {})).await;+ assert_eq!(tokio::fs::read(directory.path().join("authenticated")).await?, HELLO);++ let anonymous = manager.download_task(request("anonymous", None)).await?;+ let mut progress = anonymous.progress();+ anonymous.download().await?;+ wait_for_state(&anonymous, &mut progress, |state| matches!(state.phase, DownloadPhase::Error { .. })).await;+ assert!(!directory.path().join("anonymous").exists());++ let insecure = manager+ .download_task(+ DownloadTaskRequest::file()+ .destination(directory.path().join("insecure"))+ .source_url("http://example.invalid/private")+ .bearer_token("secret".to_string())+ .build(),+ )+ .await;+ assert!(matches!(insecure, Err(DownloadError::InsecureRequest(_))));+ Ok(())+}diff --git a/crates/legacy/mock-registry/src/model.rs b/crates/legacy/mock-registry/src/model.rsindex 8b59bdca0..a07146481 100644--- a/crates/legacy/mock-registry/src/model.rs+++ b/crates/legacy/mock-registry/src/model.rs@@ -1,6 +1,6 @@use shoji::types::{basic::Metadata,- model::{Model, ModelAccessibility, ModelBackend, ModelReference, ModelRegistry},+ model::{Model, ModelAccessibility, ModelBackend, ModelRegistry, ModelSource},};use crate::ServedFile;@@ -36,8 +36,8 @@ pub fn mock_model(properties: None,quantization: None,specializations: vec![],- accessibility: ModelAccessibility::Local {- reference: ModelReference::Mirai {+ accessibility: ModelAccessibility::OnDevice {+ source: ModelSource::Registry {toolchain_version: "1.0".to_string(),repository: None,source_repository: None,diff --git a/crates/legacy/shoji/src/types/basic/file.rs b/crates/legacy/shoji/src/types/basic/file.rsindex c6f5ca40c..7ab0e454c 100644--- a/crates/legacy/shoji/src/types/basic/file.rs+++ b/crates/legacy/shoji/src/types/basic/file.rs@@ -18,9 +18,4 @@ impl File {pub fn crc32c(&self) -> Option<String> {self.hashes.iter().find(|hash| hash.method == HashMethod::CRC32C).map(|hash| hash.value.clone())}-- #[bindings::export(Method(Getter))]- pub fn md5(&self) -> Option<String> {- self.hashes.iter().find(|hash| hash.method == HashMethod::MD5).map(|hash| hash.value.clone())- }}diff --git a/crates/legacy/shoji/src/types/basic/hash.rs b/crates/legacy/shoji/src/types/basic/hash.rsindex 7a8032e83..10d574b84 100644--- a/crates/legacy/shoji/src/types/basic/hash.rs+++ b/crates/legacy/shoji/src/types/basic/hash.rs@@ -6,8 +6,8 @@ use serde::{Deserialize, Serialize};pub enum HashMethod {#[serde(rename = "crc32c")]CRC32C,- #[serde(rename = "md5")]- MD5,+ Sha256,+ GitBlobSha1,}#[bindings::export(Structure(Class))]diff --git a/crates/legacy/shoji/src/types/model/accessibility.rs b/crates/legacy/shoji/src/types/model/accessibility.rsindex 82d01870d..203fdd188 100644--- a/crates/legacy/shoji/src/types/model/accessibility.rs+++ b/crates/legacy/shoji/src/types/model/accessibility.rs@@ -1,13 +1,15 @@use serde::{Deserialize, Serialize};-use crate::types::{basic::Repository, model::ModelReference};+use crate::types::{basic::Repository, model::ModelSource};#[bindings::export(Enumeration)]#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(tag = "type", rename_all = "snake_case")]pub enum ModelAccessibility {- Local {- reference: ModelReference,+ #[serde(rename = "local")]+ OnDevice {+ #[serde(rename = "reference")]+ source: ModelSource,},Remote {repository: Option<Repository>,diff --git a/crates/legacy/shoji/src/types/model/mod.rs b/crates/legacy/shoji/src/types/model/mod.rsindex 7170b59ad..1df6829c9 100644--- a/crates/legacy/shoji/src/types/model/mod.rs+++ b/crates/legacy/shoji/src/types/model/mod.rs@@ -3,9 +3,9 @@ mod backend;mod family;mod model;mod model_identifier;+mod model_source;mod properties;mod quantization;-mod reference;mod registry;mod specialization;mod vendor;@@ -15,9 +15,9 @@ pub use backend::ModelBackend;pub use family::ModelFamily;pub use model::Model;pub use model_identifier::ModelIdentifier;+pub use model_source::ModelSource;pub use properties::ModelProperties;pub use quantization::ModelQuantization;-pub use reference::ModelReference;pub use registry::ModelRegistry;pub use specialization::ModelSpecialization;pub use vendor::ModelVendor;diff --git a/crates/legacy/shoji/src/types/model/model.rs b/crates/legacy/shoji/src/types/model/model.rsindex 4bdcb4e94..e001a2168 100644--- a/crates/legacy/shoji/src/types/model/model.rs+++ b/crates/legacy/shoji/src/types/model/model.rs@@ -4,7 +4,7 @@ use crate::types::{basic::{Metadata, Value},model::{ModelAccessibility, ModelBackend, ModelFamily, ModelIdentifier, ModelProperties, ModelQuantization,- ModelReference, ModelRegistry, ModelSpecialization,+ ModelRegistry, ModelSource, ModelSpecialization,},};@@ -43,8 +43,8 @@ impl Model {}#[bindings::export(Method(Getter))]- pub fn is_local(&self) -> bool {- matches!(self.accessibility, ModelAccessibility::Local { .. })+ pub fn is_on_device(&self) -> bool {+ matches!(self.accessibility, ModelAccessibility::OnDevice { .. })}#[bindings::export(Method(Getter))]@@ -56,8 +56,8 @@ impl Model {pub fn is_downloadable(&self) -> bool {matches!(self.accessibility,- ModelAccessibility::Local {- reference: ModelReference::Mirai { .. } | ModelReference::HuggingFace { .. }+ ModelAccessibility::OnDevice {+ source: ModelSource::Registry { .. }})}@@ -75,101 +75,56 @@ impl Model {#[bindings::export(Method(Getter))]pub fn repo_ids(&self) -> Vec<String> {match &self.accessibility {- ModelAccessibility::Local {- reference,- ..- } => match reference {- ModelReference::Mirai {- repository,- source_repository,+ ModelAccessibility::OnDevice {+ source:+ ModelSource::Registry {+ repository,+ source_repository,+ ..+ },+ } => repository+ .iter()+ .chain(source_repository.iter())+ .map(|repository| repository.identifier.clone())+ .collect(),+ ModelAccessibility::OnDevice {+ source: ModelSource::Filesystem {..- } => {- let mut result = vec![];- if let Some(repository) = repository {- result.push(repository.identifier.clone());- }- if let Some(source_repository) = source_repository {- result.push(source_repository.identifier.clone());- }- result},- ModelReference::HuggingFace {- repository,- } => vec![repository.identifier.clone()],- ModelReference::Local {- ..- } => vec![],- },+ } => vec![],ModelAccessibility::Remote {repository,- ..- } => {- let mut result = vec![];- if let Some(repository) = repository {- result.push(repository.identifier.clone());- }- result- },+ } => repository.iter().map(|repository| repository.identifier.clone()).collect(),}}#[bindings::export(Method(Getter))]- pub fn local_external_path(&self) -> Option<String> {+ pub fn filesystem_path(&self) -> Option<String> {match &self.accessibility {- ModelAccessibility::Local {- reference,- ..- } => match reference {- ModelReference::Mirai {- ..- } => None,- ModelReference::HuggingFace {- ..- } => None,- ModelReference::Local {+ ModelAccessibility::OnDevice {+ source: ModelSource::Filesystem {path,- } => Some(path.clone()),- },- ModelAccessibility::Remote {- ..- } => None,- }- }-- #[bindings::export(Method(Getter))]- pub fn reference_name(&self) -> Option<String> {- match &self.accessibility {- ModelAccessibility::Local {- reference,- ..- } => Some(reference.name()),- ModelAccessibility::Remote {- ..- } => None,+ },+ } => Some(path.clone()),+ _ => None,}}#[bindings::export(Method(Getter))]pub fn checkpoint_version(&self) -> Option<String> {match &self.accessibility {- ModelAccessibility::Local {- reference,- ..- } => match reference {- ModelReference::Mirai {- toolchain_version,- ..- } => Some(toolchain_version.clone()),- ModelReference::HuggingFace {- repository,- } => repository.commit_hash.clone(),- ModelReference::Local {- ..- } => None,- },- ModelAccessibility::Remote {- ..- } => None,+ ModelAccessibility::OnDevice {+ source:+ ModelSource::Registry {+ toolchain_version,+ repository,+ ..+ },+ } => repository+ .as_ref()+ .and_then(|repository| repository.commit_hash.clone())+ .or_else(|| Some(toolchain_version.clone())),+ _ => None,}}}diff --git a/crates/legacy/shoji/src/types/model/model_source.rs b/crates/legacy/shoji/src/types/model/model_source.rsnew file mode 100644index 000000000..8e3106f5a--- /dev/null+++ b/crates/legacy/shoji/src/types/model/model_source.rs@@ -0,0 +1,20 @@+use serde::{Deserialize, Serialize};++use crate::types::basic::{File, Repository};++#[bindings::export(Enumeration)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum ModelSource {+ #[serde(rename = "mirai")]+ Registry {+ toolchain_version: String,+ repository: Option<Repository>,+ source_repository: Option<Repository>,+ files: Vec<File>,+ },+ #[serde(rename = "local")]+ Filesystem {+ path: String,+ },+}diff --git a/crates/legacy/shoji/src/types/model/reference.rs b/crates/legacy/shoji/src/types/model/reference.rsdeleted file mode 100644index 019e93a8d..000000000--- a/crates/legacy/shoji/src/types/model/reference.rs+++ /dev/null@@ -1,37 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::types::basic::{File, Repository};--#[bindings::export(Enumeration)]-#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]-#[serde(tag = "type", rename_all = "snake_case")]-pub enum ModelReference {- Mirai {- toolchain_version: String,- repository: Option<Repository>,- source_repository: Option<Repository>,- files: Vec<File>,- },- HuggingFace {- repository: Repository,- },- Local {- path: String,- },-}--impl ModelReference {- pub fn name(&self) -> String {- match self {- ModelReference::Mirai {- ..- } => "mirai".to_string(),- ModelReference::HuggingFace {- ..- } => "huggingface".to_string(),- ModelReference::Local {- ..- } => "local".to_string(),- }- }-}diff --git a/crates/legacy/uzu/Cargo.toml b/crates/legacy/uzu/Cargo.tomlindex 60e7012df..e8f8e231d 100644--- a/crates/legacy/uzu/Cargo.toml+++ b/crates/legacy/uzu/Cargo.toml@@ -135,6 +135,7 @@ schemars.workspace = trueserde_json.workspace = truemock-registry.workspace = truerstest.workspace = true+wiremock.workspace = truetest-tag.workspace = true[[test]]diff --git a/crates/legacy/uzu/bindings/python/uzu/__init__.pyi b/crates/legacy/uzu/bindings/python/uzu/__init__.pyiindex 62f9a244a..b4cebb0fb 100644--- a/crates/legacy/uzu/bindings/python/uzu/__init__.pyi+++ b/crates/legacy/uzu/bindings/python/uzu/__init__.pyi@@ -62,8 +62,8 @@ __all__ = ["ModelIdentifier","ModelProperties","ModelQuantization",- "ModelReference","ModelRegistry",+ "ModelSource","ModelSpecialization","ModelVendor","PcmBatch",@@ -690,7 +690,7 @@ class Engine:def remove_registry(self, registry_identifier: builtins.str) -> collections.abc.Awaitable[None]: ...def remove_backend(self, identifier: builtins.str) -> collections.abc.Awaitable[None]: ...def models(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...- def models_local(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...+ def models_on_device(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...def models_remote(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...def models_downloadable(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...def models_for_chat(self) -> collections.abc.Awaitable[builtins.list[Model]]: ...@@ -789,8 +789,6 @@ class File:def hashes(self) -> builtins.list[Hash]: ...@propertydef crc32c(self) -> typing.Optional[builtins.str]: ...- @property- def md5(self) -> typing.Optional[builtins.str]: ...def __new__(cls, url: builtins.str, name: builtins.str, size: builtins.int, hashes: typing.Sequence[Hash]) -> File: ...class Grammar:@@ -878,7 +876,7 @@ class Model:@propertydef name(self) -> builtins.str: ...@property- def is_local(self) -> builtins.bool: ...+ def is_on_device(self) -> builtins.bool: ...@propertydef is_remote(self) -> builtins.bool: ...@property@@ -890,9 +888,7 @@ class Model:@propertydef repo_ids(self) -> builtins.list[builtins.str]: ...@property- def local_external_path(self) -> typing.Optional[builtins.str]: ...- @property- def reference_name(self) -> typing.Optional[builtins.str]: ...+ def filesystem_path(self) -> typing.Optional[builtins.str]: ...@propertydef checkpoint_version(self) -> typing.Optional[builtins.str]: ...@property@@ -911,11 +907,11 @@ class Model:class ModelAccessibility:@typing.final- class Local(ModelAccessibility):- __match_args__ = ("reference",)+ class OnDevice(ModelAccessibility):+ __match_args__ = ("source",)@property- def reference(self) -> ModelReference: ...- def __new__(cls, reference: ModelReference) -> ModelAccessibility.Local: ...+ def source(self) -> ModelSource: ...+ def __new__(cls, source: ModelSource) -> ModelAccessibility.OnDevice: ...@typing.finalclass Remote(ModelAccessibility):@@ -980,9 +976,19 @@ class ModelQuantization:def name(self) -> builtins.str: ...def __new__(cls, identifier: builtins.str, method: builtins.str, bits_per_weight: builtins.int, vendor: ModelVendor, metadata: Metadata) -> ModelQuantization: ...-class ModelReference:+class ModelRegistry:+ @property+ def identifier(self) -> builtins.str: ...+ @property+ def metadata(self) -> Metadata: ...+ @property+ def name(self) -> builtins.str: ...+ def __new__(cls, identifier: builtins.str, metadata: Metadata) -> ModelRegistry: ...++class ModelSource:@typing.final- class Mirai(ModelReference):+ class Registry(ModelSource):__match_args__ = ("toolchain_version", "repository", "source_repository", "files",)@propertydef toolchain_version(self) -> builtins.str: ...@@ -992,34 +998,17 @@ class ModelReference:def source_repository(self) -> typing.Optional[Repository]: ...@propertydef files(self) -> builtins.list[File]: ...- def __new__(cls, toolchain_version: builtins.str, repository: typing.Optional[Repository], source_repository: typing.Optional[Repository], files: typing.Sequence[File]) -> ModelReference.Mirai: ...-- @typing.final- class HuggingFace(ModelReference):- __match_args__ = ("repository",)- @property- def repository(self) -> Repository: ...- def __new__(cls, repository: Repository) -> ModelReference.HuggingFace: ...+ def __new__(cls, toolchain_version: builtins.str, repository: typing.Optional[Repository], source_repository: typing.Optional[Repository], files: typing.Sequence[File]) -> ModelSource.Registry: ...@typing.final- class Local(ModelReference):+ class Filesystem(ModelSource):__match_args__ = ("path",)@propertydef path(self) -> builtins.str: ...- def __new__(cls, path: builtins.str) -> ModelReference.Local: ...+ def __new__(cls, path: builtins.str) -> ModelSource.Filesystem: ......-class ModelRegistry:- @property- def identifier(self) -> builtins.str: ...- @property- def metadata(self) -> Metadata: ...- @property- def name(self) -> builtins.str: ...- def __new__(cls, identifier: builtins.str, metadata: Metadata) -> ModelRegistry: ...-class ModelSpecialization:@typing.finalclass Chat(ModelSpecialization):@@ -1352,7 +1341,8 @@ class DownloadManagerType(enum.Enum):@typing.finalclass HashMethod(enum.Enum):CRC32C = ...- MD5 = ...+ Sha256 = ...+ GitBlobSha1 = ...@typing.finalclass ImageFormat(enum.Enum):diff --git a/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swiftindex e095452fc..5fc1fc62c 100644--- a/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift+++ b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift@@ -1741,14 +1741,6 @@ public func crc32c() -> String? {})}-public func md5() -> String? {- return try! FfiConverterOptionString.lift(try! rustCall() {- uniffi_shoji_fn_method_file_md5(- FfiConverterTypeFile_lower(self),$0- )-})-}-}@@ -2027,6 +2019,14 @@ public func checkpointVersion() -> String? {})}+public func filesystemPath() -> String? {+ return try! FfiConverterOptionString.lift(try! rustCall() {+ uniffi_shoji_fn_method_model_filesystem_path(+ FfiConverterTypeModel_lower(self),$0+ )+})+}+public func isChatCapable() -> Bool {return try! FfiConverterBool.lift(try! rustCall() {uniffi_shoji_fn_method_model_is_chat_capable(@@ -2051,9 +2051,9 @@ public func isDownloadable() -> Bool {})}-public func isLocal() -> Bool {+public func isOnDevice() -> Bool {return try! FfiConverterBool.lift(try! rustCall() {- uniffi_shoji_fn_method_model_is_local(+ uniffi_shoji_fn_method_model_is_on_device(FfiConverterTypeModel_lower(self),$0)})@@ -2099,14 +2099,6 @@ public func isTranslationCapable() -> Bool {})}-public func localExternalPath() -> String? {- return try! FfiConverterOptionString.lift(try! rustCall() {- uniffi_shoji_fn_method_model_local_external_path(- FfiConverterTypeModel_lower(self),$0- )-})-}-public func name() -> String {return try! FfiConverterString.lift(try! rustCall() {uniffi_shoji_fn_method_model_name(@@ -2115,14 +2107,6 @@ public func name() -> String {})}-public func referenceName() -> String? {- return try! FfiConverterOptionString.lift(try! rustCall() {- uniffi_shoji_fn_method_model_reference_name(- FfiConverterTypeModel_lower(self),$0- )-})-}-public func repoIds() -> [String] {return try! FfiConverterSequenceString.lift(try! rustCall() {uniffi_shoji_fn_method_model_repo_ids(@@ -4200,7 +4184,8 @@ public func FfiConverterTypeGrammar_lower(_ value: Grammar) -> RustBuffer {public enum HashMethod: Equatable, Hashable, Codable {case crc32c- case md5+ case sha256+ case gitBlobSha1@@ -4224,7 +4209,9 @@ public struct FfiConverterTypeHashMethod: FfiConverterRustBuffer {case 1: return .crc32c- case 2: return .md5+ case 2: return .sha256++ case 3: return .gitBlobSha1default: throw UniffiInternalError.unexpectedEnumCase}@@ -4238,9 +4225,13 @@ public struct FfiConverterTypeHashMethod: FfiConverterRustBuffer {writeInt(&buf, Int32(1))- case .md5:+ case .sha256:writeInt(&buf, Int32(2))++ case .gitBlobSha1:+ writeInt(&buf, Int32(3))+}}}@@ -4407,7 +4398,7 @@ public func FfiConverterTypeImageTheme_lower(_ value: ImageTheme) -> RustBufferpublic enum ModelAccessibility: Equatable, Hashable, Codable {- case local(reference: ModelReference+ case onDevice(source: ModelSource)case remote(repository: Repository?)@@ -4432,7 +4423,7 @@ public struct FfiConverterTypeModelAccessibility: FfiConverterRustBuffer {let variant: Int32 = try readInt(&buf)switch variant {- case 1: return .local(reference: try FfiConverterTypeModelReference.read(from: &buf)+ case 1: return .onDevice(source: try FfiConverterTypeModelSource.read(from: &buf))case 2: return .remote(repository: try FfiConverterOptionTypeRepository.read(from: &buf)@@ -4446,9 +4437,9 @@ public struct FfiConverterTypeModelAccessibility: FfiConverterRustBuffer {switch value {- case let .local(reference):+ case let .onDevice(source):writeInt(&buf, Int32(1))- FfiConverterTypeModelReference.write(reference, into: &buf)+ FfiConverterTypeModelSource.write(source, into: &buf)case let .remote(repository):@@ -4478,13 +4469,11 @@ public func FfiConverterTypeModelAccessibility_lower(_ value: ModelAccessibility// Note that we don't yet support `indirect` for enums.// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.-public enum ModelReference: Equatable, Hashable, Codable {+public enum ModelSource: Equatable, Hashable, Codable {- case mirai(toolchainVersion: String, repository: Repository?, sourceRepository: Repository?, files: [File]+ case registry(toolchainVersion: String, repository: Repository?, sourceRepository: Repository?, files: [File])- case huggingFace(repository: Repository- )- case local(path: String+ case filesystem(path: String)@@ -4494,37 +4483,34 @@ public enum ModelReference: Equatable, Hashable, Codable {}#if compiler(>=6)-extension ModelReference: Sendable {}+extension ModelSource: Sendable {}#endif#if swift(>=5.8)@_documentation(visibility: private)#endif-public struct FfiConverterTypeModelReference: FfiConverterRustBuffer {- typealias SwiftType = ModelReference+public struct FfiConverterTypeModelSource: FfiConverterRustBuffer {+ typealias SwiftType = ModelSource- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ModelReference {+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ModelSource {let variant: Int32 = try readInt(&buf)switch variant {- case 1: return .mirai(toolchainVersion: try FfiConverterString.read(from: &buf), repository: try FfiConverterOptionTypeRepository.read(from: &buf), sourceRepository: try FfiConverterOptionTypeRepository.read(from: &buf), files: try FfiConverterSequenceTypeFile.read(from: &buf)- )-- case 2: return .huggingFace(repository: try FfiConverterTypeRepository.read(from: &buf)+ case 1: return .registry(toolchainVersion: try FfiConverterString.read(from: &buf), repository: try FfiConverterOptionTypeRepository.read(from: &buf), sourceRepository: try FfiConverterOptionTypeRepository.read(from: &buf), files: try FfiConverterSequenceTypeFile.read(from: &buf))- case 3: return .local(path: try FfiConverterString.read(from: &buf)+ case 2: return .filesystem(path: try FfiConverterString.read(from: &buf))default: throw UniffiInternalError.unexpectedEnumCase}}- public static func write(_ value: ModelReference, into buf: inout [UInt8]) {+ public static func write(_ value: ModelSource, into buf: inout [UInt8]) {switch value {- case let .mirai(toolchainVersion,repository,sourceRepository,files):+ case let .registry(toolchainVersion,repository,sourceRepository,files):writeInt(&buf, Int32(1))FfiConverterString.write(toolchainVersion, into: &buf)FfiConverterOptionTypeRepository.write(repository, into: &buf)@@ -4532,13 +4518,8 @@ public struct FfiConverterTypeModelReference: FfiConverterRustBuffer {FfiConverterSequenceTypeFile.write(files, into: &buf)- case let .huggingFace(repository):+ case let .filesystem(path):writeInt(&buf, Int32(2))- FfiConverterTypeRepository.write(repository, into: &buf)--- case let .local(path):- writeInt(&buf, Int32(3))FfiConverterString.write(path, into: &buf)}@@ -4549,15 +4530,15 @@ public struct FfiConverterTypeModelReference: FfiConverterRustBuffer {#if swift(>=5.8)@_documentation(visibility: private)#endif-public func FfiConverterTypeModelReference_lift(_ buf: RustBuffer) throws -> ModelReference {- return try FfiConverterTypeModelReference.lift(buf)+public func FfiConverterTypeModelSource_lift(_ buf: RustBuffer) throws -> ModelSource {+ return try FfiConverterTypeModelSource.lift(buf)}#if swift(>=5.8)@_documentation(visibility: private)#endif-public func FfiConverterTypeModelReference_lower(_ value: ModelReference) -> RustBuffer {- return FfiConverterTypeModelReference.lower(value)+public func FfiConverterTypeModelSource_lower(_ value: ModelSource) -> RustBuffer {+ return FfiConverterTypeModelSource.lower(value)}diff --git a/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swiftindex 022daa3e0..effafcf2c 100644--- a/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift+++ b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift@@ -886,7 +886,7 @@ public protocol EngineProtocol: AnyObject, Sendable {func modelsForTranslation() async throws -> [Model]- func modelsLocal() async throws -> [Model]+ func modelsOnDevice() async throws -> [Model]func modelsRemote() async throws -> [Model]@@ -1374,11 +1374,11 @@ open func modelsForTranslation()async throws -> [Model] {)}-open func modelsLocal()async throws -> [Model] {+open func modelsOnDevice()async throws -> [Model] {returntry await uniffiRustCallAsync(rustFutureFunc: {- uniffi_uzu_fn_method_engine_models_local(+ uniffi_uzu_fn_method_engine_models_on_device(self.uniffiCloneHandle())@@ -3373,7 +3373,7 @@ private let initializationResult: InitializationResult = {if (uniffi_uzu_checksum_method_engine_models_for_translation() != 56970) {return InitializationResult.apiChecksumMismatch}- if (uniffi_uzu_checksum_method_engine_models_local() != 2150) {+ if (uniffi_uzu_checksum_method_engine_models_on_device() != 11803) {return InitializationResult.apiChecksumMismatch}if (uniffi_uzu_checksum_method_engine_models_remote() != 36115) {diff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mtsindex 81d0fa73b..9e86c9e70 100644--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts@@ -484,7 +484,6 @@ export declare class File {hashes: Array<Hash>constructor(url: string, name: string, size: number, hashes: Array<Hash>)get crc32C(): string | null- get md5(): string | null}export declare class GrammarJsonAny {@@ -541,14 +540,13 @@ export declare class Model {encoding?: anyconstructor(identifier: ModelIdentifier, registry: ModelRegistry, backends: Array<ModelBackend>, family?: ModelFamily, properties?: ModelProperties, quantization?: ModelQuantization, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: any)get name(): string- get isLocal(): boolean+ get isOnDevice(): booleanget isRemote(): booleanget isDownloadable(): booleanget isQuantized(): booleanget cacheIdentifier(): stringget repoIds(): Array<string>- get localExternalPath(): string | null- get referenceName(): string | null+ get filesystemPath(): string | nullget checkpointVersion(): string | nullstatic external(identifier: ModelIdentifier, registryIdentifier: string, registryName: string, backendIdentifier: string, backendName: string, backendVersion: string, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: any | undefined | null): Model@@ -559,9 +557,9 @@ export declare class Model {get isSpeculationCapable(): boolean}-export declare class ModelAccessibilityLocal {- reference: ModelReference- constructor(reference: ModelReference)+export declare class ModelAccessibilityOnDevice {+ source: ModelSource+ constructor(source: ModelSource)}export declare class ModelAccessibilityRemote {@@ -604,17 +602,19 @@ export declare class ModelQuantization {get name(): string}-export declare class ModelReferenceHuggingFace {- repository: Repository- constructor(repository: Repository)+export declare class ModelRegistry {+ identifier: string+ metadata: Metadata+ constructor(identifier: string, metadata: Metadata)+ get name(): string}-export declare class ModelReferenceLocal {+export declare class ModelSourceFilesystem {path: stringconstructor(path: string)}-export declare class ModelReferenceMirai {+export declare class ModelSourceRegistry {toolchainVersion: stringrepository?: RepositorysourceRepository?: Repository@@ -622,13 +622,6 @@ export declare class ModelReferenceMirai {constructor(toolchainVersion: string, repository?: Repository, sourceRepository?: Repository, files: Array<File>)}-export declare class ModelRegistry {- identifier: string- metadata: Metadata- constructor(identifier: string, metadata: Metadata)- get name(): string-}-export declare class ModelSpecializationChat {constructor()@@ -850,7 +843,8 @@ export type Grammar =export declare const enum HashMethod {CRC32C = 'CRC32C',- MD5 = 'MD5'+ Sha256 = 'Sha256',+ GitBlobSha1 = 'GitBlobSha1'}export declare const enum ImageFormat {@@ -865,13 +859,13 @@ export declare const enum ImageTheme {}export type ModelAccessibility =- ModelAccessibilityLocal | ModelAccessibilityRemote+ ModelAccessibilityOnDevice | ModelAccessibilityRemoteexport type ModelIdentifier =string-export type ModelReference =- ModelReferenceMirai | ModelReferenceHuggingFace | ModelReferenceLocal+export type ModelSource =+ ModelSourceRegistry | ModelSourceFilesystemexport type ModelSpecialization =ModelSpecializationChat | ModelSpecializationClassification | ModelSpecializationTextToSpeech | ModelSpecializationTranslation | ModelSpecializationSpeculation@@ -943,7 +937,7 @@ export declare class Engine {removeRegistry(registryIdentifier: string): Promise<void>removeBackend(identifier: string): Promise<void>get models(): Promise<Array<Model>>- get modelsLocal(): Promise<Array<Model>>+ get modelsOnDevice(): Promise<Array<Model>>get modelsRemote(): Promise<Array<Model>>get modelsDownloadable(): Promise<Array<Model>>get modelsForChat(): Promise<Array<Model>>diff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.tsindex 81d0fa73b..9e86c9e70 100644--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts@@ -484,7 +484,6 @@ export declare class File {hashes: Array<Hash>constructor(url: string, name: string, size: number, hashes: Array<Hash>)get crc32C(): string | null- get md5(): string | null}export declare class GrammarJsonAny {@@ -541,14 +540,13 @@ export declare class Model {encoding?: anyconstructor(identifier: ModelIdentifier, registry: ModelRegistry, backends: Array<ModelBackend>, family?: ModelFamily, properties?: ModelProperties, quantization?: ModelQuantization, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: any)get name(): string- get isLocal(): boolean+ get isOnDevice(): booleanget isRemote(): booleanget isDownloadable(): booleanget isQuantized(): booleanget cacheIdentifier(): stringget repoIds(): Array<string>- get localExternalPath(): string | null- get referenceName(): string | null+ get filesystemPath(): string | nullget checkpointVersion(): string | nullstatic external(identifier: ModelIdentifier, registryIdentifier: string, registryName: string, backendIdentifier: string, backendName: string, backendVersion: string, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: any | undefined | null): Model@@ -559,9 +557,9 @@ export declare class Model {get isSpeculationCapable(): boolean}-export declare class ModelAccessibilityLocal {- reference: ModelReference- constructor(reference: ModelReference)+export declare class ModelAccessibilityOnDevice {+ source: ModelSource+ constructor(source: ModelSource)}export declare class ModelAccessibilityRemote {@@ -604,17 +602,19 @@ export declare class ModelQuantization {get name(): string}-export declare class ModelReferenceHuggingFace {- repository: Repository- constructor(repository: Repository)+export declare class ModelRegistry {+ identifier: string+ metadata: Metadata+ constructor(identifier: string, metadata: Metadata)+ get name(): string}-export declare class ModelReferenceLocal {+export declare class ModelSourceFilesystem {path: stringconstructor(path: string)}-export declare class ModelReferenceMirai {+export declare class ModelSourceRegistry {toolchainVersion: stringrepository?: RepositorysourceRepository?: Repository@@ -622,13 +622,6 @@ export declare class ModelReferenceMirai {constructor(toolchainVersion: string, repository?: Repository, sourceRepository?: Repository, files: Array<File>)}-export declare class ModelRegistry {- identifier: string- metadata: Metadata- constructor(identifier: string, metadata: Metadata)- get name(): string-}-export declare class ModelSpecializationChat {constructor()@@ -850,7 +843,8 @@ export type Grammar =export declare const enum HashMethod {CRC32C = 'CRC32C',- MD5 = 'MD5'+ Sha256 = 'Sha256',+ GitBlobSha1 = 'GitBlobSha1'}export declare const enum ImageFormat {@@ -865,13 +859,13 @@ export declare const enum ImageTheme {}export type ModelAccessibility =- ModelAccessibilityLocal | ModelAccessibilityRemote+ ModelAccessibilityOnDevice | ModelAccessibilityRemoteexport type ModelIdentifier =string-export type ModelReference =- ModelReferenceMirai | ModelReferenceHuggingFace | ModelReferenceLocal+export type ModelSource =+ ModelSourceRegistry | ModelSourceFilesystemexport type ModelSpecialization =ModelSpecializationChat | ModelSpecializationClassification | ModelSpecializationTextToSpeech | ModelSpecializationTranslation | ModelSpecializationSpeculation@@ -943,7 +937,7 @@ export declare class Engine {removeRegistry(registryIdentifier: string): Promise<void>removeBackend(identifier: string): Promise<void>get models(): Promise<Array<Model>>- get modelsLocal(): Promise<Array<Model>>+ get modelsOnDevice(): Promise<Array<Model>>get modelsRemote(): Promise<Array<Model>>get modelsDownloadable(): Promise<Array<Model>>get modelsForChat(): Promise<Array<Model>>diff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.js b/crates/legacy/uzu/bindings/typescript/src/napi/index.jsindex 5261608f8..564f92b36 100644--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.js+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.js@@ -581,16 +581,15 @@ module.exports.Hash = nativeBinding.Hashmodule.exports.Image = nativeBinding.Imagemodule.exports.Metadata = nativeBinding.Metadatamodule.exports.Model = nativeBinding.Model-module.exports.ModelAccessibilityLocal = nativeBinding.ModelAccessibilityLocal+module.exports.ModelAccessibilityOnDevice = nativeBinding.ModelAccessibilityOnDevicemodule.exports.ModelAccessibilityRemote = nativeBinding.ModelAccessibilityRemotemodule.exports.ModelBackend = nativeBinding.ModelBackendmodule.exports.ModelFamily = nativeBinding.ModelFamilymodule.exports.ModelProperties = nativeBinding.ModelPropertiesmodule.exports.ModelQuantization = nativeBinding.ModelQuantization-module.exports.ModelReferenceHuggingFace = nativeBinding.ModelReferenceHuggingFace-module.exports.ModelReferenceLocal = nativeBinding.ModelReferenceLocal-module.exports.ModelReferenceMirai = nativeBinding.ModelReferenceMiraimodule.exports.ModelRegistry = nativeBinding.ModelRegistry+module.exports.ModelSourceFilesystem = nativeBinding.ModelSourceFilesystem+module.exports.ModelSourceRegistry = nativeBinding.ModelSourceRegistrymodule.exports.ModelSpecializationChat = nativeBinding.ModelSpecializationChatmodule.exports.ModelSpecializationClassification = nativeBinding.ModelSpecializationClassificationmodule.exports.ModelSpecializationSpeculation = nativeBinding.ModelSpecializationSpeculationdiff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.mjs b/crates/legacy/uzu/bindings/typescript/src/napi/index.mjsindex ca539a656..18e55d21f 100644--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.mjs+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.mjs@@ -78,16 +78,15 @@ export const Hash = cjs.Hash;export const Image = cjs.Image;export const Metadata = cjs.Metadata;export const Model = cjs.Model;-export const ModelAccessibilityLocal = cjs.ModelAccessibilityLocal;+export const ModelAccessibilityOnDevice = cjs.ModelAccessibilityOnDevice;export const ModelAccessibilityRemote = cjs.ModelAccessibilityRemote;export const ModelBackend = cjs.ModelBackend;export const ModelFamily = cjs.ModelFamily;export const ModelProperties = cjs.ModelProperties;export const ModelQuantization = cjs.ModelQuantization;-export const ModelReferenceHuggingFace = cjs.ModelReferenceHuggingFace;-export const ModelReferenceLocal = cjs.ModelReferenceLocal;-export const ModelReferenceMirai = cjs.ModelReferenceMirai;export const ModelRegistry = cjs.ModelRegistry;+export const ModelSourceFilesystem = cjs.ModelSourceFilesystem;+export const ModelSourceRegistry = cjs.ModelSourceRegistry;export const ModelSpecializationChat = cjs.ModelSpecializationChat;export const ModelSpecializationClassification = cjs.ModelSpecializationClassification;export const ModelSpecializationSpeculation = cjs.ModelSpecializationSpeculation;diff --git a/crates/legacy/uzu/src/engine/mod.rs b/crates/legacy/uzu/src/engine/mod.rsindex 5af2c1806..ada3739af 100644--- a/crates/legacy/uzu/src/engine/mod.rs+++ b/crates/legacy/uzu/src/engine/mod.rs@@ -40,12 +40,12 @@ use crate::{registry::{CachedRegistry, MergedRegistry, RegistryError,local::{Config as LocalRegistryConfig, Registry as LocalRegistry},- mirai::{Backend as MiraiBackend, Registry as MiraiRegistry, TELEMETRY_URL},+ mirai::{Backend as MiraiBackend, HUGGING_FACE_URL, Registry as MiraiRegistry, TELEMETRY_URL},openai::{Config as OpenAIConfig, Registry as OpenAIRegistry},unique_model,},settings::Settings,- storage::{Config as StorageConfig, DownloadPhase, DownloadState, Storage},+ storage::{BearerToken, Config as StorageConfig, DownloadPhase, DownloadState, Storage},};#[bindings::export(Class)]@@ -92,8 +92,15 @@ impl Engine {});let registry = SharedAccess::new(MergedRegistry::new(vec![]));- let storage_config =- StorageConfig::new(device.clone(), None, "mirai".to_string(), config.download_manager_type);+ let huggingface_api_key = config.huggingface_api_key.map(BearerToken::from);+ let storage_config = StorageConfig::new(+ device.clone(),+ None,+ "mirai".to_string(),+ config.download_manager_type,+ HUGGING_FACE_URL.to_string(),+ huggingface_api_key.clone(),+ );let storage_cache_path = Storage::cache_path(&storage_config);logs::start(storage_cache_path.clone(), &format!("{}.log", storage_config.name), false);let storage = Arc::new(Storage::new(runtime_handle, storage_config).await?);@@ -116,6 +123,7 @@ impl Engine {let mirai_registry = Box::new(MiraiRegistry::builder().maybe_api_key(config.mirai_api_key)+ .maybe_huggingface_api_key(huggingface_api_key).device(device.clone()).backends(vec![MiraiBackend {identifier: uzu_backend_identifier.clone(),@@ -255,8 +263,8 @@ impl Engine {}#[bindings::export(Method(Getter))]- pub async fn models_local(&self) -> Result<Vec<Model>, EngineError> {- Ok(self.models().await?.into_iter().filter(|model| model.is_local()).collect())+ pub async fn models_on_device(&self) -> Result<Vec<Model>, EngineError> {+ Ok(self.models().await?.into_iter().filter(|model| model.is_on_device()).collect())}#[bindings::export(Method(Getter))]@@ -437,11 +445,11 @@ impl Engine {&self,model: &Model,) -> Option<String> {- if !model.is_local() {+ if !model.is_on_device() {return None;}- if let Some(local_external_path) = model.local_external_path() {- return Some(local_external_path);+ if let Some(filesystem_path) = model.filesystem_path() {+ return Some(filesystem_path);}let state = self.storage.state(&model.identifier).await.ok()?;if !matches!(state.phase, DownloadPhase::Downloaded {}) {diff --git a/crates/legacy/uzu/src/engine/shorthand.rs b/crates/legacy/uzu/src/engine/shorthand.rsindex b622a18cc..655bb8a7a 100644--- a/crates/legacy/uzu/src/engine/shorthand.rs+++ b/crates/legacy/uzu/src/engine/shorthand.rs@@ -1,4 +1,4 @@-use shoji::types::model::{Model, ModelAccessibility, ModelReference};+use shoji::types::model::{Model, ModelAccessibility, ModelSource};use crate::registry::RegistryError;@@ -89,8 +89,8 @@ fn model_shorthand_matches(}fn checkpoint_size_bytes(model: &Model) -> Option<u64> {- if let ModelAccessibility::Local {- reference: ModelReference::Mirai {+ if let ModelAccessibility::OnDevice {+ source: ModelSource::Registry {files,..},diff --git a/crates/legacy/uzu/src/helpers/mod.rs b/crates/legacy/uzu/src/helpers/mod.rsindex b2f7b0f8e..9c2f42905 100644--- a/crates/legacy/uzu/src/helpers/mod.rs+++ b/crates/legacy/uzu/src/helpers/mod.rs@@ -1,5 +1,7 @@mod reachability;+mod same_origin;mod shared_access;pub use reachability::is_endpoint_reachable;+pub use same_origin::same_origin;pub use shared_access::SharedAccess;diff --git a/crates/legacy/uzu/src/helpers/same_origin.rs b/crates/legacy/uzu/src/helpers/same_origin.rsnew file mode 100644index 000000000..e806cf182--- /dev/null+++ b/crates/legacy/uzu/src/helpers/same_origin.rs@@ -0,0 +1,11 @@+use reqwest::Url;++pub fn same_origin(+ url: &str,+ endpoint: &str,+) -> bool {+ match (Url::parse(url), Url::parse(endpoint)) {+ (Ok(url), Ok(endpoint)) => url.origin() == endpoint.origin(),+ _ => false,+ }+}diff --git a/crates/legacy/uzu/src/registry/local/mod.rs b/crates/legacy/uzu/src/registry/local/mod.rsindex 45a68b580..97eb06257 100644--- a/crates/legacy/uzu/src/registry/local/mod.rs+++ b/crates/legacy/uzu/src/registry/local/mod.rs@@ -8,7 +8,7 @@ use shoji::{traits::Registry as RegistryTrait,types::{basic::Value,- model::{Model, ModelAccessibility, ModelReference, ModelSpecialization},+ model::{Model, ModelAccessibility, ModelSource, ModelSpecialization},},};use uzu_engine::engine::{ModelType, resolve_model_type};@@ -111,8 +111,8 @@ impl Registry {self.config.backend_identifier.clone(),self.config.backend_version.clone(),vec![specialization],- ModelAccessibility::Local {- reference: ModelReference::Local {+ ModelAccessibility::OnDevice {+ source: ModelSource::Filesystem {path: path.to_string_lossy().to_string(),},},diff --git a/crates/legacy/uzu/src/registry/mirai/api.rs b/crates/legacy/uzu/src/registry/mirai/api.rsindex 461d10b99..c8e378bc0 100644--- a/crates/legacy/uzu/src/registry/mirai/api.rs+++ b/crates/legacy/uzu/src/registry/mirai/api.rs@@ -1,2 +1,3 @@pub const REGISTRY_URL: &str = "https://sdk.trymirai.com/api/v1";pub const TELEMETRY_URL: &str = "https://sdk.trymirai.com/api/v2";+pub const HUGGING_FACE_URL: &str = "https://huggingface.co";diff --git a/crates/legacy/uzu/src/registry/mirai/hugging_face.rs b/crates/legacy/uzu/src/registry/mirai/hugging_face.rsnew file mode 100644index 000000000..03ffa1505--- /dev/null+++ b/crates/legacy/uzu/src/registry/mirai/hugging_face.rs@@ -0,0 +1,146 @@+use std::time::Duration;++use bon::bon;+use download_manager::BearerToken;+use reqwest::{Client, Url, header::AUTHORIZATION};+use shoji::types::basic::{File, Hash, HashMethod, Repository};++use super::{api::HUGGING_FACE_URL, hugging_face_model::HuggingFaceModel};+use crate::{helpers::same_origin, registry::RegistryError};++pub struct HuggingFace {+ client: Client,+ endpoint: Url,+ token: Option<BearerToken>,+}++#[bon]+impl HuggingFace {+ #[builder]+ pub fn new(+ #[builder(default = HUGGING_FACE_URL.to_string(), into)] endpoint: String,+ token: Option<BearerToken>,+ ) -> Result<Self, RegistryError> {+ let client = Client::builder().timeout(Duration::from_secs(30)).build().map_err(|error| {+ RegistryError::UnableToCreate {+ message: error.to_string(),+ }+ })?;+ let endpoint = Url::parse(&endpoint).map_err(|error| RegistryError::UnableToCreate {+ message: error.to_string(),+ })?;+ Ok(Self {+ client,+ endpoint,+ token,+ })+ }++ pub fn serves(+ &self,+ files: &[File],+ ) -> bool {+ !files.is_empty() && files.iter().all(|file| same_origin(&file.url, self.endpoint.as_str()))+ }++ pub async fn files(+ &self,+ repository: &Repository,+ ) -> Result<Vec<File>, RegistryError> {+ let revision = repository.commit_hash.as_deref().ok_or_else(|| RegistryError::UnableToGetModels {+ message: format!("{} has no revision", repository.identifier),+ })?;+ let mut metadata_url = self+ .url(["api", "models"].into_iter().chain(repository.identifier.split('/')).chain(["revision", revision]))?;+ metadata_url.set_query(Some("blobs=true"));+ let mut request = self.client.get(metadata_url);+ if let Some(token) = &self.token {+ request = request.header(AUTHORIZATION, token.header_value());+ }+ let response = request.send().await.and_then(|response| response.error_for_status()).map_err(|error| {+ RegistryError::UnableToGetModels {+ message: error.to_string(),+ }+ })?;+ let model: HuggingFaceModel = response.json().await.map_err(|error| RegistryError::UnableToGetModels {+ message: error.to_string(),+ })?;+ let commit = model.sha.as_str();+ if !is_lower_hex(commit, 40) {+ return Err(RegistryError::UnableToGetModels {+ message: format!("Hugging Face returned invalid commit {commit} for {revision}"),+ });+ }+ let files = model+ .siblings+ .iter()+ .filter(|sibling| repository.paths.as_ref().is_none_or(|paths| paths.contains(&sibling.rfilename)))+ .map(|sibling| {+ let name = &sibling.rfilename;+ if name.contains(['\\', ':']) || name.split('/').any(|segment| matches!(segment, "" | "." | "..")) {+ return Err(RegistryError::UnableToGetModels {+ message: format!("invalid file name: {name}"),+ });+ }+ let (size, hash) = match &sibling.lfs {+ Some(lfs) => (+ lfs.size.or(sibling.size),+ lfs.sha256.as_deref().filter(|digest| is_lower_hex(digest, 64)).map(|digest| Hash {+ method: HashMethod::Sha256,+ value: digest.to_string(),+ }),+ ),+ None => (+ sibling.size,+ sibling.blob_id.as_deref().filter(|digest| is_lower_hex(digest, 40)).map(|digest| Hash {+ method: HashMethod::GitBlobSha1,+ value: digest.to_string(),+ }),+ ),+ };+ let (Some(size), Some(hash)) = (size, hash) else {+ return Err(RegistryError::UnableToGetModels {+ message: format!("Hugging Face is missing size or digest for {name}"),+ });+ };+ Ok(File {+ url: self+ .url(repository.identifier.split('/').chain(["resolve", commit]).chain(name.split('/')))?+ .into(),+ name: name.clone(),+ size: i64::try_from(size).map_err(|_| RegistryError::UnableToGetModels {+ message: format!("file size overflow for {name}"),+ })?,+ hashes: vec![hash],+ })+ })+ .collect::<Result<Vec<_>, _>>()?;+ if files.is_empty() {+ return Err(RegistryError::UnableToGetModels {+ message: format!("{} has no files at {revision}", repository.identifier),+ });+ }+ Ok(files)+ }++ fn url<'a>(+ &self,+ segments: impl Iterator<Item = &'a str>,+ ) -> Result<Url, RegistryError> {+ let mut url = self.endpoint.clone();+ url.path_segments_mut()+ .map_err(|_| RegistryError::UnableToGetModels {+ message: "invalid Hugging Face endpoint".to_string(),+ })?+ .clear()+ .extend(segments);+ Ok(url)+ }+}++pub fn is_lower_hex(+ value: &str,+ length: usize,+) -> bool {+ value.len() == length && value.bytes().all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))+}diff --git a/crates/legacy/uzu/src/registry/mirai/hugging_face_file.rs b/crates/legacy/uzu/src/registry/mirai/hugging_face_file.rsnew file mode 100644index 000000000..266b4ae35--- /dev/null+++ b/crates/legacy/uzu/src/registry/mirai/hugging_face_file.rs@@ -0,0 +1,12 @@+use serde::Deserialize;++use super::hugging_face_lfs::HuggingFaceLfs;++#[derive(Deserialize)]+pub struct HuggingFaceFile {+ pub rfilename: String,+ pub size: Option<u64>,+ #[serde(rename = "blobId")]+ pub blob_id: Option<String>,+ pub lfs: Option<HuggingFaceLfs>,+}diff --git a/crates/legacy/uzu/src/registry/mirai/hugging_face_lfs.rs b/crates/legacy/uzu/src/registry/mirai/hugging_face_lfs.rsnew file mode 100644index 000000000..783fa999f--- /dev/null+++ b/crates/legacy/uzu/src/registry/mirai/hugging_face_lfs.rs@@ -0,0 +1,7 @@+use serde::Deserialize;++#[derive(Deserialize)]+pub struct HuggingFaceLfs {+ pub sha256: Option<String>,+ pub size: Option<u64>,+}diff --git a/crates/legacy/uzu/src/registry/mirai/hugging_face_model.rs b/crates/legacy/uzu/src/registry/mirai/hugging_face_model.rsnew file mode 100644index 000000000..a5dc602e7--- /dev/null+++ b/crates/legacy/uzu/src/registry/mirai/hugging_face_model.rs@@ -0,0 +1,9 @@+use serde::Deserialize;++use super::hugging_face_file::HuggingFaceFile;++#[derive(Deserialize)]+pub struct HuggingFaceModel {+ pub sha: String,+ pub siblings: Vec<HuggingFaceFile>,+}diff --git a/crates/legacy/uzu/src/registry/mirai/mod.rs b/crates/legacy/uzu/src/registry/mirai/mod.rsindex 3d1c1317e..33589c372 100644--- a/crates/legacy/uzu/src/registry/mirai/mod.rs+++ b/crates/legacy/uzu/src/registry/mirai/mod.rs@@ -1,9 +1,14 @@mod api;mod backend;mod fetch_models;+mod hugging_face;+mod hugging_face_file;+mod hugging_face_lfs;+mod hugging_face_model;mod registry;mod types;-pub use api::TELEMETRY_URL;+pub use api::{HUGGING_FACE_URL, TELEMETRY_URL};pub use backend::Backend;+pub use hugging_face::HuggingFace;pub use registry::Registry;diff --git a/crates/legacy/uzu/src/registry/mirai/registry.rs b/crates/legacy/uzu/src/registry/mirai/registry.rsindex 2d4dabdd0..d91a90d97 100644--- a/crates/legacy/uzu/src/registry/mirai/registry.rs+++ b/crates/legacy/uzu/src/registry/mirai/registry.rs@@ -1,24 +1,37 @@use std::{fs::{read_to_string, write},- future::Future,+ future::{Future, ready},io,path::PathBuf,pin::Pin,};use bon::bon;+use download_manager::BearerToken;+use futures::{StreamExt, stream};use nagare::api::{Client, Error as ApiError, IsTransient};-use shoji::{traits::Registry as RegistryTrait, types::model::Model};+use shoji::{+ traits::Registry as RegistryTrait,+ types::model::{Model, ModelAccessibility, ModelSource},+};-use super::{api::REGISTRY_URL, backend::Backend, fetch_models::FetchModels};+use super::{+ api::{HUGGING_FACE_URL, REGISTRY_URL},+ backend::Backend,+ fetch_models::FetchModels,+ hugging_face::{HuggingFace, is_lower_hex},+};use crate::{device::Device, registry::RegistryError};+const CONCURRENT_RESOLUTIONS: usize = 8;+pub struct Registry {device: Device,backends: Vec<Backend>,include_traces: bool,cache_path: PathBuf,client: Client,+ hugging_face: HuggingFace,}#[bon]@@ -26,16 +39,21 @@ impl Registry {#[builder]pub fn new(api_key: Option<String>,+ huggingface_api_key: Option<BearerToken>,device: Device,backends: Vec<Backend>,#[builder(default)] include_traces: bool,cache_path: PathBuf,+ #[builder(default = REGISTRY_URL.to_string(), into)] registry_url: String,+ #[builder(default = HUGGING_FACE_URL.to_string(), into)] hugging_face_url: String,) -> Result<Self, RegistryError> {- let client = Client::builder().base_url(REGISTRY_URL).maybe_bearer_token(api_key).build().map_err(|error| {+ let client = Client::builder().base_url(registry_url).maybe_bearer_token(api_key).build().map_err(|error| {RegistryError::UnableToCreate {message: error.to_string(),}})?;+ let hugging_face =+ HuggingFace::builder().endpoint(hugging_face_url).maybe_token(huggingface_api_key).build()?;Ok(Self {device,@@ -43,6 +61,7 @@ impl Registry {include_traces,cache_path,client,+ hugging_face,})}}@@ -56,8 +75,10 @@ impl RegistryTrait for Registry {fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, RegistryError>> + Send + '_>> {Box::pin(async {+ let cached = self.load_registry();match self.fetch_models().await {Ok(models) => {+ let models = self.resolve(models, cached.unwrap_or_default()).await;let saved = serde_json::to_vec_pretty(&models).map_err(io::Error::other).and_then(|contents| write(self.registry_path(), contents));@@ -68,7 +89,7 @@ impl RegistryTrait for Registry {},Err(error) => {if error.is_transient()- && let Ok(models) = self.load_registry()+ && let Ok(models) = cached{tracing::warn!(?error, "serving cached Mirai registry after fetch failure");return Ok(models);@@ -94,6 +115,63 @@ impl Registry {response.models().ok_or_else(|| ApiError::Decode("response contained no models".to_string()))}+ async fn resolve(+ &self,+ models: Vec<Model>,+ cached: Vec<Model>,+ ) -> Vec<Model> {+ stream::iter(models)+ .map(|model| self.resolve_model(model, &cached))+ .buffered(CONCURRENT_RESOLUTIONS)+ .filter_map(ready)+ .collect()+ .await+ }++ async fn resolve_model(+ &self,+ mut model: Model,+ cached: &[Model],+ ) -> Option<Model> {+ let ModelAccessibility::OnDevice {+ source:+ ModelSource::Registry {+ repository: Some(repository),+ files,+ ..+ },+ } = &mut model.accessibility+ else {+ return Some(model);+ };+ if repository.commit_hash.is_none() {+ return Some(model);+ }+ let pinned_to_commit = repository.commit_hash.as_deref().is_some_and(|revision| is_lower_hex(revision, 40));+ let previous = cached.iter().filter(|_| pinned_to_commit).find_map(|previous| match &previous.accessibility {+ ModelAccessibility::OnDevice {+ source:+ ModelSource::Registry {+ repository: Some(previous_repository),+ files,+ ..+ },+ } if previous_repository == repository && self.hugging_face.serves(files) => Some(files.clone()),+ _ => None,+ });+ *files = match previous {+ Some(files) => files,+ None => match self.hugging_face.files(repository).await {+ Ok(files) => files,+ Err(error) => {+ tracing::warn!(?error, model = %model.identifier, "skipping model with unresolved Hugging Face files");+ return None;+ },+ },+ };+ Some(model)+ }+fn registry_path(&self) -> PathBuf {self.cache_path.join("registry.json")}diff --git a/crates/legacy/uzu/src/storage/config.rs b/crates/legacy/uzu/src/storage/config.rsindex f07bfad04..16175a424 100644--- a/crates/legacy/uzu/src/storage/config.rs+++ b/crates/legacy/uzu/src/storage/config.rs@@ -1,6 +1,6 @@use std::path::PathBuf;-use download_manager::DownloadManagerType;+use download_manager::{BearerToken, DownloadManagerType};use serde::{Deserialize, Serialize};use crate::device::Device;@@ -13,6 +13,9 @@ pub struct Config {pub name: String,#[serde(default)]pub download_manager_type: DownloadManagerType,+ pub huggingface_url: String,+ #[serde(skip)]+ pub huggingface_api_key: Option<BearerToken>,}impl Config {@@ -21,12 +24,16 @@ impl Config {base_path: Option<PathBuf>,name: String,download_manager_type: DownloadManagerType,+ huggingface_url: String,+ huggingface_api_key: Option<BearerToken>,) -> Self {Self {device,base_path,name,download_manager_type,+ huggingface_url,+ huggingface_api_key,}}}diff --git a/crates/legacy/uzu/src/storage/mod.rs b/crates/legacy/uzu/src/storage/mod.rsindex 7ab896c32..2ccadd027 100644--- a/crates/legacy/uzu/src/storage/mod.rs+++ b/crates/legacy/uzu/src/storage/mod.rs@@ -4,6 +4,6 @@ mod model_tasks;mod storage;pub use config::Config;-pub use download_manager::{DownloadManagerType, DownloadPhase, DownloadState};+pub use download_manager::{BearerToken, DownloadManagerType, DownloadPhase, DownloadState};pub use error::StorageError;pub use storage::Storage;diff --git a/crates/legacy/uzu/src/storage/storage.rs b/crates/legacy/uzu/src/storage/storage.rsindex 2bbb47e1e..856ed463b 100644--- a/crates/legacy/uzu/src/storage/storage.rs+++ b/crates/legacy/uzu/src/storage/storage.rs@@ -1,11 +1,11 @@use std::{collections::HashMap, path::PathBuf, sync::Arc};-use download_manager::{DownloadManager, DownloadState, DownloadTask, DownloadTaskRequest};+use download_manager::{Checksum, DownloadManager, DownloadState, DownloadTask, DownloadTaskRequest};use futures_util::future::join_all;use kiban::{fs, rt::RuntimeHandle};use shoji::types::{- basic::File,- model::{Model, ModelAccessibility, ModelIdentifier, ModelReference},+ basic::{File, HashMethod},+ model::{Model, ModelAccessibility, ModelIdentifier, ModelSource},};use tokio::sync::{Mutex as TokioMutex,@@ -13,7 +13,10 @@ use tokio::sync::{};use tokio_stream::{StreamExt, wrappers::BroadcastStream};-use crate::storage::{Config, StorageError, model_tasks::ModelTasks};+use crate::{+ helpers::same_origin,+ storage::{Config, StorageError, model_tasks::ModelTasks},+};pub struct Storage {config: Config,@@ -49,12 +52,11 @@ impl Storage {&self,model: &Model,) -> Option<PathBuf> {- let reference_name = model.reference_name()?;let checkpoint_version = model.checkpoint_version()?;Some(Self::cache_path(&self.config).join("models")- .join(reference_name)+ .join("mirai").join(model.cache_identifier()).join(checkpoint_version),)@@ -66,8 +68,8 @@ impl Storage {) -> Result<(), StorageError> {let mut requests = HashMap::new();for model in models {- let ModelAccessibility::Local {- reference: ModelReference::Mirai {+ let ModelAccessibility::OnDevice {+ source: ModelSource::Registry {files,..},@@ -170,14 +172,29 @@ impl Storage {let subrequests = files.iter().map(|file| {- let crc32c = file.crc32c().ok_or_else(|| StorageError::HashNotFound {- identifier: model.identifier.clone(),- name: file.name.clone(),- })?;+ // Other origins reject a foreign bearer token: the Mirai CDN answers 401 to one.+ let bearer_token = self+ .config+ .huggingface_api_key+ .clone()+ .filter(|_| same_origin(&file.url, &self.config.huggingface_url));+ let checksum = file+ .hashes+ .first()+ .map(|hash| match hash.method {+ HashMethod::CRC32C => Checksum::Crc32c(hash.value.clone()),+ HashMethod::Sha256 => Checksum::Sha256(hash.value.clone()),+ HashMethod::GitBlobSha1 => Checksum::GitBlobSha1(hash.value.clone()),+ })+ .ok_or_else(|| StorageError::HashNotFound {+ identifier: model.identifier.clone(),+ name: file.name.clone(),+ })?;Ok(DownloadTaskRequest::file().destination(&file.name).source_url(&file.url)- .expected_crc32c(crc32c)+ .maybe_bearer_token(bearer_token)+ .expected_checksum(checksum).maybe_expected_bytes(u64::try_from(file.size).ok()).build())})diff --git a/crates/legacy/uzu/tests/common/test_storage.rs b/crates/legacy/uzu/tests/common/test_storage.rsindex 8345c8f1c..d5a279eb1 100644--- a/crates/legacy/uzu/tests/common/test_storage.rs+++ b/crates/legacy/uzu/tests/common/test_storage.rs@@ -4,7 +4,7 @@ use kiban::rt::RuntimeHandle;use shoji::types::model::Model;use uzu::{device::Device,- storage::{Config, DownloadManagerType, Storage},+ storage::{BearerToken, Config, DownloadManagerType, Storage},};pub struct TestStorage {@@ -17,6 +17,8 @@ impl TestStorage {tokio_handle: RuntimeHandle,models: Vec<Model>,download_manager_type: DownloadManagerType,+ huggingface_url: &str,+ huggingface_api_key: Option<&str>,) -> Result<Self, Box<dyn std::error::Error>> {let temp_dir_guard = tempfile::tempdir()?;let config = Config::new(@@ -24,6 +26,8 @@ impl TestStorage {Some(temp_dir_guard.path().to_path_buf()),"test_storage".to_string(),download_manager_type,+ huggingface_url.to_string(),+ huggingface_api_key.map(|token| BearerToken::from(token.to_string())),);let storage = Storage::new(tokio_handle, config).await?;storage.refresh(&models).await?;diff --git a/crates/legacy/uzu/tests/engine/shorthand.rs b/crates/legacy/uzu/tests/engine/shorthand.rsindex 68d634c75..d0b3692d8 100644--- a/crates/legacy/uzu/tests/engine/shorthand.rs+++ b/crates/legacy/uzu/tests/engine/shorthand.rs@@ -123,8 +123,8 @@ fn checkpoint(metadata: metadata(quantization_method),}),specializations: vec![],- accessibility: ModelAccessibility::Local {- reference: ModelReference::Mirai {+ accessibility: ModelAccessibility::OnDevice {+ source: ModelSource::Registry {toolchain_version: "test".to_string(),repository: None,source_repository: None,diff --git a/crates/legacy/uzu/tests/registry.rs b/crates/legacy/uzu/tests/registry.rsnew file mode 100644index 000000000..2341d94f4--- /dev/null+++ b/crates/legacy/uzu/tests/registry.rs@@ -0,0 +1,240 @@+#![cfg(not(target_family = "wasm"))]++use serde_json::{Value, json};+use uzu::{+ device::Device,+ registry::mirai::{Backend, HuggingFace, Registry},+ traits::Registry as RegistryTrait,+ types::{+ basic::{File, Hash, HashMethod, Repository},+ model::{Model, ModelAccessibility, ModelSource},+ },+};+use wiremock::{+ Mock, MockServer, ResponseTemplate,+ matchers::{method, path, query_param},+};++const REVISION: &str = "f5dec40ceb1d8c4b15f049bf5e185dd7be2cc150";+const HELLO_SHA256: &str = "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";+const HELLO_GIT_BLOB_SHA1: &str = "ce013625030ba8dba906f756967f9e9ca394464a";++fn repository(+ revision: &str,+ paths: Option<Vec<String>>,+) -> Repository {+ Repository {+ identifier: "trymirai/model".to_string(),+ commit_hash: Some(revision.to_string()),+ paths,+ }+}++fn siblings() -> Value {+ json!([+ { "rfilename": "config.json", "size": 6, "blobId": HELLO_GIT_BLOB_SHA1, "lfs": null },+ {+ "rfilename": "model.safetensors",+ "size": 6,+ "blobId": "0000000000000000000000000000000000000000",+ "lfs": { "sha256": HELLO_SHA256, "size": 6, "pointerSize": 134 }+ }+ ])+}++async fn mount_hugging_face(+ server: &MockServer,+ revision: &str,+ expected_calls: u64,+) {+ Mock::given(method("GET"))+ .and(path(format!("/api/models/trymirai/model/revision/{revision}")))+ .and(query_param("blobs", "true"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "sha": REVISION,+ "private": false,+ "gated": false,+ "siblings": siblings(),+ })))+ .expect(expected_calls)+ .mount(server)+ .await;+}++fn listed_model(+ identifier: &str,+ reference: Value,+) -> Value {+ json!({+ "id": identifier,+ "registry": { "id": "mirai", "metadata_id": "registry-meta" },+ "backends": [{ "id": "uzu", "version": "1", "metadata_id": "backend-meta" }],+ "family": null,+ "properties": null,+ "quantization": null,+ "specializations": [],+ "accessibility": { "type": "local", "reference": reference },+ "encodings": []+ })+}++#[tokio::test]+async fn hugging_face_files() -> Result<(), Box<dyn std::error::Error>> {+ let server = MockServer::start().await;+ mount_hugging_face(&server, REVISION, 2).await;+ mount_hugging_face(&server, "main", 1).await;+ let hugging_face = HuggingFace::builder().endpoint(server.uri()).build()?;++ let files = hugging_face.files(&repository(REVISION, None)).await?;+ assert_eq!(files.iter().map(|file| file.name.as_str()).collect::<Vec<_>>(), ["config.json", "model.safetensors"]);+ assert_eq!(files[0].url, format!("{}/trymirai/model/resolve/{REVISION}/config.json", server.uri()));+ assert_eq!(files[0].hashes[0].method, HashMethod::GitBlobSha1);+ assert_eq!(files[0].hashes[0].value, HELLO_GIT_BLOB_SHA1);+ assert_eq!(files[1].hashes[0].method, HashMethod::Sha256);+ assert_eq!(files[1].hashes[0].value, HELLO_SHA256);+ assert!(files.iter().all(|file| file.size == 6));++ let filtered = hugging_face.files(&repository(REVISION, Some(vec!["config.json".to_string()]))).await?;+ assert_eq!(filtered.len(), 1);++ let tagged = hugging_face.files(&repository("main", None)).await?;+ assert_eq!(tagged, files);++ let unpinned = hugging_face+ .files(&Repository {+ commit_hash: None,+ ..repository(REVISION, None)+ })+ .await;+ assert!(unpinned.is_err());+ Ok(())+}++#[tokio::test]+async fn hugging_face_rejects_bad_metadata() -> Result<(), Box<dyn std::error::Error>> {+ for body in [+ json!({ "sha": "main", "siblings": siblings() }),+ json!({ "sha": REVISION, "siblings": [{ "rfilename": "../config.json", "size": 6, "blobId": HELLO_GIT_BLOB_SHA1 }] }),+ json!({ "sha": REVISION, "siblings": [{ "rfilename": "config.json", "size": 6, "blobId": null }] }),+ json!({ "sha": REVISION, "siblings": [] }),+ ] {+ let server = MockServer::start().await;+ Mock::given(method("GET")).respond_with(ResponseTemplate::new(200).set_body_json(body)).mount(&server).await;+ let hugging_face = HuggingFace::builder().endpoint(server.uri()).build()?;+ assert!(hugging_face.files(&repository(REVISION, None)).await.is_err());+ }+ Ok(())+}++fn pinned(+ identifier: &str,+ revision: &str,+) -> Value {+ json!({+ "type": "mirai",+ "toolchain_version": "1",+ "repository": { "identifier": identifier, "commit_hash": revision, "paths": null },+ "source_repository": null,+ "files": []+ })+}++#[tokio::test]+async fn mirai_registry_resolves_pinned_models_once() -> Result<(), Box<dyn std::error::Error>> {+ let hugging_face = MockServer::start().await;+ mount_hugging_face(&hugging_face, REVISION, 1).await;+ mount_hugging_face(&hugging_face, "main", 2).await;+ let mirai = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/fetch/models"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "metadatas": [+ { "id": "registry-meta", "name": "Mirai", "description": null, "icons": [] },+ { "id": "backend-meta", "name": "Uzu", "description": null, "icons": [] }+ ],+ "models": [+ listed_model("pinned", pinned("trymirai/model", REVISION)),+ listed_model("tagged", pinned("trymirai/model", "main")),+ listed_model("unpinned", json!({+ "type": "mirai",+ "toolchain_version": "1",+ "repository": null,+ "source_repository": null,+ "files": [{+ "url": "https://assets.example/config.json",+ "name": "config.json",+ "size": 6,+ "hashes": [{ "method": "crc32c", "value": "AAAAAA==" }]+ }]+ })),+ listed_model("unresolvable", pinned("trymirai/missing", REVISION)),+ ]+ })))+ .mount(&mirai)+ .await;+ let directory = tempfile::tempdir()?;+ // A cache left by an older engine points the pinned files at the Mirai CDN; it must be re-resolved, not reused.+ let stale = Model::external(+ "pinned".to_string(),+ "mirai".to_string(),+ "Mirai".to_string(),+ "uzu".to_string(),+ "Uzu".to_string(),+ "1".to_string(),+ vec![],+ ModelAccessibility::OnDevice {+ source: ModelSource::Registry {+ toolchain_version: "1".to_string(),+ repository: Some(repository(REVISION, None)),+ source_repository: None,+ files: vec![File {+ url: "https://assets.example/model.safetensors".to_string(),+ name: "model.safetensors".to_string(),+ size: 6,+ hashes: vec![Hash {+ method: HashMethod::CRC32C,+ value: "AAAAAA==".to_string(),+ }],+ }],+ },+ },+ None,+ );+ std::fs::write(directory.path().join("registry.json"), serde_json::to_vec(&vec![stale])?)?;++ for _ in 0..2 {+ let registry = Registry::builder()+ .device(Device::new()?)+ .backends(vec![Backend {+ identifier: "uzu".to_string(),+ version: "1".to_string(),+ }])+ .cache_path(directory.path().to_path_buf())+ .registry_url(mirai.uri())+ .hugging_face_url(hugging_face.uri())+ .build()?;+ let models = registry.models().await?;+ assert_eq!(+ models.iter().map(|model| model.identifier.as_str()).collect::<Vec<_>>(),+ ["pinned", "tagged", "unpinned"]+ );+ for model in &models[..2] {+ let ModelAccessibility::OnDevice {+ source:+ ModelSource::Registry {+ repository: Some(repository),+ files,+ ..+ },+ } = &model.accessibility+ else {+ panic!("{} must stay on device", model.identifier);+ };+ assert_eq!(files.len(), 2);+ assert_eq!(files[1].hashes[0].method, HashMethod::Sha256);+ assert!(files.iter().all(|file| file.url.contains(REVISION)));+ assert_eq!(model.checkpoint_version(), repository.commit_hash);+ }+ }+ Ok(())+}diff --git a/crates/legacy/uzu/tests/storage.rs b/crates/legacy/uzu/tests/storage.rsindex 6e14447a1..2a7a20eac 100644--- a/crates/legacy/uzu/tests/storage.rs+++ b/crates/legacy/uzu/tests/storage.rs@@ -13,12 +13,25 @@ use tokio_stream::{StreamExt, wrappers::BroadcastStream};use uuid::Uuid;use uzu::{engine::Downloader,+ registry::mirai::HUGGING_FACE_URL,storage::{DownloadManagerType, DownloadPhase, DownloadState, Storage},- types::model::{ModelAccessibility, ModelIdentifier, ModelReference},+ types::{+ basic::{File, Hash, HashMethod, Repository},+ model::{Model, ModelAccessibility, ModelIdentifier, ModelSource},+ },+};+use wiremock::{+ Mock, MockServer, ResponseTemplate,+ matchers::{header, header_exists, method, path},};use crate::common::TestStorage;+const HELLO: &[u8] = b"hello\n";+const HELLO_SHA256: &str = "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";+const HELLO_GIT_BLOB_SHA1: &str = "ce013625030ba8dba906f756967f9e9ca394464a";+const REVISION: &str = "f5dec40ceb1d8c4b15f049bf5e185dd7be2cc150";+#[rstest]#[case::universal(DownloadManagerType::Universal)]#[cfg_attr(target_vendor = "apple", case::native(DownloadManagerType::Native))]@@ -26,7 +39,8 @@ use crate::common::TestStorage;async fn model_lifecycle(#[case] kind: DownloadManagerType) -> Result<(), Box<dyn std::error::Error>> {let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;let model = registry.models.first().ok_or("mock registry must include a model")?;- let test_storage = TestStorage::new(RuntimeHandle::current(), vec![model.clone()], kind).await?;+ let test_storage =+ TestStorage::new(RuntimeHandle::current(), vec![model.clone()], kind, HUGGING_FACE_URL, None).await?;let storage = &test_storage.storage;let identifier = model.identifier.clone();let cache_path = storage.cache_model_path(model).ok_or("model must have a cache path")?;@@ -52,7 +66,7 @@ async fn model_lifecycle(#[case] kind: DownloadManagerType) -> Result<(), Box<dyfor served in registry.files.iter() {let destination = cache_path.join(&served.file.name);assert_eq!(tokio::fs::read(&destination).await?, served.bytes.to_vec());- assert!(artifact_path(&destination, "crc").is_file());+ assert!(artifact_path(&destination, "checksum").is_file());}storage.delete(&identifier).await?;@@ -62,7 +76,7 @@ async fn model_lifecycle(#[case] kind: DownloadManagerType) -> Result<(), Box<dyfor served in registry.files.iter() {let destination = cache_path.join(&served.file.name);assert!(!destination.exists());- assert!(!artifact_path(&destination, "crc").exists());+ assert!(!artifact_path(&destination, "checksum").exists());}let served = registry.files.first().ok_or("mock registry must include files")?;@@ -82,8 +96,8 @@ async fn model_lifecycle(#[case] kind: DownloadManagerType) -> Result<(), Box<dyassert!(destination.exists());let mut changed = model.clone();- if let ModelAccessibility::Local {- reference: ModelReference::Mirai {+ if let ModelAccessibility::OnDevice {+ source: ModelSource::Registry {files,..},@@ -107,7 +121,8 @@ async fn model_lifecycle(#[case] kind: DownloadManagerType) -> Result<(), Box<dyasync fn downloader_streams(#[case] kind: DownloadManagerType) -> Result<(), Box<dyn std::error::Error>> {let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;let model = registry.models.first().ok_or("mock registry must include a model")?;- let test_storage = TestStorage::new(RuntimeHandle::current(), vec![model.clone()], kind).await?;+ let test_storage =+ TestStorage::new(RuntimeHandle::current(), vec![model.clone()], kind, HUGGING_FACE_URL, None).await?;let storage = Arc::clone(&test_storage.storage);let identifier = model.identifier.clone();let downloader = Downloader::new(identifier.clone(), Arc::clone(&storage));@@ -138,6 +153,97 @@ async fn downloader_streams(#[case] kind: DownloadManagerType) -> Result<(), BoxOk(())}+#[rstest]+#[case::universal(DownloadManagerType::Universal)]+#[cfg_attr(target_vendor = "apple", case::native(DownloadManagerType::Native))]+#[tokio::test(flavor = "multi_thread")]+async fn hugging_face_model(#[case] kind: DownloadManagerType) -> Result<(), Box<dyn std::error::Error>> {+ let hugging_face = MockServer::start().await;+ let route = format!("/trymirai/model/resolve/{REVISION}/model.safetensors");+ Mock::given(method("GET"))+ .and(path(route.clone()))+ .and(header("authorization", "Bearer hf_test"))+ .respond_with(ResponseTemplate::new(200).set_body_bytes(HELLO))+ .mount(&hugging_face)+ .await;+ // Like the Mirai CDN, this origin rejects any bearer token, so its file must download anonymously.+ let cdn = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/config.json"))+ .and(header_exists("authorization"))+ .respond_with(ResponseTemplate::new(401))+ .with_priority(1)+ .mount(&cdn)+ .await;+ Mock::given(method("GET"))+ .and(path("/config.json"))+ .respond_with(ResponseTemplate::new(200).set_body_bytes(HELLO))+ .mount(&cdn)+ .await;+ let files = vec![+ File {+ url: format!("{}/config.json", cdn.uri()),+ name: "config.json".to_string(),+ size: HELLO.len() as i64,+ hashes: vec![Hash {+ method: HashMethod::GitBlobSha1,+ value: HELLO_GIT_BLOB_SHA1.to_string(),+ }],+ },+ File {+ url: format!("{}{route}", hugging_face.uri()),+ name: "model.safetensors".to_string(),+ size: HELLO.len() as i64,+ hashes: vec![Hash {+ method: HashMethod::Sha256,+ value: HELLO_SHA256.to_string(),+ }],+ },+ ];+ let model = Model::external(+ "pinned".to_string(),+ "mirai".to_string(),+ "Mirai".to_string(),+ "uzu".to_string(),+ "Uzu".to_string(),+ "1".to_string(),+ vec![],+ ModelAccessibility::OnDevice {+ source: ModelSource::Registry {+ toolchain_version: "1".to_string(),+ repository: Some(Repository {+ identifier: "trymirai/model".to_string(),+ commit_hash: Some(REVISION.to_string()),+ paths: None,+ }),+ source_repository: None,+ files,+ },+ },+ None,+ );+ let test_storage =+ TestStorage::new(RuntimeHandle::current(), vec![model.clone()], kind, &hugging_face.uri(), Some("hf_test"))+ .await?;+ let storage = &test_storage.storage;+ let cache_path = storage.cache_model_path(&model).ok_or("model must have a cache path")?;+ assert_eq!(cache_path.file_name().and_then(|name| name.to_str()), Some(REVISION));+ let mut events = storage.subscribe();++ storage.download(&model.identifier).await?;+ let state = wait_for(storage, &model.identifier, &mut events, |state| {+ matches!(state.phase, DownloadPhase::Downloaded {} | DownloadPhase::Error { .. })+ })+ .await;+ assert!(matches!(state.phase, DownloadPhase::Downloaded {}), "got {:?}", state.phase);+ for name in ["config.json", "model.safetensors"] {+ let destination = cache_path.join(name);+ assert_eq!(tokio::fs::read(&destination).await?, HELLO);+ assert!(artifact_path(&destination, "checksum").is_file());+ }+ Ok(())+}+async fn wait_for(storage: &Storage,identifier: &ModelIdentifier,