//! Starts and owns the Ollama server used by Capri (Capri 1.0.4 `host/environment.mjs`). use std::process::Stdio; use std::time::{Duration, Instant}; use anyhow::{bail, Context, Result}; use capri_core::{Paths, Settings}; use tokio::process::{Child, Command}; use crate::sections::InferenceSection; use crate::Ollama; /// Variables passed through from the user's environment; everything else is dropped /// so no credential or unrelated variable reaches Ollama. fn allowed_env(name: &str) -> bool { matches!(name, "PATH" | "HOME" | "LANG" | "XDG_RUNTIME_DIR" | "LD_LIBRARY_PATH") || ["LC_", "CUDA_", "HIP_", "ROCR_", "HSA_", "GGML_", "VK_"].iter().any(|p| name.starts_with(p)) } /// GPU masks for the Ollama child. `auto` changes nothing. pub fn device_environment(device: &str) -> Result> { if device == "auto" { return Ok(vec![]); } let mut env: Vec<(&'static str, String)> = ["CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "GPU_DEVICE_ORDINAL", "GGML_VK_VISIBLE_DEVICES"] .into_iter() .map(|k| (k, "-1".to_string())) .chain([("OLLAMA_VULKAN", "0".to_string())]) .collect(); let mut set = |key: &'static str, value: String| env.iter_mut().filter(|(k, _)| *k == key).for_each(|(_, v)| *v = value.clone()); match device.split_once(':') { None if device == "cpu" => {} Some(("cuda", id)) if !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') => set("CUDA_VISIBLE_DEVICES", id.into()), Some(("rocm", n)) if n.parse::().is_ok_and(|n| n < 64) => { env.retain(|(k, _)| !matches!(*k, "CUDA_VISIBLE_DEVICES" | "ROCR_VISIBLE_DEVICES" | "GPU_DEVICE_ORDINAL")); env.iter_mut().filter(|(k, _)| *k == "HIP_VISIBLE_DEVICES").for_each(|(_, v)| *v = n.into()); } Some(("vulkan", n)) if n.parse::().is_ok_and(|n| n < 64) => { set("GGML_VK_VISIBLE_DEVICES", n.into()); set("OLLAMA_VULKAN", "1".into()); } _ => bail!("Invalid model device."), } Ok(env) } /// `true` when `found` (e.g. `0.40.15`) is at least `minimum`; unparsable versions fail. pub fn version_at_least(found: &str, minimum: &str) -> bool { let parse = |v: &str| -> Option<[u64; 3]> { let mut it = v.trim().splitn(3, '.'); let mut out = [0; 3]; for slot in &mut out { let part = it.next()?; let digits: String = part.chars().take_while(char::is_ascii_digit).collect(); *slot = digits.parse().ok()?; } Some(out) }; matches!((parse(found), parse(minimum)), (Some(f), Some(m)) if f >= m) } async fn version_gate(client: &Ollama, minimum: &str) -> Result<()> { let found = client.version().await?; if !version_at_least(&found, minimum) { bail!("This build needs Ollama {minimum} or newer; found {found}. Update the selected Ollama executable."); } Ok(()) } /// Running Ollama. The child (if Capri started it) is killed when this value is dropped. pub struct OllamaServer { pub client: Ollama, child: Option, } impl OllamaServer { pub fn owned(&self) -> bool { self.child.is_some() } /// Uses `settings.ollama_url` when set, an Ollama already answering on the Capri port, /// or starts `ollama serve` on that port with the Capri model store. pub async fn start(settings: &Settings, paths: &Paths) -> Result { let client = Ollama::new(settings.ollama_base_url()); let inference: InferenceSection = settings.section(); if client.version().await.is_ok() { version_gate(&client, &inference.min_ollama_version).await?; return Ok(Self { client, child: None }); } if settings.ollama_url.is_some() { bail!("Ollama does not answer at {}.", client.base()); } let models = settings.models_dir(paths); std::fs::create_dir_all(&models)?; let log = std::fs::OpenOptions::new().create(true).append(true).open(paths.logs().join("ollama.log"))?; let exe = match std::env::var_os("CAPRI_OLLAMA_PATH") { Some(path) => { let path = std::path::PathBuf::from(path); if !path.is_absolute() || !path.is_file() { bail!("CAPRI_OLLAMA_PATH must point to an existing executable."); } path } None => settings.ollama_path.clone().unwrap_or_else(|| "ollama".into()), }; let tmp = paths.cache.join("ollama-tmp"); std::fs::create_dir_all(&tmp)?; let cpu = settings.acceleration == "cpu" || inference.device == "cpu"; // VRAM reserve for the desktop. // TODO: no extra 3 GiB voice reserve since the voice state is not known here; add it when the speech crate exposes voice_expected/voice_ready. let overhead: u64 = if cpu { 0 } else { 768 << 20 }; let mut command = Command::new(&exe); command .env_clear() .envs(std::env::vars_os().filter(|(k, _)| k.to_str().is_some_and(allowed_env))) .envs(device_environment(&inference.device)?) .env("TMPDIR", &tmp) .env("LLAMA_ARG_THINK_BUDGET", inference.reasoning_budget.max(4096).to_string()) .env("OLLAMA_GPU_OVERHEAD", overhead.to_string()) .arg("serve") .env("OLLAMA_HOST", format!("127.0.0.1:{}", settings.ollama_port)) .env("OLLAMA_MODELS", &models) .env("OLLAMA_NO_CLOUD", "1") .env("OLLAMA_NUM_PARALLEL", "1") .env("OLLAMA_MAX_LOADED_MODELS", "2") .env("OLLAMA_KEEP_ALIVE", settings.keep_alive.to_string()) .env("OLLAMA_CONTEXT_LENGTH", settings.context_tokens.to_string()) .env("OLLAMA_FLASH_ATTENTION", "1") .env("OLLAMA_KV_CACHE_TYPE", "q8_0") .stdin(Stdio::null()) .stdout(log.try_clone()?) .stderr(log) .kill_on_drop(true); // Ollama must not outlive Capri, even when Capri is killed (logout, SIGKILL). // Spawned from the main thread (`block_on`), whose exit is the process exit. unsafe { command.pre_exec(|| { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM); Ok(()) }); } let mut child = command .spawn() .with_context(|| format!("Cannot start {}. Install Ollama (pacman -S ollama).", exe.display()))?; let deadline = Instant::now() + Duration::from_secs(30); while Instant::now() < deadline { if client.version().await.is_ok() { tracing::info!(port = settings.ollama_port, "Ollama ready"); let server = Self { client, child: Some(child) }; if let Err(e) = version_gate(&server.client, &inference.min_ollama_version).await { server.stop().await; return Err(e); } return Ok(server); } if let Some(status) = child.try_wait()? { bail!("Ollama exited during startup ({status}). See {}.", paths.logs().join("ollama.log").display()); } tokio::time::sleep(Duration::from_millis(250)).await; } bail!("Ollama did not become ready within 30 s.") } /// Unloads every resident model, then stops the owned server. pub async fn unload_and_stop(self) { if self.owned() { let models = self.client.ps().await.unwrap_or_default(); futures::future::join_all(models.iter().map(|m| self.client.unload(&m.name))).await; } self.stop().await; } /// Stops the owned server, giving it 3 s to exit after SIGTERM. pub async fn stop(mut self) { if let Some(mut child) = self.child.take() { if let Some(pid) = child.id() { // SIGTERM lets Ollama unload models cleanly. unsafe { libc::kill(pid as i32, libc::SIGTERM) }; } if tokio::time::timeout(Duration::from_secs(3), child.wait()).await.is_err() { let _ = child.kill().await; } } } } /// Picks the configured model, or the upstream model when the Capri alias is not installed. pub async fn resolve_model(client: &Ollama, settings: &Settings) -> Result<(String, Vec)> { for name in [&settings.model, &settings.upstream_model] { if name.is_empty() { continue; } if let Some(capabilities) = client.show(name).await? { return Ok((name.clone(), capabilities)); } } bail!("Model {} is not installed. Run: capri models pull", settings.upstream_model) } #[cfg(test)] mod tests { use super::*; #[test] fn device_masks_and_versions() { assert!(device_environment("auto").unwrap().is_empty()); let cpu = device_environment("cpu").unwrap(); assert!(cpu.contains(&("CUDA_VISIBLE_DEVICES", "-1".into())) && cpu.contains(&("OLLAMA_VULKAN", "0".into()))); let cuda = device_environment("cuda:GPU-1cbff653-6fe4").unwrap(); assert!(cuda.contains(&("CUDA_VISIBLE_DEVICES", "GPU-1cbff653-6fe4".into()))); let rocm = device_environment("rocm:1").unwrap(); assert!(rocm.contains(&("HIP_VISIBLE_DEVICES", "1".into())) && !rocm.iter().any(|(k, _)| *k == "CUDA_VISIBLE_DEVICES")); assert!(device_environment("vulkan:0").unwrap().contains(&("OLLAMA_VULKAN", "1".into()))); assert!(device_environment("rocm:99").is_err() && device_environment("cuda:a;b").is_err()); assert!(version_at_least("0.40.15", "0.40.10") && version_at_least("1.0.0-rc1", "0.40.10")); assert!(!version_at_least("0.40.9", "0.40.10") && !version_at_least("dev", "0.40.10")); assert!(allowed_env("LC_ALL") && allowed_env("CUDA_PATH") && !allowed_env("OPENAI_API_KEY") && !allowed_env("CAPRI_TOKEN")); } }