π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
add common things
Prateek Sunal8056b3917ef3
diff --git a/rust/inference_rs/Cargo.toml b/rust/inference_rs/Cargo.tomlnew file mode 100644index 0000000000..d6823dc19f--- /dev/null+++ b/rust/inference_rs/Cargo.toml@@ -0,0 +1,22 @@+[package]+name = "inference_rs"+version = "0.1.0"+edition = "2024"++[lib]+name = "inference_rs"+crate-type = ["rlib"]++[dependencies]+llama-cpp-sys-2 = { version = "=0.1.131", features = ["mtmd"] }+parking_lot = "0.12"+self_cell = "1"+serde = { version = "1", features = ["derive"] }+serde_json = "1"+thiserror = "1"++[target.'cfg(target_os = "macos")'.dependencies]+llama-cpp-2 = { version = "=0.1.131", default-features = false, features = ["mtmd"] }++[target.'cfg(not(target_os = "macos"))'.dependencies]+llama-cpp-2 = { version = "=0.1.131", features = ["mtmd"] }diff --git a/rust/inference_rs/src/api.rs b/rust/inference_rs/src/api.rsnew file mode 100644index 0000000000..f6ba6da037--- /dev/null+++ b/rust/inference_rs/src/api.rs@@ -0,0 +1,1024 @@+use llama_cpp_2::context::LlamaContext;+use llama_cpp_2::context::params::LlamaContextParams;+use llama_cpp_2::llama_backend::LlamaBackend;+use llama_cpp_2::llama_batch::LlamaBatch;+use llama_cpp_2::model::{AddBos, LlamaChatMessage, LlamaChatTemplate, LlamaModel, Special};+use llama_cpp_2::mtmd::{+ MtmdBitmap, MtmdContext, MtmdContextParams, MtmdInputText, mtmd_default_marker,+};+use llama_cpp_2::sampling::LlamaSampler;+use llama_cpp_2::token::LlamaToken;+use llama_cpp_sys_2::{+ GGML_LOG_LEVEL_ERROR, GGML_LOG_LEVEL_WARN, ggml_log_level, mtmd_helper_log_set,+};+use parking_lot::Mutex;+use self_cell::self_cell;+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::ffi::{CStr, CString};+use std::num::NonZeroU32;+use std::panic::{AssertUnwindSafe, catch_unwind};+use std::path::Path;+use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};+use std::sync::{Arc, OnceLock};+use std::time::Instant;++pub type JobId = i64;++pub trait EventSink {+ fn add(&mut self, event: GenerateEvent);+}++impl<F> EventSink for F+where+ F: FnMut(GenerateEvent),+{+ fn add(&mut self, event: GenerateEvent) {+ (self)(event);+ }+}++static BACKEND: OnceLock<Result<LlamaBackend, String>> = OnceLock::new();+static JOB_COUNTER: AtomicI64 = AtomicI64::new(1);+static CANCEL_FLAGS: OnceLock<Mutex<HashMap<JobId, Arc<AtomicBool>>>> = OnceLock::new();+static MTMD_LOG_BUFFER: OnceLock<Mutex<String>> = OnceLock::new();+static MTMD_LOG_HOOK: OnceLock<()> = OnceLock::new();++fn backend() -> Result<&'static LlamaBackend, String> {+ match BACKEND.get_or_init(|| LlamaBackend::init().map_err(|err| err.to_string())) {+ Ok(backend) => Ok(backend),+ Err(err) => Err(format!("Failed to initialize backend: {err}")),+ }+}++fn cancel_flags() -> &'static Mutex<HashMap<JobId, Arc<AtomicBool>>> {+ CANCEL_FLAGS.get_or_init(|| Mutex::new(HashMap::new()))+}++fn mtmd_log_buffer() -> &'static Mutex<String> {+ MTMD_LOG_BUFFER.get_or_init(|| Mutex::new(String::new()))+}++unsafe extern "C" fn mtmd_log_callback(+ level: ggml_log_level,+ text: *const ::std::os::raw::c_char,+ _user_data: *mut ::std::os::raw::c_void,+) {+ if text.is_null() {+ return;+ }+ if level != GGML_LOG_LEVEL_WARN && level != GGML_LOG_LEVEL_ERROR {+ return;+ }+ let cstr = unsafe { CStr::from_ptr(text) };+ if let Ok(message) = cstr.to_str() {+ let mut guard = mtmd_log_buffer().lock();+ guard.push_str(message);+ const MAX_LEN: usize = 8192;+ if guard.len() > MAX_LEN {+ let drain = guard.len() - MAX_LEN;+ guard.drain(..drain);+ }+ }+}++fn init_mtmd_logging() {+ MTMD_LOG_HOOK.get_or_init(|| unsafe {+ mtmd_helper_log_set(Some(mtmd_log_callback), std::ptr::null_mut());+ });+}++fn take_mtmd_logs() -> String {+ let mut guard = mtmd_log_buffer().lock();+ let logs = guard.clone();+ guard.clear();+ logs+}++fn register_job() -> (JobId, Arc<AtomicBool>) {+ let job_id = JOB_COUNTER.fetch_add(1, Ordering::Relaxed);+ let flag = Arc::new(AtomicBool::new(false));+ cancel_flags().lock().insert(job_id, flag.clone());+ (job_id, flag)+}++struct JobGuard(JobId);++impl Drop for JobGuard {+ fn drop(&mut self) {+ cancel_flags().lock().remove(&self.0);+ }+}++fn format_error(context: &str, err: impl std::fmt::Display) -> String {+ format!("{context}: {err}")+}++fn build_chat_prompt(+ model: &LlamaModel,+ messages: Vec<ChatMessage>,+ template_override: Option<String>,+ add_assistant: bool,+) -> Result<String, String> {+ let template = match template_override {+ Some(template) => LlamaChatTemplate::new(&template)+ .map_err(|err| format_error("Invalid chat template", err))?,+ None => model+ .chat_template(None)+ .or_else(|_| LlamaChatTemplate::new("chatml"))+ .map_err(|err| format_error("Failed to load chat template", err))?,+ };++ let chat_messages = messages+ .into_iter()+ .map(|message| {+ LlamaChatMessage::new(message.role, message.content)+ .map_err(|err| format_error("Invalid chat message", err))+ })+ .collect::<Result<Vec<_>, String>>()?;++ model+ .apply_chat_template(&template, &chat_messages, add_assistant)+ .map_err(|err| format_error("Failed to apply chat template", err))+}++fn should_add_bos(model: &LlamaModel, prompt: &str) -> AddBos {+ if let Ok(bos) = model.token_to_str(model.token_bos(), Special::Tokenize)+ && !bos.is_empty()+ && prompt.starts_with(&bos)+ {+ return AddBos::Never;+ }+ AddBos::Always+}++fn find_stop_index(text: &str, stop_sequences: &[String], start: usize) -> Option<usize> {+ let mut found: Option<usize> = None;+ let search = &text[start.min(text.len())..];++ for stop in stop_sequences {+ if stop.is_empty() {+ continue;+ }+ if let Some(idx) = search.find(stop) {+ let idx = start + idx;+ found = match found {+ Some(existing) if existing <= idx => Some(existing),+ _ => Some(idx),+ };+ }+ }++ found+}++#[allow(clippy::too_many_arguments)]+fn run_generation_loop(+ ctx: &mut LlamaContext,+ sampler: &mut LlamaSampler,+ cancel_flag: &AtomicBool,+ sink: &mut dyn EventSink,+ job_id: JobId,+ max_tokens: usize,+ stop_sequences: &[String],+ max_stop_len: usize,+ generated_tokens_count: &mut i32,+ mut pos: i32,+ mut logits_index: i32,+) -> Result<(), String> {+ let mut generated_text = String::new();+ let n_ctx = ctx.n_ctx();++ for _ in 0..max_tokens {+ if cancel_flag.load(Ordering::Relaxed) {+ return Err("Generation cancelled".to_string());+ }+ if pos >= n_ctx as i32 {+ break;+ }++ let token = sampler.sample(ctx, logits_index);+ sampler.accept(token);+ *generated_tokens_count = generated_tokens_count.saturating_add(1);++ if ctx.model.is_eog_token(token) {+ break;+ }++ let piece = ctx+ .model+ .token_to_str(token, Special::Tokenize)+ .map_err(|err| format_error("Detokenize failed", err))?;++ if !piece.is_empty() {+ let prev_len = generated_text.len();+ generated_text.push_str(&piece);++ if max_stop_len > 0 {+ let search_start = prev_len.saturating_sub(max_stop_len);+ if let Some(stop_index) =+ find_stop_index(&generated_text, stop_sequences, search_start)+ {+ let new_piece = &generated_text[prev_len..stop_index];+ if !new_piece.is_empty() {+ sink.add(GenerateEvent::Text {+ job_id,+ text: new_piece.to_string(),+ token_id: Some(token.0),+ });+ }+ generated_text.truncate(stop_index);+ break;+ }+ }++ sink.add(GenerateEvent::Text {+ job_id,+ text: piece,+ token_id: Some(token.0),+ });+ }++ let mut step_batch = LlamaBatch::new(1, 1);+ step_batch+ .add(token, pos, &[0], true)+ .map_err(|err| format_error("Failed to add token", err))?;+ ctx.decode(&mut step_batch)+ .map_err(|err| format_error("Decode failed", err))?;++ logits_index = 0;+ pos += 1;+ }++ Ok(())+}++fn build_sampler(model: &LlamaModel, request: &GenerateRequest) -> Result<LlamaSampler, String> {+ let mut samplers = Vec::new();++ let mut repeat_penalty = request.repeat_penalty.unwrap_or(1.0);+ if repeat_penalty <= 0.0 {+ repeat_penalty = 1.0;+ }+ let mut frequency_penalty = request.frequency_penalty.unwrap_or(0.0);+ if frequency_penalty < 0.0 {+ frequency_penalty = 0.0;+ }+ let mut presence_penalty = request.presence_penalty.unwrap_or(0.0);+ if presence_penalty < 0.0 {+ presence_penalty = 0.0;+ }++ if (repeat_penalty - 1.0).abs() > f32::EPSILON+ || frequency_penalty != 0.0+ || presence_penalty != 0.0+ {+ samplers.push(LlamaSampler::penalties(+ -1,+ repeat_penalty,+ frequency_penalty,+ presence_penalty,+ ));+ }++ if let Some(grammar) = request.grammar.as_deref() {+ samplers.push(+ LlamaSampler::grammar(model, grammar, "root")+ .map_err(|err| format_error("Invalid grammar", err))?,+ );+ }++ if let Some(top_k) = request.top_k+ && top_k > 0+ {+ samplers.push(LlamaSampler::top_k(top_k));+ }++ if let Some(top_p) = request.top_p+ && top_p > 0.0+ && top_p < 1.0+ {+ samplers.push(LlamaSampler::top_p(top_p, 1));+ }++ let temperature = request.temperature.unwrap_or(1.0);+ if temperature > 0.0 {+ samplers.push(LlamaSampler::temp(temperature));+ let seed = request.seed.unwrap_or(0);+ let seed = u32::try_from(seed).unwrap_or(0);+ samplers.push(LlamaSampler::dist(seed));+ } else {+ samplers.push(LlamaSampler::greedy());+ }++ Ok(LlamaSampler::chain_simple(samplers))+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ModelLoadParams {+ pub model_path: String,+ pub n_gpu_layers: Option<i32>,+ pub use_mmap: Option<bool>,+ pub use_mlock: Option<bool>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ContextParams {+ pub context_size: Option<i32>,+ pub n_threads: Option<i32>,+ pub n_batch: Option<i32>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ModelInfo {+ pub bos_token_id: Option<i32>,+ pub eos_token_id: Option<i32>,+ pub bos_token: Option<String>,+ pub eos_token: Option<String>,+ pub chat_template: Option<String>,+ pub metadata_json: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ChatMessage {+ pub role: String,+ pub content: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct GenerateRequest {+ pub prompt: String,+ pub max_tokens: Option<i32>,+ pub temperature: Option<f32>,+ pub top_p: Option<f32>,+ pub top_k: Option<i32>,+ pub repeat_penalty: Option<f32>,+ pub frequency_penalty: Option<f32>,+ pub presence_penalty: Option<f32>,+ pub seed: Option<i64>,+ pub stop_sequences: Option<Vec<String>>,+ pub grammar: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct GenerateChatRequest {+ pub messages: Vec<ChatMessage>,+ pub template_override: Option<String>,+ pub add_assistant: Option<bool>,+ pub image_paths: Option<Vec<String>>,+ pub mmproj_path: Option<String>,+ pub media_marker: Option<String>,+ pub max_tokens: Option<i32>,+ pub temperature: Option<f32>,+ pub top_p: Option<f32>,+ pub top_k: Option<i32>,+ pub repeat_penalty: Option<f32>,+ pub frequency_penalty: Option<f32>,+ pub presence_penalty: Option<f32>,+ pub seed: Option<i64>,+ pub stop_sequences: Option<Vec<String>>,+ pub grammar: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct GenerateSummary {+ pub job_id: JobId,+ pub prompt_tokens: Option<i32>,+ pub generated_tokens: Option<i32>,+ pub total_time_ms: Option<i64>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub enum GenerateEvent {+ Text {+ job_id: JobId,+ text: String,+ token_id: Option<i32>,+ },+ Done {+ summary: GenerateSummary,+ },+ Error {+ job_id: JobId,+ message: String,+ },+}++pub struct ModelHandle {+ model: LlamaModel,+}++pub type ModelHandleRef = Arc<ModelHandle>;++impl ModelHandle {+ fn model(&self) -> &LlamaModel {+ &self.model+ }+}++self_cell!(+ struct ContextHandleCell {+ owner: ModelHandleRef,++ #[covariant]+ dependent: LlamaContext,+ }+);++pub struct ContextHandle(Mutex<ContextHandleCell>);++pub type ContextHandleRef = Arc<ContextHandle>;++unsafe impl Send for ContextHandle {}+unsafe impl Sync for ContextHandle {}++impl ContextHandle {+ fn try_new(+ owner: ModelHandleRef,+ builder: impl for<'a> FnOnce(&'a ModelHandleRef) -> Result<LlamaContext<'a>, String>,+ ) -> Result<Self, String> {+ ContextHandleCell::try_new(owner, builder).map(|cell| ContextHandle(Mutex::new(cell)))+ }++ fn with_context_mut<R>(+ &self,+ func: impl for<'a, 'b> FnOnce(&'b mut LlamaContext<'a>) -> R,+ ) -> R {+ let mut guard = self.0.lock();+ guard.with_dependent_mut(|_owner, context| func(context))+ }+}++pub fn init_backend() -> Result<(), String> {+ backend().map(|_| ())+}++pub fn load_model(params: ModelLoadParams) -> Result<ModelHandleRef, String> {+ let backend = backend()?;+ let mut model_params = llama_cpp_2::model::params::LlamaModelParams::default();++ if let Some(n_gpu_layers) = params.n_gpu_layers {+ let layers =+ u32::try_from(n_gpu_layers).map_err(|_| "n_gpu_layers must be >= 0".to_string())?;+ model_params = model_params.with_n_gpu_layers(layers);+ }++ if let Some(use_mlock) = params.use_mlock {+ model_params = model_params.with_use_mlock(use_mlock);+ }++ let model = LlamaModel::load_from_file(backend, Path::new(¶ms.model_path), &model_params)+ .map_err(|err| format_error("Failed to load model", err))?;++ Ok(Arc::new(ModelHandle { model }))+}++pub fn create_context(+ model: ModelHandleRef,+ params: ContextParams,+) -> Result<ContextHandleRef, String> {+ let mut context_params = LlamaContextParams::default();++ if let Some(context_size) = params.context_size {+ let context_size =+ u32::try_from(context_size).map_err(|_| "context_size must be > 0".to_string())?;+ let context_size =+ NonZeroU32::new(context_size).ok_or_else(|| "context_size must be > 0".to_string())?;+ context_params = context_params.with_n_ctx(Some(context_size));+ }++ if let Some(n_threads) = params.n_threads {+ if n_threads <= 0 {+ return Err("n_threads must be > 0".to_string());+ }+ context_params = context_params+ .with_n_threads(n_threads)+ .with_n_threads_batch(n_threads);+ }++ if let Some(n_batch) = params.n_batch {+ let n_batch = u32::try_from(n_batch).map_err(|_| "n_batch must be > 0".to_string())?;+ context_params = context_params.with_n_batch(n_batch);+ }++ let context = ContextHandle::try_new(model, |model| {+ let backend = backend()?;+ model+ .model()+ .new_context(backend, context_params)+ .map_err(|err| format_error("Failed to create context", err))+ })?;++ Ok(Arc::new(context))+}++pub fn tokenize(+ model: &ModelHandle,+ text: String,+ add_bos: bool,+ special: bool,+) -> Result<Vec<i32>, String> {+ let add_bos = if add_bos {+ AddBos::Always+ } else {+ AddBos::Never+ };+ let _ = special;++ let tokens = model+ .model()+ .str_to_token(&text, add_bos)+ .map_err(|err| format_error("Tokenize failed", err))?;++ Ok(tokens.into_iter().map(|token| token.0).collect())+}++pub fn detokenize(model: &ModelHandle, tokens: Vec<i32>) -> Result<String, String> {+ let tokens = tokens.into_iter().map(LlamaToken::new).collect::<Vec<_>>();+ model+ .model()+ .tokens_to_str(&tokens, Special::Tokenize)+ .map_err(|err| format_error("Detokenize failed", err))+}++pub fn get_model_info(model: &ModelHandle) -> Result<ModelInfo, String> {+ let model_ref = model.model();+ let bos_token = model_ref.token_bos();+ let eos_token = model_ref.token_eos();++ let bos_token_str = model_ref+ .token_to_str(bos_token, Special::Tokenize)+ .ok()+ .filter(|value| !value.is_empty());+ let eos_token_str = model_ref+ .token_to_str(eos_token, Special::Tokenize)+ .ok()+ .filter(|value| !value.is_empty());++ let chat_template = model_ref+ .chat_template(None)+ .ok()+ .and_then(|tmpl| tmpl.to_string().ok());++ let meta_count = model_ref.meta_count();+ let mut metadata_json = None;++ if meta_count > 0 {+ let mut map = serde_json::Map::new();+ for index in 0..meta_count {+ let key = model_ref+ .meta_key_by_index(index)+ .map_err(|err| format_error("Failed to read metadata key", err))?;+ let value = model_ref+ .meta_val_str_by_index(index)+ .map_err(|err| format_error("Failed to read metadata value", err))?;+ map.insert(key, serde_json::Value::String(value));+ }+ if !map.is_empty() {+ metadata_json = Some(serde_json::Value::Object(map).to_string());+ }+ }++ Ok(ModelInfo {+ bos_token_id: Some(bos_token.0),+ eos_token_id: Some(eos_token.0),+ bos_token: bos_token_str,+ eos_token: eos_token_str,+ chat_template,+ metadata_json,+ })+}++pub fn apply_chat_template(+ model: &ModelHandle,+ messages: Vec<ChatMessage>,+ template_override: Option<String>,+ add_assistant: bool,+) -> Result<String, String> {+ build_chat_prompt(model.model(), messages, template_override, add_assistant)+}++pub fn generate_chat_stream(+ context: &ContextHandle,+ request: GenerateChatRequest,+ sink: &mut dyn EventSink,+) -> Result<GenerateSummary, String> {+ let GenerateChatRequest {+ messages,+ template_override,+ add_assistant,+ image_paths,+ mmproj_path,+ media_marker,+ max_tokens,+ temperature,+ top_p,+ top_k,+ repeat_penalty,+ frequency_penalty,+ presence_penalty,+ seed,+ stop_sequences,+ grammar,+ } = request;++ let (job_id, cancel_flag) = register_job();+ let _job_guard = JobGuard(job_id);+ let start = Instant::now();++ let max_tokens = max_tokens.unwrap_or(128);+ let max_tokens = usize::try_from(max_tokens.max(0)).unwrap_or(0);+ let stop_sequences = stop_sequences.unwrap_or_default();+ let max_stop_len = stop_sequences.iter().map(|s| s.len()).max().unwrap_or(0);++ let mut prompt_tokens_count: i32 = 0;+ let mut generated_tokens_count: i32 = 0;+ let mut error_message: Option<String> = None;++ let result = match catch_unwind(AssertUnwindSafe(|| {+ context.with_context_mut(|ctx| -> Result<(), String> {+ let add_assistant = add_assistant.unwrap_or(true);+ let mut messages = messages;+ let image_paths = image_paths.unwrap_or_default();+ let marker = media_marker+ .clone()+ .unwrap_or_else(|| mtmd_default_marker().to_string());++ if !image_paths.is_empty() {+ let mut marker_count = messages+ .iter()+ .map(|message| message.content.matches(&marker).count())+ .sum::<usize>();+ if marker_count == 0 {+ let target_index = messages+ .iter()+ .rposition(|message| message.role == "user")+ .or_else(|| messages.len().checked_sub(1))+ .ok_or_else(|| "No chat messages provided".to_string())?;+ if !messages[target_index].content.ends_with('\n') {+ messages[target_index].content.push('\n');+ }+ messages[target_index].content.push_str(&marker);+ marker_count = messages+ .iter()+ .map(|message| message.content.matches(&marker).count())+ .sum();+ }+ if marker_count != image_paths.len() {+ return Err(format!(+ "Found {marker_count} media markers but {} images were provided",+ image_paths.len()+ ));+ }+ }++ let prompt = build_chat_prompt(ctx.model, messages, template_override, add_assistant)?;++ let sampler_request = GenerateRequest {+ prompt: prompt.clone(),+ max_tokens: None,+ temperature,+ top_p,+ top_k,+ repeat_penalty,+ frequency_penalty,+ presence_penalty,+ seed,+ stop_sequences: Some(stop_sequences.clone()),+ grammar: grammar.clone(),+ };++ if image_paths.is_empty() {+ let add_bos = should_add_bos(ctx.model, &prompt);+ let prompt_tokens = ctx+ .model+ .str_to_token(&prompt, add_bos)+ .map_err(|err| format_error("Tokenize failed", err))?;++ if prompt_tokens.is_empty() {+ return Err("Prompt produced no tokens".to_string());+ }++ prompt_tokens_count = i32::try_from(prompt_tokens.len())+ .map_err(|_| "Prompt is too long".to_string())?;++ let n_ctx = ctx.n_ctx();+ if prompt_tokens.len() as u32 > n_ctx {+ return Err(format!(+ "Prompt length {} exceeds context size {}",+ prompt_tokens.len(),+ n_ctx+ ));+ }++ let n_batch = ctx.n_batch() as usize;+ if n_batch == 0 {+ return Err("Context batch size is 0".to_string());+ }++ ctx.clear_kv_cache();++ let mut token_offset = 0usize;+ let mut logits_index: i32 = 0;+ while token_offset < prompt_tokens.len() {+ let end = (token_offset + n_batch).min(prompt_tokens.len());+ let chunk = &prompt_tokens[token_offset..end];+ let mut batch = LlamaBatch::new(chunk.len(), 1);+ for (idx, token) in chunk.iter().enumerate() {+ let pos = (token_offset + idx) as i32;+ let logits = token_offset + idx + 1 == prompt_tokens.len();+ batch+ .add(*token, pos, &[0], logits)+ .map_err(|err| format_error("Failed to add prompt token", err))?;+ }+ ctx.decode(&mut batch)+ .map_err(|err| format_error("Prompt decode failed", err))?;+ if end == prompt_tokens.len() {+ logits_index = (chunk.len() - 1) as i32;+ }+ token_offset = end;+ }++ let mut sampler = build_sampler(ctx.model, &sampler_request)?;+ sampler.accept_many(prompt_tokens.iter());++ let pos = prompt_tokens.len() as i32;+ run_generation_loop(+ ctx,+ &mut sampler,+ &cancel_flag,+ sink,+ job_id,+ max_tokens,+ &stop_sequences,+ max_stop_len,+ &mut generated_tokens_count,+ pos,+ logits_index,+ )?;++ return Ok(());+ }++ let mmproj_path = mmproj_path.ok_or_else(|| {+ "mmproj_path is required when image_paths are provided".to_string()+ })?;+ if !Path::new(&mmproj_path).exists() {+ return Err(format!("mmproj file not found at {mmproj_path}"));+ }++ init_mtmd_logging();+ take_mtmd_logs();++ let media_marker = CString::new(marker.clone())+ .map_err(|err| format_error("Invalid media marker", err))?;+ let mtmd_params = MtmdContextParams {+ use_gpu: false,+ print_timings: false,+ media_marker,+ ..Default::default()+ };++ let mtmd_ctx = MtmdContext::init_from_file(&mmproj_path, ctx.model, &mtmd_params)+ .map_err(|err| {+ let logs = take_mtmd_logs();+ if logs.trim().is_empty() {+ format_error("Failed to initialize mmproj", err)+ } else {+ format!("Failed to initialize mmproj: {err}. Logs: {logs}")+ }+ })?;++ if !mtmd_ctx.support_vision() {+ return Err("Model does not support vision input".to_string());+ }++ let mut bitmaps = Vec::with_capacity(image_paths.len());+ for image_path in &image_paths {+ if !Path::new(image_path).exists() {+ return Err(format!("Image file not found at {image_path}"));+ }+ let bitmap = MtmdBitmap::from_file(&mtmd_ctx, image_path)+ .map_err(|err| format_error("Failed to load image", err))?;+ if bitmap.is_audio() {+ return Err("Audio inputs are not supported".to_string());+ }+ bitmaps.push(bitmap);+ }+ let bitmap_refs = bitmaps.iter().collect::<Vec<_>>();++ let add_special = matches!(should_add_bos(ctx.model, &prompt), AddBos::Always);+ let input_text = MtmdInputText {+ text: prompt,+ add_special,+ parse_special: true,+ };++ let chunks = mtmd_ctx+ .tokenize(input_text, &bitmap_refs)+ .map_err(|err| format_error("Failed to tokenize multimodal input", err))?;++ if chunks.is_empty() {+ return Err("Prompt produced no tokens".to_string());+ }++ prompt_tokens_count = i32::try_from(chunks.total_tokens())+ .map_err(|_| "Prompt is too long".to_string())?;++ let n_ctx = ctx.n_ctx();+ let total_positions = chunks.total_positions();+ if total_positions as u32 > n_ctx {+ return Err(format!(+ "Prompt length {} exceeds context size {}",+ total_positions, n_ctx+ ));+ }++ let n_batch = ctx.n_batch() as i32;+ if n_batch <= 0 {+ return Err("Context batch size is 0".to_string());+ }++ ctx.clear_kv_cache();++ let n_past = chunks+ .eval_chunks(&mtmd_ctx, ctx, 0, 0, n_batch, true)+ .map_err(|err| format_error("Failed to evaluate multimodal prompt", err))?;++ let mut sampler = build_sampler(ctx.model, &sampler_request)?;+ let mut prompt_tokens = Vec::new();+ for index in 0..chunks.len() {+ if let Some(chunk) = chunks.get(index)+ && let Some(tokens) = chunk.text_tokens()+ {+ prompt_tokens.extend_from_slice(tokens);+ }+ }+ sampler.accept_many(prompt_tokens.iter());++ run_generation_loop(+ ctx,+ &mut sampler,+ &cancel_flag,+ sink,+ job_id,+ max_tokens,+ &stop_sequences,+ max_stop_len,+ &mut generated_tokens_count,+ n_past,+ -1,+ )?;++ Ok(())+ })+ })) {+ Ok(inner) => inner,+ Err(_) => Err("Generation panicked".to_string()),+ };++ if let Err(err) = result {+ error_message = Some(err);+ }++ let summary = GenerateSummary {+ job_id,+ prompt_tokens: Some(prompt_tokens_count),+ generated_tokens: Some(generated_tokens_count),+ total_time_ms: Some(start.elapsed().as_millis() as i64),+ };++ if let Some(message) = error_message {+ sink.add(GenerateEvent::Error { job_id, message });+ }++ sink.add(GenerateEvent::Done {+ summary: summary.clone(),+ });++ Ok(summary)+}++pub fn generate_stream(+ context: &ContextHandle,+ request: GenerateRequest,+ sink: &mut dyn EventSink,+) -> Result<GenerateSummary, String> {+ let (job_id, cancel_flag) = register_job();+ let _job_guard = JobGuard(job_id);+ let start = Instant::now();++ let max_tokens = request.max_tokens.unwrap_or(128);+ let max_tokens = usize::try_from(max_tokens.max(0)).unwrap_or(0);+ let stop_sequences = request.stop_sequences.clone().unwrap_or_default();+ let max_stop_len = stop_sequences.iter().map(|s| s.len()).max().unwrap_or(0);++ let mut prompt_tokens_count: i32 = 0;+ let mut generated_tokens_count: i32 = 0;+ let mut error_message: Option<String> = None;++ let result = match catch_unwind(AssertUnwindSafe(|| {+ context.with_context_mut(|ctx| -> Result<(), String> {+ let add_bos = should_add_bos(ctx.model, &request.prompt);+ let prompt_tokens = ctx+ .model+ .str_to_token(&request.prompt, add_bos)+ .map_err(|err| format_error("Tokenize failed", err))?;++ if prompt_tokens.is_empty() {+ return Err("Prompt produced no tokens".to_string());+ }++ prompt_tokens_count =+ i32::try_from(prompt_tokens.len()).map_err(|_| "Prompt is too long".to_string())?;++ let n_ctx = ctx.n_ctx();+ if prompt_tokens.len() as u32 > n_ctx {+ return Err(format!(+ "Prompt length {} exceeds context size {}",+ prompt_tokens.len(),+ n_ctx+ ));+ }++ let n_batch = ctx.n_batch() as usize;+ if n_batch == 0 {+ return Err("Context batch size is 0".to_string());+ }++ ctx.clear_kv_cache();++ let mut token_offset = 0usize;+ let mut logits_index: i32 = 0;+ while token_offset < prompt_tokens.len() {+ let end = (token_offset + n_batch).min(prompt_tokens.len());+ let chunk = &prompt_tokens[token_offset..end];+ let mut batch = LlamaBatch::new(chunk.len(), 1);+ for (idx, token) in chunk.iter().enumerate() {+ let pos = (token_offset + idx) as i32;+ let logits = token_offset + idx + 1 == prompt_tokens.len();+ batch+ .add(*token, pos, &[0], logits)+ .map_err(|err| format_error("Failed to add prompt token", err))?;+ }+ ctx.decode(&mut batch)+ .map_err(|err| format_error("Prompt decode failed", err))?;+ if end == prompt_tokens.len() {+ logits_index = (chunk.len() - 1) as i32;+ }+ token_offset = end;+ }++ let mut sampler = build_sampler(ctx.model, &request)?;+ sampler.accept_many(prompt_tokens.iter());++ let pos = prompt_tokens.len() as i32;+ run_generation_loop(+ ctx,+ &mut sampler,+ &cancel_flag,+ sink,+ job_id,+ max_tokens,+ &stop_sequences,+ max_stop_len,+ &mut generated_tokens_count,+ pos,+ logits_index,+ )?;++ Ok(())+ })+ })) {+ Ok(inner) => inner,+ Err(_) => Err("Generation panicked".to_string()),+ };++ if let Err(err) = result {+ error_message = Some(err);+ }++ let summary = GenerateSummary {+ job_id,+ prompt_tokens: Some(prompt_tokens_count),+ generated_tokens: Some(generated_tokens_count),+ total_time_ms: Some(start.elapsed().as_millis() as i64),+ };++ if let Some(message) = error_message {+ sink.add(GenerateEvent::Error { job_id, message });+ }++ sink.add(GenerateEvent::Done {+ summary: summary.clone(),+ });++ Ok(summary)+}++pub fn cancel(job_id: JobId) -> Result<(), String> {+ if let Some(flag) = cancel_flags().lock().get(&job_id) {+ flag.store(true, Ordering::Relaxed);+ }+ Ok(())+}diff --git a/rust/inference_rs/src/capi.rs b/rust/inference_rs/src/capi.rsnew file mode 100644index 0000000000..9c1fbfd981--- /dev/null+++ b/rust/inference_rs/src/capi.rs@@ -0,0 +1,377 @@+use crate::api::{+ self, ChatMessage, ContextHandleRef, GenerateChatRequest, GenerateEvent, GenerateRequest,+ GenerateSummary, ModelHandleRef,+};+use serde::Serialize;+use std::ffi::{CStr, CString};+use std::os::raw::{c_char, c_void};+use std::panic::{catch_unwind, AssertUnwindSafe};+use std::ptr;++#[repr(C)]+pub struct inference_model {+ handle: ModelHandleRef,+}++#[repr(C)]+pub struct inference_context {+ handle: ContextHandleRef,+}++type EventCallback = Option<extern "C" fn(*const u8, usize, *mut c_void)>;++#[derive(Serialize)]+#[serde(tag = "type", rename_all = "snake_case")]+enum CapiEvent {+ Text {+ job_id: api::JobId,+ text: String,+ token_id: Option<i32>,+ },+ Done { summary: GenerateSummary },+ Error {+ job_id: api::JobId,+ message: String,+ },+}++impl From<GenerateEvent> for CapiEvent {+ fn from(value: GenerateEvent) -> Self {+ match value {+ GenerateEvent::Text {+ job_id,+ text,+ token_id,+ } => Self::Text {+ job_id,+ text,+ token_id,+ },+ GenerateEvent::Done { summary } => Self::Done { summary },+ GenerateEvent::Error { job_id, message } => Self::Error { job_id, message },+ }+ }+}++struct CapiEventSink {+ callback: EventCallback,+ user_data: *mut c_void,+}++impl api::EventSink for CapiEventSink {+ fn add(&mut self, event: GenerateEvent) {+ let Some(callback) = self.callback else {+ return;+ };++ let payload = CapiEvent::from(event);+ let json = serde_json::to_vec(&payload)+ .unwrap_or_else(|_| br#"{"type":"error","message":"serialization_failed"}"#.to_vec());+ callback(json.as_ptr(), json.len(), self.user_data);+ }+}++fn clear_error(error_out: *mut *mut c_char) {+ if error_out.is_null() {+ return;+ }+ unsafe {+ *error_out = ptr::null_mut();+ }+}++fn set_error(error_out: *mut *mut c_char, message: impl AsRef<str>) {+ if error_out.is_null() {+ return;+ }+ let message = message.as_ref();+ let cstring = CString::new(message).unwrap_or_else(|_| CString::new("invalid error").unwrap());+ unsafe {+ *error_out = cstring.into_raw();+ }+}++fn with_error<T>(error_out: *mut *mut c_char, result: Result<T, String>) -> Option<T> {+ match result {+ Ok(value) => {+ clear_error(error_out);+ Some(value)+ }+ Err(err) => {+ set_error(error_out, err);+ None+ }+ }+}++fn cstr_to_string(ptr: *const c_char, field: &str) -> Result<String, String> {+ if ptr.is_null() {+ return Err(format!("{field} is required"));+ }+ let cstr = unsafe { CStr::from_ptr(ptr) };+ cstr.to_str()+ .map(|value| value.to_string())+ .map_err(|err| format!("Invalid {field}: {err}"))+}++fn optional_cstr(ptr: *const c_char) -> Result<Option<String>, String> {+ if ptr.is_null() {+ return Ok(None);+ }+ let cstr = unsafe { CStr::from_ptr(ptr) };+ let value = cstr+ .to_str()+ .map_err(|err| format!("Invalid string: {err}"))?;+ if value.is_empty() {+ Ok(None)+ } else {+ Ok(Some(value.to_string()))+ }+}++fn parse_json<T>(json_ptr: *const c_char, field: &str) -> Result<T, String>+where+ T: serde::de::DeserializeOwned,+{+ let json = cstr_to_string(json_ptr, field)?;+ serde_json::from_str(&json).map_err(|err| format!("Invalid {field} JSON: {err}"))+}++fn to_json_string<T: Serialize>(value: &T) -> Result<*mut c_char, String> {+ let json = serde_json::to_string(value).map_err(|err| err.to_string())?;+ CString::new(json)+ .map_err(|err| err.to_string())+ .map(|value| value.into_raw())+}++#[unsafe(no_mangle)]+pub extern "C" fn inference_string_free(value: *mut c_char) {+ if value.is_null() {+ return;+ }+ unsafe {+ drop(CString::from_raw(value));+ }+}++#[unsafe(no_mangle)]+pub extern "C" fn inference_init_backend(error_out: *mut *mut c_char) -> bool {+ let result = catch_unwind(AssertUnwindSafe(|| api::init_backend()));+ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("init_backend panicked".to_string()),+ };+ with_error(error_out, result).is_some()+}++#[unsafe(no_mangle)]+pub extern "C" fn inference_load_model(+ params_json: *const c_char,+ error_out: *mut *mut c_char,+) -> *mut inference_model {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let params = parse_json::<api::ModelLoadParams>(params_json, "params_json")?;+ api::load_model(params)+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("load_model panicked".to_string()),+ };++ let Some(handle) = with_error(error_out, result) else {+ return ptr::null_mut();+ };++ Box::into_raw(Box::new(inference_model { handle }))+}++#[unsafe(no_mangle)]+pub extern "C" fn inference_model_free(model: *mut inference_model) {+ if model.is_null() {+ return;+ }+ unsafe {+ drop(Box::from_raw(model));+ }+}++#[unsafe(no_mangle)]+pub extern "C" fn inference_create_context(+ model: *const inference_model,+ params_json: *const c_char,+ error_out: *mut *mut c_char,+) -> *mut inference_context {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let model = unsafe { model.as_ref() }.ok_or_else(|| "model is required".to_string())?;+ let params = parse_json::<api::ContextParams>(params_json, "params_json")?;+ api::create_context(model.handle.clone(), params)+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("create_context panicked".to_string()),+ };++ let Some(handle) = with_error(error_out, result) else {+ return ptr::null_mut();+ };++ Box::into_raw(Box::new(inference_context { handle }))+}++#[unsafe(no_mangle)]+pub extern "C" fn inference_context_free(context: *mut inference_context) {+ if context.is_null() {+ return;+ }+ unsafe {+ drop(Box::from_raw(context));+ }+}++#[unsafe(no_mangle)]+pub extern "C" fn inference_tokenize_json(+ model: *const inference_model,+ text: *const c_char,+ add_bos: bool,+ special: bool,+ error_out: *mut *mut c_char,+) -> *mut c_char {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let model = unsafe { model.as_ref() }.ok_or_else(|| "model is required".to_string())?;+ let text = cstr_to_string(text, "text")?;+ let tokens = api::tokenize(model.handle.as_ref(), text, add_bos, special)?;+ to_json_string(&tokens)+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("tokenize panicked".to_string()),+ };++ with_error(error_out, result).unwrap_or(ptr::null_mut())+}++#[unsafe(no_mangle)]+pub extern "C" fn inference_detokenize_json(+ model: *const inference_model,+ tokens_json: *const c_char,+ error_out: *mut *mut c_char,+) -> *mut c_char {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let model = unsafe { model.as_ref() }.ok_or_else(|| "model is required".to_string())?;+ let tokens = parse_json::<Vec<i32>>(tokens_json, "tokens_json")?;+ let text = api::detokenize(model.handle.as_ref(), tokens)?;+ to_json_string(&text)+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("detokenize panicked".to_string()),+ };++ with_error(error_out, result).unwrap_or(ptr::null_mut())+}++#[unsafe(no_mangle)]+pub extern "C" fn inference_get_model_info_json(+ model: *const inference_model,+ error_out: *mut *mut c_char,+) -> *mut c_char {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let model = unsafe { model.as_ref() }.ok_or_else(|| "model is required".to_string())?;+ let info = api::get_model_info(model.handle.as_ref())?;+ to_json_string(&info)+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("get_model_info panicked".to_string()),+ };++ with_error(error_out, result).unwrap_or(ptr::null_mut())+}++#[unsafe(no_mangle)]+pub extern "C" fn inference_apply_chat_template_json(+ model: *const inference_model,+ messages_json: *const c_char,+ template_override: *const c_char,+ add_assistant: bool,+ error_out: *mut *mut c_char,+) -> *mut c_char {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let model = unsafe { model.as_ref() }.ok_or_else(|| "model is required".to_string())?;+ let messages = parse_json::<Vec<ChatMessage>>(messages_json, "messages_json")?;+ let template_override = optional_cstr(template_override)?;+ let rendered = api::apply_chat_template(+ model.handle.as_ref(),+ messages,+ template_override,+ add_assistant,+ )?;+ to_json_string(&rendered)+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("apply_chat_template panicked".to_string()),+ };++ with_error(error_out, result).unwrap_or(ptr::null_mut())+}++#[unsafe(no_mangle)]+pub extern "C" fn inference_generate_chat_stream(+ context: *const inference_context,+ request_json: *const c_char,+ callback: EventCallback,+ user_data: *mut c_void,+ error_out: *mut *mut c_char,+) -> bool {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let context =+ unsafe { context.as_ref() }.ok_or_else(|| "context is required".to_string())?;+ let request = parse_json::<GenerateChatRequest>(request_json, "request_json")?;+ let mut sink = CapiEventSink { callback, user_data };+ api::generate_chat_stream(context.handle.as_ref(), request, &mut sink)+ .map(|_| ())+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("generate_chat_stream panicked".to_string()),+ };++ with_error(error_out, result).is_some()+}++#[unsafe(no_mangle)]+pub extern "C" fn inference_generate_stream(+ context: *const inference_context,+ request_json: *const c_char,+ callback: EventCallback,+ user_data: *mut c_void,+ error_out: *mut *mut c_char,+) -> bool {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let context =+ unsafe { context.as_ref() }.ok_or_else(|| "context is required".to_string())?;+ let request = parse_json::<GenerateRequest>(request_json, "request_json")?;+ let mut sink = CapiEventSink { callback, user_data };+ api::generate_stream(context.handle.as_ref(), request, &mut sink).map(|_| ())+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("generate_stream panicked".to_string()),+ };++ with_error(error_out, result).is_some()+}++#[unsafe(no_mangle)]+pub extern "C" fn inference_cancel(job_id: i64) {+ let _ = api::cancel(job_id);+}diff --git a/rust/inference_rs/src/lib.rs b/rust/inference_rs/src/lib.rsnew file mode 100644index 0000000000..571155809c--- /dev/null+++ b/rust/inference_rs/src/lib.rs@@ -0,0 +1,4 @@+mod api;+mod capi;++pub use api::*;diff --git a/rust/llmchat-db/Cargo.lock b/rust/llmchat-db/Cargo.locknew file mode 100644index 0000000000..f924e68f14--- /dev/null+++ b/rust/llmchat-db/Cargo.lock@@ -0,0 +1,2104 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "aead"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"+dependencies = [+ "crypto-common",+ "generic-array",+]++[[package]]+name = "argon2"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"+dependencies = [+ "base64ct",+ "blake2",+ "cpufeatures",+ "password-hash",+]++[[package]]+name = "arrayref"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"++[[package]]+name = "arrayvec"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"++[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"++[[package]]+name = "base64"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"++[[package]]+name = "base64ct"+version = "1.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"++[[package]]+name = "bitflags"+version = "2.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"++[[package]]+name = "blake2"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"+dependencies = [+ "digest",+]++[[package]]+name = "blake2b_simd"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b79834656f71332577234b50bfc009996f7449e0c056884e6a02492ded0ca2f3"+dependencies = [+ "arrayref",+ "arrayvec",+ "constant_time_eq",+]++[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]++[[package]]+name = "block-padding"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"+dependencies = [+ "generic-array",+]++[[package]]+name = "bumpalo"+version = "3.19.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510"++[[package]]+name = "bytes"+version = "1.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3"++[[package]]+name = "cc"+version = "1.2.53"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "755d2fce177175ffca841e9a06afdb2c4ab0f593d53b4dee48147dfaade85932"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "cfg_aliases"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"++[[package]]+name = "chacha20"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"+dependencies = [+ "cfg-if",+ "cipher",+ "cpufeatures",+]++[[package]]+name = "cipher"+version = "0.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"+dependencies = [+ "crypto-common",+ "inout",+ "zeroize",+]++[[package]]+name = "constant_time_eq"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"++[[package]]+name = "core-foundation"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "rand_core 0.6.4",+ "typenum",+]++[[package]]+name = "crypto_secretstream"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a6419214057ad50a13efccb3ad7714b86b848e3a5aa7b6cf5a3ff07edf387eb"+dependencies = [+ "aead",+ "chacha20",+ "getrandom 0.2.17",+ "poly1305",+ "rand_core 0.6.4",+ "subtle",+]++[[package]]+name = "curve25519-dalek"+version = "4.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "curve25519-dalek-derive",+ "fiat-crypto",+ "rustc_version",+ "subtle",+ "zeroize",+]++[[package]]+name = "curve25519-dalek-derive"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+ "subtle",+]++[[package]]+name = "displaydoc"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "encoding_rs"+version = "0.8.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"+dependencies = [+ "cfg-if",+]++[[package]]+name = "ente-core"+version = "0.0.1"+dependencies = [+ "argon2",+ "base64",+ "blake2b_simd",+ "crypto_secretstream",+ "getrandom 0.2.17",+ "hex",+ "md-5",+ "rand_core 0.6.4",+ "reqwest",+ "salsa20",+ "serde",+ "serde_json",+ "subtle",+ "thiserror",+ "x25519-dalek",+ "xsalsa20poly1305",+ "zeroize",+]++[[package]]+name = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "fallible-iterator"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"++[[package]]+name = "fallible-streaming-iterator"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"++[[package]]+name = "fastrand"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"++[[package]]+name = "fiat-crypto"+version = "0.2.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"++[[package]]+name = "find-msvc-tools"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db"++[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"++[[package]]+name = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "futures-channel"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"+dependencies = [+ "futures-core",+]++[[package]]+name = "futures-core"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"++[[package]]+name = "futures-sink"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7"++[[package]]+name = "futures-task"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"++[[package]]+name = "futures-util"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"+dependencies = [+ "futures-core",+ "futures-task",+ "pin-project-lite",+ "pin-utils",+ "slab",+]++[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "wasi",+ "wasm-bindgen",+]++[[package]]+name = "getrandom"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "r-efi",+ "wasip2",+ "wasm-bindgen",+]++[[package]]+name = "h2"+version = "0.4.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"+dependencies = [+ "atomic-waker",+ "bytes",+ "fnv",+ "futures-core",+ "futures-sink",+ "http",+ "indexmap",+ "slab",+ "tokio",+ "tokio-util",+ "tracing",+]++[[package]]+name = "hashbrown"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"+dependencies = [+ "foldhash",+]++[[package]]+name = "hashlink"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea0b22561a9c04a7cb1a302c013e0259cd3b4bb619f145b32f72b8b4bcbed230"+dependencies = [+ "hashbrown",+]++[[package]]+name = "hex"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"++[[package]]+name = "http"+version = "1.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "http-body"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"+dependencies = [+ "bytes",+ "http",+]++[[package]]+name = "http-body-util"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "pin-project-lite",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "hyper"+version = "1.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11"+dependencies = [+ "atomic-waker",+ "bytes",+ "futures-channel",+ "futures-core",+ "h2",+ "http",+ "http-body",+ "httparse",+ "itoa",+ "pin-project-lite",+ "pin-utils",+ "smallvec",+ "tokio",+ "want",+]++[[package]]+name = "hyper-rustls"+version = "0.27.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58"+dependencies = [+ "http",+ "hyper",+ "hyper-util",+ "rustls",+ "rustls-native-certs",+ "rustls-pki-types",+ "tokio",+ "tokio-rustls",+ "tower-service",+]++[[package]]+name = "hyper-util"+version = "0.1.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "727805d60e7938b76b826a6ef209eb70eaa1812794f9424d4a4e2d740662df5f"+dependencies = [+ "base64",+ "bytes",+ "futures-channel",+ "futures-core",+ "futures-util",+ "http",+ "http-body",+ "hyper",+ "ipnet",+ "libc",+ "percent-encoding",+ "pin-project-lite",+ "socket2",+ "system-configuration",+ "tokio",+ "tower-service",+ "tracing",+ "windows-registry",+]++[[package]]+name = "icu_collections"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43"+dependencies = [+ "displaydoc",+ "potential_utf",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a"++[[package]]+name = "icu_properties"+version = "2.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec"+dependencies = [+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af"++[[package]]+name = "icu_provider"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]++[[package]]+name = "indexmap"+version = "2.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"+dependencies = [+ "equivalent",+ "hashbrown",+]++[[package]]+name = "inout"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"+dependencies = [+ "block-padding",+ "generic-array",+]++[[package]]+name = "ipnet"+version = "2.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"++[[package]]+name = "iri-string"+version = "0.7.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a"+dependencies = [+ "memchr",+ "serde",+]++[[package]]+name = "itoa"+version = "1.0.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"++[[package]]+name = "js-sys"+version = "0.3.85"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3"+dependencies = [+ "once_cell",+ "wasm-bindgen",+]++[[package]]+name = "libc"+version = "0.2.180"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc"++[[package]]+name = "libsqlite3-sys"+version = "0.36.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95b4103cffefa72eb8428cb6b47d6627161e51c2739fc5e3b734584157bc642a"+dependencies = [+ "cc",+ "pkg-config",+ "vcpkg",+]++[[package]]+name = "linux-raw-sys"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"++[[package]]+name = "litemap"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77"++[[package]]+name = "llmchat-db"+version = "0.1.0"+dependencies = [+ "ente-core",+ "rusqlite",+ "serde",+ "serde_json",+ "tempfile",+ "thiserror",+ "uuid",+ "zeroize",+]++[[package]]+name = "log"+version = "0.4.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"++[[package]]+name = "lru-slab"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"++[[package]]+name = "md-5"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"+dependencies = [+ "cfg-if",+ "digest",+]++[[package]]+name = "memchr"+version = "2.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"++[[package]]+name = "mime"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"++[[package]]+name = "mio"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc"+dependencies = [+ "libc",+ "wasi",+ "windows-sys 0.61.2",+]++[[package]]+name = "once_cell"+version = "1.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"++[[package]]+name = "opaque-debug"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"++[[package]]+name = "openssl-probe"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f50d9b3dabb09ecd771ad0aa242ca6894994c130308ca3d7684634df8037391"++[[package]]+name = "password-hash"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"+dependencies = [+ "base64ct",+ "rand_core 0.6.4",+ "subtle",+]++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "pin-project-lite"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"++[[package]]+name = "pin-utils"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"++[[package]]+name = "pkg-config"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"++[[package]]+name = "poly1305"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"+dependencies = [+ "cpufeatures",+ "opaque-debug",+ "universal-hash",+]++[[package]]+name = "potential_utf"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77"+dependencies = [+ "zerovec",+]++[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]++[[package]]+name = "proc-macro2"+version = "1.0.105"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "535d180e0ecab6268a3e718bb9fd44db66bbbc256257165fc699dadf70d16fe7"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quinn"+version = "0.11.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"+dependencies = [+ "bytes",+ "cfg_aliases",+ "pin-project-lite",+ "quinn-proto",+ "quinn-udp",+ "rustc-hash",+ "rustls",+ "socket2",+ "thiserror",+ "tokio",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-proto"+version = "0.11.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31"+dependencies = [+ "bytes",+ "getrandom 0.3.4",+ "lru-slab",+ "rand",+ "ring",+ "rustc-hash",+ "rustls",+ "rustls-pki-types",+ "slab",+ "thiserror",+ "tinyvec",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-udp"+version = "0.5.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"+dependencies = [+ "cfg_aliases",+ "libc",+ "once_cell",+ "socket2",+ "tracing",+ "windows-sys 0.60.2",+]++[[package]]+name = "quote"+version = "1.0.43"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc74d9a594b72ae6656596548f56f667211f8a97b3d4c3d467150794690dc40a"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"++[[package]]+name = "rand"+version = "0.9.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"+dependencies = [+ "rand_chacha",+ "rand_core 0.9.5",+]++[[package]]+name = "rand_chacha"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"+dependencies = [+ "ppv-lite86",+ "rand_core 0.9.5",+]++[[package]]+name = "rand_core"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+dependencies = [+ "getrandom 0.2.17",+]++[[package]]+name = "rand_core"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"+dependencies = [+ "getrandom 0.3.4",+]++[[package]]+name = "reqwest"+version = "0.12.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"+dependencies = [+ "base64",+ "bytes",+ "encoding_rs",+ "futures-core",+ "h2",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-rustls",+ "hyper-util",+ "js-sys",+ "log",+ "mime",+ "percent-encoding",+ "pin-project-lite",+ "quinn",+ "rustls",+ "rustls-native-certs",+ "rustls-pki-types",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "sync_wrapper",+ "tokio",+ "tokio-rustls",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]++[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]++[[package]]+name = "rsqlite-vfs"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8a1f2315036ef6b1fbacd1972e8ee7688030b0a2121edfc2a6550febd41574d"+dependencies = [+ "hashbrown",+ "thiserror",+]++[[package]]+name = "rusqlite"+version = "0.38.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1c93dd1c9683b438c392c492109cb702b8090b2bfc8fed6f6e4eb4523f17af3"+dependencies = [+ "bitflags",+ "fallible-iterator",+ "fallible-streaming-iterator",+ "hashlink",+ "libsqlite3-sys",+ "smallvec",+ "sqlite-wasm-rs",+]++[[package]]+name = "rustc-hash"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"++[[package]]+name = "rustc_version"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"+dependencies = [+ "semver",+]++[[package]]+name = "rustix"+version = "1.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34"+dependencies = [+ "bitflags",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustls"+version = "0.23.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b"+dependencies = [+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-native-certs"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63"+dependencies = [+ "openssl-probe",+ "rustls-pki-types",+ "schannel",+ "security-framework",+]++[[package]]+name = "rustls-pki-types"+version = "1.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"+dependencies = [+ "web-time",+ "zeroize",+]++[[package]]+name = "rustls-webpki"+version = "0.103.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted",+]++[[package]]+name = "rustversion"+version = "1.0.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"++[[package]]+name = "ryu"+version = "1.0.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a50f4cf475b65d88e057964e0e9bb1f0aa9bbb2036dc65c64596b42932536984"++[[package]]+name = "salsa20"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213"+dependencies = [+ "cipher",+]++[[package]]+name = "schannel"+version = "0.1.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "891d81b926048e76efe18581bf793546b4c0eaf8448d72be8de2bbee5fd166e1"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "security-framework"+version = "3.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3297343eaf830f66ede390ea39da1d462b6b0c1b000f420d0a83f898bbbe6ef"+dependencies = [+ "bitflags",+ "core-foundation 0.10.1",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]++[[package]]+name = "security-framework-sys"+version = "2.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc1f0cbffaac4852523ce30d8bd3c5cdc873501d96ff467ca09b6767bb8cd5c0"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "semver"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"++[[package]]+name = "serde"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "serde_json"+version = "1.0.149"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "serde_urlencoded"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"+dependencies = [+ "form_urlencoded",+ "itoa",+ "ryu",+ "serde",+]++[[package]]+name = "shlex"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"++[[package]]+name = "slab"+version = "0.4.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589"++[[package]]+name = "smallvec"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"++[[package]]+name = "socket2"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881"+dependencies = [+ "libc",+ "windows-sys 0.60.2",+]++[[package]]+name = "sqlite-wasm-rs"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f4206ed3a67690b9c29b77d728f6acc3ce78f16bf846d83c94f76400320181b"+dependencies = [+ "cc",+ "js-sys",+ "rsqlite-vfs",+ "wasm-bindgen",+]++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"++[[package]]+name = "syn"+version = "2.0.114"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "sync_wrapper"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"+dependencies = [+ "futures-core",+]++[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "system-configuration"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b"+dependencies = [+ "bitflags",+ "core-foundation 0.9.4",+ "system-configuration-sys",+]++[[package]]+name = "system-configuration-sys"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "tempfile"+version = "3.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "655da9c7eb6305c55742045d5a8d2037996d61d8de95806335c7c86ce0f82e9c"+dependencies = [+ "fastrand",+ "getrandom 0.3.4",+ "once_cell",+ "rustix",+ "windows-sys 0.61.2",+]++[[package]]+name = "thiserror"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tinystr"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869"+dependencies = [+ "displaydoc",+ "zerovec",+]++[[package]]+name = "tinyvec"+version = "1.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa"+dependencies = [+ "tinyvec_macros",+]++[[package]]+name = "tinyvec_macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"++[[package]]+name = "tokio"+version = "1.49.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86"+dependencies = [+ "bytes",+ "libc",+ "mio",+ "pin-project-lite",+ "socket2",+ "windows-sys 0.61.2",+]++[[package]]+name = "tokio-rustls"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"+dependencies = [+ "rustls",+ "tokio",+]++[[package]]+name = "tokio-util"+version = "0.7.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "tower"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"+dependencies = [+ "futures-core",+ "futures-util",+ "pin-project-lite",+ "sync_wrapper",+ "tokio",+ "tower-layer",+ "tower-service",+]++[[package]]+name = "tower-http"+version = "0.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"+dependencies = [+ "bitflags",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "iri-string",+ "pin-project-lite",+ "tower",+ "tower-layer",+ "tower-service",+]++[[package]]+name = "tower-layer"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"++[[package]]+name = "tower-service"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "pin-project-lite",+ "tracing-core",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+]++[[package]]+name = "try-lock"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"++[[package]]+name = "typenum"+version = "1.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"++[[package]]+name = "unicode-ident"+version = "1.0.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"++[[package]]+name = "universal-hash"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"+dependencies = [+ "crypto-common",+ "subtle",+]++[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+]++[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"++[[package]]+name = "uuid"+version = "1.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2e054861b4bd027cd373e18e8d8d8e6548085000e41290d95ce0c373a654b4a"+dependencies = [+ "getrandom 0.3.4",+ "js-sys",+ "uuid-rng-internal",+ "wasm-bindgen",+]++[[package]]+name = "uuid-rng-internal"+version = "1.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d0021aebf9af0cbec73af2f884a2cd0a41d984c00e42f27baa11856ab480e2c"+dependencies = [+ "getrandom 0.3.4",+]++[[package]]+name = "vcpkg"+version = "0.2.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "want"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"+dependencies = [+ "try-lock",+]++[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "wasip2"+version = "1.0.2+wasi-0.2.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "wasm-bindgen"+version = "0.2.108"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566"+dependencies = [+ "cfg-if",+ "once_cell",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.58"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "70a6e77fd0ae8029c9ea0063f87c46fde723e7d887703d74ad2616d792e51e6f"+dependencies = [+ "cfg-if",+ "futures-util",+ "js-sys",+ "once_cell",+ "wasm-bindgen",+ "web-sys",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.108"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.108"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.108"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "web-sys"+version = "0.3.85"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "312e32e551d92129218ea9a2452120f4aabc03529ef03e4d0d82fb2780608598"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "web-time"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-registry"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"+dependencies = [+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-sys"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"+dependencies = [+ "windows-targets 0.53.5",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm 0.52.6",+ "windows_aarch64_msvc 0.52.6",+ "windows_i686_gnu 0.52.6",+ "windows_i686_gnullvm 0.52.6",+ "windows_i686_msvc 0.52.6",+ "windows_x86_64_gnu 0.52.6",+ "windows_x86_64_gnullvm 0.52.6",+ "windows_x86_64_msvc 0.52.6",+]++[[package]]+name = "windows-targets"+version = "0.53.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"+dependencies = [+ "windows-link",+ "windows_aarch64_gnullvm 0.53.1",+ "windows_aarch64_msvc 0.53.1",+ "windows_i686_gnu 0.53.1",+ "windows_i686_gnullvm 0.53.1",+ "windows_i686_msvc 0.53.1",+ "windows_x86_64_gnu 0.53.1",+ "windows_x86_64_gnullvm 0.53.1",+ "windows_x86_64_msvc 0.53.1",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_aarch64_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnu"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_i686_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnu"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "windows_x86_64_msvc"+version = "0.53.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"++[[package]]+name = "wit-bindgen"+version = "0.51.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"++[[package]]+name = "writeable"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9"++[[package]]+name = "x25519-dalek"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"+dependencies = [+ "curve25519-dalek",+ "rand_core 0.6.4",+ "serde",+ "zeroize",+]++[[package]]+name = "xsalsa20poly1305"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02a6dad357567f81cd78ee75f7c61f1b30bb2fe4390be8fb7c69e2ac8dffb6c7"+dependencies = [+ "aead",+ "poly1305",+ "salsa20",+ "subtle",+ "zeroize",+]++[[package]]+name = "yoke"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zerocopy"+version = "0.8.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "668f5168d10b9ee831de31933dc111a459c97ec93225beb307aed970d1372dfd"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c7962b26b0a8685668b671ee4b54d007a67d4eaf05fda79ac0ecf41e32270f1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "zerofrom"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zeroize"+version = "1.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"+dependencies = [+ "zeroize_derive",+]++[[package]]+name = "zeroize_derive"+version = "1.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "zerotrie"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "zmij"+version = "1.0.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfcd145825aace48cff44a8844de64bf75feec3080e0aa5cdbde72961ae51a65"diff --git a/rust/llmchat-db/Cargo.toml b/rust/llmchat-db/Cargo.tomlnew file mode 100644index 0000000000..c27112f66e--- /dev/null+++ b/rust/llmchat-db/Cargo.toml@@ -0,0 +1,20 @@+[package]+name = "llmchat-db"+version = "0.1.0"+edition = "2024"++[dependencies]+ente-core = { path = "../core" }+rusqlite = { version = "0.38", features = ["bundled"], optional = true }+serde = { version = "1", features = ["derive"] }+serde_json = "1"+thiserror = "2"+uuid = { version = "1", features = ["v4", "rng-getrandom"] }+zeroize = { version = "1.8", features = ["derive"] }++[dev-dependencies]+tempfile = "3"++[features]+default = ["sqlite"]+sqlite = ["dep:rusqlite"]diff --git a/rust/llmchat-db/src/backend/mod.rs b/rust/llmchat-db/src/backend/mod.rsnew file mode 100644index 0000000000..64570d3cdc--- /dev/null+++ b/rust/llmchat-db/src/backend/mod.rs@@ -0,0 +1,93 @@+use crate::{Error, Result};++#[cfg(feature = "sqlite")]+pub mod sqlite;++#[derive(Debug, Clone, PartialEq)]+pub enum Value {+ Null,+ Integer(i64),+ Text(String),+ Blob(Vec<u8>),+}++pub type Row = Vec<Value>;++pub trait BackendTx {+ fn execute(&self, sql: &str, params: &[Value]) -> Result<usize>;+ fn query(&self, sql: &str, params: &[Value]) -> Result<Vec<Row>>;+ fn query_row(&self, sql: &str, params: &[Value]) -> Result<Option<Row>>;+ fn execute_batch(&self, sql: &str) -> Result<()>;+}++pub trait Backend: BackendTx {+ type Tx<'a>: BackendTx+ where+ Self: 'a;++ fn transaction<T, F>(&self, f: F) -> Result<T>+ where+ F: for<'a> FnOnce(&Self::Tx<'a>) -> Result<T>;+}++pub trait RowExt {+ fn get_i64(&self, idx: usize) -> Result<i64>;+ fn get_string(&self, idx: usize) -> Result<String>;+ fn get_blob(&self, idx: usize) -> Result<Vec<u8>>;+ fn get_optional_string(&self, idx: usize) -> Result<Option<String>>;+ fn get_optional_i64(&self, idx: usize) -> Result<Option<i64>>;+}++impl RowExt for Vec<Value> {+ fn get_i64(&self, idx: usize) -> Result<i64> {+ match self.get(idx) {+ Some(Value::Integer(value)) => Ok(*value),+ Some(other) => Err(Error::Row(format!(+ "expected integer at column {idx}, got {other:?}"+ ))),+ None => Err(Error::Row(format!("missing column {idx}"))),+ }+ }++ fn get_string(&self, idx: usize) -> Result<String> {+ match self.get(idx) {+ Some(Value::Text(value)) => Ok(value.clone()),+ Some(other) => Err(Error::Row(format!(+ "expected text at column {idx}, got {other:?}"+ ))),+ None => Err(Error::Row(format!("missing column {idx}"))),+ }+ }++ fn get_blob(&self, idx: usize) -> Result<Vec<u8>> {+ match self.get(idx) {+ Some(Value::Blob(value)) => Ok(value.clone()),+ Some(other) => Err(Error::Row(format!(+ "expected blob at column {idx}, got {other:?}"+ ))),+ None => Err(Error::Row(format!("missing column {idx}"))),+ }+ }++ fn get_optional_string(&self, idx: usize) -> Result<Option<String>> {+ match self.get(idx) {+ Some(Value::Null) => Ok(None),+ Some(Value::Text(value)) => Ok(Some(value.clone())),+ Some(other) => Err(Error::Row(format!(+ "expected optional text at column {idx}, got {other:?}"+ ))),+ None => Err(Error::Row(format!("missing column {idx}"))),+ }+ }++ fn get_optional_i64(&self, idx: usize) -> Result<Option<i64>> {+ match self.get(idx) {+ Some(Value::Null) => Ok(None),+ Some(Value::Integer(value)) => Ok(Some(*value)),+ Some(other) => Err(Error::Row(format!(+ "expected optional integer at column {idx}, got {other:?}"+ ))),+ None => Err(Error::Row(format!("missing column {idx}"))),+ }+ }+}diff --git a/rust/llmchat-db/src/backend/sqlite.rs b/rust/llmchat-db/src/backend/sqlite.rsnew file mode 100644index 0000000000..20b1ac96dc--- /dev/null+++ b/rust/llmchat-db/src/backend/sqlite.rs@@ -0,0 +1,208 @@+use std::path::Path;+use std::sync::{Mutex, MutexGuard};++use rusqlite::{Connection, params_from_iter};+use rusqlite::types::Value as SqlValue;++use crate::{Backend, BackendTx, Error, Result, Row, Value};++pub struct SqliteBackend {+ conn: Mutex<Connection>,+}++impl SqliteBackend {+ pub fn open(path: impl AsRef<Path>) -> Result<Self> {+ let conn = Connection::open(path)?;+ conn.execute_batch("PRAGMA foreign_keys = ON;")?;+ Ok(Self {+ conn: Mutex::new(conn),+ })+ }++ pub fn open_in_memory() -> Result<Self> {+ let conn = Connection::open_in_memory()?;+ conn.execute_batch("PRAGMA foreign_keys = ON;")?;+ Ok(Self {+ conn: Mutex::new(conn),+ })+ }++ fn lock_conn(&self) -> Result<MutexGuard<'_, Connection>> {+ self.conn+ .lock()+ .map_err(|_| Error::UnsupportedOperation("sqlite connection lock poisoned".to_string()))+ }+}++pub struct SqliteTransaction<'a> {+ guard: MutexGuard<'a, Connection>,+}++impl<'a> SqliteTransaction<'a> {+ fn begin(guard: MutexGuard<'a, Connection>) -> Result<Self> {+ guard.execute_batch("BEGIN IMMEDIATE")?;+ Ok(Self { guard })+ }++ fn commit(self) -> Result<()> {+ self.guard.execute_batch("COMMIT")?;+ Ok(())+ }++ fn rollback(self) -> Result<()> {+ self.guard.execute_batch("ROLLBACK")?;+ Ok(())+ }+}++trait SqliteConn {+ fn execute_sql(&self, sql: &str, params: &[SqlValue]) -> rusqlite::Result<usize>;+ fn prepare_sql<'a>(&'a self, sql: &str) -> rusqlite::Result<rusqlite::Statement<'a>>;+ fn execute_batch_sql(&self, sql: &str) -> rusqlite::Result<()>;+}++impl SqliteConn for Connection {+ fn execute_sql(&self, sql: &str, params: &[SqlValue]) -> rusqlite::Result<usize> {+ self.execute(sql, params_from_iter(params.iter().cloned()))+ }++ fn prepare_sql<'a>(&'a self, sql: &str) -> rusqlite::Result<rusqlite::Statement<'a>> {+ self.prepare(sql)+ }++ fn execute_batch_sql(&self, sql: &str) -> rusqlite::Result<()> {+ self.execute_batch(sql)+ }+}++impl<'a> SqliteConn for SqliteTransaction<'a> {+ fn execute_sql(&self, sql: &str, params: &[SqlValue]) -> rusqlite::Result<usize> {+ self.guard.execute(sql, params_from_iter(params.iter().cloned()))+ }++ fn prepare_sql<'b>(&'b self, sql: &str) -> rusqlite::Result<rusqlite::Statement<'b>> {+ self.guard.prepare(sql)+ }++ fn execute_batch_sql(&self, sql: &str) -> rusqlite::Result<()> {+ self.guard.execute_batch(sql)+ }+}++impl BackendTx for SqliteBackend {+ fn execute(&self, sql: &str, params: &[Value]) -> Result<usize> {+ let conn = self.lock_conn()?;+ execute_impl(&*conn, sql, params)+ }++ fn query(&self, sql: &str, params: &[Value]) -> Result<Vec<Row>> {+ let conn = self.lock_conn()?;+ query_impl(&*conn, sql, params)+ }++ fn query_row(&self, sql: &str, params: &[Value]) -> Result<Option<Row>> {+ let conn = self.lock_conn()?;+ query_row_impl(&*conn, sql, params)+ }++ fn execute_batch(&self, sql: &str) -> Result<()> {+ let conn = self.lock_conn()?;+ execute_batch_impl(&*conn, sql)+ }+}++impl Backend for SqliteBackend {+ type Tx<'a> = SqliteTransaction<'a>;++ fn transaction<T, F>(&self, f: F) -> Result<T>+ where+ F: for<'a> FnOnce(&Self::Tx<'a>) -> Result<T>,+ {+ let guard = self.lock_conn()?;+ let wrapper = SqliteTransaction::begin(guard)?;+ let result = f(&wrapper);+ match result {+ Ok(value) => {+ wrapper.commit()?;+ Ok(value)+ }+ Err(err) => {+ wrapper.rollback()?;+ Err(err)+ }+ }+ }+}++impl<'a> BackendTx for SqliteTransaction<'a> {+ fn execute(&self, sql: &str, params: &[Value]) -> Result<usize> {+ execute_impl(self, sql, params)+ }++ fn query(&self, sql: &str, params: &[Value]) -> Result<Vec<Row>> {+ query_impl(self, sql, params)+ }++ fn query_row(&self, sql: &str, params: &[Value]) -> Result<Option<Row>> {+ query_row_impl(self, sql, params)+ }++ fn execute_batch(&self, sql: &str) -> Result<()> {+ execute_batch_impl(self, sql)+ }+}++fn execute_impl<C: SqliteConn>(conn: &C, sql: &str, params: &[Value]) -> Result<usize> {+ let params = to_sql_params(params);+ Ok(conn.execute_sql(sql, ¶ms)?)+}++fn execute_batch_impl<C: SqliteConn>(conn: &C, sql: &str) -> Result<()> {+ conn.execute_batch_sql(sql)?;+ Ok(())+}++fn query_impl<C: SqliteConn>(conn: &C, sql: &str, params: &[Value]) -> Result<Vec<Row>> {+ let params = to_sql_params(params);+ let mut stmt = conn.prepare_sql(sql)?;+ let mut rows = stmt.query(params_from_iter(params))?;+ let mut results = Vec::new();+ while let Some(row) = rows.next()? {+ let column_count = row.as_ref().column_count();+ let mut values = Vec::with_capacity(column_count);+ for idx in 0..column_count {+ let value: SqlValue = row.get(idx)?;+ values.push(from_sql_value(value)?);+ }+ results.push(values);+ }+ Ok(results)+}++fn query_row_impl<C: SqliteConn>(conn: &C, sql: &str, params: &[Value]) -> Result<Option<Row>> {+ let rows = query_impl(conn, sql, params)?;+ Ok(rows.into_iter().next())+}++fn to_sql_params(params: &[Value]) -> Vec<SqlValue> {+ params.iter().map(to_sql_value).collect()+}++fn to_sql_value(value: &Value) -> SqlValue {+ match value {+ Value::Null => SqlValue::Null,+ Value::Integer(v) => SqlValue::Integer(*v),+ Value::Text(v) => SqlValue::Text(v.clone()),+ Value::Blob(v) => SqlValue::Blob(v.clone()),+ }+}++fn from_sql_value(value: SqlValue) -> Result<Value> {+ match value {+ SqlValue::Null => Ok(Value::Null),+ SqlValue::Integer(v) => Ok(Value::Integer(v)),+ SqlValue::Text(v) => Ok(Value::Text(v)),+ SqlValue::Blob(v) => Ok(Value::Blob(v)),+ SqlValue::Real(_) => Err(Error::UnsupportedValueType("real".to_string())),+ }+}diff --git a/rust/llmchat-db/src/crypto.rs b/rust/llmchat-db/src/crypto.rsnew file mode 100644index 0000000000..7c8b8870f6--- /dev/null+++ b/rust/llmchat-db/src/crypto.rs@@ -0,0 +1,90 @@+use ente_core::crypto::{self, blob};++use crate::{Error, Result};++pub const HEADER_BYTES: usize = blob::HEADER_BYTES;+pub const KEY_BYTES: usize = blob::KEY_BYTES;++pub fn encrypt_blob(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>> {+ let encrypted = blob::encrypt(plaintext, key)?;+ let mut combined = Vec::with_capacity(HEADER_BYTES + encrypted.encrypted_data.len());+ combined.extend_from_slice(&encrypted.decryption_header);+ combined.extend_from_slice(&encrypted.encrypted_data);+ Ok(combined)+}++pub fn decrypt_blob(data: &[u8], key: &[u8]) -> Result<Vec<u8>> {+ if data.len() < HEADER_BYTES {+ return Err(Error::InvalidBlobLength {+ minimum: HEADER_BYTES,+ actual: data.len(),+ });+ }+ let (header, ciphertext) = data.split_at(HEADER_BYTES);+ Ok(blob::decrypt(ciphertext, header, key)?)+}++pub fn encrypt_string(value: &str, key: &[u8]) -> Result<Vec<u8>> {+ encrypt_blob(value.as_bytes(), key)+}++pub fn decrypt_string(data: &[u8], key: &[u8]) -> Result<String> {+ let plaintext = decrypt_blob(data, key)?;+ Ok(String::from_utf8(plaintext)?)+}++pub fn encrypt_json_field(value: &str, key: &[u8]) -> Result<String> {+ let encrypted = blob::encrypt(value.as_bytes(), key)?;+ let ciphertext_b64 = crypto::encode_b64(&encrypted.encrypted_data);+ let header_b64 = crypto::encode_b64(&encrypted.decryption_header);+ Ok(format!("enc:v1:{ciphertext_b64}:{header_b64}"))+}++pub fn decrypt_json_field(value: &str, key: &[u8]) -> Result<String> {+ let mut parts = value.split(':');+ let prefix = parts.next();+ let version = parts.next();+ let ciphertext_b64 = parts.next();+ let header_b64 = parts.next();+ if prefix != Some("enc") || version != Some("v1") || parts.next().is_some() {+ return Err(Error::InvalidEncryptedField);+ }+ let ciphertext_b64 = ciphertext_b64.ok_or(Error::InvalidEncryptedField)?;+ let header_b64 = header_b64.ok_or(Error::InvalidEncryptedField)?;+ let ciphertext = crypto::decode_b64(ciphertext_b64)?;+ let header = crypto::decode_b64(header_b64)?;+ if header.len() != HEADER_BYTES {+ return Err(Error::InvalidEncryptedField);+ }+ let plaintext = blob::decrypt(&ciphertext, &header, key)?;+ Ok(String::from_utf8(plaintext)?)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn blob_roundtrip() {+ let key = vec![7u8; KEY_BYTES];+ let plaintext = b"hello";++ let encrypted = encrypt_blob(plaintext, &key).unwrap();+ assert!(encrypted.len() > plaintext.len());++ let decrypted = decrypt_blob(&encrypted, &key).unwrap();+ assert_eq!(decrypted, plaintext);+ }++ #[test]+ fn json_field_roundtrip() {+ let key = vec![9u8; KEY_BYTES];+ let plaintext = "file-name.png";++ let encrypted = encrypt_json_field(plaintext, &key).unwrap();+ assert!(encrypted.starts_with("enc:v1:"));++ let decrypted = decrypt_json_field(&encrypted, &key).unwrap();+ assert_eq!(decrypted, plaintext);+ }+}diff --git a/rust/llmchat-db/src/db.rs b/rust/llmchat-db/src/db.rsnew file mode 100644index 0000000000..c182ad37cf--- /dev/null+++ b/rust/llmchat-db/src/db.rs@@ -0,0 +1,743 @@+use std::sync::Arc;++use uuid::Uuid;+use zeroize::Zeroizing;++use crate::backend::{Backend, BackendTx, RowExt, Value};+use crate::crypto;+use crate::migrations;+use crate::models::{Attachment, EntityType, Message, Sender, Session, StoredAttachment};+use crate::traits::{Clock, RandomUuidGen, SystemClock, UuidGen};+use crate::{Error, Result};++pub struct ChatDb<B: Backend> {+ backend: B,+ key: Zeroizing<Vec<u8>>,+ clock: Arc<dyn Clock>,+ uuid_gen: Arc<dyn UuidGen>,+}++impl<B: Backend> ChatDb<B> {+ pub fn new(+ backend: B,+ key: Vec<u8>,+ clock: Arc<dyn Clock>,+ uuid_gen: Arc<dyn UuidGen>,+ ) -> Result<Self> {+ let key = validate_key(key)?;+ migrations::migrate(&backend)?;+ Ok(Self {+ backend,+ key,+ clock,+ uuid_gen,+ })+ }++ pub fn new_with_defaults(backend: B, key: Vec<u8>) -> Result<Self> {+ Self::new(+ backend,+ key,+ Arc::new(SystemClock),+ Arc::new(RandomUuidGen),+ )+ }++ pub fn create_session(&self, title: &str) -> Result<Session> {+ let now = self.clock.now_us();+ let session_uuid = self.uuid_gen.new_uuid();+ let encrypted_title = crypto::encrypt_string(title, &self.key)?;++ let affected = self.backend.execute(+ "INSERT INTO sessions (session_uuid, title, created_at, updated_at, remote_id, needs_sync, deleted_at) \+ VALUES (?, ?, ?, ?, NULL, 1, NULL)",+ &[+ Value::Text(session_uuid.to_string()),+ Value::Blob(encrypted_title),+ Value::Integer(now),+ Value::Integer(now),+ ],+ )?;++ if affected != 1 {+ return Err(Error::NotFound {+ entity: EntityType::Session,+ id: session_uuid,+ });+ }++ Ok(Session {+ uuid: session_uuid,+ title: title.to_string(),+ created_at: now,+ updated_at: now,+ remote_id: None,+ needs_sync: true,+ deleted_at: None,+ })+ }++ pub fn get_session(&self, uuid: Uuid) -> Result<Option<Session>> {+ let row = self.backend.query_row(+ "SELECT session_uuid, title, created_at, updated_at, remote_id, needs_sync, deleted_at \+ FROM sessions WHERE session_uuid = ? AND deleted_at IS NULL",+ &[Value::Text(uuid.to_string())],+ )?;++ row.map(|row| self.session_from_row(&row)).transpose()+ }++ pub fn list_sessions(&self) -> Result<Vec<Session>> {+ let rows = self.backend.query(+ "SELECT session_uuid, title, created_at, updated_at, remote_id, needs_sync, deleted_at \+ FROM sessions WHERE deleted_at IS NULL ORDER BY updated_at DESC",+ &[],+ )?;+ rows.iter().map(|row| self.session_from_row(row)).collect()+ }++ pub fn update_session_title(&self, uuid: Uuid, title: &str) -> Result<()> {+ let now = self.clock.now_us();+ let encrypted_title = crypto::encrypt_string(title, &self.key)?;+ let affected = self.backend.execute(+ "UPDATE sessions SET title = ?, updated_at = ?, needs_sync = 1 \+ WHERE session_uuid = ? AND deleted_at IS NULL",+ &[+ Value::Blob(encrypted_title),+ Value::Integer(now),+ Value::Text(uuid.to_string()),+ ],+ )?;+ ensure_row_updated(affected, EntityType::Session, uuid)+ }++ pub fn delete_session(&self, uuid: Uuid) -> Result<()> {+ let now = self.clock.now_us();+ self.backend.transaction(|tx| {+ tx.execute(+ "UPDATE messages SET deleted_at = ? WHERE session_uuid = ? AND deleted_at IS NULL",+ &[Value::Integer(now), Value::Text(uuid.to_string())],+ )?;+ let affected = tx.execute(+ "UPDATE sessions SET deleted_at = ? WHERE session_uuid = ? AND deleted_at IS NULL",+ &[Value::Integer(now), Value::Text(uuid.to_string())],+ )?;+ ensure_row_updated(affected, EntityType::Session, uuid)+ })+ }++ pub fn get_sessions_needing_sync(&self) -> Result<Vec<Session>> {+ let rows = self.backend.query(+ "SELECT session_uuid, title, created_at, updated_at, remote_id, needs_sync, deleted_at \+ FROM sessions WHERE needs_sync = 1 AND deleted_at IS NULL ORDER BY updated_at DESC",+ &[],+ )?;+ rows.iter().map(|row| self.session_from_row(row)).collect()+ }++ pub fn insert_message(+ &self,+ session_uuid: Uuid,+ sender: &str,+ text: &str,+ parent: Option<Uuid>,+ attachments: Vec<Attachment>,+ ) -> Result<Message> {+ let sender: Sender = sender.parse()?;+ let now = self.clock.now_us();+ let message_uuid = self.uuid_gen.new_uuid();+ let encrypted_text = crypto::encrypt_string(text, &self.key)?;+ let attachments_json = self.serialize_attachments(&attachments)?;++ self.backend.transaction(|tx| {+ tx.execute(+ "INSERT INTO messages (message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, deleted_at) \+ VALUES (?, ?, ?, ?, ?, ?, ?, NULL)",+ &[+ Value::Text(message_uuid.to_string()),+ Value::Text(session_uuid.to_string()),+ parent+ .map(|value| Value::Text(value.to_string()))+ .unwrap_or(Value::Null),+ Value::Text(sender.as_str().to_string()),+ Value::Blob(encrypted_text),+ attachments_json+ .map(Value::Text)+ .unwrap_or(Value::Null),+ Value::Integer(now),+ ],+ )?;++ self.touch_session(tx, session_uuid, now)?;+ Ok(())+ })?;++ Ok(Message {+ uuid: message_uuid,+ session_uuid,+ parent_message_uuid: parent,+ sender,+ text: text.to_string(),+ attachments,+ created_at: now,+ deleted_at: None,+ })+ }++ pub fn get_messages(&self, session_uuid: Uuid) -> Result<Vec<Message>> {+ let rows = self.backend.query(+ "SELECT message_uuid, session_uuid, parent_message_uuid, sender, text, attachments, created_at, deleted_at \+ FROM messages WHERE session_uuid = ? AND deleted_at IS NULL ORDER BY created_at ASC, message_uuid ASC",+ &[Value::Text(session_uuid.to_string())],+ )?;+ rows.iter().map(|row| self.message_from_row(row)).collect()+ }++ pub fn update_message_text(&self, uuid: Uuid, text: &str) -> Result<()> {+ let now = self.clock.now_us();+ let encrypted_text = crypto::encrypt_string(text, &self.key)?;+ self.backend.transaction(|tx| {+ let row = tx.query_row(+ "SELECT session_uuid FROM messages WHERE message_uuid = ? AND deleted_at IS NULL",+ &[Value::Text(uuid.to_string())],+ )?;+ let row = row.ok_or(Error::NotFound {+ entity: EntityType::Message,+ id: uuid,+ })?;+ let session_uuid = Uuid::parse_str(&row.get_string(0)?)?;++ let affected = tx.execute(+ "UPDATE messages SET text = ? WHERE message_uuid = ? AND deleted_at IS NULL",+ &[Value::Blob(encrypted_text), Value::Text(uuid.to_string())],+ )?;+ ensure_row_updated(affected, EntityType::Message, uuid)?;++ self.touch_session(tx, session_uuid, now)+ })+ }++ pub fn delete_message(&self, uuid: Uuid) -> Result<()> {+ let now = self.clock.now_us();+ self.backend.transaction(|tx| {+ let row = tx.query_row(+ "SELECT session_uuid FROM messages WHERE message_uuid = ? AND deleted_at IS NULL",+ &[Value::Text(uuid.to_string())],+ )?;+ let row = row.ok_or(Error::NotFound {+ entity: EntityType::Message,+ id: uuid,+ })?;+ let session_uuid = Uuid::parse_str(&row.get_string(0)?)?;++ let affected = tx.execute(+ "UPDATE messages SET deleted_at = ? WHERE message_uuid = ? AND deleted_at IS NULL",+ &[Value::Integer(now), Value::Text(uuid.to_string())],+ )?;+ ensure_row_updated(affected, EntityType::Message, uuid)?;++ self.touch_session(tx, session_uuid, now)+ })+ }++ pub fn mark_attachment_uploaded(&self, message_uuid: Uuid, attachment_id: &str) -> Result<()> {+ let now = self.clock.now_us();+ let row = self.backend.query_row(+ "SELECT attachments FROM messages WHERE message_uuid = ? AND deleted_at IS NULL",+ &[Value::Text(message_uuid.to_string())],+ )?;+ let row = row.ok_or(Error::NotFound {+ entity: EntityType::Message,+ id: message_uuid,+ })?;++ let attachments_json = row.get_optional_string(0)?;+ let mut stored = parse_stored_attachments(attachments_json)?;+ let mut found = false;+ for attachment in &mut stored {+ if attachment.id == attachment_id {+ if attachment.uploaded_at.is_none() {+ attachment.uploaded_at = Some(now);+ }+ found = true;+ break;+ }+ }++ if !found {+ return Err(Error::AttachmentNotFound(attachment_id.to_string()));+ }++ let updated_json = if stored.is_empty() {+ None+ } else {+ Some(serde_json::to_string(&stored)?)+ };++ self.backend.execute(+ "UPDATE messages SET attachments = ? WHERE message_uuid = ?",+ &[+ updated_json.map(Value::Text).unwrap_or(Value::Null),+ Value::Text(message_uuid.to_string()),+ ],+ )?;++ Ok(())+ }++ pub fn get_pending_uploads(&self, session_uuid: Uuid) -> Result<Vec<Attachment>> {+ let rows = self.backend.query(+ "SELECT attachments FROM messages WHERE session_uuid = ? AND deleted_at IS NULL",+ &[Value::Text(session_uuid.to_string())],+ )?;++ let mut pending = Vec::new();+ for row in rows {+ let attachments_json = row.get_optional_string(0)?;+ let stored = parse_stored_attachments(attachments_json)?;+ for attachment in stored.into_iter().filter(|att| att.uploaded_at.is_none()) {+ pending.push(self.stored_to_attachment(attachment)?);+ }+ }++ Ok(pending)+ }++ pub fn mark_session_synced(&self, uuid: Uuid, remote_id: &str) -> Result<()> {+ let affected = self.backend.execute(+ "UPDATE sessions SET remote_id = ?, needs_sync = 0 WHERE session_uuid = ?",+ &[+ Value::Text(remote_id.to_string()),+ Value::Text(uuid.to_string()),+ ],+ )?;+ ensure_row_updated(affected, EntityType::Session, uuid)+ }++ pub fn get_pending_deletions(&self) -> Result<Vec<(EntityType, Uuid)>> {+ let session_rows = self.backend.query(+ "SELECT session_uuid FROM sessions WHERE remote_id IS NOT NULL AND deleted_at IS NOT NULL ORDER BY deleted_at ASC",+ &[],+ )?;++ let mut deletions = Vec::new();+ for row in session_rows {+ let uuid = Uuid::parse_str(&row.get_string(0)?)?;+ deletions.push((EntityType::Session, uuid));+ }++ let message_rows = self.backend.query(+ "SELECT messages.message_uuid \+ FROM messages \+ JOIN sessions ON messages.session_uuid = sessions.session_uuid \+ WHERE messages.deleted_at IS NOT NULL \+ AND sessions.remote_id IS NOT NULL \+ AND sessions.deleted_at IS NULL \+ ORDER BY messages.deleted_at ASC",+ &[],+ )?;++ for row in message_rows {+ let uuid = Uuid::parse_str(&row.get_string(0)?)?;+ deletions.push((EntityType::Message, uuid));+ }++ Ok(deletions)+ }++ pub fn hard_delete(&self, entity_type: EntityType, uuid: Uuid) -> Result<()> {+ match entity_type {+ EntityType::Session => {+ self.backend.execute(+ "DELETE FROM sessions WHERE session_uuid = ?",+ &[Value::Text(uuid.to_string())],+ )?;+ }+ EntityType::Message => {+ self.backend.execute(+ "DELETE FROM messages WHERE message_uuid = ?",+ &[Value::Text(uuid.to_string())],+ )?;+ }+ }+ Ok(())+ }++ fn session_from_row(&self, row: &crate::backend::Row) -> Result<Session> {+ let uuid = Uuid::parse_str(&row.get_string(0)?)?;+ let title_blob = row.get_blob(1)?;+ let title = crypto::decrypt_string(&title_blob, &self.key)?;+ let created_at = row.get_i64(2)?;+ let updated_at = row.get_i64(3)?;+ let remote_id = row.get_optional_string(4)?;+ let needs_sync = bool_from_i64(row.get_i64(5)?)?;+ let deleted_at = row.get_optional_i64(6)?;+ Ok(Session {+ uuid,+ title,+ created_at,+ updated_at,+ remote_id,+ needs_sync,+ deleted_at,+ })+ }++ fn message_from_row(&self, row: &crate::backend::Row) -> Result<Message> {+ let uuid = Uuid::parse_str(&row.get_string(0)?)?;+ let session_uuid = Uuid::parse_str(&row.get_string(1)?)?;+ let parent_message_uuid = row+ .get_optional_string(2)?+ .map(|value| Uuid::parse_str(&value))+ .transpose()?;+ let sender: Sender = row.get_string(3)?.parse()?;+ let text_blob = row.get_blob(4)?;+ let text = crypto::decrypt_string(&text_blob, &self.key)?;+ let attachments_json = row.get_optional_string(5)?;+ let attachments = self.deserialize_attachments(attachments_json)?;+ let created_at = row.get_i64(6)?;+ let deleted_at = row.get_optional_i64(7)?;++ Ok(Message {+ uuid,+ session_uuid,+ parent_message_uuid,+ sender,+ text,+ attachments,+ created_at,+ deleted_at,+ })+ }++ fn serialize_attachments(&self, attachments: &[Attachment]) -> Result<Option<String>> {+ if attachments.is_empty() {+ return Ok(None);+ }+ let mut stored = Vec::with_capacity(attachments.len());+ for attachment in attachments {+ stored.push(self.attachment_to_stored(attachment)?);+ }+ Ok(Some(serde_json::to_string(&stored)?))+ }++ fn deserialize_attachments(&self, raw: Option<String>) -> Result<Vec<Attachment>> {+ let stored = parse_stored_attachments(raw)?;+ stored+ .into_iter()+ .map(|attachment| self.stored_to_attachment(attachment))+ .collect()+ }++ fn attachment_to_stored(&self, attachment: &Attachment) -> Result<StoredAttachment> {+ Ok(StoredAttachment {+ id: attachment.id.clone(),+ kind: attachment.kind,+ size: attachment.size,+ encrypted_name: crypto::encrypt_json_field(&attachment.name, &self.key)?,+ uploaded_at: attachment.uploaded_at,+ })+ }++ fn stored_to_attachment(&self, attachment: StoredAttachment) -> Result<Attachment> {+ Ok(Attachment {+ id: attachment.id,+ kind: attachment.kind,+ size: attachment.size,+ name: crypto::decrypt_json_field(&attachment.encrypted_name, &self.key)?,+ uploaded_at: attachment.uploaded_at,+ })+ }++ fn touch_session<T: BackendTx>(+ &self,+ backend: &T,+ session_uuid: Uuid,+ updated_at: i64,+ ) -> Result<()> {+ let affected = backend.execute(+ "UPDATE sessions SET updated_at = ?, needs_sync = 1 WHERE session_uuid = ? AND deleted_at IS NULL",+ &[Value::Integer(updated_at), Value::Text(session_uuid.to_string())],+ )?;+ ensure_row_updated(affected, EntityType::Session, session_uuid)+ }+}++#[cfg(feature = "sqlite")]+impl ChatDb<crate::backend::sqlite::SqliteBackend> {+ pub fn open_sqlite(+ path: impl AsRef<std::path::Path>,+ key: Vec<u8>,+ clock: Arc<dyn Clock>,+ uuid_gen: Arc<dyn UuidGen>,+ ) -> Result<Self> {+ let backend = crate::backend::sqlite::SqliteBackend::open(path)?;+ Self::new(backend, key, clock, uuid_gen)+ }++ pub fn open_sqlite_with_defaults(+ path: impl AsRef<std::path::Path>,+ key: Vec<u8>,+ ) -> Result<Self> {+ let backend = crate::backend::sqlite::SqliteBackend::open(path)?;+ Self::new_with_defaults(backend, key)+ }++ pub fn open_in_memory(key: Vec<u8>) -> Result<Self> {+ let backend = crate::backend::sqlite::SqliteBackend::open_in_memory()?;+ Self::new_with_defaults(backend, key)+ }+}++fn validate_key(key: Vec<u8>) -> Result<Zeroizing<Vec<u8>>> {+ if key.len() != crypto::KEY_BYTES {+ return Err(Error::InvalidKeyLength {+ expected: crypto::KEY_BYTES,+ actual: key.len(),+ });+ }+ Ok(Zeroizing::new(key))+}++fn bool_from_i64(value: i64) -> Result<bool> {+ match value {+ 0 => Ok(false),+ 1 => Ok(true),+ other => Err(Error::Row(format!("invalid bool value {other}"))),+ }+}++fn ensure_row_updated(affected: usize, entity: EntityType, uuid: Uuid) -> Result<()> {+ if affected == 0 {+ return Err(Error::NotFound { entity, id: uuid });+ }+ Ok(())+}++fn parse_stored_attachments(raw: Option<String>) -> Result<Vec<StoredAttachment>> {+ let Some(raw) = raw else {+ return Ok(Vec::new());+ };+ if raw.trim().is_empty() {+ return Ok(Vec::new());+ }+ Ok(serde_json::from_str(&raw)?)+}++#[cfg(all(test, feature = "sqlite"))]+mod tests {+ use std::collections::VecDeque;+ use std::sync::{Arc, Mutex};+ use std::sync::atomic::{AtomicI64, Ordering};++ use uuid::Uuid;++ use super::*;+ use crate::backend::{BackendTx, RowExt, Value};+ use crate::backend::sqlite::SqliteBackend;+ use crate::crypto::KEY_BYTES;+ use crate::models::{Attachment, AttachmentKind};++ #[derive(Debug)]+ struct StepClock {+ current: AtomicI64,+ step: i64,+ }++ impl StepClock {+ fn new(start: i64, step: i64) -> Self {+ Self {+ current: AtomicI64::new(start),+ step,+ }+ }+ }++ impl Clock for StepClock {+ fn now_us(&self) -> i64 {+ self.current.fetch_add(self.step, Ordering::SeqCst)+ }+ }++ #[derive(Debug)]+ struct TestUuidGen {+ uuids: Mutex<VecDeque<Uuid>>,+ }++ impl TestUuidGen {+ fn new(uuids: Vec<Uuid>) -> Self {+ Self {+ uuids: Mutex::new(uuids.into()),+ }+ }+ }++ impl UuidGen for TestUuidGen {+ fn new_uuid(&self) -> Uuid {+ self.uuids+ .lock()+ .expect("uuid lock poisoned")+ .pop_front()+ .expect("uuid queue empty")+ }+ }++ fn make_db(uuids: Vec<Uuid>, clock: Arc<dyn Clock>) -> ChatDb<SqliteBackend> {+ let backend = SqliteBackend::open_in_memory().unwrap();+ ChatDb::new(+ backend,+ vec![1u8; KEY_BYTES],+ clock,+ Arc::new(TestUuidGen::new(uuids)),+ )+ .unwrap()+ }++ #[test]+ fn create_and_get_session_encrypts_title() {+ let session_id = Uuid::from_u128(1);+ let clock = Arc::new(StepClock::new(100, 1));+ let db = make_db(vec![session_id], clock);++ let session = db.create_session("hello").unwrap();+ assert_eq!(session.uuid, session_id);+ assert_eq!(session.title, "hello");+ assert!(session.needs_sync);++ let fetched = db.get_session(session_id).unwrap().unwrap();+ assert_eq!(fetched.title, "hello");++ let row = db+ .backend+ .query_row(+ "SELECT title FROM sessions WHERE session_uuid = ?",+ &[Value::Text(session_id.to_string())],+ )+ .unwrap()+ .unwrap();+ let stored = row.get_blob(0).unwrap();+ assert!(stored.len() >= crypto::HEADER_BYTES);+ assert_ne!(stored, b"hello".to_vec());+ }++ #[test]+ fn message_updates_touch_session() {+ let session_id = Uuid::from_u128(2);+ let message_id = Uuid::from_u128(3);+ let clock = Arc::new(StepClock::new(10, 1));+ let db = make_db(vec![session_id, message_id], clock.clone());++ db.create_session("title").unwrap();+ let after_create = db.get_session(session_id).unwrap().unwrap().updated_at;++ let message = db+ .insert_message(session_id, "self", "hello", None, Vec::new())+ .unwrap();+ assert_eq!(message.uuid, message_id);++ let after_insert = db.get_session(session_id).unwrap().unwrap().updated_at;+ assert!(after_insert > after_create);++ db.update_message_text(message_id, "updated").unwrap();+ let after_update = db.get_session(session_id).unwrap().unwrap().updated_at;+ assert!(after_update > after_insert);+ }++ #[test]+ fn delete_session_soft_deletes_messages() {+ let session_id = Uuid::from_u128(4);+ let message_id = Uuid::from_u128(5);+ let clock = Arc::new(StepClock::new(1, 1));+ let db = make_db(vec![session_id, message_id], clock);++ db.create_session("title").unwrap();+ db.insert_message(session_id, "other", "hi", None, Vec::new())+ .unwrap();++ db.delete_session(session_id).unwrap();+ assert!(db.get_session(session_id).unwrap().is_none());++ let row = db+ .backend+ .query_row(+ "SELECT deleted_at FROM messages WHERE message_uuid = ?",+ &[Value::Text(message_id.to_string())],+ )+ .unwrap()+ .unwrap();+ assert!(row.get_optional_i64(0).unwrap().is_some());+ }++ #[test]+ fn attachment_upload_flow_does_not_touch_session() {+ let session_id = Uuid::from_u128(6);+ let message_id = Uuid::from_u128(7);+ let clock = Arc::new(StepClock::new(50, 1));+ let db = make_db(vec![session_id, message_id], clock.clone());++ db.create_session("title").unwrap();++ let attachments = vec![+ Attachment {+ id: "att-1".to_string(),+ kind: AttachmentKind::Image,+ size: 123,+ name: "photo.jpg".to_string(),+ uploaded_at: None,+ },+ Attachment {+ id: "att-2".to_string(),+ kind: AttachmentKind::Document,+ size: 456,+ name: "doc.pdf".to_string(),+ uploaded_at: None,+ },+ ];++ db.insert_message(session_id, "self", "hello", None, attachments)+ .unwrap();++ let updated_at_before = db.get_session(session_id).unwrap().unwrap().updated_at;++ let pending = db.get_pending_uploads(session_id).unwrap();+ assert_eq!(pending.len(), 2);++ db.mark_attachment_uploaded(message_id, "att-1").unwrap();+ let pending_after = db.get_pending_uploads(session_id).unwrap();+ assert_eq!(pending_after.len(), 1);++ let updated_at_after = db.get_session(session_id).unwrap().unwrap().updated_at;+ assert_eq!(updated_at_before, updated_at_after);++ let row = db+ .backend+ .query_row(+ "SELECT attachments FROM messages WHERE message_uuid = ?",+ &[Value::Text(message_id.to_string())],+ )+ .unwrap()+ .unwrap();+ let json = row.get_optional_string(0).unwrap().unwrap();+ let stored: Vec<StoredAttachment> = serde_json::from_str(&json).unwrap();+ assert!(stored[0].encrypted_name.starts_with("enc:v1:"));+ assert!(!stored[0].encrypted_name.contains("photo.jpg"));+ }++ #[test]+ fn invalid_sender_is_rejected() {+ let session_id = Uuid::from_u128(8);+ let message_id = Uuid::from_u128(9);+ let clock = Arc::new(StepClock::new(1, 1));+ let db = make_db(vec![session_id, message_id], clock);++ db.create_session("title").unwrap();+ let err = db+ .insert_message(session_id, "invalid", "hello", None, Vec::new())+ .unwrap_err();++ match err {+ Error::InvalidSender(_) => {}+ other => panic!("unexpected error: {other:?}"),+ }+ }+}diff --git a/rust/llmchat-db/src/error.rs b/rust/llmchat-db/src/error.rsnew file mode 100644index 0000000000..a7a5f94dee--- /dev/null+++ b/rust/llmchat-db/src/error.rs@@ -0,0 +1,57 @@+use thiserror::Error;++use crate::models::EntityType;++pub type Result<T> = std::result::Result<T, Error>;++#[derive(Error, Debug)]+pub enum Error {+ #[error("invalid encryption key length: expected {expected}, got {actual}")]+ InvalidKeyLength { expected: usize, actual: usize },++ #[error("invalid blob length: expected at least {minimum} bytes, got {actual}")]+ InvalidBlobLength { minimum: usize, actual: usize },++ #[error("invalid encrypted field format")]+ InvalidEncryptedField,++ #[error("unsupported value type: {0}")]+ UnsupportedValueType(String),++ #[error("row error: {0}")]+ Row(String),++ #[error("invalid sender: {0}")]+ InvalidSender(String),++ #[error("{entity:?} not found: {id}")]+ NotFound { entity: EntityType, id: uuid::Uuid },++ #[error("attachment not found: {0}")]+ AttachmentNotFound(String),++ #[error(transparent)]+ Crypto(#[from] ente_core::crypto::CryptoError),++ #[error(transparent)]+ SerdeJson(#[from] serde_json::Error),++ #[error(transparent)]+ Uuid(#[from] uuid::Error),++ #[error(transparent)]+ Utf8(#[from] std::string::FromUtf8Error),++ #[error(transparent)]+ Io(#[from] std::io::Error),++ #[cfg(feature = "sqlite")]+ #[error(transparent)]+ Sqlite(#[from] rusqlite::Error),++ #[error("unsupported operation: {0}")]+ UnsupportedOperation(String),++ #[error("migration error: {0}")]+ Migration(String),+}diff --git a/rust/llmchat-db/src/lib.rs b/rust/llmchat-db/src/lib.rsnew file mode 100644index 0000000000..c2661eabfd--- /dev/null+++ b/rust/llmchat-db/src/lib.rs@@ -0,0 +1,24 @@+#![forbid(unsafe_code)]++pub mod backend;+pub mod crypto;+pub mod db;+pub mod error;+pub mod migrations;+pub mod models;+pub mod schema;+pub mod traits;++pub use crate::backend::{Backend, BackendTx, Row, Value};+pub use crate::db::ChatDb;+pub use crate::error::{Error, Result};+pub use crate::models::{+ Attachment, AttachmentKind, EntityType, Message, Sender, Session,+};+pub use crate::traits::{+ AttachmentStore, Clock, FileMetaStore, FsAttachmentStore, MetaStore, RandomUuidGen,+ SystemClock, UuidGen,+};++#[cfg(feature = "sqlite")]+pub use crate::backend::sqlite::SqliteBackend;diff --git a/rust/llmchat-db/src/migrations.rs b/rust/llmchat-db/src/migrations.rsnew file mode 100644index 0000000000..1bb0f3e0e1--- /dev/null+++ b/rust/llmchat-db/src/migrations.rs@@ -0,0 +1,64 @@+use crate::{Backend, Error, Result};+use crate::backend::RowExt;+use crate::schema;++pub const LATEST_VERSION: i64 = 1;++pub fn migrate<B: Backend>(backend: &B) -> Result<()> {+ let version = user_version(backend)?;+ match version {+ 0 => {+ backend.execute_batch(schema::CREATE_ALL)?;+ backend.execute("PRAGMA user_version = 1;", &[])?;+ Ok(())+ }+ LATEST_VERSION => Ok(()),+ other => Err(Error::Migration(format!(+ "unsupported schema version {other}"+ ))),+ }+}++fn user_version<B: Backend>(backend: &B) -> Result<i64> {+ let row = backend+ .query_row("PRAGMA user_version;", &[])?+ .ok_or_else(|| Error::Migration("missing user_version pragma".to_string()))?;+ row.get_i64(0)+}++#[cfg(all(test, feature = "sqlite"))]+mod tests {+ use super::*;+ use crate::backend::{BackendTx, RowExt, Value};+ use crate::backend::sqlite::SqliteBackend;++ #[test]+ fn creates_schema_and_indexes() {+ let backend = SqliteBackend::open_in_memory().unwrap();+ migrate(&backend).unwrap();++ for table in ["sessions", "messages"] {+ let row = backend+ .query_row(+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",+ &[Value::Text(table.to_string())],+ )+ .unwrap();+ assert!(row.is_some(), "missing table {table}");+ }++ for index in ["idx_messages_order", "idx_sessions_updated"] {+ let row = backend+ .query_row(+ "SELECT name FROM sqlite_master WHERE type = 'index' AND name = ?",+ &[Value::Text(index.to_string())],+ )+ .unwrap();+ assert!(row.is_some(), "missing index {index}");+ }++ let row = backend.query_row("PRAGMA user_version;", &[]).unwrap();+ let version = row.unwrap().get_i64(0).unwrap();+ assert_eq!(version, LATEST_VERSION);+ }+}diff --git a/rust/llmchat-db/src/models.rs b/rust/llmchat-db/src/models.rsnew file mode 100644index 0000000000..7ab7962865--- /dev/null+++ b/rust/llmchat-db/src/models.rs@@ -0,0 +1,90 @@+use serde::{Deserialize, Serialize};+use uuid::Uuid;++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Session {+ pub uuid: Uuid,+ pub title: String,+ pub created_at: i64,+ pub updated_at: i64,+ pub remote_id: Option<String>,+ pub needs_sync: bool,+ pub deleted_at: Option<i64>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Message {+ pub uuid: Uuid,+ pub session_uuid: Uuid,+ pub parent_message_uuid: Option<Uuid>,+ pub sender: Sender,+ pub text: String,+ pub attachments: Vec<Attachment>,+ pub created_at: i64,+ pub deleted_at: Option<i64>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Attachment {+ pub id: String,+ pub kind: AttachmentKind,+ pub size: i64,+ pub name: String,+ pub uploaded_at: Option<i64>,+}++impl Attachment {+ pub fn needs_upload(&self) -> bool {+ self.uploaded_at.is_none()+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum AttachmentKind {+ Image,+ Document,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Sender {+ SelfUser,+ Other,+}++impl Sender {+ pub fn as_str(&self) -> &'static str {+ match self {+ Sender::SelfUser => "self",+ Sender::Other => "other",+ }+ }+}++impl std::str::FromStr for Sender {+ type Err = crate::Error;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ match value {+ "self" => Ok(Sender::SelfUser),+ "other" => Ok(Sender::Other),+ _ => Err(crate::Error::InvalidSender(value.to_string())),+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum EntityType {+ Session,+ Message,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub(crate) struct StoredAttachment {+ pub id: String,+ pub kind: AttachmentKind,+ pub size: i64,+ pub encrypted_name: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub uploaded_at: Option<i64>,+}diff --git a/rust/llmchat-db/src/schema.rs b/rust/llmchat-db/src/schema.rsnew file mode 100644index 0000000000..db16595ab3--- /dev/null+++ b/rust/llmchat-db/src/schema.rs@@ -0,0 +1,61 @@+pub const PRAGMA_FOREIGN_KEYS: &str = "PRAGMA foreign_keys = ON;";++pub const CREATE_SESSIONS: &str = "+CREATE TABLE IF NOT EXISTS sessions (+ session_uuid TEXT PRIMARY KEY NOT NULL,+ title BLOB NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ remote_id TEXT UNIQUE,+ needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1)),+ deleted_at INTEGER+);+";++pub const CREATE_MESSAGES: &str = "+CREATE TABLE IF NOT EXISTS messages (+ message_uuid TEXT PRIMARY KEY NOT NULL,+ session_uuid TEXT NOT NULL,+ parent_message_uuid TEXT,+ sender TEXT NOT NULL CHECK(sender IN ('self','other')),+ text BLOB NOT NULL,+ attachments TEXT,+ created_at INTEGER NOT NULL,+ deleted_at INTEGER,+ FOREIGN KEY (session_uuid) REFERENCES sessions(session_uuid) ON DELETE CASCADE+);+";++pub const CREATE_INDEXES: &str = "+CREATE INDEX IF NOT EXISTS idx_messages_order ON messages(session_uuid, created_at, message_uuid);+CREATE INDEX IF NOT EXISTS idx_sessions_updated ON sessions(updated_at);+";++pub const CREATE_ALL: &str = "+PRAGMA foreign_keys = ON;++CREATE TABLE IF NOT EXISTS sessions (+ session_uuid TEXT PRIMARY KEY NOT NULL,+ title BLOB NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ remote_id TEXT UNIQUE,+ needs_sync INTEGER NOT NULL DEFAULT 1 CHECK(needs_sync IN (0,1)),+ deleted_at INTEGER+);++CREATE TABLE IF NOT EXISTS messages (+ message_uuid TEXT PRIMARY KEY NOT NULL,+ session_uuid TEXT NOT NULL,+ parent_message_uuid TEXT,+ sender TEXT NOT NULL CHECK(sender IN ('self','other')),+ text BLOB NOT NULL,+ attachments TEXT,+ created_at INTEGER NOT NULL,+ deleted_at INTEGER,+ FOREIGN KEY (session_uuid) REFERENCES sessions(session_uuid) ON DELETE CASCADE+);++CREATE INDEX IF NOT EXISTS idx_messages_order ON messages(session_uuid, created_at, message_uuid);+CREATE INDEX IF NOT EXISTS idx_sessions_updated ON sessions(updated_at);+";diff --git a/rust/llmchat-db/src/traits.rs b/rust/llmchat-db/src/traits.rsnew file mode 100644index 0000000000..f716ae7357--- /dev/null+++ b/rust/llmchat-db/src/traits.rs@@ -0,0 +1,154 @@+use std::{+ fs,+ path::{Path, PathBuf},+ time::{SystemTime, UNIX_EPOCH},+};++use uuid::Uuid;++use crate::Result;++pub trait MetaStore: Send + Sync {+ fn get(&self, key: &str) -> Result<Option<Vec<u8>>>;+ fn set(&self, key: &str, value: &[u8]) -> Result<()>;+ fn delete(&self, key: &str) -> Result<()>;+}++pub trait AttachmentStore: Send + Sync {+ fn write(&self, id: &str, data: &[u8]) -> Result<()>;+ fn read(&self, id: &str) -> Result<Vec<u8>>;+ fn delete(&self, id: &str) -> Result<()>;+ fn exists(&self, id: &str) -> Result<bool>;+}++pub trait Clock: Send + Sync {+ fn now_us(&self) -> i64;+}++pub trait UuidGen: Send + Sync {+ fn new_uuid(&self) -> Uuid;+}++#[derive(Debug, Default, Clone)]+pub struct SystemClock;++impl Clock for SystemClock {+ fn now_us(&self) -> i64 {+ let duration = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default();+ let micros = duration.as_secs() as i64 * 1_000_000;+ let sub_micros = (duration.subsec_nanos() / 1_000) as i64;+ micros + sub_micros+ }+}++#[derive(Debug, Default, Clone)]+pub struct RandomUuidGen;++impl UuidGen for RandomUuidGen {+ fn new_uuid(&self) -> Uuid {+ Uuid::new_v4()+ }+}++#[derive(Debug, Clone)]+pub struct FileMetaStore {+ root: PathBuf,+}++impl FileMetaStore {+ pub fn new(root: impl Into<PathBuf>) -> Self {+ Self { root: root.into() }+ }++ fn key_path(&self, key: &str) -> PathBuf {+ let encoded = ente_core::crypto::bin2base64(key.as_bytes(), true);+ self.root.join(encoded)+ }++ fn ensure_root(&self) -> Result<()> {+ fs::create_dir_all(&self.root)?;+ Ok(())+ }+}++impl MetaStore for FileMetaStore {+ fn get(&self, key: &str) -> Result<Option<Vec<u8>>> {+ let path = self.key_path(key);+ match fs::read(&path) {+ Ok(bytes) => Ok(Some(bytes)),+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),+ Err(err) => Err(err.into()),+ }+ }++ fn set(&self, key: &str, value: &[u8]) -> Result<()> {+ self.ensure_root()?;+ let path = self.key_path(key);+ fs::write(path, value)?;+ Ok(())+ }++ fn delete(&self, key: &str) -> Result<()> {+ let path = self.key_path(key);+ match fs::remove_file(path) {+ Ok(()) => Ok(()),+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(err) => Err(err.into()),+ }+ }+}++#[derive(Debug, Clone)]+pub struct FsAttachmentStore {+ root: PathBuf,+}++impl FsAttachmentStore {+ pub fn new(root: impl Into<PathBuf>) -> Self {+ Self { root: root.into() }+ }++ fn attachment_path(&self, id: &str) -> PathBuf {+ self.root.join(id)+ }++ fn ensure_root(&self) -> Result<()> {+ fs::create_dir_all(&self.root)?;+ Ok(())+ }+}++impl AttachmentStore for FsAttachmentStore {+ fn write(&self, id: &str, data: &[u8]) -> Result<()> {+ self.ensure_root()?;+ let path = self.attachment_path(id);+ fs::write(path, data)?;+ Ok(())+ }++ fn read(&self, id: &str) -> Result<Vec<u8>> {+ let path = self.attachment_path(id);+ Ok(fs::read(path)?)+ }++ fn delete(&self, id: &str) -> Result<()> {+ let path = self.attachment_path(id);+ match fs::remove_file(path) {+ Ok(()) => Ok(()),+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(err) => Err(err.into()),+ }+ }++ fn exists(&self, id: &str) -> Result<bool> {+ let path = self.attachment_path(id);+ Ok(path.exists())+ }+}++pub fn ensure_directory(path: impl AsRef<Path>) -> Result<()> {+ fs::create_dir_all(path)?;+ Ok(())+}